diff options
| author | Vonsek <45567075+Vonsek@users.noreply.github.com> | 2026-11-22 15:51:40 +0100 |
|---|---|---|
| committer | Vonsek <45567075+Vonsek@users.noreply.github.com> | 2026-11-22 15:51:40 +0100 |
| commit | df91c6624b69ee4e6c6eeca20ed68d331ed0e728 (patch) | |
| tree | 323c88b9df89bf8abaa2b98d10808474ab675dc2 /tests | |
| parent | b40d8039a98f57b26bd05860febbabbe59b97873 (diff) | |
| parent | 6a6704df1592e1dc4a3215ddf1423a78adb52045 (diff) | |
Merge main into test/valu-int-misc (#1492)
Conflicted files: runtime/test/shaders/check.py, scripts/run_gpu_tests.py
AI-assisted.
Diffstat (limited to 'tests')
67 files changed, 11988 insertions, 72 deletions
diff --git a/tests/semantic/README.md b/tests/semantic/README.md index cef5723fc..65b741083 100644 --- a/tests/semantic/README.md +++ b/tests/semantic/README.md | |||
| @@ -85,6 +85,10 @@ What they check (`tools/rdna2spirv.py`, pixel shaders plus one compute shader): | |||
| 85 | undefined in SPIR-V (`UndefinedResult`); a "lane mod 32" model of issue #94 gives the words a 32-wide GPU | 85 | undefined in SPIR-V (`UndefinedResult`); a "lane mod 32" model of issue #94 gives the words a 32-wide GPU |
| 86 | shows (all 24 matched on an RTX 4070 SUPER, driver 610.88, without `--wave64-emulate`). Two SPIR-V sabotages (readlane lane & 31, bpermute without its half base) must change the | 86 | shows (all 24 matched on an RTX 4070 SUPER, driver 610.88, without `--wave64-emulate`). Two SPIR-V sabotages (readlane lane & 31, bpermute without its half base) must change the |
| 87 | 64-wide result. | 87 | 64-wide result. |
| 88 | - `test_w64x_scalar_load_order.py` translates wave64 programs with `--wave64-emulate` and checks the emitted rounds: | ||
| 89 | no case of the round loop's switch reads or writes buffer memory after a write, or writes after a read, so a | ||
| 90 | `buffer_store` and a later `s_load` / `s_buffer_load` of the wave (and a scalar load and a later store) run in | ||
| 91 | different rounds (#1587). Loads alone share a round. | ||
| 88 | - `test_wave64_subgroup_ops.py` runs eight more wave64 GPU tests the same way (`cs_w64x_ballot`, | 92 | - `test_wave64_subgroup_ops.py` runs eight more wave64 GPU tests the same way (`cs_w64x_ballot`, |
| 89 | `_readfirstlane`, `_load_ballot_load`, `_partial`, `cs_wave64_ballot`, `cs_wm_bfm64`, `cs_wm_half_cmp`, | 93 | `_readfirstlane`, `_load_ballot_load`, `_partial`, `cs_wave64_ballot`, `cs_wm_bfm64`, `cs_wm_half_cmp`, |
| 90 | `cs_wavemask`): on one 64-wide subgroup every word equals the GPU check; on two 32-wide subgroups the | 94 | `cs_wavemask`): on one 64-wide subgroup every word equals the GPU check; on two 32-wide subgroups the |
diff --git a/tests/semantic/fixtures/disasm/cs_fmt_sint32.s b/tests/semantic/fixtures/disasm/cs_fmt_sint32.s new file mode 100644 index 000000000..ecacaa055 --- /dev/null +++ b/tests/semantic/fixtures/disasm/cs_fmt_sint32.s | |||
| @@ -0,0 +1,64 @@ | |||
| 1 | ; cs_fmt_sint32 test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/cs_fmt_sint32.asm | ||
| 2 | v_cmpx_eq_u32_e32 0, v0 | ||
| 3 | v_mov_b32_e32 v1, 0x80000000 | ||
| 4 | v_mov_b32_e32 v2, 0x7fffffff | ||
| 5 | v_mov_b32_e32 v3, -3 | ||
| 6 | v_mov_b32_e32 v4, 17 | ||
| 7 | v_mov_b32_e32 v5, 0x80 | ||
| 8 | buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen | ||
| 9 | s_mov_b32 s4, s0 | ||
| 10 | s_mov_b32 s5, s1 | ||
| 11 | s_mov_b32 s6, s2 | ||
| 12 | s_mov_b32 s7, 0x3103f32c | ||
| 13 | buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen | ||
| 14 | v_mov_b32_e32 v6, 0x0 | ||
| 15 | buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen | ||
| 16 | s_mov_b32 s7, 0x31049fac | ||
| 17 | buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen | ||
| 18 | v_mov_b32_e32 v6, 0x10 | ||
| 19 | buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen | ||
| 20 | s_mov_b32 s7, 0x3104cfac | ||
| 21 | buffer_load_format_xyzw v[8:11], v5, s[4:7], 0 offen | ||
| 22 | v_mov_b32_e32 v6, 0x20 | ||
| 23 | buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen | ||
| 24 | s_mov_b32 s7, 0x31016000 | ||
| 25 | tbuffer_load_format_xyzw v[8:11], v5, s[4:7], 0 format:[BUF_FMT_32_32_SINT] offen | ||
| 26 | v_mov_b32_e32 v6, 0x30 | ||
| 27 | buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen | ||
| 28 | tbuffer_load_format_xyzw v[8:11], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_SINT] offen | ||
| 29 | v_mov_b32_e32 v6, 0x40 | ||
| 30 | buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen | ||
| 31 | tbuffer_load_format_xyzw v[8:11], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_32_SINT] offen | ||
| 32 | v_mov_b32_e32 v6, 0x50 | ||
| 33 | buffer_store_dwordx4 v[8:11], v6, s[0:3], 0 offen | ||
| 34 | s_mov_b32 s7, 0x3104cfac | ||
| 35 | buffer_load_format_d16_xyzw v[8:9], v5, s[4:7], 0 offen | ||
| 36 | v_mov_b32_e32 v6, 0x60 | ||
| 37 | buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen | ||
| 38 | s_mov_b32 s7, 0x31016000 | ||
| 39 | tbuffer_load_format_d16_xyzw v[8:9], v5, s[4:7], 0 format:[BUF_FMT_32_32_32_32_SINT] offen | ||
| 40 | v_mov_b32_e32 v6, 0x68 | ||
| 41 | buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen | ||
| 42 | s_mov_b32 s7, 0x31015004 | ||
| 43 | buffer_load_format_x v8, v5, s[4:7], 0 offen offset:8 | ||
| 44 | s_mov_b32 s7, 0x31016000 | ||
| 45 | tbuffer_load_format_x v9, v5, s[4:7], 0 format:[BUF_FMT_32_SINT] offen offset:8 | ||
| 46 | v_mov_b32_e32 v6, 0x70 | ||
| 47 | buffer_store_dwordx2 v[8:9], v6, s[0:3], 0 offen | ||
| 48 | s_mov_b32 s7, 0x3103ffac | ||
| 49 | v_mov_b32_e32 v6, 0x90 | ||
| 50 | buffer_store_format_xy v[1:2], v6, s[4:7], 0 offen | ||
| 51 | s_mov_b32 s7, 0x31049fac | ||
| 52 | v_mov_b32_e32 v6, 0xa0 | ||
| 53 | buffer_store_format_xyz v[1:3], v6, s[4:7], 0 offen | ||
| 54 | s_mov_b32 s7, 0x3104cfac | ||
| 55 | v_mov_b32_e32 v6, 0xb0 | ||
| 56 | buffer_store_format_xyzw v[1:4], v6, s[4:7], 0 offen | ||
| 57 | s_mov_b32 s7, 0x3103ffac | ||
| 58 | v_mov_b32_e32 v6, 0xc0 | ||
| 59 | v_mov_b32_e32 v7, 0x8000fffd | ||
| 60 | buffer_store_format_d16_xy v7, v6, s[4:7], 0 offen | ||
| 61 | s_mov_b32 s7, 0x31015004 | ||
| 62 | v_mov_b32_e32 v6, 0xc8 | ||
| 63 | buffer_store_format_x v3, v6, s[4:7], 0 offen | ||
| 64 | s_endpgm | ||
diff --git a/tests/semantic/fixtures/disasm/ps_f16_pack_mods.s b/tests/semantic/fixtures/disasm/ps_f16_pack_mods.s new file mode 100644 index 000000000..ad15acda2 --- /dev/null +++ b/tests/semantic/fixtures/disasm/ps_f16_pack_mods.s | |||
| @@ -0,0 +1,9 @@ | |||
| 1 | ; ps_f16_pack_mods test fixture generated by tests/semantic/regen_fixtures.py from runtime/test/shaders/ps_f16_pack_mods.asm | ||
| 2 | v_mov_b32 v0, 0x42003400 | ||
| 3 | v_mov_b32 v1, 0x34004400 | ||
| 4 | v_pack_b32_f16 v2, -v0, |v1| | ||
| 5 | v_pack_b32_f16 v3, v0, -v1 | ||
| 6 | v_pack_b32_f16 v4, -|v0|, v1 op_sel:[1,0,0] | ||
| 7 | v_pack_b32_f16 v5, -v0, -|v1| op_sel:[0,1,0] | ||
| 8 | exp mrt0 v2, v3, v4, v5 done vm | ||
| 9 | s_endpgm | ||
diff --git a/tests/semantic/regen_fixtures.py b/tests/semantic/regen_fixtures.py index bbd8a2811..eafc903f2 100644 --- a/tests/semantic/regen_fixtures.py +++ b/tests/semantic/regen_fixtures.py | |||
| @@ -19,7 +19,7 @@ FIXTURE_DIR = os.path.join(HERE, "fixtures", "disasm") | |||
| 19 | SHADERS = ("cs_smem_bounds", "cs_smem_stride_align", "cs_smem_sload_neg", "cs_buf_tail", # SMEM / raw MUBUF bounds measured on RDNA2 | 19 | SHADERS = ("cs_smem_bounds", "cs_smem_stride_align", "cs_smem_sload_neg", "cs_buf_tail", # SMEM / raw MUBUF bounds measured on RDNA2 |
| 20 | "ps_fnan_med3", "ps_fnan_fract", # float NaN / fract rows measured on RDNA2 hardware | 20 | "ps_fnan_med3", "ps_fnan_fract", # float NaN / fract rows measured on RDNA2 hardware |
| 21 | "ps_sdwa", "ps_ops", "ps_ops2", "ps_ops3", "ps_ops4", "ps_ops5", "ps_ops6", "ps_ops7", "ps_ops8", | 21 | "ps_sdwa", "ps_ops", "ps_ops2", "ps_ops3", "ps_ops4", "ps_ops5", "ps_ops6", "ps_ops7", "ps_ops8", |
| 22 | "ps_legacy_mul", "ps_vcc_x2", "ps_vcmpx_forms", "ps_flat", "cs_bounds", "cs_fmt_1010102", "cs_w64x_readlane", | 22 | "ps_legacy_mul", "ps_vcc_x2", "ps_vcmpx_forms", "ps_flat", "cs_bounds", "cs_fmt_1010102", "cs_fmt_sint32", "cs_w64x_readlane", |
| 23 | "cs_w64x_writelane", "cs_w64x_bpermute", "cs_w32_permute", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w64x_permute", "cs_w64x_ballot", "cs_w64x_readfirstlane", | 23 | "cs_w64x_writelane", "cs_w64x_bpermute", "cs_w32_permute", "cs_w32_int_ext", "cs_w32_salu64", "cs_w32_misc_ext", "cs_w32_new_ops", "cs_w64x_permute", "cs_w64x_ballot", "cs_w64x_readfirstlane", |
| 24 | "cs_w64x_load_ballot_load", "cs_w64x_partial", "cs_wave64_ballot", "cs_wm_bfm64", "cs_wm_half_cmp", | 24 | "cs_w64x_load_ballot_load", "cs_w64x_partial", "cs_wave64_ballot", "cs_wm_bfm64", "cs_wm_half_cmp", |
| 25 | "cs_wavemask", "cs_cvt_f32_sat", "ps_scc_minmax", "ps_fma_literal", "ps_f16_vop2", | 25 | "cs_wavemask", "cs_cvt_f32_sat", "ps_scc_minmax", "ps_fma_literal", "ps_f16_vop2", |
| @@ -28,6 +28,7 @@ SHADERS = ("cs_smem_bounds", "cs_smem_stride_align", "cs_smem_sload_neg", "cs_bu | |||
| 28 | "cs_buf_swizzle", # swizzled MUBUF / ADD_TID (test_buffer_swizzle.py) | 28 | "cs_buf_swizzle", # swizzled MUBUF / ADD_TID (test_buffer_swizzle.py) |
| 29 | # TEST-175: GPU fixtures for the docs/design.md rules that were checked on the CPU only | 29 | # TEST-175: GPU fixtures for the docs/design.md rules that were checked on the CPU only |
| 30 | "ps_cmp_nlg", "ps_cvt_off", "ps_fmac_f16_mods", "ps_vop3_const_mods", "ps_interp_f32_mods", "ps_interp_mov_mods", | 30 | "ps_cmp_nlg", "ps_cvt_off", "ps_fmac_f16_mods", "ps_vop3_const_mods", "ps_interp_f32_mods", "ps_interp_mov_mods", |
| 31 | "ps_f16_pack_mods", # v_pack_b32_f16 neg/abs (SHADER-260) | ||
| 31 | "cs_w64x_andn2_exec", # s_andn2_saveexec_b64 / s_andn2_wrexec_b64 (test_andn2_exec_b64.py) | 32 | "cs_w64x_andn2_exec", # s_andn2_saveexec_b64 / s_andn2_wrexec_b64 (test_andn2_exec_b64.py) |
| 32 | "cs_w64x_saveexec_b64", # s_and/s_or/s_andn2_saveexec_b64, s_andn2_wrexec_b64 (test_saveexec_b64.py) | 33 | "cs_w64x_saveexec_b64", # s_and/s_or/s_andn2_saveexec_b64, s_andn2_wrexec_b64 (test_saveexec_b64.py) |
| 33 | "ps_valu16_mad", "ps_valu16_subrev", # v_mad_u32_u16 / v_mad_i32_i16, v_subrev_f16 | 34 | "ps_valu16_mad", "ps_valu16_subrev", # v_mad_u32_u16 / v_mad_i32_i16, v_subrev_f16 |
diff --git a/tests/semantic/spirv_mini_interp.py b/tests/semantic/spirv_mini_interp.py index dbc1c4317..05650dec8 100644 --- a/tests/semantic/spirv_mini_interp.py +++ b/tests/semantic/spirv_mini_interp.py | |||
| @@ -37,6 +37,27 @@ class UnsupportedConstruct(NotImplementedError): | |||
| 37 | """The module uses something this interpreter deliberately does not model.""" | 37 | """The module uses something this interpreter deliberately does not model.""" |
| 38 | 38 | ||
| 39 | 39 | ||
| 40 | class InvalidModule(AssertionError): | ||
| 41 | """The module breaks a SPIR-V structural rule spirv-val enforces, so no driver would accept it, even though | ||
| 42 | this interpreter could run it. Raised instead of returning results for a shader that never reaches a GPU.""" | ||
| 43 | |||
| 44 | |||
| 45 | def check_structure(body): | ||
| 46 | """spirv-val's merge rule (SPIR-V 2.16.2): OpSelectionMerge must be the second-to-last instruction of its block, | ||
| 47 | directly before OpBranchConditional or OpSwitch, and OpLoopMerge directly before OpBranch or | ||
| 48 | OpBranchConditional. Until 2026-11-22 the interpreter skipped merges, so a translator change that put an | ||
| 49 | instruction between a merge and its branch (#1633: OpLoad %active) passed every semantic test while every | ||
| 50 | driver rejected the module. `body` is the list of (result, opcode, operands, line) of a function.""" | ||
| 51 | follow = {"OpSelectionMerge": ("OpBranchConditional", "OpSwitch"), | ||
| 52 | "OpLoopMerge": ("OpBranch", "OpBranchConditional")} | ||
| 53 | for k, (_, op, _, line) in enumerate(body): | ||
| 54 | if op in follow: | ||
| 55 | nxt = body[k + 1][1] if k + 1 < len(body) else None | ||
| 56 | if nxt not in follow[op]: | ||
| 57 | raise InvalidModule(f"{line!r} is followed by {body[k + 1][3] if nxt else 'the end of the function'!r}" | ||
| 58 | f", not by {' or '.join(follow[op])}") | ||
| 59 | |||
| 60 | |||
| 40 | # Instructions that carry no runtime semantics for a single-entry-point, straight-line module. | 61 | # Instructions that carry no runtime semantics for a single-entry-point, straight-line module. |
| 41 | _IGNORED = frozenset({ | 62 | _IGNORED = frozenset({ |
| 42 | "OpCapability", "OpExtension", "OpExtInstImport", "OpMemoryModel", "OpEntryPoint", "OpExecutionMode", | 63 | "OpCapability", "OpExtension", "OpExtInstImport", "OpMemoryModel", "OpEntryPoint", "OpExecutionMode", |
| @@ -463,6 +484,7 @@ def _invocation(text, inputs, push_constants, memory, step=False): | |||
| 463 | raise UnsupportedConstruct(f"{op} in module header") | 484 | raise UnsupportedConstruct(f"{op} in module header") |
| 464 | if not in_body: | 485 | if not in_body: |
| 465 | raise UnsupportedConstruct("no function body") | 486 | raise UnsupportedConstruct("no function body") |
| 487 | check_structure(body) | ||
| 466 | 488 | ||
| 467 | def deref(p): | 489 | def deref(p): |
| 468 | box, i = p | 490 | box, i = p |
| @@ -845,18 +867,6 @@ def _invocation(text, inputs, push_constants, memory, step=False): | |||
| 845 | values[res] = fma_f32(x, y, z) | 867 | values[res] = fma_f32(x, y, z) |
| 846 | elif op == "OpFNegate": | 868 | elif op == "OpFNegate": |
| 847 | values[res] = f32(-val(a[1])) | 869 | values[res] = f32(-val(a[1])) |
| 848 | elif op == "OpFDiv": | ||
| 849 | x, y = val(a[1]), val(a[2]) | ||
| 850 | if not (isinstance(x, float) and isinstance(y, float)): | ||
| 851 | raise UnsupportedConstruct("OpFDiv on non-float") | ||
| 852 | if y == 0.0: | ||
| 853 | raise UnsupportedConstruct("OpFDiv by zero (undefined in SPIR-V)") | ||
| 854 | if math.isinf(x) and math.isinf(y): | ||
| 855 | values[res] = math.nan | ||
| 856 | elif math.isnan(x) or math.isnan(y): | ||
| 857 | values[res] = math.nan | ||
| 858 | else: | ||
| 859 | values[res] = f32(x / y) # x/inf is a signed zero, as in Python | ||
| 860 | elif op == "OpQuantizeToF16": | 870 | elif op == "OpQuantizeToF16": |
| 861 | # Single-instruction f32 -> f16 -> f32 round to nearest, with the | 871 | # Single-instruction f32 -> f16 -> f32 round to nearest, with the |
| 862 | # SPIR-V subnormal rule: a magnitude too small for a normal f16 | 872 | # SPIR-V subnormal rule: a magnitude too small for a normal f16 |
diff --git a/tests/semantic/spirv_wave_interp.py b/tests/semantic/spirv_wave_interp.py index db8f1e950..a3adf6544 100644 --- a/tests/semantic/spirv_wave_interp.py +++ b/tests/semantic/spirv_wave_interp.py | |||
| @@ -38,6 +38,15 @@ class UnsupportedConstruct(NotImplementedError): | |||
| 38 | """The module uses something this interpreter deliberately does not model.""" | 38 | """The module uses something this interpreter deliberately does not model.""" |
| 39 | 39 | ||
| 40 | 40 | ||
| 41 | class InvalidModule(AssertionError): | ||
| 42 | """The module breaks spirv-val's merge rule (see spirv_mini_interp.check_structure): a merge instruction must | ||
| 43 | directly precede its block's branch. Raised instead of running a shader no driver would accept.""" | ||
| 44 | |||
| 45 | |||
| 46 | _MERGE_FOLLOW = {"OpSelectionMerge": ("OpBranchConditional", "OpSwitch"), | ||
| 47 | "OpLoopMerge": ("OpBranch", "OpBranchConditional")} | ||
| 48 | |||
| 49 | |||
| 41 | class F: | 50 | class F: |
| 42 | """A 32-bit float carried as its bit pattern.""" | 51 | """A 32-bit float carried as its bit pattern.""" |
| 43 | __slots__ = ("bits",) | 52 | __slots__ = ("bits",) |
| @@ -120,6 +129,7 @@ class _Module: | |||
| 120 | self.id_type = {} | 129 | self.id_type = {} |
| 121 | cur = None | 130 | cur = None |
| 122 | in_body = False | 131 | in_body = False |
| 132 | merge_line = None # (opcode, line) of a merge whose branch has not been seen yet | ||
| 123 | for raw in text.splitlines(): | 133 | for raw in text.splitlines(): |
| 124 | line = raw.strip() | 134 | line = raw.strip() |
| 125 | if not line: | 135 | if not line: |
| @@ -130,6 +140,11 @@ class _Module: | |||
| 130 | res, op, rest = m.groups() | 140 | res, op, rest = m.groups() |
| 131 | a = rest.split() | 141 | a = rest.split() |
| 132 | if in_body: | 142 | if in_body: |
| 143 | if merge_line is not None: | ||
| 144 | if op not in _MERGE_FOLLOW[merge_line[0]]: | ||
| 145 | raise InvalidModule(f"{merge_line[1]!r} is followed by {line!r}, not by " | ||
| 146 | f"{' or '.join(_MERGE_FOLLOW[merge_line[0]])}") | ||
| 147 | merge_line = None | ||
| 133 | if op == "OpFunctionEnd": | 148 | if op == "OpFunctionEnd": |
| 134 | in_body = False | 149 | in_body = False |
| 135 | continue | 150 | continue |
| @@ -149,6 +164,7 @@ class _Module: | |||
| 149 | cur.phis.append((res, a)) | 164 | cur.phis.append((res, a)) |
| 150 | elif op in ("OpSelectionMerge", "OpLoopMerge"): | 165 | elif op in ("OpSelectionMerge", "OpLoopMerge"): |
| 151 | cur.merge = (op, a[0], a[1] if op == "OpLoopMerge" else None) | 166 | cur.merge = (op, a[0], a[1] if op == "OpLoopMerge" else None) |
| 167 | merge_line = (op, line) | ||
| 152 | elif op in _TERMINATORS: | 168 | elif op in _TERMINATORS: |
| 153 | cur.term = (op, a) | 169 | cur.term = (op, a) |
| 154 | cur = None | 170 | cur = None |
diff --git a/tests/semantic/test_alu_bitop_folding.py b/tests/semantic/test_alu_bitop_folding.py new file mode 100644 index 000000000..42a2bbd9a --- /dev/null +++ b/tests/semantic/test_alu_bitop_folding.py | |||
| @@ -0,0 +1,159 @@ | |||
| 1 | from __future__ import annotations | ||
| 2 | |||
| 3 | """Regression and semantic tests for bitwise and shift constant folding in the translator. | ||
| 4 | |||
| 5 | Verifies that: | ||
| 6 | - Constant and immediate shifts fold the modulo 32 mask at translate time (no runtime OpBitwiseAnd %c31). | ||
| 7 | - Constant v_bfe_u32/i32 offset and width fold directly into OpBitField[US]Extract operands (no OpISub/OpULessThan/OpSelect). | ||
| 8 | - Constant v_alignbyte_b32 with sel=0 folds directly to the low word; non-zero sel folds into exact shifts and OpBitwiseOr. | ||
| 9 | - Constant v_alignbit_b32 with shift=0 folds directly to the low word; non-zero shift folds into exact shifts and OpBitwiseOr. | ||
| 10 | - dedupe_types terminates early upon reaching function definitions and correctly renames aliased types across the shader. | ||
| 11 | """ | ||
| 12 | import os | ||
| 13 | import re | ||
| 14 | import struct | ||
| 15 | import sys | ||
| 16 | import tempfile | ||
| 17 | import unittest | ||
| 18 | import warnings | ||
| 19 | |||
| 20 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 21 | ROOT = os.path.dirname(os.path.dirname(HERE)) | ||
| 22 | TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") | ||
| 23 | |||
| 24 | sys.dont_write_bytecode = True | ||
| 25 | if TOOLS_DIR not in sys.path: | ||
| 26 | sys.path.insert(0, TOOLS_DIR) | ||
| 27 | if HERE not in sys.path: | ||
| 28 | sys.path.insert(0, HERE) | ||
| 29 | |||
| 30 | import rdna2spirv # noqa: E402 | ||
| 31 | import spirv_mini_interp as si # noqa: E402 | ||
| 32 | import support # noqa: E402 | ||
| 33 | |||
| 34 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 35 | |||
| 36 | |||
| 37 | class BitopConstantFoldingTests(unittest.TestCase): | ||
| 38 | def translate_lines(self, lines: list[str]) -> str: | ||
| 39 | body = "\n".join("\t" + line for line in lines) | ||
| 40 | asm = f"; bitop_test\n{body}\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" | ||
| 41 | with tempfile.TemporaryDirectory() as tmp: | ||
| 42 | d_dir = os.path.join(tmp, "disasm") | ||
| 43 | os.mkdir(d_dir) | ||
| 44 | s_path = os.path.join(d_dir, "ps_bitop.s") | ||
| 45 | with open(s_path, "w", encoding="utf-8") as f: | ||
| 46 | f.write(asm) | ||
| 47 | with open(os.path.join(tmp, "ps_bitop.dxbc"), "wb") as f: | ||
| 48 | f.write(STUB_DXBC) | ||
| 49 | with warnings.catch_warnings(): | ||
| 50 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 51 | return rdna2spirv.translate(s_path) | ||
| 52 | |||
| 53 | def test_constant_shift_eliminates_runtime_mask(self): | ||
| 54 | lines = [ | ||
| 55 | "v_mov_b32 v1, 0x1234", | ||
| 56 | "v_lshlrev_b32 v0, 4, v1", | ||
| 57 | ] | ||
| 58 | spv = self.translate_lines(lines) | ||
| 59 | self.assertNotIn("OpBitwiseAnd %uint", spv) | ||
| 60 | self.assertIn("OpShiftLeftLogical %uint", spv) | ||
| 61 | res = si.run_fragment(spv)["%out_mrt0"][0] | ||
| 62 | self.assertEqual(res, 0x12340) | ||
| 63 | |||
| 64 | def test_constant_bfe_eliminates_runtime_bounds(self): | ||
| 65 | lines = [ | ||
| 66 | "v_mov_b32 v1, 0x12345678", | ||
| 67 | "v_bfe_u32 v0, v1, 8, 12", | ||
| 68 | ] | ||
| 69 | spv = self.translate_lines(lines) | ||
| 70 | # Should directly emit OpBitFieldUExtract without runtime sub, cmp, or bounds select | ||
| 71 | self.assertNotIn("OpBitwiseAnd %uint", spv) | ||
| 72 | self.assertNotIn("OpISub %uint", spv) | ||
| 73 | self.assertNotIn("OpULessThan %bool", spv) | ||
| 74 | self.assertIn("OpBitFieldUExtract %uint", spv) | ||
| 75 | res = si.run_fragment(spv)["%out_mrt0"][0] | ||
| 76 | self.assertEqual(res, 0x456) | ||
| 77 | |||
| 78 | def test_constant_alignbyte_zero_shift_folds_directly(self): | ||
| 79 | lines = [ | ||
| 80 | "v_mov_b32 v1, 0xDEADBEEF", | ||
| 81 | "v_mov_b32 v2, 0x12345678", | ||
| 82 | "v_alignbyte_b32 v0, v1, v2, 0", | ||
| 83 | ] | ||
| 84 | spv = self.translate_lines(lines) | ||
| 85 | self.assertNotIn("OpShiftRightLogical", spv) | ||
| 86 | self.assertNotIn("OpShiftLeftLogical", spv) | ||
| 87 | self.assertNotIn("OpBitwiseOr", spv) | ||
| 88 | res = si.run_fragment(spv)["%out_mrt0"][0] | ||
| 89 | self.assertEqual(res, 0x12345678) | ||
| 90 | |||
| 91 | def test_constant_alignbyte_nonzero_shift_emits_direct_shifts(self): | ||
| 92 | lines = [ | ||
| 93 | "v_mov_b32 v1, 0x8899AABB", | ||
| 94 | "v_mov_b32 v2, 0x11223344", | ||
| 95 | "v_alignbyte_b32 v0, v1, v2, 1", | ||
| 96 | ] | ||
| 97 | spv = self.translate_lines(lines) | ||
| 98 | # Shift and or are emitted directly without runtime mask or sub | ||
| 99 | self.assertNotIn("OpBitwiseAnd %uint", spv) | ||
| 100 | self.assertNotIn("OpISub %uint", spv) | ||
| 101 | self.assertIn("OpShiftRightLogical %uint", spv) | ||
| 102 | self.assertIn("OpShiftLeftLogical %uint", spv) | ||
| 103 | self.assertIn("OpBitwiseOr %uint", spv) | ||
| 104 | res = si.run_fragment(spv)["%out_mrt0"][0] | ||
| 105 | self.assertEqual(res, 0xBB112233) | ||
| 106 | |||
| 107 | def test_constant_alignbit_zero_shift_folds_directly(self): | ||
| 108 | lines = [ | ||
| 109 | "v_mov_b32 v1, 0xDEADBEEF", | ||
| 110 | "v_mov_b32 v2, 0x12345678", | ||
| 111 | "v_alignbit_b32 v0, v1, v2, 0", | ||
| 112 | ] | ||
| 113 | spv = self.translate_lines(lines) | ||
| 114 | self.assertNotIn("OpShiftRightLogical", spv) | ||
| 115 | self.assertNotIn("OpShiftLeftLogical", spv) | ||
| 116 | self.assertNotIn("OpBitwiseOr", spv) | ||
| 117 | res = si.run_fragment(spv)["%out_mrt0"][0] | ||
| 118 | self.assertEqual(res, 0x12345678) | ||
| 119 | |||
| 120 | def test_constant_alignbit_nonzero_shift_emits_direct_shifts(self): | ||
| 121 | lines = [ | ||
| 122 | "v_mov_b32 v1, 0x12345678", | ||
| 123 | "v_mov_b32 v2, 0x9ABCDEF0", | ||
| 124 | "v_alignbit_b32 v0, v1, v2, 16", | ||
| 125 | ] | ||
| 126 | spv = self.translate_lines(lines) | ||
| 127 | self.assertNotIn("OpBitwiseAnd %uint", spv) | ||
| 128 | self.assertNotIn("OpISub %uint", spv) | ||
| 129 | self.assertIn("OpShiftRightLogical %uint", spv) | ||
| 130 | self.assertIn("OpShiftLeftLogical %uint", spv) | ||
| 131 | self.assertIn("OpBitwiseOr %uint", spv) | ||
| 132 | res = si.run_fragment(spv)["%out_mrt0"][0] | ||
| 133 | self.assertEqual(res, 0x56789ABC) | ||
| 134 | |||
| 135 | def test_dedupe_types_merges_duplicate_types_and_substitutes(self): | ||
| 136 | spv_sample = ( | ||
| 137 | "OpCapability Shader\n" | ||
| 138 | "%uint = OpTypeInt 32 0\n" | ||
| 139 | "%v4uint = OpTypeVector %uint 4\n" | ||
| 140 | "%v4uint_st = OpTypeVector %uint 4\n" | ||
| 141 | "%ptr_v4uint = OpTypePointer StorageBuffer %v4uint\n" | ||
| 142 | "%ptr_v4uint_st = OpTypePointer StorageBuffer %v4uint_st\n" | ||
| 143 | "%fn = OpTypeFunction %void\n" | ||
| 144 | "%main = OpFunction %void None %fn\n" | ||
| 145 | "%entry = OpLabel\n" | ||
| 146 | "%var = OpVariable %ptr_v4uint_st StorageBuffer\n" | ||
| 147 | "%val = OpLoad %v4uint_st %var\n" | ||
| 148 | "OpReturn\n" | ||
| 149 | "OpFunctionEnd" | ||
| 150 | ) | ||
| 151 | deduped = rdna2spirv.dedupe_types(spv_sample) | ||
| 152 | self.assertNotIn("%v4uint_st =", deduped) | ||
| 153 | self.assertNotIn("%ptr_v4uint_st =", deduped) | ||
| 154 | self.assertIn("%var = OpVariable %ptr_v4uint StorageBuffer", deduped) | ||
| 155 | self.assertIn("%val = OpLoad %v4uint %var", deduped) | ||
| 156 | |||
| 157 | |||
| 158 | if __name__ == "__main__": | ||
| 159 | unittest.main() | ||
diff --git a/tests/semantic/test_alu_dot4_i8.py b/tests/semantic/test_alu_dot4_i8.py new file mode 100644 index 000000000..ff60a8508 --- /dev/null +++ b/tests/semantic/test_alu_dot4_i8.py | |||
| @@ -0,0 +1,138 @@ | |||
| 1 | """v_dot4_i32_i8 and v_dot4c_i32_i8: the dot product of the signed bytes of two dwords, plus an addend. | ||
| 2 | |||
| 3 | ISA rule (RDNA2): D = S0.b0*S1.b0 + S0.b1*S1.b1 + S0.b2*S1.b2 + S0.b3*S1.b3 + addend, every byte sign-extended, the | ||
| 4 | sum kept modulo 2^32. The addend is the third source for v_dot4_i32_i8 (VOP3P) and the old value of the destination | ||
| 5 | for v_dot4c_i32_i8 (VOP2). The 29 FSPX programs of the package's upscaler DLL (docs/fspx.md) use the pair 27,271 | ||
| 6 | times. | ||
| 7 | |||
| 8 | The expected words below were measured on RDNA2 hardware (gfx1036, the integrated GPU of a Ryzen 9 7950X3D, through | ||
| 9 | tools/hw_oracle): each case ran `v_dot4_i32_i8 v8, v1, v2, v3`, `v_dot4c_i32_i8 v10, v1, v2` with v10 holding the | ||
| 10 | addend, and the same with the two sources swapped. All three gave the word in the table, which the plain-Python | ||
| 11 | reference `ref` reproduces. With `clamp` the hardware saturates v_dot4_i32_i8 to a signed 32-bit value | ||
| 12 | (0x7fffffff and 0x80000000 in the two overflowing cases); the translator refuses that form. | ||
| 13 | |||
| 14 | op_sel. The plain instruction has op_sel 0 and op_sel_hi 7. 89 words in 8 of those programs are v_dot4_i32_i8 with | ||
| 15 | op_sel 2 and op_sel_hi 5, which llvm-mc does not decode (docs/fspx.md). Run on the same hardware as two raw words | ||
| 16 | (0xCC165008 0x0C0E0501: v8 = v1 . v2 + v3 with those fields), that form gave the words of MEASURED_OP_SEL: the dot | ||
| 17 | product with the two 16-bit halves of the second source exchanged, as op_sel selects halves for the packed 16-bit | ||
| 18 | ops. `ref_op_sel` reproduces them; the translator refuses any op_sel on these two instructions until a listing can | ||
| 19 | carry it. | ||
| 20 | |||
| 21 | python -m unittest discover -s tests/semantic -p test_alu_dot4_i8.py | ||
| 22 | """ | ||
| 23 | import os | ||
| 24 | import sys | ||
| 25 | import unittest | ||
| 26 | |||
| 27 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 28 | if HERE not in sys.path: | ||
| 29 | sys.path.insert(0, HERE) | ||
| 30 | |||
| 31 | import support # noqa: E402 | ||
| 32 | |||
| 33 | rdna2spirv = support.rdna2spirv | ||
| 34 | |||
| 35 | # (S0, S1, addend, result measured on gfx1036) | ||
| 36 | MEASURED = [ | ||
| 37 | (0x01020304, 0x05060708, 0x00000000, 0x00000046), # 4*8 + 3*7 + 2*6 + 1*5 = 70 | ||
| 38 | (0x01020304, 0x05060708, 0x000003E8, 0x0000042E), # 70 + 1000 | ||
| 39 | (0xFF80017F, 0x7F7F80FF, 0x00000000, 0xFFFFBF02), # 127*-1 + 1*-128 + -128*127 + -1*127 = -16638 | ||
| 40 | (0xFF80017F, 0x7F7F80FF, 0x00010000, 0x0000BF02), | ||
| 41 | (0x80808080, 0x80808080, 0x00000000, 0x00010000), # 4 * (-128 * -128) | ||
| 42 | (0x80808080, 0x7F7F7F7F, 0x00000005, 0xFFFF0205), # 4 * (-128 * 127) + 5 | ||
| 43 | (0x7F7F7F7F, 0x7F7F7F7F, 0x7FFFFFFF, 0x8000FC03), # wraps upward: no saturation without clamp | ||
| 44 | (0x80808080, 0x7F7F7F7F, 0x80000000, 0x7FFF0200), # wraps downward | ||
| 45 | (0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000003), # 4 * (-1 * -1) - 1 | ||
| 46 | (0x00000000, 0x12345678, 0xDEADBEEF, 0xDEADBEEF), | ||
| 47 | ] | ||
| 48 | |||
| 49 | |||
| 50 | # (S0, S1, addend, result measured on gfx1036 with op_sel 2 and op_sel_hi 5) | ||
| 51 | MEASURED_OP_SEL = [ | ||
| 52 | (0x04030201, 0x08070605, 0x00000000, 62), # the plain form gives 70 | ||
| 53 | (0x04030201, 0x08070605, 0x000003E8, 1062), | ||
| 54 | (0x7F01FE80, 0x02FD7F81, 0x00000000, 16382), # the plain form gives 16253 | ||
| 55 | (0x11223344, 0x55667788, 0x00010000, 74750), # the plain form gives 68358 | ||
| 56 | (0xFFFFFFFF, 0x01020304, 0x00000007, 0xFFFFFFFD), # every byte of S0 the same: the order cannot show | ||
| 57 | ] | ||
| 58 | |||
| 59 | |||
| 60 | def ref(a, b, addend): | ||
| 61 | def s8(x): | ||
| 62 | return x - 256 if x & 0x80 else x | ||
| 63 | total = sum(s8((a >> (8 * i)) & 0xFF) * s8((b >> (8 * i)) & 0xFF) for i in range(4)) | ||
| 64 | return (total + addend) & 0xFFFFFFFF | ||
| 65 | |||
| 66 | |||
| 67 | def ref_op_sel(a, b, addend): | ||
| 68 | """op_sel 2, op_sel_hi 5: the low half of the product reads the high half of S1 and the high half its low half.""" | ||
| 69 | return ref(a, (b & 0xFFFF) << 16 | b >> 16, addend) | ||
| 70 | |||
| 71 | |||
| 72 | def program(a, b, addend): | ||
| 73 | """mrt0 = (v_dot4_i32_i8, v_dot4c_i32_i8, v_dot4c_i32_i8 with the sources swapped, v_dot4_i32_i8 with the | ||
| 74 | sources and the addend taken from SGPRs and a literal, as the shaders do).""" | ||
| 75 | return [ | ||
| 76 | f"v_mov_b32_e32 v1, 0x{a:08x}", | ||
| 77 | f"v_mov_b32_e32 v2, 0x{b:08x}", | ||
| 78 | f"v_mov_b32_e32 v3, 0x{addend:08x}", | ||
| 79 | f"s_mov_b32 s4, 0x{addend:08x}", | ||
| 80 | "v_dot4_i32_i8 v8, v1, v2, v3", | ||
| 81 | f"v_mov_b32_e32 v9, 0x{addend:08x}", | ||
| 82 | "v_dot4c_i32_i8 v9, v1, v2", | ||
| 83 | f"v_mov_b32_e32 v10, 0x{addend:08x}", | ||
| 84 | "v_dot4c_i32_i8 v10, v2, v1", | ||
| 85 | f"v_dot4_i32_i8 v11, v1, 0x{b:08x}, s4", | ||
| 86 | "exp mrt0 v8, v9, v10, v11 done vm", | ||
| 87 | "s_endpgm", | ||
| 88 | ] | ||
| 89 | |||
| 90 | |||
| 91 | class Dot4I8(unittest.TestCase): | ||
| 92 | def test_the_reference_reproduces_the_hardware_words(self): | ||
| 93 | for a, b, addend, measured in MEASURED: | ||
| 94 | self.assertEqual(ref(a, b, addend), measured, f"{a:#x} . {b:#x} + {addend:#x}") | ||
| 95 | |||
| 96 | def test_both_forms_give_the_hardware_words(self): | ||
| 97 | for a, b, addend, measured in MEASURED: | ||
| 98 | with self.subTest(a=f"{a:#010x}", b=f"{b:#010x}", addend=f"{addend:#010x}"): | ||
| 99 | spv = support.translate_lines("ps_dot4_i8", program(a, b, addend)) | ||
| 100 | self.assertEqual(support.mrt0_words(spv), [measured] * 4) | ||
| 101 | |||
| 102 | def test_the_accumulating_form_reads_its_destination(self): | ||
| 103 | # v9 is never written before v_dot4c reads it: the old value is then the register's initial 0, not garbage | ||
| 104 | # from an expression that dropped the addend. 70 is the dot product alone. | ||
| 105 | lines = ["v_mov_b32_e32 v1, 0x01020304", "v_mov_b32_e32 v2, 0x05060708", "v_dot4c_i32_i8 v9, v1, v2", | ||
| 106 | "v_dot4c_i32_i8 v9, v1, v2", "exp mrt0 v9, v9, v9, v9 done vm", "s_endpgm"] | ||
| 107 | self.assertEqual(support.mrt0_words(support.translate_lines("ps_dot4c_twice", lines)), [140] * 4) | ||
| 108 | |||
| 109 | def test_the_bytes_are_signed(self): | ||
| 110 | # 0xff * 0x01: -1 as a signed byte, 255 as an unsigned one. | ||
| 111 | lines = ["v_mov_b32_e32 v1, 0x000000ff", "v_mov_b32_e32 v2, 0x00000001", "v_mov_b32_e32 v3, 0", | ||
| 112 | "v_dot4_i32_i8 v8, v1, v2, v3", "exp mrt0 v8, v8, v8, v8 done vm", "s_endpgm"] | ||
| 113 | self.assertEqual(support.mrt0_words(support.translate_lines("ps_dot4_signed", lines)), [0xFFFFFFFF] * 4) | ||
| 114 | |||
| 115 | def test_the_op_sel_reference_reproduces_the_hardware_words(self): | ||
| 116 | for a, b, addend, measured in MEASURED_OP_SEL: | ||
| 117 | self.assertEqual(ref_op_sel(a, b, addend), measured, f"{a:#x} . {b:#x} + {addend:#x}") | ||
| 118 | # The table can tell the two readings apart: the plain rule gives another word in four of the five cases. | ||
| 119 | self.assertEqual(sum(ref(a, b, c) != m for a, b, c, m in MEASURED_OP_SEL), 4) | ||
| 120 | |||
| 121 | def test_op_sel_is_refused(self): | ||
| 122 | lines = ["v_mov_b32_e32 v1, 1", "v_mov_b32_e32 v2, 1", "v_mov_b32_e32 v3, 0", | ||
| 123 | "v_dot4_i32_i8 v8, v1, v2, v3 op_sel:[0,1,0] op_sel_hi:[1,0,1]", | ||
| 124 | "exp mrt0 v8, v8, v8, v8 done vm", "s_endpgm"] | ||
| 125 | with self.assertRaises(rdna2spirv.Unsupported) as refused: | ||
| 126 | support.translate_lines("ps_dot4_op_sel", lines) | ||
| 127 | self.assertEqual(str(refused.exception), "v_dot4_i32_i8 op_sel") | ||
| 128 | |||
| 129 | def test_clamp_is_refused(self): | ||
| 130 | lines = ["v_mov_b32_e32 v1, 1", "v_mov_b32_e32 v2, 1", "v_mov_b32_e32 v3, 0", | ||
| 131 | "v_dot4_i32_i8 v8, v1, v2, v3 clamp", "exp mrt0 v8, v8, v8, v8 done vm", "s_endpgm"] | ||
| 132 | with self.assertRaises(rdna2spirv.Unsupported) as refused: | ||
| 133 | support.translate_lines("ps_dot4_clamp", lines) | ||
| 134 | self.assertEqual(str(refused.exception), "v_dot4_i32_i8 clamp") | ||
| 135 | |||
| 136 | |||
| 137 | if __name__ == "__main__": | ||
| 138 | unittest.main() | ||
diff --git a/tests/semantic/test_alu_min3_max3_med3_16.py b/tests/semantic/test_alu_min3_max3_med3_16.py new file mode 100644 index 000000000..2c1376a62 --- /dev/null +++ b/tests/semantic/test_alu_min3_max3_med3_16.py | |||
| @@ -0,0 +1,537 @@ | |||
| 1 | """Semantic interpreter tests for RDNA2 16-bit three-operand min/max/median instructions: | ||
| 2 | v_min3_i16, v_min3_u16, v_max3_i16, v_max3_u16, v_med3_i16, v_med3_u16, | ||
| 3 | v_min3_f16, and v_max3_f16. | ||
| 4 | |||
| 5 | Each test translates a synthetic pixel shader listing with tools/rdna2spirv.py, executes it in | ||
| 6 | tests/semantic/spirv_mini_interp.py, and compares the exported mrt0 words against plain-Python references. | ||
| 7 | |||
| 8 | Covers: | ||
| 9 | - A multi-instruction hand-written .asm fixture exercising all eight opcodes into low and high VGPR halves. | ||
| 10 | - Signed vs unsigned 16-bit integer comparisons across boundary values (0x8000, 0xFFFF, 0x7FFF, 0x0000, 0x0001) | ||
| 11 | in all 3! = 6 operand permutations. | ||
| 12 | - All 16 op_sel:[s0,s1,s2,dst] bit combinations for every opcode. | ||
| 13 | - Unwritten destination-half preservation and destination/source register aliasing. | ||
| 14 | - Inline integer/float constants and SGPR operands. | ||
| 15 | - Floating-point 16-bit NaN skipping (NMin/NMax), signed-zero ordering (-0.0 < +0.0), neg/abs source modifiers, | ||
| 16 | and VOP3 output modifiers (mul:2, mul:4, div:2, clamp). | ||
| 17 | - Unsupported rejections for clamp on integer min3/max3/med3 and non-VGPR op_sel destination. | ||
| 18 | - Seeded random sweep over all eight opcodes. | ||
| 19 | """ | ||
| 20 | from __future__ import annotations | ||
| 21 | |||
| 22 | import itertools | ||
| 23 | import math | ||
| 24 | import os | ||
| 25 | import random | ||
| 26 | import struct | ||
| 27 | import sys | ||
| 28 | import tempfile | ||
| 29 | import unittest | ||
| 30 | import warnings | ||
| 31 | |||
| 32 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 33 | ROOT = os.path.dirname(os.path.dirname(HERE)) | ||
| 34 | TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") | ||
| 35 | |||
| 36 | sys.dont_write_bytecode = True | ||
| 37 | sys.path.insert(0, TOOLS_DIR) | ||
| 38 | sys.path.insert(0, HERE) | ||
| 39 | |||
| 40 | import rdna2spirv # noqa: E402 | ||
| 41 | import spirv_mini_interp as si # noqa: E402 | ||
| 42 | |||
| 43 | MASK16 = 0xFFFF | ||
| 44 | MASK32 = 0xFFFFFFFF | ||
| 45 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 46 | OLD = 0xA55A5AA5 | ||
| 47 | |||
| 48 | INT_OPS = ( | ||
| 49 | "v_min3_i16", | ||
| 50 | "v_min3_u16", | ||
| 51 | "v_max3_i16", | ||
| 52 | "v_max3_u16", | ||
| 53 | "v_med3_i16", | ||
| 54 | "v_med3_u16", | ||
| 55 | ) | ||
| 56 | FLOAT_OPS = ("v_min3_f16", "v_max3_f16") | ||
| 57 | ALL_OPS = INT_OPS + FLOAT_OPS | ||
| 58 | |||
| 59 | # Hand-written multi-instruction RDNA2 pixel shader fixture covering all 8 opcodes into lo/hi VGPR halves. | ||
| 60 | # Register inputs: | ||
| 61 | # v10 = 0x80007FFF -> lo = 0x7FFF (+32767 i16 / 32767 u16), hi = 0x8000 (-32768 i16 / 32768 u16) | ||
| 62 | # v11 = 0xFFFF0001 -> lo = 0x0001 (+1), hi = 0xFFFF (-1 i16 / 65535 u16) | ||
| 63 | # v12 = 0x0005FFFE -> lo = 0xFFFE (-2 i16 / 65534 u16), hi = 0x0005 (+5) | ||
| 64 | # v13 = 0x3C00BC00 -> lo = 0xBC00 (-1.0 f16), hi = 0x3C00 (+1.0 f16) | ||
| 65 | # v14 = 0x80000000 -> lo = 0x0000 (+0.0 f16), hi = 0x8000 (-0.0 f16) | ||
| 66 | # v15 = 0x7E004000 -> lo = 0x4000 (+2.0 f16), hi = 0x7E00 (qNaN f16) | ||
| 67 | # Expected mrt0 words: | ||
| 68 | # v0: v_min3_i16(32767, -1, -2) = -2 (0xFFFE) | v_max3_i16(-32768, 1, 5) = 5 (0x0005) -> 0x0005FFFE | ||
| 69 | # v1: v_med3_i16(32767, -1, 5) = 5 (0x0005) | v_min3_u16(32768, 65535, 65534) = 0x8000 -> 0x80000005 | ||
| 70 | # v2: v_max3_u16(32767, 65535, 65534) = 0xFFFF | v_med3_u16(32768, 1, 65534) = 0x8000 -> 0x8000FFFF | ||
| 71 | # v3: v_min3_f16(+1.0, -0.0, qNaN) = -0.0 (0x8000) | v_max3_f16(-1.0, +0.0, +2.0) = 0x4000 -> 0x40008000 | ||
| 72 | PS_MIN3_MAX3_MED3_16_ASM = """\ | ||
| 73 | ; test_alu_min3_max3_med3_16 fixture | ||
| 74 | \tv_mov_b32 v0, 0xdeadbef0 | ||
| 75 | \tv_mov_b32 v1, 0xdeadbef1 | ||
| 76 | \tv_mov_b32 v2, 0xdeadbef2 | ||
| 77 | \tv_mov_b32 v3, 0xdeadbef3 | ||
| 78 | \tv_mov_b32 v10, 0x80007fff | ||
| 79 | \tv_mov_b32 v11, 0xffff0001 | ||
| 80 | \tv_mov_b32 v12, 0x0005fffe | ||
| 81 | \tv_mov_b32 v13, 0x3c00bc00 | ||
| 82 | \tv_mov_b32 v14, 0x80000000 | ||
| 83 | \tv_mov_b32 v15, 0x7e004000 | ||
| 84 | \tv_min3_i16 v0, v10, v11, v12 op_sel:[0,1,0,0] | ||
| 85 | \tv_max3_i16 v0, v10, v11, v12 op_sel:[1,0,1,1] | ||
| 86 | \tv_med3_i16 v1, v10, v11, v12 op_sel:[0,1,1,0] | ||
| 87 | \tv_min3_u16 v1, v10, v11, v12 op_sel:[1,1,0,1] | ||
| 88 | \tv_max3_u16 v2, v10, v11, v12 op_sel:[0,1,0,0] | ||
| 89 | \tv_med3_u16 v2, v10, v11, v12 op_sel:[1,0,0,1] | ||
| 90 | \tv_min3_f16 v3, v13, v14, v15 op_sel:[1,1,1,0] | ||
| 91 | \tv_max3_f16 v3, v13, v14, v15 op_sel:[0,0,0,1] | ||
| 92 | \texp mrt0 v0, v1, v2, v3 done vm | ||
| 93 | \ts_endpgm | ||
| 94 | """ | ||
| 95 | PS_MIN3_MAX3_MED3_16_EXPECTED = (0x0005FFFE, 0x80000005, 0x8000FFFF, 0x40008000) | ||
| 96 | |||
| 97 | INT_TRIPLES = ( | ||
| 98 | (0x0005, 0x8000, 0x0007), | ||
| 99 | (0xFFFF, 0x0000, 0x0001), | ||
| 100 | (0x7FFF, 0x8000, 0xFFFF), | ||
| 101 | (0x8001, 0x8000, 0x7FFE), | ||
| 102 | (0x0001, 0xFFFE, 0xFFFF), | ||
| 103 | (0x0009, 0x0009, 0x8000), | ||
| 104 | (0xFFFF, 0xFFFF, 0x0000), | ||
| 105 | (0x0003, 0x0003, 0x0003), | ||
| 106 | ) | ||
| 107 | |||
| 108 | # f16 bit patterns: -inf, -2.0, -1.0, -0.5, smallest neg subnormal, -0.0, +0.0, subnormal, +0.5, +1.0, +2.0, +inf | ||
| 109 | F16_VALS = ( | ||
| 110 | 0xFC00, # -inf | ||
| 111 | 0xC000, # -2.0 | ||
| 112 | 0xBC00, # -1.0 | ||
| 113 | 0xB800, # -0.5 | ||
| 114 | 0x8001, # -2^-24 (negative subnormal) | ||
| 115 | 0x8000, # -0.0 | ||
| 116 | 0x0000, # +0.0 | ||
| 117 | 0x0001, # +2^-24 (positive subnormal) | ||
| 118 | 0x3800, # +0.5 | ||
| 119 | 0x3C00, # +1.0 | ||
| 120 | 0x4000, # +2.0 | ||
| 121 | 0x7C00, # +inf | ||
| 122 | ) | ||
| 123 | |||
| 124 | |||
| 125 | def s16(h: int) -> int: | ||
| 126 | h &= MASK16 | ||
| 127 | return h - 0x10000 if h & 0x8000 else h | ||
| 128 | |||
| 129 | |||
| 130 | def f16_to_float(h: int) -> float: | ||
| 131 | return struct.unpack("<e", struct.pack("<H", h & MASK16))[0] | ||
| 132 | |||
| 133 | |||
| 134 | def float_to_f16_bits(f: float) -> int: | ||
| 135 | try: | ||
| 136 | return struct.unpack("<H", struct.pack("<e", f))[0] | ||
| 137 | except OverflowError: | ||
| 138 | return 0x7C00 if f > 0 else 0xFC00 | ||
| 139 | |||
| 140 | |||
| 141 | def half_bits(word: int, hi: int) -> int: | ||
| 142 | return ((word >> 16) if hi else word) & MASK16 | ||
| 143 | |||
| 144 | |||
| 145 | def merge_half(res16: int, dst_hi: int, old: int = OLD) -> int: | ||
| 146 | res16 &= MASK16 | ||
| 147 | return ((res16 << 16) | (old & MASK16)) if dst_hi else ((old & 0xFFFF0000) | res16) | ||
| 148 | |||
| 149 | |||
| 150 | def ref_int16(op: str, a: int, b: int, c: int) -> int: | ||
| 151 | key = s16 if op.endswith("_i16") else (lambda v: v & MASK16) | ||
| 152 | xs = [a & MASK16, b & MASK16, c & MASK16] | ||
| 153 | if "min3" in op: | ||
| 154 | return min(xs, key=key) & MASK16 | ||
| 155 | if "max3" in op: | ||
| 156 | return max(xs, key=key) & MASK16 | ||
| 157 | if "med3" in op: | ||
| 158 | return sorted(xs, key=key)[1] & MASK16 | ||
| 159 | raise ValueError(op) | ||
| 160 | |||
| 161 | |||
| 162 | def ref_f16(op: str, a_bits: int, b_bits: int, c_bits: int, mods: str = "") -> int: | ||
| 163 | vals = [f16_to_float(h) for h in (a_bits, b_bits, c_bits)] | ||
| 164 | non_nan = [v for v in vals if not math.isnan(v)] | ||
| 165 | if not non_nan: | ||
| 166 | return 0x7E00 | ||
| 167 | pick = min if "min3" in op else max | ||
| 168 | # RDNA2 orders -0.0 below +0.0. | ||
| 169 | chosen = pick(non_nan, key=lambda v: (v, math.copysign(1.0, v))) | ||
| 170 | if "mul:2" in mods: | ||
| 171 | chosen *= 2.0 | ||
| 172 | elif "mul:4" in mods: | ||
| 173 | chosen *= 4.0 | ||
| 174 | elif "div:2" in mods: | ||
| 175 | chosen *= 0.5 | ||
| 176 | if "clamp" in mods: | ||
| 177 | if math.isnan(chosen): | ||
| 178 | chosen = 0.0 | ||
| 179 | else: | ||
| 180 | chosen = max(0.0, min(1.0, chosen)) | ||
| 181 | if chosen == 0.0: | ||
| 182 | chosen = 0.0 | ||
| 183 | return float_to_f16_bits(chosen) | ||
| 184 | |||
| 185 | |||
| 186 | def ref_word(op: str, w1: int, w2: int, w3: int, sel=(0, 0, 0), dst_hi: int = 0, old: int = OLD, mods: str = "") -> int: | ||
| 187 | h1, h2, h3 = half_bits(w1, sel[0]), half_bits(w2, sel[1]), half_bits(w3, sel[2]) | ||
| 188 | r16 = ref_f16(op, h1, h2, h3, mods=mods) if op in FLOAT_OPS else ref_int16(op, h1, h2, h3) | ||
| 189 | return merge_half(r16, dst_hi, old=old) | ||
| 190 | |||
| 191 | |||
| 192 | _TMP_DIR = None | ||
| 193 | _SRC_PATH = None | ||
| 194 | |||
| 195 | |||
| 196 | def setUpModule(): | ||
| 197 | global _TMP_DIR, _SRC_PATH | ||
| 198 | _TMP_DIR = tempfile.TemporaryDirectory() | ||
| 199 | disasm_dir = os.path.join(_TMP_DIR.name, "disasm") | ||
| 200 | os.mkdir(disasm_dir) | ||
| 201 | _SRC_PATH = os.path.join(disasm_dir, "ps_min3_16.s") | ||
| 202 | with open(os.path.join(_TMP_DIR.name, "ps_min3_16.dxbc"), "wb") as f: | ||
| 203 | f.write(STUB_DXBC) | ||
| 204 | |||
| 205 | |||
| 206 | def tearDownModule(): | ||
| 207 | global _TMP_DIR | ||
| 208 | if _TMP_DIR is not None: | ||
| 209 | _TMP_DIR.cleanup() | ||
| 210 | _TMP_DIR = None | ||
| 211 | |||
| 212 | |||
| 213 | def translate_asm(asm: str) -> str: | ||
| 214 | if _TMP_DIR is None: | ||
| 215 | setUpModule() | ||
| 216 | with open(_SRC_PATH, "w", encoding="utf-8") as f: | ||
| 217 | f.write(asm) | ||
| 218 | with warnings.catch_warnings(): | ||
| 219 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 220 | return rdna2spirv.translate(_SRC_PATH) | ||
| 221 | |||
| 222 | |||
| 223 | def run_insn( | ||
| 224 | op: str, | ||
| 225 | operands_words: tuple[int | str, int | str, int | str], | ||
| 226 | *, | ||
| 227 | inline: tuple[int, ...] = (), | ||
| 228 | sgpr_idx: tuple[int, ...] = (), | ||
| 229 | src_mods: dict[int, str] | None = None, | ||
| 230 | tail_mods: str = "", | ||
| 231 | old: int = OLD, | ||
| 232 | dst: str = "v0", | ||
| 233 | alias_dst: int | None = None, | ||
| 234 | ) -> int: | ||
| 235 | lines = [f"\tv_mov_b32 v0, {old & MASK32:#x}"] | ||
| 236 | op_strs = [] | ||
| 237 | sgpr_vals: dict[int, int] = {} | ||
| 238 | for i, val in enumerate(operands_words): | ||
| 239 | fmt = (src_mods or {}).get(i, "{}") | ||
| 240 | if i in inline: | ||
| 241 | val_str = str(val) if isinstance(val, str) else (f"{val:#x}" if isinstance(val, int) and val >= 0 else str(val)) | ||
| 242 | op_strs.append(fmt.format(val_str)) | ||
| 243 | elif i in sgpr_idx: | ||
| 244 | reg = 4 + i | ||
| 245 | sgpr_vals[reg] = int(val) & MASK32 | ||
| 246 | lines.append(f"\ts_mov_b32 s{reg}, {sgpr_vals[reg]:#x}") | ||
| 247 | op_strs.append(fmt.format(f"s{reg}")) | ||
| 248 | elif alias_dst == i: | ||
| 249 | lines[0] = f"\tv_mov_b32 v0, {int(val) & MASK32:#x}" | ||
| 250 | op_strs.append(fmt.format("v0")) | ||
| 251 | else: | ||
| 252 | vreg = f"v{i + 1}" | ||
| 253 | lines.append(f"\tv_mov_b32 {vreg}, {int(val) & MASK32:#x}") | ||
| 254 | op_strs.append(fmt.format(vreg)) | ||
| 255 | mod_suffix = f" {tail_mods}" if tail_mods else "" | ||
| 256 | lines.append(f"\t{op} {dst}, {', '.join(op_strs)}{mod_suffix}") | ||
| 257 | asm = "; test_alu_min3_max3_med3_16\n" + "\n".join(lines) + "\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" | ||
| 258 | spv = translate_asm(asm) | ||
| 259 | return si.run_fragment(spv)["%out_mrt0"][0] | ||
| 260 | |||
| 261 | |||
| 262 | class ReferenceTests(unittest.TestCase): | ||
| 263 | """Cross-check plain-Python reference calculations against hand-worked edge cases.""" | ||
| 264 | |||
| 265 | def test_int_reference(self): | ||
| 266 | self.assertEqual(ref_int16("v_min3_i16", 0x7FFF, 0xFFFF, 0xFFFE), 0xFFFE) | ||
| 267 | self.assertEqual(ref_int16("v_min3_u16", 0x7FFF, 0xFFFF, 0xFFFE), 0x7FFF) | ||
| 268 | self.assertEqual(ref_int16("v_max3_i16", 0x8000, 0x0001, 0x0005), 0x0005) | ||
| 269 | self.assertEqual(ref_int16("v_max3_u16", 0x8000, 0x0001, 0x0005), 0x8000) | ||
| 270 | self.assertEqual(ref_int16("v_med3_i16", 0x7FFF, 0xFFFF, 0x0005), 0x0005) | ||
| 271 | self.assertEqual(ref_int16("v_med3_u16", 0x8000, 0x0001, 0xFFFE), 0x8000) | ||
| 272 | |||
| 273 | def test_f16_reference(self): | ||
| 274 | self.assertEqual(ref_f16("v_min3_f16", 0x3C00, 0x8000, 0x7E00), 0x8000) | ||
| 275 | self.assertEqual(ref_f16("v_max3_f16", 0xBC00, 0x0000, 0x8000), 0x0000) | ||
| 276 | self.assertEqual(ref_f16("v_min3_f16", 0x0000, 0x8000, 0x3C00), 0x8000) | ||
| 277 | |||
| 278 | |||
| 279 | class FixtureTests(unittest.TestCase): | ||
| 280 | """Hand-written multi-instruction RDNA2 .asm fixture for all 8 instructions.""" | ||
| 281 | |||
| 282 | def test_ps_min3_max3_med3_16_fixture(self): | ||
| 283 | spv = translate_asm(PS_MIN3_MAX3_MED3_16_ASM) | ||
| 284 | got = si.run_fragment(spv)["%out_mrt0"] | ||
| 285 | self.assertEqual(got, PS_MIN3_MAX3_MED3_16_EXPECTED) | ||
| 286 | |||
| 287 | |||
| 288 | class Int16PermutationsTests(unittest.TestCase): | ||
| 289 | """Verify signed vs unsigned ordering across all 3! = 6 operand permutations.""" | ||
| 290 | |||
| 291 | def test_boundary_permutations(self): | ||
| 292 | for op in INT_OPS: | ||
| 293 | for triple in INT_TRIPLES: | ||
| 294 | for perm in sorted(set(itertools.permutations(triple))): | ||
| 295 | w1, w2, w3 = (0xBEEF0000 | x for x in perm) | ||
| 296 | with self.subTest(op=op, perm=[hex(x) for x in perm]): | ||
| 297 | self.assertEqual(run_insn(op, (w1, w2, w3)), ref_word(op, w1, w2, w3)) | ||
| 298 | |||
| 299 | |||
| 300 | class OpselAllPatternsTests(unittest.TestCase): | ||
| 301 | """Test all 16 op_sel:[s0,s1,s2,dst] bit combinations for every opcode.""" | ||
| 302 | |||
| 303 | def test_all_sixteen_opsel_patterns_int(self): | ||
| 304 | # Distinct lo/hi values in every register, mixing signed-negative and unsigned-high patterns. | ||
| 305 | w1, w2, w3 = 0x80007FFF, 0xFFFF0001, 0x0005FFFE | ||
| 306 | for op in INT_OPS: | ||
| 307 | for bits in itertools.product((0, 1), repeat=4): | ||
| 308 | mods = f"op_sel:[{bits[0]},{bits[1]},{bits[2]},{bits[3]}]" | ||
| 309 | with self.subTest(op=op, mods=mods): | ||
| 310 | got = run_insn(op, (w1, w2, w3), tail_mods=mods) | ||
| 311 | want = ref_word(op, w1, w2, w3, bits[:3], bits[3]) | ||
| 312 | self.assertEqual(got, want) | ||
| 313 | |||
| 314 | def test_all_sixteen_opsel_patterns_f16(self): | ||
| 315 | # v1 = (-1.0 | 4.0), v2 = (0.5 | 2.0), v3 = (1.5 | -3.0) | ||
| 316 | w1 = float_to_f16_bits(4.0) << 16 | float_to_f16_bits(-1.0) | ||
| 317 | w2 = float_to_f16_bits(2.0) << 16 | float_to_f16_bits(0.5) | ||
| 318 | w3 = float_to_f16_bits(-3.0) << 16 | float_to_f16_bits(1.5) | ||
| 319 | for op in FLOAT_OPS: | ||
| 320 | for bits in itertools.product((0, 1), repeat=4): | ||
| 321 | mods = f"op_sel:[{bits[0]},{bits[1]},{bits[2]},{bits[3]}]" | ||
| 322 | with self.subTest(op=op, mods=mods): | ||
| 323 | got = run_insn(op, (w1, w2, w3), tail_mods=mods) | ||
| 324 | want = ref_word(op, w1, w2, w3, bits[:3], bits[3]) | ||
| 325 | self.assertEqual(got, want) | ||
| 326 | |||
| 327 | |||
| 328 | class HalfPreservationAndAliasingTests(unittest.TestCase): | ||
| 329 | """Unwritten half of dst is preserved, including when dst aliases src0, src1, or src2.""" | ||
| 330 | |||
| 331 | def test_preserves_unwritten_half(self): | ||
| 332 | for op in ALL_OPS: | ||
| 333 | w1, w2, w3 = 0x3C003800, 0x4000B800, 0xBC000001 | ||
| 334 | for dst_hi in (0, 1): | ||
| 335 | for sentinel in (0x12345678, 0xFEDCBA98): | ||
| 336 | with self.subTest(op=op, dst_hi=dst_hi, sentinel=hex(sentinel)): | ||
| 337 | got = run_insn(op, (w1, w2, w3), tail_mods=f"op_sel:[0,0,0,{dst_hi}]", old=sentinel) | ||
| 338 | self.assertEqual(got, ref_word(op, w1, w2, w3, (0, 0, 0), dst_hi, old=sentinel)) | ||
| 339 | |||
| 340 | def test_dst_source_aliasing(self): | ||
| 341 | for op in ALL_OPS: | ||
| 342 | w = [0x80003C00, 0x4000FFFF, 0x38000002] | ||
| 343 | for alias_idx in (0, 1, 2): | ||
| 344 | for dst_hi in (0, 1): | ||
| 345 | mods = f"op_sel:[1,0,1,{dst_hi}]" | ||
| 346 | with self.subTest(op=op, alias_idx=alias_idx, dst_hi=dst_hi): | ||
| 347 | got = run_insn( | ||
| 348 | op, | ||
| 349 | (w[0], w[1], w[2]), | ||
| 350 | tail_mods=mods, | ||
| 351 | alias_dst=alias_idx, | ||
| 352 | ) | ||
| 353 | want = ref_word(op, w[0], w[1], w[2], (1, 0, 1), dst_hi, old=w[alias_idx]) | ||
| 354 | self.assertEqual(got, want) | ||
| 355 | |||
| 356 | |||
| 357 | class ConstantsAndSgprTests(unittest.TestCase): | ||
| 358 | """Inline constants (imm / fimm) and SGPR sources.""" | ||
| 359 | |||
| 360 | def test_int_inline_constants_and_sgpr(self): | ||
| 361 | # -16 inline is 0xFFFFFFF0 (lo = 0xFFF0 = -16 i16 / 65520 u16, hi = 0xFFFF = -1 i16 / 65535 u16). | ||
| 362 | cases = [ | ||
| 363 | ("v_min3_i16", (-16, 64, 0x00030005), (0, 1), (), "op_sel:[0,0,0,0]"), | ||
| 364 | ("v_min3_u16", (-16, 64, 0x00030005), (0, 1), (), "op_sel:[0,0,0,1]"), | ||
| 365 | ("v_max3_i16", (-1, 0x80000002, 10), (0, 2), (1,), "op_sel:[0,1,0,0]"), | ||
| 366 | ("v_max3_u16", (-16, 0x00010002, 0x80000003), (0,), (1,), "op_sel:[1,0,1,1]"), | ||
| 367 | ("v_med3_i16", (0x7FFF8000, -1, 16), (1, 2), (0,), "op_sel:[0,0,0,0]"), | ||
| 368 | ("v_med3_u16", (0x7FFF8000, -16, 64), (1, 2), (0,), "op_sel:[1,0,0,1]"), | ||
| 369 | ] | ||
| 370 | for op, words, inl, sgprs, mods in cases: | ||
| 371 | with self.subTest(op=op, words=words, mods=mods): | ||
| 372 | sel_parts = [int(x) for x in mods.split("[")[1].rstrip("]").split(",")] | ||
| 373 | norm_words = [ | ||
| 374 | (w & MASK32) if isinstance(w, int) else w | ||
| 375 | for w in words | ||
| 376 | ] | ||
| 377 | got = run_insn(op, words, inline=inl, sgpr_idx=sgprs, tail_mods=mods) | ||
| 378 | want = ref_word(op, norm_words[0], norm_words[1], norm_words[2], sel_parts[:3], sel_parts[3]) | ||
| 379 | self.assertEqual(got, want) | ||
| 380 | |||
| 381 | def test_f16_fimm_constants_and_sgpr(self): | ||
| 382 | # Inline float constants populate the low half as f16 with high half = +0.0 (docs/design.md). | ||
| 383 | # 1.0 -> 0x00003C00; -2.0 -> 0x0000C000; 0.5 -> 0x00003800 | ||
| 384 | got_min = run_insn( | ||
| 385 | "v_min3_f16", | ||
| 386 | ("1.0", 0x40003C00, "-2.0"), | ||
| 387 | inline=(0, 2), | ||
| 388 | sgpr_idx=(1,), | ||
| 389 | tail_mods="op_sel:[0,1,0,0]", | ||
| 390 | ) | ||
| 391 | self.assertEqual(got_min, merge_half(0xC000, 0)) | ||
| 392 | |||
| 393 | # Selecting the high half of an inline float constant reads +0.0. | ||
| 394 | got_hi_fimm = run_insn( | ||
| 395 | "v_max3_f16", | ||
| 396 | ("1.0", 0xBC00BC00, "-0.5"), | ||
| 397 | inline=(0, 2), | ||
| 398 | tail_mods="op_sel:[1,0,0,1]", | ||
| 399 | ) | ||
| 400 | self.assertEqual(got_hi_fimm, merge_half(0x0000, 1)) | ||
| 401 | |||
| 402 | |||
| 403 | class Float16SpecialsAndModsTests(unittest.TestCase): | ||
| 404 | """f16 NaNs, signed zeros (-0.0 < +0.0), neg/abs, omod, and clamp.""" | ||
| 405 | |||
| 406 | def test_signed_zeros_all_orders(self): | ||
| 407 | # -0.0 (0x8000) orders strictly below +0.0 (0x0000) regardless of operand position. | ||
| 408 | for triple in ( | ||
| 409 | (0x8000, 0x0000, 0x3C00), # -0, +0, +1 -> min=-0, max=+1 | ||
| 410 | (0x8000, 0x0000, 0xBC00), # -0, +0, -1 -> min=-1, max=+0 | ||
| 411 | (0x8000, 0x0000, 0x0000), # -0, +0, +0 -> min=-0, max=+0 | ||
| 412 | (0x8000, 0x8000, 0x0000), # -0, -0, +0 -> min=-0, max=+0 | ||
| 413 | ): | ||
| 414 | for perm in sorted(set(itertools.permutations(triple))): | ||
| 415 | for op in FLOAT_OPS: | ||
| 416 | with self.subTest(op=op, perm=[hex(x) for x in perm]): | ||
| 417 | got = run_insn(op, perm) | ||
| 418 | self.assertEqual(got, ref_word(op, *perm)) | ||
| 419 | |||
| 420 | def test_nan_operands(self): | ||
| 421 | for op in FLOAT_OPS: | ||
| 422 | # One quiet or signaling NaN: returns min/max of the remaining finite values. | ||
| 423 | for nan_bits in (0x7E00, 0x7C01, 0xFE01): | ||
| 424 | for perm in sorted(set(itertools.permutations((nan_bits, 0x4000, 0xBC00)))): | ||
| 425 | with self.subTest(op=op, perm=[hex(x) for x in perm]): | ||
| 426 | got = run_insn(op, perm) | ||
| 427 | self.assertEqual(got, ref_word(op, *perm)) | ||
| 428 | # Two NaNs: returns the single non-NaN operand. | ||
| 429 | for perm in sorted(set(itertools.permutations((0x7E00, 0xFE01, 0x3800)))): | ||
| 430 | with self.subTest(op=op, two_nans=[hex(x) for x in perm]): | ||
| 431 | got = run_insn(op, perm) | ||
| 432 | self.assertEqual(got, ref_word(op, *perm)) | ||
| 433 | # Three NaNs: result is NaN and unwritten high half is preserved. | ||
| 434 | got_all_nan = run_insn(op, (0x7E00, 0x7E01, 0xFE01)) | ||
| 435 | self.assertEqual(got_all_nan >> 16, OLD >> 16) | ||
| 436 | self.assertTrue(math.isnan(f16_to_float(got_all_nan & MASK16))) | ||
| 437 | |||
| 438 | def test_source_and_output_modifiers(self): | ||
| 439 | # Input neg/abs apply to the selected half; omod (mul:2/mul:4/div:2) runs before clamp [0, 1]. | ||
| 440 | w1 = float_to_f16_bits(-3.0) << 16 | float_to_f16_bits(0.5) | ||
| 441 | w2 = float_to_f16_bits(0.25) << 16 | float_to_f16_bits(-2.0) | ||
| 442 | w3 = float_to_f16_bits(-0.125) << 16 | float_to_f16_bits(4.0) | ||
| 443 | |||
| 444 | # neg(|v1.hi|) = -3.0, |v2.lo| = +2.0, v3.hi = -0.125 -> min = -3.0 -> div:2 = -1.5 | ||
| 445 | got_div2 = run_insn( | ||
| 446 | "v_min3_f16", | ||
| 447 | (w1, w2, w3), | ||
| 448 | src_mods={0: "-|{}|", 1: "|{}|"}, | ||
| 449 | tail_mods="op_sel:[1,0,1,0] div:2", | ||
| 450 | ) | ||
| 451 | self.assertEqual(got_div2, merge_half(float_to_f16_bits(-1.5), 0)) | ||
| 452 | |||
| 453 | # min(|v1.lo|=0.5, v2.hi=0.25, -v3.hi=0.125) = 0.125 -> mul:4 = 0.5 -> clamp = 0.5 (hi half) | ||
| 454 | got_mul4_clamp = run_insn( | ||
| 455 | "v_min3_f16", | ||
| 456 | (w1, w2, w3), | ||
| 457 | src_mods={0: "|{}|", 2: "-{}"}, | ||
| 458 | tail_mods="op_sel:[0,1,1,1] mul:4 clamp", | ||
| 459 | ) | ||
| 460 | self.assertEqual(got_mul4_clamp, merge_half(float_to_f16_bits(0.5), 1)) | ||
| 461 | |||
| 462 | # max(v1.lo=0.5, v2.hi=0.25, v3.lo=4.0) = 4.0 -> div:2 = 2.0 -> clamp = 1.0 | ||
| 463 | got_max_clamp = run_insn( | ||
| 464 | "v_max3_f16", | ||
| 465 | (w1, w2, w3), | ||
| 466 | tail_mods="op_sel:[0,1,0,0] div:2 clamp", | ||
| 467 | ) | ||
| 468 | self.assertEqual(got_max_clamp, merge_half(float_to_f16_bits(1.0), 0)) | ||
| 469 | |||
| 470 | # max(v1.hi=-3.0, v2.lo=-2.0, v3.hi=-0.125) = -0.125 -> mul:2 = -0.25 -> clamp = +0.0 | ||
| 471 | got_neg_clamp = run_insn( | ||
| 472 | "v_max3_f16", | ||
| 473 | (w1, w2, w3), | ||
| 474 | tail_mods="op_sel:[1,0,1,1] mul:2 clamp", | ||
| 475 | ) | ||
| 476 | self.assertEqual(got_neg_clamp, merge_half(0x0000, 1)) | ||
| 477 | |||
| 478 | |||
| 479 | class UnsupportedTests(unittest.TestCase): | ||
| 480 | """Reject unmodelled integer clamp and non-VGPR op_sel destinations.""" | ||
| 481 | |||
| 482 | def test_int_clamp_rejected(self): | ||
| 483 | for op in INT_OPS: | ||
| 484 | with self.subTest(op=op): | ||
| 485 | asm = ( | ||
| 486 | "; test_unsupported_clamp\n" | ||
| 487 | "\tv_mov_b32 v1, 1\n\tv_mov_b32 v2, 2\n\tv_mov_b32 v3, 3\n" | ||
| 488 | f"\t{op} v0, v1, v2, v3 clamp\n" | ||
| 489 | "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" | ||
| 490 | ) | ||
| 491 | with self.assertRaises(rdna2spirv.Unsupported): | ||
| 492 | translate_asm(asm) | ||
| 493 | |||
| 494 | def test_non_vgpr_opsel_dst_rejected(self): | ||
| 495 | for op in ALL_OPS: | ||
| 496 | with self.subTest(op=op): | ||
| 497 | asm = ( | ||
| 498 | "; test_unsupported_dst\n" | ||
| 499 | "\tv_mov_b32 v1, 1\n\tv_mov_b32 v2, 2\n\tv_mov_b32 v3, 3\n" | ||
| 500 | f"\t{op} s0, v1, v2, v3 op_sel:[0,0,0,1]\n" | ||
| 501 | "\texp mrt0 v1, v1, v1, v1 done vm\n\ts_endpgm\n" | ||
| 502 | ) | ||
| 503 | with self.assertRaises(rdna2spirv.Unsupported): | ||
| 504 | translate_asm(asm) | ||
| 505 | |||
| 506 | |||
| 507 | class RandomSweepTests(unittest.TestCase): | ||
| 508 | """Seeded random sweep over all eight opcodes, halves, and destination halves.""" | ||
| 509 | |||
| 510 | def test_seeded_sweep(self): | ||
| 511 | rng = random.Random(0x1633) | ||
| 512 | int_pool = [0, 1, 0x7FFE, 0x7FFF, 0x8000, 0x8001, 0xFFFE, 0xFFFF] | ||
| 513 | for op in INT_OPS: | ||
| 514 | for _ in range(18): | ||
| 515 | w1, w2, w3 = ( | ||
| 516 | ((rng.choice(int_pool) if rng.random() < 0.4 else rng.randrange(0x10000)) << 16) | ||
| 517 | | (rng.choice(int_pool) if rng.random() < 0.4 else rng.randrange(0x10000)) | ||
| 518 | for _ in range(3) | ||
| 519 | ) | ||
| 520 | sel = tuple(rng.randrange(2) for _ in range(3)) | ||
| 521 | dst_hi = rng.randrange(2) | ||
| 522 | mods = f"op_sel:[{sel[0]},{sel[1]},{sel[2]},{dst_hi}]" | ||
| 523 | with self.subTest(op=op, w=(hex(w1), hex(w2), hex(w3)), mods=mods): | ||
| 524 | self.assertEqual(run_insn(op, (w1, w2, w3), tail_mods=mods), ref_word(op, w1, w2, w3, sel, dst_hi)) | ||
| 525 | |||
| 526 | for op in FLOAT_OPS: | ||
| 527 | for _ in range(18): | ||
| 528 | w1, w2, w3 = ((rng.choice(F16_VALS) << 16) | rng.choice(F16_VALS) for _ in range(3)) | ||
| 529 | sel = tuple(rng.randrange(2) for _ in range(3)) | ||
| 530 | dst_hi = rng.randrange(2) | ||
| 531 | mods = f"op_sel:[{sel[0]},{sel[1]},{sel[2]},{dst_hi}]" | ||
| 532 | with self.subTest(op=op, w=(hex(w1), hex(w2), hex(w3)), mods=mods): | ||
| 533 | self.assertEqual(run_insn(op, (w1, w2, w3), tail_mods=mods), ref_word(op, w1, w2, w3, sel, dst_hi)) | ||
| 534 | |||
| 535 | |||
| 536 | if __name__ == "__main__": | ||
| 537 | unittest.main() | ||
diff --git a/tests/semantic/test_alu_sincos.py b/tests/semantic/test_alu_sincos.py new file mode 100644 index 000000000..78d864bd3 --- /dev/null +++ b/tests/semantic/test_alu_sincos.py | |||
| @@ -0,0 +1,183 @@ | |||
| 1 | """Semantic interpreter tests for RDNA2 v_sin_f32 / v_cos_f32 / v_sin_f16 / v_cos_f16 (SHADER-88). | ||
| 2 | |||
| 3 | The operand is an angle in TURNS (valid over +-256 turns). Multiplying by 2*pi before reducing rounds the fractional | ||
| 4 | turn away in binary32 (up to ~1e-4 rad near +-255 turns), so the translator reduces in turns first. Each case | ||
| 5 | translates a synthetic pixel shader with tools/rdna2spirv.py, runs it in tests/semantic/spirv_mini_interp.py and | ||
| 6 | compares the exported value with math.sin / math.cos(2*pi*x) computed in double (a reference, not a model of the | ||
| 7 | translator). Tolerances are absolute and explicit: 1e-6 for f32 (a few ulp of a value near 1), 1e-3 for f16 (one | ||
| 8 | f16 ulp near 1 is ~4.9e-4 and the result is rounded to f16). | ||
| 9 | """ | ||
| 10 | import math | ||
| 11 | import os | ||
| 12 | import struct | ||
| 13 | import sys | ||
| 14 | import tempfile | ||
| 15 | import unittest | ||
| 16 | import warnings | ||
| 17 | |||
| 18 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 19 | ROOT = os.path.dirname(os.path.dirname(HERE)) | ||
| 20 | TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") | ||
| 21 | |||
| 22 | sys.dont_write_bytecode = True | ||
| 23 | sys.path.insert(0, TOOLS_DIR) | ||
| 24 | sys.path.insert(0, HERE) | ||
| 25 | |||
| 26 | import rdna2spirv # noqa: E402 | ||
| 27 | import spirv_mini_interp as si # noqa: E402 | ||
| 28 | |||
| 29 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 30 | OLD = 0xAAAA5555 | ||
| 31 | TOL32 = 1e-6 | ||
| 32 | TOL16 = 1e-3 | ||
| 33 | INPUTS = [0.25, 0.5, 1.0, 100.3, 254.25, 254.51, 255.9, 0.1, 0.0, -0.0, -0.25, -100.3, -254.51, -255.5] | ||
| 34 | |||
| 35 | _TMP_DIR = None | ||
| 36 | _SRC_PATH = None | ||
| 37 | |||
| 38 | |||
| 39 | def f2u(x): | ||
| 40 | return struct.unpack("<I", struct.pack("<f", x))[0] | ||
| 41 | |||
| 42 | |||
| 43 | def u2f(u): | ||
| 44 | return struct.unpack("<f", struct.pack("<I", u & 0xFFFFFFFF))[0] | ||
| 45 | |||
| 46 | |||
| 47 | def h2f(h): | ||
| 48 | return struct.unpack("<e", struct.pack("<H", h & 0xFFFF))[0] | ||
| 49 | |||
| 50 | |||
| 51 | def f2h(x): | ||
| 52 | return struct.unpack("<H", struct.pack("<e", x))[0] | ||
| 53 | |||
| 54 | |||
| 55 | def ref(op, x): | ||
| 56 | return math.sin(2 * math.pi * x) if "sin" in op else math.cos(2 * math.pi * x) | ||
| 57 | |||
| 58 | |||
| 59 | def setUpModule(): | ||
| 60 | global _TMP_DIR, _SRC_PATH | ||
| 61 | _TMP_DIR = tempfile.TemporaryDirectory() | ||
| 62 | disasm_dir = os.path.join(_TMP_DIR.name, "disasm") | ||
| 63 | os.mkdir(disasm_dir) | ||
| 64 | _SRC_PATH = os.path.join(disasm_dir, "ps_sincos.s") | ||
| 65 | with open(os.path.join(_TMP_DIR.name, "ps_sincos.dxbc"), "wb") as f: | ||
| 66 | f.write(STUB_DXBC) | ||
| 67 | |||
| 68 | |||
| 69 | def tearDownModule(): | ||
| 70 | global _TMP_DIR | ||
| 71 | if _TMP_DIR is not None: | ||
| 72 | _TMP_DIR.cleanup() | ||
| 73 | _TMP_DIR = None | ||
| 74 | |||
| 75 | |||
| 76 | def run(line, v1, old=0): | ||
| 77 | if _TMP_DIR is None: | ||
| 78 | setUpModule() | ||
| 79 | lines = [f"v_mov_b32 v1, {v1:#x}", f"v_mov_b32 v0, {old:#x}", line] | ||
| 80 | asm = "; test_sincos\n" + "".join(f"\t{ln}\n" for ln in lines) + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" | ||
| 81 | with open(_SRC_PATH, "w", encoding="utf-8") as f: | ||
| 82 | f.write(asm) | ||
| 83 | with warnings.catch_warnings(): | ||
| 84 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 85 | spv = rdna2spirv.translate(_SRC_PATH) | ||
| 86 | return si.run_fragment(spv)["%out_mrt0"][0] | ||
| 87 | |||
| 88 | |||
| 89 | class SinCosF32Tests(unittest.TestCase): | ||
| 90 | def test_values_against_double_reference(self): | ||
| 91 | for op in ("v_sin_f32", "v_cos_f32"): | ||
| 92 | for x in INPUTS: | ||
| 93 | x32 = u2f(f2u(x)) # the binary32 operand the shader sees | ||
| 94 | with self.subTest(op=op, x=x): | ||
| 95 | got = u2f(run(f"{op}_e32 v0, v1", f2u(x))) | ||
| 96 | self.assertLessEqual(abs(got - ref(op, x32)), TOL32) | ||
| 97 | |||
| 98 | def test_exact_quarter_turns(self): | ||
| 99 | self.assertLessEqual(abs(u2f(run("v_sin_f32_e32 v0, v1", f2u(0.25))) - 1.0), TOL32) | ||
| 100 | self.assertLessEqual(abs(u2f(run("v_cos_f32_e32 v0, v1", f2u(0.5))) + 1.0), TOL32) | ||
| 101 | self.assertLessEqual(abs(u2f(run("v_sin_f32_e32 v0, v1", f2u(254.25))) - 1.0), TOL32) | ||
| 102 | self.assertLessEqual(abs(u2f(run("v_cos_f32_e32 v0, v1", f2u(-254.5))) + 1.0), TOL32) | ||
| 103 | |||
| 104 | def test_worst_case_of_the_issue(self): | ||
| 105 | # x = 254.51: x * 2*pi first was off by 1.05e-4; reducing in turns is within 1e-6. | ||
| 106 | x32 = u2f(f2u(254.51)) | ||
| 107 | got = u2f(run("v_sin_f32_e32 v0, v1", f2u(254.51))) | ||
| 108 | self.assertLessEqual(abs(got - math.sin(2 * math.pi * x32)), TOL32) | ||
| 109 | |||
| 110 | def test_signed_zero_and_special_values(self): | ||
| 111 | self.assertEqual(run("v_sin_f32_e32 v0, v1", 0x00000000), 0x00000000) | ||
| 112 | self.assertEqual(run("v_sin_f32_e32 v0, v1", 0x80000000), 0x80000000) # sin(-0) = -0 | ||
| 113 | self.assertEqual(u2f(run("v_cos_f32_e32 v0, v1", 0x80000000)), 1.0) | ||
| 114 | for bits in (0x7F800000, 0xFF800000, 0x7FC00000): | ||
| 115 | for op in ("v_sin_f32", "v_cos_f32"): | ||
| 116 | with self.subTest(op=op, x=hex(bits)): | ||
| 117 | self.assertTrue(math.isnan(u2f(run(f"{op}_e32 v0, v1", bits)))) | ||
| 118 | |||
| 119 | def test_modifiers(self): | ||
| 120 | got = u2f(run("v_sin_f32_e64 v0, -v1", f2u(100.3))) # neg: sin(-x) | ||
| 121 | self.assertLessEqual(abs(got - math.sin(-2 * math.pi * u2f(f2u(100.3)))), TOL32) | ||
| 122 | got = u2f(run("v_cos_f32_e64 v0, |v1|", f2u(-254.51))) # abs | ||
| 123 | self.assertLessEqual(abs(got - math.cos(2 * math.pi * u2f(f2u(254.51)))), TOL32) | ||
| 124 | got = u2f(run("v_sin_f32_e64 v0, v1 clamp", f2u(-0.25))) # clamp: sin = -1 -> 0 | ||
| 125 | self.assertEqual(got, 0.0) | ||
| 126 | got = u2f(run("v_sin_f32_e64 v0, v1 mul:2", f2u(100.3))) # omod | ||
| 127 | self.assertLessEqual(abs(got - 2 * math.sin(2 * math.pi * u2f(f2u(100.3)))), 2 * TOL32) | ||
| 128 | |||
| 129 | def test_whole_turns_give_plus_zero_for_either_sign(self): | ||
| 130 | """Measured on an RX 6800 (gfx1030, #616): v_sin_f32 of a whole number of turns, negative or positive, is | ||
| 131 | +0 (only sin(-0) is -0) and v_cos_f32 of it is 1.""" | ||
| 132 | for x in (-1.0, -2.0, -100.0, 1.0, 2.0, 100.0): | ||
| 133 | with self.subTest(x=x): | ||
| 134 | self.assertEqual(run("v_sin_f32_e32 v0, v1", f2u(x)), 0x00000000) | ||
| 135 | self.assertEqual(run("v_cos_f32_e32 v0, v1", f2u(x)), f2u(1.0)) | ||
| 136 | |||
| 137 | def test_tiny_arguments_keep_their_sign_and_size(self): | ||
| 138 | """A reducer built on floor() would turn x = -2**-26 into 1.0 - 2**-26 = 1.0 in binary32 and return +0; | ||
| 139 | x - RoundEven(x) keeps the small centred argument. The result is below TOL32 either way, so the check is on | ||
| 140 | the sign and on a much tighter absolute tolerance (suggested by bobcatchris on #616).""" | ||
| 141 | for x in (-2.0 ** -26, 2.0 ** -26, -2.0 ** -20, 2.0 ** -20): | ||
| 142 | with self.subTest(x=x): | ||
| 143 | got = u2f(run("v_sin_f32_e32 v0, v1", f2u(x))) | ||
| 144 | self.assertEqual(math.copysign(1.0, got), math.copysign(1.0, x)) | ||
| 145 | self.assertNotEqual(got, 0.0) | ||
| 146 | self.assertLessEqual(abs(got - math.sin(2 * math.pi * x)), 2e-9) | ||
| 147 | self.assertLessEqual(abs(u2f(run("v_cos_f32_e32 v0, v1", f2u(x))) - 1.0), 1e-6) | ||
| 148 | |||
| 149 | |||
| 150 | class SinCosF16Tests(unittest.TestCase): | ||
| 151 | def test_values_keep_the_high_half(self): | ||
| 152 | for op in ("v_sin_f16", "v_cos_f16"): | ||
| 153 | for x in (0.25, 0.5, 100.25, 254.5, -254.25, 0.3): | ||
| 154 | h = f2h(x) | ||
| 155 | with self.subTest(op=op, x=x): | ||
| 156 | got = run(f"{op}_e32 v0, v1", 0x12340000 | h, OLD) | ||
| 157 | self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000) | ||
| 158 | self.assertLessEqual(abs(h2f(got) - ref(op, h2f(h))), TOL16) | ||
| 159 | |||
| 160 | def test_negative_zero_keeps_its_sign(self): | ||
| 161 | """f16 -0.0 is 0x8000: sin(-0) stays -0 (the sign bit survives the turns reduction) and cos(-0) is 1; | ||
| 162 | the high half of the destination is kept in both.""" | ||
| 163 | got = run("v_sin_f16_e32 v0, v1", 0x12340000 | 0x8000, OLD) | ||
| 164 | self.assertEqual(got, (OLD & 0xFFFF0000) | 0x8000) | ||
| 165 | got = run("v_cos_f16_e32 v0, v1", 0x12340000 | 0x8000, OLD) | ||
| 166 | self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000) | ||
| 167 | self.assertEqual(h2f(got), 1.0) | ||
| 168 | |||
| 169 | def test_large_angle_near_the_256_turn_edge(self): | ||
| 170 | """Where x * 2*pi first would lose the fractional turn: 254.25 and 255.0 are exact in f16, and the | ||
| 171 | reference is computed in double.""" | ||
| 172 | for op, x in (("v_sin_f16", 254.25), ("v_sin_f16", -254.25), ("v_cos_f16", 254.5), ("v_cos_f16", 255.0), | ||
| 173 | ("v_sin_f16", 255.5), ("v_cos_f16", -255.5)): | ||
| 174 | h = f2h(x) | ||
| 175 | self.assertEqual(h2f(h), x) # the input is exactly representable | ||
| 176 | with self.subTest(op=op, x=x): | ||
| 177 | got = run(f"{op}_e32 v0, v1", 0x12340000 | h, OLD) | ||
| 178 | self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000) | ||
| 179 | self.assertLessEqual(abs(h2f(got) - ref(op, x)), TOL16) | ||
| 180 | |||
| 181 | |||
| 182 | if __name__ == "__main__": | ||
| 183 | unittest.main() | ||
diff --git a/tests/semantic/test_alu_swaprel.py b/tests/semantic/test_alu_swaprel.py new file mode 100644 index 000000000..cf89d4c27 --- /dev/null +++ b/tests/semantic/test_alu_swaprel.py | |||
| @@ -0,0 +1,92 @@ | |||
| 1 | """Value tests for v_swaprel_b32 (GFX10 VOP1 opcode 104), run through spirv_mini_interp. | ||
| 2 | |||
| 3 | tmp = VGPR[D + M0[25:16]]; VGPR[D + M0[25:16]] = VGPR[S0 + M0[9:0]]; VGPR[S0 + M0[9:0]] = tmp | ||
| 4 | |||
| 5 | The same two M0 fields as v_movrelsd_2_b32; the other M0 bits are ignored. Each case loads a distinct sentinel into | ||
| 6 | v1..v30 (0x40000000 + n, normal floats, so the export round trip can't change them), sets M0, runs one v_swaprel_b32 | ||
| 7 | and exports four registers through exp mrt0. Expected words come from a plain-Python register-file model. | ||
| 8 | Standard library only; no GPU, no game files. | ||
| 9 | """ | ||
| 10 | import os | ||
| 11 | import struct | ||
| 12 | import sys | ||
| 13 | import tempfile | ||
| 14 | import unittest | ||
| 15 | import warnings | ||
| 16 | |||
| 17 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 18 | ROOT = os.path.dirname(os.path.dirname(HERE)) | ||
| 19 | sys.dont_write_bytecode = True | ||
| 20 | sys.path.insert(0, os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools")) | ||
| 21 | sys.path.insert(0, HERE) | ||
| 22 | |||
| 23 | import rdna2spirv # noqa: E402 | ||
| 24 | import spirv_mini_interp as si # noqa: E402 | ||
| 25 | |||
| 26 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 27 | |||
| 28 | |||
| 29 | def sentinel(n): | ||
| 30 | return 0x40000000 + n | ||
| 31 | |||
| 32 | |||
| 33 | def model(d, s0, m0): | ||
| 34 | regs = {n: sentinel(n) for n in range(1, 31)} | ||
| 35 | a, b = d + ((m0 >> 16) & 0x3FF), s0 + (m0 & 0x3FF) | ||
| 36 | regs[a], regs[b] = regs[b], regs[a] | ||
| 37 | return regs | ||
| 38 | |||
| 39 | |||
| 40 | def run(d, s0, m0, export, extra=()): | ||
| 41 | with tempfile.TemporaryDirectory() as tmp: | ||
| 42 | os.mkdir(os.path.join(tmp, "disasm")) | ||
| 43 | with open(os.path.join(tmp, "ps_swaprel.dxbc"), "wb") as f: | ||
| 44 | f.write(STUB_DXBC) | ||
| 45 | lines = [f"v_mov_b32 v{n}, {sentinel(n):#x}" for n in range(1, 31)] + [f"s_mov_b32 m0, {m0:#x}", *extra, | ||
| 46 | f"v_swaprel_b32 v{d}, v{s0}", f"exp mrt0 {', '.join(f'v{r}' for r in export)} done vm", "s_endpgm"] | ||
| 47 | src = os.path.join(tmp, "disasm", "ps_swaprel.s") | ||
| 48 | with open(src, "w", encoding="utf-8") as f: | ||
| 49 | f.write("; ps_swaprel\n" + "".join(f"\t{ln}\n" for ln in lines)) | ||
| 50 | with warnings.catch_warnings(): | ||
| 51 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 52 | spv = rdna2spirv.translate(src) | ||
| 53 | return list(si.run_fragment(spv)["%out_mrt0"]) | ||
| 54 | |||
| 55 | |||
| 56 | class SwaprelTests(unittest.TestCase): | ||
| 57 | def check(self, d, s0, m0): | ||
| 58 | regs = model(d, s0, m0) | ||
| 59 | a, b = d + ((m0 >> 16) & 0x3FF), s0 + (m0 & 0x3FF) | ||
| 60 | export = [a, b, a + 1, b - 1 if b > 1 else b + 1] | ||
| 61 | self.assertEqual(run(d, s0, m0, export), [regs[r] for r in export]) | ||
| 62 | |||
| 63 | def test_fields(self): | ||
| 64 | for d, s0, m0 in ((1, 2, 0), (3, 10, 0x0005_0002), (20, 1, 0x0002_0007), (5, 5, 0x0001_0000)): | ||
| 65 | with self.subTest(d=d, s0=s0, m0=hex(m0)): | ||
| 66 | self.check(d, s0, m0) | ||
| 67 | |||
| 68 | def test_other_m0_bits_are_ignored(self): | ||
| 69 | # bits 15:10 and 31:26 set: same result as M0 = (3 << 16) | 4 | ||
| 70 | self.check(2, 6, 0xFC03_FC04) | ||
| 71 | |||
| 72 | def test_both_sides_name_one_register(self): | ||
| 73 | # D + M0[25:16] == S0 + M0[9:0]: the register is swapped with itself and keeps its value | ||
| 74 | self.assertEqual(run(4, 6, 0x0003_0001, [7, 6, 8, 1]), [sentinel(7), sentinel(6), sentinel(8), sentinel(1)]) | ||
| 75 | |||
| 76 | def test_model(self): | ||
| 77 | regs = model(1, 2, 0x0002_0005) # D slot 1 + 2 = 3, S0 slot 2 + 5 = 7 | ||
| 78 | self.assertEqual((regs[3], regs[7], regs[4]), (sentinel(7), sentinel(3), sentinel(4))) | ||
| 79 | |||
| 80 | def test_non_vgpr_operand_rejected(self): | ||
| 81 | with tempfile.TemporaryDirectory() as tmp: | ||
| 82 | os.mkdir(os.path.join(tmp, "disasm")) | ||
| 83 | with open(os.path.join(tmp, "ps_swaprel.dxbc"), "wb") as f: | ||
| 84 | f.write(STUB_DXBC) | ||
| 85 | src = os.path.join(tmp, "disasm", "ps_swaprel.s") | ||
| 86 | with open(src, "w", encoding="utf-8") as f: | ||
| 87 | f.write("; ps_swaprel\n\tv_swaprel_b32 v1, s2\n\texp mrt0 v1, v1, v1, v1 done vm\n\ts_endpgm\n") | ||
| 88 | with self.assertRaises(rdna2spirv.Unsupported): | ||
| 89 | rdna2spirv.translate(src) | ||
| 90 | |||
| 91 | if __name__ == "__main__": | ||
| 92 | unittest.main() | ||
diff --git a/tests/semantic/test_buffer_oob_select.py b/tests/semantic/test_buffer_oob_select.py index 50170c924..a936452b4 100644 --- a/tests/semantic/test_buffer_oob_select.py +++ b/tests/semantic/test_buffer_oob_select.py | |||
| @@ -222,6 +222,59 @@ class OobSelect(unittest.TestCase): | |||
| 222 | want = {BASE + addr + 4 * k: 0x11111111 * (k + 1) for k in range(4)} if ok else {} | 222 | want = {BASE + addr + 4 * k: 0x11111111 * (k + 1) for k in range(4)} if ok else {} |
| 223 | self.assertEqual(dict(memory), want, ("store", mode, stride, nr, idx, off, runtime)) | 223 | self.assertEqual(dict(memory), want, ("store", mode, stride, nr, idx, off, runtime)) |
| 224 | 224 | ||
| 225 | def test_loads_literal_v_sharp_from_s_mov_b64(self): | ||
| 226 | # s_mov_b64 s[6:7], imm folds word3 (OOB_SELECT mode) without run-time extraction. | ||
| 227 | for mode in range(4): | ||
| 228 | with self.subTest(mode=mode): | ||
| 229 | w3 = 0x01000FAC | (mode << 28) | ||
| 230 | val64 = (w3 << 32) | 0x10 | ||
| 231 | lines = [f"s_mov_b64 s[4:5], {BASE:#x}", f"s_mov_b64 s[6:7], {val64:#x}", | ||
| 232 | "buffer_load_dword v2, off, s[4:7], 0", "s_waitcnt vmcnt(0)", | ||
| 233 | "buffer_store_dword v2, off, s[0:3], 0"] | ||
| 234 | spv = self.translate(lines) | ||
| 235 | self.assertEqual(len(MODE_EXTRACT.findall(spv)), 1, f"mode {mode} did not fold from s_mov_b64") | ||
| 225 | 236 | ||
| 237 | def test_loads_literal_v_sharp_from_s_movk_i32(self): | ||
| 238 | # s_movk_i32 s7, imm sets word3 for modes where word3 fits in 16 bits sign-extended. | ||
| 239 | lines = [f"s_mov_b32 s4, {BASE:#x}", "s_mov_b32 s5, 0", "s_mov_b32 s6, 16", | ||
| 240 | "s_movk_i32 s7, 0x3000", | ||
| 241 | "buffer_load_dword v2, off, s[4:7], 0", "s_waitcnt vmcnt(0)", | ||
| 242 | "buffer_store_dword v2, off, s[0:3], 0"] | ||
| 243 | spv = self.translate(lines) | ||
| 244 | self.assertEqual(len(MODE_EXTRACT.findall(spv)), 1, "s_movk_i32 did not fold into literal V#") | ||
| 245 | |||
| 246 | def test_loads_literal_v_sharp_from_sgpr_copy(self): | ||
| 247 | # Copy propagation: s_mov_b32 from a constant SGPR preserves sgpr_imm. | ||
| 248 | w3 = 0x31000FAC | ||
| 249 | lines = [f"s_mov_b32 s8, {w3:#x}", "s_mov_b32 s7, s8", | ||
| 250 | f"s_mov_b32 s4, {BASE:#x}", "s_mov_b32 s5, 0", "s_mov_b32 s6, 16", | ||
| 251 | "buffer_load_dword v2, off, s[4:7], 0", "s_waitcnt vmcnt(0)", | ||
| 252 | "buffer_store_dword v2, off, s[0:3], 0"] | ||
| 253 | spv = self.translate(lines) | ||
| 254 | self.assertEqual(len(MODE_EXTRACT.findall(spv)), 1, "s_mov_b32 copy did not fold into literal V#") | ||
| 255 | |||
| 256 | def test_loads_literal_v_sharp_from_s_mov_b64_copy(self): | ||
| 257 | # Copy propagation: s_mov_b64 64-bit pair copy preserves sgpr_imm. | ||
| 258 | w3 = 0x31000FAC | ||
| 259 | val64 = (w3 << 32) | 16 | ||
| 260 | lines = [f"s_mov_b64 s[8:9], {val64:#x}", "s_mov_b64 s[6:7], s[8:9]", | ||
| 261 | f"s_mov_b32 s4, {BASE:#x}", "s_mov_b32 s5, 0", | ||
| 262 | "buffer_load_dword v2, off, s[4:7], 0", "s_waitcnt vmcnt(0)", | ||
| 263 | "buffer_store_dword v2, off, s[0:3], 0"] | ||
| 264 | spv = self.translate(lines) | ||
| 265 | self.assertEqual(len(MODE_EXTRACT.findall(spv)), 1, "s_mov_b64 pair copy did not fold into literal V#") | ||
| 266 | |||
| 267 | def test_loads_literal_v_sharp_from_s_mov_b64_overlapping_copy(self): | ||
| 268 | # Overlapping 64-bit copy s_mov_b64 s[6:7], s[5:6] where d == s + 1: | ||
| 269 | # Both source registers must be evaluated before writing destination, | ||
| 270 | # so s7 gets the old s6 literal rather than the newly written s6 (s5). | ||
| 271 | w3 = 0x31000FAC | ||
| 272 | lines = [f"s_mov_b32 s4, {BASE:#x}", "s_mov_b32 s5, 16", | ||
| 273 | f"s_mov_b32 s6, {w3:#x}", | ||
| 274 | "s_mov_b64 s[6:7], s[5:6]", | ||
| 275 | "buffer_load_dword v2, off, s[4:7], 0", "s_waitcnt vmcnt(0)", | ||
| 276 | "buffer_store_dword v2, off, s[0:3], 0"] | ||
| 277 | spv = self.translate(lines) | ||
| 278 | self.assertEqual(len(MODE_EXTRACT.findall(spv)), 1, "s_mov_b64 overlapping copy did not fold into literal V#") | ||
| 226 | if __name__ == "__main__": | 279 | if __name__ == "__main__": |
| 227 | unittest.main() | 280 | unittest.main() |
diff --git a/tests/semantic/test_f16_interp_fallback.py b/tests/semantic/test_f16_interp_fallback.py index 5565252ea..3eb9c8b5d 100644 --- a/tests/semantic/test_f16_interp_fallback.py +++ b/tests/semantic/test_f16_interp_fallback.py | |||
| @@ -3,8 +3,9 @@ | |||
| 3 | By default a location any *_f16 interp reads is a PerVertexKHR vec4[3] of the producer's raw words, decoded and | 3 | By default a location any *_f16 interp reads is a PerVertexKHR vec4[3] of the producer's raw words, decoded and |
| 4 | weighted in the PS (test_interp_f16_high.py). MoltenVK can't compile that decoration to MSL ("PerVertexKHR decoration | 4 | weighted in the PS (test_interp_f16_high.py). MoltenVK can't compile that decoration to MSL ("PerVertexKHR decoration |
| 5 | is not supported in MSL"), so with the flag the producer (VS `exp paramN`, mesh params) also exports each channel's two | 5 | is not supported in MSL"), so with the flag the producer (VS `exp paramN`, mesh params) also exports each channel's two |
| 6 | f16 halves decoded to f32, low halves at location 29 - 2N and high halves at 30 - 2N, and the PS reads them as ordinary | 6 | f16 halves decoded to f32, low halves at location 28 - 2N and high halves at 29 - 2N, and the PS reads them as ordinary |
| 7 | smooth inputs. Interpolating the decoded halves is the same P0 + i(P1 - P0) + j(P2 - P0). Here: | 7 | smooth inputs (the top is 29: MoltenVK's maxVertexOutputComponents, 124, counts gl_Position; SHADER-291). |
| 8 | Interpolating the decoded halves is the same P0 + i(P1 - P0) + j(P2 - P0). Here: | ||
| 8 | * the PS has no PerVertexKHR, no barycentric builtin, and reads 1.75 / 9.0 from the decoded-half inputs (the | 9 | * the PS has no PerVertexKHR, no barycentric builtin, and reads 1.75 / 9.0 from the decoded-half inputs (the |
| 9 | per-vertex values of test_interp_f16_high.py, interpolated as Vulkan would), the f32 control and the flat raw read | 10 | per-vertex values of test_interp_f16_high.py, interpolated as Vulkan would), the f32 control and the flat raw read |
| 10 | unchanged; | 11 | unchanged; |
| @@ -15,6 +16,7 @@ smooth inputs. Interpolating the decoded halves is the same P0 + i(P1 - P0) + j( | |||
| 15 | The GPU check is runtime/test/shaders/ps_interp_f16_high drawn with vs_f16_pack, which run_gpu_tests.py translates | 16 | The GPU check is runtime/test/shaders/ps_interp_f16_high drawn with vs_f16_pack, which run_gpu_tests.py translates |
| 16 | with the flag where tools/vk_subgroup_info.py reports per_vertex_inputs false (MoltenVK). | 17 | with the flag where tools/vk_subgroup_info.py reports per_vertex_inputs false (MoltenVK). |
| 17 | """ | 18 | """ |
| 19 | import re | ||
| 18 | import struct | 20 | import struct |
| 19 | import unittest | 21 | import unittest |
| 20 | 22 | ||
| @@ -82,11 +84,11 @@ class FallbackPixelShader(unittest.TestCase): | |||
| 82 | self.assertNotIn("fragmentShaderBarycentric", self.meta["features"]) | 84 | self.assertNotIn("fragmentShaderBarycentric", self.meta["features"]) |
| 83 | 85 | ||
| 84 | def test_decoded_half_inputs(self): | 86 | def test_decoded_half_inputs(self): |
| 85 | self.assertIn("OpDecorate %in_f16h0_0 Location 29", self.spv) | 87 | self.assertIn("OpDecorate %in_f16h0_0 Location 28", self.spv) |
| 86 | self.assertIn("OpDecorate %in_f16h0_1 Location 30", self.spv) | 88 | self.assertIn("OpDecorate %in_f16h0_1 Location 29", self.spv) |
| 87 | self.assertNotIn("%in_f16h0_0 Flat", self.spv) | 89 | self.assertNotIn("%in_f16h0_0 Flat", self.spv) |
| 88 | self.assertEqual(self.meta["f16_halves"], {"0": [29, 30]}) | 90 | self.assertEqual(self.meta["f16_halves"], {"0": [28, 29]}) |
| 89 | self.assertEqual(self.meta["inputs"], [0, 1, 29, 30]) | 91 | self.assertEqual(self.meta["inputs"], [0, 1, 28, 29]) |
| 90 | 92 | ||
| 91 | def test_values(self): | 93 | def test_values(self): |
| 92 | words = support.mrt0_words(self.spv, inputs=self.inputs()) | 94 | words = support.mrt0_words(self.spv, inputs=self.inputs()) |
| @@ -102,9 +104,9 @@ class FallbackPixelShader(unittest.TestCase): | |||
| 102 | self.assertEqual([f"{w & 0xFFFF:#06x}" for w in words[:2]], ["0x3f00", "0x3f00"]) | 104 | self.assertEqual([f"{w & 0xFFFF:#06x}" for w in words[:2]], ["0x3f00", "0x3f00"]) |
| 103 | 105 | ||
| 104 | def test_location_clash_is_rejected(self): | 106 | def test_location_clash_is_rejected(self): |
| 105 | """attr29 read as f32 sits where attr0's low halves go: refuse instead of reading the wrong data.""" | 107 | """attr28 read as f32 sits where attr0's low halves go: refuse instead of reading the wrong data.""" |
| 106 | clash = ["v_interp_p1ll_f16 v2, v0, attr0.x", "v_interp_p2_f16 v2, v1, attr0.x, v2", | 108 | clash = ["v_interp_p1ll_f16 v2, v0, attr0.x", "v_interp_p2_f16 v2, v1, attr0.x, v2", |
| 107 | "v_interp_p1_f32_e32 v3, v0, attr29.x", "v_interp_p2_f32_e32 v3, v1, attr29.x", | 109 | "v_interp_p1_f32_e32 v3, v0, attr28.x", "v_interp_p2_f32_e32 v3, v1, attr28.x", |
| 108 | "exp mrt0 v2, v3, v3, v3 done vm", "s_endpgm"] | 110 | "exp mrt0 v2, v3, v3, v3 done vm", "s_endpgm"] |
| 109 | with self.assertRaises(rdna2spirv.Unsupported): | 111 | with self.assertRaises(rdna2spirv.Unsupported): |
| 110 | translate("ps_f16_clash", clash) | 112 | translate("ps_f16_clash", clash) |
| @@ -119,10 +121,10 @@ class FallbackPixelShader(unittest.TestCase): | |||
| 119 | class FallbackVertexShader(unittest.TestCase): | 121 | class FallbackVertexShader(unittest.TestCase): |
| 120 | def test_exports_decoded_halves(self): | 122 | def test_exports_decoded_halves(self): |
| 121 | spv, meta = translate("vs_f16_fallback", VS.splitlines()) | 123 | spv, meta = translate("vs_f16_fallback", VS.splitlines()) |
| 122 | for n, lo, hi in ((0, 29, 30), (1, 27, 28)): | 124 | for n, lo, hi in ((0, 28, 29), (1, 26, 27)): |
| 123 | self.assertIn(f"OpDecorate %out_f16h{n}_0 Location {lo}", spv) | 125 | self.assertIn(f"OpDecorate %out_f16h{n}_0 Location {lo}", spv) |
| 124 | self.assertIn(f"OpDecorate %out_f16h{n}_1 Location {hi}", spv) | 126 | self.assertIn(f"OpDecorate %out_f16h{n}_1 Location {hi}", spv) |
| 125 | self.assertEqual(meta["f16_halves"], {"0": [29, 30], "1": [27, 28]}) | 127 | self.assertEqual(meta["f16_halves"], {"0": [28, 29], "1": [26, 27]}) |
| 126 | for vid in range(3): | 128 | for vid in range(3): |
| 127 | out = run_fragment(spv, inputs={"%vertex_index": vid, "%instance_index": 0}) | 129 | out = run_fragment(spv, inputs={"%vertex_index": vid, "%instance_index": 0}) |
| 128 | u, v = float((vid << 1) & 2), float(vid & 2) | 130 | u, v = float((vid << 1) & 2), float(vid & 2) |
| @@ -137,13 +139,31 @@ class FallbackVertexShader(unittest.TestCase): | |||
| 137 | self.assertEqual(list(out["%out_param1"])[:2], [support_bits(u), support_bits(v)]) | 139 | self.assertEqual(list(out["%out_param1"])[:2], [support_bits(u), support_bits(v)]) |
| 138 | 140 | ||
| 139 | def test_halves_never_overlap_the_shaders_params(self): | 141 | def test_halves_never_overlap_the_shaders_params(self): |
| 140 | """param29 occupies location 29, so param0's halves (29, 30) are left out; nothing else moves.""" | 142 | """param28 occupies location 28, so param0's halves (28, 29) are left out; nothing else moves.""" |
| 141 | spv, meta = translate("vs_f16_far", ["v_mov_b32_e32 v1, 1.0", "exp pos0 v1, v1, v1, v1 done", | 143 | spv, meta = translate("vs_f16_far", ["v_mov_b32_e32 v1, 1.0", "exp pos0 v1, v1, v1, v1 done", |
| 142 | "exp param0 v1, v1, v1, v1", "exp param29 v1, v1, v1, v1", | 144 | "exp param0 v1, v1, v1, v1", "exp param28 v1, v1, v1, v1", |
| 143 | "s_endpgm"]) | 145 | "s_endpgm"]) |
| 144 | self.assertNotIn("%out_f16h0", spv) | 146 | self.assertNotIn("%out_f16h0", spv) |
| 145 | self.assertNotIn("f16_halves", meta) | 147 | self.assertNotIn("f16_halves", meta) |
| 146 | self.assertIn("OpDecorate %out_param29 Location 29", spv) | 148 | self.assertIn("OpDecorate %out_param28 Location 28", spv) |
| 149 | |||
| 150 | def test_halves_fit_just_above_the_shaders_params(self): | ||
| 151 | """param27 ends at location 27, so param0's halves still fit at 28 and 29.""" | ||
| 152 | spv, meta = translate("vs_f16_near", ["v_mov_b32_e32 v1, 1.0", "exp pos0 v1, v1, v1, v1 done", | ||
| 153 | "exp param0 v1, v1, v1, v1", "exp param27 v1, v1, v1, v1", | ||
| 154 | "s_endpgm"]) | ||
| 155 | self.assertEqual(meta["f16_halves"], {"0": [28, 29]}) | ||
| 156 | self.assertIn("OpDecorate %out_param27 Location 27", spv) | ||
| 157 | |||
| 158 | def test_top_half_fits_moltenvk_output_budget(self): | ||
| 159 | """SHADER-291: MoltenVK reports maxVertexOutputComponents = 124, and Metal and the validation layer count | ||
| 160 | gl_Position's 4 in it (VUID-RuntimeSpirv-Location-06272), so the highest location a VS writes must be 29.""" | ||
| 161 | top = rdna2spirv.f16_half_location(0, 1) | ||
| 162 | self.assertEqual(top, 29) | ||
| 163 | self.assertLessEqual((top + 1) * 4 + 4, 124) | ||
| 164 | spv, _ = translate("vs_f16_fallback", VS.splitlines()) | ||
| 165 | locations = [int(m) for m in re.findall(r"OpDecorate %out\S+ Location (\d+)", spv)] | ||
| 166 | self.assertEqual(max(locations), top) | ||
| 147 | 167 | ||
| 148 | def test_off_by_default(self): | 168 | def test_off_by_default(self): |
| 149 | spv, meta = translate("vs_f16_fallback", VS.splitlines(), fallback=False) | 169 | spv, meta = translate("vs_f16_fallback", VS.splitlines(), fallback=False) |
diff --git a/tests/semantic/test_interp_merge_check.py b/tests/semantic/test_interp_merge_check.py new file mode 100644 index 000000000..382955f5f --- /dev/null +++ b/tests/semantic/test_interp_merge_check.py | |||
| @@ -0,0 +1,78 @@ | |||
| 1 | """spirv_mini_interp and spirv_wave_interp reject a module that breaks spirv-val's merge rule. | ||
| 2 | |||
| 3 | OpSelectionMerge must directly precede OpBranchConditional / OpSwitch, and OpLoopMerge directly precede OpBranch / | ||
| 4 | OpBranchConditional (SPIR-V 2.16.2). Both interpreters used to skip merges, so #1633's first version, with an | ||
| 5 | `OpLoad %active` between the merge and its branch, passed every semantic test while spirv-val rejected every module | ||
| 6 | it produced (found by @mokkymiah, confirmed by @Impre-visible). Each case takes a translated module, which the | ||
| 7 | interpreters run, and moves one instruction to sit between a merge and its branch. Standard library only. | ||
| 8 | """ | ||
| 9 | import os | ||
| 10 | import re | ||
| 11 | import sys | ||
| 12 | import unittest | ||
| 13 | |||
| 14 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 15 | sys.dont_write_bytecode = True | ||
| 16 | sys.path.insert(0, HERE) | ||
| 17 | |||
| 18 | from test_salu64_bitwise_data import translate_ps # noqa: E402 (also puts tools/ on sys.path) | ||
| 19 | import spirv_mini_interp as si # noqa: E402 | ||
| 20 | import spirv_wave_interp as wi # noqa: E402 | ||
| 21 | |||
| 22 | LINES = ["v_mbcnt_lo_u32_b32 v4, -1, 0", "v_cmpx_gt_u32_e32 5, v4", "v_mov_b32 v0, 1.0", | ||
| 23 | "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] | ||
| 24 | |||
| 25 | |||
| 26 | def spv(): | ||
| 27 | text = translate_ps(LINES) | ||
| 28 | assert text.count("OpSelectionMerge") >= 1 | ||
| 29 | return text | ||
| 30 | |||
| 31 | |||
| 32 | def break_merge(text): | ||
| 33 | """Put the instruction just before the first OpSelectionMerge between it and its branch.""" | ||
| 34 | lines = text.splitlines() | ||
| 35 | k = next(i for i, ln in enumerate(lines) if ln.strip().startswith("OpSelectionMerge")) | ||
| 36 | assert re.match(r"\s*%\S+ = Op", lines[k - 1]), lines[k - 1] | ||
| 37 | lines[k - 1], lines[k] = lines[k], lines[k - 1] | ||
| 38 | return "\n".join(lines) + "\n" | ||
| 39 | |||
| 40 | |||
| 41 | def drop_branch(text): | ||
| 42 | """Remove the branch after the first OpSelectionMerge, so the merge is followed by something else.""" | ||
| 43 | lines = text.splitlines() | ||
| 44 | k = next(i for i, ln in enumerate(lines) if ln.strip().startswith("OpSelectionMerge")) | ||
| 45 | return "\n".join(lines[:k + 1] + lines[k + 2:]) + "\n" | ||
| 46 | |||
| 47 | |||
| 48 | class MergeRule(unittest.TestCase): | ||
| 49 | def test_translated_module_runs(self): | ||
| 50 | text = spv() | ||
| 51 | self.assertEqual(si.run_fragment(text)["%out_mrt0"][0], 0x3F800000) | ||
| 52 | self.assertEqual(len(wi.run_wave(text, wave=32)["outputs"]), 32) | ||
| 53 | |||
| 54 | def test_instruction_between_merge_and_branch(self): | ||
| 55 | bad = break_merge(spv()) | ||
| 56 | with self.assertRaisesRegex(si.InvalidModule, "OpSelectionMerge"): | ||
| 57 | si.run_fragment(bad) | ||
| 58 | with self.assertRaisesRegex(wi.InvalidModule, "OpSelectionMerge"): | ||
| 59 | wi.run_wave(bad, wave=32) | ||
| 60 | |||
| 61 | def test_merge_without_its_branch(self): | ||
| 62 | bad = drop_branch(spv()) | ||
| 63 | with self.assertRaises(si.InvalidModule): | ||
| 64 | si.run_fragment(bad) | ||
| 65 | with self.assertRaises(wi.InvalidModule): | ||
| 66 | wi.run_wave(bad, wave=32) | ||
| 67 | |||
| 68 | def test_loop_merge_rule(self): | ||
| 69 | ok = [(None, "OpLoopMerge", [], "OpLoopMerge %m %c None"), (None, "OpBranch", [], "OpBranch %h")] | ||
| 70 | si.check_structure(ok) | ||
| 71 | with self.assertRaisesRegex(si.InvalidModule, "OpLoopMerge"): | ||
| 72 | si.check_structure([ok[0], (None, "OpIAdd", [], "%x = OpIAdd %uint %a %b"), ok[1]]) | ||
| 73 | with self.assertRaisesRegex(si.InvalidModule, "end of the function"): | ||
| 74 | si.check_structure([ok[0]]) | ||
| 75 | |||
| 76 | |||
| 77 | if __name__ == "__main__": | ||
| 78 | unittest.main() | ||
diff --git a/tests/semantic/test_interp_p1lv_f16.py b/tests/semantic/test_interp_p1lv_f16.py new file mode 100644 index 000000000..0ddf9bd74 --- /dev/null +++ b/tests/semantic/test_interp_p1lv_f16.py | |||
| @@ -0,0 +1,470 @@ | |||
| 1 | """Semantic and translation tests for v_interp_p1lv_f16, f16 --bary-fallback, and stage/attr guards. | ||
| 2 | |||
| 3 | Covers the remaining 16-bit interpolation behaviour in tools/rdna2spirv.py not exercised by | ||
| 4 | test_interp_f16.py (clamp), test_interp_f16_high.py (p1ll low/high), or test_f16_interp_fallback.py: | ||
| 5 | - v_interp_p1lv_f16: PerVertexKHR low/high half decoding, standalone f32 intermediate, paired v_interp_p2_f16 | ||
| 6 | f16 narrowing and VOP3 clamp, nearest-even tie rounding, SV_Position ISG1 layout coexistence, | ||
| 7 | --f16-interp-fallback (F16_HALVES) execution and location-clash rejection, and SPIR-V negative controls. | ||
| 8 | - --bary-fallback (BARY_FALLBACK) with v_interp_p1ll_f16, v_interp_p1lv_f16, and v_interp_p2_f16: omits | ||
| 9 | PerVertexKHR / BaryCoordKHR, reads ordinary smooth vec4 inputs (where `high` cannot be distinguished), | ||
| 10 | places %bary at the lowest free location when raw v0/v1 reads are also present, and yields to | ||
| 11 | --f16-interp-fallback when both flags are enabled. | ||
| 12 | - I-source guards (interp_pair_src) for v_interp_p1lv_f16 and v_interp_p1ll_f16, plus Unsupported("<op> form") | ||
| 13 | rejection on non-PS stages (vs_, cs_) and missing `attr` operands for all three *_f16 opcodes. | ||
| 14 | """ | ||
| 15 | import os | ||
| 16 | import re | ||
| 17 | import struct | ||
| 18 | import sys | ||
| 19 | import unittest | ||
| 20 | |||
| 21 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 22 | ROOT = os.path.dirname(os.path.dirname(HERE)) | ||
| 23 | TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") | ||
| 24 | |||
| 25 | sys.dont_write_bytecode = True | ||
| 26 | if TOOLS_DIR not in sys.path: | ||
| 27 | sys.path.insert(0, TOOLS_DIR) | ||
| 28 | if HERE not in sys.path: | ||
| 29 | sys.path.insert(0, HERE) | ||
| 30 | |||
| 31 | import rdna2spirv # noqa: E402 | ||
| 32 | import support # noqa: E402 | ||
| 33 | |||
| 34 | BARY = (0.25, 0.25, 0.5) # vertex 0, 1, 2 weights (AMD i = 0.25, j = 0.5) | ||
| 35 | LO = (0.5, 1.5, 2.5) # exact interpolated value: 1.75 (0x3f00) | ||
| 36 | HI = (-4.0, 8.0, 16.0) # exact interpolated value: 9.0 (0x4880) | ||
| 37 | |||
| 38 | |||
| 39 | def pack_f16(lo, hi): | ||
| 40 | """Pack two floats as (low_f16 | high_f16 << 16) in a 32-bit word.""" | ||
| 41 | return struct.unpack("<I", struct.pack("<ee", lo, hi))[0] | ||
| 42 | |||
| 43 | |||
| 44 | def f16_bits(val): | ||
| 45 | return struct.unpack("<H", struct.pack("<e", float(val)))[0] | ||
| 46 | |||
| 47 | |||
| 48 | def f32_bits(val): | ||
| 49 | return struct.unpack("<I", struct.pack("<f", float(val)))[0] | ||
| 50 | |||
| 51 | |||
| 52 | def lerp(values, bary=BARY): | ||
| 53 | return sum(b * v for b, v in zip(bary, values)) | ||
| 54 | |||
| 55 | |||
| 56 | def isg1_dxbc(elements): | ||
| 57 | """Synthetic DXBC container with one ISG1 chunk: elements = (register, mask, rw_mask, sysv, ctype).""" | ||
| 58 | payload = bytearray(struct.pack("<II", len(elements), 8)) | ||
| 59 | for reg, mask, rw_mask, sysv, ctype in elements: | ||
| 60 | elem = bytearray(32) | ||
| 61 | struct.pack_into("<6I", elem, 0, 0, 0, 0, sysv, ctype, reg) | ||
| 62 | elem[24], elem[25] = mask, rw_mask | ||
| 63 | payload += elem | ||
| 64 | part = b"ISG1" + struct.pack("<I", len(payload)) + bytes(payload) | ||
| 65 | part += bytes((-len(part)) % 4) | ||
| 66 | header = b"DXBC" + bytes(16) + struct.pack("<III", 1, 0, 1) | ||
| 67 | return header + struct.pack("<I", len(header) + 8) + bytes(4) + part | ||
| 68 | |||
| 69 | |||
| 70 | def cs_fssm(rsrc2, group): | ||
| 71 | """Minimal compute FSSM header carrying COMPUTE_PGM_RSRC2 and local thread-group dimensions.""" | ||
| 72 | header = bytearray(0x148) | ||
| 73 | struct.pack_into("<4I", header, 0x138, rsrc2, *group) | ||
| 74 | return bytes(header) | ||
| 75 | |||
| 76 | |||
| 77 | # Default compute FSSM (4 user SGPRs, 64x1x1 threads) and PS ISG1 (attr0.xyzw + attr1.x, float32). | ||
| 78 | CS_FSSM = cs_fssm(0x8088, (64, 1, 1)) | ||
| 79 | PS_ATTR01_DXBC = isg1_dxbc([(0, 0xF, 0xF, 0, 3), (1, 0x1, 0x1, 0, 3)]) | ||
| 80 | PS_POS_ATTR0_DXBC = isg1_dxbc([(0, 0xF, 0x3, 1, 3), (1, 0xF, 0xF, 0, 3)]) | ||
| 81 | |||
| 82 | |||
| 83 | def translate_with_flags(name, lines, *, dxbc=support.STUB_DXBC, fssm=None, | ||
| 84 | bary_fallback=False, f16_halves=False): | ||
| 85 | """Translate `lines` with explicit BARY_FALLBACK / F16_HALVES flags and return (spvasm, meta).""" | ||
| 86 | old_bf, old_fh = rdna2spirv.BARY_FALLBACK, rdna2spirv.F16_HALVES | ||
| 87 | rdna2spirv.BARY_FALLBACK = bary_fallback | ||
| 88 | rdna2spirv.F16_HALVES = f16_halves | ||
| 89 | try: | ||
| 90 | spv = support.translate_lines(name, lines, dxbc=dxbc, fssm=fssm) | ||
| 91 | meta = rdna2spirv.shader_meta(rdna2spirv.translate.last_gen, spv) | ||
| 92 | finally: | ||
| 93 | rdna2spirv.BARY_FALLBACK = old_bf | ||
| 94 | rdna2spirv.F16_HALVES = old_fh | ||
| 95 | return spv, meta | ||
| 96 | |||
| 97 | |||
| 98 | # Primary v_interp_p1lv_f16 PS exercising low half, high half, clamp, standalone f32 intermediate, | ||
| 99 | # and f32/flat controls on attr0 (PerVertexKHR) and attr1 (smooth f32). | ||
| 100 | P1LV_SHADER = [ | ||
| 101 | "v_mov_b32_e32 v10, 0", | ||
| 102 | "v_interp_p1lv_f16 v2, v0, attr0.x, v10", | ||
| 103 | "v_interp_p2_f16 v2, v1, attr0.x, v2", | ||
| 104 | "v_interp_p1lv_f16 v3, v0, attr0.x, v10 high", | ||
| 105 | "v_interp_p2_f16 v3, v1, attr0.x, v3 high", | ||
| 106 | "v_interp_p1lv_f16 v4, v0, attr0.y, v10", | ||
| 107 | "v_interp_p2_f16 v4, v1, attr0.y, v4 clamp", | ||
| 108 | "v_interp_p1lv_f16 v5, v0, attr0.y, v10 high", | ||
| 109 | "v_interp_p2_f16 v5, v1, attr0.y, v5 high clamp", | ||
| 110 | "v_interp_p1lv_f16 v6, v0, attr0.z, v10", # standalone f32 intermediate | ||
| 111 | "v_interp_p1_f32_e32 v7, v0, attr1.x", | ||
| 112 | "v_interp_p2_f32_e32 v7, v1, attr1.x", | ||
| 113 | "v_interp_mov_f32_e32 v8, p0, attr0.w", | ||
| 114 | "exp mrt0 v2, v3, v4, v5", | ||
| 115 | "s_nop 0", | ||
| 116 | "exp mrt1 v6, v7, v8, v8 done vm", | ||
| 117 | "s_endpgm", | ||
| 118 | ] | ||
| 119 | |||
| 120 | P1LV_CLAMP_PAIR = [ | ||
| 121 | "v_mov_b32_e32 v10, 0", | ||
| 122 | "v_interp_p1lv_f16 v2, v0, attr0.x, v10", | ||
| 123 | "v_interp_p2_f16 v2, v1, attr0.x, v2 clamp", | ||
| 124 | "v_interp_p1lv_f16 v3, v0, attr0.x, v10 high", | ||
| 125 | "v_interp_p2_f16 v3, v1, attr0.x, v3 high clamp", | ||
| 126 | "v_interp_p1lv_f16 v4, v0, attr0.y, v10", | ||
| 127 | "v_interp_p2_f16 v4, v1, attr0.y, v4", | ||
| 128 | "v_interp_p1lv_f16 v5, v0, attr0.z, v10", | ||
| 129 | "exp mrt0 v2, v3, v4, v5 done vm", | ||
| 130 | "s_endpgm", | ||
| 131 | ] | ||
| 132 | |||
| 133 | |||
| 134 | class InterpP1lvF16DefaultTests(unittest.TestCase): | ||
| 135 | """Default PerVertexKHR translation and execution for v_interp_p1lv_f16.""" | ||
| 136 | |||
| 137 | def _default_attrs(self): | ||
| 138 | # attr0.x: (lo=1.75, hi=9.0); attr0.y: (lo=-0.25 -> clamp 0.0, hi=1.75 -> clamp 1.0); | ||
| 139 | # attr0.z: lo=(1.0, 3.0, 5.0) -> 3.5 as f32 intermediate; attr0.w: raw flat words. | ||
| 140 | y_lo = (-1.0, -1.0, 0.5) # 0.25*(-1.0) + 0.25*(-1.0) + 0.5*0.5 = -0.25 -> clamped to 0.0 | ||
| 141 | y_hi = (0.5, 1.5, 2.5) # 1.75 -> clamped to 1.0 | ||
| 142 | z_lo = (1.0, 3.0, 5.0) # 3.5 | ||
| 143 | w_raw = (0x1234, 0x5678, 0x9ABC) | ||
| 144 | attr0 = [(pack_f16(lo, hi), pack_f16(yl, yh), pack_f16(zl, 0.0), wr) | ||
| 145 | for lo, hi, yl, yh, zl, wr in zip(LO, HI, y_lo, y_hi, z_lo, w_raw)] | ||
| 146 | attr1 = [(f32_bits(x), 0, 0, 0) for x in (-2.0, 2.0, 4.0)] # 0.25*(-2)+0.25*2+0.5*4 = 2.0 | ||
| 147 | return {0: attr0, 1: attr1} | ||
| 148 | |||
| 149 | def test_p1lv_low_high_clamp_and_intermediate_end_to_end(self): | ||
| 150 | spv, meta = translate_with_flags("ps_p1lv", P1LV_SHADER, dxbc=PS_ATTR01_DXBC) | ||
| 151 | |||
| 152 | self.assertIn("OpCapability FragmentBarycentricKHR", spv) | ||
| 153 | self.assertIn('OpExtension "SPV_KHR_fragment_shader_barycentric"', spv) | ||
| 154 | self.assertIn("OpDecorate %in_attr0 PerVertexKHR", spv) | ||
| 155 | self.assertIn("OpDecorate %bary BuiltIn BaryCoordKHR", spv) | ||
| 156 | self.assertIn("OpDecorate %in_attr1 Location 1", spv) | ||
| 157 | self.assertNotIn("OpDecorate %in_attr1 PerVertexKHR", spv) | ||
| 158 | self.assertNotIn("OpDecorate %in_attr1 Flat", spv) | ||
| 159 | self.assertIn("UnpackHalf2x16", spv) | ||
| 160 | self.assertEqual(meta["features"], ["fragmentShaderBarycentric"]) | ||
| 161 | self.assertEqual(meta["inputs"], [0, 1]) | ||
| 162 | |||
| 163 | attrs = self._default_attrs() | ||
| 164 | out = support.run_fragment(spv, inputs=support.varyings(spv, attrs, BARY)) | ||
| 165 | mrt0, mrt1 = out["%out_mrt0"], out["%out_mrt1"] | ||
| 166 | self.assertEqual([w & 0xFFFF for w in mrt0], [0x3F00, 0x4880, 0x0000, 0x3C00]) | ||
| 167 | # Standalone v_interp_p1lv_f16 exports the f32 intermediate (3.5), not f16 bits. | ||
| 168 | self.assertEqual(f"{mrt1[0]:#010x}", f"{f32_bits(3.5):#010x}") | ||
| 169 | self.assertEqual(f"{mrt1[1]:#010x}", f"{f32_bits(2.0):#010x}") | ||
| 170 | self.assertEqual(mrt1[2], 0x1234) | ||
| 171 | |||
| 172 | def test_p1lv_clamp_vs_unclamped_and_in_range(self): | ||
| 173 | # attr0.x: lo=1.5 (clamp->1.0), hi=-0.25 (clamp->+0.0); attr0.y: lo=0.5 (in-range); attr0.z: lo=3.5 (p1lv) | ||
| 174 | attrs = {0: [(pack_f16(1.5, -0.25), pack_f16(0.5, 0.0), pack_f16(3.5, 0.0), 0)] * 3} | ||
| 175 | spv_clamp, _ = translate_with_flags("ps_p1lv_clamp", P1LV_CLAMP_PAIR, dxbc=PS_ATTR01_DXBC) | ||
| 176 | self.assertIn("FClamp", spv_clamp) | ||
| 177 | words_clamp = support.mrt0_words(spv_clamp, inputs=support.varyings(spv_clamp, attrs, BARY)) | ||
| 178 | self.assertEqual([w & 0xFFFF for w in words_clamp[:3]], [0x3C00, 0x0000, 0x3800]) | ||
| 179 | self.assertEqual(words_clamp[3], f32_bits(3.5)) | ||
| 180 | |||
| 181 | no_clamp_lines = [ln.replace(" clamp", "") for ln in P1LV_CLAMP_PAIR] | ||
| 182 | spv_raw, _ = translate_with_flags("ps_p1lv_noclamp", no_clamp_lines, dxbc=PS_ATTR01_DXBC) | ||
| 183 | self.assertNotIn("FClamp", spv_raw) | ||
| 184 | words_raw = support.mrt0_words(spv_raw, inputs=support.varyings(spv_raw, attrs, BARY)) | ||
| 185 | self.assertEqual([w & 0xFFFF for w in words_raw[:3]], [f16_bits(1.5), f16_bits(-0.25), 0x3800]) | ||
| 186 | |||
| 187 | def test_p1lv_nearest_even_rounding_and_subnormal_f16(self): | ||
| 188 | # Midpoint ties: | ||
| 189 | # 1.0 (0x3c00) and 1.0 + 2^-10 (0x3c01) averaged at (0.5, 0.5, 0.0) -> 1.0 + 2^-11 -> 0x3c00 (even) | ||
| 190 | # 1.0 + 2^-10 (0x3c01) and 1.0 + 2^-9 (0x3c02) averaged -> 1.0 + 3*2^-11 -> 0x3c02 (even) | ||
| 191 | # Subnormals 0x0002 and 0x0004 averaged -> 0x0003 (subnormal preserved by f16_bits) | ||
| 192 | lines = [ | ||
| 193 | "v_mov_b32_e32 v10, 0", | ||
| 194 | "v_interp_p1lv_f16 v2, v0, attr0.x, v10", | ||
| 195 | "v_interp_p2_f16 v2, v1, attr0.x, v2", | ||
| 196 | "v_interp_p1lv_f16 v3, v0, attr0.x, v10 high", | ||
| 197 | "v_interp_p2_f16 v3, v1, attr0.x, v3 high", | ||
| 198 | "v_interp_p1lv_f16 v4, v0, attr0.y, v10", | ||
| 199 | "v_interp_p2_f16 v4, v1, attr0.y, v4", | ||
| 200 | "exp mrt0 v2, v3, v4, v4 done vm", | ||
| 201 | "s_endpgm", | ||
| 202 | ] | ||
| 203 | h0 = 0x3C00 | ||
| 204 | h1 = 0x3C01 | ||
| 205 | h2 = 0x3C02 | ||
| 206 | attr0 = [ | ||
| 207 | ((h0 & 0xFFFF) | ((h1 & 0xFFFF) << 16), 0x0002, 0, 0), | ||
| 208 | ((h1 & 0xFFFF) | ((h2 & 0xFFFF) << 16), 0x0004, 0, 0), | ||
| 209 | ((h0 & 0xFFFF) | ((h1 & 0xFFFF) << 16), 0x0002, 0, 0), | ||
| 210 | ] | ||
| 211 | spv, _ = translate_with_flags("ps_p1lv_ties", lines, dxbc=PS_ATTR01_DXBC) | ||
| 212 | words = support.mrt0_words(spv, inputs=support.varyings(spv, {0: attr0}, (0.5, 0.5, 0.0))) | ||
| 213 | self.assertEqual([w & 0xFFFF for w in words[:3]], [0x3C00, 0x3C02, 0x0003]) | ||
| 214 | |||
| 215 | def test_p1lv_with_sv_position_in_isg1(self): | ||
| 216 | # SV_Position at ISG1 reg 0 occupies v2..v5; v_interp_p1lv_f16 reads v0 and vsrc2=v10 without conflict. | ||
| 217 | lines = [ | ||
| 218 | "v_mov_b32_e32 v10, 0", | ||
| 219 | "v_interp_p1lv_f16 v6, v0, attr0.x, v10 high", | ||
| 220 | "v_interp_p2_f16 v6, v1, attr0.x, v6 high", | ||
| 221 | "v_add_f32_e32 v7, v2, v3", | ||
| 222 | "exp mrt0 v6, v7, v6, v7 done vm", | ||
| 223 | "s_endpgm", | ||
| 224 | ] | ||
| 225 | spv, meta = translate_with_flags("ps_p1lv_pos", lines, dxbc=PS_POS_ATTR0_DXBC) | ||
| 226 | self.assertEqual(meta["ps_system_inputs"], ["0", "1"]) | ||
| 227 | attr0 = [(pack_f16(0.5, hi), 0, 0, 0) for hi in HI] | ||
| 228 | inputs = support.varyings(spv, {0: attr0}, BARY) | ||
| 229 | inputs["%frag_coord"] = (1.25, 2.5, 0.0, 1.0) | ||
| 230 | words = support.mrt0_words(spv, inputs=inputs) | ||
| 231 | self.assertEqual(words[0] & 0xFFFF, 0x4880) | ||
| 232 | self.assertEqual(words[1], f32_bits(3.75)) | ||
| 233 | |||
| 234 | def test_negative_controls_p1lv(self): | ||
| 235 | attrs = {0: [(pack_f16(1.5, -0.25), pack_f16(0.5, 0.0), pack_f16(3.5, 0.0), 0)] * 3} | ||
| 236 | spv, _ = translate_with_flags("ps_p1lv_neg", P1LV_CLAMP_PAIR, dxbc=PS_ATTR01_DXBC) | ||
| 237 | inputs = support.varyings(spv, attrs, BARY) | ||
| 238 | baseline = support.mrt0_words(spv, inputs=inputs) | ||
| 239 | self.assertEqual([w & 0xFFFF for w in baseline[:3]], [0x3C00, 0x0000, 0x3800]) | ||
| 240 | |||
| 241 | # Sabotage 1: force high-half extract (component 1) to low half (component 0). | ||
| 242 | bad_half = re.sub(r"OpCompositeExtract %float (%\S+) 1", r"OpCompositeExtract %float \1 0", spv) | ||
| 243 | self.assertNotEqual(bad_half, spv) | ||
| 244 | self.assertNotEqual(support.mrt0_words(bad_half, inputs=inputs), baseline) | ||
| 245 | |||
| 246 | # Sabotage 2: drop FClamp by replacing FClamp %v %f0 %f1 with FMax %v %f0. | ||
| 247 | bad_clamp = re.sub(r"OpExtInst %float %glsl FClamp (%\S+) %f0 %f1", r"OpExtInst %float %glsl FMax \1 %f0", spv) | ||
| 248 | self.assertNotEqual(bad_clamp, spv) | ||
| 249 | self.assertNotEqual(support.mrt0_words(bad_clamp, inputs=inputs), baseline) | ||
| 250 | |||
| 251 | |||
| 252 | class InterpP1lvF16HalvesFallbackTests(unittest.TestCase): | ||
| 253 | """--f16-interp-fallback (F16_HALVES) behaviour with v_interp_p1lv_f16.""" | ||
| 254 | |||
| 255 | def test_p1lv_f16_halves_translation_and_execution(self): | ||
| 256 | spv, meta = translate_with_flags("ps_p1lv_fh", P1LV_CLAMP_PAIR, | ||
| 257 | dxbc=PS_ATTR01_DXBC, f16_halves=True) | ||
| 258 | self.assertNotIn("PerVertexKHR", spv) | ||
| 259 | self.assertNotIn("BaryCoordKHR", spv) | ||
| 260 | self.assertNotIn("FragmentBarycentricKHR", spv) | ||
| 261 | self.assertNotIn("fragmentShaderBarycentric", meta["features"]) | ||
| 262 | self.assertIn("OpDecorate %in_f16h0_0 Location 28", spv) | ||
| 263 | self.assertIn("OpDecorate %in_f16h0_1 Location 29", spv) | ||
| 264 | self.assertNotIn("OpDecorate %in_f16h0_0 Flat", spv) | ||
| 265 | self.assertEqual(meta["f16_halves"], {"0": [28, 29]}) | ||
| 266 | self.assertEqual(meta["inputs"], [28, 29]) | ||
| 267 | |||
| 268 | inputs = { | ||
| 269 | "%in_f16h0_0": (lerp(LO), 0.5, 3.5, 0.0), # attr0 low: 1.75 (clamped->1.0), 0.5, 3.5 (p1lv f32) | ||
| 270 | "%in_f16h0_1": (lerp(HI), 0.0, 0.0, 0.0), # attr0 high: 9.0 (clamped->1.0) | ||
| 271 | } | ||
| 272 | words = support.mrt0_words(spv, inputs=inputs) | ||
| 273 | self.assertEqual([w & 0xFFFF for w in words[:3]], [0x3C00, 0x3C00, 0x3800]) | ||
| 274 | self.assertEqual(words[3], f32_bits(3.5)) | ||
| 275 | |||
| 276 | def test_p1lv_f16_halves_location_clash_rejected(self): | ||
| 277 | clash = [ | ||
| 278 | "v_mov_b32_e32 v10, 0", | ||
| 279 | "v_interp_p1lv_f16 v2, v0, attr0.x, v10", | ||
| 280 | "v_interp_p2_f16 v2, v1, attr0.x, v2", | ||
| 281 | "v_interp_p1_f32_e32 v3, v0, attr29.x", | ||
| 282 | "v_interp_p2_f32_e32 v3, v1, attr29.x", | ||
| 283 | "exp mrt0 v2, v3, v3, v3 done vm", | ||
| 284 | "s_endpgm", | ||
| 285 | ] | ||
| 286 | with self.assertRaises(rdna2spirv.Unsupported) as cm: | ||
| 287 | translate_with_flags("ps_p1lv_fh_clash", clash, f16_halves=True) | ||
| 288 | self.assertIn("decoded-half location", str(cm.exception)) | ||
| 289 | |||
| 290 | |||
| 291 | class InterpF16BaryFallbackTests(unittest.TestCase): | ||
| 292 | """--bary-fallback (BARY_FALLBACK) translation and execution for *_f16 ops.""" | ||
| 293 | |||
| 294 | def test_bary_fallback_for_p1ll_p1lv_p2_uses_smooth_inputs_without_per_vertex(self): | ||
| 295 | lines = [ | ||
| 296 | "v_mov_b32_e32 v10, 0", | ||
| 297 | "v_interp_p1ll_f16 v2, v0, attr0.x", | ||
| 298 | "v_interp_p2_f16 v2, v1, attr0.x, v2", | ||
| 299 | "v_interp_p1lv_f16 v3, v0, attr0.y, v10 high", | ||
| 300 | "v_interp_p2_f16 v3, v1, attr0.y, v3 high clamp", | ||
| 301 | "v_interp_p1lv_f16 v4, v0, attr0.z, v10", # standalone f32 intermediate | ||
| 302 | "exp mrt0 v2, v3, v4, v2 done vm", | ||
| 303 | "s_endpgm", | ||
| 304 | ] | ||
| 305 | spv, meta = translate_with_flags("ps_f16_bf", lines, dxbc=PS_ATTR01_DXBC, bary_fallback=True) | ||
| 306 | |||
| 307 | self.assertNotIn("PerVertexKHR", spv) | ||
| 308 | self.assertNotIn("BaryCoordKHR", spv) | ||
| 309 | self.assertNotIn("FragmentBarycentricKHR", spv) | ||
| 310 | self.assertNotIn("SPV_KHR_fragment_shader_barycentric", spv) | ||
| 311 | self.assertNotIn("%bary", spv) | ||
| 312 | self.assertIn("OpDecorate %in_attr0 Location 0", spv) | ||
| 313 | self.assertNotIn("OpDecorate %in_attr0 Flat", spv) | ||
| 314 | self.assertEqual(meta["features"], []) | ||
| 315 | self.assertEqual(meta["inputs"], [0]) | ||
| 316 | self.assertNotIn("bary_fallback_input", meta) | ||
| 317 | self.assertNotIn("f16_halves", meta) | ||
| 318 | |||
| 319 | # Under --bary-fallback there are no per-vertex inputs, so high reads the same smooth f32 channel. | ||
| 320 | attrs = {0: [(f32_bits(x), f32_bits(y), f32_bits(z), 0) | ||
| 321 | for x, y, z in zip((0.5, 1.5, 2.5), (-1.0, -1.0, 0.5), (1.0, 3.0, 5.0))]} | ||
| 322 | words = support.mrt0_words(spv, inputs=support.varyings(spv, attrs, BARY)) | ||
| 323 | self.assertEqual(words[0] & 0xFFFF, 0x3F00) # 1.75 | ||
| 324 | self.assertEqual(words[1] & 0xFFFF, 0x0000) # -0.25 clamped to +0.0 | ||
| 325 | self.assertEqual(words[2], f32_bits(3.5)) # standalone p1lv f32 intermediate | ||
| 326 | |||
| 327 | # Confirm `high` and non-`high` read identically under --bary-fallback. | ||
| 328 | lines_same = [ | ||
| 329 | "v_mov_b32_e32 v10, 0", | ||
| 330 | "v_interp_p1ll_f16 v2, v0, attr0.x", | ||
| 331 | "v_interp_p2_f16 v2, v1, attr0.x, v2", | ||
| 332 | "v_interp_p1lv_f16 v3, v0, attr0.x, v10 high", | ||
| 333 | "v_interp_p2_f16 v3, v1, attr0.x, v3 high", | ||
| 334 | "exp mrt0 v2, v3, v2, v3 done vm", | ||
| 335 | "s_endpgm", | ||
| 336 | ] | ||
| 337 | spv_same, _ = translate_with_flags("ps_f16_bf_same", lines_same, dxbc=PS_ATTR01_DXBC, bary_fallback=True) | ||
| 338 | words_same = support.mrt0_words(spv_same, inputs={"%in_attr0": (1.75, 0.0, 0.0, 0.0)}) | ||
| 339 | self.assertEqual([w & 0xFFFF for w in words_same[:2]], [0x3F00, 0x3F00]) | ||
| 340 | |||
| 341 | def test_bary_fallback_with_raw_bary_read_and_sparse_attr(self): | ||
| 342 | for attr_idx, want_bary_loc in ((0, 1), (30, 0)): | ||
| 343 | with self.subTest(attr=attr_idx): | ||
| 344 | lines = [ | ||
| 345 | "v_mov_b32_e32 v10, 0", | ||
| 346 | f"v_interp_p1lv_f16 v2, v0, attr{attr_idx}.x, v10", | ||
| 347 | f"v_interp_p2_f16 v2, v1, attr{attr_idx}.x, v2", | ||
| 348 | "v_mov_b32_e32 v4, v0", | ||
| 349 | "v_mov_b32_e32 v5, v1", | ||
| 350 | "exp mrt0 v2, v4, v5, v2 done vm", | ||
| 351 | "s_endpgm", | ||
| 352 | ] | ||
| 353 | spv, meta = translate_with_flags(f"ps_f16_bf_raw_{attr_idx}", lines, bary_fallback=True) | ||
| 354 | self.assertNotIn("PerVertexKHR", spv) | ||
| 355 | self.assertNotIn("BaryCoordKHR", spv) | ||
| 356 | self.assertNotIn("FragmentBarycentricKHR", spv) | ||
| 357 | self.assertIn(f"OpDecorate %in_attr{attr_idx} Location {attr_idx}", spv) | ||
| 358 | self.assertIn(f"OpDecorate %bary Location {want_bary_loc}", spv) | ||
| 359 | self.assertIsNone(re.search(r"OpDecorate %bary (Flat|NoPerspective)", spv)) | ||
| 360 | self.assertEqual(meta["bary_fallback_input"], {"location": want_bary_loc}) | ||
| 361 | self.assertEqual(meta["ps_system_inputs"], ["bary_i", "bary_j"]) | ||
| 362 | |||
| 363 | words = support.mrt0_words(spv, inputs={ | ||
| 364 | f"%in_attr{attr_idx}": (1.75, 0.0, 0.0, 0.0), | ||
| 365 | "%bary": BARY, | ||
| 366 | }) | ||
| 367 | self.assertEqual(words[0] & 0xFFFF, 0x3F00) | ||
| 368 | self.assertEqual(words[1], f32_bits(BARY[1])) | ||
| 369 | self.assertEqual(words[2], f32_bits(BARY[2])) | ||
| 370 | |||
| 371 | def test_f16_halves_takes_precedence_over_bary_fallback(self): | ||
| 372 | spv, meta = translate_with_flags("ps_both_flags", P1LV_CLAMP_PAIR, | ||
| 373 | dxbc=PS_ATTR01_DXBC, bary_fallback=True, f16_halves=True) | ||
| 374 | self.assertNotIn("PerVertexKHR", spv) | ||
| 375 | self.assertIn("OpDecorate %in_f16h0_0 Location 28", spv) | ||
| 376 | self.assertIn("OpDecorate %in_f16h0_1 Location 29", spv) | ||
| 377 | self.assertEqual(meta["f16_halves"], {"0": [28, 29]}) | ||
| 378 | |||
| 379 | |||
| 380 | class InterpF16GuardsAndRejectionsTests(unittest.TestCase): | ||
| 381 | """interp_pair_src guards and Unsupported('<op> form') stage/attr rejections.""" | ||
| 382 | |||
| 383 | def test_p1lv_and_p1ll_i_source_guards(self): | ||
| 384 | bad_cases = [ | ||
| 385 | ("v_interp_p1lv_f16 I source v4", [ | ||
| 386 | "v_mov_b32_e32 v10, 0", | ||
| 387 | "v_interp_p1lv_f16 v2, v4, attr0.x, v10", | ||
| 388 | "v_interp_p2_f16 v2, v1, attr0.x, v2", | ||
| 389 | "exp mrt0 v2, v2, v2, v2 done vm", | ||
| 390 | "s_endpgm", | ||
| 391 | ]), | ||
| 392 | ("v_interp_p1lv_f16 I source v1", [ | ||
| 393 | "v_mov_b32_e32 v10, 0", | ||
| 394 | "v_interp_p1lv_f16 v2, v1, attr0.x, v10", | ||
| 395 | "v_interp_p2_f16 v2, v1, attr0.x, v2", | ||
| 396 | "exp mrt0 v2, v2, v2, v2 done vm", | ||
| 397 | "s_endpgm", | ||
| 398 | ]), | ||
| 399 | ("v_interp_p1ll_f16 I source v1", [ | ||
| 400 | "v_interp_p1ll_f16 v2, v1, attr0.x", | ||
| 401 | "v_interp_p2_f16 v2, v1, attr0.x, v2", | ||
| 402 | "exp mrt0 v2, v2, v2, v2 done vm", | ||
| 403 | "s_endpgm", | ||
| 404 | ]), | ||
| 405 | # An I source holding a zeroed v0 ("v_mov v0, 0; v_mov v6, v0") is a computed I of 0, which the translator | ||
| 406 | # models since #1545 (computed I/J barycentrics) instead of rejecting; it is no longer a bad case here. | ||
| 407 | ("v_interp_p2_f16 J source v0", [ | ||
| 408 | "v_mov_b32_e32 v10, 0", | ||
| 409 | "v_interp_p1lv_f16 v2, v0, attr0.x, v10", | ||
| 410 | "v_interp_p2_f16 v2, v0, attr0.x, v2", | ||
| 411 | "exp mrt0 v2, v2, v2, v2 done vm", | ||
| 412 | "s_endpgm", | ||
| 413 | ]), | ||
| 414 | ] | ||
| 415 | for msg, lines in bad_cases: | ||
| 416 | with self.subTest(msg=msg): | ||
| 417 | with self.assertRaises(rdna2spirv.Unsupported) as cm: | ||
| 418 | translate_with_flags("ps_guard_bad", lines, dxbc=PS_ATTR01_DXBC) | ||
| 419 | self.assertIn(msg, str(cm.exception)) | ||
| 420 | |||
| 421 | def test_p1lv_accepts_saved_copy_of_v0_even_if_v0_later_zeroed(self): | ||
| 422 | lines = [ | ||
| 423 | "v_mov_b32_e32 v6, v0", | ||
| 424 | "v_mov_b32_e32 v7, v1", | ||
| 425 | "v_mov_b32_e32 v0, 0", | ||
| 426 | "v_mov_b32_e32 v1, 0", | ||
| 427 | "v_mov_b32_e32 v10, 0", | ||
| 428 | "v_interp_p1lv_f16 v2, v6, attr0.x, v10 high", | ||
| 429 | "v_interp_p2_f16 v2, v7, attr0.x, v2 high", | ||
| 430 | "exp mrt0 v2, v2, v2, v2 done vm", | ||
| 431 | "s_endpgm", | ||
| 432 | ] | ||
| 433 | spv, _ = translate_with_flags("ps_p1lv_copy", lines, dxbc=PS_ATTR01_DXBC) | ||
| 434 | attrs = {0: [(pack_f16(lo, hi), 0, 0, 0) for lo, hi in zip(LO, HI)]} | ||
| 435 | words = support.mrt0_words(spv, inputs=support.varyings(spv, attrs, BARY)) | ||
| 436 | self.assertEqual(words[0] & 0xFFFF, 0x4880) | ||
| 437 | |||
| 438 | def test_non_ps_stages_rejected_for_all_f16_interp_ops(self): | ||
| 439 | ops = [ | ||
| 440 | ("v_interp_p1ll_f16", "v_interp_p1ll_f16 v2, v0, attr0.x"), | ||
| 441 | ("v_interp_p1lv_f16", "v_interp_p1lv_f16 v2, v0, attr0.x, v3"), | ||
| 442 | ("v_interp_p2_f16", "v_interp_p2_f16 v2, v1, attr0.x, v2"), | ||
| 443 | ] | ||
| 444 | for op, insn in ops: | ||
| 445 | with self.subTest(stage="vs", op=op): | ||
| 446 | with self.assertRaises(rdna2spirv.Unsupported) as cm: | ||
| 447 | translate_with_flags(f"vs_{op}", [insn, "exp pos0 v2, v2, v2, v2 done", "s_endpgm"]) | ||
| 448 | self.assertIn(f"{op} form", str(cm.exception)) | ||
| 449 | with self.subTest(stage="cs", op=op): | ||
| 450 | with self.assertRaises(rdna2spirv.Unsupported) as cm: | ||
| 451 | translate_with_flags(f"cs_{op}", [insn, "s_endpgm"], fssm=CS_FSSM) | ||
| 452 | self.assertIn(f"{op} form", str(cm.exception)) | ||
| 453 | |||
| 454 | def test_missing_attr_operand_rejected_for_all_f16_interp_ops(self): | ||
| 455 | ops = [ | ||
| 456 | ("v_interp_p1ll_f16", "v_interp_p1ll_f16 v2, v0, v3"), | ||
| 457 | ("v_interp_p1lv_f16", "v_interp_p1lv_f16 v2, v0, v3, v4"), | ||
| 458 | ("v_interp_p2_f16", "v_interp_p2_f16 v2, v1, v3, v2"), | ||
| 459 | ] | ||
| 460 | for op, insn in ops: | ||
| 461 | with self.subTest(op=op): | ||
| 462 | with self.assertRaises(rdna2spirv.Unsupported) as cm: | ||
| 463 | translate_with_flags(f"ps_noattr_{op}", | ||
| 464 | [insn, "exp mrt0 v2, v2, v2, v2 done vm", "s_endpgm"], | ||
| 465 | dxbc=PS_ATTR01_DXBC) | ||
| 466 | self.assertIn(f"{op} form", str(cm.exception)) | ||
| 467 | |||
| 468 | |||
| 469 | if __name__ == "__main__": | ||
| 470 | unittest.main() | ||
diff --git a/tests/semantic/test_lds_bitwise_b64.py b/tests/semantic/test_lds_bitwise_b64.py new file mode 100644 index 000000000..5b9f0bddf --- /dev/null +++ b/tests/semantic/test_lds_bitwise_b64.py | |||
| @@ -0,0 +1,83 @@ | |||
| 1 | """Value tests for RDNA2 ds_and_b64, ds_or_b64, ds_xor_b64 and their _rtn_ forms, run through spirv_mini_interp. | ||
| 2 | |||
| 3 | RDNA2 ISA, "Data Share Instructions": M = M op DATA on the 64-bit element at ADDR = vaddr + offset (the dwords at ADDR | ||
| 4 | and ADDR + 4, low first); the _rtn_ forms return the old 64 bits in vdst[0:1]. The translator does one 32-bit atomic | ||
| 5 | per dword, which leaves the same memory because a bitwise op works on each bit alone. Each case is a compute shader | ||
| 6 | run as one invocation: it seeds both dwords with ds_write_b64, runs the op, reads the element back with ds_read_b64 | ||
| 7 | and stores (vdst lo, vdst hi, M lo, M hi) to a buffer. Standard library only; no GPU, no LLVM, no game files. | ||
| 8 | """ | ||
| 9 | import os | ||
| 10 | import random | ||
| 11 | import sys | ||
| 12 | import unittest | ||
| 13 | |||
| 14 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 15 | sys.dont_write_bytecode = True | ||
| 16 | sys.path.insert(0, HERE) | ||
| 17 | |||
| 18 | from test_lds_atomics_values import run_listing # noqa: E402 (also puts tools/ on sys.path) | ||
| 19 | import rdna2spirv # noqa: E402 | ||
| 20 | |||
| 21 | M32 = 0xFFFFFFFF | ||
| 22 | OPS = {"and": lambda m, d: m & d, "or": lambda m, d: m | d, "xor": lambda m, d: m ^ d} | ||
| 23 | VALUES = [0, (1 << 64) - 1, 0x00000000_FFFFFFFF, 0xFFFFFFFF_00000000, 0x12345678_9ABCDEF0, 0x80000000_00000001] | ||
| 24 | |||
| 25 | |||
| 26 | def run_b64(line: str, init: int, data: int, addr: int = 0x40, offset: int = 0): | ||
| 27 | body = [f"v_mov_b32_e32 v1, {addr:#x}", f"v_mov_b32_e32 v2, {init & M32:#x}", f"v_mov_b32_e32 v3, {init >> 32:#x}", | ||
| 28 | f"ds_write_b64 v1, v[2:3] offset:{offset}", "s_waitcnt lgkmcnt(0)", | ||
| 29 | f"v_mov_b32_e32 v4, {data & M32:#x}", f"v_mov_b32_e32 v5, {data >> 32:#x}", | ||
| 30 | "v_mov_b32_e32 v6, 0xdead", "v_mov_b32_e32 v7, 0xbeef", | ||
| 31 | line + (f" offset:{offset}" if offset else ""), "s_waitcnt lgkmcnt(0)", | ||
| 32 | f"ds_read_b64 v[8:9], v1 offset:{offset}", "s_waitcnt lgkmcnt(0)"] | ||
| 33 | for k, r in enumerate((6, 7, 8, 9)): | ||
| 34 | body += [f"v_mov_b32_e32 v31, {4 * k}", f"buffer_store_dword v{r}, v31, s[0:3], 0 offen"] | ||
| 35 | mem = run_listing(body) | ||
| 36 | return tuple(mem.get(4 * k) for k in range(4)) | ||
| 37 | |||
| 38 | |||
| 39 | def split(v: int): | ||
| 40 | return v & M32, v >> 32 | ||
| 41 | |||
| 42 | |||
| 43 | class LdsBitwiseB64(unittest.TestCase): | ||
| 44 | def test_returning_forms(self): | ||
| 45 | for kind, fn in OPS.items(): | ||
| 46 | for m in VALUES: | ||
| 47 | for d in VALUES[::2]: | ||
| 48 | with self.subTest(op=kind, m=hex(m), d=hex(d)): | ||
| 49 | got = run_b64(f"ds_{kind}_rtn_b64 v[6:7], v1, v[4:5]", m, d) | ||
| 50 | self.assertEqual(got, split(m) + split(fn(m, d))) | ||
| 51 | |||
| 52 | def test_non_returning_forms_leave_vdst_alone(self): | ||
| 53 | for kind, fn in OPS.items(): | ||
| 54 | for m, d in ((0x12345678_9ABCDEF0, 0x0F0F0F0F_F0F0F0F0), (0, (1 << 64) - 1)): | ||
| 55 | with self.subTest(op=kind, m=hex(m), d=hex(d)): | ||
| 56 | self.assertEqual(run_b64(f"ds_{kind}_b64 v1, v[4:5]", m, d), (0xDEAD, 0xBEEF) + split(fn(m, d))) | ||
| 57 | |||
| 58 | def test_offset(self): | ||
| 59 | m, d = 0x11111111_22222222, 0x0000FFFF_FFFF0000 | ||
| 60 | self.assertEqual(run_b64("ds_xor_rtn_b64 v[6:7], v1, v[4:5]", m, d, addr=0x20, offset=0x18), | ||
| 61 | split(m) + split(m ^ d)) | ||
| 62 | |||
| 63 | def test_vdst_aliasing_data(self): | ||
| 64 | # vdst v[4:5] is also the data pair: the data is read before the old value is written back. | ||
| 65 | m, d = 0xF0F0F0F0_0F0F0F0F, 0xFF00FF00_00FF00FF | ||
| 66 | got = run_b64("ds_or_rtn_b64 v[4:5], v1, v[4:5]", m, d) | ||
| 67 | self.assertEqual(got[2:], split(m | d)) | ||
| 68 | |||
| 69 | def test_seeded(self): | ||
| 70 | rng = random.Random(0xB64) | ||
| 71 | for _ in range(15): | ||
| 72 | kind, m, d = rng.choice(list(OPS)), rng.getrandbits(64), rng.getrandbits(64) | ||
| 73 | with self.subTest(op=kind, m=hex(m), d=hex(d)): | ||
| 74 | self.assertEqual(run_b64(f"ds_{kind}_rtn_b64 v[6:7], v1, v[4:5]", m, d), | ||
| 75 | split(m) + split(OPS[kind](m, d))) | ||
| 76 | |||
| 77 | def test_bad_operands_rejected(self): | ||
| 78 | with self.assertRaises(rdna2spirv.Unsupported): | ||
| 79 | run_listing(["v_mov_b32_e32 v1, 0", "ds_and_b64 v1, v4"]) | ||
| 80 | |||
| 81 | |||
| 82 | if __name__ == "__main__": | ||
| 83 | unittest.main() | ||
diff --git a/tests/semantic/test_pack_b32_f16_mods.py b/tests/semantic/test_pack_b32_f16_mods.py new file mode 100644 index 000000000..c949eb32f --- /dev/null +++ b/tests/semantic/test_pack_b32_f16_mods.py | |||
| @@ -0,0 +1,136 @@ | |||
| 1 | """Semantic tests for the neg/abs source modifiers on v_pack_b32_f16 (SHADER-260, abs is the follow-up to #1570). | ||
| 2 | |||
| 3 | v_pack_b32_f16 packs the low 16 bits of src0 and of src1 into one dword (op_sel picks a source's high half | ||
| 4 | instead). On RDNA2 the VOP3 NEG and ABS fields act on the selected 16-bit half as plain bit moves, before the | ||
| 5 | half is packed: ABS clears bit 15 and NEG flips it, ABS first. NEG was measured on a Radeon 680M (gfx1036, RDNA2 | ||
| 6 | iGPU, AMD Windows driver 32.0.21044.64) with 192 hand-written raw kernels in wave32 and wave64 (#1548 | ||
| 7 | SHADER-260): ``-v0`` turned 0x7c01 into 0xfe01 with IEEE mode 1 and into 0xfc01 with IEEE mode 0, in either half | ||
| 8 | and with op_sel, so the sign move does not depend on the mode. ABS is the ISA's sign clear of the same field pair | ||
| 9 | and has no hardware run of this instruction yet. The translator used to reject any such operand as Unsupported. | ||
| 10 | |||
| 11 | Not modelled here: IEEE mode 1 quieting a signalling NaN half (0x7c01 -> 0x7e01). Which mode the game's shaders | ||
| 12 | run in is SHADER-190; the NaN cases below are the plain bit moves of mode 0. | ||
| 13 | |||
| 14 | The whole 16-bit half is moved, so an sNaN payload survives; the interpreter runs the integer SPIR-V | ||
| 15 | (OpBitwiseAnd/OpBitwiseXor), which is exact. | ||
| 16 | """ | ||
| 17 | import os | ||
| 18 | import struct | ||
| 19 | import sys | ||
| 20 | import tempfile | ||
| 21 | import unittest | ||
| 22 | import warnings | ||
| 23 | |||
| 24 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 25 | ROOT = os.path.dirname(os.path.dirname(HERE)) | ||
| 26 | TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") | ||
| 27 | |||
| 28 | sys.dont_write_bytecode = True | ||
| 29 | sys.path.insert(0, TOOLS_DIR) | ||
| 30 | sys.path.insert(0, HERE) | ||
| 31 | |||
| 32 | import rdna2spirv # noqa: E402 | ||
| 33 | import spirv_mini_interp as si # noqa: E402 | ||
| 34 | |||
| 35 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 36 | SIGN = 0x8000 | ||
| 37 | MANT = 0x7FFF | ||
| 38 | |||
| 39 | # Operand words. Each holds a different value in each half so that op_sel and the modifier can be told apart. | ||
| 40 | # Low halves: 1.5, -0.25, an sNaN. High halves: -3.0, 1.5, another sNaN, +0/-0. | ||
| 41 | W1 = 0xB400_3E00 | ||
| 42 | W2 = 0x3E00_B400 | ||
| 43 | W3 = 0x3E00_7C01 | ||
| 44 | W4 = 0x0000_8000 | ||
| 45 | W5 = 0xC400_3E00 | ||
| 46 | |||
| 47 | _TMP = None | ||
| 48 | |||
| 49 | |||
| 50 | def run(lines, export=None): | ||
| 51 | """Run the listing through the translator and the interpreter, return the mrt0 words.""" | ||
| 52 | global _TMP | ||
| 53 | if _TMP is None: | ||
| 54 | _TMP = tempfile.TemporaryDirectory() | ||
| 55 | os.mkdir(os.path.join(_TMP.name, "disasm")) | ||
| 56 | with open(os.path.join(_TMP.name, "ps_packmods.dxbc"), "wb") as f: | ||
| 57 | f.write(STUB_DXBC) | ||
| 58 | path = os.path.join(_TMP.name, "disasm", "ps_packmods.s") | ||
| 59 | exp = export or ("v0",) * 4 | ||
| 60 | with open(path, "w", encoding="utf-8") as f: | ||
| 61 | f.write("; ps_packmods\n" + "".join(f"\t{ln}\n" for ln in lines) + | ||
| 62 | "\texp mrt0 " + ", ".join(exp) + " done vm\n\ts_endpgm\n") | ||
| 63 | with warnings.catch_warnings(): | ||
| 64 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 65 | spv = rdna2spirv.translate(path) | ||
| 66 | return si.run_fragment(spv)["%out_mrt0"][:len(exp)] | ||
| 67 | |||
| 68 | |||
| 69 | def tearDownModule(): | ||
| 70 | global _TMP | ||
| 71 | if _TMP is not None: | ||
| 72 | _TMP.cleanup() | ||
| 73 | _TMP = None | ||
| 74 | |||
| 75 | |||
| 76 | def half(word, hi, neg, abs_): | ||
| 77 | """One source half as the hardware hands it to the packer: op_sel picks the half, then ABS, then NEG.""" | ||
| 78 | bits = word >> (16 if hi else 0) & 0xFFFF | ||
| 79 | if abs_: | ||
| 80 | bits &= MANT | ||
| 81 | if neg: | ||
| 82 | bits ^= SIGN | ||
| 83 | return bits | ||
| 84 | |||
| 85 | |||
| 86 | def operand(base, neg, abs_, hi): | ||
| 87 | text = f"{'-' if neg else ''}{'|' if abs_ else ''}{base}{'|' if abs_ else ''}" | ||
| 88 | return text, f"[{1 if hi else 0}]" | ||
| 89 | |||
| 90 | |||
| 91 | # (src0 word, src1 word, src0 neg/abs/hi, src1 neg/abs/hi) | ||
| 92 | CASES = [ | ||
| 93 | (W1, W2, (0, 0, 0), (0, 0, 0)), # plain pack (control) | ||
| 94 | (W2, W1, (1, 0, 0), (0, 0, 0)), # src0 neg flips the low half's sign | ||
| 95 | (W3, W4, (0, 1, 0), (0, 0, 0)), # src0 abs on an sNaN half keeps the payload | ||
| 96 | (W4, W4, (1, 1, 0), (0, 0, 0)), # neg(abs(-0.0)) -> -0.0 | ||
| 97 | (W3, W5, (1, 1, 1), (1, 1, 1)), # high halves of both, both modifiers: sNaN negated, -3.0 abs | ||
| 98 | (W2, W1, (0, 1, 1), (0, 0, 0)), # op_sel high with abs (the high half of W2 is 1.5) | ||
| 99 | (W1, W3, (1, 0, 0), (1, 0, 1)), # neg on both, src1 op_sel high: -1.5 | -sNaN | ||
| 100 | ] | ||
| 101 | |||
| 102 | |||
| 103 | class PackModsTests(unittest.TestCase): | ||
| 104 | def test_neg_abs_are_bit_moves_on_the_selected_half(self): | ||
| 105 | for w1, w2, (n0, ab0, hi0), (n1, ab1, hi1) in CASES: | ||
| 106 | with self.subTest(w1=f"{w1:08x}", w2=f"{w2:08x}", mods=(n0, ab0, hi0, n1, ab1, hi1)): | ||
| 107 | s0, o0 = operand("v1", n0, ab0, hi0) | ||
| 108 | s1, o1 = operand("v2", n1, ab1, hi1) | ||
| 109 | mods = f" op_sel:[{o0[1]},{o1[1]},0]" if (hi0 or hi1) else "" | ||
| 110 | lines = [f"v_mov_b32 v1, {w1:#x}", f"v_mov_b32 v2, {w2:#x}", | ||
| 111 | f"v_pack_b32_f16 v0, {s0}, {s1}{mods}"] | ||
| 112 | want = half(w1, hi0, n0, ab0) | half(w2, hi1, n1, ab1) << 16 | ||
| 113 | self.assertEqual(run(lines)[0], want) | ||
| 114 | |||
| 115 | def test_negative_inline_constant_keeps_its_sign(self): | ||
| 116 | # -1.0 as an inline constant arrives with the sign in the value, not as a NEG modifier. | ||
| 117 | self.assertEqual(run(["v_pack_b32_f16 v0, -1.0, v1"])[0], 0xBC00) | ||
| 118 | |||
| 119 | def test_abs_inline_constant(self): | ||
| 120 | self.assertEqual(run(["v_pack_b32_f16 v0, 1.0, |v1|"])[0], 0x3C00) | ||
| 121 | |||
| 122 | def test_snan_payload_is_kept(self): | ||
| 123 | # 0x7c01 is an sNaN half: the packer moves the whole 16 bits, it does not round a float. | ||
| 124 | self.assertEqual(run(["v_mov_b32 v1, 0x7c01", "v_pack_b32_f16 v0, v1, v2"])[0], 0x00007C01) | ||
| 125 | |||
| 126 | def test_gpu_fixture_words(self): | ||
| 127 | # The words in runtime/test/shaders/ps_f16_pack_mods.asm are what a GPU must give. | ||
| 128 | words = run(["v_mov_b32 v0, 0x42003400", "v_mov_b32 v1, 0x34004400", | ||
| 129 | "v_pack_b32_f16 v2, -v0, |v1|", "v_pack_b32_f16 v3, v0, -v1", | ||
| 130 | "v_pack_b32_f16 v4, -|v0|, v1 op_sel:[1,0,0]", | ||
| 131 | "v_pack_b32_f16 v5, -v0, -|v1| op_sel:[0,1,0]"], export=("v2", "v3", "v4", "v5")) | ||
| 132 | self.assertEqual(list(words), [0x4400B400, 0xC4003400, 0x4400C200, 0xB400B400]) | ||
| 133 | |||
| 134 | |||
| 135 | if __name__ == "__main__": | ||
| 136 | unittest.main() | ||
diff --git a/tests/semantic/test_salu_cmov_b64.py b/tests/semantic/test_salu_cmov_b64.py new file mode 100644 index 000000000..934df9cc3 --- /dev/null +++ b/tests/semantic/test_salu_cmov_b64.py | |||
| @@ -0,0 +1,247 @@ | |||
| 1 | """Semantic tests for RDNA2 s_cmov_b64 on 64-bit scalar *data* pairs. | ||
| 2 | |||
| 3 | Rule: D[63:0] = SCC ? S0[63:0] : D[63:0]; SCC is read, not written (RDNA2 ISA SOP1, | ||
| 4 | LLVM AMDGPU SOPInstructions.td `S_CMOV_B64 : SOP1_64` under `Uses = [SCC]`). | ||
| 5 | |||
| 6 | Only plain data is supported. A lane-mask register holds one lane's bit in this | ||
| 7 | translator, so selecting it as 64-bit data would silently read back a per-lane | ||
| 8 | bool instead of the wave's mask (issue #210). Those operands stay rejected. | ||
| 9 | |||
| 10 | Every program here is hand-written; the translator and mini interpreter from | ||
| 11 | this repository do the work. No LLVM, SPIR-V tools, GPU or game files are used. | ||
| 12 | |||
| 13 | Run directly: | ||
| 14 | python -I tests/semantic/test_salu_cmov_b64.py -v | ||
| 15 | """ | ||
| 16 | import os | ||
| 17 | import re | ||
| 18 | import sys | ||
| 19 | import tempfile | ||
| 20 | import unittest | ||
| 21 | import warnings | ||
| 22 | |||
| 23 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 24 | if HERE not in sys.path: | ||
| 25 | sys.path.insert(0, HERE) | ||
| 26 | |||
| 27 | from support import STUB_DXBC, mrt0_words, rdna2spirv # noqa: E402 | ||
| 28 | |||
| 29 | MASK32 = 0xFFFFFFFF | ||
| 30 | MASK64 = 0xFFFFFFFFFFFFFFFF | ||
| 31 | |||
| 32 | _TMP_DIR = None | ||
| 33 | _PS_PATH = None | ||
| 34 | |||
| 35 | |||
| 36 | def setUpModule(): | ||
| 37 | global _TMP_DIR, _PS_PATH | ||
| 38 | _TMP_DIR = tempfile.TemporaryDirectory() | ||
| 39 | dis = os.path.join(_TMP_DIR.name, "disasm") | ||
| 40 | os.mkdir(dis) | ||
| 41 | _PS_PATH = os.path.join(dis, "ps_cmov64.s") | ||
| 42 | with open(os.path.join(_TMP_DIR.name, "ps_cmov64.dxbc"), "wb") as f: | ||
| 43 | f.write(STUB_DXBC) | ||
| 44 | |||
| 45 | |||
| 46 | def tearDownModule(): | ||
| 47 | global _TMP_DIR | ||
| 48 | if _TMP_DIR is not None: | ||
| 49 | _TMP_DIR.cleanup() | ||
| 50 | _TMP_DIR = None | ||
| 51 | |||
| 52 | |||
| 53 | def translate_ps(lines): | ||
| 54 | if _TMP_DIR is None: | ||
| 55 | setUpModule() | ||
| 56 | asm = "; ps_cmov64\n" + "".join(f"\t{ln}\n" for ln in lines) | ||
| 57 | with open(_PS_PATH, "w", encoding="utf-8", newline="") as f: | ||
| 58 | f.write(asm) | ||
| 59 | with warnings.catch_warnings(): | ||
| 60 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 61 | return rdna2spirv.translate(_PS_PATH) | ||
| 62 | |||
| 63 | |||
| 64 | def run_ps(lines): | ||
| 65 | spv = translate_ps(lines + ["exp mrt0 v0, v1, v2, v3 done vm", "s_endpgm"]) | ||
| 66 | return mrt0_words(spv) | ||
| 67 | |||
| 68 | |||
| 69 | def scc_line(scc): | ||
| 70 | return "s_cmp_eq_u32 1, 1" if scc else "s_cmp_eq_u32 0, 1" | ||
| 71 | |||
| 72 | |||
| 73 | def load_pair_lines(reg, val64): | ||
| 74 | return [f"s_mov_b32 s{reg}, {val64 & MASK32:#x}", | ||
| 75 | f"s_mov_b32 s{reg + 1}, {(val64 >> 32) & MASK32:#x}"] | ||
| 76 | |||
| 77 | |||
| 78 | def export_pair_lines(reg): | ||
| 79 | return [f"v_mov_b32 v0, s{reg}", f"v_mov_b32 v1, s{reg + 1}"] | ||
| 80 | |||
| 81 | |||
| 82 | def ref_cmov64(old, src, scc): | ||
| 83 | return (src if scc else old) & MASK64 | ||
| 84 | |||
| 85 | |||
| 86 | class DataPairTests(unittest.TestCase): | ||
| 87 | def test_plain_data_pair_is_accepted(self): | ||
| 88 | # The explicit non-mask case: both dwords come from plain immediate moves, | ||
| 89 | # not from EXEC, VCC or a compare. D is an ordinary SGPR data pair. | ||
| 90 | old = 0xDEADBEEF_11223344 | ||
| 91 | src = 0x55667788_90ABCDEF | ||
| 92 | for scc in (0, 1): | ||
| 93 | with self.subTest(scc=scc): | ||
| 94 | want = ref_cmov64(old, src, scc) | ||
| 95 | words = run_ps( | ||
| 96 | load_pair_lines(2, old) | ||
| 97 | + load_pair_lines(4, src) | ||
| 98 | + [scc_line(scc), "s_cmov_b64 s[2:3], s[4:5]", | ||
| 99 | "s_cselect_b32 s10, 1, 0"] | ||
| 100 | + export_pair_lines(2) | ||
| 101 | + ["v_mov_b32 v2, s10", "v_mov_b32 v3, 0"] | ||
| 102 | ) | ||
| 103 | self.assertEqual(words, [want & MASK32, want >> 32, scc, 0]) | ||
| 104 | |||
| 105 | def test_edge_values(self): | ||
| 106 | pairs = [ | ||
| 107 | (0, 0xFFFFFFFF_FFFFFFFF), | ||
| 108 | (0x00000001_00000000, 0x80000000_7FFFFFFF), | ||
| 109 | (0x7FFFFFFF_FFFFFFFF, 0x80000000_00000000), | ||
| 110 | (0x00000002_80000001, 0x00000002_80000002), | ||
| 111 | ] | ||
| 112 | for old, src in pairs: | ||
| 113 | for scc in (0, 1): | ||
| 114 | with self.subTest(old=hex(old), src=hex(src), scc=scc): | ||
| 115 | want = ref_cmov64(old, src, scc) | ||
| 116 | words = run_ps( | ||
| 117 | load_pair_lines(2, old) | ||
| 118 | + load_pair_lines(4, src) | ||
| 119 | + [scc_line(scc), "s_cmov_b64 s[2:3], s[4:5]"] | ||
| 120 | + export_pair_lines(2) | ||
| 121 | + ["v_mov_b32 v2, 0", "v_mov_b32 v3, 0"] | ||
| 122 | ) | ||
| 123 | self.assertEqual(words, [want & MASK32, want >> 32, 0, 0]) | ||
| 124 | |||
| 125 | def test_immediate_and_null_sources(self): | ||
| 126 | old = 0x55667788_11223344 | ||
| 127 | # shader_ir leaves a literal wider than 32 bits as a raw operand, which | ||
| 128 | # src64_data does not accept (the same holds for s_mov_b64); use the | ||
| 129 | # immediate forms the parser actually delivers. | ||
| 130 | for src_asm, src in (("0x12345678", 0x12345678), ("42", 42), | ||
| 131 | ("0", 0), ("-1", MASK64), ("-2", MASK64 - 1), ("null", 0)): | ||
| 132 | for scc in (0, 1): | ||
| 133 | with self.subTest(src=src_asm, scc=scc): | ||
| 134 | want = ref_cmov64(old, src, scc) | ||
| 135 | words = run_ps( | ||
| 136 | load_pair_lines(2, old) | ||
| 137 | + [scc_line(scc), f"s_cmov_b64 s[2:3], {src_asm}"] | ||
| 138 | + export_pair_lines(2) | ||
| 139 | + ["v_mov_b32 v2, 0", "v_mov_b32 v3, 0"] | ||
| 140 | ) | ||
| 141 | self.assertEqual(words, [want & MASK32, want >> 32, 0, 0]) | ||
| 142 | |||
| 143 | def test_destination_aliasing(self): | ||
| 144 | a64 = 0x55667788_11223344 | ||
| 145 | b64 = 0xDDEEFF00_99AABBCC | ||
| 146 | # s[3:4] = (s4 << 32) | s3, with s4 = low(a64), s3 = low(b64). | ||
| 147 | overlap_val = ((a64 & MASK32) << 32) | (b64 & MASK32) | ||
| 148 | for source, src_val in (("s[4:5]", a64), ("s[3:4]", overlap_val)): | ||
| 149 | for scc in (0, 1): | ||
| 150 | with self.subTest(source=source, scc=scc): | ||
| 151 | want = ref_cmov64(a64, src_val, scc) | ||
| 152 | lines = load_pair_lines(3, b64) + load_pair_lines(4, a64) | ||
| 153 | lines += [scc_line(scc), f"s_cmov_b64 s[4:5], {source}"] | ||
| 154 | lines += export_pair_lines(4) + ["v_mov_b32 v2, 0", "v_mov_b32 v3, 0"] | ||
| 155 | words = run_ps(lines) | ||
| 156 | self.assertEqual(words, [want & MASK32, want >> 32, 0, 0]) | ||
| 157 | |||
| 158 | def test_constant_pairs_are_not_mistaken_for_masks(self): | ||
| 159 | # 0 / -1 are EITHER in tools/lane_masks.py (the same bits as data), so | ||
| 160 | # they must not be mistaken for lane masks here. | ||
| 161 | for src_asm, src in (("-1", MASK64), ("0", 0)): | ||
| 162 | for scc in (0, 1): | ||
| 163 | with self.subTest(src=src_asm, scc=scc): | ||
| 164 | want = ref_cmov64(0x11223344_55667788, src, scc) | ||
| 165 | words = run_ps( | ||
| 166 | load_pair_lines(2, 0x11223344_55667788) | ||
| 167 | + [f"s_mov_b64 s[4:5], {src_asm}", scc_line(scc), | ||
| 168 | "s_cmov_b64 s[2:3], s[4:5]"] | ||
| 169 | + export_pair_lines(2) | ||
| 170 | + ["v_mov_b32 v2, 0", "v_mov_b32 v3, 0"] | ||
| 171 | ) | ||
| 172 | self.assertEqual(words, [want & MASK32, want >> 32, 0, 0]) | ||
| 173 | |||
| 174 | def test_scc_is_not_written(self): | ||
| 175 | old, src = 0x11111111_22222222, 0x33333333_44444444 | ||
| 176 | for scc in (0, 1): | ||
| 177 | with self.subTest(scc=scc): | ||
| 178 | want = ref_cmov64(old, src, scc) | ||
| 179 | words = run_ps( | ||
| 180 | load_pair_lines(2, old) | ||
| 181 | + load_pair_lines(4, src) | ||
| 182 | + [scc_line(scc), "s_cmov_b64 s[2:3], s[4:5]", | ||
| 183 | "s_addc_u32 s10, 10, 20"] | ||
| 184 | + export_pair_lines(2) | ||
| 185 | + ["v_mov_b32 v2, s10", "v_mov_b32 v3, 0"] | ||
| 186 | ) | ||
| 187 | self.assertEqual(words, [want & MASK32, want >> 32, 30 + scc, 0]) | ||
| 188 | |||
| 189 | |||
| 190 | class RejectionTests(unittest.TestCase): | ||
| 191 | MASK_SOURCE = "s_cmov_b64 lane-mask source" | ||
| 192 | MASK_DEST = "s_cmov_b64 lane-mask destination" | ||
| 193 | DEST = "s_cmov_b64 destination" | ||
| 194 | |||
| 195 | def test_lane_mask_source_rejected_with_message(self): | ||
| 196 | cmp = "v_cmp_ne_u32_e64 s[20:21], 0, v0" | ||
| 197 | cases = [ | ||
| 198 | ([cmp, "s_mov_b64 s[22:23], s[20:21]"], "s[22:23]"), | ||
| 199 | (["s_mov_b64 s[22:23], exec"], "s[22:23]"), | ||
| 200 | ([], "exec"), | ||
| 201 | # A zero-extended 32-bit mask: one dword is a mask, the other is | ||
| 202 | # an EITHER constant. holds_lane_mask() alone misses this pair. | ||
| 203 | ([cmp, "s_mov_b32 s2, s20", "s_mov_b32 s3, 0"], "s[2:3]"), | ||
| 204 | ([cmp, "s_mov_b32 s2, 0", "s_mov_b32 s3, s20"], "s[2:3]"), | ||
| 205 | ] | ||
| 206 | for prologue, src in cases: | ||
| 207 | with self.subTest(src=src, prologue=prologue[-1] if prologue else "none"): | ||
| 208 | lines = prologue + [scc_line(1), f"s_cmov_b64 s[2:3], {src}", | ||
| 209 | "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] | ||
| 210 | with self.assertRaisesRegex(rdna2spirv.Unsupported, re.escape(self.MASK_SOURCE)): | ||
| 211 | translate_ps(lines) | ||
| 212 | |||
| 213 | def test_mask_destination_rejected_with_message(self): | ||
| 214 | cmp = "v_cmp_ne_u32_e64 s[20:21], 0, v0" | ||
| 215 | cases = [ | ||
| 216 | [cmp, "s_cmov_b64 s[20:21], s[4:5]"], | ||
| 217 | [cmp, "s_mov_b32 s2, s20", "s_mov_b32 s3, 0", "s_cmov_b64 s[2:3], s[4:5]"], | ||
| 218 | ] | ||
| 219 | for lines in cases: | ||
| 220 | with self.subTest(lines=lines[-1]): | ||
| 221 | full = lines + ["exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] | ||
| 222 | with self.assertRaisesRegex(rdna2spirv.Unsupported, re.escape(self.MASK_DEST)): | ||
| 223 | translate_ps(full) | ||
| 224 | |||
| 225 | def test_ever_mask_pair_rejected_after_overwrite(self): | ||
| 226 | # A register that held a mask earlier, then plain data, is refused: at a | ||
| 227 | # CFG join lane_masks.py can drop the register (mask on one path, data on | ||
| 228 | # another), so "not a mask now" does not prove it is data on every path. | ||
| 229 | lines = ["v_cmp_ne_u32_e64 s[20:21], 0, v0", | ||
| 230 | "s_mov_b64 s[20:21], 0", "s_mov_b64 s[2:3], 0", | ||
| 231 | "s_cmov_b64 s[2:3], s[20:21]", | ||
| 232 | "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] | ||
| 233 | with self.assertRaisesRegex(rdna2spirv.Unsupported, re.escape(self.MASK_SOURCE)): | ||
| 234 | translate_ps(lines) | ||
| 235 | |||
| 236 | def test_invalid_destinations_rejected_with_message(self): | ||
| 237 | for line in ("s_cmov_b64 exec, s[4:5]", "s_cmov_b64 vcc, s[4:5]", | ||
| 238 | "s_cmov_b64 m0, s[4:5]", "s_cmov_b64 s4, s[4:5]", | ||
| 239 | "s_cmov_b64 null, s[4:5]"): | ||
| 240 | with self.subTest(line=line): | ||
| 241 | full = [line, "exp mrt0 v0, v0, v0, v0 done vm", "s_endpgm"] | ||
| 242 | with self.assertRaisesRegex(rdna2spirv.Unsupported, re.escape(self.DEST)): | ||
| 243 | translate_ps(full) | ||
| 244 | |||
| 245 | |||
| 246 | if __name__ == "__main__": | ||
| 247 | unittest.main() | ||
diff --git a/tests/semantic/test_salu_movrels_lane_mask.py b/tests/semantic/test_salu_movrels_lane_mask.py new file mode 100644 index 000000000..15a791609 --- /dev/null +++ b/tests/semantic/test_salu_movrels_lane_mask.py | |||
| @@ -0,0 +1,117 @@ | |||
| 1 | """s_movrels_b32 / s_movrels_b64 reading an SGPR that holds a lane mask (#1548, SHADER-284). | ||
| 2 | |||
| 3 | A lane-mask SGPR (a saved EXEC, a v_cmp result) holds only this lane's bit in the translation, so a plain dynamic | ||
| 4 | load copied that bit as data: with EXEC saved as 5, `s_movrels_b32 s12, s10` then `s_bcnt1_i32_b32 s13, s12` gave | ||
| 5 | 32 where the ISA gives 2. The translator now collects the whole wave's mask word for every mask SGPR and uses it | ||
| 6 | when the index lands there. Each case runs every lane of a synthetic compute shader in | ||
| 7 | spirv_mini_interp.run_workgroup (wave32 and native wave64) and stores D and the bit count per lane. Standard | ||
| 8 | library only; no GPU, no game files. | ||
| 9 | """ | ||
| 10 | import gc | ||
| 11 | import os | ||
| 12 | import struct | ||
| 13 | import sys | ||
| 14 | import tempfile | ||
| 15 | import unittest | ||
| 16 | import warnings | ||
| 17 | |||
| 18 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 19 | ROOT = os.path.dirname(os.path.dirname(HERE)) | ||
| 20 | TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") | ||
| 21 | |||
| 22 | sys.dont_write_bytecode = True | ||
| 23 | if HERE not in sys.path: | ||
| 24 | sys.path.insert(0, HERE) | ||
| 25 | if TOOLS_DIR not in sys.path: | ||
| 26 | sys.path.insert(0, TOOLS_DIR) | ||
| 27 | |||
| 28 | import rdna2spirv # noqa: E402 | ||
| 29 | import spirv_mini_interp as si # noqa: E402 | ||
| 30 | |||
| 31 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 32 | VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] # OOB_SELECT 3 (raw) | ||
| 33 | |||
| 34 | |||
| 35 | def run_cs(name, body, wave_size): | ||
| 36 | """Translate `body` as a compute shader (s[0:3] = output V#) and run all lanes; return the memory.""" | ||
| 37 | prev = rdna2spirv.WAVE64_EMULATE | ||
| 38 | try: | ||
| 39 | rdna2spirv.WAVE64_EMULATE = False | ||
| 40 | with tempfile.TemporaryDirectory() as tmp: | ||
| 41 | os.mkdir(os.path.join(tmp, "disasm")) | ||
| 42 | os.mkdir(os.path.join(tmp, "fssm")) | ||
| 43 | path = os.path.join(tmp, "disasm", name + ".s") | ||
| 44 | with open(path, "w", encoding="utf-8") as f: | ||
| 45 | f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in body) + "\ts_endpgm\n") | ||
| 46 | with open(os.path.join(tmp, name + ".dxbc"), "wb") as f: | ||
| 47 | f.write(STUB_DXBC) | ||
| 48 | with open(os.path.join(tmp, "fssm", name + ".fssm"), "wb") as f: | ||
| 49 | f.write(bytes(0x138) + struct.pack("<4I", 0x8088, wave_size, 1, 1)) | ||
| 50 | with warnings.catch_warnings(): | ||
| 51 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 52 | spv = rdna2spirv.translate(path) | ||
| 53 | gc.collect() | ||
| 54 | finally: | ||
| 55 | rdna2spirv.WAVE64_EMULATE = prev | ||
| 56 | return si.run_workgroup(spv, wave_size, wave_size, | ||
| 57 | inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, | ||
| 58 | push_constants=VSHARP + [0] * 28, memory={}) | ||
| 59 | |||
| 60 | |||
| 61 | def store(regs): | ||
| 62 | """Store the four SGPRs `regs` for each lane at lane * 16 (v0 = lane).""" | ||
| 63 | return (["s_mov_b32 exec_lo, -1", "v_lshlrev_b32 v20, 4, v0"] + | ||
| 64 | [f"v_mov_b32 v{21 + k}, s{s}" for k, s in enumerate(regs)] + | ||
| 65 | ["buffer_store_dwordx4 v[21:24], v20, s[0:3], 0 offen"]) | ||
| 66 | |||
| 67 | |||
| 68 | def lanes(mem, wave_size, count): | ||
| 69 | return [tuple(mem.get(lane * 16 + 4 * k, 0) for k in range(count)) for lane in range(wave_size)] | ||
| 70 | |||
| 71 | |||
| 72 | class MovrelsLaneMaskWave32(unittest.TestCase): | ||
| 73 | def test_finding_reproducer(self): | ||
| 74 | # The listing from the finding: EXEC = lanes 0 and 2, saved in s10, read back through s_movrels. | ||
| 75 | body = ["s_mov_b32 exec_lo, 5", "s_mov_b32 s10, exec_lo", "s_mov_b32 exec_lo, -1", "s_mov_b32 m0, 0", | ||
| 76 | "s_movrels_b32 s12, s10", "s_bcnt1_i32_b32 s13, s12", | ||
| 77 | "s_mov_b32 s14, s10", "s_bcnt1_i32_b32 s15, s14"] # the control: a plain copy | ||
| 78 | got = lanes(run_cs("cs_movrels_mask_w32", body + store([12, 13, 14, 15]), 32), 32, 4) | ||
| 79 | for lane, (d, bits, ctl_d, ctl_bits) in enumerate(got): | ||
| 80 | with self.subTest(lane=lane): | ||
| 81 | self.assertEqual((d, bits), (5, 2)) | ||
| 82 | self.assertEqual(ctl_bits, 2) | ||
| 83 | self.assertEqual(ctl_d, 0xFFFFFFFF if lane in (0, 2) else 0) # a copy stays a mask | ||
| 84 | |||
| 85 | def test_index_from_m0_hits_mask_and_data_neighbours(self): | ||
| 86 | # s10 data, s11 a v_cmp mask (lanes 1, 4, 9), s12 data; M0 picks each in turn from a base of s9. | ||
| 87 | body = ["s_mov_b32 exec_lo, -1", "s_mov_b32 s10, 0x1234", "s_mov_b32 s12, 0xabcd", | ||
| 88 | "v_cmp_eq_u32_e64 s11, v0, 1", "v_cmp_eq_u32_e64 s16, v0, 4", "s_or_b32 s11, s11, s16", | ||
| 89 | "v_cmp_eq_u32_e64 s16, v0, 9", "s_or_b32 s11, s11, s16", "s_mov_b32 s9, 0"] | ||
| 90 | reads = [] | ||
| 91 | for k, m in enumerate((1, 2, 3)): | ||
| 92 | reads += [f"s_mov_b32 s17, {m}", "s_mov_b32 m0, s17", f"s_movrels_b32 s{20 + k}, s9"] | ||
| 93 | reads += ["s_bcnt1_i32_b32 s23, s21"] | ||
| 94 | got = lanes(run_cs("cs_movrels_mix_w32", body + reads + store([20, 21, 22, 23]), 32), 32, 4) | ||
| 95 | want_mask = (1 << 1) | (1 << 4) | (1 << 9) | ||
| 96 | for lane, row in enumerate(got): | ||
| 97 | with self.subTest(lane=lane): | ||
| 98 | self.assertEqual(row, (0x1234, want_mask, 0xABCD, 3)) | ||
| 99 | |||
| 100 | |||
| 101 | class MovrelsLaneMaskWave64(unittest.TestCase): | ||
| 102 | def test_b64_pair_of_saved_exec(self): | ||
| 103 | # EXEC = lanes 0, 2 and 40, saved in s[10:11]; the b64 read gives both halves as data. | ||
| 104 | body = ["s_mov_b64 exec, -1", "v_cmp_eq_u32_e64 s[4:5], v0, 0", "v_cmp_eq_u32_e64 s[6:7], v0, 2", | ||
| 105 | "s_or_b64 s[4:5], s[4:5], s[6:7]", "v_cmp_eq_u32_e64 s[6:7], v0, 40", | ||
| 106 | "s_or_b64 s[4:5], s[4:5], s[6:7]", "s_mov_b64 exec, s[4:5]", "s_mov_b64 s[10:11], exec", | ||
| 107 | "s_mov_b64 exec, -1", "s_mov_b32 m0, 0", "s_movrels_b64 s[12:13], s[10:11]", | ||
| 108 | "s_bcnt1_i32_b64 s14, s[12:13]", "s_mov_b32 m0, 1", "s_movrels_b32 s15, s10"] | ||
| 109 | got = lanes(run_cs("cs_movrels_mask_w64", body + ["s_mov_b64 exec, -1"] + store([12, 13, 14, 15]), 64), | ||
| 110 | 64, 4) | ||
| 111 | for lane, row in enumerate(got): | ||
| 112 | with self.subTest(lane=lane): | ||
| 113 | self.assertEqual(row, (5, 1 << 8, 3, 1 << 8)) # M0 = 1 from s10 lands on s11, the high half | ||
| 114 | |||
| 115 | |||
| 116 | if __name__ == "__main__": | ||
| 117 | unittest.main() | ||
diff --git a/tests/semantic/test_scalar_alu_and_smem_folding.py b/tests/semantic/test_scalar_alu_and_smem_folding.py new file mode 100644 index 000000000..bb34022e5 --- /dev/null +++ b/tests/semantic/test_scalar_alu_and_smem_folding.py | |||
| @@ -0,0 +1,193 @@ | |||
| 1 | from __future__ import annotations | ||
| 2 | |||
| 3 | """Regression and semantic tests for scalar ALU and s_buffer_load constant folding in the translator. | ||
| 4 | |||
| 5 | Verifies that: | ||
| 6 | - Constant scalar ALU operations (s_and_b32, s_or_b32, s_xor_b32, s_not_b32, s_lshl_b32, s_lshr_b32, s_mul_i32) | ||
| 7 | fold at translate time without emitting runtime SPIR-V instructions. | ||
| 8 | - s_buffer_load with known descriptor limits folds limit calculations at translate time, eliminating | ||
| 9 | OpBitFieldUExtract, OpIMul, OpIEqual, and OpSelect. | ||
| 10 | - In-bounds s_buffer_load dwords emit direct straight-line OpLoad without OpSelectionMerge, OpBranchConditional, or OpPhi. | ||
| 11 | - Out-of-bounds s_buffer_load dwords emit constant zero without memory load or branch. | ||
| 12 | - Constant SGPR offsets in scalar loads fold directly into the 64-bit address calculation. | ||
| 13 | """ | ||
| 14 | import os | ||
| 15 | import struct | ||
| 16 | import sys | ||
| 17 | import tempfile | ||
| 18 | import unittest | ||
| 19 | import warnings | ||
| 20 | |||
| 21 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 22 | ROOT = os.path.dirname(os.path.dirname(HERE)) | ||
| 23 | TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") | ||
| 24 | |||
| 25 | sys.dont_write_bytecode = True | ||
| 26 | if TOOLS_DIR not in sys.path: | ||
| 27 | sys.path.insert(0, TOOLS_DIR) | ||
| 28 | if HERE not in sys.path: | ||
| 29 | sys.path.insert(0, HERE) | ||
| 30 | |||
| 31 | import rdna2spirv # noqa: E402 | ||
| 32 | from shader_ir import parse_line # noqa: E402 | ||
| 33 | import spirv_mini_interp as si # noqa: E402 | ||
| 34 | |||
| 35 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 36 | |||
| 37 | |||
| 38 | class ScalarAluAndSmemFoldingTests(unittest.TestCase): | ||
| 39 | def translate_lines(self, lines: list[str]) -> str: | ||
| 40 | body = "\n".join("\t" + line for line in lines) | ||
| 41 | asm = f"; scalar_fold_test\n{body}\n\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" | ||
| 42 | with tempfile.TemporaryDirectory() as tmp: | ||
| 43 | d_dir = os.path.join(tmp, "disasm") | ||
| 44 | os.mkdir(d_dir) | ||
| 45 | s_path = os.path.join(d_dir, "ps_scalar.s") | ||
| 46 | with open(s_path, "w", encoding="utf-8") as f: | ||
| 47 | f.write(asm) | ||
| 48 | with open(os.path.join(tmp, "ps_scalar.dxbc"), "wb") as f: | ||
| 49 | f.write(STUB_DXBC) | ||
| 50 | with warnings.catch_warnings(): | ||
| 51 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 52 | return rdna2spirv.translate(s_path) | ||
| 53 | |||
| 54 | def test_s_and_b32_and_s_or_b32_constant_folding(self): | ||
| 55 | # Bitwise s_and_b32 / s_or_b32 fold constants without runtime bitwise instructions | ||
| 56 | lines = [ | ||
| 57 | "s_and_b32 s4, 0xFF00, 0x0FF0", | ||
| 58 | "v_mov_b32 v0, s4", | ||
| 59 | ] | ||
| 60 | spv = self.translate_lines(lines) | ||
| 61 | self.assertNotIn("OpBitwiseAnd %uint", spv) | ||
| 62 | res = si.run_fragment(spv)["%out_mrt0"][0] | ||
| 63 | self.assertEqual(res, 0x0F00) | ||
| 64 | |||
| 65 | lines_or = [ | ||
| 66 | "s_or_b32 s4, 0xF0, 0x0F", | ||
| 67 | "v_mov_b32 v0, s4", | ||
| 68 | ] | ||
| 69 | spv_or = self.translate_lines(lines_or) | ||
| 70 | self.assertNotIn("OpBitwiseOr %uint", spv_or) | ||
| 71 | res_or = si.run_fragment(spv_or)["%out_mrt0"][0] | ||
| 72 | self.assertEqual(res_or, 0xFF) | ||
| 73 | |||
| 74 | def test_s_xor_b32_and_s_not_b32_constant_folding(self): | ||
| 75 | # Bitwise s_xor_b32 and s_not_b32 fold constants | ||
| 76 | lines_xor = [ | ||
| 77 | "s_xor_b32 s4, 0xAAAA5555, 0x5555AAAA", | ||
| 78 | "v_mov_b32 v0, s4", | ||
| 79 | ] | ||
| 80 | spv_xor = self.translate_lines(lines_xor) | ||
| 81 | self.assertNotIn("OpBitwiseXor %uint", spv_xor) | ||
| 82 | res_xor = si.run_fragment(spv_xor)["%out_mrt0"][0] | ||
| 83 | self.assertEqual(res_xor, 0xFFFFFFFF) | ||
| 84 | |||
| 85 | lines_not = [ | ||
| 86 | "s_not_b32 s4, 0", | ||
| 87 | "v_mov_b32 v0, s4", | ||
| 88 | ] | ||
| 89 | spv_not = self.translate_lines(lines_not) | ||
| 90 | self.assertNotIn("OpNot %uint", spv_not) | ||
| 91 | res_not = si.run_fragment(spv_not)["%out_mrt0"][0] | ||
| 92 | self.assertEqual(res_not, 0xFFFFFFFF) | ||
| 93 | |||
| 94 | def test_s_lshl_b32_s_lshr_b32_s_mul_i32_folding(self): | ||
| 95 | # Shifts and multiply fold constants | ||
| 96 | lines_shl = [ | ||
| 97 | "s_lshl_b32 s4, 3, 4", # 3 << 4 = 48 | ||
| 98 | "v_mov_b32 v0, s4", | ||
| 99 | ] | ||
| 100 | spv_shl = self.translate_lines(lines_shl) | ||
| 101 | self.assertNotIn("OpShiftLeftLogical %uint", spv_shl) | ||
| 102 | res_shl = si.run_fragment(spv_shl)["%out_mrt0"][0] | ||
| 103 | self.assertEqual(res_shl, 48) | ||
| 104 | |||
| 105 | lines_mul = [ | ||
| 106 | "s_mul_i32 s4, 6, 7", | ||
| 107 | "v_mov_b32 v0, s4", | ||
| 108 | ] | ||
| 109 | spv_mul = self.translate_lines(lines_mul) | ||
| 110 | self.assertNotIn("OpIMul %uint", spv_mul) | ||
| 111 | res_mul = si.run_fragment(spv_mul)["%out_mrt0"][0] | ||
| 112 | self.assertEqual(res_mul, 42) | ||
| 113 | |||
| 114 | lines_shr = [ | ||
| 115 | "s_lshr_b32 s4, 96, 3", # 96 >> 3 = 12 | ||
| 116 | "v_mov_b32 v0, s4", | ||
| 117 | ] | ||
| 118 | spv_shr = self.translate_lines(lines_shr) | ||
| 119 | self.assertNotIn("OpShiftRightLogical %uint", spv_shr) | ||
| 120 | res_shr = si.run_fragment(spv_shr)["%out_mrt0"][0] | ||
| 121 | self.assertEqual(res_shr, 12) | ||
| 122 | |||
| 123 | def test_s_buffer_load_in_bounds_eliminates_branch_diamond(self): | ||
| 124 | # When V# limits and offset are constants with offset in bounds: | ||
| 125 | # eliminates limit setup and conditional branch diamond. | ||
| 126 | g = rdna2spirv.Gen("ps") | ||
| 127 | # Load literal V# into s[4:7]: | ||
| 128 | # s4: base lo, s5: base hi (0) + stride 4 in bits 16..29 (0x00040000) | ||
| 129 | # s6: num_records = 256 (limit = 256 * 4 = 1024 bytes) | ||
| 130 | # s7: word3 | ||
| 131 | g.sgpr_imm[4] = 0x1000 | ||
| 132 | g.sgpr_imm[5] = 0x00040000 | ||
| 133 | g.sgpr_imm[6] = 256 | ||
| 134 | g.sgpr_imm[7] = 0x31000FAC | ||
| 135 | |||
| 136 | ins = parse_line("s_buffer_load_dword s0, s[4:7], 0x10") | ||
| 137 | g.scalar_load(ins["op"], ins["args"], ins["mods"]) | ||
| 138 | text = "\n".join(g.body) | ||
| 139 | |||
| 140 | # No dynamic limit calculation instructions | ||
| 141 | self.assertNotIn("OpBitFieldUExtract %uint", text) | ||
| 142 | self.assertNotIn("OpIMul %ulong", text) | ||
| 143 | self.assertNotIn("OpSelect %ulong", text) | ||
| 144 | |||
| 145 | # In bounds (0x10 + 4 = 20 <= 1024): no branch or phi | ||
| 146 | self.assertNotIn("OpBranchConditional", text) | ||
| 147 | self.assertNotIn("OpSelectionMerge", text) | ||
| 148 | self.assertNotIn("OpPhi", text) | ||
| 149 | |||
| 150 | # Emits direct aligned load | ||
| 151 | self.assertIn("OpAccessChain %_ptr_PSB_uint", text) | ||
| 152 | self.assertIn("OpLoad %uint", text) | ||
| 153 | |||
| 154 | def test_s_buffer_load_out_of_bounds_emits_constant_zero(self): | ||
| 155 | # When V# limits and offset are constants with offset out of bounds: | ||
| 156 | # emits constant 0 without memory load or branches. | ||
| 157 | g = rdna2spirv.Gen("ps") | ||
| 158 | g.sgpr_imm[4] = 0x1000 | ||
| 159 | g.sgpr_imm[5] = 0x00040000 | ||
| 160 | g.sgpr_imm[6] = 16 # limit = 16 * 4 = 64 bytes | ||
| 161 | g.sgpr_imm[7] = 0x31000FAC | ||
| 162 | |||
| 163 | ins = parse_line("s_buffer_load_dword s0, s[4:7], 0x80") # offset 128 > limit 64 | ||
| 164 | g.scalar_load(ins["op"], ins["args"], ins["mods"]) | ||
| 165 | text = "\n".join(g.body) | ||
| 166 | |||
| 167 | # No branch or PSB memory load emitted for out of bounds | ||
| 168 | self.assertNotIn("OpBranchConditional", text) | ||
| 169 | self.assertNotIn("OpSelectionMerge", text) | ||
| 170 | self.assertNotIn("OpPhi", text) | ||
| 171 | self.assertNotIn("OpAccessChain %_ptr_PSB_uint", text) | ||
| 172 | self.assertNotIn("Aligned 4", text) | ||
| 173 | |||
| 174 | # Directly stores %c0 to sgpr 0 | ||
| 175 | self.assertTrue(any(ln.strip().startswith("OpStore %t") and ln.strip().endswith(g.cu(0)) for ln in g.body)) | ||
| 176 | |||
| 177 | def test_s_buffer_load_sgpr_offset_folded_from_sgpr_imm(self): | ||
| 178 | # When offset is passed via SGPR holding a known literal: | ||
| 179 | # folded into constant offset without runtime OpBitwiseAnd / OpUConvert on the offset register. | ||
| 180 | g = rdna2spirv.Gen("ps") | ||
| 181 | g.sgpr_imm[2] = 0x20 # s2 = 32 | ||
| 182 | ins = parse_line("s_load_dword s0, s[4:5], s2") | ||
| 183 | g.scalar_load(ins["op"], ins["args"], ins["mods"]) | ||
| 184 | text = "\n".join(g.body) | ||
| 185 | |||
| 186 | # The offset is folded into constant ulong %cl20 | ||
| 187 | self.assertIn("%cl20", text) | ||
| 188 | # Only base lo is masked with %cfffffffc; offset s2 is not dynamically masked | ||
| 189 | self.assertEqual(text.count("%cfffffffc"), 1) | ||
| 190 | |||
| 191 | |||
| 192 | if __name__ == "__main__": | ||
| 193 | unittest.main() | ||
diff --git a/tests/semantic/test_scalar_noop_waitcnt.py b/tests/semantic/test_scalar_noop_waitcnt.py new file mode 100644 index 000000000..67b805220 --- /dev/null +++ b/tests/semantic/test_scalar_noop_waitcnt.py | |||
| @@ -0,0 +1,636 @@ | |||
| 1 | """Semantic and translation tests for RDNA2 scalar no-op, hint, waitcnt, and mode instructions. | ||
| 2 | |||
| 3 | Covers the 11 named scalar instructions and their syntax variants in tools/shader_ir.py and tools/rdna2spirv.py: | ||
| 4 | * In rdna2spirv.NOOPS (emits no SPIR-V instructions, preserves VGPRs, SGPRs, VCC, SCC, and EXEC): | ||
| 5 | s_clause, s_delay_alu (RDNA3 hint kept in NOOPS), s_inst_prefetch, s_setprio, s_sleep, | ||
| 6 | s_waitcnt_depctr, s_waitcnt_expcnt, s_waitcnt_lgkmcnt, s_waitcnt_vmcnt, | ||
| 7 | plus the sibling wait/no-op forms s_waitcnt, s_waitcnt_vscnt, s_nop, and v_nop. | ||
| 8 | * Refused mode mnemonics in rdna2spirv._insn: | ||
| 9 | s_denorm_mode and s_round_mode raise Unsupported ("MODE is modelled through s_setreg only"); | ||
| 10 | valid MODE.FP_ROUND[3:2] writes go through s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 0|3, | ||
| 11 | which updates %mode_r16 only and leaves VGPRs, SGPRs, VCC, SCC, and EXEC intact, while | ||
| 12 | non-MODE s_setreg* writes emit nothing and other MODE writes stay Unsupported. | ||
| 13 | |||
| 14 | Standard library only (runs with python -I); hand-written RDNA2 listings, no GPU or game data. | ||
| 15 | """ | ||
| 16 | from __future__ import annotations | ||
| 17 | |||
| 18 | import gc | ||
| 19 | import os | ||
| 20 | import struct | ||
| 21 | import sys | ||
| 22 | import tempfile | ||
| 23 | import unittest | ||
| 24 | import warnings | ||
| 25 | |||
| 26 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 27 | ROOT = os.path.dirname(os.path.dirname(HERE)) | ||
| 28 | TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") | ||
| 29 | |||
| 30 | sys.dont_write_bytecode = True | ||
| 31 | for _p in (HERE, TOOLS_DIR): | ||
| 32 | if _p not in sys.path: | ||
| 33 | sys.path.insert(0, _p) | ||
| 34 | |||
| 35 | import rdna2spirv # noqa: E402 | ||
| 36 | import shader_ir # noqa: E402 | ||
| 37 | import spirv_mini_interp as si # noqa: E402 | ||
| 38 | |||
| 39 | M32 = 0xFFFFFFFF | ||
| 40 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 41 | # Raw buffer V# (OOB_SELECT 3, stride 0): any dword offset is in bounds in spirv_mini_interp. | ||
| 42 | VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] | ||
| 43 | |||
| 44 | # Handled scalar no-op/hint/waitcnt instructions and explicit syntax variants accepted by shader_ir.py. | ||
| 45 | SCALAR_NOOP_VARIANTS = [ | ||
| 46 | "s_clause 0x1", | ||
| 47 | "s_clause 0", | ||
| 48 | "s_clause 15", | ||
| 49 | "s_delay_alu 0", | ||
| 50 | "s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)", | ||
| 51 | "s_delay_alu instid0(VALU_DEP_2)", | ||
| 52 | "s_inst_prefetch 0x0", | ||
| 53 | "s_inst_prefetch 0x1", | ||
| 54 | "s_inst_prefetch -1", | ||
| 55 | "s_setprio 0x0", | ||
| 56 | "s_setprio 0x2", | ||
| 57 | "s_setprio 3", | ||
| 58 | "s_sleep 0x0", | ||
| 59 | "s_sleep 0x1", | ||
| 60 | "s_sleep 7", | ||
| 61 | "s_waitcnt_depctr 0xffe3", | ||
| 62 | "s_waitcnt_depctr 0x0", | ||
| 63 | "s_waitcnt_depctr depctr_vm_vsrc(0) depctr_va_sdst(0)", | ||
| 64 | "s_waitcnt_depctr depctr_hold_cnt(0) depctr_sa_sdst(0) depctr_va_vdst(0)", | ||
| 65 | "s_waitcnt_expcnt null, 0x0", | ||
| 66 | "s_waitcnt_expcnt null, 0x7", | ||
| 67 | "s_waitcnt_expcnt 0x0", | ||
| 68 | "s_waitcnt_lgkmcnt null, 0x0", | ||
| 69 | "s_waitcnt_lgkmcnt null, 0x3f", | ||
| 70 | "s_waitcnt_lgkmcnt 0x0", | ||
| 71 | "s_waitcnt_vmcnt null, 0x0", | ||
| 72 | "s_waitcnt_vmcnt null, 0x3f", | ||
| 73 | "s_waitcnt_vmcnt 0x0", | ||
| 74 | # Sibling wait/no-op and non-MODE setreg forms handled alongside them in NOOPS / mode_write. | ||
| 75 | "s_waitcnt vmcnt(0)", | ||
| 76 | "s_waitcnt expcnt(0)", | ||
| 77 | "s_waitcnt lgkmcnt(0)", | ||
| 78 | "s_waitcnt vmcnt(1) lgkmcnt(2)", | ||
| 79 | "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)", | ||
| 80 | "s_waitcnt 0", | ||
| 81 | "s_waitcnt_vscnt null, 0x0", | ||
| 82 | "s_waitcnt_vscnt vscnt(0)", | ||
| 83 | "s_nop 0", | ||
| 84 | "s_nop 0x7", | ||
| 85 | "v_nop", | ||
| 86 | "v_nop_e32", | ||
| 87 | "v_nop_e64", | ||
| 88 | "s_setreg_imm32_b32 hwreg(HW_REG_FLAT_SCR_LO, 0, 32), 0", | ||
| 89 | "s_setreg_b32 hwreg(HW_REG_IB_STS), s2", | ||
| 90 | ] | ||
| 91 | |||
| 92 | # Representative instruction per handled mnemonic from the 9-op scalar NOOPS group + s_waitcnt / s_nop. | ||
| 93 | REPRESENTATIVE_NOOPS = [ | ||
| 94 | "s_clause 0x1", | ||
| 95 | "s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)", | ||
| 96 | "s_inst_prefetch 0x0", | ||
| 97 | "s_setprio 0x2", | ||
| 98 | "s_sleep 0x1", | ||
| 99 | "s_waitcnt_depctr 0xffe3", | ||
| 100 | "s_waitcnt_expcnt null, 0x0", | ||
| 101 | "s_waitcnt_lgkmcnt null, 0x0", | ||
| 102 | "s_waitcnt_vmcnt null, 0x0", | ||
| 103 | "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)", | ||
| 104 | "s_waitcnt_vscnt null, 0x0", | ||
| 105 | "s_nop 0", | ||
| 106 | ] | ||
| 107 | |||
| 108 | REFUSED_MODE_VARIANTS = [ | ||
| 109 | "s_denorm_mode 0x3", | ||
| 110 | "s_denorm_mode 0", | ||
| 111 | "s_round_mode 0x3", | ||
| 112 | "s_round_mode 0", | ||
| 113 | ] | ||
| 114 | |||
| 115 | MODELLED_MODE_VARIANTS = [ | ||
| 116 | ("s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 0", "%c0"), | ||
| 117 | ("s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3", "%c3"), | ||
| 118 | ] | ||
| 119 | |||
| 120 | _TMP_DIR: tempfile.TemporaryDirectory | None = None | ||
| 121 | |||
| 122 | |||
| 123 | def setUpModule() -> None: | ||
| 124 | global _TMP_DIR | ||
| 125 | _TMP_DIR = tempfile.TemporaryDirectory() | ||
| 126 | os.mkdir(os.path.join(_TMP_DIR.name, "disasm")) | ||
| 127 | os.mkdir(os.path.join(_TMP_DIR.name, "fssm")) | ||
| 128 | |||
| 129 | |||
| 130 | def tearDownModule() -> None: | ||
| 131 | global _TMP_DIR | ||
| 132 | if _TMP_DIR is not None: | ||
| 133 | gc.collect() | ||
| 134 | _TMP_DIR.cleanup() | ||
| 135 | _TMP_DIR = None | ||
| 136 | |||
| 137 | |||
| 138 | def _ensure_dir() -> str: | ||
| 139 | if _TMP_DIR is None: | ||
| 140 | setUpModule() | ||
| 141 | assert _TMP_DIR is not None | ||
| 142 | return _TMP_DIR.name | ||
| 143 | |||
| 144 | |||
| 145 | def make_fssm(threads: int, user_sgprs: int = 4) -> bytes: | ||
| 146 | """Synthetic compute FSSM header: user_sgprs USER_SGPRs, TGID_X_EN=0, TIDIG_COMP_CNT=0, size=(threads,1,1).""" | ||
| 147 | blob = bytearray(0x148) | ||
| 148 | rsrc2 = (user_sgprs & 31) << 1 | ||
| 149 | struct.pack_into("<4I", blob, 0x138, rsrc2, threads, 1, 1) | ||
| 150 | return bytes(blob) | ||
| 151 | |||
| 152 | |||
| 153 | def translate_ps(name: str, lines: list[str]) -> str: | ||
| 154 | root = _ensure_dir() | ||
| 155 | src = os.path.join(root, "disasm", name + ".s") | ||
| 156 | with open(src, "w", encoding="utf-8", newline="\n") as f: | ||
| 157 | f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in lines)) | ||
| 158 | with open(os.path.join(root, name + ".dxbc"), "wb") as f: | ||
| 159 | f.write(STUB_DXBC) | ||
| 160 | with warnings.catch_warnings(): | ||
| 161 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 162 | return rdna2spirv.translate(src) | ||
| 163 | |||
| 164 | |||
| 165 | def translate_cs(name: str, lines: list[str], threads: int) -> str: | ||
| 166 | root = _ensure_dir() | ||
| 167 | src = os.path.join(root, "disasm", name + ".s") | ||
| 168 | with open(src, "w", encoding="utf-8", newline="\n") as f: | ||
| 169 | f.write(f"; {name}\n" + "".join(f"\t{ln}\n" for ln in lines)) | ||
| 170 | with open(os.path.join(root, name + ".dxbc"), "wb") as f: | ||
| 171 | f.write(STUB_DXBC) | ||
| 172 | with open(os.path.join(root, "fssm", name + ".fssm"), "wb") as f: | ||
| 173 | f.write(make_fssm(threads)) | ||
| 174 | with warnings.catch_warnings(): | ||
| 175 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 176 | return rdna2spirv.translate(src) | ||
| 177 | |||
| 178 | |||
| 179 | def ps_program(middle: list[str], *, scc_one: bool = True, vcc_one: bool = True, | ||
| 180 | exec_lo: int = 0xAAAA5555, add_k: int = 0x10) -> list[str]: | ||
| 181 | """Synthetic PS testing VGPRs, SGPRs, SCC, VCC, and EXEC across interleaved arithmetic and `middle`.""" | ||
| 182 | s_rhs = 5 if scc_one else 0 | ||
| 183 | s_lhs = 0xFFFFFFFF if scc_one else 0x12340000 | ||
| 184 | cmp_val = (0x11112222 + add_k) & M32 if vcc_one else 0x00000000 | ||
| 185 | return [ | ||
| 186 | "v_mov_b32 v0, 0x11112222", | ||
| 187 | "v_mov_b32 v1, 0x33334444", | ||
| 188 | "v_mov_b32 v2, 0x55556666", | ||
| 189 | "v_mov_b32 v3, 0x77778888", | ||
| 190 | f"s_mov_b32 s2, {s_lhs:#x}", | ||
| 191 | f"s_mov_b32 s3, {s_rhs:#x}", | ||
| 192 | "s_add_u32 s4, s2, s3", # SCC = 1 iff s_lhs + s_rhs overflows 32 bits | ||
| 193 | f"v_add_nc_u32 v0, v0, {add_k:#x}", | ||
| 194 | f"v_cmp_eq_u32 vcc_lo, v0, {cmp_val:#x}", # VCC = 1 iff vcc_one | ||
| 195 | f"s_mov_b32 exec_lo, {exec_lo:#x}", | ||
| 196 | *middle, | ||
| 197 | "s_cselect_b32 s5, 0x10000001, 0x20000002", # reads SCC | ||
| 198 | "s_add_u32 s6, s4, s5", # reads SGPR s4 and selected s5 | ||
| 199 | "v_cndmask_b32 v1, 0x99990000, v1, vcc_lo", # reads VCC (and VGPR v1 when VCC=1) | ||
| 200 | "v_add_nc_u32 v2, v2, s6", # reads EXEC, VGPR v2, SGPR s6 | ||
| 201 | "exp mrt0 v0, v1, v2, v3 done vm", | ||
| 202 | "s_endpgm", | ||
| 203 | ] | ||
| 204 | |||
| 205 | |||
| 206 | def expected_ps_mrt0(*, scc_one: bool = True, vcc_one: bool = True, | ||
| 207 | exec_lo: int = 0xAAAA5555, add_k: int = 0x10) -> tuple[int, int, int, int]: | ||
| 208 | """Plain-Python reference for ps_program().""" | ||
| 209 | active = bool(exec_lo & 1) | ||
| 210 | s_lhs = 0xFFFFFFFF if scc_one else 0x12340000 | ||
| 211 | s_rhs = 5 if scc_one else 0 | ||
| 212 | s4 = (s_lhs + s_rhs) & M32 | ||
| 213 | scc = (s_lhs + s_rhs) > M32 | ||
| 214 | v0 = ((0x11112222 + add_k) & M32) # executed while EXEC=1 initially | ||
| 215 | vcc = vcc_one # evaluated while EXEC=1 initially | ||
| 216 | s5 = 0x10000001 if scc else 0x20000002 | ||
| 217 | s6 = (s4 + s5) & M32 | ||
| 218 | v1 = (0x33334444 if vcc else 0x99990000) if active else 0x33334444 | ||
| 219 | v2 = ((0x55556666 + s6) & M32) if active else 0x55556666 | ||
| 220 | v3 = 0x77778888 | ||
| 221 | if not active: | ||
| 222 | return (0, 0, 0, 0) | ||
| 223 | return (v0, v1, v2, v3) | ||
| 224 | |||
| 225 | |||
| 226 | def cs_program(middle: list[str], *, wave64: bool, scc_one: bool = True, | ||
| 227 | exec_lo: int = 0xA5A55A5A, exec_hi: int = 0x3C3C6969) -> list[str]: | ||
| 228 | """Synthetic wave32/wave64 CS checking VGPRs, SGPRs, SCC, VCC, and EXEC across all lanes.""" | ||
| 229 | s_lhs = 0xFFFFFFFF if scc_one else 0x10203040 | ||
| 230 | s_rhs = 3 if scc_one else 1 | ||
| 231 | if wave64: | ||
| 232 | lane_setup = [ | ||
| 233 | "s_mov_b64 exec, -1", | ||
| 234 | "v_mbcnt_lo_u32_b32 v0, -1, 0", | ||
| 235 | "v_mbcnt_hi_u32_b32 v0, -1, v0", | ||
| 236 | ] | ||
| 237 | vcc_cmp = "v_cmp_eq_u32 vcc, v4, 0" | ||
| 238 | set_exec = [f"s_mov_b32 exec_lo, {exec_lo:#x}", f"s_mov_b32 exec_hi, {exec_hi:#x}"] | ||
| 239 | reset_exec = "s_mov_b64 exec, -1" | ||
| 240 | vcc_cnd = "v_cndmask_b32 v2, 0x99990000, v2, vcc" | ||
| 241 | else: | ||
| 242 | lane_setup = [] # v0 is seeded directly from LocalInvocationId.x | ||
| 243 | vcc_cmp = "v_cmp_eq_u32 vcc_lo, v4, 0" | ||
| 244 | set_exec = [f"s_mov_b32 exec_lo, {exec_lo:#x}"] | ||
| 245 | reset_exec = "s_mov_b32 exec_lo, -1" | ||
| 246 | vcc_cnd = "v_cndmask_b32 v2, 0x99990000, v2, vcc_lo" | ||
| 247 | |||
| 248 | return [ | ||
| 249 | *lane_setup, | ||
| 250 | "v_mov_b32 v1, v0", | ||
| 251 | "v_add_nc_u32 v1, v1, 10", | ||
| 252 | "v_mov_b32 v2, 0x77770000", | ||
| 253 | "v_add_nc_u32 v2, v2, v0", | ||
| 254 | "v_mov_b32 v3, 0x1000", | ||
| 255 | "v_and_b32 v4, v0, 1", | ||
| 256 | vcc_cmp, # even lanes: VCC = 1; odd lanes: VCC = 0 | ||
| 257 | "s_mov_b32 s8, 0x01020304", | ||
| 258 | "s_mov_b32 s9, 0x55667788", | ||
| 259 | f"s_mov_b32 s10, {s_lhs:#x}", | ||
| 260 | f"s_add_u32 s11, s10, {s_rhs:#x}", # SCC = 1 iff scc_one | ||
| 261 | *set_exec, | ||
| 262 | *middle, | ||
| 263 | "v_add_nc_u32 v1, v1, 0x100", # updates v1 only in lanes where EXEC=1 | ||
| 264 | "s_cselect_b32 s12, 0x10000, 0x20000", # reads SCC | ||
| 265 | reset_exec, | ||
| 266 | vcc_cnd, # reads VCC across all lanes (even keeps v2, odd gets 0x99990000) | ||
| 267 | "v_add_nc_u32 v3, v3, s8", # reads SGPR s8 | ||
| 268 | "v_add_nc_u32 v3, v3, s12", # reads s12 (SCC outcome) | ||
| 269 | "v_add_nc_u32 v3, v3, s11", # reads s11 (s_add_u32 sum) | ||
| 270 | "v_mov_b32 v4, s9", # reads SGPR s9 | ||
| 271 | "v_lshlrev_b32 v5, 4, v0", # byte offset = 16 * lane | ||
| 272 | "buffer_store_dwordx4 v[1:4], v5, s[0:3], 0 offen", | ||
| 273 | "s_endpgm", | ||
| 274 | ] | ||
| 275 | |||
| 276 | |||
| 277 | def expected_cs_words(lanes: int, *, scc_one: bool = True, | ||
| 278 | exec_lo: int = 0xA5A55A5A, exec_hi: int = 0x3C3C6969) -> list[tuple[int, int, int, int]]: | ||
| 279 | """Plain-Python reference for cs_program().""" | ||
| 280 | s_lhs = 0xFFFFFFFF if scc_one else 0x10203040 | ||
| 281 | s_rhs = 3 if scc_one else 1 | ||
| 282 | s11 = (s_lhs + s_rhs) & M32 | ||
| 283 | s12 = 0x10000 if ((s_lhs + s_rhs) > M32) else 0x20000 | ||
| 284 | exec_mask = (exec_hi << 32) | exec_lo | ||
| 285 | out = [] | ||
| 286 | for lane in range(lanes): | ||
| 287 | active = bool((exec_mask >> lane) & 1) | ||
| 288 | w0 = (lane + 10 + (0x100 if active else 0)) & M32 | ||
| 289 | w1 = (0x77770000 + lane) if (lane % 2 == 0) else 0x99990000 | ||
| 290 | w2 = (0x1000 + 0x01020304 + s12 + s11) & M32 | ||
| 291 | w3 = 0x55667788 | ||
| 292 | out.append((w0, w1, w2, w3)) | ||
| 293 | return out | ||
| 294 | |||
| 295 | |||
| 296 | def run_cs(spv: str, lanes: int) -> list[tuple[int, int, int, int]]: | ||
| 297 | mem = si.run_workgroup( | ||
| 298 | spv, lanes, lanes, | ||
| 299 | inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i}, | ||
| 300 | push_constants=VSHARP + [0] * 28, | ||
| 301 | memory={}, | ||
| 302 | ) | ||
| 303 | return [tuple(mem[16 * lane + 4 * c] for c in range(4)) for lane in range(lanes)] | ||
| 304 | |||
| 305 | |||
| 306 | class ScalarNoopWaitcntParsingTests(unittest.TestCase): | ||
| 307 | """Exact syntax and operand parsing in tools/shader_ir.py for all 11 scalar ops and variants.""" | ||
| 308 | |||
| 309 | def test_parse_all_scalar_noop_waitcnt_and_mode_forms(self): | ||
| 310 | cases = [ | ||
| 311 | ("s_clause 0x1", "s_clause", [{"k": "imm", "v": 1}]), | ||
| 312 | ("s_delay_alu 0", "s_delay_alu", [{"k": "imm", "v": 0}]), | ||
| 313 | ( | ||
| 314 | "s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)", | ||
| 315 | "s_delay_alu", | ||
| 316 | [{"k": "special", "t": "instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)"}], | ||
| 317 | ), | ||
| 318 | ("s_denorm_mode 0x3", "s_denorm_mode", [{"k": "imm", "v": 3}]), | ||
| 319 | ("s_inst_prefetch 0x0", "s_inst_prefetch", [{"k": "imm", "v": 0}]), | ||
| 320 | ("s_inst_prefetch -1", "s_inst_prefetch", [{"k": "imm", "v": -1}]), | ||
| 321 | ("s_round_mode 0x3", "s_round_mode", [{"k": "imm", "v": 3}]), | ||
| 322 | ("s_setprio 0x2", "s_setprio", [{"k": "imm", "v": 2}]), | ||
| 323 | ("s_sleep 0x1", "s_sleep", [{"k": "imm", "v": 1}]), | ||
| 324 | ("s_waitcnt_depctr 0xffe3", "s_waitcnt_depctr", [{"k": "imm", "v": 0xFFE3}]), | ||
| 325 | ( | ||
| 326 | "s_waitcnt_depctr depctr_vm_vsrc(0) depctr_va_sdst(0)", | ||
| 327 | "s_waitcnt_depctr", | ||
| 328 | [{"k": "special", "t": "depctr_vm_vsrc(0)"}, {"k": "special", "t": "depctr_va_sdst(0)"}], | ||
| 329 | ), | ||
| 330 | ( | ||
| 331 | "s_waitcnt_expcnt null, 0x0", | ||
| 332 | "s_waitcnt_expcnt", | ||
| 333 | [{"k": "special", "t": "null", "neg": False, "abs": False}, {"k": "imm", "v": 0}], | ||
| 334 | ), | ||
| 335 | ( | ||
| 336 | "s_waitcnt_lgkmcnt null, 0x3f", | ||
| 337 | "s_waitcnt_lgkmcnt", | ||
| 338 | [{"k": "special", "t": "null", "neg": False, "abs": False}, {"k": "imm", "v": 0x3F}], | ||
| 339 | ), | ||
| 340 | ( | ||
| 341 | "s_waitcnt_vmcnt null, 0x0", | ||
| 342 | "s_waitcnt_vmcnt", | ||
| 343 | [{"k": "special", "t": "null", "neg": False, "abs": False}, {"k": "imm", "v": 0}], | ||
| 344 | ), | ||
| 345 | ( | ||
| 346 | "s_waitcnt_vscnt null, 0x0", | ||
| 347 | "s_waitcnt_vscnt", | ||
| 348 | [{"k": "special", "t": "null", "neg": False, "abs": False}, {"k": "imm", "v": 0}], | ||
| 349 | ), | ||
| 350 | ("s_waitcnt vmcnt(0)", "s_waitcnt", [{"k": "special", "t": "vmcnt(0)"}]), | ||
| 351 | ("s_waitcnt expcnt(0)", "s_waitcnt", [{"k": "special", "t": "expcnt(0)"}]), | ||
| 352 | ("s_waitcnt lgkmcnt(0)", "s_waitcnt", [{"k": "special", "t": "lgkmcnt(0)"}]), | ||
| 353 | ( | ||
| 354 | "s_waitcnt vmcnt(1) lgkmcnt(2)", | ||
| 355 | "s_waitcnt", | ||
| 356 | [{"k": "special", "t": "vmcnt(1)"}, {"k": "special", "t": "lgkmcnt(2)"}], | ||
| 357 | ), | ||
| 358 | ( | ||
| 359 | "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)", | ||
| 360 | "s_waitcnt", | ||
| 361 | [{"k": "special", "t": "vmcnt(0) expcnt(0) lgkmcnt(0)"}], | ||
| 362 | ), | ||
| 363 | ("s_waitcnt 0", "s_waitcnt", [{"k": "imm", "v": 0}]), | ||
| 364 | ( | ||
| 365 | "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 3", | ||
| 366 | "s_setreg_imm32_b32", | ||
| 367 | [{"k": "special", "t": "hwreg(HW_REG_MODE, 2, 2)"}, {"k": "imm", "v": 3}], | ||
| 368 | ), | ||
| 369 | ("s_nop 0", "s_nop", [{"k": "imm", "v": 0}]), | ||
| 370 | ("v_nop", "v_nop", []), | ||
| 371 | ] | ||
| 372 | for text, want_op, want_args in cases: | ||
| 373 | with self.subTest(line=text): | ||
| 374 | parsed = shader_ir.parse_line("\t" + text) | ||
| 375 | self.assertIsNotNone(parsed) | ||
| 376 | self.assertEqual(parsed["op"], want_op) | ||
| 377 | self.assertEqual(parsed["args"], want_args) | ||
| 378 | self.assertEqual(parsed["mods"], []) | ||
| 379 | self.assertTrue(all(arg["k"] != "raw" for arg in parsed["args"])) | ||
| 380 | |||
| 381 | |||
| 382 | class PixelShaderNoopWaitcntTests(unittest.TestCase): | ||
| 383 | """PS translation and spirv_mini_interp execution across all handled NOOPS and waitcnt variants.""" | ||
| 384 | |||
| 385 | def test_variants_emit_no_extra_spirv_and_preserve_state_active_scc1_vcc1(self): | ||
| 386 | baseline = translate_ps("ps_noop_base_11", ps_program([], scc_one=True, vcc_one=True)) | ||
| 387 | want = expected_ps_mrt0(scc_one=True, vcc_one=True) | ||
| 388 | self.assertEqual(want, (0x11112232, 0x33334444, 0x6555666B, 0x77778888)) | ||
| 389 | self.assertEqual(tuple(si.run_fragment(baseline, inputs={"%sg_lane": 0})["%out_mrt0"]), want) | ||
| 390 | self.assertNotIn("OpControlBarrier", baseline) | ||
| 391 | self.assertNotIn("OpMemoryBarrier", baseline) | ||
| 392 | |||
| 393 | for variant in SCALAR_NOOP_VARIANTS: | ||
| 394 | with self.subTest(insn=variant): | ||
| 395 | spv = translate_ps("ps_noop_var", ps_program([variant], scc_one=True, vcc_one=True)) | ||
| 396 | self.assertEqual(spv, baseline, f"{variant} emitted unexpected SPIR-V operations") | ||
| 397 | self.assertEqual(tuple(si.run_fragment(spv, inputs={"%sg_lane": 0})["%out_mrt0"]), want) | ||
| 398 | |||
| 399 | def test_variants_preserve_scc0_and_vcc0(self): | ||
| 400 | baseline = translate_ps("ps_noop_base_00", ps_program([], scc_one=False, vcc_one=False)) | ||
| 401 | want = expected_ps_mrt0(scc_one=False, vcc_one=False) | ||
| 402 | self.assertEqual(want, (0x11112232, 0x99990000, 0x87896668, 0x77778888)) | ||
| 403 | self.assertEqual(tuple(si.run_fragment(baseline, inputs={"%sg_lane": 0})["%out_mrt0"]), want) | ||
| 404 | |||
| 405 | for variant in SCALAR_NOOP_VARIANTS: | ||
| 406 | with self.subTest(insn=variant): | ||
| 407 | spv = translate_ps("ps_noop_var00", ps_program([variant], scc_one=False, vcc_one=False)) | ||
| 408 | self.assertEqual(spv, baseline) | ||
| 409 | self.assertEqual(tuple(si.run_fragment(spv, inputs={"%sg_lane": 0})["%out_mrt0"]), want) | ||
| 410 | |||
| 411 | def test_interleaved_across_every_arithmetic_step(self): | ||
| 412 | base_lines = ps_program([], scc_one=True, vcc_one=True) | ||
| 413 | baseline = translate_ps("ps_interleave_base", base_lines) | ||
| 414 | want = expected_ps_mrt0(scc_one=True, vcc_one=True) | ||
| 415 | interleaved = [ | ||
| 416 | "v_mov_b32 v0, 0x11112222", | ||
| 417 | "v_mov_b32 v1, 0x33334444", | ||
| 418 | "v_mov_b32 v2, 0x55556666", | ||
| 419 | "v_mov_b32 v3, 0x77778888", | ||
| 420 | "s_clause 0x1", | ||
| 421 | "s_mov_b32 s2, 0xffffffff", | ||
| 422 | "s_mov_b32 s3, 5", | ||
| 423 | "s_delay_alu instid0(VALU_DEP_1) | instskip(NEXT) | instid1(SALU_CYCLE_1)", | ||
| 424 | "s_add_u32 s4, s2, s3", | ||
| 425 | "s_inst_prefetch 0x0", | ||
| 426 | "s_setprio 0x2", | ||
| 427 | "v_add_nc_u32 v0, v0, 0x10", | ||
| 428 | "s_sleep 0x1", | ||
| 429 | "v_cmp_eq_u32 vcc_lo, v0, 0x11112232", | ||
| 430 | "s_waitcnt_depctr depctr_vm_vsrc(0) depctr_va_sdst(0)", | ||
| 431 | "s_mov_b32 exec_lo, 0xaaaa5555", | ||
| 432 | "s_waitcnt_expcnt null, 0x0", | ||
| 433 | "s_waitcnt_lgkmcnt null, 0x0", | ||
| 434 | "s_waitcnt_vmcnt null, 0x0", | ||
| 435 | "s_waitcnt vmcnt(0) expcnt(0) lgkmcnt(0)", | ||
| 436 | "s_waitcnt_vscnt null, 0x0", | ||
| 437 | "s_nop 0", | ||
| 438 | "v_nop", | ||
| 439 | "s_cselect_b32 s5, 0x10000001, 0x20000002", | ||
| 440 | "s_add_u32 s6, s4, s5", | ||
| 441 | "v_cndmask_b32 v1, 0x99990000, v1, vcc_lo", | ||
| 442 | "v_add_nc_u32 v2, v2, s6", | ||
| 443 | "exp mrt0 v0, v1, v2, v3 done vm", | ||
| 444 | "s_endpgm", | ||
| 445 | ] | ||
| 446 | spv = translate_ps("ps_interleave", interleaved) | ||
| 447 | self.assertEqual(spv, baseline) | ||
| 448 | self.assertEqual(tuple(si.run_fragment(spv, inputs={"%sg_lane": 0})["%out_mrt0"]), want) | ||
| 449 | |||
| 450 | def test_inactive_exec_stays_zero_for_vgpr_writes_and_exports(self): | ||
| 451 | # Part 1: EXEC=0 around all handled no-ops blocks VGPR writes, then restoring EXEC exports intact values. | ||
| 452 | base_vgpr = [ | ||
| 453 | "v_mov_b32 v0, 0x10000001", | ||
| 454 | "v_mov_b32 v1, 0x20000002", | ||
| 455 | "v_mov_b32 v2, 0x30000003", | ||
| 456 | "v_mov_b32 v3, 0x40000004", | ||
| 457 | "s_mov_b32 exec_lo, 0", | ||
| 458 | "v_add_nc_u32 v2, v2, 0x1234", | ||
| 459 | "v_mov_b32 v3, 0xdeadbeef", | ||
| 460 | "s_mov_b32 exec_lo, -1", | ||
| 461 | "exp mrt0 v0, v1, v2, v3 done vm", | ||
| 462 | "s_endpgm", | ||
| 463 | ] | ||
| 464 | with_noops = base_vgpr[:5] + REPRESENTATIVE_NOOPS + base_vgpr[5:] | ||
| 465 | spv_base = translate_ps("ps_exec0_vgpr_base", base_vgpr) | ||
| 466 | spv_noops = translate_ps("ps_exec0_vgpr_noops", with_noops) | ||
| 467 | self.assertEqual(spv_noops, spv_base) | ||
| 468 | self.assertEqual(tuple(si.run_fragment(spv_noops, inputs={"%sg_lane": 0})["%out_mrt0"]), | ||
| 469 | (0x10000001, 0x20000002, 0x30000003, 0x40000004)) | ||
| 470 | |||
| 471 | # Part 2: EXEC=0 across all handled no-ops keeps the lane inactive through end of shader (OpKill -> {}). | ||
| 472 | base_exp = [ | ||
| 473 | "v_mov_b32 v0, 0x10000001", | ||
| 474 | "v_mov_b32 v1, 0x20000002", | ||
| 475 | "v_mov_b32 v2, 0x30000003", | ||
| 476 | "v_mov_b32 v3, 0x40000004", | ||
| 477 | "exp mrt0 v0, v1, v2, v3 vm", | ||
| 478 | "s_mov_b32 exec_lo, 0xaaaa5554", | ||
| 479 | "v_mov_b32 v0, 0xbad00000", | ||
| 480 | "exp mrt0 v0, v0, v0, v0 done vm", | ||
| 481 | "s_endpgm", | ||
| 482 | ] | ||
| 483 | spv_exp_base = translate_ps("ps_exec0_exp_base", base_exp) | ||
| 484 | spv_exp_noops = translate_ps("ps_exec0_exp_noops", base_exp[:6] + REPRESENTATIVE_NOOPS + base_exp[6:]) | ||
| 485 | self.assertEqual(spv_exp_noops, spv_exp_base) | ||
| 486 | self.assertEqual(si.run_fragment(spv_exp_noops, inputs={"%sg_lane": 0}), {}) | ||
| 487 | |||
| 488 | |||
| 489 | class ComputeShaderNoopWaitcntTests(unittest.TestCase): | ||
| 490 | """FSSM compute shader translation and multi-lane execution (wave32 & wave64).""" | ||
| 491 | |||
| 492 | def test_wave32_each_and_all_preserve_registers_vcc_scc_and_exec(self): | ||
| 493 | for scc_one in (True, False): | ||
| 494 | baseline = translate_cs("cs_w32_base", cs_program([], wave64=False, scc_one=scc_one), threads=32) | ||
| 495 | want = expected_cs_words(32, scc_one=scc_one) | ||
| 496 | self.assertEqual(run_cs(baseline, 32), want) | ||
| 497 | self.assertNotIn("OpControlBarrier", baseline) | ||
| 498 | self.assertNotIn("OpMemoryBarrier", baseline) | ||
| 499 | |||
| 500 | for variant in SCALAR_NOOP_VARIANTS: | ||
| 501 | with self.subTest(scc_one=scc_one, insn=variant): | ||
| 502 | spv = translate_cs("cs_w32_var", cs_program([variant], wave64=False, scc_one=scc_one), threads=32) | ||
| 503 | self.assertEqual(spv, baseline) | ||
| 504 | self.assertEqual(run_cs(spv, 32), want) | ||
| 505 | |||
| 506 | spv_all = translate_cs("cs_w32_all", cs_program(REPRESENTATIVE_NOOPS, wave64=False, scc_one=scc_one), | ||
| 507 | threads=32) | ||
| 508 | self.assertEqual(spv_all, baseline) | ||
| 509 | self.assertEqual(run_cs(spv_all, 32), want) | ||
| 510 | |||
| 511 | def test_wave64_preserves_state_across_all_64_lanes(self): | ||
| 512 | for scc_one in (True, False): | ||
| 513 | baseline = translate_cs("cs_w64_base", cs_program([], wave64=True, scc_one=scc_one), threads=64) | ||
| 514 | want = expected_cs_words(64, scc_one=scc_one) | ||
| 515 | self.assertEqual(run_cs(baseline, 64), want) | ||
| 516 | self.assertNotIn("OpControlBarrier", baseline) | ||
| 517 | self.assertNotIn("OpMemoryBarrier", baseline) | ||
| 518 | |||
| 519 | with self.subTest(scc_one=scc_one): | ||
| 520 | spv_all = translate_cs("cs_w64_all", cs_program(REPRESENTATIVE_NOOPS, wave64=True, scc_one=scc_one), | ||
| 521 | threads=64) | ||
| 522 | self.assertEqual(spv_all, baseline) | ||
| 523 | self.assertEqual(run_cs(spv_all, 64), want) | ||
| 524 | |||
| 525 | |||
| 526 | class ModeInstructionsTests(unittest.TestCase): | ||
| 527 | """Tests for s_denorm_mode, s_round_mode, and s_setreg* hardware MODE writes.""" | ||
| 528 | |||
| 529 | def test_s_denorm_mode_and_s_round_mode_stay_unsupported(self): | ||
| 530 | for insn in REFUSED_MODE_VARIANTS: | ||
| 531 | op = insn.split()[0] | ||
| 532 | with self.subTest(stage="ps", insn=insn): | ||
| 533 | with self.assertRaises(rdna2spirv.Unsupported) as ctx: | ||
| 534 | translate_ps("ps_refused_mode", ps_program([insn])) | ||
| 535 | self.assertIn(op, str(ctx.exception)) | ||
| 536 | self.assertIn("s_setreg", str(ctx.exception)) | ||
| 537 | |||
| 538 | with self.subTest(stage="cs", insn=insn): | ||
| 539 | with self.assertRaises(rdna2spirv.Unsupported) as ctx: | ||
| 540 | translate_cs("cs_refused_mode", cs_program([insn], wave64=False), threads=32) | ||
| 541 | self.assertIn(op, str(ctx.exception)) | ||
| 542 | self.assertIn("s_setreg", str(ctx.exception)) | ||
| 543 | |||
| 544 | def test_s_setreg_mode_fp_round_emits_only_mode_r16_and_preserves_state(self): | ||
| 545 | ps_base = translate_ps("ps_mode_base", ps_program([])) | ||
| 546 | want_ps = expected_ps_mrt0() | ||
| 547 | cs_base = translate_cs("cs_mode_base", cs_program([], wave64=False), threads=32) | ||
| 548 | want_cs = expected_cs_words(32) | ||
| 549 | |||
| 550 | for insn, mode_const in MODELLED_MODE_VARIANTS: | ||
| 551 | with self.subTest(stage="ps", insn=insn): | ||
| 552 | spv = translate_ps("ps_mode_setreg", ps_program([insn])) | ||
| 553 | self.assertIn("%mode_r16 = OpVariable %_ptr_Function_uint Function %c0", spv) | ||
| 554 | self.assertIn(f"OpStore %mode_r16 {mode_const}", spv) | ||
| 555 | self.assertNotIn("OpControlBarrier", spv) | ||
| 556 | # Removing the two mode lines recovers the exact baseline SPIR-V (modulo unused %c3 if added). | ||
| 557 | self.assertEqual(spv.count("OpStore %mode_r16"), 1) | ||
| 558 | self.assertEqual(tuple(si.run_fragment(spv, inputs={"%sg_lane": 0})["%out_mrt0"]), want_ps) | ||
| 559 | self.assertEqual(tuple(si.run_fragment(ps_base, inputs={"%sg_lane": 0})["%out_mrt0"]), want_ps) | ||
| 560 | |||
| 561 | with self.subTest(stage="cs", insn=insn): | ||
| 562 | spv = translate_cs("cs_mode_setreg", cs_program([insn], wave64=False), threads=32) | ||
| 563 | self.assertIn("%mode_r16 = OpVariable %_ptr_Function_uint Function %c0", spv) | ||
| 564 | self.assertIn(f"OpStore %mode_r16 {mode_const}", spv) | ||
| 565 | self.assertEqual(run_cs(spv, 32), want_cs) | ||
| 566 | self.assertEqual(run_cs(cs_base, 32), want_cs) | ||
| 567 | |||
| 568 | def test_unmodelled_s_setreg_mode_forms_raise_unsupported(self): | ||
| 569 | bad_mode_writes = [ | ||
| 570 | "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 0, 2), 3", | ||
| 571 | "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 4, 4), 15", | ||
| 572 | "s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0", | ||
| 573 | "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 1", | ||
| 574 | "s_setreg_imm32_b32 hwreg(HW_REG_MODE, 2, 2), 2", | ||
| 575 | "s_setreg_b32 hwreg(HW_REG_MODE, 2, 2), s2", | ||
| 576 | ] | ||
| 577 | for insn in bad_mode_writes: | ||
| 578 | with self.subTest(insn=insn): | ||
| 579 | with self.assertRaises(rdna2spirv.Unsupported): | ||
| 580 | translate_ps("ps_bad_mode", ps_program([insn])) | ||
| 581 | |||
| 582 | |||
| 583 | class NegativeControlTests(unittest.TestCase): | ||
| 584 | """Negative controls: sabotaging arithmetic or using unknown mnemonics must be detected.""" | ||
| 585 | |||
| 586 | def test_sabotaging_arithmetic_around_noop_waitcnt_changes_output(self): | ||
| 587 | good_spv = translate_ps("ps_neg_good", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"])) | ||
| 588 | good_out = si.run_fragment(good_spv, inputs={"%sg_lane": 0}) | ||
| 589 | self.assertEqual(tuple(good_out["%out_mrt0"]), expected_ps_mrt0(scc_one=True, vcc_one=True)) | ||
| 590 | |||
| 591 | # Assembly-level sabotage around the waitcnt/clause instructions: | ||
| 592 | sabotaged_cases = [ | ||
| 593 | ("SCC flipped 1->0", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"], scc_one=False)), | ||
| 594 | ("VCC flipped 1->0", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"], vcc_one=False)), | ||
| 595 | ("v_add_nc_u32 addend changed", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"], add_k=0x20)), | ||
| 596 | ("EXEC bit 0 cleared", ps_program(["s_waitcnt_vmcnt null, 0x0", "s_clause 0x1"], exec_lo=0xAAAA5554)), | ||
| 597 | ] | ||
| 598 | for label, bad_lines in sabotaged_cases: | ||
| 599 | with self.subTest(sabotage=label): | ||
| 600 | bad_spv = translate_ps("ps_neg_bad", bad_lines) | ||
| 601 | bad_out = si.run_fragment(bad_spv, inputs={"%sg_lane": 0}) | ||
| 602 | self.assertNotEqual(bad_out, good_out) | ||
| 603 | |||
| 604 | # SPIR-V-level sabotage on the translated output around the no-op/waitcnt block: | ||
| 605 | for old, new, label in ( | ||
| 606 | ("OpIAdd %uint", "OpISub %uint", "v_add_nc_u32/s_add_u32 turned into OpISub"), | ||
| 607 | ("OpIEqual %bool", "OpINotEqual %bool", "v_cmp_eq_u32 inverted"), | ||
| 608 | ): | ||
| 609 | with self.subTest(spirv_sabotage=label): | ||
| 610 | self.assertIn(old, good_spv) | ||
| 611 | mutated = good_spv.replace(old, new) | ||
| 612 | self.assertNotEqual(si.run_fragment(mutated, inputs={"%sg_lane": 0}), good_out) | ||
| 613 | |||
| 614 | # CS multi-lane negative control: | ||
| 615 | cs_good = translate_cs("cs_neg_good", cs_program(["s_sleep 0x1", "s_waitcnt_depctr 0xffe3"], wave64=False), | ||
| 616 | threads=32) | ||
| 617 | cs_good_words = run_cs(cs_good, 32) | ||
| 618 | cs_bad = translate_cs("cs_neg_bad", cs_program(["s_sleep 0x1", "s_waitcnt_depctr 0xffe3"], | ||
| 619 | wave64=False, scc_one=False), threads=32) | ||
| 620 | self.assertNotEqual(run_cs(cs_bad, 32), cs_good_words) | ||
| 621 | |||
| 622 | def test_unknown_waitcnt_and_noop_mnemonics_fail_with_unsupported(self): | ||
| 623 | for bogus in ("s_bogus_waitcnt 0x0", "s_bogus_waitcnt", "s_bogus_noop 0"): | ||
| 624 | with self.subTest(stage="ps", insn=bogus): | ||
| 625 | with self.assertRaises(rdna2spirv.Unsupported) as ctx: | ||
| 626 | translate_ps("ps_bogus", ps_program([bogus])) | ||
| 627 | self.assertIn(bogus.split()[0], str(ctx.exception)) | ||
| 628 | |||
| 629 | with self.subTest(stage="cs", insn=bogus): | ||
| 630 | with self.assertRaises(rdna2spirv.Unsupported) as ctx: | ||
| 631 | translate_cs("cs_bogus", cs_program([bogus], wave64=False), threads=32) | ||
| 632 | self.assertIn(bogus.split()[0], str(ctx.exception)) | ||
| 633 | |||
| 634 | |||
| 635 | if __name__ == "__main__": | ||
| 636 | unittest.main() | ||
diff --git a/tests/semantic/test_valu_cvt_pk_u8_f32.py b/tests/semantic/test_valu_cvt_pk_u8_f32.py new file mode 100644 index 000000000..d0f42b1f1 --- /dev/null +++ b/tests/semantic/test_valu_cvt_pk_u8_f32.py | |||
| @@ -0,0 +1,757 @@ | |||
| 1 | """Semantic value tests for RDNA2 v_cvt_pk_u8_f32 (VOP3). | ||
| 2 | |||
| 3 | AMD RDNA2 ISA semantics for `v_cvt_pk_u8_f32 vD, src0, src1, src2`: | ||
| 4 | - Converts binary32 `src0` to an 8-bit unsigned integer using IEEE-754 round-to-nearest-even (`RoundEven`), | ||
| 5 | clamped to [0, 255] (negative values and -inf -> 0; values >= 255.0 and +inf -> 255; NaN -> 0). | ||
| 6 | - Inserts that byte into byte lane `src1[1:0]` (`src1 & 3`, i.e. bits [7:0], [15:8], [23:16], or [31:24]) | ||
| 7 | of `src2`, leaving the other 3 bytes of `src2` untouched in `vD`. | ||
| 8 | |||
| 9 | Executed end-to-end through tools/rdna2spirv.py and tests/semantic/spirv_mini_interp.py (single-lane pixel | ||
| 10 | shaders via run_fragment and multi-lane compute shaders via run_workgroup), and checked against hand-worked | ||
| 11 | constants and an independent pure-Python binary32 Fraction/RTE reference oracle. Standard library only; | ||
| 12 | hand-written RDNA2 disassembly listings only. | ||
| 13 | |||
| 14 | Finding on NaN inputs (open item also listed in docs/design.md, "Multiply-add and output modifiers" row): | ||
| 15 | tools/rdna2spirv.py lowers `v_cvt_pk_u8_f32` via `OpExtInst %float %glsl FClamp {x} %f0 %f_255` without an | ||
| 16 | `OpIsNan` guard before `RoundEven` + `OpConvertFToU`. In SPIR-V / GLSL.std.450, `FClamp` with a NaN operand | ||
| 17 | is undefined, so tests/semantic/spirv_mini_interp.py raises `UnsupportedConstruct` for `qNaN`, `-qNaN`, and | ||
| 18 | `sNaN`. Accordingly, `OracleTests` verifies the RDNA2 ISA `NaN -> 0` rule, and `NaNHandlingTests` asserts | ||
| 19 | both the translated SPIR-V structure (`FClamp`, `RoundEven`, `OpConvertFToU`) and that `spirv_mini_interp.py` | ||
| 20 | rejects NaN inputs with `UnsupportedConstruct` rather than returning a fabricated value. | ||
| 21 | """ | ||
| 22 | import gc | ||
| 23 | import os | ||
| 24 | import random | ||
| 25 | import re | ||
| 26 | import struct | ||
| 27 | import sys | ||
| 28 | import tempfile | ||
| 29 | import unittest | ||
| 30 | import warnings | ||
| 31 | from fractions import Fraction | ||
| 32 | |||
| 33 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 34 | ROOT = os.path.dirname(os.path.dirname(HERE)) | ||
| 35 | TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") | ||
| 36 | |||
| 37 | sys.dont_write_bytecode = True | ||
| 38 | if TOOLS_DIR not in sys.path: | ||
| 39 | sys.path.insert(0, TOOLS_DIR) | ||
| 40 | if HERE not in sys.path: | ||
| 41 | sys.path.insert(0, HERE) | ||
| 42 | |||
| 43 | import rdna2spirv # noqa: E402 | ||
| 44 | import spirv_mini_interp as si # noqa: E402 | ||
| 45 | |||
| 46 | MASK32 = 0xFFFFFFFF | ||
| 47 | OLD = 0xDEADBEEF | ||
| 48 | CANARY = 0xCAFEBABE | ||
| 49 | HEAP_FILL = 0xEEEEEEEE | ||
| 50 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 51 | VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] | ||
| 52 | |||
| 53 | # Representative binary32 bit encodings. | ||
| 54 | F32_POS_ZERO = 0x00000000 | ||
| 55 | F32_NEG_ZERO = 0x80000000 | ||
| 56 | F32_POS_SUB_MIN = 0x00000001 | ||
| 57 | F32_POS_SUB_MID = 0x00400000 | ||
| 58 | F32_POS_SUB_MAX = 0x007FFFFF | ||
| 59 | F32_NEG_SUB_MIN = 0x80000001 | ||
| 60 | F32_NEG_SUB_MAX = 0x807FFFFF | ||
| 61 | F32_POS_NORM_MIN = 0x00800000 | ||
| 62 | F32_NEG_NORM_MIN = 0x80800000 | ||
| 63 | F32_FLT_MAX = 0x7F7FFFFF | ||
| 64 | F32_NEG_FLT_MAX = 0xFF7FFFFF | ||
| 65 | F32_POS_INF = 0x7F800000 | ||
| 66 | F32_NEG_INF = 0xFF800000 | ||
| 67 | F32_QNAN = 0x7FC00000 | ||
| 68 | F32_NEG_QNAN = 0xFFC00000 | ||
| 69 | F32_QNAN_PAYLOAD = 0x7FC12345 | ||
| 70 | F32_SNAN = 0x7F800001 | ||
| 71 | F32_NEG_SNAN = 0xFF800001 | ||
| 72 | |||
| 73 | |||
| 74 | def f32_bits(x: float) -> int: | ||
| 75 | try: | ||
| 76 | return struct.unpack("<I", struct.pack("<f", x))[0] | ||
| 77 | except OverflowError: | ||
| 78 | return F32_POS_INF if x > 0 else F32_NEG_INF | ||
| 79 | |||
| 80 | |||
| 81 | def bits_f32(bits: int) -> float: | ||
| 82 | return struct.unpack("<f", struct.pack("<I", bits & MASK32))[0] | ||
| 83 | |||
| 84 | |||
| 85 | def is_f32_nan_bits(bits: int) -> bool: | ||
| 86 | return (bits & 0x7F800000) == 0x7F800000 and (bits & 0x007FFFFF) != 0 | ||
| 87 | |||
| 88 | |||
| 89 | # ----------------------------------------------------------------------------- | ||
| 90 | # Independent IEEE-754 Binary32 Fraction/RTE Reference Oracle | ||
| 91 | # ----------------------------------------------------------------------------- | ||
| 92 | |||
| 93 | def f32_bits_to_fraction(bits: int) -> Fraction: | ||
| 94 | """Exact rational value of a finite IEEE-754 binary32 bit encoding.""" | ||
| 95 | bits &= MASK32 | ||
| 96 | sign = -1 if (bits >> 31) else 1 | ||
| 97 | exp = (bits >> 23) & 0xFF | ||
| 98 | man = bits & 0x7FFFFF | ||
| 99 | if exp == 0xFF: | ||
| 100 | raise ValueError(f"non-finite binary32 {bits:#010x}") | ||
| 101 | if exp == 0: | ||
| 102 | return sign * Fraction(man, 1 << 23) * (Fraction(2) ** -126) | ||
| 103 | return sign * Fraction((1 << 23) | man, 1 << 23) * (Fraction(2) ** (exp - 127)) | ||
| 104 | |||
| 105 | |||
| 106 | def rne_nonneg_fraction(q: Fraction) -> int: | ||
| 107 | """Round a non-negative rational to the nearest integer, ties to even.""" | ||
| 108 | n = q.numerator // q.denominator | ||
| 109 | rem = q - n | ||
| 110 | half = Fraction(1, 2) | ||
| 111 | if rem > half or (rem == half and (n & 1)): | ||
| 112 | n += 1 | ||
| 113 | return n | ||
| 114 | |||
| 115 | |||
| 116 | def ref_cvt_pk_u8_byte(x_bits: int) -> int: | ||
| 117 | """RDNA2 flt32_to_uint8: binary32 bits -> IEEE-754 RTE clamped [0, 255] (NaN -> 0).""" | ||
| 118 | bits = x_bits & MASK32 | ||
| 119 | if is_f32_nan_bits(bits): | ||
| 120 | return 0 | ||
| 121 | if (bits >> 31) or (bits & 0x7FFFFFFF) == 0: | ||
| 122 | return 0 | ||
| 123 | if bits == F32_POS_INF: | ||
| 124 | return 255 | ||
| 125 | q = f32_bits_to_fraction(bits) | ||
| 126 | if q >= 255: | ||
| 127 | return 255 | ||
| 128 | return min(255, rne_nonneg_fraction(q)) | ||
| 129 | |||
| 130 | |||
| 131 | def ref_cvt_pk_u8_f32(x_bits: int, slot: int, base: int) -> int: | ||
| 132 | """RDNA2 V_CVT_PK_U8_F32: insert ref_cvt_pk_u8_byte(x_bits) at byte (slot & 3) of base.""" | ||
| 133 | u = ref_cvt_pk_u8_byte(x_bits) | ||
| 134 | sh = 8 * (slot & 3) | ||
| 135 | return ((base & MASK32) & ~(0xFF << sh)) | (u << sh) | ||
| 136 | |||
| 137 | |||
| 138 | # Hand-worked reference expectations: (label, x_bits, slot, base, expected_dword). | ||
| 139 | HAND_WORKED = ( | ||
| 140 | ("slot0_old", f32_bits(18.0), 0, OLD, 0xDEADBE12), | ||
| 141 | ("slot1_old", f32_bits(52.0), 1, OLD, 0xDEAD34EF), | ||
| 142 | ("slot2_old", f32_bits(86.0), 2, OLD, 0xDE56BEEF), | ||
| 143 | ("slot3_old", f32_bits(120.0), 3, OLD, 0x78ADBEEF), | ||
| 144 | ("slot4_wraps_0", f32_bits(0xAB), 4, OLD, 0xDEADBEAB), | ||
| 145 | ("slot5_wraps_1", f32_bits(0xCD), 5, OLD, 0xDEADCDEF), | ||
| 146 | ("slot7_wraps_3", f32_bits(0x42), 7, OLD, 0x42ADBEEF), | ||
| 147 | ("slot_neg1_wraps_3", f32_bits(0x99), -1, OLD, 0x99ADBEEF), | ||
| 148 | ("tie_0_5_even", f32_bits(0.5), 0, OLD, 0xDEADBE00), | ||
| 149 | ("tie_1_5_even", f32_bits(1.5), 1, OLD, 0xDEAD02EF), | ||
| 150 | ("tie_2_5_even", f32_bits(2.5), 2, OLD, 0xDE02BEEF), | ||
| 151 | ("tie_253_5_even", f32_bits(253.5), 0, OLD, 0xDEADBEFE), | ||
| 152 | ("tie_254_5_even", f32_bits(254.5), 1, OLD, 0xDEADFEEF), | ||
| 153 | ("clamp_255_49", f32_bits(255.49), 2, OLD, 0xDEFFBEEF), | ||
| 154 | ("clamp_255_5", f32_bits(255.5), 3, OLD, 0xFFADBEEF), | ||
| 155 | ("neg_0_001", f32_bits(-0.001), 0, OLD, 0xDEADBE00), | ||
| 156 | ("neg_1000", f32_bits(-1000.0), 1, OLD, 0xDEAD00EF), | ||
| 157 | ("neg_inf", F32_NEG_INF, 2, OLD, 0xDE00BEEF), | ||
| 158 | ("pos_inf", F32_POS_INF, 3, OLD, 0xFFADBEEF), | ||
| 159 | ("subnormal_pos", F32_POS_SUB_MIN, 0, OLD, 0xDEADBE00), | ||
| 160 | ("subnormal_neg", F32_NEG_SUB_MAX, 1, OLD, 0xDEAD00EF), | ||
| 161 | ("qnan", F32_QNAN, 0, OLD, 0xDEADBE00), | ||
| 162 | ("neg_qnan", F32_NEG_QNAN, 2, OLD, 0xDE00BEEF), | ||
| 163 | ("snan", F32_SNAN, 3, OLD, 0x00ADBEEF), | ||
| 164 | ) | ||
| 165 | |||
| 166 | |||
| 167 | # ----------------------------------------------------------------------------- | ||
| 168 | # Translation & Execution Helpers | ||
| 169 | # ----------------------------------------------------------------------------- | ||
| 170 | |||
| 171 | _TMP_DIR = None | ||
| 172 | _PS_PATH = None | ||
| 173 | _CS_PATH = None | ||
| 174 | _CS_FSSM = None | ||
| 175 | |||
| 176 | |||
| 177 | def _make_fssm(rsrc2: int, group: tuple[int, int, int]) -> bytes: | ||
| 178 | header = bytearray(0x148) | ||
| 179 | struct.pack_into("<4I", header, 0x138, rsrc2, *group) | ||
| 180 | return bytes(header) | ||
| 181 | |||
| 182 | |||
| 183 | def setUpModule(): | ||
| 184 | global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM | ||
| 185 | _TMP_DIR = tempfile.TemporaryDirectory() | ||
| 186 | disasm_dir = os.path.join(_TMP_DIR.name, "disasm") | ||
| 187 | fssm_dir = os.path.join(_TMP_DIR.name, "fssm") | ||
| 188 | os.mkdir(disasm_dir) | ||
| 189 | os.mkdir(fssm_dir) | ||
| 190 | _PS_PATH = os.path.join(disasm_dir, "ps_valu_cvt_pk_u8_f32.s") | ||
| 191 | _CS_PATH = os.path.join(disasm_dir, "cs_valu_cvt_pk_u8_f32.s") | ||
| 192 | _CS_FSSM = os.path.join(fssm_dir, "cs_valu_cvt_pk_u8_f32.fssm") | ||
| 193 | with open(os.path.join(_TMP_DIR.name, "ps_valu_cvt_pk_u8_f32.dxbc"), "wb") as f: | ||
| 194 | f.write(STUB_DXBC) | ||
| 195 | |||
| 196 | |||
| 197 | def tearDownModule(): | ||
| 198 | global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM | ||
| 199 | if _TMP_DIR is not None: | ||
| 200 | gc.collect() | ||
| 201 | _TMP_DIR.cleanup() | ||
| 202 | _TMP_DIR = None | ||
| 203 | _PS_PATH = None | ||
| 204 | _CS_PATH = None | ||
| 205 | _CS_FSSM = None | ||
| 206 | |||
| 207 | |||
| 208 | def translate_ps(lines: list[str]) -> str: | ||
| 209 | if _TMP_DIR is None: | ||
| 210 | setUpModule() | ||
| 211 | asm = "; test_valu_cvt_pk_u8_f32\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" | ||
| 212 | with open(_PS_PATH, "w", encoding="utf-8", newline="") as f: | ||
| 213 | f.write(asm) | ||
| 214 | with warnings.catch_warnings(): | ||
| 215 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 216 | spv = rdna2spirv.translate(_PS_PATH) | ||
| 217 | gc.collect() | ||
| 218 | return spv | ||
| 219 | |||
| 220 | |||
| 221 | def run_ps_mrt0(lines: list[str], regs: tuple[str, str, str, str] = ("v0", "v0", "v0", "v0")) -> tuple[int, ...]: | ||
| 222 | spv = translate_ps(list(lines) + [f"exp mrt0 {', '.join(regs)} done vm"]) | ||
| 223 | out = si.run_fragment(spv) | ||
| 224 | if list(out) != ["%out_mrt0"]: | ||
| 225 | raise AssertionError(f"expected %out_mrt0 only; got {sorted(out)}") | ||
| 226 | return tuple(out["%out_mrt0"]) | ||
| 227 | |||
| 228 | |||
| 229 | def run_cs(lines: list[str], group_size: int, subgroup_size: int, memory: dict[int, int]) -> dict[int, int]: | ||
| 230 | if _TMP_DIR is None: | ||
| 231 | setUpModule() | ||
| 232 | # rsrc2 = 0x0088: USER_SGPR = 4 (s[0:3] V#), TGID_X_EN = 1 (s4), TIDIG_COMP_CNT = 0 (v0 = local_id.x). | ||
| 233 | with open(_CS_FSSM, "wb") as f: | ||
| 234 | f.write(_make_fssm(0x0088, (group_size, 1, 1))) | ||
| 235 | asm = "; test_cs_valu_cvt_pk_u8_f32\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" | ||
| 236 | with open(_CS_PATH, "w", encoding="utf-8", newline="") as f: | ||
| 237 | f.write(asm) | ||
| 238 | with warnings.catch_warnings(): | ||
| 239 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 240 | spv = rdna2spirv.translate(_CS_PATH) | ||
| 241 | gc.collect() | ||
| 242 | return si.run_workgroup( | ||
| 243 | spv, group_size, subgroup_size, | ||
| 244 | inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0)}, | ||
| 245 | push_constants=VSHARP + [0] * 28, | ||
| 246 | memory=memory, | ||
| 247 | ) | ||
| 248 | |||
| 249 | |||
| 250 | class _Heap(dict): | ||
| 251 | def get(self, key, default=None): | ||
| 252 | return super().get(key, HEAP_FILL) | ||
| 253 | |||
| 254 | |||
| 255 | # ----------------------------------------------------------------------------- | ||
| 256 | # 1. Reference Oracle Self-Tests | ||
| 257 | # ----------------------------------------------------------------------------- | ||
| 258 | |||
| 259 | class OracleTests(unittest.TestCase): | ||
| 260 | def test_hand_worked_constants_match_oracle(self): | ||
| 261 | for label, x_bits, slot, base, want in HAND_WORKED: | ||
| 262 | with self.subTest(case=label): | ||
| 263 | self.assertEqual(ref_cvt_pk_u8_f32(x_bits, slot, base), want) | ||
| 264 | |||
| 265 | def test_oracle_agrees_with_python_float_round_for_finite_values(self): | ||
| 266 | for k in range(256): | ||
| 267 | for delta in (-0.25, 0.0, 0.25, 0.5): | ||
| 268 | x = k + delta | ||
| 269 | xb = f32_bits(x) | ||
| 270 | expected_u = min(255, max(0, round(bits_f32(xb)))) | ||
| 271 | self.assertEqual(ref_cvt_pk_u8_byte(xb), expected_u, f"x={x}") | ||
| 272 | # Verify 1-ULP neighbors around .5 ties. | ||
| 273 | for tie in (0.5, 1.5, 2.5, 127.5, 128.5, 253.5, 254.5): | ||
| 274 | tb = f32_bits(tie) | ||
| 275 | for b in (tb - 1, tb, tb + 1): | ||
| 276 | expected_u = min(255, max(0, round(bits_f32(b)))) | ||
| 277 | self.assertEqual(ref_cvt_pk_u8_byte(b), expected_u, f"b={b:#010x}") | ||
| 278 | |||
| 279 | |||
| 280 | # ----------------------------------------------------------------------------- | ||
| 281 | # 2. Byte Slots (0..3), Slot Masking (slot & 3), and Untouched Bytes | ||
| 282 | # ----------------------------------------------------------------------------- | ||
| 283 | |||
| 284 | class ByteSlotAndMaskingTests(unittest.TestCase): | ||
| 285 | def test_all_four_slots_preserve_other_three_bytes_of_base(self): | ||
| 286 | # Distinct byte values including 0x00 and 0xFF (slot 3 gives 0xFFADBEEF / 0x00ADBEEF). | ||
| 287 | byte_vals = (0.0, 1.0, 18.0, 127.0, 128.0, 254.0, 255.0) | ||
| 288 | for suffix in ("", "_e64"): | ||
| 289 | for slot in range(4): | ||
| 290 | for start in range(0, len(byte_vals), 4): | ||
| 291 | chunk = byte_vals[start:start + 4] | ||
| 292 | lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], [] | ||
| 293 | for lane, val in enumerate(chunk): | ||
| 294 | xb = f32_bits(val) | ||
| 295 | dst = f"v{10 + lane}" | ||
| 296 | lines += [ | ||
| 297 | f"v_mov_b32 {dst}, {CANARY:#x}", | ||
| 298 | f"v_mov_b32 v1, {xb:#x}", | ||
| 299 | f"v_mov_b32 v2, {slot}", | ||
| 300 | f"v_cvt_pk_u8_f32{suffix} {dst}, v1, v2, v3", | ||
| 301 | ] | ||
| 302 | expected.append(ref_cvt_pk_u8_f32(xb, slot, OLD)) | ||
| 303 | while len(expected) < 4: | ||
| 304 | lines.append(f"v_mov_b32 v{10 + len(expected)}, 0") | ||
| 305 | expected.append(0) | ||
| 306 | with self.subTest(suffix=suffix or "bare", slot=slot, batch=start // 4): | ||
| 307 | got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")) | ||
| 308 | self.assertEqual(got, tuple(expected)) | ||
| 309 | |||
| 310 | def test_slot_and_3_masking_across_vgpr_sgpr_and_inline_operands(self): | ||
| 311 | slots = [0, 1, 2, 3, 4, 5, 6, 7, 8, -1, 0xFFFFFFFF, 0xFFFFFFFC, 0x80000001, 0x1234567A] | ||
| 312 | payloads = [17.0, 65.0, 145.0, 243.0] | ||
| 313 | |||
| 314 | for op_kind in ("vgpr", "sgpr", "inline"): | ||
| 315 | for start in range(0, len(slots), 4): | ||
| 316 | chunk = slots[start:start + 4] | ||
| 317 | lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], [] | ||
| 318 | for idx, slot in enumerate(chunk): | ||
| 319 | x = payloads[(start + idx) % len(payloads)] | ||
| 320 | xb = f32_bits(x) | ||
| 321 | dst = f"v{10 + idx}" | ||
| 322 | lines.append(f"v_mov_b32 {dst}, {CANARY:#x}") | ||
| 323 | lines.append(f"v_mov_b32 v1, {xb:#x}") | ||
| 324 | if op_kind == "vgpr": | ||
| 325 | lines.append(f"v_mov_b32 v2, {slot & MASK32:#x}") | ||
| 326 | slot_arg = "v2" | ||
| 327 | elif op_kind == "sgpr": | ||
| 328 | lines.append(f"s_mov_b32 s4, {slot & MASK32:#x}") | ||
| 329 | slot_arg = "s4" | ||
| 330 | else: | ||
| 331 | slot_arg = str(slot) if -16 <= slot <= 64 else f"{slot & MASK32:#x}" | ||
| 332 | lines.append(f"v_cvt_pk_u8_f32_e64 {dst}, v1, {slot_arg}, v3") | ||
| 333 | expected.append(ref_cvt_pk_u8_f32(xb, slot, OLD)) | ||
| 334 | while len(expected) < 4: | ||
| 335 | lines.append(f"v_mov_b32 v{10 + len(expected)}, 0") | ||
| 336 | expected.append(0) | ||
| 337 | with self.subTest(op_kind=op_kind, chunk=chunk): | ||
| 338 | got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")) | ||
| 339 | self.assertEqual(got, tuple(expected)) | ||
| 340 | |||
| 341 | def test_base_from_sgpr_inline_and_sequential_four_byte_pack(self): | ||
| 342 | # src2 from SGPR, inline 0, and inline -1. | ||
| 343 | got_bases = run_ps_mrt0([ | ||
| 344 | f"v_mov_b32 v1, {f32_bits(0x4A):#x}", | ||
| 345 | f"s_mov_b32 s5, {OLD:#x}", | ||
| 346 | "v_cvt_pk_u8_f32 v10, v1, 2, s5", # 0xDE4ABEEF | ||
| 347 | "v_cvt_pk_u8_f32 v11, v1, 1, 0", # 0x00004A00 | ||
| 348 | "v_cvt_pk_u8_f32 v12, v1, 3, -1", # 0x4AFFFFFF | ||
| 349 | "v_cvt_pk_u8_f32 v13, v1, 0, -1", # 0xFFFFFF4A | ||
| 350 | ], ("v10", "v11", "v12", "v13")) | ||
| 351 | self.assertEqual(got_bases, ( | ||
| 352 | ref_cvt_pk_u8_f32(f32_bits(0x4A), 2, OLD), | ||
| 353 | ref_cvt_pk_u8_f32(f32_bits(0x4A), 1, 0), | ||
| 354 | ref_cvt_pk_u8_f32(f32_bits(0x4A), 3, MASK32), | ||
| 355 | ref_cvt_pk_u8_f32(f32_bits(0x4A), 0, MASK32), | ||
| 356 | )) | ||
| 357 | |||
| 358 | # Pack 4 floats sequentially into bytes 0, 1, 2, 3 of v0 starting from OLD. | ||
| 359 | got_packed = run_ps_mrt0([ | ||
| 360 | f"v_mov_b32 v0, {OLD:#x}", | ||
| 361 | f"v_mov_b32 v1, {f32_bits(0x11):#x}", | ||
| 362 | f"v_mov_b32 v2, {f32_bits(0x22):#x}", | ||
| 363 | f"v_mov_b32 v3, {f32_bits(0x33):#x}", | ||
| 364 | f"v_mov_b32 v4, {f32_bits(0x44):#x}", | ||
| 365 | "v_cvt_pk_u8_f32 v0, v1, 0, v0", | ||
| 366 | "v_cvt_pk_u8_f32 v0, v2, 1, v0", | ||
| 367 | "v_cvt_pk_u8_f32 v0, v3, 2, v0", | ||
| 368 | "v_cvt_pk_u8_f32 v0, v4, 3, v0", | ||
| 369 | ])[0] | ||
| 370 | self.assertEqual(got_packed, 0x44332211) | ||
| 371 | |||
| 372 | |||
| 373 | # ----------------------------------------------------------------------------- | ||
| 374 | # 3. Clamping, Special Float Inputs, and .5 Round-to-Nearest-Even Ties | ||
| 375 | # ----------------------------------------------------------------------------- | ||
| 376 | |||
| 377 | class ClampingAndSpecialInputsTests(unittest.TestCase): | ||
| 378 | def test_negative_overflow_and_subnormal_clamping(self): | ||
| 379 | cases = [ | ||
| 380 | # Negatives -> 0 | ||
| 381 | ("pos_zero", F32_POS_ZERO), | ||
| 382 | ("neg_zero", F32_NEG_ZERO), | ||
| 383 | ("neg_tiny", f32_bits(-1e-30)), | ||
| 384 | ("neg_0_001", f32_bits(-0.001)), | ||
| 385 | ("neg_half", f32_bits(-0.5)), | ||
| 386 | ("neg_one", f32_bits(-1.0)), | ||
| 387 | ("neg_127_5", f32_bits(-127.5)), | ||
| 388 | ("neg_1000", f32_bits(-1000.0)), | ||
| 389 | ("neg_flt_max", F32_NEG_FLT_MAX), | ||
| 390 | ("neg_inf", F32_NEG_INF), | ||
| 391 | # Overflow -> 255 | ||
| 392 | ("255_0", f32_bits(255.0)), | ||
| 393 | ("255_001", f32_bits(255.001)), | ||
| 394 | ("255_49", f32_bits(255.49)), | ||
| 395 | ("255_5", f32_bits(255.5)), | ||
| 396 | ("256_0", f32_bits(256.0)), | ||
| 397 | ("512_0", f32_bits(512.0)), | ||
| 398 | ("1e10", f32_bits(1e10)), | ||
| 399 | ("flt_max", F32_FLT_MAX), | ||
| 400 | ("pos_inf", F32_POS_INF), | ||
| 401 | # Tiny subnormals & near-zero normals -> 0 | ||
| 402 | ("pos_sub_min", F32_POS_SUB_MIN), | ||
| 403 | ("pos_sub_mid", F32_POS_SUB_MID), | ||
| 404 | ("pos_sub_max", F32_POS_SUB_MAX), | ||
| 405 | ("neg_sub_min", F32_NEG_SUB_MIN), | ||
| 406 | ("neg_sub_max", F32_NEG_SUB_MAX), | ||
| 407 | ("pos_norm_min", F32_POS_NORM_MIN), | ||
| 408 | ("neg_norm_min", F32_NEG_NORM_MIN), | ||
| 409 | # ULP boundaries around 0.5, 1.5, 254.5, 255.0 | ||
| 410 | ("0_5_minus_ulp", f32_bits(0.5) - 1), | ||
| 411 | ("0_5_plus_ulp", f32_bits(0.5) + 1), | ||
| 412 | ("1_5_minus_ulp", f32_bits(1.5) - 1), | ||
| 413 | ("1_5_plus_ulp", f32_bits(1.5) + 1), | ||
| 414 | ("254_5_minus_ulp", f32_bits(254.5) - 1), | ||
| 415 | ("254_5_plus_ulp", f32_bits(254.5) + 1), | ||
| 416 | ("255_0_minus_ulp", f32_bits(255.0) - 1), | ||
| 417 | ("255_0_plus_ulp", f32_bits(255.0) + 1), | ||
| 418 | ] | ||
| 419 | for start in range(0, len(cases), 4): | ||
| 420 | chunk = cases[start:start + 4] | ||
| 421 | lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], [] | ||
| 422 | for idx, (_, xb) in enumerate(chunk): | ||
| 423 | slot = (start + idx) & 3 | ||
| 424 | dst = f"v{10 + idx}" | ||
| 425 | lines += [ | ||
| 426 | f"v_mov_b32 v1, {xb:#x}", | ||
| 427 | f"v_cvt_pk_u8_f32 {dst}, v1, {slot}, v3", | ||
| 428 | ] | ||
| 429 | expected.append(ref_cvt_pk_u8_f32(xb, slot, OLD)) | ||
| 430 | while len(expected) < 4: | ||
| 431 | lines.append(f"v_mov_b32 v{10 + len(expected)}, 0") | ||
| 432 | expected.append(0) | ||
| 433 | with self.subTest(cases=[lbl for lbl, _ in chunk]): | ||
| 434 | got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")) | ||
| 435 | self.assertEqual(got, tuple(expected)) | ||
| 436 | |||
| 437 | def test_seeded_finite_sweep(self): | ||
| 438 | rng = random.Random(0xC08E) | ||
| 439 | samples = [(f32_bits(rng.uniform(-20.0, 280.0)), rng.randrange(0, 8)) for _ in range(64)] | ||
| 440 | for start in range(0, len(samples), 4): | ||
| 441 | chunk = samples[start:start + 4] | ||
| 442 | lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], [] | ||
| 443 | for idx, (xb, slot) in enumerate(chunk): | ||
| 444 | dst = f"v{10 + idx}" | ||
| 445 | lines += [ | ||
| 446 | f"v_mov_b32 v1, {xb:#x}", | ||
| 447 | f"v_cvt_pk_u8_f32 {dst}, v1, {slot}, v3", | ||
| 448 | ] | ||
| 449 | expected.append(ref_cvt_pk_u8_f32(xb, slot, OLD)) | ||
| 450 | with self.subTest(batch=start // 4): | ||
| 451 | self.assertEqual(run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")), tuple(expected)) | ||
| 452 | |||
| 453 | |||
| 454 | class RoundToNearestEvenTieTests(unittest.TestCase): | ||
| 455 | def test_all_half_ties_from_0_5_to_255_5_and_255_49(self): | ||
| 456 | ties = [k + 0.5 for k in range(256)] + [255.49] | ||
| 457 | for start in range(0, len(ties), 4): | ||
| 458 | chunk = ties[start:start + 4] | ||
| 459 | lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], [] | ||
| 460 | for idx, x in enumerate(chunk): | ||
| 461 | xb = f32_bits(x) | ||
| 462 | slot = (start + idx) & 3 | ||
| 463 | dst = f"v{10 + idx}" | ||
| 464 | lines += [ | ||
| 465 | f"v_mov_b32 v1, {xb:#x}", | ||
| 466 | f"v_cvt_pk_u8_f32 {dst}, v1, {slot}, v3", | ||
| 467 | ] | ||
| 468 | expected.append(ref_cvt_pk_u8_f32(xb, slot, OLD)) | ||
| 469 | while len(expected) < 4: | ||
| 470 | lines.append(f"v_mov_b32 v{10 + len(expected)}, 0") | ||
| 471 | expected.append(0) | ||
| 472 | with self.subTest(ties=chunk): | ||
| 473 | got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")) | ||
| 474 | self.assertEqual(got, tuple(expected)) | ||
| 475 | |||
| 476 | def test_all_exact_integers_0_to_255(self): | ||
| 477 | for start in range(0, 256, 4): | ||
| 478 | chunk = range(start, start + 4) | ||
| 479 | lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], [] | ||
| 480 | for idx, k in enumerate(chunk): | ||
| 481 | xb = f32_bits(float(k)) | ||
| 482 | dst = f"v{10 + idx}" | ||
| 483 | lines += [ | ||
| 484 | f"v_mov_b32 v1, {xb:#x}", | ||
| 485 | f"v_cvt_pk_u8_f32 {dst}, v1, {idx}, v3", | ||
| 486 | ] | ||
| 487 | expected.append(ref_cvt_pk_u8_f32(xb, idx, OLD)) | ||
| 488 | with self.subTest(start=start): | ||
| 489 | self.assertEqual(run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")), tuple(expected)) | ||
| 490 | |||
| 491 | |||
| 492 | # ----------------------------------------------------------------------------- | ||
| 493 | # 4. VOP3 Modifiers, SGPR/Inline Float Sources, Destination Aliasing, EXEC | ||
| 494 | # ----------------------------------------------------------------------------- | ||
| 495 | |||
| 496 | class SourceModifiersAndOperandsTests(unittest.TestCase): | ||
| 497 | def test_vop3_source_modifiers(self): | ||
| 498 | cases = [ | ||
| 499 | (f32_bits(-42.5), "-v1", 0, 42), # -(-42.5) = 42.5 -> 42 (even) | ||
| 500 | (f32_bits(-43.5), "-v1", 1, 44), # -(-43.5) = 43.5 -> 44 (even) | ||
| 501 | (f32_bits(42.5), "-v1", 2, 0), # -(42.5) = -42.5 -> 0 | ||
| 502 | (F32_NEG_INF, "-v1", 3, 255), # -(-inf) = +inf -> 255 | ||
| 503 | (F32_POS_INF, "-v1", 0, 0), # -(+inf) = -inf -> 0 | ||
| 504 | (f32_bits(-13.5), "|v1|", 1, 14), # |-13.5| = 13.5 -> 14 (even) | ||
| 505 | (f32_bits(-14.5), "|v1|", 2, 14), # |-14.5| = 14.5 -> 14 (even) | ||
| 506 | (f32_bits(-300.0), "|v1|", 3, 255), # |-300.0| = 300.0 -> 255 | ||
| 507 | (F32_NEG_INF, "|v1|", 0, 255), # |-inf| = +inf -> 255 | ||
| 508 | (f32_bits(10.0), "-|v1|", 1, 0), # -|10.0| = -10.0 -> 0 | ||
| 509 | (f32_bits(-10.0), "-|v1|", 2, 0), # -|-10.0| = -10.0 -> 0 | ||
| 510 | (F32_NEG_INF, "-|v1|", 3, 0), # -|-inf| = -inf -> 0 | ||
| 511 | (f32_bits(-1.5), "neg(v1)", 0, 2), # neg(-1.5) = 1.5 -> 2 | ||
| 512 | (f32_bits(-2.5), "abs(v1)", 1, 2), # abs(-2.5) = 2.5 -> 2 | ||
| 513 | (f32_bits(-7.5), "-|s4|", 2, 0), | ||
| 514 | (f32_bits(-7.5), "|s4|", 3, 8), | ||
| 515 | ] | ||
| 516 | for start in range(0, len(cases), 4): | ||
| 517 | chunk = cases[start:start + 4] | ||
| 518 | lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], [] | ||
| 519 | for idx, (xb, expr, slot, want_byte) in enumerate(chunk): | ||
| 520 | dst = f"v{10 + idx}" | ||
| 521 | reg = "s4" if "s4" in expr else "v1" | ||
| 522 | lines += [ | ||
| 523 | f"{'s_mov_b32' if reg == 's4' else 'v_mov_b32'} {reg}, {xb:#x}", | ||
| 524 | f"v_cvt_pk_u8_f32_e64 {dst}, {expr}, {slot}, v3", | ||
| 525 | ] | ||
| 526 | sh = 8 * (slot & 3) | ||
| 527 | expected.append((OLD & ~(0xFF << sh)) | (want_byte << sh)) | ||
| 528 | while len(expected) < 4: | ||
| 529 | lines.append(f"v_mov_b32 v{10 + len(expected)}, 0") | ||
| 530 | expected.append(0) | ||
| 531 | with self.subTest(cases=[(e, s) for _, e, s, _ in chunk]): | ||
| 532 | got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")) | ||
| 533 | self.assertEqual(got, tuple(expected)) | ||
| 534 | |||
| 535 | def test_inline_constant_and_sgpr_float_sources(self): | ||
| 536 | inline_cases = [ | ||
| 537 | ("0.5", 0, 0), | ||
| 538 | ("1.0", 1, 1), | ||
| 539 | ("2.0", 2, 2), | ||
| 540 | ("4.0", 3, 4), | ||
| 541 | ("-1.0", 0, 0), | ||
| 542 | ("-0.5", 1, 0), | ||
| 543 | ("-2.0", 2, 0), | ||
| 544 | ("-4.0", 3, 0), | ||
| 545 | ("0.0", 0, 0), | ||
| 546 | ("0", 1, 0), | ||
| 547 | ] | ||
| 548 | for start in range(0, len(inline_cases), 4): | ||
| 549 | chunk = inline_cases[start:start + 4] | ||
| 550 | lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], [] | ||
| 551 | for idx, (lit, slot, want_byte) in enumerate(chunk): | ||
| 552 | dst = f"v{10 + idx}" | ||
| 553 | lines.append(f"v_cvt_pk_u8_f32 {dst}, {lit}, {slot}, v3") | ||
| 554 | sh = 8 * (slot & 3) | ||
| 555 | expected.append((OLD & ~(0xFF << sh)) | (want_byte << sh)) | ||
| 556 | while len(expected) < 4: | ||
| 557 | lines.append(f"v_mov_b32 v{10 + len(expected)}, 0") | ||
| 558 | expected.append(0) | ||
| 559 | with self.subTest(inlines=[c[0] for c in chunk]): | ||
| 560 | got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")) | ||
| 561 | self.assertEqual(got, tuple(expected)) | ||
| 562 | |||
| 563 | # SGPR float sources across edge values. | ||
| 564 | sgpr_cases = [ | ||
| 565 | (f32_bits(0.5), 0), | ||
| 566 | (f32_bits(1.0), 1), | ||
| 567 | (f32_bits(2.0), 2), | ||
| 568 | (f32_bits(4.0), 3), | ||
| 569 | (f32_bits(-1.0), 0), | ||
| 570 | (f32_bits(127.5), 1), | ||
| 571 | (f32_bits(254.5), 2), | ||
| 572 | (F32_POS_INF, 3), | ||
| 573 | ] | ||
| 574 | for start in range(0, len(sgpr_cases), 4): | ||
| 575 | chunk = sgpr_cases[start:start + 4] | ||
| 576 | lines, expected = [f"v_mov_b32 v3, {OLD:#x}"], [] | ||
| 577 | for idx, (xb, slot) in enumerate(chunk): | ||
| 578 | dst = f"v{10 + idx}" | ||
| 579 | lines += [ | ||
| 580 | f"s_mov_b32 s4, {xb:#x}", | ||
| 581 | f"v_cvt_pk_u8_f32_e64 {dst}, s4, {slot}, v3", | ||
| 582 | ] | ||
| 583 | expected.append(ref_cvt_pk_u8_f32(xb, slot, OLD)) | ||
| 584 | with self.subTest(batch=start // 4): | ||
| 585 | got = run_ps_mrt0(lines, ("v10", "v11", "v12", "v13")) | ||
| 586 | self.assertEqual(got, tuple(expected)) | ||
| 587 | |||
| 588 | def test_destination_aliasing(self): | ||
| 589 | # 1. dst == src2: v_cvt_pk_u8_f32 v0, v1, 2, v0 | ||
| 590 | # 2. dst == src0: v_cvt_pk_u8_f32 v0, v0, 1, v3 | ||
| 591 | # 3. dst == src1: v_cvt_pk_u8_f32 v0, v1, v0, v3 | ||
| 592 | # 4. dst == src0 == src2: v_cvt_pk_u8_f32 v0, v0, 1, v0 (v0 holds 12.5 = 0x41480000 -> byte 12 at slot 1) | ||
| 593 | got = run_ps_mrt0([ | ||
| 594 | f"v_mov_b32 v3, {OLD:#x}", | ||
| 595 | f"v_mov_b32 v1, {f32_bits(86.0):#x}", | ||
| 596 | f"v_mov_b32 v10, {OLD:#x}", | ||
| 597 | "v_cvt_pk_u8_f32 v10, v1, 2, v10", | ||
| 598 | f"v_mov_b32 v11, {f32_bits(35.5):#x}", | ||
| 599 | "v_cvt_pk_u8_f32 v11, v11, 1, v3", | ||
| 600 | "v_mov_b32 v12, 7", | ||
| 601 | "v_cvt_pk_u8_f32 v12, v1, v12, v3", | ||
| 602 | f"v_mov_b32 v13, {f32_bits(12.5):#x}", | ||
| 603 | "v_cvt_pk_u8_f32 v13, v13, 1, v13", | ||
| 604 | ], ("v10", "v11", "v12", "v13")) | ||
| 605 | self.assertEqual(got, ( | ||
| 606 | ref_cvt_pk_u8_f32(f32_bits(86.0), 2, OLD), | ||
| 607 | ref_cvt_pk_u8_f32(f32_bits(35.5), 1, OLD), | ||
| 608 | ref_cvt_pk_u8_f32(f32_bits(86.0), 7, OLD), | ||
| 609 | ref_cvt_pk_u8_f32(f32_bits(12.5), 1, f32_bits(12.5)), | ||
| 610 | )) | ||
| 611 | |||
| 612 | # 5. All four operands alias v0: 0x41480003 is 12.500003 -> byte 13 (0x0D) at slot (0x41480003 & 3 == 3). | ||
| 613 | all_alias_in = 0x41480003 | ||
| 614 | got_all = run_ps_mrt0([ | ||
| 615 | f"v_mov_b32 v0, {all_alias_in:#x}", | ||
| 616 | "v_cvt_pk_u8_f32 v0, v0, v0, v0", | ||
| 617 | ])[0] | ||
| 618 | self.assertEqual(got_all, ref_cvt_pk_u8_f32(all_alias_in, all_alias_in, all_alias_in)) | ||
| 619 | self.assertEqual(got_all, 0x0D480003) | ||
| 620 | |||
| 621 | |||
| 622 | class ExecMaskingTests(unittest.TestCase): | ||
| 623 | def test_single_lane_exec_mask_preserves_destination(self): | ||
| 624 | # Inactive lane leaves v0 untouched; disabled instruction before re-enabling EXEC is skipped. | ||
| 625 | got = run_ps_mrt0([ | ||
| 626 | f"v_mov_b32 v1, {f32_bits(77.0):#x}", | ||
| 627 | f"v_mov_b32 v3, {CANARY:#x}", | ||
| 628 | f"v_mov_b32 v10, {OLD:#x}", | ||
| 629 | f"v_mov_b32 v11, {OLD:#x}", | ||
| 630 | "s_mov_b32 exec_lo, 0", | ||
| 631 | "v_cvt_pk_u8_f32 v10, v1, 1, v3", | ||
| 632 | "v_cvt_pk_u8_f32 v11, v1, 0, v3", | ||
| 633 | "s_mov_b32 exec_lo, -1", | ||
| 634 | "v_cvt_pk_u8_f32 v11, v1, 2, v3", | ||
| 635 | ], ("v10", "v11", "v10", "v11")) | ||
| 636 | self.assertEqual(got[:2], (OLD, ref_cvt_pk_u8_f32(f32_bits(77.0), 2, CANARY))) | ||
| 637 | |||
| 638 | def test_multilane_compute_exec_masking(self): | ||
| 639 | # 16 lanes in lockstep: odd lanes are masked off via v_cmpx_eq_u32 before v_cvt_pk_u8_f32, | ||
| 640 | # so active even lanes write the converted byte into OLD while inactive odd lanes keep OLD. | ||
| 641 | lane_floats = [f32_bits(float(i * 15) + 0.5) for i in range(16)] | ||
| 642 | mem = _Heap({0x100 + 4 * i: w for i, w in enumerate(lane_floats)}) | ||
| 643 | run_cs([ | ||
| 644 | "v_lshlrev_b32_e32 v5, 2, v0", | ||
| 645 | "v_add_nc_u32_e32 v6, 0x100, v5", | ||
| 646 | "buffer_load_dword v1, v6, s[0:3], 0 offen", | ||
| 647 | f"v_mov_b32_e32 v2, {OLD:#x}", | ||
| 648 | f"v_mov_b32_e32 v3, {OLD:#x}", | ||
| 649 | "v_and_b32_e32 v4, 1, v0", | ||
| 650 | "v_cmpx_eq_u32_e32 0, v4", # keep even lanes active | ||
| 651 | "v_cvt_pk_u8_f32_e64 v2, v1, v0, v3", | ||
| 652 | "s_mov_b32 exec_lo, -1", | ||
| 653 | "buffer_store_dword v2, v5, s[0:3], 0 offen", | ||
| 654 | ], group_size=16, subgroup_size=32, memory=mem) | ||
| 655 | |||
| 656 | got = [mem.get(4 * i) for i in range(16)] | ||
| 657 | want = [ | ||
| 658 | ref_cvt_pk_u8_f32(lane_floats[i], i, OLD) if (i & 1) == 0 else OLD | ||
| 659 | for i in range(16) | ||
| 660 | ] | ||
| 661 | self.assertEqual(got, want) | ||
| 662 | |||
| 663 | |||
| 664 | # ----------------------------------------------------------------------------- | ||
| 665 | # 5. NaN Inputs (Documented Open Gap in Translator SPIR-V Lowering) | ||
| 666 | # ----------------------------------------------------------------------------- | ||
| 667 | |||
| 668 | class NaNHandlingTests(unittest.TestCase): | ||
| 669 | """v_cvt_pk_u8_f32 emits FClamp without an OpIsNan guard (docs/design.md line 287). | ||
| 670 | |||
| 671 | In spirv_mini_interp.py, FClamp on NaN raises UnsupportedConstruct because GLSL.std.450 leaves it undefined. | ||
| 672 | """ | ||
| 673 | |||
| 674 | def test_nan_translation_and_interpreter_rejection(self): | ||
| 675 | nan_cases = [ | ||
| 676 | ("qnan", F32_QNAN, "v1"), | ||
| 677 | ("neg_qnan", F32_NEG_QNAN, "v1"), | ||
| 678 | ("qnan_payload", F32_QNAN_PAYLOAD, "v1"), | ||
| 679 | ("snan", F32_SNAN, "v1"), | ||
| 680 | ("neg_snan", F32_NEG_SNAN, "v1"), | ||
| 681 | ("qnan_abs", F32_NEG_QNAN, "|v1|"), | ||
| 682 | ("qnan_neg", F32_QNAN, "-v1"), | ||
| 683 | ] | ||
| 684 | for label, xb, expr in nan_cases: | ||
| 685 | with self.subTest(case=label): | ||
| 686 | spv = translate_ps([ | ||
| 687 | f"v_mov_b32 v1, {xb:#x}", | ||
| 688 | f"v_mov_b32 v3, {OLD:#x}", | ||
| 689 | f"v_cvt_pk_u8_f32_e64 v0, {expr}, 0, v3", | ||
| 690 | "exp mrt0 v0, v0, v0, v0 done vm", | ||
| 691 | ]) | ||
| 692 | self.assertIn("glsl FClamp", spv) | ||
| 693 | self.assertIn("glsl RoundEven", spv) | ||
| 694 | self.assertIn("OpConvertFToU", spv) | ||
| 695 | with self.assertRaisesRegex(si.UnsupportedConstruct, r"FClamp.*undefined"): | ||
| 696 | si.run_fragment(spv) | ||
| 697 | |||
| 698 | |||
| 699 | # ----------------------------------------------------------------------------- | ||
| 700 | # 6. Negative Controls (SPIR-V Sabotage Detection) | ||
| 701 | # ----------------------------------------------------------------------------- | ||
| 702 | |||
| 703 | class NegativeControlsTests(unittest.TestCase): | ||
| 704 | def test_sabotage_round_even_to_trunc(self): | ||
| 705 | # 1.5 -> RoundEven gives 2, whereas Trunc gives 1. | ||
| 706 | good = translate_ps([ | ||
| 707 | f"v_mov_b32 v1, {f32_bits(1.5):#x}", | ||
| 708 | f"v_mov_b32 v3, {OLD:#x}", | ||
| 709 | "v_cvt_pk_u8_f32 v0, v1, 1, v3", | ||
| 710 | "exp mrt0 v0, v0, v0, v0 done vm", | ||
| 711 | ]) | ||
| 712 | want = ref_cvt_pk_u8_f32(f32_bits(1.5), 1, OLD) | ||
| 713 | self.assertEqual(si.run_fragment(good)["%out_mrt0"][0], want) | ||
| 714 | |||
| 715 | bad, n = re.subn(r"\bRoundEven\b", "Trunc", good) | ||
| 716 | self.assertEqual(n, 1) | ||
| 717 | got_bad = si.run_fragment(bad)["%out_mrt0"][0] | ||
| 718 | self.assertNotEqual(got_bad, want) | ||
| 719 | self.assertEqual(got_bad, 0xDEAD01EF) | ||
| 720 | |||
| 721 | def test_sabotage_missing_slot_shift(self): | ||
| 722 | # Removing the * 8 shift (OpIMul %uint %slot3 %c8 -> %c0) writes slot 0 instead of slot 2. | ||
| 723 | good = translate_ps([ | ||
| 724 | f"v_mov_b32 v1, {f32_bits(0x42):#x}", | ||
| 725 | f"v_mov_b32 v3, {OLD:#x}", | ||
| 726 | "v_cvt_pk_u8_f32 v0, v1, 2, v3", | ||
| 727 | "exp mrt0 v0, v0, v0, v0 done vm", | ||
| 728 | ]) | ||
| 729 | want = ref_cvt_pk_u8_f32(f32_bits(0x42), 2, OLD) | ||
| 730 | self.assertEqual(si.run_fragment(good)["%out_mrt0"][0], want) | ||
| 731 | |||
| 732 | bad, n = re.subn(r"OpIMul %uint (%\w+) %c8\b", r"OpIMul %uint \1 %c0", good) | ||
| 733 | self.assertEqual(n, 1) | ||
| 734 | got_bad = si.run_fragment(bad)["%out_mrt0"][0] | ||
| 735 | self.assertNotEqual(got_bad, want) | ||
| 736 | self.assertEqual(got_bad, ref_cvt_pk_u8_f32(f32_bits(0x42), 0, OLD)) | ||
| 737 | |||
| 738 | def test_sabotage_missing_slot_mask(self): | ||
| 739 | # Widening slot & 3 to slot & 7 breaks slot 5 (shift = 40 >= 32 -> undefined in SPIR-V). | ||
| 740 | good = translate_ps([ | ||
| 741 | f"v_mov_b32 v1, {f32_bits(0x42):#x}", | ||
| 742 | f"v_mov_b32 v2, 5", | ||
| 743 | f"v_mov_b32 v3, {OLD:#x}", | ||
| 744 | "v_cvt_pk_u8_f32 v0, v1, v2, v3", | ||
| 745 | "exp mrt0 v0, v0, v0, v0 done vm", | ||
| 746 | ]) | ||
| 747 | want = ref_cvt_pk_u8_f32(f32_bits(0x42), 5, OLD) | ||
| 748 | self.assertEqual(si.run_fragment(good)["%out_mrt0"][0], want) | ||
| 749 | |||
| 750 | bad, n = re.subn(r"OpBitwiseAnd %uint (%\w+) %c3\b", r"OpBitwiseAnd %uint \1 %c7", good) | ||
| 751 | self.assertEqual(n, 1) | ||
| 752 | with self.assertRaises(si.UnsupportedConstruct): | ||
| 753 | si.run_fragment(bad) | ||
| 754 | |||
| 755 | |||
| 756 | if __name__ == "__main__": | ||
| 757 | unittest.main() | ||
diff --git a/tests/semantic/test_valu_f32_class_rndne.py b/tests/semantic/test_valu_f32_class_rndne.py index d57dd546f..618a2a94d 100644 --- a/tests/semantic/test_valu_f32_class_rndne.py +++ b/tests/semantic/test_valu_f32_class_rndne.py | |||
| @@ -17,15 +17,15 @@ run_fragment and multi-lane compute run_workgroup), and checked against hand-com | |||
| 17 | plain-Python RDNA2 ISA reference functions. Standard library only; hand-written RDNA2 listings only. | 17 | plain-Python RDNA2 ISA reference functions. Standard library only; hand-written RDNA2 listings only. |
| 18 | 18 | ||
| 19 | Findings & exclusions (no shared files modified): | 19 | Findings & exclusions (no shared files modified): |
| 20 | 1. v_rcp_iflag_f32 CANNOT execute in tests/semantic/spirv_mini_interp.py: | 20 | 1. v_rcp_iflag_f32 lowers to `OpFDiv %float %f1 {x}` followed by the VOP3 output modifiers (`clamp`, `mul:2`, |
| 21 | tools/rdna2spirv.py (lines 3693-3697) lowers v_rcp_iflag_f32 to `OpFDiv %float %f1 {x}`, and | 21 | `mul:4`, `div:2`) through `clamp_mods`, as `v_rcp_f32` does. When this file was written the translator dropped |
| 22 | tests/semantic/spirv_mini_interp.py does not implement `OpFDiv` (it raises `UnsupportedConstruct: OpFDiv`). | 22 | those modifiers and spirv_mini_interp.py had no `OpFDiv`; both have changed since (FUZZ-3, ed6da6b6), so |
| 23 | In addition, tools/rdna2spirv.py line 3697 emits `self.dst(a[0], self.tou(r))` without calling | 23 | RcpIflagF32OracleAndTranslationTests now executes it on exact inputs (powers of two, so the 1-ULP hardware |
| 24 | `self.clamp_mods(r, mods)` (unlike `v_rcp_f32` at line 3737 and `v_rndne_f32` at line 2178), so VOP3 output | 24 | approximation and the interpreter's exact division agree) with each output modifier. A zero operand stays |
| 25 | modifiers (`clamp`, `mul:2`, `mul:4`, `div:2`) on `v_rcp_iflag_f32_e64` are silently dropped by the translator. | 25 | out: `OpFDiv` by zero is undefined in SPIR-V and the interpreter refuses it (docs/design.md, "Denormal flush |
| 26 | Accordingly, `v_rcp_iflag_f32` is excluded from `spirv_mini_interp.py` value-execution assertions; its | 26 | and special results", Not modelled yet). gfx1036 hardware agrees with the translator on 2,570 of 3,000 fuzzed |
| 27 | independent RDNA2 ISA reference oracle and hand-worked constants are checked in OracleTests, and its | 27 | programs with clamp/omod and differs on none (`tools/f32_fuzz.py --oracle translator,hw --ops |
| 28 | SPIR-V translation (`OpFDiv %float %f1 ...`) is checked structurally in RcpIflagF32OracleAndTranslationTests. | 28 | v_rcp_iflag_f32`, seeds 1 to 3; the rest are division by zero or cases the model does not judge). |
| 29 | 2. NaN caveats in SPIR-V / spirv_mini_interp.py: | 29 | 2. NaN caveats in SPIR-V / spirv_mini_interp.py: |
| 30 | - For `v_rndne_f32` on NaN (`qNaN` / `sNaN`), SPIR-V / GLSL.std.450 `RoundEven` leaves NaN payload/quieting | 30 | - For `v_rndne_f32` on NaN (`qNaN` / `sNaN`), SPIR-V / GLSL.std.450 `RoundEven` leaves NaN payload/quieting |
| 31 | unspecified (spirv_mini_interp.py returns the input NaN unchanged; hardware quiets `sNaN`). Tests assert | 31 | unspecified (spirv_mini_interp.py returns the input NaN unchanged; hardware quiets `sNaN`). Tests assert |
| @@ -729,16 +729,47 @@ class RndneF32Tests(unittest.TestCase): | |||
| 729 | 729 | ||
| 730 | 730 | ||
| 731 | # ----------------------------------------------------------------------------- | 731 | # ----------------------------------------------------------------------------- |
| 732 | # 4. v_rcp_iflag_f32 (Excluded from spirv_mini_interp execution; documented finding) | 732 | # 4. v_rcp_iflag_f32 |
| 733 | # ----------------------------------------------------------------------------- | 733 | # ----------------------------------------------------------------------------- |
| 734 | 734 | ||
| 735 | class RcpIflagF32OracleAndTranslationTests(unittest.TestCase): | 735 | class RcpIflagF32OracleAndTranslationTests(unittest.TestCase): |
| 736 | """Documents and checks translation for v_rcp_iflag_f32 without executing OpFDiv in spirv_mini_interp.py. | 736 | """Checks the translation of v_rcp_iflag_f32 and executes it with source and output modifiers. |
| 737 | 737 | ||
| 738 | See module docstring: spirv_mini_interp.py raises UnsupportedConstruct("OpFDiv"), and tools/rdna2spirv.py | 738 | See module docstring, finding 1: exact (power-of-two) inputs only, and no zero operand. |
| 739 | omits clamp_mods on v_rcp_iflag_f32. | ||
| 740 | """ | 739 | """ |
| 741 | 740 | ||
| 741 | def test_executes_with_output_modifiers(self): | ||
| 742 | got = run_ps_mrt0([ | ||
| 743 | "v_mov_b32 v1, 0x40000000", # +2.0 | ||
| 744 | "v_rcp_iflag_f32_e64 v10, v1 mul:2", # 0.5 * 2 = 1.0 | ||
| 745 | "v_rcp_iflag_f32_e64 v11, v1 mul:4", # 0.5 * 4 = 2.0 | ||
| 746 | "v_rcp_iflag_f32_e64 v12, v1 div:2", # 0.5 / 2 = 0.25 | ||
| 747 | "v_rcp_iflag_f32_e64 v13, -v1 clamp", # clamp(-0.5, 0, 1) = +0.0 | ||
| 748 | ], ("v10", "v11", "v12", "v13")) | ||
| 749 | self.assertEqual(got, (f32_bits(1.0), f32_bits(2.0), f32_bits(0.25), f32_bits(0.0))) | ||
| 750 | |||
| 751 | got2 = run_ps_mrt0([ | ||
| 752 | "v_mov_b32 v1, 0x3e800000", # +0.25 | ||
| 753 | "v_rcp_iflag_f32_e64 v10, v1 clamp", # clamp(4.0, 0, 1) = 1.0 | ||
| 754 | "v_rcp_iflag_f32_e64 v11, -|v1|", # -4.0 | ||
| 755 | "v_rcp_iflag_f32_e64 v12, v1 div:2 clamp", # clamp(2.0, 0, 1) = 1.0 | ||
| 756 | "v_rcp_iflag_f32_e32 v13, v1", # 4.0, no modifiers | ||
| 757 | ], ("v10", "v11", "v12", "v13")) | ||
| 758 | self.assertEqual(got2, (f32_bits(1.0), f32_bits(-4.0), f32_bits(1.0), f32_bits(4.0))) | ||
| 759 | for x_bits, want in ((0x40000000, 0x3F000000), (0x3E800000, 0x40800000), (0xC0000000, 0xBF000000)): | ||
| 760 | with self.subTest(x=f"{x_bits:#010x}"): | ||
| 761 | self.assertEqual(ref_rcp_iflag_f32(x_bits), want) | ||
| 762 | |||
| 763 | def test_dropping_output_modifiers_is_detected(self): | ||
| 764 | # Negative control: if the translator stopped applying the modifier, mul:2 would read back 0.5, not 1.0. | ||
| 765 | good = translate_ps(["v_mov_b32 v1, 0x40000000", "v_rcp_iflag_f32_e64 v0, v1 mul:2", | ||
| 766 | "exp mrt0 v0, v0, v0, v0 done vm"]) | ||
| 767 | self.assertEqual(si.run_fragment(good)["%out_mrt0"][0], f32_bits(1.0)) | ||
| 768 | bad, n = re.subn(r"^(\s*%\w+) = OpFMul %float (%\w+) %\w+$", r"\1 = OpFMul %float \2 %f1", good, | ||
| 769 | count=1, flags=re.M) | ||
| 770 | self.assertEqual(n, 1) | ||
| 771 | self.assertNotEqual(si.run_fragment(bad)["%out_mrt0"][0], f32_bits(1.0)) | ||
| 772 | |||
| 742 | def test_translates_to_op_fdiv_with_no_contraction(self): | 773 | def test_translates_to_op_fdiv_with_no_contraction(self): |
| 743 | for line in ( | 774 | for line in ( |
| 744 | "v_rcp_iflag_f32_e32 v0, v1", | 775 | "v_rcp_iflag_f32_e32 v0, v1", |
diff --git a/tests/semantic/test_valu_fma_mix.py b/tests/semantic/test_valu_fma_mix.py index 1d0730fe3..6c2a39cc6 100644 --- a/tests/semantic/test_valu_fma_mix.py +++ b/tests/semantic/test_valu_fma_mix.py | |||
| @@ -212,6 +212,25 @@ class FmaMixF16Tests(unittest.TestCase): | |||
| 212 | got = run("v_fma_mixhi_f16 v0, v0, v1, v2 op_sel:[0,0,0] op_sel_hi:[1,0,1]", f2u(2.0), pack_h(0.5, 9.0), 0, old=old) | 212 | got = run("v_fma_mixhi_f16 v0, v0, v1, v2 op_sel:[0,0,0] op_sel_hi:[1,0,1]", f2u(2.0), pack_h(0.5, 9.0), 0, old=old) |
| 213 | self.assertEqual(got, pack_h(1.5, 3.5)) | 213 | self.assertEqual(got, pack_h(1.5, 3.5)) |
| 214 | 214 | ||
| 215 | def test_single_rounding_discriminating_cases(self): | ||
| 216 | # Discriminating test cases A through G from tools/fma_mix_probe.py where | ||
| 217 | # hardware single rounding gives 1 ulp difference from double rounding. | ||
| 218 | # Case A: 1 * 2^-40 + (1 + 2^-11) -> single: 0x3c01, double: 0x3c00 | ||
| 219 | got_a = run("v_fma_mixlo_f16 v0, v1, v2, v3", 0x3F800000, 0x2B800000, 0x3F801000, old=OLD) | ||
| 220 | self.assertEqual(got_a, (OLD & 0xFFFF0000) | 0x3C01) | ||
| 221 | |||
| 222 | # Case B: 1 * -2^-40 + (1 + 3 * 2^-11) -> single: 0x3c01, double: 0x3c02 | ||
| 223 | got_b = run("v_fma_mixhi_f16 v0, v1, v2, v3", 0x3F800000, 0xAB800000, 0x3F803000, old=OLD) | ||
| 224 | self.assertEqual(got_b, (0x3C01 << 16) | (OLD & 0xFFFF)) | ||
| 225 | |||
| 226 | # Case C: -1 * 2^-40 - (1 + 2^-11) -> single: 0xbc01, double: 0xbc00 | ||
| 227 | got_c = run("v_fma_mixlo_f16 v0, v1, v2, v3", 0xBF800000, 0x2B800000, 0xBF801000, old=OLD) | ||
| 228 | self.assertEqual(got_c, (OLD & 0xFFFF0000) | 0xBC01) | ||
| 229 | |||
| 230 | # Case G (f16 operands): (1 + 2^-7) * (2^-11 - 2^-18) + (1 + 2^-10) -> single: 0x3c01, double: 0x3c02 | ||
| 231 | got_g = run("v_fma_mixlo_f16 v0, v1, v2, v3 op_sel_hi:[1,1,1]", 0x3C08, 0x0FF0, 0x3C01, old=OLD) | ||
| 232 | self.assertEqual(got_g, (OLD & 0xFFFF0000) | 0x3C01) | ||
| 233 | |||
| 215 | 234 | ||
| 216 | class NegativeControls(unittest.TestCase): | 235 | class NegativeControls(unittest.TestCase): |
| 217 | """Sabotaging the translated SPIR-V must change the observed output.""" | 236 | """Sabotaging the translated SPIR-V must change the observed output.""" |
| @@ -226,5 +245,52 @@ class NegativeControls(unittest.TestCase): | |||
| 226 | self.assertNotEqual(si.run_fragment(bad)["%out_mrt0"][0], good) | 245 | self.assertNotEqual(si.run_fragment(bad)["%out_mrt0"][0], good) |
| 227 | 246 | ||
| 228 | 247 | ||
| 248 | class FmaMixF32DenormalOperandTests(unittest.TestCase): | ||
| 249 | """SHADER-298: an f32 operand of v_fma_mix* that is denormal reads as a zero of its sign (the game's MODE has | ||
| 250 | denorm_mode_32 = 0), measured on gfx1036 by @Sanonymous01 for 0x00000001, 0x807fffff and the integer inline | ||
| 251 | constants 1 and 64. The result is not flushed here (not measured), so 0 * y + denormal keeps the denormal only | ||
| 252 | when the denormal is not an operand, which cannot happen; the checks below use operands only.""" | ||
| 253 | |||
| 254 | BIG = f2u(1.0e30) | ||
| 255 | ZERO = 0x00000000 | ||
| 256 | NEG_ZERO = 0x80000000 | ||
| 257 | |||
| 258 | def test_denormal_multiplicand_reads_as_zero(self): | ||
| 259 | # 1.4e-45 * 1e30 = 1.4e-15 if the denormal is kept; 0 if it is flushed. | ||
| 260 | for d in (0x00000001, 0x007FFFFF): | ||
| 261 | with self.subTest(denormal=hex(d), slot="src0"): | ||
| 262 | self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", d, self.BIG, self.ZERO), 0x00000000) | ||
| 263 | with self.subTest(denormal=hex(d), slot="src1"): | ||
| 264 | self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", self.BIG, d, self.ZERO), 0x00000000) | ||
| 265 | |||
| 266 | def test_negative_denormal_reads_as_negative_zero(self): | ||
| 267 | # (-0) * 1e30 + (-0) = -0; a kept denormal would give -1.1e-8-ish tiny non-zero. | ||
| 268 | for d in (0x80000001, 0x807FFFFF): | ||
| 269 | with self.subTest(denormal=hex(d)): | ||
| 270 | self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", d, self.BIG, self.NEG_ZERO), 0x80000000) | ||
| 271 | |||
| 272 | def test_denormal_addend_reads_as_zero(self): | ||
| 273 | # 0 * y + denormal: the denormal addend is flushed, so the result is +0 (kept it would be the denormal). | ||
| 274 | self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", self.ZERO, self.BIG, 0x00000001), 0x00000000) | ||
| 275 | |||
| 276 | def test_integer_inline_constants_are_denormal_f32_operands(self): | ||
| 277 | # `1` and `64` in an f32 operand slot are the words 0x00000001 and 0x00000040: denormal, flushed to +0. | ||
| 278 | for const in ("1", "64"): | ||
| 279 | with self.subTest(const=const): | ||
| 280 | self.assertEqual(run(f"v_fma_mix_f32 v0, {const}, v2, v3", self.ZERO, self.BIG, self.ZERO), 0x00000000) | ||
| 281 | |||
| 282 | def test_normal_operands_are_untouched(self): | ||
| 283 | a, b, c = f2u(2.5), f2u(-1.25), f2u(0.75) | ||
| 284 | self.assertEqual(run("v_fma_mix_f32 v0, v1, v2, v3", a, b, c), f2u(ref_fma(a, b, c, (0, 0, 0), (0, 0, 0)))) | ||
| 285 | smallest_normal = 0x00800000 # 2**-126 is the first value that is not flushed | ||
| 286 | got = run("v_fma_mix_f32 v0, v1, v2, v3", smallest_normal, f2u(1.0), self.ZERO) | ||
| 287 | self.assertEqual(got, smallest_normal) | ||
| 288 | |||
| 289 | def test_the_flush_reaches_the_f16_result(self): | ||
| 290 | # 1.4e-45 * 3e37 = 4.2e-8 rounds to the f16 subnormal 0x0001 if the denormal is kept, and is 0 flushed. | ||
| 291 | got = run("v_fma_mixlo_f16 v0, v1, v2, v3", 0x00000001, f2u(3.0e37), self.ZERO, old=0xAAAA0000) | ||
| 292 | self.assertEqual(got, 0xAAAA0000) | ||
| 293 | |||
| 294 | |||
| 229 | if __name__ == "__main__": | 295 | if __name__ == "__main__": |
| 230 | unittest.main() | 296 | unittest.main() |
diff --git a/tests/semantic/test_valu_fract_f16.py b/tests/semantic/test_valu_fract_f16.py new file mode 100644 index 000000000..aabad97c6 --- /dev/null +++ b/tests/semantic/test_valu_fract_f16.py | |||
| @@ -0,0 +1,703 @@ | |||
| 1 | """End-to-end semantic value tests for RDNA2 v_fract_f16 (S0.f16 - floor(S0.f16)). | ||
| 2 | |||
| 3 | Covers v_fract_f16 executed end-to-end through tools/rdna2spirv.py and | ||
| 4 | tests/semantic/spirv_mini_interp.py against an independent Fraction-based | ||
| 5 | IEEE-754 binary16 `x - floor(x)` oracle: | ||
| 6 | - Positive & negative finite non-integers, including tiny negatives and | ||
| 7 | negative subnormals (-0.0001, -1e-5, -2**-12, -2**-24) whose exact | ||
| 8 | x - floor(x) rounds to 1.0 in binary16 and maps to 0x3bff (the largest | ||
| 9 | binary16 strictly below 1.0), plus the adjacent 0x3bfe / 0x3bff edge. | ||
| 10 | - Exact integers (0.0, 1.0, -1.0, 65504.0, -65504.0 -> +0.0) and -0.0 -> +0.0. | ||
| 11 | - +-inf and qNaN/sNaN behavior (GLSL.std.450 Fract returns NaN; fract_below_one | ||
| 12 | uses OpFOrdEqual + OpSelect so NaN survives into f16_bits -> qNaN). | ||
| 13 | - _e32, _e64, and bare mnemonics, keeping the untouched 16-bit half of dst. | ||
| 14 | - Runtime memory inputs via s_buffer_load_dwordx4 alongside immediate inputs. | ||
| 15 | - All 4 op_sel:[src,dst] combinations ([0,0], [1,0], [0,1], [1,1]). | ||
| 16 | - VOP3 source modifiers (-v1, |v1|, -|v1|) and output modifiers | ||
| 17 | (clamp, mul:2, mul:4, div:2, mul:2 clamp, mul:4 clamp). | ||
| 18 | - Inline f16 constants (0.5, -0.5, 1.0, -1.0), SGPR sources, destination | ||
| 19 | aliasing (v0, v0), single-lane and multi-lane EXEC masking, and SPIR-V | ||
| 20 | sabotage negative controls (Fract -> Trunc / Floor). | ||
| 21 | |||
| 22 | Note: Under VOP3 `clamp`, GLSL.std.450 FClamp on NaN is undefined in SPIR-V | ||
| 23 | and spirv_mini_interp.py raises UnsupportedConstruct (documented in | ||
| 24 | docs/design.md), so `clamp` value tests use finite inputs. Standard library | ||
| 25 | only; hand-written RDNA2 disassembly listings only; zero game data. | ||
| 26 | """ | ||
| 27 | from fractions import Fraction | ||
| 28 | import gc | ||
| 29 | import itertools | ||
| 30 | import math | ||
| 31 | import os | ||
| 32 | import re | ||
| 33 | import struct | ||
| 34 | import sys | ||
| 35 | import tempfile | ||
| 36 | import unittest | ||
| 37 | import warnings | ||
| 38 | |||
| 39 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 40 | ROOT = os.path.dirname(os.path.dirname(HERE)) | ||
| 41 | TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") | ||
| 42 | |||
| 43 | sys.dont_write_bytecode = True | ||
| 44 | if TOOLS_DIR not in sys.path: | ||
| 45 | sys.path.insert(0, TOOLS_DIR) | ||
| 46 | if HERE not in sys.path: | ||
| 47 | sys.path.insert(0, HERE) | ||
| 48 | |||
| 49 | import rdna2spirv # noqa: E402 | ||
| 50 | import spirv_mini_interp as si # noqa: E402 | ||
| 51 | |||
| 52 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 53 | OLD = 0xBEEF1234 | ||
| 54 | PUSH_ADDR = [0x1000, 0, 32, 0] + [0] * 28 | ||
| 55 | VSHARP_CS = [0, 0, 0xFFFFFFFF, 0x31016FAC] | ||
| 56 | HEAP_FILL = 0xEEEEEEEE | ||
| 57 | |||
| 58 | # Representative binary16 encodings (cross-checked in OracleTests). | ||
| 59 | H_POS_ZERO = 0x0000 # +0.0 | ||
| 60 | H_NEG_ZERO = 0x8000 # -0.0 | ||
| 61 | H_SUB_MIN = 0x0001 # +2^-24 (~5.96e-8) | ||
| 62 | H_NEG_SUB_MIN = 0x8001 # -2^-24 | ||
| 63 | H_SUB_1E5 = 0x00A8 # +1e-5 rounded to f16 subnormal (~1.001e-5) | ||
| 64 | H_NEG_SUB_1E5 = 0x80A8 # -1e-5 rounded to f16 subnormal (~-1.001e-5) | ||
| 65 | H_SUB_MAX = 0x03FF # +1023 * 2^-24 (largest +subnormal) | ||
| 66 | H_NEG_SUB_MAX = 0x83FF # -1023 * 2^-24 (largest-magnitude -subnormal) | ||
| 67 | H_NORM_MIN = 0x0400 # +2^-14 (smallest +normal) | ||
| 68 | H_NEG_NORM_MIN = 0x8400 # -2^-14 | ||
| 69 | H_1E4 = 0x068E # +0.0001 rounded to f16 (~1.000166e-4) | ||
| 70 | H_NEG_1E4 = 0x868E # -0.0001 rounded to f16 (~-1.000166e-4) | ||
| 71 | H_2PM13 = 0x0800 # +2^-13 | ||
| 72 | H_NEG_2PM13 = 0x8800 # -2^-13 | ||
| 73 | H_NEG_2PM12_M = 0x8BFF # -(2^-12 - 2^-23): just above -2^-12 | ||
| 74 | H_NEG_2PM12 = 0x8C00 # -2^-12: exact tie between 0x3bff and 0x3c00 | ||
| 75 | H_NEG_2PM12_P = 0x8C01 # -(2^-12 + 2^-22): strictly closer to 0x3bff | ||
| 76 | H_NEG_3P2M13 = 0x8E00 # -3 * 2^-13: strictly closer to 0x3bff | ||
| 77 | H_NEG_2PM11 = 0x9000 # -2^-11: 1 - 2^-11 = 0x3bff exact | ||
| 78 | H_NEG_3P2M12 = 0x9200 # -3 * 2^-12: exact tie between 0x3bfe (even) and 0x3bff (odd) -> 0x3bfe | ||
| 79 | H_NEG_2PM10 = 0x9400 # -2^-10: 1 - 2^-10 = 0x3bfe exact | ||
| 80 | H_0P125 = 0x3000 # 0.125 | ||
| 81 | H_0P25 = 0x3400 # 0.25 | ||
| 82 | H_NEG_0P25 = 0xB400 # -0.25 | ||
| 83 | H_0P375 = 0x3600 # 0.375 | ||
| 84 | H_0P5 = 0x3800 # 0.5 | ||
| 85 | H_NEG_0P5 = 0xB800 # -0.5 | ||
| 86 | H_0P75 = 0x3A00 # 0.75 | ||
| 87 | H_NEG_0P75 = 0xBA00 # -0.75 | ||
| 88 | H_NEAR_ONE = 0x3BFF # 1 - 2^-11 (largest f16 < 1.0) | ||
| 89 | H_1P0 = 0x3C00 # 1.0 | ||
| 90 | H_NEG_1P0 = 0xBC00 # -1.0 | ||
| 91 | H_1P25 = 0x3D00 # 1.25 | ||
| 92 | H_NEG_1P25 = 0xBD00 # -1.25 | ||
| 93 | H_1P5 = 0x3E00 # 1.5 | ||
| 94 | H_NEG_1P5 = 0xBE00 # -1.5 | ||
| 95 | H_1P75 = 0x3F00 # 1.75 | ||
| 96 | H_NEG_1P75 = 0xBF00 # -1.75 | ||
| 97 | H_2P0 = 0x4000 # 2.0 | ||
| 98 | H_NEG_2P0 = 0xC000 # -2.0 | ||
| 99 | H_2P5 = 0x4100 # 2.5 | ||
| 100 | H_NEG_2P5 = 0xC100 # -2.5 | ||
| 101 | H_3P0 = 0x4200 # 3.0 | ||
| 102 | H_NEG_3P0 = 0xC200 # -3.0 | ||
| 103 | H_3P75 = 0x4380 # 3.75 | ||
| 104 | H_NEG_3P75 = 0xC380 # -3.75 | ||
| 105 | H_1023P5 = 0x63FF # 1023.5 | ||
| 106 | H_NEG_1023P5 = 0xE3FF # -1023.5 | ||
| 107 | H_1024 = 0x6400 # 1024.0 | ||
| 108 | H_NEG_1024 = 0xE400 # -1024.0 | ||
| 109 | H_MAX = 0x7BFF # 65504.0 | ||
| 110 | H_NEG_MAX = 0xFBFF # -65504.0 | ||
| 111 | H_POS_INF = 0x7C00 # +inf | ||
| 112 | H_NEG_INF = 0xFC00 # -inf | ||
| 113 | H_QNAN = 0x7E01 # +qNaN | ||
| 114 | H_NEG_QNAN = 0xFE01 # -qNaN | ||
| 115 | H_SNAN = 0x7C01 # +sNaN | ||
| 116 | H_NEG_SNAN = 0xFC01 # -sNaN | ||
| 117 | |||
| 118 | |||
| 119 | # ----------------------------------------------------------------------------- | ||
| 120 | # Independent Fraction-Based IEEE-754 Binary16 Oracle | ||
| 121 | # ----------------------------------------------------------------------------- | ||
| 122 | |||
| 123 | def h16_is_finite(h: int) -> bool: | ||
| 124 | return ((h >> 10) & 0x1F) != 0x1F | ||
| 125 | |||
| 126 | |||
| 127 | def h16_is_nan(h: int) -> bool: | ||
| 128 | return (h & 0x7FFF) > 0x7C00 | ||
| 129 | |||
| 130 | |||
| 131 | def h16_is_inf(h: int) -> bool: | ||
| 132 | return (h & 0x7FFF) == 0x7C00 | ||
| 133 | |||
| 134 | |||
| 135 | def h16_to_fraction(h: int) -> Fraction: | ||
| 136 | """Decode finite IEEE-754 binary16 bit pattern ``h`` into an exact Fraction.""" | ||
| 137 | h &= 0xFFFF | ||
| 138 | exp = (h >> 10) & 0x1F | ||
| 139 | if exp == 0x1F: | ||
| 140 | raise ValueError(f"non-finite binary16 {h:#06x}") | ||
| 141 | sign = -1 if (h >> 15) else 1 | ||
| 142 | mant = h & 0x3FF | ||
| 143 | if exp == 0: | ||
| 144 | return Fraction(0) if mant == 0 else Fraction(sign * mant, 1 << 24) | ||
| 145 | return Fraction(sign * ((1 << 10) | mant)) * (Fraction(2) ** (exp - 25)) | ||
| 146 | |||
| 147 | |||
| 148 | def fraction_to_h16(q: Fraction) -> int: | ||
| 149 | """Round an exact Fraction to IEEE-754 binary16 (nearest, ties to even).""" | ||
| 150 | if q == 0: | ||
| 151 | return H_POS_ZERO | ||
| 152 | sgn = 0x8000 if q < 0 else 0 | ||
| 153 | a = abs(q) | ||
| 154 | e = max(a.numerator.bit_length() - a.denominator.bit_length(), -14) | ||
| 155 | if e > -14 and Fraction(2) ** e > a: | ||
| 156 | e -= 1 | ||
| 157 | m = a / (Fraction(2) ** (e - 10)) | ||
| 158 | n = m.numerator // m.denominator | ||
| 159 | rem = m - n | ||
| 160 | if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (n & 1)): | ||
| 161 | n += 1 | ||
| 162 | if e == -14 and n < 1024: | ||
| 163 | return sgn | n | ||
| 164 | if n >= 2048: | ||
| 165 | n >>= 1 | ||
| 166 | e += 1 | ||
| 167 | if e > 15: | ||
| 168 | return sgn | H_POS_INF | ||
| 169 | return sgn | ((e + 15) << 10) | (n - 1024) | ||
| 170 | |||
| 171 | |||
| 172 | def exact_fract_fraction(h: int) -> Fraction | None: | ||
| 173 | """Exact ``x - floor(x)`` as a Fraction in [0, 1), or None for +-inf / NaN.""" | ||
| 174 | if not h16_is_finite(h): | ||
| 175 | return None | ||
| 176 | q = h16_to_fraction(h) | ||
| 177 | return q - math.floor(q) | ||
| 178 | |||
| 179 | |||
| 180 | def oracle_fract_f16( | ||
| 181 | h: int, | ||
| 182 | *, | ||
| 183 | abs_: bool = False, | ||
| 184 | neg: bool = False, | ||
| 185 | mul: int = 1, | ||
| 186 | div: int = 1, | ||
| 187 | clamp: bool = False, | ||
| 188 | ) -> int | None: | ||
| 189 | """Independent binary16 reference for v_fract_f16, returning 16-bit int or None for NaN. | ||
| 190 | |||
| 191 | Models RDNA2 source modifiers (abs before neg), exact ``x - floor(x)``, | ||
| 192 | the hardware/translator 0x3c00 -> 0x3bff clamp when no output multiplier is | ||
| 193 | present, and VOP3 output scaling (mul/div) + [0, 1] clamp before narrowing. | ||
| 194 | """ | ||
| 195 | h &= 0xFFFF | ||
| 196 | if abs_: | ||
| 197 | h &= 0x7FFF | ||
| 198 | if neg: | ||
| 199 | h ^= 0x8000 | ||
| 200 | r = exact_fract_fraction(h) | ||
| 201 | if r is None: | ||
| 202 | return None | ||
| 203 | if mul == 1 and div == 1: | ||
| 204 | res = fraction_to_h16(r) | ||
| 205 | return H_NEAR_ONE if res == H_1P0 else res | ||
| 206 | scaled = r * Fraction(mul, div) | ||
| 207 | if clamp: | ||
| 208 | scaled = min(max(scaled, Fraction(0)), Fraction(1)) | ||
| 209 | return fraction_to_h16(scaled) | ||
| 210 | |||
| 211 | |||
| 212 | def merge_half(old: int, half: int, dst_hi: int) -> int: | ||
| 213 | h = half & 0xFFFF | ||
| 214 | return ((h << 16) | (old & 0xFFFF)) if dst_hi else ((old & 0xFFFF0000) | h) | ||
| 215 | |||
| 216 | |||
| 217 | # ----------------------------------------------------------------------------- | ||
| 218 | # Translation & Execution Helpers | ||
| 219 | # ----------------------------------------------------------------------------- | ||
| 220 | |||
| 221 | _TMP_DIR = None | ||
| 222 | _PS_PATH = None | ||
| 223 | _CS_PATH = None | ||
| 224 | _CS_FSSM = None | ||
| 225 | |||
| 226 | |||
| 227 | def _make_fssm(rsrc2: int, group: tuple[int, int, int]) -> bytes: | ||
| 228 | header = bytearray(0x148) | ||
| 229 | struct.pack_into("<4I", header, 0x138, rsrc2, *group) | ||
| 230 | return bytes(header) | ||
| 231 | |||
| 232 | |||
| 233 | def setUpModule(): | ||
| 234 | global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM | ||
| 235 | _TMP_DIR = tempfile.TemporaryDirectory() | ||
| 236 | disasm_dir = os.path.join(_TMP_DIR.name, "disasm") | ||
| 237 | fssm_dir = os.path.join(_TMP_DIR.name, "fssm") | ||
| 238 | os.mkdir(disasm_dir) | ||
| 239 | os.mkdir(fssm_dir) | ||
| 240 | _PS_PATH = os.path.join(disasm_dir, "ps_fract_f16.s") | ||
| 241 | _CS_PATH = os.path.join(disasm_dir, "cs_fract_f16.s") | ||
| 242 | _CS_FSSM = os.path.join(fssm_dir, "cs_fract_f16.fssm") | ||
| 243 | with open(os.path.join(_TMP_DIR.name, "ps_fract_f16.dxbc"), "wb") as f: | ||
| 244 | f.write(STUB_DXBC) | ||
| 245 | |||
| 246 | |||
| 247 | def tearDownModule(): | ||
| 248 | global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM | ||
| 249 | if _TMP_DIR is not None: | ||
| 250 | gc.collect() | ||
| 251 | _TMP_DIR.cleanup() | ||
| 252 | _TMP_DIR = None | ||
| 253 | _PS_PATH = None | ||
| 254 | _CS_PATH = None | ||
| 255 | _CS_FSSM = None | ||
| 256 | |||
| 257 | |||
| 258 | def translate_ps(lines: list[str]) -> str: | ||
| 259 | if _TMP_DIR is None: | ||
| 260 | setUpModule() | ||
| 261 | asm = ( | ||
| 262 | "; test_valu_fract_f16\n" | ||
| 263 | + "".join(f"\t{ln}\n" for ln in lines) | ||
| 264 | + "\texp mrt0 v0, v0, v0, v0 done vm\n\ts_endpgm\n" | ||
| 265 | ) | ||
| 266 | with open(_PS_PATH, "w", encoding="utf-8", newline="\n") as f: | ||
| 267 | f.write(asm) | ||
| 268 | with warnings.catch_warnings(): | ||
| 269 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 270 | spv = rdna2spirv.translate(_PS_PATH) | ||
| 271 | gc.collect() | ||
| 272 | return spv | ||
| 273 | |||
| 274 | |||
| 275 | def run_ps(lines: list[str], *, push_constants=None, memory=None) -> int: | ||
| 276 | out = si.run_fragment(translate_ps(lines), push_constants=push_constants, memory=memory) | ||
| 277 | return out["%out_mrt0"][0] | ||
| 278 | |||
| 279 | |||
| 280 | def run_op(line: str, v1: int = 0, *, old: int = OLD, s4: int = 0) -> int: | ||
| 281 | return run_ps([ | ||
| 282 | f"s_mov_b32 s4, {s4:#x}", | ||
| 283 | f"v_mov_b32 v1, {v1:#x}", | ||
| 284 | f"v_mov_b32 v0, {old:#x}", | ||
| 285 | line, | ||
| 286 | ]) | ||
| 287 | |||
| 288 | |||
| 289 | def run_cs(lines: list[str], group_size: int, memory: dict[int, int]) -> None: | ||
| 290 | if _TMP_DIR is None: | ||
| 291 | setUpModule() | ||
| 292 | # rsrc2 = 0x0088: USER_SGPR = 4 (s[0:3] V#), TGID_X_EN = 1 (s4), TIDIG_COMP_CNT = 0 (v0 = local_id.x). | ||
| 293 | with open(_CS_FSSM, "wb") as f: | ||
| 294 | f.write(_make_fssm(0x0088, (group_size, 1, 1))) | ||
| 295 | asm = "; test_cs_valu_fract_f16\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" | ||
| 296 | with open(_CS_PATH, "w", encoding="utf-8", newline="\n") as f: | ||
| 297 | f.write(asm) | ||
| 298 | with warnings.catch_warnings(): | ||
| 299 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 300 | spv = rdna2spirv.translate(_CS_PATH) | ||
| 301 | gc.collect() | ||
| 302 | si.run_workgroup( | ||
| 303 | spv, | ||
| 304 | group_size, | ||
| 305 | 32, | ||
| 306 | inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0)}, | ||
| 307 | push_constants=VSHARP_CS + [0] * 28, | ||
| 308 | memory=memory, | ||
| 309 | ) | ||
| 310 | |||
| 311 | |||
| 312 | class _Heap(dict): | ||
| 313 | def get(self, key, default=None): | ||
| 314 | return super().get(key, HEAP_FILL) | ||
| 315 | |||
| 316 | |||
| 317 | # ----------------------------------------------------------------------------- | ||
| 318 | # Oracle Self-Tests | ||
| 319 | # ----------------------------------------------------------------------------- | ||
| 320 | |||
| 321 | class OracleTests(unittest.TestCase): | ||
| 322 | """Cross-checks the independent Fraction binary16 oracle against IEEE-754 encodings.""" | ||
| 323 | |||
| 324 | def test_exhaustive_binary16_decode_and_roundtrip(self): | ||
| 325 | for h in range(0x10000): | ||
| 326 | if not h16_is_finite(h): | ||
| 327 | self.assertIsNone(exact_fract_fraction(h)) | ||
| 328 | self.assertIsNone(oracle_fract_f16(h)) | ||
| 329 | continue | ||
| 330 | q = h16_to_fraction(h) | ||
| 331 | expected_float = struct.unpack("<e", struct.pack("<H", h))[0] | ||
| 332 | self.assertEqual(q, Fraction(expected_float)) | ||
| 333 | want = H_POS_ZERO if h == H_NEG_ZERO else h | ||
| 334 | self.assertEqual(fraction_to_h16(q), want) | ||
| 335 | |||
| 336 | def test_hand_worked_fract_f16_rows(self): | ||
| 337 | rows = [ | ||
| 338 | (H_POS_ZERO, H_POS_ZERO), | ||
| 339 | (H_NEG_ZERO, H_POS_ZERO), | ||
| 340 | (H_0P25, H_0P25), | ||
| 341 | (H_1P25, H_0P25), | ||
| 342 | (H_3P75, H_0P75), | ||
| 343 | (H_NEG_0P25, H_0P75), | ||
| 344 | (H_NEG_1P25, H_0P75), | ||
| 345 | (H_NEG_0P5, H_0P5), | ||
| 346 | (H_NEG_0P75, H_0P25), | ||
| 347 | (H_1P0, H_POS_ZERO), | ||
| 348 | (H_NEG_1P0, H_POS_ZERO), | ||
| 349 | (H_MAX, H_POS_ZERO), | ||
| 350 | (H_NEG_MAX, H_POS_ZERO), | ||
| 351 | (H_NEG_2PM10, 0x3BFE), | ||
| 352 | (H_NEG_3P2M12, 0x3BFE), | ||
| 353 | (H_NEG_2PM11, H_NEAR_ONE), | ||
| 354 | (H_NEG_3P2M13, H_NEAR_ONE), | ||
| 355 | (H_NEG_2PM12_P, H_NEAR_ONE), | ||
| 356 | (H_NEG_2PM12, H_NEAR_ONE), | ||
| 357 | (H_NEG_2PM12_M, H_NEAR_ONE), | ||
| 358 | (H_NEG_2PM13, H_NEAR_ONE), | ||
| 359 | (H_NEG_1E4, H_NEAR_ONE), | ||
| 360 | (H_NEG_SUB_1E5, H_NEAR_ONE), | ||
| 361 | (H_NEG_SUB_MAX, H_NEAR_ONE), | ||
| 362 | (H_NEG_SUB_MIN, H_NEAR_ONE), | ||
| 363 | (H_SUB_MIN, H_SUB_MIN), | ||
| 364 | (H_SUB_1E5, H_SUB_1E5), | ||
| 365 | (H_1E4, H_1E4), | ||
| 366 | ] | ||
| 367 | for h, want in rows: | ||
| 368 | with self.subTest(h=hex(h)): | ||
| 369 | self.assertEqual(oracle_fract_f16(h), want) | ||
| 370 | # Verify decimal conversions match our binary16 constants. | ||
| 371 | self.assertEqual(struct.unpack("<H", struct.pack("<e", -0.0001))[0], H_NEG_1E4) | ||
| 372 | self.assertEqual(struct.unpack("<H", struct.pack("<e", -1e-5))[0], H_NEG_SUB_1E5) | ||
| 373 | self.assertEqual(struct.unpack("<H", struct.pack("<e", 3.75))[0], H_3P75) | ||
| 374 | |||
| 375 | |||
| 376 | # ----------------------------------------------------------------------------- | ||
| 377 | # End-to-End Execution Tests | ||
| 378 | # ----------------------------------------------------------------------------- | ||
| 379 | |||
| 380 | class FractF16ExecutionTests(unittest.TestCase): | ||
| 381 | def test_finite_values_across_e32_e64_and_bare(self): | ||
| 382 | samples = [ | ||
| 383 | H_POS_ZERO, H_NEG_ZERO, | ||
| 384 | H_SUB_MIN, H_NEG_SUB_MIN, H_SUB_1E5, H_NEG_SUB_1E5, | ||
| 385 | H_SUB_MAX, H_NEG_SUB_MAX, H_NORM_MIN, H_NEG_NORM_MIN, | ||
| 386 | H_1E4, H_NEG_1E4, H_2PM13, H_NEG_2PM13, | ||
| 387 | H_NEG_2PM12_M, H_NEG_2PM12, H_NEG_2PM12_P, H_NEG_3P2M13, | ||
| 388 | H_NEG_2PM11, H_NEG_3P2M12, H_NEG_2PM10, | ||
| 389 | H_0P125, H_0P25, H_NEG_0P25, H_0P5, H_NEG_0P5, H_0P75, H_NEG_0P75, | ||
| 390 | H_NEAR_ONE, | ||
| 391 | H_1P0, H_NEG_1P0, H_1P25, H_NEG_1P25, H_1P5, H_NEG_1P5, H_1P75, H_NEG_1P75, | ||
| 392 | H_2P0, H_NEG_2P0, H_2P5, H_NEG_2P5, H_3P0, H_NEG_3P0, H_3P75, H_NEG_3P75, | ||
| 393 | H_1023P5, H_NEG_1023P5, H_1024, H_NEG_1024, H_MAX, H_NEG_MAX, | ||
| 394 | ] | ||
| 395 | for suffix in ("_e32", "_e64", ""): | ||
| 396 | for h in samples: | ||
| 397 | v1 = 0x55550000 | h | ||
| 398 | want = merge_half(OLD, oracle_fract_f16(h), 0) | ||
| 399 | with self.subTest(form="v_fract_f16" + suffix, h=hex(h)): | ||
| 400 | self.assertEqual(run_op(f"v_fract_f16{suffix} v0, v1", v1), want) | ||
| 401 | |||
| 402 | def test_tiny_negatives_and_subnormals_near_one_boundary(self): | ||
| 403 | # Crosses the exact binary16 rounding transition: -2^-10 and -3*2^-12 give 0x3bfe; | ||
| 404 | # -2^-11 .. -2^-24 (including -0.0001 and -1e-5) give 0x3bff (never 0x3c00 = 1.0). | ||
| 405 | cases = [ | ||
| 406 | (H_NEG_2PM10, 0x3BFE), | ||
| 407 | (H_NEG_3P2M12, 0x3BFE), | ||
| 408 | (H_NEG_2PM11, H_NEAR_ONE), | ||
| 409 | (H_NEG_3P2M13, H_NEAR_ONE), | ||
| 410 | (H_NEG_2PM12_P, H_NEAR_ONE), | ||
| 411 | (H_NEG_2PM12, H_NEAR_ONE), | ||
| 412 | (H_NEG_2PM12_M, H_NEAR_ONE), | ||
| 413 | (H_NEG_2PM13, H_NEAR_ONE), | ||
| 414 | (H_NEG_1E4, H_NEAR_ONE), | ||
| 415 | (H_NEG_SUB_1E5, H_NEAR_ONE), | ||
| 416 | (H_NEG_SUB_MAX, H_NEAR_ONE), | ||
| 417 | (H_NEG_SUB_MIN, H_NEAR_ONE), | ||
| 418 | ] | ||
| 419 | for h, want in cases: | ||
| 420 | with self.subTest(h=hex(h)): | ||
| 421 | self.assertEqual(oracle_fract_f16(h), want) | ||
| 422 | self.assertEqual(run_op("v_fract_f16_e32 v0, v1", 0xCAFE0000 | h), merge_half(OLD, want, 0)) | ||
| 423 | self.assertEqual(run_op("v_fract_f16_e64 v0, v1 op_sel:[0,1]", 0xCAFE0000 | h), | ||
| 424 | merge_half(OLD, want, 1)) | ||
| 425 | |||
| 426 | def test_exact_integers_and_signed_zero_give_positive_zero(self): | ||
| 427 | # GLSL.std.450 Fract(-0.0) in spirv_mini_interp returns +0.0 (copysign == +1), matching hardware. | ||
| 428 | self.assertEqual(si._fract(-0.0), 0.0) | ||
| 429 | self.assertEqual(math.copysign(1.0, si._fract(-0.0)), 1.0) | ||
| 430 | for h in (H_POS_ZERO, H_NEG_ZERO, H_1P0, H_NEG_1P0, H_2P0, H_NEG_2P0, | ||
| 431 | H_3P0, H_NEG_3P0, H_1024, H_NEG_1024, H_MAX, H_NEG_MAX): | ||
| 432 | with self.subTest(h=hex(h)): | ||
| 433 | got = run_op("v_fract_f16_e32 v0, v1", 0xABCD0000 | h) | ||
| 434 | self.assertEqual(got, merge_half(OLD, H_POS_ZERO, 0)) | ||
| 435 | self.assertNotEqual(got & 0xFFFF, H_NEG_ZERO) | ||
| 436 | got_hi = run_op("v_fract_f16_e64 v0, v1 op_sel:[1,1]", (h << 16) | 0x1111) | ||
| 437 | self.assertEqual(got_hi, merge_half(OLD, H_POS_ZERO, 1)) | ||
| 438 | |||
| 439 | def test_runtime_memory_inputs_via_s_buffer_load(self): | ||
| 440 | # Loaded at runtime through s_buffer_load_dwordx4 so constant folding cannot bypass Fract. | ||
| 441 | lanes_lo = [H_NEG_1E4, H_NEG_SUB_1E5, H_NEG_ZERO, H_3P75] | ||
| 442 | lanes_hi = [H_NEG_MAX, H_NEG_0P25, H_1P25, H_POS_INF] | ||
| 443 | packed = [(hi << 16) | lo for lo, hi in zip(lanes_lo, lanes_hi)] | ||
| 444 | mem = {0x1000 + 4 * i: w for i, w in enumerate(packed)} | ||
| 445 | for idx, (lo, hi) in enumerate(zip(lanes_lo, lanes_hi)): | ||
| 446 | reg = f"v{idx + 1}" | ||
| 447 | lines_head = [ | ||
| 448 | "s_buffer_load_dwordx4 s[4:7], s[0:3], 0", | ||
| 449 | "s_waitcnt lgkmcnt(0)", | ||
| 450 | "v_mov_b32_e32 v1, s4", | ||
| 451 | "v_mov_b32_e32 v2, s5", | ||
| 452 | "v_mov_b32_e32 v3, s6", | ||
| 453 | "v_mov_b32_e32 v4, s7", | ||
| 454 | f"v_mov_b32_e32 v0, {OLD:#x}", | ||
| 455 | ] | ||
| 456 | got_lo = run_ps(lines_head + [f"v_fract_f16_e32 v0, {reg}"], push_constants=PUSH_ADDR, memory=mem) | ||
| 457 | self.assertEqual(got_lo, merge_half(OLD, oracle_fract_f16(lo), 0)) | ||
| 458 | got_hi = run_ps(lines_head + [f"v_fract_f16_e64 v0, {reg} op_sel:[1,1]"], | ||
| 459 | push_constants=PUSH_ADDR, memory=mem) | ||
| 460 | want_hi = oracle_fract_f16(hi) | ||
| 461 | if want_hi is None: | ||
| 462 | self.assertEqual(got_hi & 0xFFFF, OLD & 0xFFFF) | ||
| 463 | self.assertTrue(h16_is_nan(got_hi >> 16), hex(got_hi)) | ||
| 464 | else: | ||
| 465 | self.assertEqual(got_hi, merge_half(OLD, want_hi, 1)) | ||
| 466 | |||
| 467 | def test_inf_and_nan_produce_nan_and_preserve_untouched_half(self): | ||
| 468 | # Verify spirv_mini_interp Fract on +-inf/NaN and translator's OpFOrdEqual guard. | ||
| 469 | self.assertTrue(math.isnan(si._fract(float("inf")))) | ||
| 470 | self.assertTrue(math.isnan(si._fract(float("-inf")))) | ||
| 471 | self.assertTrue(math.isnan(si._fract(float("nan")))) | ||
| 472 | |||
| 473 | for h in (H_POS_INF, H_NEG_INF, H_QNAN, H_NEG_QNAN, H_SNAN, H_NEG_SNAN): | ||
| 474 | for suffix in ("_e32", "_e64", ""): | ||
| 475 | with self.subTest(h=hex(h), form=suffix or "bare"): | ||
| 476 | got = run_op(f"v_fract_f16{suffix} v0, v1", 0xCAFE0000 | h) | ||
| 477 | self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000) | ||
| 478 | self.assertTrue(h16_is_nan(got & 0xFFFF), f"expected NaN in low half, got {got:#010x}") | ||
| 479 | for src_hi, dst_hi in itertools.product((0, 1), repeat=2): | ||
| 480 | v1 = ((h << 16) | H_0P25) if src_hi else ((H_0P25 << 16) | h) | ||
| 481 | with self.subTest(h=hex(h), src_hi=src_hi, dst_hi=dst_hi): | ||
| 482 | got = run_op(f"v_fract_f16_e64 v0, v1 op_sel:[{src_hi},{dst_hi}]", v1) | ||
| 483 | if dst_hi: | ||
| 484 | self.assertEqual(got & 0xFFFF, OLD & 0xFFFF) | ||
| 485 | self.assertTrue(h16_is_nan(got >> 16), hex(got)) | ||
| 486 | else: | ||
| 487 | self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000) | ||
| 488 | self.assertTrue(h16_is_nan(got & 0xFFFF), hex(got)) | ||
| 489 | |||
| 490 | def test_op_sel_all_four_combinations(self): | ||
| 491 | pairs = [ | ||
| 492 | (H_NEG_1P25, H_0P25), # hi: 0.75, lo: 0.25 | ||
| 493 | (H_NEG_SUB_1E5, H_3P75), # hi: 0x3bff, lo: 0.75 | ||
| 494 | ] | ||
| 495 | for hi, lo in pairs: | ||
| 496 | v1 = (hi << 16) | lo | ||
| 497 | for src_hi, dst_hi in itertools.product((0, 1), repeat=2): | ||
| 498 | h_in = hi if src_hi else lo | ||
| 499 | line = f"v_fract_f16_e64 v0, v1 op_sel:[{src_hi},{dst_hi}]" | ||
| 500 | with self.subTest(line=line, v1=hex(v1)): | ||
| 501 | self.assertEqual(run_op(line, v1), merge_half(OLD, oracle_fract_f16(h_in), dst_hi)) | ||
| 502 | |||
| 503 | def test_vop3_source_modifiers(self): | ||
| 504 | cases = [ | ||
| 505 | ("v_fract_f16_e64 v0, -v1 op_sel:[0,0]", (H_NEG_1P25 << 16) | H_0P25, H_0P25, False, True, 0), | ||
| 506 | ("v_fract_f16_e64 v0, -v1 op_sel:[1,1]", (H_NEG_0P25 << 16) | H_1P25, H_NEG_0P25, False, True, 1), | ||
| 507 | ("v_fract_f16_e64 v0, -v1 op_sel:[0,0]", (H_0P25 << 16) | H_2PM13, H_2PM13, False, True, 0), | ||
| 508 | ("v_fract_f16_e64 v0, -v1 op_sel:[0,0]", H_POS_ZERO, H_POS_ZERO, False, True, 0), | ||
| 509 | ("v_fract_f16_e64 v0, -v1 op_sel:[0,0]", H_1P0, H_1P0, False, True, 0), | ||
| 510 | ("v_fract_f16_e64 v0, |v1| op_sel:[1,1]", (H_NEG_1P25 << 16) | H_0P25, H_NEG_1P25, True, False, 1), | ||
| 511 | ("v_fract_f16_e64 v0, |v1| op_sel:[1,0]", (H_NEG_2PM13 << 16) | H_0P5, H_NEG_2PM13, True, False, 0), | ||
| 512 | ("v_fract_f16_e64 v0, -|v1| op_sel:[1,0]", (H_NEG_1P25 << 16) | H_0P25, H_NEG_1P25, True, True, 0), | ||
| 513 | ("v_fract_f16_e64 v0, -|v1| op_sel:[0,1]", (H_0P5 << 16) | H_3P75, H_3P75, True, True, 1), | ||
| 514 | ("v_fract_f16_e64 v0, -|v1| op_sel:[0,0]", H_2PM13, H_2PM13, True, True, 0), | ||
| 515 | ] | ||
| 516 | for line, v1, h_in, abs_, neg, dst_hi in cases: | ||
| 517 | with self.subTest(line=line, v1=hex(v1)): | ||
| 518 | want = oracle_fract_f16(h_in, abs_=abs_, neg=neg) | ||
| 519 | self.assertEqual(run_op(line, v1), merge_half(OLD, want, dst_hi)) | ||
| 520 | |||
| 521 | # Source modifiers on inf/NaN preserve NaN output and keep untouched half. | ||
| 522 | for mod in ("-v1", "|v1|", "-|v1|"): | ||
| 523 | for h in (H_POS_INF, H_NEG_INF, H_QNAN): | ||
| 524 | with self.subTest(mod=mod, h=hex(h)): | ||
| 525 | got = run_op(f"v_fract_f16_e64 v0, {mod}", (H_0P25 << 16) | h) | ||
| 526 | self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000) | ||
| 527 | self.assertTrue(h16_is_nan(got & 0xFFFF), hex(got)) | ||
| 528 | |||
| 529 | def test_vop3_output_modifiers(self): | ||
| 530 | # (asm_suffix, input_h, dst_hi, kwargs_for_oracle) | ||
| 531 | cases = [ | ||
| 532 | # clamp without omod keeps [0, 1) and preserves 0x3c00 -> 0x3bff | ||
| 533 | ("clamp", H_0P75, 0, dict(clamp=True)), | ||
| 534 | ("clamp", H_NEG_0P25, 0, dict(clamp=True)), | ||
| 535 | ("clamp", H_NEG_2PM13, 0, dict(clamp=True)), | ||
| 536 | ("clamp", H_NEG_ZERO, 0, dict(clamp=True)), | ||
| 537 | # mul:2 / mul:4 / div:2 (true 1.0 stays 0x3c00 when omod is active) | ||
| 538 | ("mul:2", H_0P5, 0, dict(mul=2)), | ||
| 539 | ("mul:2", H_0P75, 0, dict(mul=2)), | ||
| 540 | ("mul:2", H_NEG_0P25, 0, dict(mul=2)), | ||
| 541 | ("mul:2", H_NEG_2PM13, 0, dict(mul=2)), | ||
| 542 | ("mul:4", H_0P25, 0, dict(mul=4)), | ||
| 543 | ("mul:4", H_0P5, 0, dict(mul=4)), | ||
| 544 | ("mul:4", H_NEG_1P25, 0, dict(mul=4)), | ||
| 545 | ("div:2", H_0P5, 0, dict(div=2)), | ||
| 546 | ("div:2", H_NEG_1P25, 0, dict(div=2)), | ||
| 547 | ("div:2", H_0P25, 0, dict(div=2)), | ||
| 548 | ("div:2", H_NEG_2PM13, 0, dict(div=2)), | ||
| 549 | # combined omod + clamp | ||
| 550 | ("mul:2 clamp", H_0P25, 0, dict(mul=2, clamp=True)), | ||
| 551 | ("mul:2 clamp", H_0P5, 0, dict(mul=2, clamp=True)), | ||
| 552 | ("mul:2 clamp", H_0P75, 0, dict(mul=2, clamp=True)), | ||
| 553 | ("mul:2 clamp", H_NEG_0P25, 0, dict(mul=2, clamp=True)), | ||
| 554 | ("mul:4 clamp", H_0P5, 0, dict(mul=4, clamp=True)), | ||
| 555 | ("op_sel:[1,1] mul:2 clamp", H_NEG_1P25, 1, dict(mul=2, clamp=True)), | ||
| 556 | ("op_sel:[1,1] mul:4 clamp", H_0P125, 1, dict(mul=4, clamp=True)), | ||
| 557 | ] | ||
| 558 | for suffix, h_in, dst_hi, kw in cases: | ||
| 559 | v1 = ((h_in << 16) | H_0P25) if "op_sel:[1,1]" in suffix else ((H_3P75 << 16) | h_in) | ||
| 560 | line = f"v_fract_f16_e64 v0, v1 {suffix}" | ||
| 561 | want = oracle_fract_f16(h_in, **kw) | ||
| 562 | with self.subTest(line=line, h_in=hex(h_in)): | ||
| 563 | self.assertEqual(run_op(line, v1), merge_half(OLD, want, dst_hi)) | ||
| 564 | |||
| 565 | # Verify explicit exact values for the critical omod transitions. | ||
| 566 | self.assertEqual(run_op("v_fract_f16_e64 v0, v1 mul:2", H_0P5), merge_half(OLD, H_1P0, 0)) | ||
| 567 | self.assertEqual(run_op("v_fract_f16_e64 v0, v1 mul:2 clamp", H_0P75), merge_half(OLD, H_1P0, 0)) | ||
| 568 | self.assertEqual(run_op("v_fract_f16_e64 v0, v1 mul:4", H_0P5), merge_half(OLD, H_2P0, 0)) | ||
| 569 | self.assertEqual(run_op("v_fract_f16_e64 v0, v1 div:2", H_0P5), merge_half(OLD, H_0P25, 0)) | ||
| 570 | |||
| 571 | def test_inline_f16_constants(self): | ||
| 572 | for lit, h in (("0.5", H_0P5), ("-0.5", H_NEG_0P5), ("1.0", H_1P0), ("-1.0", H_NEG_1P0)): | ||
| 573 | want = oracle_fract_f16(h) | ||
| 574 | for form in ("_e32", "_e64", ""): | ||
| 575 | with self.subTest(lit=lit, form=form or "bare"): | ||
| 576 | self.assertEqual(run_op(f"v_fract_f16{form} v0, {lit}"), merge_half(OLD, want, 0)) | ||
| 577 | # op_sel:[0,1] writes the inline constant's fract into high half; low half preserved. | ||
| 578 | self.assertEqual(run_op(f"v_fract_f16_e64 v0, {lit} op_sel:[0,1]"), merge_half(OLD, want, 1)) | ||
| 579 | # Inline float constants place +0.0 in the high half (docs/design.md / src_h). | ||
| 580 | self.assertEqual(run_op(f"v_fract_f16_e64 v0, {lit} op_sel:[1,0]"), merge_half(OLD, H_POS_ZERO, 0)) | ||
| 581 | |||
| 582 | self.assertEqual(run_op("v_fract_f16_e64 v0, -0.5 mul:2"), merge_half(OLD, H_1P0, 0)) | ||
| 583 | self.assertEqual(run_op("v_fract_f16_e64 v0, -0.5 div:2"), merge_half(OLD, H_0P25, 0)) | ||
| 584 | |||
| 585 | def test_sgpr_sources_and_destination_aliasing(self): | ||
| 586 | s4 = (H_NEG_1P25 << 16) | H_0P25 | ||
| 587 | self.assertEqual(run_op("v_fract_f16_e32 v0, s4", s4=s4), merge_half(OLD, H_0P25, 0)) | ||
| 588 | self.assertEqual(run_op("v_fract_f16_e64 v0, s4 op_sel:[0,0]", s4=s4), merge_half(OLD, H_0P25, 0)) | ||
| 589 | self.assertEqual(run_op("v_fract_f16_e64 v0, s4 op_sel:[1,0]", s4=s4), merge_half(OLD, H_0P75, 0)) | ||
| 590 | self.assertEqual(run_op("v_fract_f16_e64 v0, s4 op_sel:[0,1]", s4=s4), merge_half(OLD, H_0P25, 1)) | ||
| 591 | self.assertEqual(run_op("v_fract_f16_e64 v0, s4 op_sel:[1,1]", s4=s4), merge_half(OLD, H_0P75, 1)) | ||
| 592 | self.assertEqual(run_op("v_fract_f16_e64 v0, -s4 op_sel:[1,0]", s4=s4), merge_half(OLD, H_0P25, 0)) | ||
| 593 | self.assertEqual(run_op("v_fract_f16_e64 v0, |s4| op_sel:[1,1]", s4=s4), merge_half(OLD, H_0P25, 1)) | ||
| 594 | |||
| 595 | # Destination aliasing: dst == src (v0, v0) keeps the untouched half of v0. | ||
| 596 | v0_init = (H_3P75 << 16) | H_NEG_0P25 | ||
| 597 | self.assertEqual( | ||
| 598 | run_ps([f"v_mov_b32 v0, {v0_init:#x}", "v_fract_f16_e32 v0, v0"]), | ||
| 599 | (H_3P75 << 16) | H_0P75, | ||
| 600 | ) | ||
| 601 | self.assertEqual( | ||
| 602 | run_ps([f"v_mov_b32 v0, {v0_init:#x}", "v_fract_f16 v0, v0"]), | ||
| 603 | (H_3P75 << 16) | H_0P75, | ||
| 604 | ) | ||
| 605 | for src_hi, dst_hi in itertools.product((0, 1), repeat=2): | ||
| 606 | h_in = H_3P75 if src_hi else H_NEG_0P25 | ||
| 607 | want_h = oracle_fract_f16(h_in) | ||
| 608 | with self.subTest(alias_op_sel=(src_hi, dst_hi)): | ||
| 609 | self.assertEqual( | ||
| 610 | run_ps([ | ||
| 611 | f"v_mov_b32 v0, {v0_init:#x}", | ||
| 612 | f"v_fract_f16_e64 v0, v0 op_sel:[{src_hi},{dst_hi}]", | ||
| 613 | ]), | ||
| 614 | merge_half(v0_init, want_h, dst_hi), | ||
| 615 | ) | ||
| 616 | |||
| 617 | def test_exec_masking_single_lane_and_workgroup(self): | ||
| 618 | # Single-lane pixel shader: inactive lane preserves pre-existing v0; re-enabling executes. | ||
| 619 | self.assertEqual(run_ps([ | ||
| 620 | f"v_mov_b32 v1, {H_1P5:#x}", | ||
| 621 | f"v_mov_b32 v0, {OLD:#x}", | ||
| 622 | "s_mov_b32 exec_lo, 0", | ||
| 623 | "v_fract_f16_e32 v0, v1", | ||
| 624 | "v_fract_f16_e64 v0, v1 op_sel:[0,1]", | ||
| 625 | "s_mov_b32 exec_lo, 1", | ||
| 626 | ]), OLD) | ||
| 627 | |||
| 628 | self.assertEqual(run_ps([ | ||
| 629 | f"v_mov_b32 v1, {(H_NEG_1P25 << 16) | H_2P5:#x}", | ||
| 630 | f"v_mov_b32 v0, {OLD:#x}", | ||
| 631 | "s_mov_b32 exec_lo, 0", | ||
| 632 | "v_fract_f16_e64 v0, v1 op_sel:[0,0]", | ||
| 633 | "v_fract_f16_e64 v0, v1 op_sel:[1,1]", | ||
| 634 | "s_mov_b32 exec_lo, 1", | ||
| 635 | "v_fract_f16_e64 v0, v1 op_sel:[1,0]", | ||
| 636 | ]), merge_half(OLD, H_0P75, 0)) | ||
| 637 | |||
| 638 | # Multi-lane 8-thread compute shader: even lanes active, odd lanes masked off keep OLD. | ||
| 639 | lane_inputs = [ | ||
| 640 | (H_NEG_1P25 << 16) | H_0P25, | ||
| 641 | (H_3P75 << 16) | H_NEG_0P25, | ||
| 642 | (H_NEG_SUB_1E5 << 16) | H_1P25, | ||
| 643 | (H_2P5 << 16) | H_NEG_1E4, | ||
| 644 | (H_NEG_ZERO << 16) | H_NEG_0P5, | ||
| 645 | (H_1P5 << 16) | H_NEG_MAX, | ||
| 646 | (H_NEG_MAX << 16) | H_NEG_2PM12, | ||
| 647 | (H_0P75 << 16) | H_3P75, | ||
| 648 | ] | ||
| 649 | lane_olds = [0xAA00BB00 + 0x00110001 * i for i in range(8)] | ||
| 650 | for dst_hi, op_line in ( | ||
| 651 | (0, "v_fract_f16_e32 v2, v1"), | ||
| 652 | (1, "v_fract_f16_e64 v2, v1 op_sel:[1,1]"), | ||
| 653 | ): | ||
| 654 | mem = _Heap( | ||
| 655 | {0x100 + 4 * i: w for i, w in enumerate(lane_inputs)} | ||
| 656 | | {0x200 + 4 * i: w for i, w in enumerate(lane_olds)} | ||
| 657 | ) | ||
| 658 | run_cs([ | ||
| 659 | "v_lshlrev_b32_e32 v5, 2, v0", | ||
| 660 | "v_add_nc_u32_e32 v6, 0x100, v5", | ||
| 661 | "v_add_nc_u32_e32 v7, 0x200, v5", | ||
| 662 | "buffer_load_dword v1, v6, s[0:3], 0 offen", | ||
| 663 | "buffer_load_dword v2, v7, s[0:3], 0 offen", | ||
| 664 | "v_and_b32_e32 v3, 1, v0", | ||
| 665 | "v_cmp_eq_u32_e32 vcc_lo, 0, v3", | ||
| 666 | "s_and_saveexec_b32 s6, vcc_lo", | ||
| 667 | op_line, | ||
| 668 | "s_mov_b32 exec_lo, s6", | ||
| 669 | "buffer_store_dword v2, v5, s[0:3], 0 offen", | ||
| 670 | ], group_size=8, memory=mem) | ||
| 671 | |||
| 672 | got = [mem.get(4 * i) for i in range(8)] | ||
| 673 | want = [] | ||
| 674 | for lane, (inp, old_w) in enumerate(zip(lane_inputs, lane_olds)): | ||
| 675 | if lane & 1: | ||
| 676 | want.append(old_w) | ||
| 677 | else: | ||
| 678 | h_in = (inp >> 16) if dst_hi else (inp & 0xFFFF) | ||
| 679 | want.append(merge_half(old_w, oracle_fract_f16(h_in), dst_hi)) | ||
| 680 | with self.subTest(op_line=op_line): | ||
| 681 | self.assertEqual(got, want) | ||
| 682 | |||
| 683 | def test_negative_control_sabotaged_spirv(self): | ||
| 684 | # Input -1.25: true fract = 0.75 (0x3a00); Trunc gives -1.0 (0xbc00); Floor gives -2.0 (0xc000). | ||
| 685 | spv = translate_ps([ | ||
| 686 | f"v_mov_b32 v1, {H_NEG_1P25:#x}", | ||
| 687 | f"v_mov_b32 v0, {OLD:#x}", | ||
| 688 | "v_fract_f16_e32 v0, v1", | ||
| 689 | ]) | ||
| 690 | expected = merge_half(OLD, H_0P75, 0) | ||
| 691 | self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], expected) | ||
| 692 | |||
| 693 | for replacement, sabotaged_half in (("Trunc", H_NEG_1P0), ("Floor", H_NEG_2P0)): | ||
| 694 | sabotaged, n = re.subn(r"\bFract\b", replacement, spv, count=1) | ||
| 695 | self.assertEqual(n, 1) | ||
| 696 | got = si.run_fragment(sabotaged)["%out_mrt0"][0] | ||
| 697 | with self.subTest(replacement=replacement): | ||
| 698 | self.assertNotEqual(got, expected) | ||
| 699 | self.assertEqual(got, merge_half(OLD, sabotaged_half, 0)) | ||
| 700 | |||
| 701 | |||
| 702 | if __name__ == "__main__": | ||
| 703 | unittest.main() | ||
diff --git a/tests/semantic/test_valu_permlane16.py b/tests/semantic/test_valu_permlane16.py new file mode 100644 index 000000000..3256b9d8d --- /dev/null +++ b/tests/semantic/test_valu_permlane16.py | |||
| @@ -0,0 +1,814 @@ | |||
| 1 | """Semantic value and translation tests for RDNA2 cross-lane permutes: | ||
| 2 | v_permlane16_b32 D = vS[(l & ~15) | sel[l & 15]] | ||
| 3 | v_permlanex16_b32 D = vS[((l & ~15) ^ 16) | sel[l & 15]] | ||
| 4 | |||
| 5 | where the 4-bit lane selector nibbles `sel[0..7]` come from `src1` (bits `[4*k+3 : 4*k]`) and | ||
| 6 | `sel[8..15]` come from `src2` (bits `[4*(k-8)+3 : 4*(k-8)]`), applied independently inside each | ||
| 7 | 32-lane row (`[0..15]` and `[16..31]`, and in wave64 `[32..47]` and `[48..63]`). Only lanes active | ||
| 8 | in `EXEC` write `vD`; inactive destination lanes preserve their prior `vD`. | ||
| 9 | |||
| 10 | Executed end-to-end through `tools/rdna2spirv.py` and `tests/semantic/spirv_mini_interp.py` | ||
| 11 | (`run_workgroup`) across 32 lanes (wave32) and 64 lanes (wave64 on both one 64-wide subgroup and | ||
| 12 | two 32-wide subgroups), as well as partial waves (20 and 40 lanes), and checked against | ||
| 13 | hand-computed constants and an independent plain-Python RDNA2 ISA reference model. Standard library | ||
| 14 | only; zero game data; hand-written RDNA2 disassembly listings only. | ||
| 15 | |||
| 16 | Documented findings (observed in `tools/rdna2spirv.py`; no shared files modified): | ||
| 17 | 1. `op_sel:[fi, bound_ctrl]` and inactive source lanes (`tools/rdna2spirv.py` lines 4608-4632): | ||
| 18 | In RDNA2 ISA (measured on RDNA2 gfx1036 and RDNA3.5 gfx1150; see `docs/shader_validation.md` | ||
| 19 | and `tools/crosslane_fuzz.py`), when a source lane is inactive in `EXEC` (`EXEC[src] == 0`): | ||
| 20 | - `fi=1` (`op_sel:[1,0]`, `op_sel:[1,1]`): reads the inactive source lane's pre-existing `vS`. | ||
| 21 | - `fi=0, bound_ctrl=0` (`op_sel:[0,0]` or omitted): keeps the destination lane's prior `vD`. | ||
| 22 | - `fi=0, bound_ctrl=1` (`op_sel:[0,1]`): writes `0` to the destination lane. | ||
| 23 | `tools/rdna2spirv.py` lines 4608-4632 do not inspect `mods` (`op_sel:[fi, bound_ctrl]`) and emit | ||
| 24 | `self.g_shuffle(r, v, src)` unconditionally without checking the source lane's `%active` bit. | ||
| 25 | Therefore: | ||
| 26 | - When all accessed source lanes are active in `EXEC`, all four `op_sel` modes (`[0,0]`, | ||
| 27 | `[1,0]`, `[0,1]`, `[1,1]`) and omitted `op_sel` match the RDNA2 ISA. | ||
| 28 | - When a source lane is inactive in `EXEC` and `fi=1` (`op_sel:[1,0]`, `op_sel:[1,1]`), the | ||
| 29 | translation matches the RDNA2 ISA (reading the inactive source lane's pre-existing `vS`). | ||
| 30 | - When a source lane is inactive in `EXEC` and `fi=0` (`op_sel:[0,0]`/omitted, | ||
| 31 | `op_sel:[0,1]`), the translator currently reads `vS[src]` instead of keeping `vD` or | ||
| 32 | writing `0`. Those inactive-source `fi=0` cases are tested in the plain-Python ISA | ||
| 33 | reference tests (`OracleTests`) and excluded from passing end-to-end assertions rather | ||
| 34 | than relaxing expected values; structural SPIR-V translation is verified in | ||
| 35 | `EmulationAndFindingTests`. | ||
| 36 | 2. `--wave64-emulate` (`tools/rdna2spirv.py` lines 2671-2810, 2890-2895, 4608-4632): | ||
| 37 | With `WAVE64_EMULATE = True`, wave64 compute/mesh shaders lower `g_shuffle` and `sub_lane` | ||
| 38 | through `%x_buf` Workgroup-memory exchanges, `OpControlBarrier`, and a round loop (`OpLoopMerge` | ||
| 39 | with a backward branch). `tests/semantic/spirv_mini_interp.py` rejects `Workgroup` barriers and | ||
| 40 | non-forward branches (`UnsupportedConstruct`), so `--wave64-emulate` is covered by translation | ||
| 41 | and structural SPIR-V invariants here (and rejected cleanly by `run_workgroup`). | ||
| 42 | 3. Wave64 native on two 32-wide subgroups (`subgroup_size = 32`): | ||
| 43 | Because `v_permlane16_b32` and `v_permlanex16_b32` never cross the 32-lane row boundary | ||
| 44 | (`0..31` vs `32..63`), both instructions stay exact across all 64 lanes even on two 32-wide | ||
| 45 | subgroups without `--wave64-emulate`. | ||
| 46 | """ | ||
| 47 | import gc | ||
| 48 | import os | ||
| 49 | import re | ||
| 50 | import struct | ||
| 51 | import sys | ||
| 52 | import tempfile | ||
| 53 | import unittest | ||
| 54 | import warnings | ||
| 55 | |||
| 56 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 57 | ROOT = os.path.dirname(os.path.dirname(HERE)) | ||
| 58 | TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") | ||
| 59 | |||
| 60 | sys.dont_write_bytecode = True | ||
| 61 | if TOOLS_DIR not in sys.path: | ||
| 62 | sys.path.insert(0, TOOLS_DIR) | ||
| 63 | if HERE not in sys.path: | ||
| 64 | sys.path.insert(0, HERE) | ||
| 65 | |||
| 66 | import rdna2spirv # noqa: E402 | ||
| 67 | import spirv_mini_interp as si # noqa: E402 | ||
| 68 | |||
| 69 | MASK32 = 0xFFFFFFFF | ||
| 70 | ALL32 = 0xFFFFFFFF | ||
| 71 | ALL64 = 0xFFFFFFFFFFFFFFFF | ||
| 72 | OLD_SENTINEL = 0xCAFE0000 | ||
| 73 | HEAP_FILL = 0xEEEEEEEE | ||
| 74 | # V# in s[0:3]: base 0, stride 0, num_records 0x10000 bytes (OOB_SELECT = 3). | ||
| 75 | VSHARP = [0, 0, 0x10000, 0x31016FAC] | ||
| 76 | INPUT_BASE = 0x8000 | ||
| 77 | |||
| 78 | ID_S1 = 0x76543210 | ||
| 79 | ID_S2 = 0xFEDCBA98 | ||
| 80 | REV8_S1 = 0x01234567 | ||
| 81 | REV8_S2 = 0x89ABCDEF | ||
| 82 | REV16_S1 = 0x89ABCDEF | ||
| 83 | REV16_S2 = 0x01234567 | ||
| 84 | PAIR_SWAP_S1 = 0x10325476 | ||
| 85 | PAIR_SWAP_S2 = 0x98BADCFE | ||
| 86 | ASYM_S1 = 0x3A0F5C91 | ||
| 87 | ASYM_S2 = 0xE27B48D6 | ||
| 88 | |||
| 89 | |||
| 90 | def ref_permlane(x16: bool, src_vals: list[int], dst_old: list[int], s1: int, s2: int, | ||
| 91 | exec_mask: int, fi: int = 0, bound_ctrl: int = 0) -> list[int]: | ||
| 92 | """Independent RDNA2 ISA reference model for v_permlane16_b32 / v_permlanex16_b32.""" | ||
| 93 | lanes = len(src_vals) | ||
| 94 | assert len(dst_old) == lanes and lanes in (32, 64) | ||
| 95 | out = [] | ||
| 96 | for lane in range(lanes): | ||
| 97 | if not ((exec_mask >> lane) & 1): | ||
| 98 | out.append(dst_old[lane] & MASK32) | ||
| 99 | continue | ||
| 100 | within = lane & 15 | ||
| 101 | sel_word = s2 if within >= 8 else s1 | ||
| 102 | nib = (sel_word >> (4 * (lane & 7))) & 0xF | ||
| 103 | half = lane & ~15 | ||
| 104 | row = (half ^ 16) if x16 else half | ||
| 105 | src_lane = row | nib | ||
| 106 | if ((exec_mask >> src_lane) & 1) or fi: | ||
| 107 | out.append(src_vals[src_lane] & MASK32) | ||
| 108 | elif bound_ctrl: | ||
| 109 | out.append(0) | ||
| 110 | else: | ||
| 111 | out.append(dst_old[lane] & MASK32) | ||
| 112 | return out | ||
| 113 | |||
| 114 | |||
| 115 | class _Heap(dict): | ||
| 116 | def get(self, key, default=None): | ||
| 117 | return super().get(key, HEAP_FILL) | ||
| 118 | |||
| 119 | |||
| 120 | _TMP_DIR = None | ||
| 121 | _DISASM_DIR = None | ||
| 122 | _FSSM_DIR = None | ||
| 123 | |||
| 124 | |||
| 125 | def _make_fssm(threads: int, rsrc2: int = 0x8088) -> bytes: | ||
| 126 | header = bytearray(0x148) | ||
| 127 | struct.pack_into("<4I", header, 0x138, rsrc2, threads, 1, 1) | ||
| 128 | return bytes(header) | ||
| 129 | |||
| 130 | |||
| 131 | def setUpModule(): | ||
| 132 | global _TMP_DIR, _DISASM_DIR, _FSSM_DIR | ||
| 133 | _TMP_DIR = tempfile.TemporaryDirectory() | ||
| 134 | _DISASM_DIR = os.path.join(_TMP_DIR.name, "disasm") | ||
| 135 | _FSSM_DIR = os.path.join(_TMP_DIR.name, "fssm") | ||
| 136 | os.mkdir(_DISASM_DIR) | ||
| 137 | os.mkdir(_FSSM_DIR) | ||
| 138 | |||
| 139 | |||
| 140 | def tearDownModule(): | ||
| 141 | global _TMP_DIR, _DISASM_DIR, _FSSM_DIR | ||
| 142 | if _TMP_DIR is not None: | ||
| 143 | gc.collect() | ||
| 144 | _TMP_DIR.cleanup() | ||
| 145 | _TMP_DIR = None | ||
| 146 | _DISASM_DIR = None | ||
| 147 | _FSSM_DIR = None | ||
| 148 | |||
| 149 | |||
| 150 | def translate_cs(name: str, lines: list[str], threads: int, emulate: bool = False) -> tuple[str, object]: | ||
| 151 | assert name.startswith("cs_"), f"compute shader name must start with cs_: {name!r}" | ||
| 152 | if _TMP_DIR is None: | ||
| 153 | setUpModule() | ||
| 154 | with open(os.path.join(_FSSM_DIR, name + ".fssm"), "wb") as f: | ||
| 155 | f.write(_make_fssm(threads)) | ||
| 156 | src_path = os.path.join(_DISASM_DIR, name + ".s") | ||
| 157 | asm = f"; {name}\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" | ||
| 158 | with open(src_path, "w", encoding="utf-8", newline="") as f: | ||
| 159 | f.write(asm) | ||
| 160 | old_emu = rdna2spirv.WAVE64_EMULATE | ||
| 161 | rdna2spirv.WAVE64_EMULATE = emulate | ||
| 162 | try: | ||
| 163 | with warnings.catch_warnings(): | ||
| 164 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 165 | spv = rdna2spirv.translate(src_path) | ||
| 166 | gen = rdna2spirv.translate.last_gen | ||
| 167 | gc.collect() | ||
| 168 | finally: | ||
| 169 | rdna2spirv.WAVE64_EMULATE = old_emu | ||
| 170 | return spv, gen | ||
| 171 | |||
| 172 | |||
| 173 | def run_cs(name: str, lines: list[str], threads: int, subgroup_size: int, | ||
| 174 | init_inputs: list[int] | None = None, out_slots: int = 1) -> list[int]: | ||
| 175 | """Translate and run a compute shader; return `threads * out_slots` 32-bit output words.""" | ||
| 176 | spv, _ = translate_cs(name, lines, threads, emulate=False) | ||
| 177 | mem = _Heap() | ||
| 178 | if init_inputs is not None: | ||
| 179 | for i, val in enumerate(init_inputs): | ||
| 180 | mem[INPUT_BASE + 4 * i] = val & MASK32 | ||
| 181 | si.run_workgroup( | ||
| 182 | spv, threads, subgroup_size, | ||
| 183 | inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % subgroup_size}, | ||
| 184 | push_constants=VSHARP + [0] * 28, | ||
| 185 | memory=mem, | ||
| 186 | ) | ||
| 187 | out_bytes = 4 * threads * out_slots | ||
| 188 | stray = sorted(a for a in mem if a < INPUT_BASE and (a % 4 != 0 or a >= out_bytes)) | ||
| 189 | if stray: | ||
| 190 | raise AssertionError(f"{name}: unexpected stores outside out[0..{threads * out_slots - 1}]: {stray}") | ||
| 191 | return [mem.get(4 * k) for k in range(threads * out_slots)] | ||
| 192 | |||
| 193 | |||
| 194 | def exec_mask_lines(mask: int, wave: int) -> list[str]: | ||
| 195 | lines = [f"s_mov_b32 exec_lo, {mask & MASK32:#x}"] | ||
| 196 | if wave == 64: | ||
| 197 | lines.append(f"s_mov_b32 exec_hi, {(mask >> 32) & MASK32:#x}") | ||
| 198 | return lines | ||
| 199 | |||
| 200 | |||
| 201 | def restore_exec_lines(wave: int) -> list[str]: | ||
| 202 | return ["s_mov_b64 exec, -1"] if wave == 64 else ["s_mov_b32 exec_lo, -1"] | ||
| 203 | |||
| 204 | |||
| 205 | def store_slots_lines(regs: list[str], threads: int) -> list[str]: | ||
| 206 | """Emit buffer_store_dword for each VGPR in `regs` at `4 * (slot * threads + v0)`.""" | ||
| 207 | lines = ["v_lshlrev_b32_e32 v21, 2, v0"] | ||
| 208 | for slot, reg in enumerate(regs): | ||
| 209 | if slot == 0: | ||
| 210 | lines.append(f"buffer_store_dword {reg}, v21, s[0:3], 0 offen") | ||
| 211 | else: | ||
| 212 | lines.append(f"buffer_store_dword {reg}, v21, s[0:3], 0 offen offset:{4 * slot * threads}") | ||
| 213 | return lines | ||
| 214 | |||
| 215 | |||
| 216 | class OracleTests(unittest.TestCase): | ||
| 217 | """Cross-check hand-worked constants and ISA semantics against ref_permlane.""" | ||
| 218 | |||
| 219 | def test_hand_worked_identity_and_half_swap(self): | ||
| 220 | vals32 = [100 + l for l in range(32)] | ||
| 221 | old32 = [OLD_SENTINEL | l for l in range(32)] | ||
| 222 | # v_permlane16_b32 identity leaves all 32 lanes unchanged. | ||
| 223 | self.assertEqual(ref_permlane(False, vals32, old32, ID_S1, ID_S2, ALL32), vals32) | ||
| 224 | # v_permlanex16_b32 swaps [0..15] and [16..31]. | ||
| 225 | self.assertEqual( | ||
| 226 | ref_permlane(True, vals32, old32, ID_S1, ID_S2, ALL32), | ||
| 227 | [100 + (l ^ 16) for l in range(32)], | ||
| 228 | ) | ||
| 229 | |||
| 230 | # Wave64 swaps within each 32-lane row: [0..15]<->[16..31] and [32..47]<->[48..63]. | ||
| 231 | vals64 = [500 + l for l in range(64)] | ||
| 232 | old64 = [OLD_SENTINEL | l for l in range(64)] | ||
| 233 | got64 = ref_permlane(True, vals64, old64, ID_S1, ID_S2, ALL64) | ||
| 234 | self.assertEqual((got64[0], got64[15], got64[16], got64[31]), (516, 531, 500, 515)) | ||
| 235 | self.assertEqual((got64[32], got64[47], got64[48], got64[63]), (548, 563, 532, 547)) | ||
| 236 | |||
| 237 | def test_hand_worked_nibble_patterns_and_exec_opsel_rules(self): | ||
| 238 | vals32 = [1000 + l for l in range(32)] | ||
| 239 | old32 = [OLD_SENTINEL | l for l in range(32)] | ||
| 240 | |||
| 241 | # Broadcast 0 from s1 (lanes 0..7) and 15 from s2 (lanes 8..15). | ||
| 242 | got_bcast = ref_permlane(False, vals32, old32, 0x00000000, 0xFFFFFFFF, ALL32) | ||
| 243 | self.assertEqual(got_bcast[0:8], [1000] * 8) | ||
| 244 | self.assertEqual(got_bcast[8:16], [1015] * 8) | ||
| 245 | self.assertEqual(got_bcast[16:24], [1016] * 8) | ||
| 246 | self.assertEqual(got_bcast[24:32], [1031] * 8) | ||
| 247 | |||
| 248 | # Full 16-lane reversal: s1=0x89abcdef (lanes 0..7 -> 15..8), s2=0x01234567 (lanes 8..15 -> 7..0). | ||
| 249 | got_rev16 = ref_permlane(False, vals32, old32, REV16_S1, REV16_S2, ALL32) | ||
| 250 | self.assertEqual(got_rev16[0:16], [1000 + (15 - l) for l in range(16)]) | ||
| 251 | self.assertEqual(got_rev16[16:32], [1016 + (15 - l) for l in range(16)]) | ||
| 252 | |||
| 253 | # Sub-half 8-lane reversal: s1=0x01234567 (0..7 -> 7..0), s2=0x89abcdef (8..15 -> 15..8). | ||
| 254 | got_rev8 = ref_permlane(True, vals32, old32, REV8_S1, REV8_S2, ALL32) | ||
| 255 | self.assertEqual(got_rev8[0:8], [1016 + (7 - l) for l in range(8)]) | ||
| 256 | self.assertEqual(got_rev8[8:16], [1016 + (15 - l) for l in range(8)]) | ||
| 257 | |||
| 258 | # op_sel:[fi, bound_ctrl] when lane 0 is INACTIVE in EXEC (0xFFFFFFFE): | ||
| 259 | # lanes 1..15 broadcast local lane 0 (inactive in half 0!), lanes 16..31 broadcast local lane 16 (active!). | ||
| 260 | exec_no_0 = ALL32 ^ 1 | ||
| 261 | # fi=0, bound_ctrl=0 -> lanes 1..15 keep old32, lane 0 keeps old32[0], lanes 16..31 read 1016. | ||
| 262 | r00 = ref_permlane(False, vals32, old32, 0, 0, exec_no_0, fi=0, bound_ctrl=0) | ||
| 263 | self.assertEqual(r00[0], old32[0]) | ||
| 264 | self.assertEqual(r00[1:16], old32[1:16]) | ||
| 265 | self.assertEqual(r00[16:32], [1016] * 16) | ||
| 266 | |||
| 267 | # fi=0, bound_ctrl=1 -> lanes 1..15 write 0, lane 0 keeps old32[0], lanes 16..31 read 1016. | ||
| 268 | r01 = ref_permlane(False, vals32, old32, 0, 0, exec_no_0, fi=0, bound_ctrl=1) | ||
| 269 | self.assertEqual(r01[0], old32[0]) | ||
| 270 | self.assertEqual(r01[1:16], [0] * 15) | ||
| 271 | self.assertEqual(r01[16:32], [1016] * 16) | ||
| 272 | |||
| 273 | # fi=1, bound_ctrl=0 or 1 -> lanes 1..15 read inactive lane 0's vals32[0], lane 0 keeps old32[0]. | ||
| 274 | for bc in (0, 1): | ||
| 275 | r1x = ref_permlane(False, vals32, old32, 0, 0, exec_no_0, fi=1, bound_ctrl=bc) | ||
| 276 | self.assertEqual(r1x[0], old32[0]) | ||
| 277 | self.assertEqual(r1x[1:16], [1000] * 15) | ||
| 278 | self.assertEqual(r1x[16:32], [1016] * 16) | ||
| 279 | |||
| 280 | |||
| 281 | class Wave32ExecutionTests(unittest.TestCase): | ||
| 282 | """End-to-end 32-lane execution for v_permlane16_b32 and v_permlanex16_b32.""" | ||
| 283 | |||
| 284 | def _run_batch(self, specs: list[tuple[bool, int, int, str, str]], init_vals: list[int], | ||
| 285 | old_vals: list[int], exec_mask: int = ALL32) -> list[list[int]]: | ||
| 286 | """Run a list of (x16, s1, s2, src_form, extra_mods) batched into one shader.""" | ||
| 287 | lines = [ | ||
| 288 | "v_lshlrev_b32_e32 v20, 2, v0", | ||
| 289 | f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20", | ||
| 290 | "buffer_load_dword v1, v20, s[0:3], 0 offen", | ||
| 291 | ] | ||
| 292 | regs = [] | ||
| 293 | for idx, _ in enumerate(specs): | ||
| 294 | dst = f"v{2 + idx}" | ||
| 295 | regs.append(dst) | ||
| 296 | lines.append(f"v_or_b32_e32 {dst}, {OLD_SENTINEL:#x}, v0") | ||
| 297 | lines.extend(exec_mask_lines(exec_mask, 32)) | ||
| 298 | for idx, (x16, s1, s2, src_expr, extra) in enumerate(specs): | ||
| 299 | dst = f"v{2 + idx}" | ||
| 300 | op = "v_permlanex16_b32" if x16 else "v_permlane16_b32" | ||
| 301 | if src_expr == "sgpr": | ||
| 302 | lines += [f"s_mov_b32 s4, {s1:#x}", f"s_mov_b32 s5, {s2:#x}", | ||
| 303 | f"{op} {dst}, v1, s4, s5{extra}"] | ||
| 304 | elif src_expr == "lit_sgpr": | ||
| 305 | lines += [f"s_mov_b32 s5, {s2:#x}", f"{op} {dst}, v1, {s1:#x}, s5{extra}"] | ||
| 306 | elif src_expr == "sgpr_lit": | ||
| 307 | lines += [f"s_mov_b32 s4, {s1:#x}", f"{op} {dst}, v1, s4, {s2:#x}{extra}"] | ||
| 308 | elif src_expr == "inline": | ||
| 309 | lines.append(f"{op} {dst}, v1, {s1}, {s2}{extra}") | ||
| 310 | elif src_expr == "same_sgpr": | ||
| 311 | assert s1 == s2 | ||
| 312 | lines += [f"s_mov_b32 s4, {s1:#x}", f"{op} {dst}, v1, s4, s4{extra}"] | ||
| 313 | elif src_expr == "e64_sgpr": | ||
| 314 | lines += [f"s_mov_b32 s4, {s1:#x}", f"s_mov_b32 s5, {s2:#x}", | ||
| 315 | f"{op}_e64 {dst}, v1, s4, s5{extra}"] | ||
| 316 | else: | ||
| 317 | raise ValueError(src_expr) | ||
| 318 | lines.extend(restore_exec_lines(32)) | ||
| 319 | lines.extend(store_slots_lines(regs, 32)) | ||
| 320 | flat = run_cs("cs_w32_permlane_batch", lines, 32, 32, init_inputs=init_vals, out_slots=len(specs)) | ||
| 321 | return [flat[slot * 32:(slot + 1) * 32] for slot in range(len(specs))] | ||
| 322 | |||
| 323 | def test_half_isolation_vs_cross_half_swap_and_nibble_selectors(self): | ||
| 324 | init_vals = [(0x10000000 + l * 0x010101) & MASK32 for l in range(32)] | ||
| 325 | old_vals = [OLD_SENTINEL | l for l in range(32)] | ||
| 326 | specs = [ | ||
| 327 | # Identity (SGPR+SGPR, literal+SGPR, SGPR+literal, _e64) | ||
| 328 | (False, ID_S1, ID_S2, "sgpr", ""), | ||
| 329 | (True, ID_S1, ID_S2, "sgpr", ""), | ||
| 330 | (False, ID_S1, ID_S2, "lit_sgpr", ""), | ||
| 331 | (True, ID_S1, ID_S2, "sgpr_lit", ""), | ||
| 332 | (True, ID_S1, ID_S2, "e64_sgpr", ""), | ||
| 333 | # Broadcasts with inline constants (0, -1, 15, -16) and same-SGPR | ||
| 334 | (False, 0, 0, "inline", ""), | ||
| 335 | (True, 0, 0, "inline", ""), | ||
| 336 | (False, -1, -1, "inline", ""), | ||
| 337 | (True, 0, -1, "inline", ""), | ||
| 338 | (False, -16, 15, "inline", ""), # -16 = 0xfffffff0, 15 = 0x0000000f | ||
| 339 | (True, 0x55555555, 0x55555555, "same_sgpr", ""), | ||
| 340 | # 8-lane reversal vs full 16-lane reversal | ||
| 341 | (False, REV8_S1, REV8_S2, "sgpr", ""), | ||
| 342 | (True, REV8_S1, REV8_S2, "sgpr", ""), | ||
| 343 | (False, REV16_S1, REV16_S2, "sgpr", ""), | ||
| 344 | (True, REV16_S1, REV16_S2, "sgpr", ""), | ||
| 345 | # Pairwise swap & asymmetric non-bijective permutation | ||
| 346 | (False, PAIR_SWAP_S1, PAIR_SWAP_S2, "sgpr", ""), | ||
| 347 | (True, ASYM_S1, ASYM_S2, "sgpr", ""), | ||
| 348 | ] | ||
| 349 | results = self._run_batch(specs, init_vals, old_vals) | ||
| 350 | for idx, (x16, s1, s2, form, _) in enumerate(specs): | ||
| 351 | s1_u = s1 & MASK32 | ||
| 352 | s2_u = s2 & MASK32 | ||
| 353 | want = ref_permlane(x16, init_vals, old_vals, s1_u, s2_u, ALL32) | ||
| 354 | with self.subTest(idx=idx, x16=x16, form=form, s1=hex(s1_u), s2=hex(s2_u)): | ||
| 355 | self.assertEqual(results[idx], want) | ||
| 356 | |||
| 357 | # Spot-check half-staying vs half-swapping explicitly: | ||
| 358 | self.assertEqual(results[0], init_vals) | ||
| 359 | self.assertEqual(results[1], init_vals[16:32] + init_vals[0:16]) | ||
| 360 | |||
| 361 | def test_all_16_nibble_broadcasts_for_both_ops(self): | ||
| 362 | init_vals = [0x9000 + l * 17 for l in range(32)] | ||
| 363 | old_vals = [OLD_SENTINEL | l for l in range(32)] | ||
| 364 | specs = [] | ||
| 365 | for nib in range(16): | ||
| 366 | sel = 0x11111111 * nib | ||
| 367 | specs.append((False, sel, sel, "same_sgpr", "")) | ||
| 368 | specs.append((True, sel, sel, "same_sgpr", "")) | ||
| 369 | # Batch 16 specs at a time to stay well within VGPR file (v2..v17). | ||
| 370 | for base in (0, 16): | ||
| 371 | chunk = specs[base:base + 16] | ||
| 372 | results = self._run_batch(chunk, init_vals, old_vals) | ||
| 373 | for idx, (x16, s1, s2, _, _) in enumerate(chunk): | ||
| 374 | want = ref_permlane(x16, init_vals, old_vals, s1, s2, ALL32) | ||
| 375 | with self.subTest(x16=x16, nib=s1 & 0xF): | ||
| 376 | self.assertEqual(results[idx], want) | ||
| 377 | |||
| 378 | def test_butterfly_32lane_sum_reduction(self): | ||
| 379 | # Real compiler idiom: xor 1, 2, 4, 8 via v_permlane16_b32 then xor 16 via v_permlanex16_b32. | ||
| 380 | init_vals = [3 * l + 5 for l in range(32)] | ||
| 381 | expected_sum = sum(init_vals) | ||
| 382 | got = run_cs("cs_w32_permlane_butterfly", [ | ||
| 383 | "v_lshlrev_b32_e32 v20, 2, v0", | ||
| 384 | f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20", | ||
| 385 | "buffer_load_dword v1, v20, s[0:3], 0 offen", | ||
| 386 | # xor 1: s1=0x67452301, s2=0xefcdab89 | ||
| 387 | "s_mov_b32 s5, 0xefcdab89", | ||
| 388 | "v_permlane16_b32 v2, v1, 0x67452301, s5", | ||
| 389 | "v_add_nc_u32_e32 v1, v1, v2", | ||
| 390 | # xor 2: s1=0x54761032, s2=0xdcfe98ba | ||
| 391 | "s_mov_b32 s5, 0xdcfe98ba", | ||
| 392 | "v_permlane16_b32 v2, v1, 0x54761032, s5", | ||
| 393 | "v_add_nc_u32_e32 v1, v1, v2", | ||
| 394 | # xor 4: s1=0x32107654, s2=0xba98fedc | ||
| 395 | "s_mov_b32 s5, 0xba98fedc", | ||
| 396 | "v_permlane16_b32 v2, v1, 0x32107654, s5", | ||
| 397 | "v_add_nc_u32_e32 v1, v1, v2", | ||
| 398 | # xor 8: s1=0xfedcba98, s2=0x76543210 | ||
| 399 | "s_mov_b32 s5, 0x76543210", | ||
| 400 | "v_permlane16_b32 v2, v1, 0xfedcba98, s5", | ||
| 401 | "v_add_nc_u32_e32 v1, v1, v2", | ||
| 402 | # xor 16: identity nibbles via v_permlanex16_b32 | ||
| 403 | "s_mov_b32 s4, 0x76543210", | ||
| 404 | "s_mov_b32 s5, 0xfedcba98", | ||
| 405 | "v_permlanex16_b32 v2, v1, s4, s5", | ||
| 406 | "v_add_nc_u32_e32 v1, v1, v2", | ||
| 407 | "v_lshlrev_b32_e32 v21, 2, v0", | ||
| 408 | "buffer_store_dword v1, v21, s[0:3], 0 offen", | ||
| 409 | ], 32, 32, init_inputs=init_vals) | ||
| 410 | self.assertEqual(got, [expected_sum] * 32) | ||
| 411 | |||
| 412 | def test_exec_destination_masking_and_all_op_sel_with_active_sources(self): | ||
| 413 | # Active lanes in each 16-lane half are {0, 2, 4, 6, 8, 9, 10, 11}; | ||
| 414 | # selectors ONLY read from active lanes {0, 2, 4, 6, 8, 9, 10, 11}, so all 4 op_sel modes match ISA. | ||
| 415 | exec_mask = 0x0F550F55 | ||
| 416 | s1_sel = 0x64206420 # nibbles in {0, 2, 4, 6} (all active) | ||
| 417 | s2_sel = 0xBA98BA98 # nibbles in {8, 9, 10, 11} (all active) | ||
| 418 | init_vals = [0x100 + l for l in range(32)] | ||
| 419 | old_vals = [OLD_SENTINEL | l for l in range(32)] | ||
| 420 | specs = [] | ||
| 421 | for x16 in (False, True): | ||
| 422 | for mods in ("", " op_sel:[0,0]", " op_sel:[1,0]", " op_sel:[0,1]", " op_sel:[1,1]"): | ||
| 423 | specs.append((x16, s1_sel, s2_sel, "sgpr", mods)) | ||
| 424 | results = self._run_batch(specs, init_vals, old_vals, exec_mask=exec_mask) | ||
| 425 | for idx, (x16, s1, s2, _, mods) in enumerate(specs): | ||
| 426 | want = ref_permlane(x16, init_vals, old_vals, s1, s2, exec_mask) | ||
| 427 | with self.subTest(x16=x16, mods=mods or "default"): | ||
| 428 | self.assertEqual(results[idx], want) | ||
| 429 | |||
| 430 | def test_op_sel_fi1_reads_inactive_source_lanes(self): | ||
| 431 | # Lanes 0, 16 are OFF in EXEC; active lanes modify v1 to 9999 AFTER pre-filling v1, | ||
| 432 | # then v_permlane16_b32 / v_permlanex16_b32 with op_sel:[1,0] and op_sel:[1,1] broadcast | ||
| 433 | # local lane 0 (inactive lane 0 / inactive lane 16!). Active lanes must see the inactive | ||
| 434 | # lanes' pre-existing values (2000 and 2016), while inactive lanes 0 and 16 keep OLD. | ||
| 435 | exec_mask = ALL32 ^ ((1 << 0) | (1 << 16)) | ||
| 436 | init_vals = [2000 + l for l in range(32)] | ||
| 437 | old_vals = [OLD_SENTINEL | l for l in range(32)] | ||
| 438 | updated_vals = [init_vals[l] if not ((exec_mask >> l) & 1) else 9999 for l in range(32)] | ||
| 439 | |||
| 440 | lines = [ | ||
| 441 | "v_lshlrev_b32_e32 v20, 2, v0", | ||
| 442 | f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20", | ||
| 443 | "buffer_load_dword v1, v20, s[0:3], 0 offen", | ||
| 444 | f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0", | ||
| 445 | f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0", | ||
| 446 | f"v_or_b32_e32 v4, {OLD_SENTINEL:#x}, v0", | ||
| 447 | f"v_or_b32_e32 v5, {OLD_SENTINEL:#x}, v0", | ||
| 448 | *exec_mask_lines(exec_mask, 32), | ||
| 449 | "v_mov_b32_e32 v1, 9999", # inactive lanes 0 & 16 keep 2000 & 2016 | ||
| 450 | "v_permlane16_b32 v2, v1, 0, 0 op_sel:[1,0]", | ||
| 451 | "v_permlane16_b32 v3, v1, 0, 0 op_sel:[1,1]", | ||
| 452 | "v_permlanex16_b32 v4, v1, 0, 0 op_sel:[1,0]", | ||
| 453 | "v_permlanex16_b32 v5, v1, 0, 0 op_sel:[1,1]", | ||
| 454 | *restore_exec_lines(32), | ||
| 455 | *store_slots_lines(["v2", "v3", "v4", "v5"], 32), | ||
| 456 | ] | ||
| 457 | flat = run_cs("cs_w32_permlane_fi1", lines, 32, 32, init_inputs=init_vals, out_slots=4) | ||
| 458 | for slot, x16 in enumerate((False, False, True, True)): | ||
| 459 | got = flat[slot * 32:(slot + 1) * 32] | ||
| 460 | want = ref_permlane(x16, updated_vals, old_vals, 0, 0, exec_mask, fi=1, bound_ctrl=slot & 1) | ||
| 461 | self.assertEqual(got, want) | ||
| 462 | self.assertEqual(flat[0], OLD_SENTINEL | 0) | ||
| 463 | self.assertEqual(flat[1], 2000) | ||
| 464 | self.assertEqual(flat[16], OLD_SENTINEL | 16) | ||
| 465 | self.assertEqual(flat[17], 2016) | ||
| 466 | # Slot 2 (permlanex16 op_sel:[1,0]): active lanes 1..15 read inactive lane 16 (2016). | ||
| 467 | self.assertEqual(flat[2 * 32 + 1], 2016) | ||
| 468 | self.assertEqual(flat[2 * 32 + 17], 2000) | ||
| 469 | |||
| 470 | def test_destination_aliasing_v1_and_v0(self): | ||
| 471 | init_vals = [300 + l for l in range(32)] | ||
| 472 | # 1. Alias v1, v1 (with EXEC mask & fi=1 reading inactive lane 0 before overwrite) | ||
| 473 | exec_mask = ALL32 ^ (1 << 0) | ||
| 474 | got_v1 = run_cs("cs_w32_permlane_alias_v1", [ | ||
| 475 | "v_lshlrev_b32_e32 v20, 2, v0", | ||
| 476 | f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20", | ||
| 477 | "buffer_load_dword v1, v20, s[0:3], 0 offen", | ||
| 478 | "v_mov_b32_e32 v2, v1", | ||
| 479 | *exec_mask_lines(exec_mask, 32), | ||
| 480 | "s_mov_b32 s4, 0x00000000", | ||
| 481 | "s_mov_b32 s5, 0x00000000", | ||
| 482 | "v_permlane16_b32 v1, v1, s4, s5 op_sel:[1,0]", | ||
| 483 | "v_permlanex16_b32 v2, v2, 0x76543210, 0xfedcba98 op_sel:[1,0]", | ||
| 484 | *restore_exec_lines(32), | ||
| 485 | *store_slots_lines(["v1", "v2"], 32), | ||
| 486 | ], 32, 32, init_inputs=init_vals, out_slots=2) | ||
| 487 | self.assertEqual(got_v1[:32], ref_permlane(False, init_vals, init_vals, 0, 0, exec_mask, fi=1)) | ||
| 488 | self.assertEqual(got_v1[32:], ref_permlane(True, init_vals, init_vals, ID_S1, ID_S2, exec_mask, fi=1)) | ||
| 489 | |||
| 490 | # 2. Alias v0, v0 directly (save output byte offset 4 * v0 in v21 first) | ||
| 491 | got_v0_16 = run_cs("cs_w32_permlane16_alias_v0", [ | ||
| 492 | "v_lshlrev_b32_e32 v21, 2, v0", | ||
| 493 | f"s_mov_b32 s4, {REV16_S1:#x}", | ||
| 494 | f"s_mov_b32 s5, {REV16_S2:#x}", | ||
| 495 | "v_permlane16_b32 v0, v0, s4, s5", | ||
| 496 | "buffer_store_dword v0, v21, s[0:3], 0 offen", | ||
| 497 | ], 32, 32) | ||
| 498 | self.assertEqual(got_v0_16, ref_permlane(False, list(range(32)), list(range(32)), REV16_S1, REV16_S2, ALL32)) | ||
| 499 | |||
| 500 | got_v0_x16 = run_cs("cs_w32_permlanex16_alias_v0", [ | ||
| 501 | "v_lshlrev_b32_e32 v21, 2, v0", | ||
| 502 | f"s_mov_b32 s4, {REV16_S1:#x}", | ||
| 503 | f"s_mov_b32 s5, {REV16_S2:#x}", | ||
| 504 | "v_permlanex16_b32 v0, v0, s4, s5", | ||
| 505 | "buffer_store_dword v0, v21, s[0:3], 0 offen", | ||
| 506 | ], 32, 32) | ||
| 507 | self.assertEqual(got_v0_x16, ref_permlane(True, list(range(32)), list(range(32)), REV16_S1, REV16_S2, ALL32)) | ||
| 508 | |||
| 509 | def test_partial_wave_20_lanes_avoids_missing_lanes(self): | ||
| 510 | # 20 threads on a 32-wide subgroup: lanes 20..31 do not exist. | ||
| 511 | # 1. All 20 existing lanes active (0xFFFFF): selectors in {0..3} read existing active lanes 0..3 / 16..19. | ||
| 512 | exec_20 = 0xFFFFF | ||
| 513 | got_all20 = run_cs("cs_w32_partial20_all", [ | ||
| 514 | "v_add_nc_u32_e32 v1, 700, v0", | ||
| 515 | f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0", | ||
| 516 | f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0", | ||
| 517 | *exec_mask_lines(exec_20, 32), | ||
| 518 | "v_permlane16_b32 v2, v1, 0x32103210, 0x01230123", | ||
| 519 | "v_permlanex16_b32 v3, v1, 0x32103210, 0x01230123", | ||
| 520 | *restore_exec_lines(32), | ||
| 521 | *store_slots_lines(["v2", "v3"], 20), | ||
| 522 | ], 20, 32, out_slots=2) | ||
| 523 | vals_padded = [700 + l for l in range(20)] + [0] * 12 | ||
| 524 | old_padded = [OLD_SENTINEL | l for l in range(20)] + [0] * 12 | ||
| 525 | self.assertEqual(got_all20[:20], ref_permlane(False, vals_padded, old_padded, 0x32103210, 0x01230123, exec_20)[:20]) | ||
| 526 | self.assertEqual(got_all20[20:40], ref_permlane(True, vals_padded, old_padded, 0x32103210, 0x01230123, exec_20)[:20]) | ||
| 527 | |||
| 528 | # 2. EXEC = 0xFFFF (lanes 16..19 inactive): permlane16 reads [0..15] and preserves OLD on 16..19; | ||
| 529 | # permlanex16 op_sel:[1,0] (fi=1) reads inactive lanes 16..19 while inactive lanes 16..19 discard UNDEF | ||
| 530 | # shuffles from missing lanes 20..31 and keep OLD. | ||
| 531 | exec_16 = 0xFFFF | ||
| 532 | got_masked = run_cs("cs_w32_partial20_masked", [ | ||
| 533 | "v_add_nc_u32_e32 v1, 700, v0", | ||
| 534 | f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0", | ||
| 535 | f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0", | ||
| 536 | *exec_mask_lines(exec_16, 32), | ||
| 537 | "v_permlane16_b32 v2, v1, 0x01234567, 0x89abcdef", | ||
| 538 | "v_permlanex16_b32 v3, v1, 0x32103210, 0x01230123 op_sel:[1,0]", | ||
| 539 | *restore_exec_lines(32), | ||
| 540 | *store_slots_lines(["v2", "v3"], 20), | ||
| 541 | ], 20, 32, out_slots=2) | ||
| 542 | self.assertEqual(got_masked[:20], ref_permlane(False, vals_padded, old_padded, REV8_S1, REV8_S2, exec_16)[:20]) | ||
| 543 | self.assertEqual(got_masked[20:40], ref_permlane(True, vals_padded, old_padded, 0x32103210, 0x01230123, exec_16, fi=1)[:20]) | ||
| 544 | |||
| 545 | |||
| 546 | class Wave64ExecutionTests(unittest.TestCase): | ||
| 547 | """End-to-end 64-lane execution across one 64-wide subgroup AND two 32-wide subgroups.""" | ||
| 548 | |||
| 549 | def test_wave64_halves_selectors_exec_and_fi1_on_subgroup_64_and_32(self): | ||
| 550 | init_vals = [0x4000 + l * 31 for l in range(64)] | ||
| 551 | old_vals = [OLD_SENTINEL | l for l in range(64)] | ||
| 552 | # Asymmetric 64-bit EXEC: active lanes in each 16-lane quarter are {0, 2, 4, 6, 8, 9, 10, 11}. | ||
| 553 | exec_active_only = 0x0F550F550F550F55 | ||
| 554 | # Inactive source lane 0 and lane 32 (one in each 32-lane row) for fi=1 test. | ||
| 555 | exec_no_0_32 = ALL64 ^ ((1 << 0) | (1 << 32)) | ||
| 556 | updated_fi1 = [init_vals[l] if not ((exec_no_0_32 >> l) & 1) else (8800 + l) for l in range(64)] | ||
| 557 | |||
| 558 | lines = [ | ||
| 559 | "s_mov_b64 exec, -1", | ||
| 560 | "v_lshlrev_b32_e32 v20, 2, v0", | ||
| 561 | f"v_add_nc_u32_e32 v20, {INPUT_BASE:#x}, v20", | ||
| 562 | "buffer_load_dword v1, v20, s[0:3], 0 offen", | ||
| 563 | "v_mov_b32_e32 v10, v1", | ||
| 564 | # Slot 0: v_permlane16_b32 identity (stays in [0..15], [16..31], [32..47], [48..63]) | ||
| 565 | f"s_mov_b32 s4, {ID_S1:#x}", | ||
| 566 | f"s_mov_b32 s5, {ID_S2:#x}", | ||
| 567 | "v_permlane16_b32 v2, v1, s4, s5", | ||
| 568 | # Slot 1: v_permlanex16_b32 identity (swaps [0..15]<->[16..31] and [32..47]<->[48..63]) | ||
| 569 | "v_permlanex16_b32 v3, v1, s4, s5", | ||
| 570 | # Slot 2: v_permlane16_b32 asymmetric non-bijective selectors | ||
| 571 | f"s_mov_b32 s6, {ASYM_S1:#x}", | ||
| 572 | f"s_mov_b32 s7, {ASYM_S2:#x}", | ||
| 573 | "v_permlane16_b32 v4, v1, s6, s7", | ||
| 574 | # Slot 3: v_permlanex16_b32_e64 full 16-lane reversal | ||
| 575 | f"s_mov_b32 s8, {REV16_S2:#x}", | ||
| 576 | f"v_permlanex16_b32_e64 v5, v1, {REV16_S1:#x}, s8", | ||
| 577 | # Slot 4: 64-bit EXEC destination masking with active sources (v6 pre-loaded with OLD) | ||
| 578 | f"v_or_b32_e32 v6, {OLD_SENTINEL:#x}, v0", | ||
| 579 | "s_mov_b32 s9, 0xba98ba98", | ||
| 580 | *exec_mask_lines(exec_active_only, 64), | ||
| 581 | "v_permlanex16_b32 v6, v1, 0x64206420, s9", | ||
| 582 | *restore_exec_lines(64), | ||
| 583 | # Slot 5: fi=1 reading inactive source lane 0 (in low 32) and lane 32 (in high 32) | ||
| 584 | f"v_or_b32_e32 v7, {OLD_SENTINEL:#x}, v0", | ||
| 585 | *exec_mask_lines(exec_no_0_32, 64), | ||
| 586 | "v_add_nc_u32_e32 v10, 8800, v0", | ||
| 587 | "v_permlane16_b32 v7, v10, 0, 0 op_sel:[1,0]", | ||
| 588 | # Slot 6: fi=1 permlanex16 reading inactive lane 32 from lanes 48..63 & lane 0 from 16..31 | ||
| 589 | *restore_exec_lines(64), | ||
| 590 | f"v_or_b32_e32 v8, {OLD_SENTINEL:#x}, v0", | ||
| 591 | *exec_mask_lines(exec_no_0_32, 64), | ||
| 592 | "v_permlanex16_b32 v8, v10, 0, 0 op_sel:[1,1]", | ||
| 593 | *restore_exec_lines(64), | ||
| 594 | *store_slots_lines(["v2", "v3", "v4", "v5", "v6", "v7", "v8"], 64), | ||
| 595 | ] | ||
| 596 | |||
| 597 | expected_slots = [ | ||
| 598 | ref_permlane(False, init_vals, old_vals, ID_S1, ID_S2, ALL64), | ||
| 599 | ref_permlane(True, init_vals, old_vals, ID_S1, ID_S2, ALL64), | ||
| 600 | ref_permlane(False, init_vals, old_vals, ASYM_S1, ASYM_S2, ALL64), | ||
| 601 | ref_permlane(True, init_vals, old_vals, REV16_S1, REV16_S2, ALL64), | ||
| 602 | ref_permlane(True, init_vals, old_vals, 0x64206420, 0xBA98BA98, exec_active_only), | ||
| 603 | ref_permlane(False, updated_fi1, old_vals, 0, 0, exec_no_0_32, fi=1, bound_ctrl=0), | ||
| 604 | ref_permlane(True, updated_fi1, old_vals, 0, 0, exec_no_0_32, fi=1, bound_ctrl=1), | ||
| 605 | ] | ||
| 606 | |||
| 607 | for subgroup_size in (64, 32): | ||
| 608 | with self.subTest(subgroup_size=subgroup_size): | ||
| 609 | flat = run_cs(f"cs_w64_permlane_sg{subgroup_size}", lines, 64, subgroup_size, | ||
| 610 | init_inputs=init_vals, out_slots=7) | ||
| 611 | for slot, want in enumerate(expected_slots): | ||
| 612 | got = flat[slot * 64:(slot + 1) * 64] | ||
| 613 | self.assertEqual(got, want, f"subgroup={subgroup_size}, slot={slot}") | ||
| 614 | |||
| 615 | def test_wave64_destination_aliasing_v0_and_v1(self): | ||
| 616 | for subgroup_size in (64, 32): | ||
| 617 | with self.subTest(subgroup_size=subgroup_size): | ||
| 618 | got = run_cs(f"cs_w64_permlane_alias_sg{subgroup_size}", [ | ||
| 619 | "s_mov_b64 exec, -1", | ||
| 620 | "v_lshlrev_b32_e32 v21, 2, v0", | ||
| 621 | "v_add_nc_u32_e32 v1, 500, v0", | ||
| 622 | f"s_mov_b32 s4, {PAIR_SWAP_S1:#x}", | ||
| 623 | f"s_mov_b32 s5, {PAIR_SWAP_S2:#x}", | ||
| 624 | "v_permlane16_b32 v1, v1, s4, s5", | ||
| 625 | "v_permlanex16_b32 v0, v0, s4, s5", | ||
| 626 | "buffer_store_dword v1, v21, s[0:3], 0 offen", | ||
| 627 | f"buffer_store_dword v0, v21, s[0:3], 0 offen offset:{4 * 64}", | ||
| 628 | ], 64, subgroup_size, out_slots=2) | ||
| 629 | self.assertEqual( | ||
| 630 | got[:64], | ||
| 631 | ref_permlane(False, [500 + l for l in range(64)], [0] * 64, PAIR_SWAP_S1, PAIR_SWAP_S2, ALL64), | ||
| 632 | ) | ||
| 633 | self.assertEqual( | ||
| 634 | got[64:], | ||
| 635 | ref_permlane(True, list(range(64)), list(range(64)), PAIR_SWAP_S1, PAIR_SWAP_S2, ALL64), | ||
| 636 | ) | ||
| 637 | |||
| 638 | def test_wave64_partial_wave_40_lanes(self): | ||
| 639 | # 40 threads in a 64-wide subgroup: lanes 32..39 exist in quarter [32..47]; lanes 40..63 do not. | ||
| 640 | # Active lanes 0..31 run v_permlanex16_b32 across [0..15] <-> [16..31], and lanes 32..39 run | ||
| 641 | # v_permlane16_b32 within [32..39]; inactive lanes 32..39 on permlanex16 discard UNDEF from [48..63]. | ||
| 642 | exec_low32 = 0x00000000FFFFFFFF | ||
| 643 | got = run_cs("cs_w64_partial40_permlane", [ | ||
| 644 | "s_mov_b64 exec, -1", | ||
| 645 | "v_add_nc_u32_e32 v1, 200, v0", | ||
| 646 | f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0", | ||
| 647 | f"v_or_b32_e32 v3, {OLD_SENTINEL:#x}, v0", | ||
| 648 | "v_permlane16_b32 v2, v1, 0x32107654, 0x32107654", | ||
| 649 | *exec_mask_lines(exec_low32, 64), | ||
| 650 | "v_permlanex16_b32 v3, v1, 0x01234567, 0x89abcdef", | ||
| 651 | *restore_exec_lines(64), | ||
| 652 | *store_slots_lines(["v2", "v3"], 40), | ||
| 653 | ], 40, 64, out_slots=2) | ||
| 654 | vals64 = [200 + l for l in range(40)] + [0] * 24 | ||
| 655 | old64 = [OLD_SENTINEL | l for l in range(40)] + [0] * 24 | ||
| 656 | self.assertEqual(got[:40], ref_permlane(False, vals64, old64, 0x32107654, 0x32107654, ALL64)[:40]) | ||
| 657 | self.assertEqual(got[40:], ref_permlane(True, vals64, old64, REV8_S1, REV8_S2, exec_low32)[:40]) | ||
| 658 | |||
| 659 | |||
| 660 | class EmulationAndFindingTests(unittest.TestCase): | ||
| 661 | """Translation / structural SPIR-V checks for --wave64-emulate and documented op_sel finding.""" | ||
| 662 | |||
| 663 | def test_wave64_emulate_lowers_permlane_through_x_buf_without_subgroup_ops(self): | ||
| 664 | base = [ | ||
| 665 | "s_mov_b64 exec, -1", | ||
| 666 | "v_add_nc_u32_e32 v1, 100, v0", | ||
| 667 | f"s_mov_b32 s4, {ID_S1:#x}", | ||
| 668 | f"s_mov_b32 s5, {ID_S2:#x}", | ||
| 669 | ] | ||
| 670 | tail = [ | ||
| 671 | "v_lshlrev_b32_e32 v21, 2, v0", | ||
| 672 | "buffer_store_dword v2, v21, s[0:3], 0 offen", | ||
| 673 | ] | ||
| 674 | spv_16, gen_16 = translate_cs("cs_w64_emu_perm16", base + ["v_permlane16_b32 v2, v1, s4, s5"] + tail, | ||
| 675 | 64, emulate=True) | ||
| 676 | spv_x16, gen_x16 = translate_cs("cs_w64_emu_permx16", base + ["v_permlanex16_b32 v2, v1, s4, s5"] + tail, | ||
| 677 | 64, emulate=True) | ||
| 678 | for spv, gen in ((spv_16, gen_16), (spv_x16, gen_x16)): | ||
| 679 | self.assertTrue(gen.wave64 and gen.emulate) | ||
| 680 | self.assertNotIn("OpGroupNonUniform", spv) | ||
| 681 | self.assertNotIn("%sg_lane", spv) | ||
| 682 | self.assertIn("%x_buf = OpVariable", spv) | ||
| 683 | self.assertGreaterEqual(spv.count("OpControlBarrier"), 2) | ||
| 684 | # Nibble extraction (width = 4) and 16-lane half mask (0xFFFFFFF0) | ||
| 685 | self.assertRegex(spv, r"OpBitFieldUExtract %uint %\w+ %\w+ %c4\b") | ||
| 686 | self.assertIn("OpBitwiseAnd %uint %", spv) | ||
| 687 | self.assertIn("%cfffffff0", spv) | ||
| 688 | # spirv_mini_interp.py deliberately rejects the emulated Workgroup/loop scheduler. | ||
| 689 | with self.assertRaises(si.UnsupportedConstruct): | ||
| 690 | si.run_workgroup( | ||
| 691 | spv, 64, 32, | ||
| 692 | inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % 32}, | ||
| 693 | push_constants=VSHARP + [0] * 28, memory={}, | ||
| 694 | ) | ||
| 695 | |||
| 696 | # v_permlanex16_b32 XORs the masked half base with 16 (%c10); v_permlane16_b32 does not. | ||
| 697 | xor16_pat = r"OpBitwiseAnd %uint %\w+ %cfffffff0\n\s*%\w+ = OpBitwiseXor %uint %\w+ %c10\b" | ||
| 698 | self.assertIsNone(re.search(xor16_pat, spv_16)) | ||
| 699 | self.assertIsNotNone(re.search(xor16_pat, spv_x16)) | ||
| 700 | |||
| 701 | # Wave32 shaders are unaffected by WAVE64_EMULATE=True. | ||
| 702 | w32_lines = ["v_permlanex16_b32 v2, v0, 0x76543210, 0xfedcba98", | ||
| 703 | "v_lshlrev_b32_e32 v21, 2, v0", "buffer_store_dword v2, v21, s[0:3], 0 offen"] | ||
| 704 | spv_w32_plain, _ = translate_cs("cs_w32_emu_nop", w32_lines, 32, emulate=False) | ||
| 705 | spv_w32_emu, gen_w32_emu = translate_cs("cs_w32_emu_nop", w32_lines, 32, emulate=True) | ||
| 706 | self.assertFalse(gen_w32_emu.wave64 or gen_w32_emu.emulate) | ||
| 707 | self.assertEqual(spv_w32_plain, spv_w32_emu) | ||
| 708 | |||
| 709 | def test_op_sel_fi0_translates_cleanly_while_inactive_src_handling_is_excluded(self): | ||
| 710 | # Documented finding (tools/rdna2spirv.py lines 4608-4632): op_sel:[0,0] and op_sel:[0,1] | ||
| 711 | # are accepted by shader_ir/rdna2spirv without raising Unsupported, and lower to | ||
| 712 | # OpGroupNonUniformShuffle without inspecting mods or source %active; inactive-source fi=0 | ||
| 713 | # value assertions stay excluded from Wave32ExecutionTests / Wave64ExecutionTests. | ||
| 714 | for op in ("v_permlane16_b32", "v_permlanex16_b32"): | ||
| 715 | for opsel in ("op_sel:[0,0]", "op_sel:[0,1]"): | ||
| 716 | with self.subTest(op=op, opsel=opsel): | ||
| 717 | spv, gen = translate_cs("cs_w32_opsel_fi0", [ | ||
| 718 | "v_mov_b32_e32 v1, v0", | ||
| 719 | "s_mov_b32 exec_lo, 0xfffffffe", | ||
| 720 | f"{op} v2, v1, 0, 0 {opsel}", | ||
| 721 | "s_mov_b32 exec_lo, -1", | ||
| 722 | "v_lshlrev_b32_e32 v21, 2, v0", | ||
| 723 | "buffer_store_dword v2, v21, s[0:3], 0 offen", | ||
| 724 | ], 32) | ||
| 725 | self.assertFalse(gen.wave64) | ||
| 726 | self.assertIn("OpGroupNonUniformShuffle %uint %c3", spv) | ||
| 727 | self.assertRegex(spv, r"OpBitFieldUExtract %uint %\w+ %\w+ %c4\b") | ||
| 728 | |||
| 729 | |||
| 730 | class NegativeControls(unittest.TestCase): | ||
| 731 | """Sabotage the translated SPIR-V like a translator regression; multi-lane execution must detect it.""" | ||
| 732 | |||
| 733 | def _run(self, spv: str, threads: int, subgroup_size: int) -> list[int]: | ||
| 734 | mem = _Heap() | ||
| 735 | si.run_workgroup( | ||
| 736 | spv, threads, subgroup_size, | ||
| 737 | inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0), "%sg_lane": i % subgroup_size}, | ||
| 738 | push_constants=VSHARP + [0] * 28, | ||
| 739 | memory=mem, | ||
| 740 | ) | ||
| 741 | return [mem.get(4 * k) for k in range(threads)] | ||
| 742 | |||
| 743 | def test_sabotage_permlanex16_xor16_dropped(self): | ||
| 744 | spv, _ = translate_cs("cs_w64_neg_x16", [ | ||
| 745 | "s_mov_b64 exec, -1", | ||
| 746 | "v_add_nc_u32_e32 v1, 100, v0", | ||
| 747 | f"v_permlanex16_b32 v2, v1, {ID_S1:#x}, {ID_S2:#x}", | ||
| 748 | "v_lshlrev_b32_e32 v21, 2, v0", | ||
| 749 | "buffer_store_dword v2, v21, s[0:3], 0 offen", | ||
| 750 | ], 64) | ||
| 751 | want = ref_permlane(True, [100 + l for l in range(64)], [0] * 64, ID_S1, ID_S2, ALL64) | ||
| 752 | self.assertEqual(self._run(spv, 64, 64), want) | ||
| 753 | |||
| 754 | bad, n = re.subn(r"(%\w+) = OpBitwiseXor %uint (%\w+) %c10\b", r"\1 = OpCopyObject %uint \2", spv) | ||
| 755 | self.assertEqual(n, 1) | ||
| 756 | got_bad = self._run(bad, 64, 64) | ||
| 757 | self.assertNotEqual(got_bad, want) | ||
| 758 | self.assertEqual(got_bad, [100 + l for l in range(64)]) # collapsed to permlane16 | ||
| 759 | |||
| 760 | def test_sabotage_half_base_dropped_or_shuffle_removed(self): | ||
| 761 | spv, _ = translate_cs("cs_w32_neg_perm16", [ | ||
| 762 | "v_add_nc_u32_e32 v1, 200, v0", | ||
| 763 | f"v_or_b32_e32 v2, {OLD_SENTINEL:#x}, v0", | ||
| 764 | f"s_mov_b32 exec_lo, {0x0F550F55:#x}", | ||
| 765 | "s_mov_b32 s4, 0x64206420", | ||
| 766 | "s_mov_b32 s5, 0xba98ba98", | ||
| 767 | "v_permlane16_b32 v2, v1, s4, s5", | ||
| 768 | "s_mov_b32 exec_lo, -1", | ||
| 769 | "v_lshlrev_b32_e32 v21, 2, v0", | ||
| 770 | "buffer_store_dword v2, v21, s[0:3], 0 offen", | ||
| 771 | ], 32) | ||
| 772 | want = ref_permlane(False, [200 + l for l in range(32)], [OLD_SENTINEL | l for l in range(32)], | ||
| 773 | 0x64206420, 0xBA98BA98, 0x0F550F55) | ||
| 774 | self.assertEqual(self._run(spv, 32, 32), want) | ||
| 775 | |||
| 776 | # 1. Dropping the 0xFFFFFFF0 half-base mask sends lanes 16..31 into [0..15]. | ||
| 777 | bad_half, n1 = re.subn(r"OpBitwiseAnd %uint (%\w+) %cfffffff0\b", r"OpBitwiseAnd %uint \1 %c0", spv) | ||
| 778 | self.assertEqual(n1, 1) | ||
| 779 | self.assertNotEqual(self._run(bad_half, 32, 32), want) | ||
| 780 | |||
| 781 | # 2. Swapping the hi8 OpSelect arms swaps s1 (lanes 0..7) and s2 (lanes 8..15). | ||
| 782 | bad_sel, n2 = re.subn( | ||
| 783 | r"(%\w+ = OpUGreaterThanEqual %bool %\w+ %c8\n(?:.*\n){0,5}?\s*%\w+ = OpSelect %uint %\w+ )(%\w+) (%\w+)", | ||
| 784 | r"\1\3 \2", | ||
| 785 | spv, | ||
| 786 | ) | ||
| 787 | self.assertEqual(n2, 1) | ||
| 788 | self.assertNotEqual(self._run(bad_sel, 32, 32), want) | ||
| 789 | |||
| 790 | # 3. Replacing OpGroupNonUniformShuffle with OpCopyObject turns permute into own-lane copy. | ||
| 791 | bad_shuf, n3 = re.subn( | ||
| 792 | r"(%\w+) = OpGroupNonUniformShuffle %uint %c3 (%\w+) %\w+", | ||
| 793 | r"\1 = OpCopyObject %uint \2", | ||
| 794 | spv, | ||
| 795 | ) | ||
| 796 | self.assertEqual(n3, 1) | ||
| 797 | self.assertNotEqual(self._run(bad_shuf, 32, 32), want) | ||
| 798 | |||
| 799 | # 4. Dropping the destination EXEC OpSelect overwrites inactive destination lanes. | ||
| 800 | bad_exec, n4 = re.subn( | ||
| 801 | r"(%\w+ = OpGroupNonUniformShuffle %uint %c3 %\w+ %\w+\n(?:.*\n){0,4}?\s*" | ||
| 802 | r"%\w+ = OpLoad %bool %active\n\s*" | ||
| 803 | r"(%\w+) = OpSelect %uint %\w+ (%\w+)) %\w+", | ||
| 804 | r"\1 \3", | ||
| 805 | spv, | ||
| 806 | ) | ||
| 807 | self.assertEqual(n4, 1) | ||
| 808 | got_bad_exec = self._run(bad_exec, 32, 32) | ||
| 809 | self.assertNotEqual(got_bad_exec, want) | ||
| 810 | self.assertNotEqual(got_bad_exec[1], OLD_SENTINEL | 1) | ||
| 811 | |||
| 812 | |||
| 813 | if __name__ == "__main__": | ||
| 814 | unittest.main() | ||
diff --git a/tests/semantic/test_valu_rcp_fdiv.py b/tests/semantic/test_valu_rcp_fdiv.py new file mode 100644 index 000000000..e7f649ae0 --- /dev/null +++ b/tests/semantic/test_valu_rcp_fdiv.py | |||
| @@ -0,0 +1,824 @@ | |||
| 1 | """Semantic value tests for OpFDiv in spirv_mini_interp and RDNA2 reciprocal VALU ops: | ||
| 2 | - OpFDiv (scalar %float and vector %v2float) directly in tests/semantic/spirv_mini_interp.py | ||
| 3 | - v_rcp_f32: D.f32 = 1.0 / S0.f32 | ||
| 4 | - v_rcp_iflag_f32: D.f32 = 1.0 / S0.f32 (no FP flags) | ||
| 5 | - v_rcp_f16: D.f16 = 1.0 / S0.f16 (preserves the untouched 16-bit half of D) | ||
| 6 | |||
| 7 | Per the SPIR-V specification and tests/semantic/README.md, OpFDiv by zero (+-0.0) is undefined and raises | ||
| 8 | spirv_mini_interp.UnsupportedConstruct("OpFDiv by zero (undefined in SPIR-V)"). Accordingly, finite non-zero, | ||
| 9 | subnormal, +-inf, and NaN operands are value-checked against independent Fraction-based binary32/binary16 | ||
| 10 | oracles, while +-0.0 divisors/inputs are verified to raise UnsupportedConstruct. | ||
| 11 | |||
| 12 | NaN payloads are not pinned because values passing through Python floats lose exact NaN payload bits; NaN | ||
| 13 | results are asserted as binary32/binary16 NaNs. Standard library only; hand-written RDNA2 listings only. | ||
| 14 | """ | ||
| 15 | from fractions import Fraction | ||
| 16 | import gc | ||
| 17 | import itertools | ||
| 18 | import math | ||
| 19 | import os | ||
| 20 | import re | ||
| 21 | import struct | ||
| 22 | import sys | ||
| 23 | import tempfile | ||
| 24 | import unittest | ||
| 25 | import warnings | ||
| 26 | |||
| 27 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 28 | ROOT = os.path.dirname(os.path.dirname(HERE)) | ||
| 29 | TOOLS_DIR = os.environ.get("LEONIDA_TOOLS_DIR") or os.path.join(ROOT, "tools") | ||
| 30 | |||
| 31 | sys.dont_write_bytecode = True | ||
| 32 | if TOOLS_DIR not in sys.path: | ||
| 33 | sys.path.insert(0, TOOLS_DIR) | ||
| 34 | if HERE not in sys.path: | ||
| 35 | sys.path.insert(0, HERE) | ||
| 36 | |||
| 37 | import rdna2spirv # noqa: E402 | ||
| 38 | import spirv_mini_interp as si # noqa: E402 | ||
| 39 | |||
| 40 | MASK32 = 0xFFFFFFFF | ||
| 41 | STUB_DXBC = b"DXBC" + bytes(24) + struct.pack("<I", 0) + bytes(4) | ||
| 42 | VSHARP = [0, 0, 0xFFFFFFFF, 0x31016FAC] | ||
| 43 | OLD = 0xBEEF1234 | ||
| 44 | |||
| 45 | # Representative binary16 encodings. | ||
| 46 | H_POS_ZERO = 0x0000 | ||
| 47 | H_NEG_ZERO = 0x8000 | ||
| 48 | H_SUB_MIN = 0x0001 # 2^-24 | ||
| 49 | H_NEG_SUB_MIN = 0x8001 # -2^-24 | ||
| 50 | H_SUB_2M16 = 0x0100 # 2^-16 (1/x = 65536 >= 65520 -> +inf) | ||
| 51 | H_SUB_2M15 = 0x0200 # 2^-15 (1/x = 32768 = 0x7800) | ||
| 52 | H_SUB_MAX = 0x03FF # 1023 * 2^-24 | ||
| 53 | H_NORM_MIN = 0x0400 # 2^-14 (1/x = 16384 = 0x7400) | ||
| 54 | H_0P25 = 0x3400 # 0.25 | ||
| 55 | H_NEG_0P25 = 0xB400 # -0.25 | ||
| 56 | H_0P5 = 0x3800 # 0.5 | ||
| 57 | H_NEG_0P5 = 0xB800 # -0.5 | ||
| 58 | H_0P75 = 0x3A00 # 0.75 | ||
| 59 | H_1P0 = 0x3C00 # 1.0 | ||
| 60 | H_NEG_1P0 = 0xBC00 # -1.0 | ||
| 61 | H_NEG_1P25 = 0xBD00 # -1.25 | ||
| 62 | H_1P5 = 0x3E00 # 1.5 | ||
| 63 | H_2P0 = 0x4000 # 2.0 | ||
| 64 | H_NEG_2P0 = 0xC000 # -2.0 | ||
| 65 | H_3P0 = 0x4200 # 3.0 | ||
| 66 | H_NEG_3P0 = 0xC200 # -3.0 | ||
| 67 | H_4P0 = 0x4400 # 4.0 | ||
| 68 | H_NEG_4P0 = 0xC400 # -4.0 | ||
| 69 | H_8P0 = 0x4800 # 8.0 | ||
| 70 | H_16P0 = 0x4C00 # 16.0 | ||
| 71 | H_1024 = 0x6400 # 1024.0 | ||
| 72 | H_MAX = 0x7BFF # 65504.0 | ||
| 73 | H_NEG_MAX = 0xFBFF # -65504.0 | ||
| 74 | H_POS_INF = 0x7C00 # +inf | ||
| 75 | H_NEG_INF = 0xFC00 # -inf | ||
| 76 | H_QNAN = 0x7E01 # +qNaN | ||
| 77 | H_NEG_QNAN = 0xFE01 # -qNaN | ||
| 78 | H_SNAN = 0x7C01 # +sNaN | ||
| 79 | |||
| 80 | |||
| 81 | def f32_bits(x: float) -> int: | ||
| 82 | try: | ||
| 83 | return struct.unpack("<I", struct.pack("<f", x))[0] | ||
| 84 | except OverflowError: | ||
| 85 | return 0x7F800000 if x > 0 else 0xFF800000 | ||
| 86 | |||
| 87 | |||
| 88 | def is_f32_nan_bits(bits: int) -> bool: | ||
| 89 | return (bits & 0x7F800000) == 0x7F800000 and (bits & 0x007FFFFF) != 0 | ||
| 90 | |||
| 91 | |||
| 92 | def is_f16_nan(half: int) -> bool: | ||
| 93 | return (half & 0x7FFF) > 0x7C00 | ||
| 94 | |||
| 95 | |||
| 96 | def merge_half(old: int, half: int, dst_hi: int) -> int: | ||
| 97 | h = half & 0xFFFF | ||
| 98 | return ((h << 16) | (old & 0xFFFF)) if dst_hi else ((old & 0xFFFF0000) | h) | ||
| 99 | |||
| 100 | |||
| 101 | # ----------------------------------------------------------------------------- | ||
| 102 | # Independent Exact-Rational Binary32 / Binary16 Reference Oracles | ||
| 103 | # ----------------------------------------------------------------------------- | ||
| 104 | |||
| 105 | def _rne_int(q: Fraction) -> int: | ||
| 106 | n = q.numerator // q.denominator | ||
| 107 | rem = q - n | ||
| 108 | if rem > Fraction(1, 2) or (rem == Fraction(1, 2) and (n & 1)): | ||
| 109 | n += 1 | ||
| 110 | return n | ||
| 111 | |||
| 112 | |||
| 113 | def f32_to_fraction(bits: int) -> Fraction: | ||
| 114 | bits &= MASK32 | ||
| 115 | sign = -1 if (bits >> 31) else 1 | ||
| 116 | exp = (bits >> 23) & 0xFF | ||
| 117 | man = bits & 0x7FFFFF | ||
| 118 | if exp == 0xFF: | ||
| 119 | raise ValueError(f"non-finite f32 bits {bits:#010x}") | ||
| 120 | if exp == 0: | ||
| 121 | return sign * Fraction(man, 1 << 23) * Fraction(2) ** -126 | ||
| 122 | return sign * Fraction((1 << 23) | man, 1 << 23) * Fraction(2) ** (exp - 127) | ||
| 123 | |||
| 124 | |||
| 125 | def round_fraction_to_f32(val: Fraction, neg_zero: bool = False) -> int: | ||
| 126 | if val == 0: | ||
| 127 | return 0x80000000 if neg_zero else 0x00000000 | ||
| 128 | sign = 0x80000000 if val < 0 else 0 | ||
| 129 | a = abs(val) | ||
| 130 | e = a.numerator.bit_length() - a.denominator.bit_length() | ||
| 131 | if Fraction(2) ** e > a: | ||
| 132 | e -= 1 | ||
| 133 | if e < -126: | ||
| 134 | n = _rne_int(a / Fraction(2) ** -149) | ||
| 135 | if n == 0: | ||
| 136 | return sign | ||
| 137 | if n < (1 << 23): | ||
| 138 | return sign | n | ||
| 139 | return sign | (1 << 23) | ||
| 140 | n = _rne_int(a / Fraction(2) ** (e - 23)) | ||
| 141 | if n == (1 << 24): | ||
| 142 | n >>= 1 | ||
| 143 | e += 1 | ||
| 144 | if e > 127: | ||
| 145 | return sign | 0x7F800000 | ||
| 146 | return sign | ((e + 127) << 23) | (n & 0x7FFFFF) | ||
| 147 | |||
| 148 | |||
| 149 | def f16_to_fraction(half: int) -> Fraction: | ||
| 150 | half &= 0xFFFF | ||
| 151 | sign = -1 if (half >> 15) else 1 | ||
| 152 | exp = (half >> 10) & 0x1F | ||
| 153 | man = half & 0x3FF | ||
| 154 | if exp == 0x1F: | ||
| 155 | raise ValueError(f"non-finite f16 bits {half:#06x}") | ||
| 156 | if exp == 0: | ||
| 157 | return sign * Fraction(man, 1 << 10) * Fraction(2) ** -14 | ||
| 158 | return sign * Fraction((1 << 10) | man, 1 << 10) * Fraction(2) ** (exp - 15) | ||
| 159 | |||
| 160 | |||
| 161 | def round_fraction_to_f16(val: Fraction, neg_zero: bool = False) -> int: | ||
| 162 | if val == 0: | ||
| 163 | return 0x8000 if neg_zero else 0x0000 | ||
| 164 | sign = 0x8000 if val < 0 else 0 | ||
| 165 | a = abs(val) | ||
| 166 | e = a.numerator.bit_length() - a.denominator.bit_length() | ||
| 167 | if Fraction(2) ** e > a: | ||
| 168 | e -= 1 | ||
| 169 | if e < -14: | ||
| 170 | n = _rne_int(a / Fraction(2) ** -24) | ||
| 171 | return sign | n | ||
| 172 | n = _rne_int(a / Fraction(2) ** (e - 10)) | ||
| 173 | if n == (1 << 11): | ||
| 174 | n >>= 1 | ||
| 175 | e += 1 | ||
| 176 | if e > 15: | ||
| 177 | return sign | 0x7C00 | ||
| 178 | return sign | ((e + 15) << 10) | (n & 0x3FF) | ||
| 179 | |||
| 180 | |||
| 181 | def ref_rcp_f32(x_bits: int, *, scale: Fraction = Fraction(1), clamp: bool = False) -> int: | ||
| 182 | """Reference oracle for non-zero f32 reciprocal (with optional output scale/clamp).""" | ||
| 183 | bits = x_bits & MASK32 | ||
| 184 | sign = bits & 0x80000000 | ||
| 185 | absu = bits & 0x7FFFFFFF | ||
| 186 | if absu == 0: | ||
| 187 | raise ValueError("division by zero is undefined in SPIR-V") | ||
| 188 | if absu > 0x7F800000: | ||
| 189 | if clamp: | ||
| 190 | raise ValueError("clamp of NaN is undefined in GLSL.std.450") | ||
| 191 | return 0x7FC00000 | ||
| 192 | if absu == 0x7F800000: | ||
| 193 | # 1 / (+-inf) = +-0.0; omod preserves sign of zero, clamp orders -0 below +0 -> +0. | ||
| 194 | return 0 if clamp else sign | ||
| 195 | # Match OpFDiv(1, x) rounded to binary32 before clamp_mods (scale, then FClamp [0, 1]). | ||
| 196 | r_bits = round_fraction_to_f32(Fraction(1) / f32_to_fraction(bits)) | ||
| 197 | if (r_bits & 0x7FFFFFFF) == 0x7F800000: | ||
| 198 | r_sign = r_bits & 0x80000000 | ||
| 199 | if clamp: | ||
| 200 | return 0 if r_sign else 0x3F800000 | ||
| 201 | return r_bits | ||
| 202 | val = f32_to_fraction(r_bits) * scale | ||
| 203 | if clamp: | ||
| 204 | if val <= 0: | ||
| 205 | return 0x00000000 | ||
| 206 | if val >= 1: | ||
| 207 | return 0x3F800000 | ||
| 208 | return round_fraction_to_f32(val) | ||
| 209 | |||
| 210 | |||
| 211 | def ref_rcp_f16(h_bits: int, *, scale: Fraction = Fraction(1), clamp: bool = False) -> int: | ||
| 212 | """Reference oracle for non-zero f16 reciprocal (f32 OpFDiv + clamp_mods + f16_bits).""" | ||
| 213 | h = h_bits & 0xFFFF | ||
| 214 | sign = (h & 0x8000) << 16 | ||
| 215 | absh = h & 0x7FFF | ||
| 216 | if absh == 0: | ||
| 217 | raise ValueError("division by zero is undefined in SPIR-V") | ||
| 218 | if absh > 0x7C00: | ||
| 219 | if clamp: | ||
| 220 | raise ValueError("clamp of NaN is undefined in GLSL.std.450") | ||
| 221 | return (h & 0x8000) | 0x7E00 | ||
| 222 | if absh == 0x7C00: | ||
| 223 | return 0 if clamp else (h & 0x8000) | ||
| 224 | # Widening f16 -> f32 is exact, then f32 OpFDiv + omod/clamp, then f16 nearest-even narrowing. | ||
| 225 | r_bits = round_fraction_to_f32(Fraction(1) / f16_to_fraction(h)) | ||
| 226 | r_sign = r_bits & 0x80000000 | ||
| 227 | if (r_bits & 0x7FFFFFFF) == 0x7F800000: | ||
| 228 | if clamp: | ||
| 229 | return 0 if r_sign else 0x3C00 | ||
| 230 | return (r_sign >> 16) | 0x7C00 | ||
| 231 | val = f32_to_fraction(r_bits) * scale | ||
| 232 | if clamp: | ||
| 233 | if val <= 0: | ||
| 234 | return 0x0000 | ||
| 235 | if val >= 1: | ||
| 236 | return 0x3C00 | ||
| 237 | r_f32 = round_fraction_to_f32(val, neg_zero=bool(sign)) | ||
| 238 | return round_fraction_to_f16(f32_to_fraction(r_f32), neg_zero=bool(r_f32 & 0x80000000)) | ||
| 239 | |||
| 240 | |||
| 241 | RCP_F32_HAND_WORKED = ( | ||
| 242 | ("pos_one", 0x3F800000, 0x3F800000), | ||
| 243 | ("neg_one", 0xBF800000, 0xBF800000), | ||
| 244 | ("pos_two", 0x40000000, 0x3F000000), | ||
| 245 | ("neg_two", 0xC0000000, 0xBF000000), | ||
| 246 | ("pos_four", 0x40800000, 0x3E800000), | ||
| 247 | ("neg_quarter", 0xBE800000, 0xC0800000), | ||
| 248 | ("pos_2p20", 0x49800000, 0x35800000), | ||
| 249 | ("neg_2pm20", 0xB5800000, 0xC9800000), | ||
| 250 | ("pos_1p5", 0x3FC00000, 0x3F2AAAAB), | ||
| 251 | ("neg_3p0", 0xC0400000, 0xBEAAAAAB), | ||
| 252 | ("pos_0p3", 0x3E99999A, 0x40555555), | ||
| 253 | ("subnorm_2m128_to_inf", 0x00200000, 0x7F800000), | ||
| 254 | ("neg_subnorm_min_to_ninf", 0x80000001, 0xFF800000), | ||
| 255 | ("2p127_to_subnorm", 0x7F000000, 0x00400000), | ||
| 256 | ("pos_inf", 0x7F800000, 0x00000000), | ||
| 257 | ("neg_inf", 0xFF800000, 0x80000000), | ||
| 258 | ) | ||
| 259 | |||
| 260 | RCP_F16_HAND_WORKED = ( | ||
| 261 | ("pos_one", H_1P0, H_1P0), | ||
| 262 | ("neg_one", H_NEG_1P0, H_NEG_1P0), | ||
| 263 | ("pos_two", H_2P0, H_0P5), | ||
| 264 | ("neg_two", H_NEG_2P0, H_NEG_0P5), | ||
| 265 | ("pos_four", H_4P0, H_0P25), | ||
| 266 | ("neg_quarter", H_NEG_0P25, H_NEG_4P0), | ||
| 267 | ("pos_1p5", H_1P5, 0x3955), | ||
| 268 | ("pos_3p0", H_3P0, 0x3555), | ||
| 269 | ("neg_3p0", H_NEG_3P0, 0xB555), | ||
| 270 | ("sub_min_overflow", H_SUB_MIN, H_POS_INF), | ||
| 271 | ("neg_sub_min_overflow", H_NEG_SUB_MIN, H_NEG_INF), | ||
| 272 | ("sub_2m16_overflow", H_SUB_2M16, H_POS_INF), | ||
| 273 | ("sub_2m15", H_SUB_2M15, 0x7800), | ||
| 274 | ("sub_max", H_SUB_MAX, 0x7401), | ||
| 275 | ("norm_min", H_NORM_MIN, 0x7400), | ||
| 276 | ("f16_max", H_MAX, 0x0100), | ||
| 277 | ("neg_f16_max", H_NEG_MAX, 0x8100), | ||
| 278 | ("pos_inf", H_POS_INF, H_POS_ZERO), | ||
| 279 | ("neg_inf", H_NEG_INF, H_NEG_ZERO), | ||
| 280 | ) | ||
| 281 | |||
| 282 | |||
| 283 | # ----------------------------------------------------------------------------- | ||
| 284 | # Translation & Execution Helpers | ||
| 285 | # ----------------------------------------------------------------------------- | ||
| 286 | |||
| 287 | _TMP_DIR = None | ||
| 288 | _PS_PATH = None | ||
| 289 | _CS_PATH = None | ||
| 290 | _CS_FSSM = None | ||
| 291 | |||
| 292 | |||
| 293 | def _make_fssm(rsrc2: int, group: tuple[int, int, int]) -> bytes: | ||
| 294 | header = bytearray(0x148) | ||
| 295 | struct.pack_into("<4I", header, 0x138, rsrc2, *group) | ||
| 296 | return bytes(header) | ||
| 297 | |||
| 298 | |||
| 299 | def setUpModule(): | ||
| 300 | global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM | ||
| 301 | _TMP_DIR = tempfile.TemporaryDirectory() | ||
| 302 | disasm_dir = os.path.join(_TMP_DIR.name, "disasm") | ||
| 303 | fssm_dir = os.path.join(_TMP_DIR.name, "fssm") | ||
| 304 | os.mkdir(disasm_dir) | ||
| 305 | os.mkdir(fssm_dir) | ||
| 306 | _PS_PATH = os.path.join(disasm_dir, "ps_valu_rcp_fdiv.s") | ||
| 307 | _CS_PATH = os.path.join(disasm_dir, "cs_valu_rcp_fdiv.s") | ||
| 308 | _CS_FSSM = os.path.join(fssm_dir, "cs_valu_rcp_fdiv.fssm") | ||
| 309 | with open(os.path.join(_TMP_DIR.name, "ps_valu_rcp_fdiv.dxbc"), "wb") as f: | ||
| 310 | f.write(STUB_DXBC) | ||
| 311 | |||
| 312 | |||
| 313 | def tearDownModule(): | ||
| 314 | global _TMP_DIR, _PS_PATH, _CS_PATH, _CS_FSSM | ||
| 315 | if _TMP_DIR is not None: | ||
| 316 | gc.collect() | ||
| 317 | _TMP_DIR.cleanup() | ||
| 318 | _TMP_DIR = None | ||
| 319 | _PS_PATH = None | ||
| 320 | _CS_PATH = None | ||
| 321 | _CS_FSSM = None | ||
| 322 | |||
| 323 | |||
| 324 | def translate_ps(lines: list[str]) -> str: | ||
| 325 | if _TMP_DIR is None: | ||
| 326 | setUpModule() | ||
| 327 | asm = ( | ||
| 328 | "; test_valu_rcp_fdiv\n" | ||
| 329 | + "".join(f"\t{ln}\n" for ln in lines) | ||
| 330 | + "\texp mrt0 v0, v0, v0, v0 done vm\n" | ||
| 331 | + "\ts_endpgm\n" | ||
| 332 | ) | ||
| 333 | with open(_PS_PATH, "w", encoding="utf-8", newline="") as f: | ||
| 334 | f.write(asm) | ||
| 335 | with warnings.catch_warnings(): | ||
| 336 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 337 | spv = rdna2spirv.translate(_PS_PATH) | ||
| 338 | gc.collect() | ||
| 339 | return spv | ||
| 340 | |||
| 341 | |||
| 342 | def run_ps_v0(lines: list[str]) -> int: | ||
| 343 | return si.run_fragment(translate_ps(lines))["%out_mrt0"][0] | ||
| 344 | |||
| 345 | |||
| 346 | def run_op(line: str, v1: int, old: int = OLD, s4: int = 0) -> int: | ||
| 347 | return run_ps_v0([ | ||
| 348 | f"s_mov_b32 s4, {s4:#x}", | ||
| 349 | f"v_mov_b32 v1, {v1:#x}", | ||
| 350 | f"v_mov_b32 v0, {old:#x}", | ||
| 351 | line, | ||
| 352 | ]) | ||
| 353 | |||
| 354 | |||
| 355 | def run_cs(lines: list[str], group_size: int, subgroup_size: int, memory: dict[int, int]) -> dict[int, int]: | ||
| 356 | if _TMP_DIR is None: | ||
| 357 | setUpModule() | ||
| 358 | with open(_CS_FSSM, "wb") as f: | ||
| 359 | f.write(_make_fssm(0x0088, (group_size, 1, 1))) | ||
| 360 | asm = "; test_cs_valu_rcp_fdiv\n" + "".join(f"\t{ln}\n" for ln in lines) + "\ts_endpgm\n" | ||
| 361 | with open(_CS_PATH, "w", encoding="utf-8", newline="") as f: | ||
| 362 | f.write(asm) | ||
| 363 | with warnings.catch_warnings(): | ||
| 364 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 365 | spv = rdna2spirv.translate(_CS_PATH) | ||
| 366 | gc.collect() | ||
| 367 | return si.run_workgroup( | ||
| 368 | spv, group_size, subgroup_size, | ||
| 369 | inputs_for=lambda i: {"%wg_id": (0, 0, 0), "%local_id": (i, 0, 0)}, | ||
| 370 | push_constants=VSHARP + [0] * 28, | ||
| 371 | memory=memory, | ||
| 372 | ) | ||
| 373 | |||
| 374 | |||
| 375 | # ----------------------------------------------------------------------------- | ||
| 376 | # 1. Reference Oracle Self-Tests | ||
| 377 | # ----------------------------------------------------------------------------- | ||
| 378 | |||
| 379 | class OracleSelfTests(unittest.TestCase): | ||
| 380 | def test_hand_worked_rcp_f32_and_f16_match_fraction_oracles(self): | ||
| 381 | for name, x_bits, want in RCP_F32_HAND_WORKED: | ||
| 382 | with self.subTest(kind="f32", name=name): | ||
| 383 | self.assertEqual(ref_rcp_f32(x_bits), want) | ||
| 384 | for name, h_bits, want in RCP_F16_HAND_WORKED: | ||
| 385 | with self.subTest(kind="f16", name=name): | ||
| 386 | self.assertEqual(ref_rcp_f16(h_bits), want) | ||
| 387 | |||
| 388 | |||
| 389 | # ----------------------------------------------------------------------------- | ||
| 390 | # 2. Direct OpFDiv Unit Tests in spirv_mini_interp.py | ||
| 391 | # ----------------------------------------------------------------------------- | ||
| 392 | |||
| 393 | FDIV_HEADER = """\ | ||
| 394 | OpCapability Shader | ||
| 395 | OpMemoryModel Logical GLSL450 | ||
| 396 | OpEntryPoint Fragment %main "main" %out | ||
| 397 | %void = OpTypeVoid | ||
| 398 | %fn = OpTypeFunction %void | ||
| 399 | %uint = OpTypeInt 32 0 | ||
| 400 | %float = OpTypeFloat 32 | ||
| 401 | %v2float = OpTypeVector %float 2 | ||
| 402 | %_ptr_Output_uint = OpTypePointer Output %uint | ||
| 403 | %out = OpVariable %_ptr_Output_uint Output | ||
| 404 | %_ptr_PC = OpTypePointer PushConstant %uint | ||
| 405 | %pc = OpVariable %_ptr_PC PushConstant | ||
| 406 | %c0 = OpConstant %uint 0 | ||
| 407 | %c1 = OpConstant %uint 1 | ||
| 408 | %c2 = OpConstant %uint 2 | ||
| 409 | %c3 = OpConstant %uint 3 | ||
| 410 | %f0 = OpConstant %float 0 | ||
| 411 | %f0p5 = OpConstant %float 0.5 | ||
| 412 | %f1 = OpConstant %float 1 | ||
| 413 | %f2 = OpConstant %float 2 | ||
| 414 | %f3 = OpConstant %float 3 | ||
| 415 | %f4 = OpConstant %float 4 | ||
| 416 | %f255 = OpConstant %float 255 | ||
| 417 | %u_neg0 = OpConstant %uint 2147483648 | ||
| 418 | %u_inf = OpConstant %uint 2139095040 | ||
| 419 | %u_ninf = OpConstant %uint 4286578688 | ||
| 420 | %u_qnan = OpConstant %uint 2143289344 | ||
| 421 | %u_snan = OpConstant %uint 2139095041 | ||
| 422 | %u_fltmax = OpConstant %uint 2139095039 | ||
| 423 | %u_nfltmax = OpConstant %uint 4286578687 | ||
| 424 | %main = OpFunction %void None %fn | ||
| 425 | %entry = OpLabel | ||
| 426 | %fm0 = OpBitcast %float %u_neg0 | ||
| 427 | %inf = OpBitcast %float %u_inf | ||
| 428 | %ninf = OpBitcast %float %u_ninf | ||
| 429 | %qnan = OpBitcast %float %u_qnan | ||
| 430 | %snan = OpBitcast %float %u_snan | ||
| 431 | %fltmax = OpBitcast %float %u_fltmax | ||
| 432 | %nfltmax = OpBitcast %float %u_nfltmax | ||
| 433 | %fm2 = OpFNegate %float %f2 | ||
| 434 | %fm3 = OpFNegate %float %f3 | ||
| 435 | %fm1 = OpFNegate %float %f1 | ||
| 436 | """ | ||
| 437 | FDIV_FOOTER = "OpReturn\nOpFunctionEnd\n" | ||
| 438 | |||
| 439 | |||
| 440 | def run_fdiv_scalar(num: str, den: str) -> int: | ||
| 441 | text = ( | ||
| 442 | FDIV_HEADER | ||
| 443 | + f"%r = OpFDiv %float {num} {den}\n" | ||
| 444 | + "%res = OpBitcast %uint %r\n" | ||
| 445 | + "OpStore %out %res\n" | ||
| 446 | + FDIV_FOOTER | ||
| 447 | ) | ||
| 448 | return si.run_fragment(text)["%out"][0] | ||
| 449 | |||
| 450 | |||
| 451 | def run_fdiv_vec2(n0: str, n1: str, d0: str, d1: str) -> tuple[int, int]: | ||
| 452 | hdr = FDIV_HEADER.replace( | ||
| 453 | 'OpEntryPoint Fragment %main "main" %out', | ||
| 454 | 'OpEntryPoint Fragment %main "main" %out %out1', | ||
| 455 | ).replace( | ||
| 456 | "%out = OpVariable %_ptr_Output_uint Output", | ||
| 457 | "%out = OpVariable %_ptr_Output_uint Output\n%out1 = OpVariable %_ptr_Output_uint Output", | ||
| 458 | ) | ||
| 459 | body = ( | ||
| 460 | f"%vn = OpCompositeConstruct %v2float {n0} {n1}\n" | ||
| 461 | + f"%vd = OpCompositeConstruct %v2float {d0} {d1}\n" | ||
| 462 | + "%vr = OpFDiv %v2float %vn %vd\n" | ||
| 463 | + "%r0 = OpCompositeExtract %float %vr 0\n" | ||
| 464 | + "%r1 = OpCompositeExtract %float %vr 1\n" | ||
| 465 | + "%b0 = OpBitcast %uint %r0\n" | ||
| 466 | + "%b1 = OpBitcast %uint %r1\n" | ||
| 467 | + "OpStore %out %b0\n" | ||
| 468 | + "OpStore %out1 %b1\n" | ||
| 469 | ) | ||
| 470 | res = si.run_fragment(hdr + body + FDIV_FOOTER) | ||
| 471 | return res["%out"][0], res["%out1"][0] | ||
| 472 | |||
| 473 | |||
| 474 | class OpFDivInterpreterTests(unittest.TestCase): | ||
| 475 | def test_scalar_finite_signed_zero_inf_and_overflow(self): | ||
| 476 | cases = ( | ||
| 477 | ("%f1", "%f4", f32_bits(0.25)), | ||
| 478 | ("%fm3", "%f2", f32_bits(-1.5)), | ||
| 479 | ("%f3", "%f255", 0x3C40C0C1), | ||
| 480 | # Signed zero dividends keep exact IEEE sign rules. | ||
| 481 | ("%f0", "%f2", 0x00000000), | ||
| 482 | ("%f0", "%fm2", 0x80000000), | ||
| 483 | ("%fm0", "%f2", 0x80000000), | ||
| 484 | ("%fm0", "%fm2", 0x00000000), | ||
| 485 | # Division by +-inf -> +-0.0. | ||
| 486 | ("%f1", "%inf", 0x00000000), | ||
| 487 | ("%fm1", "%inf", 0x80000000), | ||
| 488 | ("%f1", "%ninf", 0x80000000), | ||
| 489 | ("%fm1", "%ninf", 0x00000000), | ||
| 490 | ("%f0", "%ninf", 0x80000000), | ||
| 491 | ("%fm0", "%inf", 0x80000000), | ||
| 492 | ("%fm0", "%ninf", 0x00000000), | ||
| 493 | # +-inf divided by finite non-zero -> +-inf. | ||
| 494 | ("%inf", "%f2", 0x7F800000), | ||
| 495 | ("%inf", "%fm2", 0xFF800000), | ||
| 496 | ("%ninf", "%f2", 0xFF800000), | ||
| 497 | ("%ninf", "%fm2", 0x7F800000), | ||
| 498 | # Binary32 overflow -> +-inf. | ||
| 499 | ("%fltmax", "%f0p5", 0x7F800000), | ||
| 500 | ("%nfltmax", "%f0p5", 0xFF800000), | ||
| 501 | ) | ||
| 502 | for num, den, want in cases: | ||
| 503 | with self.subTest(num=num, den=den): | ||
| 504 | self.assertEqual(run_fdiv_scalar(num, den), want) | ||
| 505 | |||
| 506 | def test_scalar_inf_over_inf_and_nan_propagation(self): | ||
| 507 | nan_cases = ( | ||
| 508 | ("%inf", "%inf"), | ||
| 509 | ("%inf", "%ninf"), | ||
| 510 | ("%ninf", "%inf"), | ||
| 511 | ("%ninf", "%ninf"), | ||
| 512 | ("%qnan", "%f2"), | ||
| 513 | ("%f2", "%qnan"), | ||
| 514 | ("%qnan", "%inf"), | ||
| 515 | ("%inf", "%qnan"), | ||
| 516 | ("%f0", "%qnan"), | ||
| 517 | ("%snan", "%f2"), | ||
| 518 | ("%f2", "%snan"), | ||
| 519 | ) | ||
| 520 | for num, den in nan_cases: | ||
| 521 | with self.subTest(num=num, den=den): | ||
| 522 | got = run_fdiv_scalar(num, den) | ||
| 523 | self.assertTrue(is_f32_nan_bits(got), f"expected NaN for {num}/{den}, got {got:#010x}") | ||
| 524 | |||
| 525 | def test_vector_v2float_division(self): | ||
| 526 | self.assertEqual(run_fdiv_vec2("%f1", "%fm3", "%f4", "%fm2"), (f32_bits(0.25), f32_bits(1.5))) | ||
| 527 | self.assertEqual(run_fdiv_vec2("%f1", "%fm0", "%ninf", "%ninf"), (0x80000000, 0x00000000)) | ||
| 528 | g0, g1 = run_fdiv_vec2("%f1", "%inf", "%ninf", "%ninf") | ||
| 529 | self.assertEqual(g0, 0x80000000) | ||
| 530 | self.assertTrue(is_f32_nan_bits(g1), f"expected NaN in lane 1, got {g1:#010x}") | ||
| 531 | |||
| 532 | def test_zero_divisor_and_non_float_are_rejected(self): | ||
| 533 | for num, den in ( | ||
| 534 | ("%f1", "%f0"), | ||
| 535 | ("%f1", "%fm0"), | ||
| 536 | ("%fm1", "%f0"), | ||
| 537 | ("%fm1", "%fm0"), | ||
| 538 | ("%f0", "%f0"), | ||
| 539 | ("%fm0", "%fm0"), | ||
| 540 | ("%inf", "%f0"), | ||
| 541 | ("%qnan", "%f0"), | ||
| 542 | ("%qnan", "%fm0"), | ||
| 543 | ): | ||
| 544 | with self.subTest(num=num, den=den): | ||
| 545 | with self.assertRaises(si.UnsupportedConstruct): | ||
| 546 | run_fdiv_scalar(num, den) | ||
| 547 | |||
| 548 | for n0, n1, d0, d1 in ( | ||
| 549 | ("%f1", "%f2", "%f0", "%f2"), | ||
| 550 | ("%f1", "%f2", "%f2", "%fm0"), | ||
| 551 | ): | ||
| 552 | with self.subTest(vec=(n0, n1, d0, d1)): | ||
| 553 | with self.assertRaises(si.UnsupportedConstruct): | ||
| 554 | run_fdiv_vec2(n0, n1, d0, d1) | ||
| 555 | |||
| 556 | with self.assertRaises(si.UnsupportedConstruct): | ||
| 557 | si.run_fragment( | ||
| 558 | FDIV_HEADER + "%res = OpFDiv %uint %c2 %c1\nOpStore %out %res\n" + FDIV_FOOTER | ||
| 559 | ) | ||
| 560 | |||
| 561 | |||
| 562 | # ----------------------------------------------------------------------------- | ||
| 563 | # 3. End-to-End v_rcp_f32 & v_rcp_iflag_f32 Value Tests | ||
| 564 | # ----------------------------------------------------------------------------- | ||
| 565 | |||
| 566 | class RcpF32AndIflagExecutionTests(unittest.TestCase): | ||
| 567 | OPS = ("v_rcp_f32", "v_rcp_iflag_f32") | ||
| 568 | |||
| 569 | def test_hand_worked_and_edge_values_across_encodings(self): | ||
| 570 | for op in self.OPS: | ||
| 571 | for suffix in ("_e32", "_e64", ""): | ||
| 572 | for name, x_bits, want in RCP_F32_HAND_WORKED: | ||
| 573 | with self.subTest(op=op + suffix, case=name): | ||
| 574 | got = run_op(f"{op}{suffix} v0, v1", x_bits) | ||
| 575 | self.assertEqual(got, want) | ||
| 576 | |||
| 577 | def test_nan_inputs_preserve_nan(self): | ||
| 578 | for op in self.OPS: | ||
| 579 | for suffix in ("_e32", "_e64"): | ||
| 580 | for x_bits in (0x7FC00000, 0xFFC00001, 0x7F800001, 0xFF800001): | ||
| 581 | with self.subTest(op=op + suffix, x=hex(x_bits)): | ||
| 582 | got = run_op(f"{op}{suffix} v0, v1", x_bits) | ||
| 583 | self.assertTrue(is_f32_nan_bits(got), f"expected NaN, got {got:#010x}") | ||
| 584 | |||
| 585 | def test_zero_inputs_raise_unsupported_construct(self): | ||
| 586 | for op in self.OPS: | ||
| 587 | for suffix in ("_e32", "_e64"): | ||
| 588 | for x_bits in (0x00000000, 0x80000000): | ||
| 589 | with self.subTest(op=op + suffix, x=hex(x_bits)): | ||
| 590 | with self.assertRaises(si.UnsupportedConstruct): | ||
| 591 | run_op(f"{op}{suffix} v0, v1", x_bits) | ||
| 592 | with self.subTest(op=op, mod="-|0|"): | ||
| 593 | with self.assertRaises(si.UnsupportedConstruct): | ||
| 594 | run_op(f"{op}_e64 v0, -|0|", 0) | ||
| 595 | |||
| 596 | def test_vop3_output_and_source_modifiers(self): | ||
| 597 | cases = ( | ||
| 598 | # (insn_suffix_and_src, v1_bits, scale, clamp) | ||
| 599 | ("v1 clamp", f32_bits(0.5), Fraction(1), True), | ||
| 600 | ("v1 clamp", f32_bits(-0.5), Fraction(1), True), | ||
| 601 | ("v1 clamp", f32_bits(4.0), Fraction(1), True), | ||
| 602 | ("v1 mul:2", f32_bits(4.0), Fraction(2), False), | ||
| 603 | ("v1 mul:2", f32_bits(-0.5), Fraction(2), False), | ||
| 604 | ("v1 mul:4", f32_bits(4.0), Fraction(4), False), | ||
| 605 | ("v1 mul:4", f32_bits(-2.0), Fraction(4), False), | ||
| 606 | ("v1 div:2", f32_bits(2.0), Fraction(1, 2), False), | ||
| 607 | ("v1 div:2", f32_bits(-0.5), Fraction(1, 2), False), | ||
| 608 | # omod applies before clamp: 1/0.5 * 0.5 = 1.0; 1/4.0 * 2 = 0.5; 1/0.5 * 2 -> clamped 1.0 | ||
| 609 | ("v1 mul:2 clamp", f32_bits(0.5), Fraction(2), True), | ||
| 610 | ("v1 mul:2 clamp", f32_bits(4.0), Fraction(2), True), | ||
| 611 | ("v1 mul:2 clamp", f32_bits(-0.5), Fraction(2), True), | ||
| 612 | ("v1 clamp div:2", f32_bits(0.5), Fraction(1, 2), True), | ||
| 613 | ("v1 clamp div:2", f32_bits(-0.5), Fraction(1, 2), True), | ||
| 614 | ) | ||
| 615 | for op in self.OPS: | ||
| 616 | for args, x_bits, scale, clamp in cases: | ||
| 617 | with self.subTest(op=op, args=args, x=hex(x_bits)): | ||
| 618 | got = run_op(f"{op}_e64 v0, {args}", x_bits) | ||
| 619 | want = ref_rcp_f32(x_bits, scale=scale, clamp=clamp) | ||
| 620 | self.assertEqual(got, want) | ||
| 621 | |||
| 622 | # Source modifiers (-v1, |v1|, -|v1|) alone and combined with output modifiers. | ||
| 623 | src_cases = ( | ||
| 624 | ("-v1", f32_bits(2.0), f32_bits(-0.5)), | ||
| 625 | ("|v1|", f32_bits(-4.0), f32_bits(0.25)), | ||
| 626 | ("-|v1|", f32_bits(-2.0), f32_bits(-0.5)), | ||
| 627 | ("-|v1|", f32_bits(2.0), f32_bits(-0.5)), | ||
| 628 | ("-v1 clamp", f32_bits(-0.5), f32_bits(1.0)), | ||
| 629 | ("|v1| mul:2", f32_bits(-0.5), f32_bits(4.0)), | ||
| 630 | ("-|v1| mul:2 clamp", f32_bits(0.5), f32_bits(0.0)), | ||
| 631 | ("-|v1| div:2", f32_bits(-0.5), f32_bits(-1.0)), | ||
| 632 | ) | ||
| 633 | for op in self.OPS: | ||
| 634 | for args, x_bits, want in src_cases: | ||
| 635 | with self.subTest(op=op, args=args, x=hex(x_bits)): | ||
| 636 | self.assertEqual(run_op(f"{op}_e64 v0, {args}", x_bits), want) | ||
| 637 | |||
| 638 | def test_inline_constants_literals_sgprs_and_aliasing(self): | ||
| 639 | for op in self.OPS: | ||
| 640 | # Inline float constants, VOP3 constant modifiers, and 32-bit literal. | ||
| 641 | self.assertEqual(run_op(f"{op}_e32 v0, 0.5", 0), f32_bits(2.0)) | ||
| 642 | self.assertEqual(run_op(f"{op}_e32 v0, -0.5", 0), f32_bits(-2.0)) | ||
| 643 | self.assertEqual(run_op(f"{op}_e32 v0, 4.0", 0), f32_bits(0.25)) | ||
| 644 | self.assertEqual(run_op(f"{op}_e64 v0, -|2.0|", 0), f32_bits(-0.5)) | ||
| 645 | self.assertEqual(run_op(f"{op}_e64 v0, neg(0x3f800000)", 0), f32_bits(-1.0)) | ||
| 646 | self.assertEqual(run_op(f"{op}_e32 v0, 0x40400000", 0), 0x3EAAAAAB) | ||
| 647 | |||
| 648 | # SGPR source and modified SGPR source. | ||
| 649 | self.assertEqual(run_op(f"{op}_e32 v0, s4", 0, s4=f32_bits(-4.0)), f32_bits(-0.25)) | ||
| 650 | self.assertEqual(run_op(f"{op}_e64 v0, |s4| mul:2", 0, s4=f32_bits(-4.0)), f32_bits(0.5)) | ||
| 651 | |||
| 652 | # In-place aliasing: dst == src. | ||
| 653 | self.assertEqual(run_ps_v0(["v_mov_b32 v0, 0x40000000", f"{op}_e32 v0, v0"]), f32_bits(0.5)) | ||
| 654 | self.assertEqual(run_ps_v0(["v_mov_b32 v0, 0xc0800000", f"{op}_e64 v0, -v0 mul:4"]), f32_bits(1.0)) | ||
| 655 | |||
| 656 | |||
| 657 | # ----------------------------------------------------------------------------- | ||
| 658 | # 4. End-to-End v_rcp_f16 Value Tests | ||
| 659 | # ----------------------------------------------------------------------------- | ||
| 660 | |||
| 661 | class RcpF16ExecutionTests(unittest.TestCase): | ||
| 662 | def test_hand_worked_values_across_e32_e64_and_bare(self): | ||
| 663 | for suffix in ("_e32", "_e64", ""): | ||
| 664 | for name, h_bits, want_half in RCP_F16_HAND_WORKED: | ||
| 665 | with self.subTest(suffix=suffix, case=name): | ||
| 666 | got = run_op(f"v_rcp_f16{suffix} v0, v1", 0xCAFE0000 | h_bits) | ||
| 667 | self.assertEqual(got, merge_half(OLD, want_half, 0)) | ||
| 668 | |||
| 669 | def test_nan_preserves_nan_and_other_half(self): | ||
| 670 | for suffix in ("_e32", "_e64"): | ||
| 671 | for h in (H_QNAN, H_NEG_QNAN, H_SNAN): | ||
| 672 | with self.subTest(suffix=suffix, h=hex(h)): | ||
| 673 | got = run_op(f"v_rcp_f16{suffix} v0, v1", 0xCAFE0000 | h) | ||
| 674 | self.assertEqual(got & 0xFFFF0000, OLD & 0xFFFF0000) | ||
| 675 | self.assertTrue(is_f16_nan(got & 0xFFFF), f"expected NaN in low half, got {got:#010x}") | ||
| 676 | |||
| 677 | def test_zero_inputs_raise_unsupported_construct(self): | ||
| 678 | for line, v1 in ( | ||
| 679 | ("v_rcp_f16_e32 v0, v1", (H_1P0 << 16) | H_POS_ZERO), | ||
| 680 | ("v_rcp_f16_e32 v0, v1", (H_1P0 << 16) | H_NEG_ZERO), | ||
| 681 | ("v_rcp_f16_e64 v0, v1 op_sel:[1,0]", (H_POS_ZERO << 16) | H_1P0), | ||
| 682 | ("v_rcp_f16_e64 v0, v1 op_sel:[1,1]", (H_NEG_ZERO << 16) | H_1P0), | ||
| 683 | ): | ||
| 684 | with self.subTest(line=line, v1=hex(v1)): | ||
| 685 | with self.assertRaises(si.UnsupportedConstruct): | ||
| 686 | run_op(line, v1) | ||
| 687 | |||
| 688 | def test_op_sel_all_combinations(self): | ||
| 689 | # v1 = (hi: -4.0, lo: 0.5) -> rcp(hi) = -0.25, rcp(lo) = 2.0. | ||
| 690 | v1 = (H_NEG_4P0 << 16) | H_0P5 | ||
| 691 | for src_hi, dst_hi in itertools.product((0, 1), repeat=2): | ||
| 692 | h_in = H_NEG_4P0 if src_hi else H_0P5 | ||
| 693 | line = f"v_rcp_f16_e64 v0, v1 op_sel:[{src_hi},{dst_hi}]" | ||
| 694 | with self.subTest(line=line): | ||
| 695 | self.assertEqual(run_op(line, v1), merge_half(OLD, ref_rcp_f16(h_in), dst_hi)) | ||
| 696 | |||
| 697 | def test_vop3_source_and_output_modifiers(self): | ||
| 698 | v1 = (H_NEG_0P5 << 16) | H_4P0 | ||
| 699 | self.assertEqual(run_op("v_rcp_f16_e64 v0, -v1 op_sel:[0,0]", v1), merge_half(OLD, H_NEG_0P25, 0)) | ||
| 700 | self.assertEqual(run_op("v_rcp_f16_e64 v0, |v1| op_sel:[1,1]", v1), merge_half(OLD, H_2P0, 1)) | ||
| 701 | self.assertEqual(run_op("v_rcp_f16_e64 v0, -|v1| op_sel:[1,0]", v1), merge_half(OLD, H_NEG_2P0, 0)) | ||
| 702 | |||
| 703 | # Output modifiers scale first, then clamp to [0.0, 1.0], then pack to f16 keeping the other half. | ||
| 704 | self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 mul:2", v1), merge_half(OLD, H_0P5, 0)) | ||
| 705 | self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 mul:4", v1), merge_half(OLD, H_1P0, 0)) | ||
| 706 | self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 div:2", v1), merge_half(OLD, 0x3000, 0)) # 0.125 | ||
| 707 | self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 op_sel:[1,1] mul:2", v1), merge_half(OLD, H_NEG_4P0, 1)) | ||
| 708 | self.assertEqual(run_op("v_rcp_f16_e64 v0, v1 op_sel:[1,1] clamp", v1), merge_half(OLD, H_POS_ZERO, 1)) | ||
| 709 | self.assertEqual(run_op("v_rcp_f16_e64 v0, |v1| op_sel:[1,0] mul:2 clamp", v1), merge_half(OLD, H_1P0, 0)) | ||
| 710 | self.assertEqual(run_op("v_rcp_f16_e64 v0, |v1| op_sel:[1,1] clamp div:2", v1), merge_half(OLD, H_1P0, 1)) | ||
| 711 | |||
| 712 | def test_inline_constants_sgpr_and_aliasing(self): | ||
| 713 | self.assertEqual(run_op("v_rcp_f16_e32 v0, 0.5", 0), merge_half(OLD, H_2P0, 0)) | ||
| 714 | self.assertEqual(run_op("v_rcp_f16_e32 v0, -0.5", 0), merge_half(OLD, H_NEG_2P0, 0)) | ||
| 715 | self.assertEqual(run_op("v_rcp_f16_e64 v0, -1.0", 0), merge_half(OLD, H_NEG_1P0, 0)) | ||
| 716 | self.assertEqual(run_op("v_rcp_f16_e64 v0, -|0x4000|", 0), merge_half(OLD, H_NEG_0P5, 0)) | ||
| 717 | |||
| 718 | s4 = (H_NEG_4P0 << 16) | H_0P5 | ||
| 719 | self.assertEqual(run_op("v_rcp_f16_e32 v0, s4", 0, s4=s4), merge_half(OLD, H_2P0, 0)) | ||
| 720 | self.assertEqual(run_op("v_rcp_f16_e64 v0, s4 op_sel:[1,1]", 0, s4=s4), merge_half(OLD, H_NEG_0P25, 1)) | ||
| 721 | |||
| 722 | # In-place aliasing: dst == src reading one half and writing the other keeps the original unread half. | ||
| 723 | v0_init = (H_0P5 << 16) | H_4P0 | ||
| 724 | self.assertEqual( | ||
| 725 | run_ps_v0([f"v_mov_b32 v0, {v0_init:#x}", "v_rcp_f16_e64 v0, v0 op_sel:[1,0]"]), | ||
| 726 | (H_0P5 << 16) | H_2P0, | ||
| 727 | ) | ||
| 728 | self.assertEqual( | ||
| 729 | run_ps_v0([f"v_mov_b32 v0, {v0_init:#x}", "v_rcp_f16_e32 v0, v0"]), | ||
| 730 | (H_0P5 << 16) | H_0P25, | ||
| 731 | ) | ||
| 732 | |||
| 733 | |||
| 734 | # ----------------------------------------------------------------------------- | ||
| 735 | # 5. EXEC Masking & Negative Control Tests | ||
| 736 | # ----------------------------------------------------------------------------- | ||
| 737 | |||
| 738 | class RcpExecMaskingTests(unittest.TestCase): | ||
| 739 | def test_single_lane_exec_masking(self): | ||
| 740 | for line in ( | ||
| 741 | "v_rcp_f32_e32 v0, v1", | ||
| 742 | "v_rcp_iflag_f32_e32 v0, v1", | ||
| 743 | "v_rcp_f16_e32 v0, v1", | ||
| 744 | "v_rcp_f16_e64 v0, v1 op_sel:[1,1]", | ||
| 745 | ): | ||
| 746 | with self.subTest(line=line): | ||
| 747 | got = run_ps_v0([ | ||
| 748 | f"v_mov_b32 v1, {(H_2P0 << 16) | H_4P0:#x}", | ||
| 749 | f"v_mov_b32 v0, {OLD:#x}", | ||
| 750 | "s_mov_b32 exec_lo, 0", | ||
| 751 | line, | ||
| 752 | "s_mov_b32 exec_lo, 1", | ||
| 753 | ]) | ||
| 754 | self.assertEqual(got, OLD) | ||
| 755 | |||
| 756 | # Disabled ops leave v0 unchanged; re-enabling EXEC executes the subsequent op. | ||
| 757 | got_toggled = run_ps_v0([ | ||
| 758 | f"v_mov_b32 v1, {(H_0P5 << 16) | H_4P0:#x}", | ||
| 759 | f"v_mov_b32 v0, {OLD:#x}", | ||
| 760 | "s_mov_b32 exec_lo, 0", | ||
| 761 | "v_rcp_f16_e64 v0, v1 op_sel:[0,0]", | ||
| 762 | "v_rcp_f16_e64 v0, v1 op_sel:[1,1]", | ||
| 763 | "s_mov_b32 exec_lo, 1", | ||
| 764 | "v_rcp_f16_e64 v0, v1 op_sel:[1,0]", | ||
| 765 | ]) | ||
| 766 | self.assertEqual(got_toggled, merge_half(OLD, H_2P0, 0)) | ||
| 767 | |||
| 768 | def test_multilane_compute_exec_masking(self): | ||
| 769 | # 4 lanes in wave32: disable odd lanes (lane & 1 != 0) before executing v_rcp_*. | ||
| 770 | # Active even lanes (0, 2) compute the reciprocal; inactive odd lanes (1, 3) keep OLD. | ||
| 771 | cases = ( | ||
| 772 | ("v_rcp_f32_e32 v3, v2", f32_bits(4.0), f32_bits(0.25)), | ||
| 773 | ("v_rcp_iflag_f32_e64 v3, v2 mul:2", f32_bits(4.0), f32_bits(0.5)), | ||
| 774 | ("v_rcp_f16_e64 v3, v2 op_sel:[1,1]", (H_0P5 << 16) | H_4P0, merge_half(OLD, H_2P0, 1)), | ||
| 775 | ) | ||
| 776 | for insn, src_word, active_want in cases: | ||
| 777 | with self.subTest(insn=insn): | ||
| 778 | mem = {} | ||
| 779 | lines = [ | ||
| 780 | "v_lshlrev_b32 v4, 2, v0", # lane byte offset = lane * 4 | ||
| 781 | f"v_mov_b32 v2, {src_word:#x}", | ||
| 782 | f"v_mov_b32 v3, {OLD:#x}", | ||
| 783 | "v_and_b32 v5, v0, 1", | ||
| 784 | "v_cmpx_eq_u32 v5, 0", # keep even lanes active | ||
| 785 | insn, | ||
| 786 | "s_mov_b32 exec_lo, -1", | ||
| 787 | "buffer_store_dword v3, v4, s[0:3], 0 offen", | ||
| 788 | ] | ||
| 789 | run_cs(lines, group_size=4, subgroup_size=32, memory=mem) | ||
| 790 | self.assertEqual( | ||
| 791 | [mem[4 * i] for i in range(4)], | ||
| 792 | [active_want, OLD, active_want, OLD], | ||
| 793 | ) | ||
| 794 | |||
| 795 | |||
| 796 | class NegativeControlTests(unittest.TestCase): | ||
| 797 | def test_sabotaged_spirv_is_detected(self): | ||
| 798 | cases = ( | ||
| 799 | ("v_rcp_f32_e32 v0, v1", f32_bits(4.0), f32_bits(0.25)), | ||
| 800 | ("v_rcp_iflag_f32_e64 v0, v1 mul:2", f32_bits(4.0), f32_bits(0.5)), | ||
| 801 | ("v_rcp_f16_e64 v0, v1 op_sel:[0,1]", (H_1P0 << 16) | H_4P0, merge_half(OLD, H_0P25, 1)), | ||
| 802 | ) | ||
| 803 | for line, v1_bits, want in cases: | ||
| 804 | with self.subTest(line=line): | ||
| 805 | spv = translate_ps([f"v_mov_b32 v0, {OLD:#x}", f"v_mov_b32 v1, {v1_bits:#x}", line]) | ||
| 806 | self.assertEqual(si.run_fragment(spv)["%out_mrt0"][0], want) | ||
| 807 | bad, n = re.subn(r"OpFDiv %float %f1\b", "OpFMul %float %f1", spv, count=1) | ||
| 808 | self.assertEqual(n, 1) | ||
| 809 | self.assertNotEqual(si.run_fragment(bad)["%out_mrt0"][0], want) | ||
| 810 | |||
| 811 | # Sabotaging FClamp on v_rcp_iflag_f32_e64 clamp changes clamped 1/0.5 = 2.0 -> 1.0. | ||
| 812 | spv_clamp = translate_ps([ | ||
| 813 | f"v_mov_b32 v0, {OLD:#x}", | ||
| 814 | f"v_mov_b32 v1, {f32_bits(0.5):#x}", | ||
| 815 | "v_rcp_iflag_f32_e64 v0, v1 clamp", | ||
| 816 | ]) | ||
| 817 | self.assertEqual(si.run_fragment(spv_clamp)["%out_mrt0"][0], f32_bits(1.0)) | ||
| 818 | bad_clamp, n = re.subn(r"OpExtInst %float %glsl FClamp (%\w+) %f0 %f1", r"OpCopyObject %float \1", spv_clamp) | ||
| 819 | self.assertEqual(n, 1) | ||
| 820 | self.assertEqual(si.run_fragment(bad_clamp)["%out_mrt0"][0], f32_bits(2.0)) | ||
| 821 | |||
| 822 | |||
| 823 | if __name__ == "__main__": | ||
| 824 | unittest.main() | ||
diff --git a/tests/semantic/test_value_semantics.py b/tests/semantic/test_value_semantics.py index e90163cdd..32cf911db 100644 --- a/tests/semantic/test_value_semantics.py +++ b/tests/semantic/test_value_semantics.py | |||
| @@ -493,6 +493,30 @@ class TranslatorValueSemantics(unittest.TestCase): | |||
| 493 | with self.subTest(address=address): | 493 | with self.subTest(address=address): |
| 494 | self.assertEqual(f"{memory.get(address, 0):#010x}", f"{want:#010x}") | 494 | self.assertEqual(f"{memory.get(address, 0):#010x}", f"{want:#010x}") |
| 495 | 495 | ||
| 496 | def test_signed_typed_buffers(self): | ||
| 497 | spv = support.translate_fixture("cs_fmt_sint32", fssm=CS_BOUNDS_FSSM) | ||
| 498 | memory = {} | ||
| 499 | support.run_fragment( | ||
| 500 | spv, inputs={"%wg_id": (0, 0, 0), "%local_id": (0, 0, 0)}, | ||
| 501 | push_constants=[0, 0, 0x100, 0x31016FAC] + [0] * 28, memory=memory) | ||
| 502 | expected = { | ||
| 503 | 0x0C: 1, # MUBUF integer DST_SEL=1 | ||
| 504 | 0x18: 0xFFFFFFFD, # MUBUF 96-bit format, third component | ||
| 505 | 0x34: 0x7FFFFFFF, 0x38: 0, # MTBUF 64-bit format with absent third component | ||
| 506 | 0x48: 0xFFFFFFFD, 0x4C: 0, # MTBUF 96-bit format with absent fourth component | ||
| 507 | 0x58: 0xFFFFFFFD, 0x5C: 17, # MTBUF 128-bit format | ||
| 508 | 0x60: 0x7FFF8000, 0x64: 0x0011FFFD, | ||
| 509 | 0x68: 0x7FFF8000, 0x6C: 0x0011FFFD, | ||
| 510 | 0x70: 0xFFFFFFFD, 0x74: 0xFFFFFFFD, | ||
| 511 | 0x90: 0x80000000, 0xA8: 0xFFFFFFFD, 0xBC: 17, | ||
| 512 | 0xC0: 0xFFFFFFFD, 0xC4: 0xFFFF8000, 0xC8: 0xFFFFFFFD, | ||
| 513 | } | ||
| 514 | for address, word in expected.items(): | ||
| 515 | with self.subTest(address=hex(address)): | ||
| 516 | self.assertEqual(memory.get(address), word) | ||
| 517 | for address in (0x98, 0xAC, 0xCC): | ||
| 518 | self.assertNotIn(address, memory) | ||
| 519 | |||
| 496 | def test_s_ff0_s_ff1_read_an_immediate_as_a_value(self): | 520 | def test_s_ff0_s_ff1_read_an_immediate_as_a_value(self): |
| 497 | # SHADER-46: an inline constant or literal is a 32-bit value. Read as a lane mask (all ones or zero from | 521 | # SHADER-46: an inline constant or literal is a 32-bit value. Read as a lane mask (all ones or zero from |
| 498 | # bit 0), s_ff0 of 61 and of 0x0000ffff gave -1; the s_ff1 words guard the path it already got right. | 522 | # bit 0), s_ff0 of 61 and of 0x0000ffff gave -1; the s_ff1 words guard the path it already got right. |
diff --git a/tests/semantic/test_vop3_const_mods.py b/tests/semantic/test_vop3_const_mods.py index 2d07d1fb7..052457f41 100644 --- a/tests/semantic/test_vop3_const_mods.py +++ b/tests/semantic/test_vop3_const_mods.py | |||
| @@ -178,11 +178,14 @@ class F16AndMixConstModifierTests(unittest.TestCase): | |||
| 178 | ]) | 178 | ]) |
| 179 | self.assertEqual(got[:3], [0x4000BC00, 0x00007C01, 0x7C01FC01]) | 179 | self.assertEqual(got[:3], [0x4000BC00, 0x00007C01, 0x7C01FC01]) |
| 180 | 180 | ||
| 181 | def test_v_pack_b32_f16_abs_is_still_rejected(self): | 181 | def test_v_pack_b32_f16_abs_clears_the_sign_of_the_packed_half(self): |
| 182 | # Only `neg` is measured on this instruction; `abs` would be a guessed sign clear, so it stays refused. | 182 | # `abs` is the ISA's sign clear (|S|), applied before `neg`; it has no hardware run of this instruction yet. |
| 183 | with self.assertRaises(rdna2spirv.Unsupported): | 183 | got = run([ |
| 184 | translate(["v_pack_b32_f16 v0, abs(0x3c00), 1.0"]) | 184 | "v_mov_b32 v1, 0xbc00", |
| 185 | 185 | "v_pack_b32_f16 v0, abs(0xbc00), 0x4000", # +1.0h in the low half, 2.0h in the high one | |
| 186 | "v_pack_b32_f16 v2, -abs(v1), v1", # clear then flip the low half; src1 stays -1.0h | ||
| 187 | ]) | ||
| 188 | self.assertEqual(got[:3], [0x40003C00, 0x0000BC00, 0xBC00BC00]) | ||
| 186 | 189 | ||
| 187 | class F64ConstModifierStructureTests(unittest.TestCase): | 190 | class F64ConstModifierStructureTests(unittest.TestCase): |
| 188 | def test_f64_emits_fabs_then_fnegate_for_neg_abs_const(self): | 191 | def test_f64_emits_fabs_then_fnegate_for_neg_abs_const(self): |
diff --git a/tests/semantic/test_w64x_scalar_load_order.py b/tests/semantic/test_w64x_scalar_load_order.py new file mode 100644 index 000000000..1621afaa7 --- /dev/null +++ b/tests/semantic/test_w64x_scalar_load_order.py | |||
| @@ -0,0 +1,133 @@ | |||
| 1 | """--wave64-emulate: a scalar load (s_load / s_buffer_load) is ordered with the wave's vector stores (#1587). | ||
| 2 | |||
| 3 | On hardware a wave issues its instructions in order, so every lane's `buffer_store` is done (`s_waitcnt vmcnt(0)`) | ||
| 4 | before the wave's `s_load` of the same address. Under `--wave64-emulate` the two halves of a wave can run in two | ||
| 5 | 32-wide subgroups, which order memory only at the barrier between rounds (docs/design.md, "Wave64 emulation"). Until | ||
| 6 | #1587 a scalar load was not one of the accesses `Gen.x_memory_order` cuts a round at, so a store and a later scalar | ||
| 7 | load of the same wave sat in one segment, and the other half could load before this half had stored: | ||
| 8 | `tools/valu_fuzz.py --family mem --emulate` found lanes 32-63 reading the buffer's fill pattern after an | ||
| 9 | `s_buffer_load` / `s_load` of the slot lane 0 had just written (the slot comes from `v_readfirstlane_b32`, which | ||
| 10 | the emulation already reads over the whole wave). | ||
| 11 | |||
| 12 | The interpreters here don't run workgroup barriers, so this checks the rule on the emitted rounds: the SPIR-V of every | ||
| 13 | segment (a case of the round loop's `OpSwitch %pcv`) may not access buffer memory (the PhysicalStorageBuffer pointers | ||
| 14 | both the vector and the scalar memory ops go through) in a conflicting order: no access after a write, no write after | ||
| 15 | a read. The programs are written here; no game data. | ||
| 16 | """ | ||
| 17 | import os | ||
| 18 | import re | ||
| 19 | import struct | ||
| 20 | import sys | ||
| 21 | import unittest | ||
| 22 | |||
| 23 | HERE = os.path.dirname(os.path.abspath(__file__)) | ||
| 24 | if HERE not in sys.path: | ||
| 25 | sys.path.insert(0, HERE) # python -I leaves the script's folder off sys.path | ||
| 26 | |||
| 27 | import support # noqa: E402 (support puts tools/ on sys.path, honouring LEONIDA_TOOLS_DIR) | ||
| 28 | |||
| 29 | rdna2spirv = support.rdna2spirv | ||
| 30 | |||
| 31 | # s[0:3] is the output V# (4 user SGPRs); s[8:9] a 64-bit pointer to the same memory, s[12:15] a V# of it for | ||
| 32 | # s_buffer_load. Every access is one dword, so one instruction is one OpLoad or OpStore. | ||
| 33 | HEAD = ["s_mov_b64 exec, -1", "s_mov_b32 s8, 0", "s_mov_b32 s9, 0", | ||
| 34 | "s_mov_b32 s12, 0", "s_mov_b32 s13, 0", "s_mov_b32 s14, 0x1000", "s_mov_b32 s15, 0x31016FAC", | ||
| 35 | "v_lshlrev_b32_e32 v1, 2, v0", # v1 = the lane's byte offset | ||
| 36 | # as in the fuzz program, before any memory op: s16 = the byte offset of the wave's first lane | ||
| 37 | "v_readfirstlane_b32 s16, v1"] | ||
| 38 | STORE = ["buffer_store_dword v0, v1, s[0:3], 0 offen", "s_waitcnt vmcnt(0)"] | ||
| 39 | SLOAD = ["s_load_dword s10, s[8:9], 0x0", "s_waitcnt lgkmcnt(0)", "v_mov_b32_e32 v2, s10"] | ||
| 40 | # The fuzz program's shape: the slot of the wave's first lane, from v_readfirstlane_b32, as the soffset. | ||
| 41 | SBUF = ["s_buffer_load_dword s10, s[12:15], s16 offset:0x0", "s_waitcnt lgkmcnt(0)", | ||
| 42 | "v_mov_b32_e32 v2, s10"] | ||
| 43 | TAIL = ["buffer_store_dword v2, v1, s[0:3], 0 offen offset:256", "s_endpgm"] | ||
| 44 | |||
| 45 | |||
| 46 | def fssm(threads=64): | ||
| 47 | """Compute header: COMPUTE_PGM_RSRC2 0x8088 (4 user SGPRs, TGID_X), one wave of `threads`.""" | ||
| 48 | return bytes(0x138) + struct.pack("<4I", 0x8088, threads, 1, 1) | ||
| 49 | |||
| 50 | |||
| 51 | def translate(lines, emulate=True): | ||
| 52 | prev = rdna2spirv.WAVE64_EMULATE | ||
| 53 | rdna2spirv.WAVE64_EMULATE = emulate | ||
| 54 | try: | ||
| 55 | spv = support.translate_lines("cs_w64x_sload_order", lines, fssm=fssm()) | ||
| 56 | finally: | ||
| 57 | rdna2spirv.WAVE64_EMULATE = prev | ||
| 58 | assert rdna2spirv.translate.last_gen.wave64, "the test program must translate as wave64" | ||
| 59 | return spv | ||
| 60 | |||
| 61 | |||
| 62 | def segments(spv): | ||
| 63 | """{segment label: ["r"/"w", ...]}: the buffer accesses of each case of the round loop's switch, in order.""" | ||
| 64 | lines = spv.splitlines() | ||
| 65 | sw = next((ln.split() for ln in lines if ln.split()[:2] == ["OpSwitch", "%pcv"]), None) | ||
| 66 | assert sw is not None, "no round-loop switch: not an emulated translation" | ||
| 67 | labels = set(sw[4::2]) | ||
| 68 | psb = set() | ||
| 69 | out, cur = {}, None | ||
| 70 | for ln in lines: | ||
| 71 | t = ln.split() | ||
| 72 | if len(t) >= 3 and t[1] == "=" and t[2] == "OpLabel": | ||
| 73 | if t[0] in labels: | ||
| 74 | cur = out.setdefault(t[0], []) | ||
| 75 | elif t[0] == sw[3]: # the default label ends the cases | ||
| 76 | cur = None | ||
| 77 | continue | ||
| 78 | if cur is None: | ||
| 79 | continue | ||
| 80 | if len(t) >= 4 and t[2] == "OpAccessChain" and t[3] == "%_ptr_PSB_uint": | ||
| 81 | psb.add(t[0]) | ||
| 82 | elif len(t) >= 5 and t[2] == "OpLoad" and t[4] in psb: | ||
| 83 | cur.append("r") | ||
| 84 | elif len(t) >= 2 and t[0] == "OpStore" and t[1] in psb: | ||
| 85 | cur.append("w") | ||
| 86 | return out | ||
| 87 | |||
| 88 | |||
| 89 | def conflicts(segs): | ||
| 90 | """The segments where an access follows a write, or a write follows a read (x_memory_order's rule).""" | ||
| 91 | bad = [] | ||
| 92 | for lab, acc in segs.items(): | ||
| 93 | s = "".join(acc) | ||
| 94 | if re.search(r"w.", s) or re.search(r"r.*w", s): | ||
| 95 | bad.append((lab, s)) | ||
| 96 | return bad | ||
| 97 | |||
| 98 | |||
| 99 | class ScalarLoadOrderTests(unittest.TestCase): | ||
| 100 | def check_ordered(self, lines, accesses): | ||
| 101 | segs = segments(translate(lines)) | ||
| 102 | self.assertEqual(sum(len(a) for a in segs.values()), accesses, segs) # every access was found | ||
| 103 | self.assertEqual(conflicts(segs), [], segs) | ||
| 104 | return segs | ||
| 105 | |||
| 106 | def test_store_then_s_load(self): | ||
| 107 | # read after write: the store's round ends before the load | ||
| 108 | self.check_ordered(HEAD + STORE + SLOAD + TAIL, 3) | ||
| 109 | |||
| 110 | def test_store_then_s_buffer_load_at_the_first_lane_slot(self): | ||
| 111 | # the #1587 program shape: buffer_store, then v_readfirstlane_b32 + s_buffer_load | ||
| 112 | self.check_ordered(HEAD + STORE + SBUF + TAIL, 3) | ||
| 113 | |||
| 114 | def test_s_load_then_store(self): | ||
| 115 | # write after read: the other half's store may not land before this half's scalar load | ||
| 116 | self.check_ordered(HEAD + SLOAD + STORE + ["s_endpgm"], 2) | ||
| 117 | |||
| 118 | def test_reads_share_a_round(self): | ||
| 119 | # loads alone never conflict: two scalar loads and a vector load stay in one segment | ||
| 120 | lines = HEAD + SLOAD + ["s_load_dword s11, s[8:9], 0x4", "s_waitcnt lgkmcnt(0)", | ||
| 121 | "buffer_load_dword v3, v1, s[0:3], 0 offen", "s_waitcnt vmcnt(0)", "s_endpgm"] | ||
| 122 | segs = self.check_ordered(lines, 3) | ||
| 123 | self.assertIn(["r", "r", "r"], segs.values(), segs) | ||
| 124 | |||
| 125 | def test_native_wave64_is_unchanged(self): | ||
| 126 | # without the flag there are no rounds: the store and the load are one straight run | ||
| 127 | spv = translate(HEAD + STORE + SLOAD + TAIL, emulate=False) | ||
| 128 | self.assertNotIn("%pcv", spv) | ||
| 129 | self.assertNotIn("OpControlBarrier", spv) | ||
| 130 | |||
| 131 | |||
| 132 | if __name__ == "__main__": | ||
| 133 | unittest.main() | ||
diff --git a/tests/test_anim_rigs.py b/tests/test_anim_rigs.py new file mode 100644 index 000000000..7ae94fb61 --- /dev/null +++ b/tests/test_anim_rigs.py | |||
| @@ -0,0 +1,134 @@ | |||
| 1 | """Synthetic tests for tools/anim_rigs.py. | ||
| 2 | |||
| 3 | python -I tests/test_anim_rigs.py | ||
| 4 | |||
| 5 | Every byte here is built by the test: a fake RPF9 data area with two rig dictionaries and one clip dictionary | ||
| 6 | (the builders of tests/test_anim_clips.py), and a small rig-set JSON in the shape `anim_index.py --rigs` writes. | ||
| 7 | No game file or game asset name is used. | ||
| 8 | """ | ||
| 9 | import json | ||
| 10 | import os | ||
| 11 | import struct | ||
| 12 | import subprocess | ||
| 13 | import sys | ||
| 14 | import tempfile | ||
| 15 | import unittest | ||
| 16 | |||
| 17 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 18 | TOOL = os.path.join(ROOT, "tools", "anim_rigs.py") | ||
| 19 | sys.path.insert(0, os.path.join(ROOT, "tools")) | ||
| 20 | sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | ||
| 21 | |||
| 22 | import anim_rigs # noqa: E402 | ||
| 23 | from anim_index import joaat32 # noqa: E402 | ||
| 24 | from test_anim_clips import Page, two_sequence_dictionary, write_rpf # noqa: E402 | ||
| 25 | |||
| 26 | KIND_A, KIND_B = joaat32("kind_a"), joaat32("kind_b") | ||
| 27 | |||
| 28 | |||
| 29 | def rig_block(page, tables, version=2): | ||
| 30 | """`RIG` + version, u32 length, 8 filler bytes, then each table {kind, 0xC + 8n, n, word} + n items.""" | ||
| 31 | body = bytearray(b"\x11" * 8) | ||
| 32 | for kind, items in tables: | ||
| 33 | body += struct.pack("<4I", kind, 0xC + 8 * len(items), len(items), 0x0300) | ||
| 34 | body += b"".join(struct.pack("<II", h, 0x0300 + i) for i, h in enumerate(items)) | ||
| 35 | return page.alloc(MAGIC_V(version) + struct.pack("<I", len(body)) + bytes(body)) | ||
| 36 | |||
| 37 | |||
| 38 | def MAGIC_V(version): | ||
| 39 | return b"RIG" + bytes([version]) | ||
| 40 | |||
| 41 | |||
| 42 | def rig_dictionary(name, rigs): | ||
| 43 | """rigs: {rig path: [(kind, [item hashes])]}. The root's own +0x70 holds `RIG` + version like the real ones.""" | ||
| 44 | p = Page() | ||
| 45 | pm = p.alloc(bytes(16)) | ||
| 46 | p.b[pm + 8], p.b[pm + 9] = 1, 0 | ||
| 47 | p.ptr(8, pm) | ||
| 48 | p.string(0x38, name) | ||
| 49 | struct.pack_into("<I", p.b, 0x68, joaat32(name)) | ||
| 50 | p.b[0x70:0x74] = MAGIC_V(2) | ||
| 51 | items = [] | ||
| 52 | for path, tables in rigs.items(): | ||
| 53 | value = p.alloc(bytes(0x90)) | ||
| 54 | p.ptr(value + 0x20, rig_block(p, tables)) | ||
| 55 | items.append((joaat32(path), value)) | ||
| 56 | p.atmap(0x48, items) | ||
| 57 | return bytes(p.b) | ||
| 58 | |||
| 59 | |||
| 60 | RIGS = { | ||
| 61 | "src@one": {"anim/rig/x/a": [(KIND_A, [1, 2, 3])], "anim/rig/x/b": [(KIND_A, [4]), (KIND_B, [5, 6])]}, | ||
| 62 | "src@two": {"anim/rig/y/c": [(KIND_B, [7, 8])], "anim/rig/y/unused": [(KIND_A, [9])]}, | ||
| 63 | } | ||
| 64 | RIGSETS = {"rbf0": {"rigsets": [ | ||
| 65 | {"key": "anim/rigset/ped/p", "entries": [ | ||
| 66 | {"source": "src@one", "rig": "anim/rig/x/a", "group": "pose"}, | ||
| 67 | {"source": "src@one", "rig": "anim/rig/x/b", "group": "deformation"}, | ||
| 68 | {"source": "src@two", "rig": "anim/rig/y/c", "group": "facial"}]}, | ||
| 69 | {"key": "anim/rigset/object/o", "entries": [ | ||
| 70 | {"source": "src@two", "rig": "anim/rig/x/a", "group": "pose"}, # rig is in the other dictionary | ||
| 71 | {"source": "src@none", "rig": "anim/rig/z/q", "group": "pose"}, # no dictionary has this name | ||
| 72 | {"source": "src@one", "rig": "anim/rig/x/missing", "group": "pose"}]}, | ||
| 73 | ]}} | ||
| 74 | |||
| 75 | |||
| 76 | class RigDictionaryTest(unittest.TestCase): | ||
| 77 | def setUp(self): | ||
| 78 | self.tmp = tempfile.TemporaryDirectory() | ||
| 79 | self.rpf = os.path.join(self.tmp.name, "synthetic.rpf") | ||
| 80 | self.rigs = os.path.join(self.tmp.name, "rigs.json") | ||
| 81 | with open(self.rigs, "w", encoding="utf-8") as f: | ||
| 82 | json.dump(RIGSETS, f) | ||
| 83 | streams = [rig_dictionary(name, rigs) for name, rigs in RIGS.items()] + [two_sequence_dictionary()] | ||
| 84 | self.offsets = write_rpf(self.rpf, streams) | ||
| 85 | |||
| 86 | def tearDown(self): | ||
| 87 | self.tmp.cleanup() | ||
| 88 | |||
| 89 | def test_scan_reads_only_rig_dictionaries(self): | ||
| 90 | dicts, summary = anim_rigs.scan(self.rpf) | ||
| 91 | self.assertEqual([d["name"] for d in dicts], ["src@one", "src@two"]) | ||
| 92 | self.assertEqual([d["offset"] for d in dicts], self.offsets[:2]) | ||
| 93 | c = summary["counts"] | ||
| 94 | self.assertEqual((c["rig_dictionaries"], c["rig_dictionary_hash_matches_name"], c["entries"], | ||
| 95 | c["entries_with_block"], c["entries_key_high_zero"], c["block_version:2"]), (2, 2, 4, 4, 4, 4)) | ||
| 96 | self.assertEqual((c["tables"], c[f"table_kind:0x{KIND_A:08x}"], c[f"table_kind:0x{KIND_B:08x}"]), (5, 3, 2)) | ||
| 97 | self.assertEqual((c[f"table_items:0x{KIND_A:08x}"], c[f"table_items:0x{KIND_B:08x}"]), (5, 4)) | ||
| 98 | |||
| 99 | def test_entry_keys_and_tables(self): | ||
| 100 | dicts, _ = anim_rigs.scan(self.rpf) | ||
| 101 | one = {e["key"]: e["tables"] for e in dicts[0]["entries"]} | ||
| 102 | self.assertEqual(one, {joaat32("anim/rig/x/a"): [(KIND_A, 3)], | ||
| 103 | joaat32("anim/rig/x/b"): [(KIND_A, 1), (KIND_B, 2)]}) | ||
| 104 | |||
| 105 | def test_join_rbf0(self): | ||
| 106 | dicts, _ = anim_rigs.scan(self.rpf) | ||
| 107 | self.assertEqual(anim_rigs.join_rbf0(dicts, RIGSETS), { | ||
| 108 | "distinct_rigs": 6, "in_another_dictionary": 1, "key_missing": 1, "keys": 4, | ||
| 109 | "keys_named_by_an_entry": 3, "no_dictionary_named_source": 1, "resolved": 3}) | ||
| 110 | |||
| 111 | def test_bad_block_is_reported_not_raised(self): | ||
| 112 | page = bytearray(rig_dictionary("src@bad", {"anim/rig/b": [(KIND_A, [1])]})) | ||
| 113 | at = page.rfind(b"RIG\x02") | ||
| 114 | page[at:at + 3] = b"XYZ" | ||
| 115 | rpf = os.path.join(self.tmp.name, "bad.rpf") | ||
| 116 | write_rpf(rpf, [bytes(page)]) | ||
| 117 | dicts, summary = anim_rigs.scan(rpf) | ||
| 118 | self.assertEqual(summary["counts"]["rig_dictionaries_unparsed"], 1) | ||
| 119 | self.assertIn("no RIG block", dicts[0]["error"]) | ||
| 120 | |||
| 121 | def test_cli_writes_counts_only(self): | ||
| 122 | out = os.path.join(self.tmp.name, "out.json") | ||
| 123 | r = subprocess.run([sys.executable, "-I", TOOL, self.rpf, out, "--rigs", self.rigs], | ||
| 124 | capture_output=True, text=True) | ||
| 125 | self.assertEqual(r.returncode, 0, r.stderr) | ||
| 126 | with open(out, encoding="utf-8") as f: | ||
| 127 | doc = json.load(f) | ||
| 128 | self.assertEqual(doc["summary"]["rbf0_join"]["resolved"], 3) | ||
| 129 | self.assertEqual([row["entries"] for row in doc["rig_dictionaries"]], [2, 2]) | ||
| 130 | self.assertNotIn("tables", json.dumps(doc["rig_dictionaries"])) | ||
| 131 | |||
| 132 | |||
| 133 | if __name__ == "__main__": | ||
| 134 | unittest.main() | ||
diff --git a/tests/test_awc_opus.py b/tests/test_awc_opus.py index 76b26ff0c..aebdd0fd8 100644 --- a/tests/test_awc_opus.py +++ b/tests/test_awc_opus.py | |||
| @@ -393,8 +393,9 @@ class ExportBankTest(unittest.TestCase): | |||
| 393 | self.assertEqual(last["serial"], 3) | 393 | self.assertEqual(last["serial"], 3) |
| 394 | 394 | ||
| 395 | def test_stereo_plain_stream_length_is_per_channel(self): | 395 | def test_stereo_plain_stream_length_is_per_channel(self): |
| 396 | # A stereo format tag stores interleaved samples. Three 960-frame stereo packets carry | 396 | # A stereo format tag stores interleaved samples: 3840 counts = 1920 frames per channel. |
| 397 | # 2880 frames per channel; the declared 3840 is twice the real per-channel length. | 397 | # Three 960-frame packets carry 2880 frames per channel, so the declared 1920 trims |
| 398 | # 960 frames of payload; the point is the halving, not a realistic stream length. | ||
| 398 | packet = bytes([0x9C]) # CELT 20 ms, code 0, stereo bit: 960 frames per channel | 399 | packet = bytes([0x9C]) # CELT 20 ms, code 0, stereo bit: 960 frames per channel |
| 399 | opus = bytearray(3 * 2048) | 400 | opus = bytearray(3 * 2048) |
| 400 | for block in range(3): | 401 | for block in range(3): |
| @@ -414,8 +415,8 @@ class ExportBankTest(unittest.TestCase): | |||
| 414 | 415 | ||
| 415 | def test_declared_samples_are_48khz_frames_not_scaled_by_rate(self): | 416 | def test_declared_samples_are_48khz_frames_not_scaled_by_rate(self): |
| 416 | # Four 960-frame packets are 3840 frames; the tag declares 2880 real frames and a 32 kHz | 417 | # Four 960-frame packets are 3840 frames; the tag declares 2880 real frames and a 32 kHz |
| 417 | # source rate. Scaling by 48000/32000 would make the length 4320, so the last granule | 418 | # source rate. Scaling by 48000/32000 would make the target 4320, above the payload, so |
| 418 | # would stay at 312 + 3840 and the padding would not be trimmed. | 419 | # the old code kept all 3840 packet frames (granule 3840, 3528 after the pre-skip). |
| 419 | packet = bytes([0x08]) # SILK 20 ms, code 0: 960 frames | 420 | packet = bytes([0x08]) # SILK 20 ms, code 0: 960 frames |
| 420 | opus = bytearray(4 * 2048) | 421 | opus = bytearray(4 * 2048) |
| 421 | for block in range(4): | 422 | for block in range(4): |
| @@ -431,12 +432,13 @@ class ExportBankTest(unittest.TestCase): | |||
| 431 | pages = parse_ogg_pages(f.read()) | 432 | pages = parse_ogg_pages(f.read()) |
| 432 | self.assertEqual(pages[-1]["granule"], 312 + 2880) | 433 | self.assertEqual(pages[-1]["granule"], 312 + 2880) |
| 433 | 434 | ||
| 434 | def test_format_block_per_channel_frame_count_is_used(self): | 435 | def test_inconsistent_format_frame_count_falls_back(self): |
| 435 | # +0x0C is the per-channel Opus frame count and wins over dividing the +0 count: | 436 | # +0x0C is authoritative only when it agrees with the interleaved +0 count: |
| 436 | # 9999 interleaved samples / 2 would be 4999 frames and would not trim the padding. | 437 | # 1920 * 2 != 9999, so the block is malformed and +0 / channels (4999) is used |
| 438 | # instead of silently truncating the real audio. | ||
| 437 | packet = bytes([0x9C]) # CELT 20 ms, code 0, stereo bit: 960 frames per channel | 439 | packet = bytes([0x9C]) # CELT 20 ms, code 0, stereo bit: 960 frames per channel |
| 438 | opus = bytearray(3 * 2048) | 440 | opus = bytearray(6 * 2048) |
| 439 | for block in range(3): | 441 | for block in range(6): |
| 440 | struct.pack_into("<H", opus, block * 2048, len(packet)) | 442 | struct.pack_into("<H", opus, block * 2048, len(packet)) |
| 441 | opus[block * 2048 + 2:block * 2048 + 2 + len(packet)] = packet | 443 | opus[block * 2048 + 2:block * 2048 + 2 + len(packet)] = packet |
| 442 | fmt = bytearray(format_block(9999, 48000, 0x0B, 2)) | 444 | fmt = bytearray(format_block(9999, 48000, 0x0B, 2)) |
| @@ -449,8 +451,69 @@ class ExportBankTest(unittest.TestCase): | |||
| 449 | awc.export_bank(path, self.out) | 451 | awc.export_bank(path, self.out) |
| 450 | with open(os.path.join(self.out, "frames", "0000000B.ogg"), "rb") as f: | 452 | with open(os.path.join(self.out, "frames", "0000000B.ogg"), "rb") as f: |
| 451 | pages = parse_ogg_pages(f.read()) | 453 | pages = parse_ogg_pages(f.read()) |
| 454 | self.assertEqual(pages[-1]["granule"], 312 + 4999) | ||
| 455 | |||
| 456 | def test_consistent_format_frame_count_is_used(self): | ||
| 457 | # 3840 interleaved stereo samples = 1920 per channel, and +0x0C agrees. | ||
| 458 | packet = bytes([0x9C]) # CELT 20 ms, code 0, stereo bit: 960 frames per channel | ||
| 459 | opus = bytearray(3 * 2048) | ||
| 460 | for block in range(3): | ||
| 461 | struct.pack_into("<H", opus, block * 2048, len(packet)) | ||
| 462 | opus[block * 2048 + 2:block * 2048 + 2 + len(packet)] = packet | ||
| 463 | fmt = bytearray(format_block(3840, 48000, 0x0B, 2)) | ||
| 464 | struct.pack_into("<I", fmt, 12, 1920) | ||
| 465 | bank = build_bank([(12, bytes(fmt), bytes(opus))]) | ||
| 466 | path = os.path.join(self.tmp.name, "frames_ok.awc") | ||
| 467 | with open(path, "wb") as f: | ||
| 468 | f.write(bank) | ||
| 469 | |||
| 470 | awc.export_bank(path, self.out) | ||
| 471 | with open(os.path.join(self.out, "frames_ok", "0000000C.ogg"), "rb") as f: | ||
| 472 | pages = parse_ogg_pages(f.read()) | ||
| 452 | self.assertEqual(pages[-1]["granule"], 312 + 1920) | 473 | self.assertEqual(pages[-1]["granule"], 312 + 1920) |
| 453 | 474 | ||
| 475 | def test_eos_page_is_emitted_at_the_trim_point(self): | ||
| 476 | # 27 packets of 160 bytes / 960 frames: the 26th packet crosses the target | ||
| 477 | # (312 + 24000 = 24312) and would otherwise flush a full page first. The EOS | ||
| 478 | # page must carry the reaching packet and drop the 27th padding packet, not | ||
| 479 | # emit a later page whose granule is smaller than the previous one. | ||
| 480 | packet = bytes([0x08]) + bytes(159) # SILK 20 ms, 960 frames | ||
| 481 | packets = [packet] * 27 | ||
| 482 | path = os.path.join(self.tmp.name, "trim.ogg") | ||
| 483 | awc.write_ogg_opus(path, packets, 1, 21, 24000) | ||
| 484 | with open(path, "rb") as f: | ||
| 485 | pages = parse_ogg_pages(f.read()) | ||
| 486 | audio = pages[2:] | ||
| 487 | granules = [p["granule"] for p in audio] | ||
| 488 | self.assertEqual(granules, sorted(granules)) | ||
| 489 | self.assertEqual(audio[-1]["granule"], 312 + 24000) | ||
| 490 | self.assertEqual(audio[-1]["flags"] & 0x04, 0x04) | ||
| 491 | self.assertEqual(sum(1 for p in audio for value in p["lacing"] if value < 255), 26) | ||
| 492 | |||
| 493 | def test_pre_skip_larger_than_the_stream_is_clamped(self): | ||
| 494 | # Six 960-frame packets are 5760 samples; a pre-skip of 65535 would put the | ||
| 495 | # EOS granule below the pre-skip and make the stream undecodable. | ||
| 496 | packet = bytes([0x08]) | ||
| 497 | packets = [packet] * 6 | ||
| 498 | path = os.path.join(self.tmp.name, "preskip.ogg") | ||
| 499 | awc.write_ogg_opus(path, packets, 1, 23, 4800, pre_skip=65535) | ||
| 500 | with open(path, "rb") as f: | ||
| 501 | pages = parse_ogg_pages(f.read()) | ||
| 502 | self.assertEqual(struct.unpack_from("<H", pages[0]["body"], 10)[0], 5760) | ||
| 503 | self.assertGreaterEqual(pages[-1]["granule"], 5760) | ||
| 504 | with self.assertRaises(ValueError): | ||
| 505 | awc.write_ogg_opus(path, packets, 1, 24, 4800, pre_skip=65536) | ||
| 506 | |||
| 507 | def test_empty_packet_list_writes_an_eos_page(self): | ||
| 508 | # No audio packets is still a valid empty stream: the EOS flag must be present. | ||
| 509 | path = os.path.join(self.tmp.name, "empty.ogg") | ||
| 510 | self.assertEqual(awc.write_ogg_opus(path, [], 1, 25, 0), 0) | ||
| 511 | with open(path, "rb") as f: | ||
| 512 | pages = parse_ogg_pages(f.read()) | ||
| 513 | self.assertEqual(len(pages), 3) | ||
| 514 | self.assertEqual(pages[-1]["flags"] & 0x04, 0x04) | ||
| 515 | self.assertEqual(pages[-1]["granule"], 0) | ||
| 516 | |||
| 454 | def test_cli_pre_skip_override(self): | 517 | def test_cli_pre_skip_override(self): |
| 455 | bank, _, _ = self.make_bank() | 518 | bank, _, _ = self.make_bank() |
| 456 | subprocess.run([sys.executable, "-I", awc.__file__, bank, self.out, "--jobs", "1", "--pre-skip", "0"], | 519 | subprocess.run([sys.executable, "-I", awc.__file__, bank, self.out, "--jobs", "1", "--pre-skip", "0"], |
diff --git a/tests/test_build_runtime_fallback.py b/tests/test_build_runtime_fallback.py index 93457d1c7..75d938fdc 100644 --- a/tests/test_build_runtime_fallback.py +++ b/tests/test_build_runtime_fallback.py | |||
| @@ -41,6 +41,11 @@ class FallbackBuildsTheHarnesses(unittest.TestCase): | |||
| 41 | with self.subTest(source=name): | 41 | with self.subTest(source=name): |
| 42 | self.assertTrue((ROOT / "runtime" / "test" / name).is_file()) | 42 | self.assertTrue((ROOT / "runtime" / "test" / name).is_file()) |
| 43 | 43 | ||
| 44 | def test_build_cmd_sets_utf8_codepage_for_ninja_showincludes(self): | ||
| 45 | text = SCRIPT.read_text(encoding="utf-8") | ||
| 46 | self.assertIn("chcp 65001 >nul", text) | ||
| 47 | self.assertLess(text.index("chcp 65001 >nul"), text.index('call `"$vcvars`"')) | ||
| 48 | |||
| 44 | 49 | ||
| 45 | if __name__ == "__main__": | 50 | if __name__ == "__main__": |
| 46 | unittest.main() | 51 | unittest.main() |
diff --git a/tests/test_calibrated_texture_extra.py b/tests/test_calibrated_texture_extra.py new file mode 100644 index 000000000..115611a8e --- /dev/null +++ b/tests/test_calibrated_texture_extra.py | |||
| @@ -0,0 +1,2192 @@ | |||
| 1 | """Expanded stdlib-only unit tests for tools/calibrated_texture.py. | ||
| 2 | |||
| 3 | Covers native loader wiring, array validation, zig/distance/accumulate helpers, | ||
| 4 | tile address mapping, BC1/BC3/BC4/BC5/BC7 block rebuilders, LocalDecoder chunk | ||
| 5 | decoding/caching/surface/DDS export paths, error handling, and CLI integration | ||
| 6 | using synthetic pools/profiles and unittest.mock (no game data). | ||
| 7 | |||
| 8 | python -I tests/test_calibrated_texture_extra.py -v | ||
| 9 | """ | ||
| 10 | from __future__ import annotations | ||
| 11 | |||
| 12 | import bisect | ||
| 13 | from contextlib import contextmanager, redirect_stderr, redirect_stdout | ||
| 14 | import ctypes | ||
| 15 | import hashlib | ||
| 16 | import importlib.util | ||
| 17 | import io | ||
| 18 | import json | ||
| 19 | import math | ||
| 20 | import os | ||
| 21 | from pathlib import Path | ||
| 22 | import struct | ||
| 23 | import sys | ||
| 24 | import tempfile | ||
| 25 | import unittest | ||
| 26 | from unittest import mock | ||
| 27 | import zlib | ||
| 28 | |||
| 29 | ROOT = Path(__file__).resolve().parents[1] | ||
| 30 | TOOLS_DIR = ROOT / "tools" | ||
| 31 | TESTS_DIR = ROOT / "tests" | ||
| 32 | for _p in (str(TESTS_DIR), str(TOOLS_DIR)): | ||
| 33 | if _p not in sys.path: | ||
| 34 | sys.path.insert(0, _p) | ||
| 35 | |||
| 36 | import bcpack # noqa: E402 | ||
| 37 | import bcpack_tables # noqa: E402 | ||
| 38 | import bcpack_tables_bptc as _bptc # noqa: E402 | ||
| 39 | import test_bcpack as tb # noqa: E402 | ||
| 40 | import test_ttpf_mips as ttm # noqa: E402 | ||
| 41 | import tex_headers # noqa: E402 | ||
| 42 | import ttpf_mips as ttpf # noqa: E402 | ||
| 43 | from test_calibrated_texture import synthetic_profile # noqa: E402 | ||
| 44 | |||
| 45 | |||
| 46 | # --------------------------------------------------------------------------- | ||
| 47 | # Minimal pure-stdlib NumPy shim for environments without NumPy installed. | ||
| 48 | # Only used when importlib.util.find_spec("numpy") is None. | ||
| 49 | # --------------------------------------------------------------------------- | ||
| 50 | |||
| 51 | class _FakeDType: | ||
| 52 | """Minimal NumPy-like dtype descriptor supporting integers, bool, float, str, and Vn.""" | ||
| 53 | |||
| 54 | _SPEC = { | ||
| 55 | "bool": ("b", 1, "?", False, False), | ||
| 56 | "b1": ("b", 1, "?", False, False), | ||
| 57 | "int8": ("i", 1, "b", True, False), | ||
| 58 | "i1": ("i", 1, "b", True, False), | ||
| 59 | "uint8": ("u", 1, "B", False, False), | ||
| 60 | "u1": ("u", 1, "B", False, False), | ||
| 61 | "int16": ("i", 2, "<h", True, False), | ||
| 62 | "i2": ("i", 2, "<h", True, False), | ||
| 63 | "<i2": ("i", 2, "<h", True, False), | ||
| 64 | "uint16": ("u", 2, "<H", False, False), | ||
| 65 | "u2": ("u", 2, "<H", False, False), | ||
| 66 | "<u2": ("u", 2, "<H", False, False), | ||
| 67 | "int32": ("i", 4, "<i", True, False), | ||
| 68 | "i4": ("i", 4, "<i", True, False), | ||
| 69 | "<i4": ("i", 4, "<i", True, False), | ||
| 70 | "uint32": ("u", 4, "<I", False, False), | ||
| 71 | "u4": ("u", 4, "<I", False, False), | ||
| 72 | "<u4": ("u", 4, "<I", False, False), | ||
| 73 | "int64": ("i", 8, "<q", True, False), | ||
| 74 | "i8": ("i", 8, "<q", True, False), | ||
| 75 | "<i8": ("i", 8, "<q", True, False), | ||
| 76 | "uint64": ("u", 8, "<Q", False, False), | ||
| 77 | "u8": ("u", 8, "<Q", False, False), | ||
| 78 | "<u8": ("u", 8, "<Q", False, False), | ||
| 79 | "float64": ("f", 8, "<d", True, True), | ||
| 80 | "f8": ("f", 8, "<d", True, True), | ||
| 81 | "str": ("U", 4, None, False, False), | ||
| 82 | "object": ("O", 8, None, False, False), | ||
| 83 | } | ||
| 84 | |||
| 85 | def __init__(self, spec): | ||
| 86 | if isinstance(spec, _FakeDType): | ||
| 87 | self.name = spec.name | ||
| 88 | self.kind = spec.kind | ||
| 89 | self.itemsize = spec.itemsize | ||
| 90 | self._struct = spec._struct | ||
| 91 | self.signed = spec.signed | ||
| 92 | self.is_float = spec.is_float | ||
| 93 | return | ||
| 94 | if spec is bool: | ||
| 95 | key = "bool" | ||
| 96 | elif spec is int: | ||
| 97 | key = "int64" | ||
| 98 | elif spec is float: | ||
| 99 | key = "float64" | ||
| 100 | elif spec is str: | ||
| 101 | key = "str" | ||
| 102 | else: | ||
| 103 | key = str(spec) | ||
| 104 | if key.startswith("V") and key[1:].isdigit(): | ||
| 105 | n = int(key[1:]) | ||
| 106 | self.name = key | ||
| 107 | self.kind = "V" | ||
| 108 | self.itemsize = n | ||
| 109 | self._struct = None | ||
| 110 | self.signed = False | ||
| 111 | self.is_float = False | ||
| 112 | return | ||
| 113 | if key not in self._SPEC: | ||
| 114 | raise TypeError(f"Unsupported fake dtype: {spec!r}") | ||
| 115 | kind, size, fmt, signed, is_float = self._SPEC[key] | ||
| 116 | self.name = key | ||
| 117 | self.kind = kind | ||
| 118 | self.itemsize = size | ||
| 119 | self._struct = struct.Struct(fmt) if fmt else None | ||
| 120 | self.signed = signed | ||
| 121 | self.is_float = is_float | ||
| 122 | |||
| 123 | def cast_val(self, v): | ||
| 124 | if self.kind == "b": | ||
| 125 | return bool(v) | ||
| 126 | if self.kind == "V": | ||
| 127 | if isinstance(v, (bytes, bytearray)): | ||
| 128 | b = bytes(v) | ||
| 129 | elif isinstance(v, int) and v == 0: | ||
| 130 | b = b"\x00" * self.itemsize | ||
| 131 | else: | ||
| 132 | raise TypeError(f"Cannot store {v!r} in {self.name}") | ||
| 133 | if len(b) != self.itemsize: | ||
| 134 | raise ValueError(f"Expected {self.itemsize} bytes, got {len(b)}") | ||
| 135 | return b | ||
| 136 | if self.kind in "iu": | ||
| 137 | iv = int(v) | ||
| 138 | bits = self.itemsize * 8 | ||
| 139 | mask = (1 << bits) - 1 | ||
| 140 | iv &= mask | ||
| 141 | if self.signed: | ||
| 142 | sign = 1 << (bits - 1) | ||
| 143 | iv = (iv ^ sign) - sign | ||
| 144 | return iv | ||
| 145 | if self.kind == "f": | ||
| 146 | return float(v) | ||
| 147 | return v | ||
| 148 | |||
| 149 | def __eq__(self, other): | ||
| 150 | if isinstance(other, _FakeDType): | ||
| 151 | return (self.kind, self.itemsize) == (other.kind, other.itemsize) | ||
| 152 | return NotImplemented | ||
| 153 | |||
| 154 | def __repr__(self): | ||
| 155 | return f"_FakeDType({self.name!r})" | ||
| 156 | |||
| 157 | |||
| 158 | def _normalize_dtype(dtype): | ||
| 159 | return dtype if isinstance(dtype, _FakeDType) else _FakeDType(dtype) | ||
| 160 | |||
| 161 | |||
| 162 | def _promote_dtype(a, b): | ||
| 163 | da = _normalize_dtype(a) | ||
| 164 | db = _normalize_dtype(b) | ||
| 165 | if da == db: | ||
| 166 | return da | ||
| 167 | if da.kind == "b": | ||
| 168 | return db | ||
| 169 | if db.kind == "b": | ||
| 170 | return da | ||
| 171 | if da.kind == "f" or db.kind == "f": | ||
| 172 | return _FakeDType("float64") | ||
| 173 | if da.kind == db.kind: | ||
| 174 | return da if da.itemsize >= db.itemsize else db | ||
| 175 | u_dt, i_dt = (da, db) if da.kind == "u" else (db, da) | ||
| 176 | if u_dt.itemsize >= i_dt.itemsize: | ||
| 177 | if u_dt.itemsize == 8: | ||
| 178 | return _FakeDType("uint64") | ||
| 179 | return _FakeDType(f"int{max(i_dt.itemsize, u_dt.itemsize * 2) * 8}") | ||
| 180 | return i_dt | ||
| 181 | |||
| 182 | |||
| 183 | def _infer_dtype(flat_vals): | ||
| 184 | if not flat_vals: | ||
| 185 | return _FakeDType("int64") | ||
| 186 | kinds = set() | ||
| 187 | for v in flat_vals: | ||
| 188 | if isinstance(v, (bytes, bytearray)): | ||
| 189 | kinds.add(("V", len(v))) | ||
| 190 | elif isinstance(v, bool): | ||
| 191 | kinds.add("b") | ||
| 192 | elif isinstance(v, int): | ||
| 193 | kinds.add("i") | ||
| 194 | elif isinstance(v, float): | ||
| 195 | kinds.add("f") | ||
| 196 | elif isinstance(v, str): | ||
| 197 | kinds.add("U") | ||
| 198 | else: | ||
| 199 | kinds.add("O") | ||
| 200 | if len(kinds) == 1: | ||
| 201 | k = next(iter(kinds)) | ||
| 202 | if isinstance(k, tuple) and k[0] == "V": | ||
| 203 | return _FakeDType(f"V{k[1]}") | ||
| 204 | if k == "b": | ||
| 205 | return _FakeDType("bool") | ||
| 206 | if k == "i": | ||
| 207 | lo = min(flat_vals) | ||
| 208 | hi = max(flat_vals) | ||
| 209 | if -0x8000000000000000 <= lo and hi <= 0x7FFFFFFFFFFFFFFF: | ||
| 210 | return _FakeDType("int64") | ||
| 211 | return _FakeDType("uint64") | ||
| 212 | if k == "f": | ||
| 213 | return _FakeDType("float64") | ||
| 214 | if k == "U": | ||
| 215 | return _FakeDType("str") | ||
| 216 | if kinds <= {"b", "i"}: | ||
| 217 | return _FakeDType("int64") | ||
| 218 | if kinds <= {"b", "i", "f"}: | ||
| 219 | return _FakeDType("float64") | ||
| 220 | return _FakeDType("object") | ||
| 221 | |||
| 222 | |||
| 223 | def _flatten_nested(obj): | ||
| 224 | if isinstance(obj, _FakeArray): | ||
| 225 | return obj.shape, obj._flat_list(), obj.dtype | ||
| 226 | if isinstance(obj, (list, tuple)): | ||
| 227 | if not obj: | ||
| 228 | return (0,), [], None | ||
| 229 | sub_shapes = [] | ||
| 230 | items = [] | ||
| 231 | sub_dtypes = [] | ||
| 232 | for elem in obj: | ||
| 233 | if isinstance(elem, (list, tuple, _FakeArray)): | ||
| 234 | sh, fl, dt = _flatten_nested(elem) | ||
| 235 | sub_shapes.append(sh) | ||
| 236 | items.extend(fl) | ||
| 237 | if dt is not None: | ||
| 238 | sub_dtypes.append(dt) | ||
| 239 | else: | ||
| 240 | sub_shapes.append(()) | ||
| 241 | items.append(elem) | ||
| 242 | if len(set(sub_shapes)) != 1: | ||
| 243 | raise ValueError("inhomogeneous shape") | ||
| 244 | shape = (len(obj),) + sub_shapes[0] | ||
| 245 | dt = sub_dtypes[0] if sub_dtypes and all(d == sub_dtypes[0] for d in sub_dtypes) else None | ||
| 246 | return shape, items, dt | ||
| 247 | return (), [obj], None | ||
| 248 | |||
| 249 | |||
| 250 | def _shape_strides(shape): | ||
| 251 | strides = [1] * len(shape) | ||
| 252 | for i in range(len(shape) - 2, -1, -1): | ||
| 253 | strides[i] = strides[i + 1] * shape[i + 1] | ||
| 254 | return tuple(strides) | ||
| 255 | |||
| 256 | |||
| 257 | def _broadcast_shapes(s1, s2): | ||
| 258 | n = max(len(s1), len(s2)) | ||
| 259 | p1 = (1,) * (n - len(s1)) + s1 | ||
| 260 | p2 = (1,) * (n - len(s2)) + s2 | ||
| 261 | out = [] | ||
| 262 | for a, b in zip(p1, p2): | ||
| 263 | if a == b: | ||
| 264 | out.append(a) | ||
| 265 | elif a == 1: | ||
| 266 | out.append(b) | ||
| 267 | elif b == 1: | ||
| 268 | out.append(a) | ||
| 269 | else: | ||
| 270 | raise ValueError(f"operands could not be broadcast together with shapes {s1} {s2}") | ||
| 271 | return tuple(out) | ||
| 272 | |||
| 273 | |||
| 274 | def _broadcast_index(out_coord, target_shape): | ||
| 275 | pad = len(out_coord) - len(target_shape) | ||
| 276 | res = [] | ||
| 277 | for c, dim in zip(out_coord[pad:], target_shape): | ||
| 278 | res.append(0 if dim == 1 else c) | ||
| 279 | return tuple(res) | ||
| 280 | |||
| 281 | |||
| 282 | def _unravel(flat_idx, shape): | ||
| 283 | if not shape: | ||
| 284 | return () | ||
| 285 | coords = [0] * len(shape) | ||
| 286 | rem = flat_idx | ||
| 287 | for ax in range(len(shape) - 1, -1, -1): | ||
| 288 | dim = shape[ax] | ||
| 289 | coords[ax] = rem % dim | ||
| 290 | rem //= dim | ||
| 291 | return tuple(coords) | ||
| 292 | |||
| 293 | |||
| 294 | def _ravel_coord(coord, strides): | ||
| 295 | return sum(c * s for c, s in zip(coord, strides)) | ||
| 296 | |||
| 297 | |||
| 298 | class _FakeCtypesView: | ||
| 299 | def __init__(self, arr): | ||
| 300 | self._arr = arr | ||
| 301 | |||
| 302 | @property | ||
| 303 | def data(self): | ||
| 304 | return ctypes.addressof(self._arr._buf) | ||
| 305 | |||
| 306 | |||
| 307 | class _FakeFlat: | ||
| 308 | def __init__(self, arr): | ||
| 309 | self._arr = arr | ||
| 310 | |||
| 311 | def __getitem__(self, idx): | ||
| 312 | return self._arr.ravel()[idx] | ||
| 313 | |||
| 314 | def __setitem__(self, idx, value): | ||
| 315 | indices = idx._flat_list() if isinstance(idx, _FakeArray) else list(idx) | ||
| 316 | vals = value._flat_list() if isinstance(value, _FakeArray) else ( | ||
| 317 | list(value) if isinstance(value, (list, tuple)) else [value] * len(indices) | ||
| 318 | ) | ||
| 319 | if len(vals) == 1 and len(indices) != 1: | ||
| 320 | vals = vals * len(indices) | ||
| 321 | for pos, val in zip(indices, vals): | ||
| 322 | self._arr._set_flat(int(pos), val) | ||
| 323 | |||
| 324 | |||
| 325 | class _FakeArray: | ||
| 326 | """Pure-Python contiguous ndarray subset backed by a live ctypes byte buffer.""" | ||
| 327 | |||
| 328 | def __init__(self, shape, dtype, flat_vals=None, raw_bytes=None): | ||
| 329 | self.shape = tuple(shape) | ||
| 330 | self.dtype = _normalize_dtype(dtype) | ||
| 331 | self.size = math.prod(self.shape) if self.shape else 1 | ||
| 332 | self.ndim = len(self.shape) | ||
| 333 | self._strides = _shape_strides(self.shape) | ||
| 334 | total_bytes = self.size * self.dtype.itemsize | ||
| 335 | if self.dtype.kind in "UO": | ||
| 336 | self._buf = None | ||
| 337 | self._obj_data = list(flat_vals) if flat_vals is not None else [None] * self.size | ||
| 338 | return | ||
| 339 | self._obj_data = None | ||
| 340 | self._buf = (ctypes.c_ubyte * max(1, total_bytes))() | ||
| 341 | if raw_bytes is not None: | ||
| 342 | if len(raw_bytes) != total_bytes: | ||
| 343 | raise ValueError(f"Expected {total_bytes} raw bytes, got {len(raw_bytes)}") | ||
| 344 | if total_bytes: | ||
| 345 | ctypes.memmove(self._buf, raw_bytes, total_bytes) | ||
| 346 | elif flat_vals is not None: | ||
| 347 | for i, val in enumerate(flat_vals): | ||
| 348 | self._set_flat(i, val) | ||
| 349 | |||
| 350 | def _get_flat(self, i): | ||
| 351 | if i < 0: | ||
| 352 | i += self.size | ||
| 353 | if not 0 <= i < self.size: | ||
| 354 | raise IndexError(i) | ||
| 355 | if self._obj_data is not None: | ||
| 356 | return self._obj_data[i] | ||
| 357 | sz = self.dtype.itemsize | ||
| 358 | if self.dtype.kind == "V": | ||
| 359 | return bytes(self._buf[i * sz : (i + 1) * sz]) | ||
| 360 | return self.dtype._struct.unpack_from(self._buf, i * sz)[0] | ||
| 361 | |||
| 362 | def _set_flat(self, i, val): | ||
| 363 | if i < 0: | ||
| 364 | i += self.size | ||
| 365 | if not 0 <= i < self.size: | ||
| 366 | raise IndexError(i) | ||
| 367 | if self._obj_data is not None: | ||
| 368 | self._obj_data[i] = val | ||
| 369 | return | ||
| 370 | coerced = self.dtype.cast_val(val) | ||
| 371 | sz = self.dtype.itemsize | ||
| 372 | if self.dtype.kind == "V": | ||
| 373 | for b_i, byte in enumerate(coerced): | ||
| 374 | self._buf[i * sz + b_i] = byte | ||
| 375 | else: | ||
| 376 | self.dtype._struct.pack_into(self._buf, i * sz, coerced) | ||
| 377 | |||
| 378 | def _flat_list(self): | ||
| 379 | return [self._get_flat(i) for i in range(self.size)] | ||
| 380 | |||
| 381 | def _get_coord(self, coord): | ||
| 382 | return self._get_flat(_ravel_coord(coord, self._strides)) | ||
| 383 | |||
| 384 | def _set_coord(self, coord, val): | ||
| 385 | self._set_flat(_ravel_coord(coord, self._strides), val) | ||
| 386 | |||
| 387 | @property | ||
| 388 | def ctypes(self): | ||
| 389 | return _FakeCtypesView(self) | ||
| 390 | |||
| 391 | @property | ||
| 392 | def flat(self): | ||
| 393 | return _FakeFlat(self) | ||
| 394 | |||
| 395 | @property | ||
| 396 | def T(self): | ||
| 397 | return self.transpose(*reversed(range(self.ndim))) | ||
| 398 | |||
| 399 | def __len__(self): | ||
| 400 | if self.ndim == 0: | ||
| 401 | raise TypeError("len() of unsized object") | ||
| 402 | return self.shape[0] | ||
| 403 | |||
| 404 | def __iter__(self): | ||
| 405 | if self.ndim == 0: | ||
| 406 | raise TypeError("iteration over a 0-d array") | ||
| 407 | for i in range(self.shape[0]): | ||
| 408 | yield self[i] | ||
| 409 | |||
| 410 | def __int__(self): | ||
| 411 | if self.size != 1: | ||
| 412 | raise TypeError("only length-1 arrays can be converted to Python scalars") | ||
| 413 | return int(self._get_flat(0)) | ||
| 414 | |||
| 415 | def __index__(self): | ||
| 416 | if self.size != 1 or self.dtype.kind not in "iu": | ||
| 417 | raise TypeError("only integer scalar arrays can be converted to a scalar index") | ||
| 418 | return int(self._get_flat(0)) | ||
| 419 | |||
| 420 | def __bool__(self): | ||
| 421 | if self.size != 1: | ||
| 422 | raise ValueError("The truth value of an array with more than one element is ambiguous") | ||
| 423 | return bool(self._get_flat(0)) | ||
| 424 | |||
| 425 | def copy(self): | ||
| 426 | if self._obj_data is not None: | ||
| 427 | return _FakeArray(self.shape, self.dtype, flat_vals=list(self._obj_data)) | ||
| 428 | return _FakeArray(self.shape, self.dtype, raw_bytes=self.tobytes()) | ||
| 429 | |||
| 430 | def tobytes(self): | ||
| 431 | if self._obj_data is not None: | ||
| 432 | raise TypeError("cannot convert object/str array to bytes") | ||
| 433 | n = self.size * self.dtype.itemsize | ||
| 434 | return bytes(memoryview(self._buf)[:n]) | ||
| 435 | |||
| 436 | def tolist(self): | ||
| 437 | def _build(offset, shape): | ||
| 438 | if not shape: | ||
| 439 | return self._get_flat(offset) | ||
| 440 | step = math.prod(shape[1:]) if len(shape) > 1 else 1 | ||
| 441 | return [_build(offset + i * step, shape[1:]) for i in range(shape[0])] | ||
| 442 | return _build(0, self.shape) | ||
| 443 | |||
| 444 | def astype(self, dtype): | ||
| 445 | dt = _normalize_dtype(dtype) | ||
| 446 | return _FakeArray(self.shape, dt, flat_vals=self._flat_list()) | ||
| 447 | |||
| 448 | def ravel(self): | ||
| 449 | return _FakeArray((self.size,), self.dtype, raw_bytes=self.tobytes()) if self._buf is not None else _FakeArray((self.size,), self.dtype, flat_vals=self._flat_list()) | ||
| 450 | |||
| 451 | def reshape(self, *newshape): | ||
| 452 | if len(newshape) == 1 and isinstance(newshape[0], (tuple, list)): | ||
| 453 | newshape = tuple(newshape[0]) | ||
| 454 | shape = list(newshape) | ||
| 455 | if -1 in shape: | ||
| 456 | neg_idx = shape.index(-1) | ||
| 457 | known = math.prod(d for d in shape if d != -1) | ||
| 458 | shape[neg_idx] = self.size // known | ||
| 459 | shape = tuple(shape) | ||
| 460 | if math.prod(shape) != self.size: | ||
| 461 | raise ValueError(f"cannot reshape array of size {self.size} into shape {shape}") | ||
| 462 | if self._buf is not None: | ||
| 463 | return _FakeArray(shape, self.dtype, raw_bytes=self.tobytes()) | ||
| 464 | return _FakeArray(shape, self.dtype, flat_vals=self._flat_list()) | ||
| 465 | |||
| 466 | def transpose(self, *axes): | ||
| 467 | if len(axes) == 1 and isinstance(axes[0], (tuple, list)): | ||
| 468 | axes = tuple(axes[0]) | ||
| 469 | if not axes: | ||
| 470 | axes = tuple(reversed(range(self.ndim))) | ||
| 471 | new_shape = tuple(self.shape[a] for a in axes) | ||
| 472 | vals = [] | ||
| 473 | for idx in range(self.size): | ||
| 474 | coord = _unravel(idx, new_shape) | ||
| 475 | src = [0] * self.ndim | ||
| 476 | for new_ax, old_ax in enumerate(axes): | ||
| 477 | src[old_ax] = coord[new_ax] | ||
| 478 | vals.append(self._get_coord(tuple(src))) | ||
| 479 | return _FakeArray(new_shape, self.dtype, flat_vals=vals) | ||
| 480 | |||
| 481 | def any(self): | ||
| 482 | return any(bool(v) for v in self._flat_list()) | ||
| 483 | |||
| 484 | def all(self): | ||
| 485 | return all(bool(v) for v in self._flat_list()) | ||
| 486 | |||
| 487 | def max(self): | ||
| 488 | vals = self._flat_list() | ||
| 489 | if not vals: | ||
| 490 | raise ValueError("zero-size array to reduction operation maximum which has no identity") | ||
| 491 | return max(vals) | ||
| 492 | |||
| 493 | def min(self): | ||
| 494 | vals = self._flat_list() | ||
| 495 | if not vals: | ||
| 496 | raise ValueError("zero-size array to reduction operation minimum which has no identity") | ||
| 497 | return min(vals) | ||
| 498 | |||
| 499 | # --- Indexing --- | ||
| 500 | def _parse_key(self, key): | ||
| 501 | if not isinstance(key, tuple): | ||
| 502 | key = (key,) | ||
| 503 | # Fast path: single boolean mask matching array shape or leading axis | ||
| 504 | if len(key) == 1 and isinstance(key[0], _FakeArray) and key[0].dtype.kind == "b": | ||
| 505 | return ("bool_mask", key[0]) | ||
| 506 | if len(key) == 1 and isinstance(key[0], (list, tuple)) and key[0] and all(isinstance(v, bool) for v in key[0]): | ||
| 507 | return ("bool_mask", _fake_asarray(key[0], dtype="bool")) | ||
| 508 | |||
| 509 | # General multi-axis key supporting int, slice, None, and integer fancy indexers | ||
| 510 | items = list(key) | ||
| 511 | non_none = [x for x in items if x is not None] | ||
| 512 | while len(non_none) < self.ndim: | ||
| 513 | items.append(slice(None)) | ||
| 514 | non_none.append(slice(None)) | ||
| 515 | return ("axes", items) | ||
| 516 | |||
| 517 | def __getitem__(self, key): | ||
| 518 | kind, parsed = self._parse_key(key) | ||
| 519 | if kind == "bool_mask": | ||
| 520 | mask = parsed | ||
| 521 | if mask.shape == self.shape: | ||
| 522 | vals = [v for v, m in zip(self._flat_list(), mask._flat_list()) if m] | ||
| 523 | return _FakeArray((len(vals),), self.dtype, flat_vals=vals) | ||
| 524 | if mask.ndim == 1 and len(mask) == self.shape[0]: | ||
| 525 | tail_shape = self.shape[1:] | ||
| 526 | tail_size = math.prod(tail_shape) if tail_shape else 1 | ||
| 527 | vals = [] | ||
| 528 | rows = 0 | ||
| 529 | for r, keep in enumerate(mask._flat_list()): | ||
| 530 | if keep: | ||
| 531 | rows += 1 | ||
| 532 | base = r * tail_size | ||
| 533 | for off in range(tail_size): | ||
| 534 | vals.append(self._get_flat(base + off)) | ||
| 535 | return _FakeArray((rows,) + tail_shape, self.dtype, flat_vals=vals) | ||
| 536 | raise IndexError("boolean index did not match indexed array") | ||
| 537 | |||
| 538 | # Separate axes into newaxis, slice, int, or fancy integer array | ||
| 539 | fancy_positions = [] | ||
| 540 | axis = 0 | ||
| 541 | axis_specs = [] | ||
| 542 | for item in parsed: | ||
| 543 | if item is None: | ||
| 544 | axis_specs.append(("newaxis", None)) | ||
| 545 | continue | ||
| 546 | dim = self.shape[axis] | ||
| 547 | if isinstance(item, slice): | ||
| 548 | axis_specs.append(("slice", range(*item.indices(dim)))) | ||
| 549 | elif isinstance(item, int) or (isinstance(item, _FakeArray) and item.ndim == 0 and item.dtype.kind in "iu"): | ||
| 550 | idx = int(item) | ||
| 551 | if idx < 0: | ||
| 552 | idx += dim | ||
| 553 | if not 0 <= idx < dim: | ||
| 554 | raise IndexError(idx) | ||
| 555 | axis_specs.append(("int", idx)) | ||
| 556 | else: | ||
| 557 | arr = item if isinstance(item, _FakeArray) else _fake_asarray(item) | ||
| 558 | if arr.dtype.kind not in "iu": | ||
| 559 | raise IndexError("arrays used as indices must be of integer type") | ||
| 560 | fancy_positions.append((len(axis_specs), dim, arr)) | ||
| 561 | axis_specs.append(("fancy", arr)) | ||
| 562 | axis += 1 | ||
| 563 | |||
| 564 | if not fancy_positions: | ||
| 565 | out_shape = [] | ||
| 566 | ranges = [] | ||
| 567 | for sp_kind, sp_val in axis_specs: | ||
| 568 | if sp_kind == "newaxis": | ||
| 569 | out_shape.append(1) | ||
| 570 | ranges.append([0]) | ||
| 571 | elif sp_kind == "slice": | ||
| 572 | out_shape.append(len(sp_val)) | ||
| 573 | ranges.append(list(sp_val)) | ||
| 574 | else: | ||
| 575 | ranges.append([sp_val]) | ||
| 576 | if not out_shape: | ||
| 577 | coord = tuple(r[0] for r in ranges) | ||
| 578 | return self._get_coord(coord) | ||
| 579 | vals = [] | ||
| 580 | total = math.prod(out_shape) | ||
| 581 | for idx in range(total): | ||
| 582 | oc = _unravel(idx, tuple(out_shape)) | ||
| 583 | src = [] | ||
| 584 | oi = 0 | ||
| 585 | for sp_kind, sp_val in axis_specs: | ||
| 586 | if sp_kind == "newaxis": | ||
| 587 | oi += 1 | ||
| 588 | elif sp_kind == "slice": | ||
| 589 | src.append(sp_val[oc[oi]]) | ||
| 590 | oi += 1 | ||
| 591 | else: | ||
| 592 | src.append(sp_val) | ||
| 593 | vals.append(self._get_coord(tuple(src))) | ||
| 594 | return _FakeArray(tuple(out_shape), self.dtype, flat_vals=vals) | ||
| 595 | |||
| 596 | # Broadcast all fancy arrays together | ||
| 597 | bshape = () | ||
| 598 | for _, _, arr in fancy_positions: | ||
| 599 | bshape = _broadcast_shapes(bshape, arr.shape) | ||
| 600 | contiguous_fancy = [p for p, _, _ in fancy_positions] == list( | ||
| 601 | range(fancy_positions[0][0], fancy_positions[0][0] + len(fancy_positions)) | ||
| 602 | ) | ||
| 603 | # Build output shape | ||
| 604 | out_shape = [] | ||
| 605 | fancy_inserted = False | ||
| 606 | slice_ranges = {} | ||
| 607 | for pos, (sp_kind, sp_val) in enumerate(axis_specs): | ||
| 608 | if sp_kind == "newaxis": | ||
| 609 | out_shape.append(1) | ||
| 610 | elif sp_kind == "slice": | ||
| 611 | out_shape.append(len(sp_val)) | ||
| 612 | slice_ranges[pos] = list(sp_val) | ||
| 613 | elif sp_kind == "fancy": | ||
| 614 | if contiguous_fancy: | ||
| 615 | if not fancy_inserted: | ||
| 616 | out_shape.extend(bshape) | ||
| 617 | fancy_inserted = True | ||
| 618 | else: | ||
| 619 | if not fancy_inserted: | ||
| 620 | out_shape = list(bshape) + out_shape | ||
| 621 | fancy_inserted = True | ||
| 622 | |||
| 623 | # Map each output coordinate to source coordinate | ||
| 624 | total = math.prod(out_shape) if out_shape else 1 | ||
| 625 | vals = [] | ||
| 626 | b_start = 0 if not contiguous_fancy else sum( | ||
| 627 | 1 for p, (k, _) in enumerate(axis_specs[: fancy_positions[0][0]]) if k in ("newaxis", "slice") | ||
| 628 | ) | ||
| 629 | b_len = len(bshape) | ||
| 630 | for flat_i in range(total): | ||
| 631 | oc = _unravel(flat_i, tuple(out_shape)) | ||
| 632 | b_coord = oc[b_start : b_start + b_len] | ||
| 633 | src = [] | ||
| 634 | oi = 0 if contiguous_fancy else b_len | ||
| 635 | for pos, (sp_kind, sp_val) in enumerate(axis_specs): | ||
| 636 | if sp_kind == "newaxis": | ||
| 637 | oi += 1 | ||
| 638 | elif sp_kind == "slice": | ||
| 639 | src.append(slice_ranges[pos][oc[oi]]) | ||
| 640 | oi += 1 | ||
| 641 | elif sp_kind == "int": | ||
| 642 | src.append(sp_val) | ||
| 643 | elif sp_kind == "fancy": | ||
| 644 | if pos == fancy_positions[0][0] and contiguous_fancy: | ||
| 645 | oi += b_len | ||
| 646 | dim = self.shape[len(src)] | ||
| 647 | fc = _broadcast_index(b_coord, sp_val.shape) | ||
| 648 | idx_v = int(sp_val._get_coord(fc)) if sp_val.ndim else int(sp_val._get_flat(0)) | ||
| 649 | if idx_v < 0: | ||
| 650 | idx_v += dim | ||
| 651 | if not 0 <= idx_v < dim: | ||
| 652 | raise IndexError(idx_v) | ||
| 653 | src.append(idx_v) | ||
| 654 | vals.append(self._get_coord(tuple(src))) | ||
| 655 | if not out_shape: | ||
| 656 | return vals[0] | ||
| 657 | return _FakeArray(tuple(out_shape), self.dtype, flat_vals=vals) | ||
| 658 | |||
| 659 | def __setitem__(self, key, value): | ||
| 660 | kind, parsed = self._parse_key(key) | ||
| 661 | if kind == "bool_mask": | ||
| 662 | mask = parsed | ||
| 663 | rhs = value if isinstance(value, _FakeArray) else _fake_asarray(value, dtype=self.dtype) | ||
| 664 | if mask.shape == self.shape: | ||
| 665 | k = 0 | ||
| 666 | for i, m in enumerate(mask._flat_list()): | ||
| 667 | if m: | ||
| 668 | v = rhs._get_flat(0) if rhs.size == 1 else rhs._get_flat(k) | ||
| 669 | self._set_flat(i, v) | ||
| 670 | k += 1 | ||
| 671 | return | ||
| 672 | if mask.ndim == 1 and len(mask) == self.shape[0]: | ||
| 673 | tail_shape = self.shape[1:] | ||
| 674 | tail_size = math.prod(tail_shape) if tail_shape else 1 | ||
| 675 | n_true = sum(1 for m in mask._flat_list() if m) | ||
| 676 | target_shape = (n_true,) + tail_shape | ||
| 677 | b_shape = _broadcast_shapes(target_shape, rhs.shape) | ||
| 678 | if b_shape != target_shape: | ||
| 679 | raise ValueError(f"cannot broadcast {rhs.shape} to {target_shape}") | ||
| 680 | t_idx = 0 | ||
| 681 | for r, keep in enumerate(mask._flat_list()): | ||
| 682 | if keep: | ||
| 683 | base = r * tail_size | ||
| 684 | for off in range(tail_size): | ||
| 685 | tc = (t_idx,) + _unravel(off, tail_shape) | ||
| 686 | rc = _broadcast_index(tc, rhs.shape) | ||
| 687 | self._set_flat(base + off, rhs._get_coord(rc) if rhs.ndim else rhs._get_flat(0)) | ||
| 688 | t_idx += 1 | ||
| 689 | return | ||
| 690 | raise IndexError("boolean index did not match indexed array") | ||
| 691 | |||
| 692 | # Concrete axis assignment (ints and slices) | ||
| 693 | slices = [] | ||
| 694 | sub_shape = [] | ||
| 695 | axis = 0 | ||
| 696 | for item in parsed: | ||
| 697 | if item is None: | ||
| 698 | continue | ||
| 699 | dim = self.shape[axis] | ||
| 700 | if isinstance(item, slice): | ||
| 701 | rng = list(range(*item.indices(dim))) | ||
| 702 | slices.append(rng) | ||
| 703 | sub_shape.append(len(rng)) | ||
| 704 | else: | ||
| 705 | idx = int(item) | ||
| 706 | if idx < 0: | ||
| 707 | idx += dim | ||
| 708 | if not 0 <= idx < dim: | ||
| 709 | raise IndexError(idx) | ||
| 710 | slices.append([idx]) | ||
| 711 | axis += 1 | ||
| 712 | rhs = value if isinstance(value, _FakeArray) else _fake_asarray(value, dtype=self.dtype) | ||
| 713 | sub_shape = tuple(sub_shape) | ||
| 714 | if not sub_shape: | ||
| 715 | coord = tuple(r[0] for r in slices) | ||
| 716 | self._set_coord(coord, rhs._get_flat(0) if rhs.size == 1 else rhs) | ||
| 717 | return | ||
| 718 | total = math.prod(sub_shape) | ||
| 719 | for fi in range(total): | ||
| 720 | sc = _unravel(fi, sub_shape) | ||
| 721 | dst = [] | ||
| 722 | si = 0 | ||
| 723 | for rng in slices: | ||
| 724 | if len(rng) == 1 and len(sub_shape) < len(slices): | ||
| 725 | dst.append(rng[0]) | ||
| 726 | else: | ||
| 727 | dst.append(rng[sc[si]]) | ||
| 728 | si += 1 | ||
| 729 | # Re-derive dst accurately: | ||
| 730 | dst = [] | ||
| 731 | si = 0 | ||
| 732 | for ax_i, item in enumerate(parsed): | ||
| 733 | if item is None: | ||
| 734 | continue | ||
| 735 | if isinstance(item, slice): | ||
| 736 | dst.append(slices[ax_i][sc[si]]) | ||
| 737 | si += 1 | ||
| 738 | else: | ||
| 739 | dst.append(slices[ax_i][0]) | ||
| 740 | rc = _broadcast_index(sc, rhs.shape) | ||
| 741 | self._set_coord(tuple(dst), rhs._get_coord(rc) if rhs.ndim else rhs._get_flat(0)) | ||
| 742 | |||
| 743 | # --- Operators --- | ||
| 744 | def _binop(self, other, fn, out_dtype=None): | ||
| 745 | rhs = other if isinstance(other, _FakeArray) else _fake_asarray(other) | ||
| 746 | bshape = _broadcast_shapes(self.shape, rhs.shape) | ||
| 747 | dt = _normalize_dtype(out_dtype) if out_dtype is not None else _promote_dtype(self.dtype, rhs.dtype) | ||
| 748 | total = math.prod(bshape) if bshape else 1 | ||
| 749 | vals = [] | ||
| 750 | for i in range(total): | ||
| 751 | oc = _unravel(i, bshape) | ||
| 752 | a_val = self._get_coord(_broadcast_index(oc, self.shape)) if self.ndim else self._get_flat(0) | ||
| 753 | b_val = rhs._get_coord(_broadcast_index(oc, rhs.shape)) if rhs.ndim else rhs._get_flat(0) | ||
| 754 | vals.append(fn(a_val, b_val)) | ||
| 755 | return _FakeArray(bshape, dt, flat_vals=vals) | ||
| 756 | |||
| 757 | def _rbinop(self, other, fn, out_dtype=None): | ||
| 758 | lhs = other if isinstance(other, _FakeArray) else _fake_asarray(other) | ||
| 759 | return lhs._binop(self, fn, out_dtype=out_dtype) | ||
| 760 | |||
| 761 | def _ibop(self, other, fn): | ||
| 762 | res = self._binop(other, fn, out_dtype=self.dtype) | ||
| 763 | for i, v in enumerate(res._flat_list()): | ||
| 764 | self._set_flat(i, v) | ||
| 765 | return self | ||
| 766 | |||
| 767 | def __add__(self, o): return self._binop(o, lambda a, b: a + b) | ||
| 768 | def __radd__(self, o): return self._rbinop(o, lambda a, b: a + b) | ||
| 769 | def __iadd__(self, o): return self._ibop(o, lambda a, b: a + b) | ||
| 770 | def __sub__(self, o): return self._binop(o, lambda a, b: a - b) | ||
| 771 | def __rsub__(self, o): return self._rbinop(o, lambda a, b: a - b) | ||
| 772 | def __mul__(self, o): return self._binop(o, lambda a, b: a * b) | ||
| 773 | def __rmul__(self, o): return self._rbinop(o, lambda a, b: a * b) | ||
| 774 | def __floordiv__(self, o): return self._binop(o, lambda a, b: a // b) | ||
| 775 | def __mod__(self, o): return self._binop(o, lambda a, b: a % b) | ||
| 776 | def __imod__(self, o): return self._ibop(o, lambda a, b: a % b) | ||
| 777 | def __lshift__(self, o): return self._binop(o, lambda a, b: a << b) | ||
| 778 | def __rlshift__(self, o): | ||
| 779 | # Preserve self's integer dtype when shifting a scalar 1 << uint64_arr | ||
| 780 | rhs_arr = o if isinstance(o, _FakeArray) else _fake_asarray(o, dtype=self.dtype) | ||
| 781 | return rhs_arr._binop(self, lambda a, b: a << b, out_dtype=self.dtype) | ||
| 782 | def __rshift__(self, o): return self._binop(o, lambda a, b: a >> b) | ||
| 783 | def __and__(self, o): return self._binop(o, lambda a, b: a & b) | ||
| 784 | def __or__(self, o): return self._binop(o, lambda a, b: a | b) | ||
| 785 | def __ior__(self, o): return self._ibop(o, lambda a, b: a | b) | ||
| 786 | def __xor__(self, o): return self._binop(o, lambda a, b: a ^ b) | ||
| 787 | def __lt__(self, o): return self._binop(o, lambda a, b: a < b, out_dtype="bool") | ||
| 788 | def __le__(self, o): return self._binop(o, lambda a, b: a <= b, out_dtype="bool") | ||
| 789 | def __gt__(self, o): return self._binop(o, lambda a, b: a > b, out_dtype="bool") | ||
| 790 | def __ge__(self, o): return self._binop(o, lambda a, b: a >= b, out_dtype="bool") | ||
| 791 | def __eq__(self, o): return self._binop(o, lambda a, b: a == b, out_dtype="bool") | ||
| 792 | def __ne__(self, o): return self._binop(o, lambda a, b: a != b, out_dtype="bool") | ||
| 793 | |||
| 794 | def __neg__(self): | ||
| 795 | return _FakeArray(self.shape, self.dtype, flat_vals=[-v for v in self._flat_list()]) | ||
| 796 | |||
| 797 | def __invert__(self): | ||
| 798 | if self.dtype.kind == "b": | ||
| 799 | return _FakeArray(self.shape, self.dtype, flat_vals=[not v for v in self._flat_list()]) | ||
| 800 | return _FakeArray(self.shape, self.dtype, flat_vals=[~v for v in self._flat_list()]) | ||
| 801 | |||
| 802 | def __matmul__(self, other): | ||
| 803 | rhs = other if isinstance(other, _FakeArray) else _fake_asarray(other) | ||
| 804 | dt = _promote_dtype(self.dtype, rhs.dtype) | ||
| 805 | if self.ndim == 2 and rhs.ndim == 1 and self.shape[1] == rhs.shape[0]: | ||
| 806 | m, k = self.shape | ||
| 807 | r_vals = rhs._flat_list() | ||
| 808 | s_vals = self._flat_list() | ||
| 809 | out = [sum(s_vals[i * k + j] * r_vals[j] for j in range(k)) for i in range(m)] | ||
| 810 | return _FakeArray((m,), dt, flat_vals=out) | ||
| 811 | raise ValueError(f"Unsupported matmul shapes {self.shape} @ {rhs.shape}") | ||
| 812 | |||
| 813 | |||
| 814 | def _fake_asarray(values, dtype=None): | ||
| 815 | if isinstance(values, _FakeArray): | ||
| 816 | if dtype is None or values.dtype == _normalize_dtype(dtype): | ||
| 817 | return values | ||
| 818 | return values.astype(dtype) | ||
| 819 | shape, flat, sub_dt = _flatten_nested(values) | ||
| 820 | dt = _normalize_dtype(dtype) if dtype is not None else (sub_dt or _infer_dtype(flat)) | ||
| 821 | return _FakeArray(shape, dt, flat_vals=flat) | ||
| 822 | |||
| 823 | |||
| 824 | def _fake_array(values, dtype=None): | ||
| 825 | arr = _fake_asarray(values, dtype=dtype) | ||
| 826 | return arr.copy() | ||
| 827 | |||
| 828 | |||
| 829 | def _fake_ascontiguousarray(values, dtype=None): | ||
| 830 | return _fake_asarray(values, dtype=dtype).copy() | ||
| 831 | |||
| 832 | |||
| 833 | def _fake_zeros(shape, dtype="float64"): | ||
| 834 | sh = (int(shape),) if isinstance(shape, int) else tuple(shape) | ||
| 835 | dt = _normalize_dtype(dtype) | ||
| 836 | n = math.prod(sh) if sh else 1 | ||
| 837 | if dt.kind == "V": | ||
| 838 | return _FakeArray(sh, dt, flat_vals=[b"\x00" * dt.itemsize] * n) | ||
| 839 | return _FakeArray(sh, dt, flat_vals=[0] * n) | ||
| 840 | |||
| 841 | |||
| 842 | def _fake_empty(shape, dtype="float64"): | ||
| 843 | return _fake_zeros(shape, dtype=dtype) | ||
| 844 | |||
| 845 | |||
| 846 | def _fake_frombuffer(buf, dtype="uint8"): | ||
| 847 | raw = bytes(buf) | ||
| 848 | dt = _normalize_dtype(dtype) | ||
| 849 | if len(raw) % dt.itemsize != 0: | ||
| 850 | raise ValueError("buffer size must be a multiple of element size") | ||
| 851 | return _FakeArray((len(raw) // dt.itemsize,), dt, raw_bytes=raw) | ||
| 852 | |||
| 853 | |||
| 854 | def _fake_arange(start, stop=None, step=1, dtype=None): | ||
| 855 | if stop is None: | ||
| 856 | start, stop = 0, start | ||
| 857 | vals = list(range(int(start), int(stop), int(step))) | ||
| 858 | return _FakeArray((len(vals),), dtype or "int64", flat_vals=vals) | ||
| 859 | |||
| 860 | |||
| 861 | def _fake_any(arr): | ||
| 862 | return _fake_asarray(arr).any() | ||
| 863 | |||
| 864 | |||
| 865 | def _fake_all(arr): | ||
| 866 | return _fake_asarray(arr).all() | ||
| 867 | |||
| 868 | |||
| 869 | def _fake_unique(arr): | ||
| 870 | vals = sorted(set(_fake_asarray(arr)._flat_list())) | ||
| 871 | dt = arr.dtype if isinstance(arr, _FakeArray) else _infer_dtype(vals) | ||
| 872 | return _FakeArray((len(vals),), dt, flat_vals=vals) | ||
| 873 | |||
| 874 | |||
| 875 | def _fake_searchsorted(a, v, side="left"): | ||
| 876 | edges = _fake_asarray(a)._flat_list() | ||
| 877 | queries = _fake_asarray(v) | ||
| 878 | fn = bisect.bisect_right if side == "right" else bisect.bisect_left | ||
| 879 | res = [fn(edges, x) for x in queries._flat_list()] | ||
| 880 | return _FakeArray(queries.shape, "int64", flat_vals=res) | ||
| 881 | |||
| 882 | |||
| 883 | def _fake_roll(a, shift): | ||
| 884 | arr = _fake_asarray(a) | ||
| 885 | vals = arr._flat_list() | ||
| 886 | n = len(vals) | ||
| 887 | if n == 0: | ||
| 888 | return arr.copy() | ||
| 889 | s = shift % n | ||
| 890 | rolled = vals[-s:] + vals[:-s] if s else list(vals) | ||
| 891 | return _FakeArray(arr.shape, arr.dtype, flat_vals=rolled) | ||
| 892 | |||
| 893 | |||
| 894 | def _fake_column_stack(tup): | ||
| 895 | cols = [_fake_asarray(c) for c in tup] | ||
| 896 | n = cols[0].shape[0] | ||
| 897 | dt = cols[0].dtype | ||
| 898 | for c in cols[1:]: | ||
| 899 | dt = _promote_dtype(dt, c.dtype) | ||
| 900 | flat = [] | ||
| 901 | for r in range(n): | ||
| 902 | for c in cols: | ||
| 903 | flat.append(c._get_flat(r)) | ||
| 904 | return _FakeArray((n, len(cols)), dt, flat_vals=flat) | ||
| 905 | |||
| 906 | |||
| 907 | class _FakeBitwiseOr: | ||
| 908 | @staticmethod | ||
| 909 | def reduce(arr, axis=0): | ||
| 910 | a = _fake_asarray(arr) | ||
| 911 | if axis < 0: | ||
| 912 | axis += a.ndim | ||
| 913 | out_shape = tuple(d for i, d in enumerate(a.shape) if i != axis) | ||
| 914 | dim = a.shape[axis] | ||
| 915 | total = math.prod(out_shape) if out_shape else 1 | ||
| 916 | vals = [] | ||
| 917 | for idx in range(total): | ||
| 918 | oc = _unravel(idx, out_shape) | ||
| 919 | acc = 0 | ||
| 920 | for k in range(dim): | ||
| 921 | src = list(oc) | ||
| 922 | src.insert(axis, k) | ||
| 923 | acc |= a._get_coord(tuple(src)) | ||
| 924 | vals.append(acc) | ||
| 925 | return _FakeArray(out_shape, a.dtype, flat_vals=vals) | ||
| 926 | |||
| 927 | |||
| 928 | def _make_fake_numpy(): | ||
| 929 | import types | ||
| 930 | mod = types.ModuleType("numpy") | ||
| 931 | mod.array = _fake_array | ||
| 932 | mod.asarray = _fake_asarray | ||
| 933 | mod.ascontiguousarray = _fake_ascontiguousarray | ||
| 934 | mod.zeros = _fake_zeros | ||
| 935 | mod.empty = _fake_empty | ||
| 936 | mod.frombuffer = _fake_frombuffer | ||
| 937 | mod.arange = _fake_arange | ||
| 938 | mod.any = _fake_any | ||
| 939 | mod.all = _fake_all | ||
| 940 | mod.unique = _fake_unique | ||
| 941 | mod.searchsorted = _fake_searchsorted | ||
| 942 | mod.roll = _fake_roll | ||
| 943 | mod.column_stack = _fake_column_stack | ||
| 944 | mod.bitwise_or = _FakeBitwiseOr() | ||
| 945 | mod.ndarray = _FakeArray | ||
| 946 | return mod | ||
| 947 | |||
| 948 | |||
| 949 | def _load_calibrated_texture(): | ||
| 950 | """Load tools/calibrated_texture.py using real NumPy if present, else the stdlib shim.""" | ||
| 951 | if importlib.util.find_spec("numpy") is not None: | ||
| 952 | import calibrated_texture | ||
| 953 | return calibrated_texture, False | ||
| 954 | fake_np = _make_fake_numpy() | ||
| 955 | spec = importlib.util.spec_from_file_location( | ||
| 956 | "calibrated_texture", str(TOOLS_DIR / "calibrated_texture.py") | ||
| 957 | ) | ||
| 958 | mod = importlib.util.module_from_spec(spec) | ||
| 959 | with mock.patch.dict(sys.modules, {"numpy": fake_np}): | ||
| 960 | spec.loader.exec_module(mod) | ||
| 961 | return mod, True | ||
| 962 | |||
| 963 | |||
| 964 | ct, _USING_FAKE_NP = _load_calibrated_texture() | ||
| 965 | np = ct.np | ||
| 966 | |||
| 967 | |||
| 968 | # --------------------------------------------------------------------------- | ||
| 969 | # Synthetic RDS5 / ETPF pool and BCPack stream builders (no game data) | ||
| 970 | # --------------------------------------------------------------------------- | ||
| 971 | |||
| 972 | def write_custom_pool(path, records, chunks): | ||
| 973 | """Write a synthetic RDS5/ETPF pool with arbitrary `(codec, payload, virt_size)` chunks.""" | ||
| 974 | count = len(chunks) + 2 | ||
| 975 | table_end = 24 + (count - 1) * 8 | ||
| 976 | etpf = ttpf.align(table_end, 256) | ||
| 977 | area = len(records) * 24 | ||
| 978 | metadata = 16 + area + len(records) * 32 | ||
| 979 | padded = ttpf.align(metadata, 4096) | ||
| 980 | |||
| 981 | source = etpf + padded | ||
| 982 | virt = padded | ||
| 983 | entries = [] | ||
| 984 | packed_chunks = [] | ||
| 985 | for codec, payload, vsize_chunk in chunks: | ||
| 986 | assert vsize_chunk > 0 and vsize_chunk % 4096 == 0 | ||
| 987 | if codec == 0: | ||
| 988 | assert len(payload) == vsize_chunk | ||
| 989 | pad = 0 | ||
| 990 | else: | ||
| 991 | pad = (-len(payload)) % 256 | ||
| 992 | entries.append((source // 256) | (codec << 26) | ((virt // 4096) << 30) | (pad << 52)) | ||
| 993 | packed_chunks.append((source, payload)) | ||
| 994 | source += len(payload) + pad | ||
| 995 | virt += vsize_chunk | ||
| 996 | |||
| 997 | vsize = virt | ||
| 998 | entries.append((source // 256) | ((vsize // 4096) << 30)) | ||
| 999 | |||
| 1000 | header = bytearray(24) | ||
| 1001 | header[0:4] = b"RDS5" | ||
| 1002 | struct.pack_into("<I", header, 4, count) | ||
| 1003 | struct.pack_into("<Q", header, 8, vsize | (22 << 56)) | ||
| 1004 | struct.pack_into("<I", header, 16, (count + 31) // 32) | ||
| 1005 | struct.pack_into("<I", header, 20, 0) | ||
| 1006 | |||
| 1007 | blob = bytearray(source) | ||
| 1008 | blob[0:24] = header | ||
| 1009 | for i, e in enumerate(entries): | ||
| 1010 | struct.pack_into("<Q", blob, 24 + i * 8, e) | ||
| 1011 | blob[etpf : etpf + 4] = b"ETPF" | ||
| 1012 | struct.pack_into("<III", blob, etpf + 4, 634, len(records), area) | ||
| 1013 | for i, rec in enumerate(records): | ||
| 1014 | blob[etpf + 16 + i * 16 : etpf + 16 + (i + 1) * 16] = rec | ||
| 1015 | struct.pack_into("<Q", blob, etpf + 16 + len(records) * 16 + i * 8, 0x1000 + i) | ||
| 1016 | for src, payload in packed_chunks: | ||
| 1017 | blob[src : src + len(payload)] = payload | ||
| 1018 | Path(path).write_bytes(bytes(blob)) | ||
| 1019 | return padded | ||
| 1020 | |||
| 1021 | |||
| 1022 | def _bc3_profile_from_tables(): | ||
| 1023 | alpha = [a0 | (a1 << 3) for a0, a1 in bcpack_tables.BC3_ALPHA_PAIR] | ||
| 1024 | endpoints = {"-512": [0, 0, 0, 128, 0, 0, 0, 128]} | ||
| 1025 | for k, vals in (bcpack_tables.BC3_HISTORY_CONFIRMED | bcpack_tables.BC3_HISTORY_PROVISIONAL).items(): | ||
| 1026 | a0, a1, r0, g0, b0, r1, g1, b1 = vals | ||
| 1027 | endpoints[str(k - 256)] = [r0, g0, b0, a0, r1, g1, b1, a1] | ||
| 1028 | return { | ||
| 1029 | "endpoints": endpoints, | ||
| 1030 | "color": list(bcpack_tables.BC3_COLOUR_QUADRANT), | ||
| 1031 | "alpha": alpha, | ||
| 1032 | } | ||
| 1033 | |||
| 1034 | |||
| 1035 | def _bc1_profile_with_confirmed(): | ||
| 1036 | prof = synthetic_profile() | ||
| 1037 | for entry, vals in bcpack_tables.BC1_HISTORY_CONFIRMED.items(): | ||
| 1038 | prof["bc1"]["endpoints"][256 - entry] = list(vals) | ||
| 1039 | return prof | ||
| 1040 | |||
| 1041 | |||
| 1042 | def _empty_bc7_section(): | ||
| 1043 | return { | ||
| 1044 | "labels": [[0, 0, 0, 0] for _ in range(1024)], | ||
| 1045 | "anchors": [1] * 128, | ||
| 1046 | "seeds": { | ||
| 1047 | "base": [[[0, 8] for _ in range(56)] for _ in range(256)], | ||
| 1048 | "secondary": [[[0, 8] for _ in range(56)] for _ in range(256)], | ||
| 1049 | "early": [[[0, 8] for _ in range(56)] for _ in range(256)], | ||
| 1050 | "refined": [[[0, 8] for _ in range(56)] for _ in range(256)], | ||
| 1051 | }, | ||
| 1052 | "adjustments": {}, | ||
| 1053 | } | ||
| 1054 | |||
| 1055 | |||
| 1056 | def _encode_bc4_from_lanes(lanes): | ||
| 1057 | return tb.encode_lanes(lanes, 4) | ||
| 1058 | |||
| 1059 | |||
| 1060 | def _encode_bc5_from_lanes(lanes): | ||
| 1061 | return tb.encode_lanes(lanes, 5) | ||
| 1062 | |||
| 1063 | |||
| 1064 | def _encode_bc3_from_lanes(lanes): | ||
| 1065 | return tb.encode_lanes(lanes, 3) | ||
| 1066 | |||
| 1067 | |||
| 1068 | def _encode_bc6h_solid(nblocks): | ||
| 1069 | # Self-contained mode-11 (1-region, 4-bit index) zero-delta blocks. | ||
| 1070 | # For di=0, iref[0]=8; shift anchor pixel 0 by -8 so index 0 clears the anchor bit. | ||
| 1071 | lanes = [[0] * (2 * nblocks) for _ in range(16)] | ||
| 1072 | ix0 = tb._pack_ix_pair(tb._zig(-8), 0, 0) | ||
| 1073 | for i in range(nblocks): | ||
| 1074 | lanes[15][2 * i] = 10 # mode 11 | ||
| 1075 | lanes[2][2 * i] = tb._zig(100 + (i & 15)) | ||
| 1076 | lanes[11][2 * i] = ix0 | ||
| 1077 | return tb.encode_lanes(lanes, 6) | ||
| 1078 | |||
| 1079 | |||
| 1080 | def _encode_bc7_mode6_solid(nblocks): | ||
| 1081 | blk = ttm.solid_bc7(180, 90, 45) | ||
| 1082 | return tb.encode_bc7_mode6_blocks(blk * nblocks) | ||
| 1083 | |||
| 1084 | |||
| 1085 | @contextmanager | ||
| 1086 | def _fake_native_context(*, unpack_fn=None, rebuild_fn=None): | ||
| 1087 | """Patch ct.native() with a mock library supporting ctypes pointer reads/writes.""" | ||
| 1088 | lib = mock.MagicMock() | ||
| 1089 | if unpack_fn is None: | ||
| 1090 | lib.unpack.side_effect = lambda *args: -1 | ||
| 1091 | else: | ||
| 1092 | lib.unpack.side_effect = unpack_fn | ||
| 1093 | if rebuild_fn is not None: | ||
| 1094 | lib.rebuild.side_effect = rebuild_fn | ||
| 1095 | else: | ||
| 1096 | lib.rebuild.side_effect = lambda *args: None | ||
| 1097 | with mock.patch.object(ct, "native", return_value=lib): | ||
| 1098 | yield lib | ||
| 1099 | |||
| 1100 | |||
| 1101 | def _read_u8_buf(ptr, n): | ||
| 1102 | return bytes((ctypes.c_ubyte * n).from_address(ptr)) if n else b"" | ||
| 1103 | |||
| 1104 | |||
| 1105 | def _write_u8_buf(ptr, data): | ||
| 1106 | if data: | ||
| 1107 | ctypes.memmove(ptr, data, len(data)) | ||
| 1108 | |||
| 1109 | |||
| 1110 | # --------------------------------------------------------------------------- | ||
| 1111 | # Tests | ||
| 1112 | # --------------------------------------------------------------------------- | ||
| 1113 | |||
| 1114 | class TestNativeLoader(unittest.TestCase): | ||
| 1115 | def setUp(self): | ||
| 1116 | ct.native.cache_clear() | ||
| 1117 | self.addCleanup(ct.native.cache_clear) | ||
| 1118 | |||
| 1119 | def test_platform_library_names_and_ctypes_signatures(self): | ||
| 1120 | cases = ( | ||
| 1121 | ("win32", "bcpack_calibration.dll"), | ||
| 1122 | ("darwin", "libbcpack_calibration.dylib"), | ||
| 1123 | ("linux", "libbcpack_calibration.so"), | ||
| 1124 | ("freebsd14", "libbcpack_calibration.so"), | ||
| 1125 | ) | ||
| 1126 | expected_dir = Path(ct.__file__).with_name("bcpack_calibration") / "target/release" | ||
| 1127 | for plat, filename in cases: | ||
| 1128 | with self.subTest(platform=plat): | ||
| 1129 | ct.native.cache_clear() | ||
| 1130 | fake_lib = mock.MagicMock() | ||
| 1131 | with mock.patch.object(ct.sys, "platform", plat), \ | ||
| 1132 | mock.patch.object(ct.ctypes, "CDLL", return_value=fake_lib) as cdll: | ||
| 1133 | got = ct.native() | ||
| 1134 | self.assertIs(got, fake_lib) | ||
| 1135 | cdll.assert_called_once_with(str(expected_dir / filename)) | ||
| 1136 | self.assertEqual( | ||
| 1137 | fake_lib.unpack.argtypes, | ||
| 1138 | [ | ||
| 1139 | ctypes.c_char_p, | ||
| 1140 | ctypes.c_size_t, | ||
| 1141 | ctypes.c_char_p, | ||
| 1142 | ctypes.c_size_t, | ||
| 1143 | ctypes.c_size_t, | ||
| 1144 | ctypes.c_void_p, | ||
| 1145 | ], | ||
| 1146 | ) | ||
| 1147 | self.assertIs(fake_lib.unpack.restype, ctypes.c_ssize_t) | ||
| 1148 | self.assertEqual( | ||
| 1149 | fake_lib.rebuild.argtypes, | ||
| 1150 | [ctypes.c_void_p, ctypes.c_size_t] + [ctypes.c_void_p] * 5, | ||
| 1151 | ) | ||
| 1152 | self.assertIsNone(fake_lib.rebuild.restype) | ||
| 1153 | |||
| 1154 | def test_native_caches_until_cleared_and_propagates_oserror(self): | ||
| 1155 | fake_lib = mock.MagicMock() | ||
| 1156 | with mock.patch.object(ct.ctypes, "CDLL", return_value=fake_lib) as cdll: | ||
| 1157 | self.assertIs(ct.native(), fake_lib) | ||
| 1158 | self.assertIs(ct.native(), fake_lib) | ||
| 1159 | self.assertEqual(cdll.call_count, 1) | ||
| 1160 | ct.native.cache_clear() | ||
| 1161 | self.assertIs(ct.native(), fake_lib) | ||
| 1162 | self.assertEqual(cdll.call_count, 2) | ||
| 1163 | |||
| 1164 | ct.native.cache_clear() | ||
| 1165 | with mock.patch.object(ct.ctypes, "CDLL", side_effect=OSError("missing dll")) as cdll: | ||
| 1166 | with self.assertRaises(OSError): | ||
| 1167 | ct.native() | ||
| 1168 | with self.assertRaises(OSError): | ||
| 1169 | ct.native() | ||
| 1170 | self.assertEqual(cdll.call_count, 2) | ||
| 1171 | |||
| 1172 | |||
| 1173 | class TestArrayAndMathHelpers(unittest.TestCase): | ||
| 1174 | def test_array_validation_and_contiguous_conversion(self): | ||
| 1175 | arr = ct.array([[0, 255], [-1, 128]], (2, 2), "int16", -1, 255) | ||
| 1176 | self.assertEqual(arr.shape, (2, 2)) | ||
| 1177 | self.assertEqual(arr.dtype.kind, "i") | ||
| 1178 | self.assertEqual(arr.tobytes(), struct.pack("<4h", 0, 255, -1, 128)) | ||
| 1179 | |||
| 1180 | # Unsigned boundary 0..65535 | ||
| 1181 | u = ct.array([0, 65535], (2,), "uint16", 0, 65535) | ||
| 1182 | self.assertEqual(u.tobytes(), struct.pack("<2H", 0, 65535)) | ||
| 1183 | |||
| 1184 | # Transposed non-contiguous input becomes contiguous in row-major order. | ||
| 1185 | src = np.array([[1, 2], [3, 4]]).T | ||
| 1186 | contig = ct.array(src, (2, 2), "uint8", 0, 10) | ||
| 1187 | self.assertEqual(contig.tobytes(), bytes([1, 3, 2, 4])) | ||
| 1188 | |||
| 1189 | # Invalid shape, type, and out-of-range values | ||
| 1190 | for bad_val, shape, dt, lo, hi in ( | ||
| 1191 | ([1, 2, 3], (2, 2), "int32", 0, 10), | ||
| 1192 | ([1.0, 2.0], (2,), "int32", 0, 10), | ||
| 1193 | ([True, False], (2,), "uint8", 0, 1), | ||
| 1194 | (["1", "2"], (2,), "uint8", 0, 10), | ||
| 1195 | ([-2, 0], (2,), "int16", -1, 10), | ||
| 1196 | ([0, 256], (2,), "uint8", 0, 255), | ||
| 1197 | ): | ||
| 1198 | with self.subTest(bad_val=bad_val, shape=shape): | ||
| 1199 | with self.assertRaisesRegex(ValueError, "Invalid calibration field"): | ||
| 1200 | ct.array(bad_val, shape, dt, lo, hi) | ||
| 1201 | |||
| 1202 | def test_unzig_matches_bcpack(self): | ||
| 1203 | vals = list(range(256)) | ||
| 1204 | got = ct.unzig(np.array(vals, dtype="int32")).tolist() | ||
| 1205 | self.assertEqual(got, [bcpack._unzig(v) for v in vals]) | ||
| 1206 | self.assertEqual(ct.unzig(0), 0) | ||
| 1207 | self.assertEqual(ct.unzig(1), -1) | ||
| 1208 | self.assertEqual(ct.unzig(2), 1) | ||
| 1209 | self.assertEqual(ct.unzig(255), -128) | ||
| 1210 | |||
| 1211 | def test_distance_exhaustive_inter8_and_lane_selection(self): | ||
| 1212 | pairs = [(a, b) for a in range(16) for b in range(16)] | ||
| 1213 | # Shape (256, 2, 2): put pair in lane 1 and zero in lane 0. | ||
| 1214 | syms = [[[0, a], [0, b]] for a, b in pairs] | ||
| 1215 | arr = np.array(syms, dtype="uint8") | ||
| 1216 | self.assertEqual(ct.distance(arr, 0).tolist(), [0] * 256) | ||
| 1217 | self.assertEqual(ct.distance(arr, 1).tolist(), [bcpack._inter8(a, b) for a, b in pairs]) | ||
| 1218 | |||
| 1219 | def test_accumulate_chains_zero_and_external_roots(self): | ||
| 1220 | # Empty input | ||
| 1221 | empty_r = ct.accumulate(np.array([], dtype="int32"), np.zeros((0, 2), dtype="int32")) | ||
| 1222 | self.assertEqual(empty_r.shape, (0,)) | ||
| 1223 | |||
| 1224 | # Block 0: d=0 (-512); Block 1->0->-512; Block 2->1->0; Block 3->2->1->0 (depth 3); | ||
| 1225 | # Block 4: d=10 (external -> root = 4 - 10 = -6); Block 5->4 (root = -6). | ||
| 1226 | distances = np.array([0, 1, 1, 1, 10, 1, 2, 0], dtype="int32") | ||
| 1227 | residuals = np.array( | ||
| 1228 | [[10, 1], [2, 3], [4, 5], [6, 7], [100, 200], [5, -10], [7, 8], [9, 10]], | ||
| 1229 | dtype="int32", | ||
| 1230 | ) | ||
| 1231 | roots = ct.accumulate(distances, residuals) | ||
| 1232 | self.assertEqual(roots.tolist(), [-512, -512, -512, -512, -6, -6, -6, -512]) | ||
| 1233 | self.assertEqual( | ||
| 1234 | residuals.tolist(), | ||
| 1235 | [[10, 1], [12, 4], [16, 9], [22, 16], [100, 200], [105, 190], [107, 208], [9, 10]], | ||
| 1236 | ) | ||
| 1237 | |||
| 1238 | def test_addresses_matches_detile_across_4k_and_64k_tiles(self): | ||
| 1239 | ct.addresses.cache_clear() | ||
| 1240 | for tile in (4096, 65536): | ||
| 1241 | for fmt, bs in ((71, 8), (98, 16)): | ||
| 1242 | with self.subTest(tile=tile, bs=bs): | ||
| 1243 | lay = ttpf.surface_layout(256, 192, fmt, 8, tile) | ||
| 1244 | bw, bh = lay["block_w"], lay["block_h"] | ||
| 1245 | for mip in (lay["mips"][0], lay["mips"][-1]): | ||
| 1246 | w, h = mip["blocks_w"], mip["blocks_h"] | ||
| 1247 | x0, y0 = mip["tile_x"], mip["tile_y"] | ||
| 1248 | got = ct.addresses(tile, bs, bw, bh, w, h, x0, y0).tolist() | ||
| 1249 | # Compare against ttpf.detile by placing unique byte markers at each offset. | ||
| 1250 | # Note detile checks offset within mip["region"]; fill a synthetic region with | ||
| 1251 | # 8-byte / 16-byte tagged offsets. | ||
| 1252 | region = bytearray(mip["region"]) | ||
| 1253 | for off in range(0, len(region), bs): | ||
| 1254 | struct.pack_into("<Q", region, off, off) | ||
| 1255 | detiled = ttpf.detile(lay, mip, bytes(region)) | ||
| 1256 | expected = [ | ||
| 1257 | struct.unpack_from("<Q", detiled, i * bs)[0] for i in range(w * h) | ||
| 1258 | ] | ||
| 1259 | self.assertEqual(got, expected) | ||
| 1260 | info_before = ct.addresses.cache_info() | ||
| 1261 | ct.addresses(4096, 8, 32, 16, 4, 4, 0, 0) | ||
| 1262 | ct.addresses(4096, 8, 32, 16, 4, 4, 0, 0) | ||
| 1263 | info_after = ct.addresses.cache_info() | ||
| 1264 | self.assertEqual(info_after.hits, info_before.hits + 1) | ||
| 1265 | |||
| 1266 | |||
| 1267 | class TestBlockRebuildersParity(unittest.TestCase): | ||
| 1268 | def test_bc1_blocks_parity_chains_and_missing_history(self): | ||
| 1269 | prof = _bc1_profile_with_confirmed() | ||
| 1270 | seeds = ct.array(prof["bc1"]["endpoints"], (256, 6), "int32", -1, 63) | ||
| 1271 | selectors = ct.array(prof["bc1"]["selectors"], (4, 256), "uint32", 0, 0xFFFFFFFF) | ||
| 1272 | |||
| 1273 | # Block 0: external confirmed entry 1 (d=255 -> 256+0-255=1 -> age=255) | ||
| 1274 | # Block 1: d=1 -> chains onto Block 0 (external root) | ||
| 1275 | # Block 2: d=0 -> self-contained with negative endpoint wrap | ||
| 1276 | # Block 3: d=1 -> chains onto Block 2 | ||
| 1277 | lanes = [ | ||
| 1278 | [tb._zig(-1), tb._zig(1), 0, tb._zig(1)], # l0: -1 mod 256 = 255 | ||
| 1279 | [0, 0, 0, 0], | ||
| 1280 | [tb._zig(2), tb._zig(-3), tb._zig(-1), tb._zig(4)], | ||
| 1281 | [tb._zig(-4), tb._zig(5), tb._zig(-2), tb._zig(10)], | ||
| 1282 | [tb._zig(1), tb._zig(2), tb._zig(-3), tb._zig(7)], | ||
| 1283 | [tb._zig(-1), tb._zig(3), tb._zig(-5), tb._zig(2)], | ||
| 1284 | [tb._zig(6), tb._zig(-2), tb._zig(-1), tb._zig(8)], | ||
| 1285 | [tb._zig(0), tb._zig(1), tb._zig(-2), tb._zig(3)], | ||
| 1286 | [0, 17, 128, 255], | ||
| 1287 | [1, 33, 64, 200], | ||
| 1288 | [2, 99, 150, 10], | ||
| 1289 | [3, 210, 44, 77], | ||
| 1290 | ] | ||
| 1291 | sy = np.ascontiguousarray(np.asarray(lanes, dtype="uint8").T) | ||
| 1292 | got = ct.bc1_blocks(sy, (seeds, selectors)) | ||
| 1293 | expected = bcpack._bc1_blocks(lanes, 4, None) | ||
| 1294 | self.assertEqual(got, expected) | ||
| 1295 | |||
| 1296 | # Missing external history (provisional entry 6 -> age 250 has -1 in seeds) raises ValueError. | ||
| 1297 | bad_seeds = ct.array([[-1] * 6 for _ in range(256)], (256, 6), "int32", -1, 63) | ||
| 1298 | lanes_ext = [[tb._zig(-6)] if k == 0 else [0] for k in range(12)] | ||
| 1299 | sy_ext = np.ascontiguousarray(np.asarray(lanes_ext, dtype="uint8").T) | ||
| 1300 | with self.assertRaisesRegex(ValueError, "Missing BC1 endpoint history"): | ||
| 1301 | ct.bc1_blocks(sy_ext, (bad_seeds, selectors)) | ||
| 1302 | |||
| 1303 | # Self-contained stream (d=0) succeeds even with -1 in all external seeds. | ||
| 1304 | lanes_self = [[k * 3 % 32] for k in range(12)] | ||
| 1305 | lanes_self[0] = [0] | ||
| 1306 | lanes_self[1] = [0] | ||
| 1307 | sy_self = np.ascontiguousarray(np.asarray(lanes_self, dtype="uint8").T) | ||
| 1308 | self.assertEqual(ct.bc1_blocks(sy_self, (bad_seeds, selectors)), bcpack._bc1_blocks(lanes_self, 1, None)) | ||
| 1309 | |||
| 1310 | def test_bc7_blocks_invokes_native_rebuild(self): | ||
| 1311 | sy = np.array([[i for i in range(16)] for _ in range(4)], dtype="uint8") # 2 blocks | ||
| 1312 | labels = ct.array([[1, 2, 0, 0] for _ in range(1024)], (1024, 4), "int16", -1, 255) | ||
| 1313 | anchors = ct.array([7] * 128, (128,), "uint16", 0, 65535) | ||
| 1314 | seed = ct.array([[[0, 8] for _ in range(56)] for _ in range(256)], (256, 56, 2), "uint8", 0, 255) | ||
| 1315 | |||
| 1316 | b0 = bytes(range(16)) | ||
| 1317 | b1 = bytes(range(16, 32)) | ||
| 1318 | seen = {} | ||
| 1319 | |||
| 1320 | def fake_rebuild(s_ptr, count, lab_ptr, seed_ptr, anc_ptr, out_ptr, ok_ptr): | ||
| 1321 | seen["args"] = (s_ptr, count, lab_ptr, seed_ptr, anc_ptr, out_ptr, ok_ptr) | ||
| 1322 | seen["s_bytes"] = _read_u8_buf(s_ptr, count * 32) | ||
| 1323 | _write_u8_buf(out_ptr, b0 + b1) | ||
| 1324 | _write_u8_buf(ok_ptr, bytes([1, 0])) | ||
| 1325 | |||
| 1326 | with _fake_native_context(rebuild_fn=fake_rebuild) as lib: | ||
| 1327 | out, ok = ct.bc7_blocks(sy, (labels, anchors), seed) | ||
| 1328 | self.assertEqual(lib.rebuild.call_count, 1) | ||
| 1329 | self.assertEqual(seen["args"][1], 2) | ||
| 1330 | self.assertEqual(seen["args"][2], labels.ctypes.data) | ||
| 1331 | self.assertEqual(seen["args"][3], seed.ctypes.data) | ||
| 1332 | self.assertEqual(seen["args"][4], anchors.ctypes.data) | ||
| 1333 | self.assertEqual(seen["s_bytes"], sy.tobytes()) | ||
| 1334 | self.assertEqual(out.tobytes(), b0 + b1) | ||
| 1335 | self.assertEqual(ok.tolist(), [True, False]) | ||
| 1336 | |||
| 1337 | # Zero blocks | ||
| 1338 | empty_sy = np.zeros((0, 16), dtype="uint8") | ||
| 1339 | with _fake_native_context() as lib: | ||
| 1340 | out0, ok0 = ct.bc7_blocks(empty_sy, (labels, anchors), seed) | ||
| 1341 | self.assertEqual(out0.shape, (0,)) | ||
| 1342 | self.assertEqual(ok0.shape, (0,)) | ||
| 1343 | self.assertEqual(lib.rebuild.call_args[0][1], 0) | ||
| 1344 | |||
| 1345 | def test_scalar_bc4_parity_and_missing_slot(self): | ||
| 1346 | table = dict(bcpack_tables.BC4_HISTORY_PROVISIONAL) | ||
| 1347 | # Block 0: d=0; Block 1: d=1; Block 2: external slot 25 (d=256+2-25=233 -> unzig(-23)) | ||
| 1348 | d2 = tb._zig(-23) | ||
| 1349 | lanes = [ | ||
| 1350 | [0, tb._zig(1), d2], | ||
| 1351 | [0, 0, 0], | ||
| 1352 | [tb._zig(30), tb._zig(-50), tb._zig(-100)], | ||
| 1353 | [tb._zig(-120), tb._zig(45), tb._zig(20)], | ||
| 1354 | [0, 12, 33], [1, 15, 44], [2, 20, 55], [3, 25, 63], | ||
| 1355 | [4, 30, 7], [5, 35, 8], [6, 40, 9], [7, 45, 10], | ||
| 1356 | ] | ||
| 1357 | sy = np.ascontiguousarray(np.asarray(lanes, dtype="uint8").T) | ||
| 1358 | got = ct.scalar_bc4(sy, table) | ||
| 1359 | expected = bcpack._bc4_blocks(lanes, 3, set()) | ||
| 1360 | self.assertEqual(got, expected) | ||
| 1361 | |||
| 1362 | with self.assertRaises(KeyError): | ||
| 1363 | ct.scalar_bc4(sy, {}) | ||
| 1364 | |||
| 1365 | def test_local_bc5_parity_and_missing_slot(self): | ||
| 1366 | # Block 0: confirmed entry 182 (d=256+0-182=74) | ||
| 1367 | # Block 1: d=1 (chains onto Block 0) | ||
| 1368 | # Block 2: provisional entry 3 (d=256+2-3=255 -> -1 mod 256) | ||
| 1369 | # Block 3: distance=0 (seed 128) | ||
| 1370 | # local_bc5 uses compatibility endpoint ordering where s[:, 0, 2:4] holds | ||
| 1371 | # (r0, r1) and s[:, 1, 2:4] holds (g0, g1), while selector lanes 4..11 | ||
| 1372 | # match bcpack._bc5_blocks identically. | ||
| 1373 | d0a, d0b = tb._deint4(tb._zig(74) & 255) | ||
| 1374 | d1a, d1b = tb._deint4(tb._zig(1) & 255) | ||
| 1375 | d2a, d2b = tb._deint4(tb._zig(-1) & 255) | ||
| 1376 | lanes = [[] for _ in range(12)] | ||
| 1377 | lanes[0] = [d0a, d0b, d1a, d1b, d2a, d2b, 0, 0] | ||
| 1378 | lanes[1] = [0] * 8 | ||
| 1379 | lanes[2] = [tb._zig(10), tb._zig(-20), tb._zig(5), tb._zig(-15), tb._zig(30), tb._zig(40), tb._zig(-60), tb._zig(70)] | ||
| 1380 | lanes[3] = [tb._zig(-5), tb._zig(25), tb._zig(-10), tb._zig(35), tb._zig(-40), tb._zig(12), tb._zig(80), tb._zig(-90)] | ||
| 1381 | for ln in range(4, 12): | ||
| 1382 | lanes[ln] = [(ln * 7 + k * 5) & 63 for k in range(8)] | ||
| 1383 | sy = np.ascontiguousarray(np.asarray(lanes, dtype="uint8").T) | ||
| 1384 | got = ct.local_bc5(sy) | ||
| 1385 | |||
| 1386 | # Verify selector bytes (bytes 2..7 and 10..15 of each 16-byte block) match bcpack._bc5_blocks, | ||
| 1387 | # and endpoint bytes match the compatibility ordering against BC5_HISTORY_* tables. | ||
| 1388 | ref = bcpack._bc5_blocks(lanes, 4, set()) | ||
| 1389 | self.assertEqual(len(got), 64) | ||
| 1390 | h182 = bcpack_tables.BC5_HISTORY_CONFIRMED[182] | ||
| 1391 | h3 = bcpack_tables.BC5_HISTORY_PROVISIONAL[3] | ||
| 1392 | # Block 0: base h182 reshaped (2, 2) -> [[h182[0], h182[1]], [h182[2], h182[3]]] | ||
| 1393 | b0_ep = ( | ||
| 1394 | (h182[0] + 10) % 256, | ||
| 1395 | (h182[1] - 5) % 256, | ||
| 1396 | (h182[2] - 20) % 256, | ||
| 1397 | (h182[3] + 25) % 256, | ||
| 1398 | ) | ||
| 1399 | # Block 1: chains onto Block 0 | ||
| 1400 | b1_ep = ( | ||
| 1401 | (b0_ep[0] + 5) % 256, | ||
| 1402 | (b0_ep[1] - 10) % 256, | ||
| 1403 | (b0_ep[2] - 15) % 256, | ||
| 1404 | (b0_ep[3] + 35) % 256, | ||
| 1405 | ) | ||
| 1406 | # Block 2: base h3 | ||
| 1407 | b2_ep = ( | ||
| 1408 | (h3[0] + 30) % 256, | ||
| 1409 | (h3[1] - 40) % 256, | ||
| 1410 | (h3[2] + 40) % 256, | ||
| 1411 | (h3[3] + 12) % 256, | ||
| 1412 | ) | ||
| 1413 | # Block 3: d=0 -> seed (128, 128, 128, 128) | ||
| 1414 | b3_ep = ((128 - 60) % 256, (128 + 80) % 256, (128 + 70) % 256, (128 - 90) % 256) | ||
| 1415 | for bi, ep in enumerate((b0_ep, b1_ep, b2_ep, b3_ep)): | ||
| 1416 | off = bi * 16 | ||
| 1417 | self.assertEqual((got[off], got[off + 1], got[off + 8], got[off + 9]), ep) | ||
| 1418 | self.assertEqual(got[off + 2 : off + 8], ref[off + 2 : off + 8]) | ||
| 1419 | self.assertEqual(got[off + 10 : off + 16], ref[off + 10 : off + 16]) | ||
| 1420 | |||
| 1421 | # Unknown history entry 1 (neither confirmed nor provisional) raises KeyError. | ||
| 1422 | u0a, u0b = tb._deint4(tb._zig(-1) & 255) | ||
| 1423 | bad_lanes = [[u0a, u0b] if k == 0 else [0, 0] for k in range(12)] | ||
| 1424 | bad_sy = np.ascontiguousarray(np.asarray(bad_lanes, dtype="uint8").T) | ||
| 1425 | with self.assertRaises(KeyError): | ||
| 1426 | ct.local_bc5(bad_sy) | ||
| 1427 | |||
| 1428 | def test_local_bc3_parity_and_missing_slot(self): | ||
| 1429 | profile = _bc3_profile_from_tables() | ||
| 1430 | # Block 0: d=0 (slot -512) | ||
| 1431 | # Block 1: d=1 (chains onto Block 0) | ||
| 1432 | # Block 2: provisional entry 26 (d=256+2-26=232 -> unzig(-24) & 255) | ||
| 1433 | d0a, d0b = 0, 0 | ||
| 1434 | d1a, d1b = tb._deint4(tb._zig(1) & 255) | ||
| 1435 | d2a, d2b = tb._deint4(tb._zig(-24) & 255) | ||
| 1436 | lanes = [[] for _ in range(12)] | ||
| 1437 | lanes[0] = [d0a, d0b, d1a, d1b, d2a, d2b] | ||
| 1438 | lanes[1] = [0] * 6 | ||
| 1439 | lanes[2] = [tb._zig(20), tb._zig(-30), tb._zig(5), tb._zig(-10), tb._zig(40), tb._zig(-50)] | ||
| 1440 | for ln in range(3, 7): | ||
| 1441 | lanes[ln] = [(ln * 11 + k * 7) & 63 for k in range(6)] | ||
| 1442 | lanes[7] = [tb._zig(7), tb._zig(-3), tb._zig(4), tb._zig(-2), tb._zig(12), tb._zig(-8)] | ||
| 1443 | lanes[8] = [tb._zig(-15), tb._zig(22), tb._zig(3), tb._zig(-9), tb._zig(18), tb._zig(25)] | ||
| 1444 | lanes[9] = [tb._zig(9), tb._zig(-12), tb._zig(-1), tb._zig(6), tb._zig(-14), tb._zig(11)] | ||
| 1445 | lanes[10] = [12, 45, 78, 123, 200, 251] | ||
| 1446 | lanes[11] = [33, 67, 101, 144, 188, 229] | ||
| 1447 | |||
| 1448 | sy = np.ascontiguousarray(np.asarray(lanes, dtype="uint8").T) | ||
| 1449 | got = ct.local_bc3(sy, profile) | ||
| 1450 | expected = bcpack._bc3_blocks(lanes, 3, set()) | ||
| 1451 | self.assertEqual(got, expected) | ||
| 1452 | |||
| 1453 | with self.assertRaises(KeyError): | ||
| 1454 | ct.local_bc3(sy, {"endpoints": {}, "color": profile["color"], "alpha": profile["alpha"]}) | ||
| 1455 | |||
| 1456 | |||
| 1457 | class TestLocalDecoder(unittest.TestCase): | ||
| 1458 | def setUp(self): | ||
| 1459 | tmp = tempfile.TemporaryDirectory() | ||
| 1460 | self.addCleanup(tmp.cleanup) | ||
| 1461 | self.root = Path(tmp.name) | ||
| 1462 | |||
| 1463 | def _open_pool(self, name, records, chunks): | ||
| 1464 | path = self.root / name | ||
| 1465 | base = write_custom_pool(path, records, chunks) | ||
| 1466 | pool = ttpf.Pool(str(path)) | ||
| 1467 | self.addCleanup(pool.close) | ||
| 1468 | return pool, base | ||
| 1469 | |||
| 1470 | def test_init_rejects_bad_calibration_versions_and_isolates_cache(self): | ||
| 1471 | pool, base = self._open_pool( | ||
| 1472 | "raw.ttpf", | ||
| 1473 | [ttm.pack_etpf_record(64, 64, 1, 0, 71, 1, 1, 4, 4096)], | ||
| 1474 | [(0, b"\xAA" * 4096, 4096)], | ||
| 1475 | ) | ||
| 1476 | for bad in (None, [], "v1", 1, {}, {"version": 0}, {"version": 2}, {"version": "1"}): | ||
| 1477 | with self.subTest(bad=bad): | ||
| 1478 | with self.assertRaisesRegex(ValueError, "Unsupported calibration version"): | ||
| 1479 | ct.LocalDecoder(pool, bad) | ||
| 1480 | |||
| 1481 | dec1 = ct.LocalDecoder(pool, {"version": 1}) | ||
| 1482 | dec2 = ct.LocalDecoder(pool, {"version": 1}) | ||
| 1483 | self.assertEqual(dec1.edges.tolist(), [base, base + 4096]) | ||
| 1484 | b1, m1 = dec1.read_chunk(0, 8, "base") | ||
| 1485 | self.assertIsNone(m1) | ||
| 1486 | self.assertEqual(len(b1), 512) | ||
| 1487 | self.assertEqual(dec1.read_chunk.cache_info().currsize, 1) | ||
| 1488 | self.assertEqual(dec2.read_chunk.cache_info().currsize, 0) | ||
| 1489 | |||
| 1490 | def test_seed_validation_precision_and_caching(self): | ||
| 1491 | pool, _ = self._open_pool( | ||
| 1492 | "dummy.ttpf", | ||
| 1493 | [ttm.pack_etpf_record(64, 64, 1, 0, 98, 1, 1, 4, 4096)], | ||
| 1494 | [(0, b"\x00" * 4096, 4096)], | ||
| 1495 | ) | ||
| 1496 | cal = {"version": 1, "bc7": _empty_bc7_section()} | ||
| 1497 | dec = ct.LocalDecoder(pool, cal) | ||
| 1498 | s1 = dec.seed("base") | ||
| 1499 | s2 = dec.seed("base") | ||
| 1500 | self.assertIs(s1, s2) | ||
| 1501 | with self.assertRaises(KeyError): | ||
| 1502 | dec.seed("nonexistent") | ||
| 1503 | |||
| 1504 | cal["bc7"]["seeds"]["bad_prec"] = [[[0, 9] for _ in range(56)] for _ in range(256)] | ||
| 1505 | with self.assertRaisesRegex(ValueError, "Invalid history precision"): | ||
| 1506 | dec.seed("bad_prec") | ||
| 1507 | |||
| 1508 | def test_symbols_native_fallback_compatibility_and_errors(self): | ||
| 1509 | # Build a valid 64x64 1-mip BC1 BCPack chunk (512 blocks = 4096 bytes) | ||
| 1510 | layout = ttpf.surface_layout(64, 64, 71, 1, 4096) | ||
| 1511 | linear = ttm.solid_chain(layout, 71)[0] | ||
| 1512 | tiled = bytearray(layout["size"]) | ||
| 1513 | ttm.retile_to(layout, layout["mips"][0], linear, tiled) | ||
| 1514 | packed_bc1 = tb.encode_bc1_blocks(bytes(tiled)) | ||
| 1515 | chunk_sha = hashlib.sha256(packed_bc1).hexdigest() | ||
| 1516 | |||
| 1517 | # Chunk 0: valid BC1 BCPack | ||
| 1518 | # Chunk 1: valid BC1 BCPack with an extra trailing 0x00 byte so decode_lanes consumes < packed | ||
| 1519 | # Chunk 2: valid BC4 BCPack (unused compatibility branch when codec != 1) | ||
| 1520 | bc4_lanes = [[0] * 512 for _ in range(12)] | ||
| 1521 | packed_bc4 = _encode_bc4_from_lanes(bc4_lanes) | ||
| 1522 | pool, _ = self._open_pool( | ||
| 1523 | "syms.ttpf", | ||
| 1524 | [ttm.pack_etpf_record(64, 64, 1, 0, 71, 1, 1, 4, 4096)], | ||
| 1525 | [ | ||
| 1526 | (1, packed_bc1, 4096), | ||
| 1527 | (1, packed_bc1 + b"\x00", 4096), | ||
| 1528 | (4, packed_bc4, 4096), | ||
| 1529 | ], | ||
| 1530 | ) | ||
| 1531 | |||
| 1532 | # 1. Native unpack succeeds (returns packed) -> bcpack.decode_lanes is NOT called. | ||
| 1533 | dec_nat = ct.LocalDecoder(pool, {"version": 1}) | ||
| 1534 | expected_lanes, _ = bcpack.decode_lanes(packed_bc1, 1, 4096) | ||
| 1535 | expected_sy = np.ascontiguousarray(np.asarray(expected_lanes, dtype="uint8").T) | ||
| 1536 | |||
| 1537 | def fake_unpack(raw, packed, widths_bytes, nlanes, nsym, sy_ptr): | ||
| 1538 | self.assertEqual(raw, packed_bc1) | ||
| 1539 | self.assertEqual(packed, len(packed_bc1)) | ||
| 1540 | self.assertEqual(widths_bytes, bytes(w - 1 for w in bcpack.LANE_WIDTHS[1])) | ||
| 1541 | self.assertEqual(nlanes, 12) | ||
| 1542 | self.assertEqual(nsym, 512) | ||
| 1543 | _write_u8_buf(sy_ptr, expected_sy.tobytes()) | ||
| 1544 | return packed | ||
| 1545 | |||
| 1546 | with _fake_native_context(unpack_fn=fake_unpack), \ | ||
| 1547 | mock.patch.object(bcpack, "decode_lanes", side_effect=AssertionError("unexpected fallback")): | ||
| 1548 | got_sy = dec_nat.symbols(0) | ||
| 1549 | self.assertEqual(got_sy.tobytes(), expected_sy.tobytes()) | ||
| 1550 | |||
| 1551 | # 2. Native unpack returns -1 -> falls back to bcpack.decode_lanes. | ||
| 1552 | with _fake_native_context(): | ||
| 1553 | got_fallback = dec_nat.symbols(0) | ||
| 1554 | self.assertEqual(got_fallback.tobytes(), expected_sy.tobytes()) | ||
| 1555 | |||
| 1556 | # 3. Trailing unstripped zero byte makes consumed != packed -> ValueError. | ||
| 1557 | with _fake_native_context(): | ||
| 1558 | with self.assertRaisesRegex(ValueError, "Entropy decode failed for chunk 1"): | ||
| 1559 | dec_nat.symbols(1) | ||
| 1560 | |||
| 1561 | # 4. Compatibility rotation on codec 1 rotates selected flat positions left by 1. | ||
| 1562 | cycle = [1, 5, 13] | ||
| 1563 | dec_rot = ct.LocalDecoder(pool, {"version": 1, "compatibility": {chunk_sha: cycle}}) | ||
| 1564 | with _fake_native_context(): | ||
| 1565 | rotated = dec_rot.symbols(0) | ||
| 1566 | flat_orig = expected_sy.ravel().tolist() | ||
| 1567 | flat_rot = rotated.ravel().tolist() | ||
| 1568 | self.assertEqual(flat_rot[1], flat_orig[5]) | ||
| 1569 | self.assertEqual(flat_rot[5], flat_orig[13]) | ||
| 1570 | self.assertEqual(flat_rot[13], flat_orig[1]) | ||
| 1571 | for idx in range(len(flat_orig)): | ||
| 1572 | if idx not in cycle: | ||
| 1573 | self.assertEqual(flat_rot[idx], flat_orig[idx]) | ||
| 1574 | |||
| 1575 | # 5. Compatibility rotation errors (duplicate, out-of-range, negative, non-int including bool). | ||
| 1576 | for bad_cycle in ([0, 0], [-1], [expected_sy.size], [True], [1.0], ["0"]): | ||
| 1577 | with self.subTest(bad_cycle=bad_cycle): | ||
| 1578 | dec_bad = ct.LocalDecoder( | ||
| 1579 | pool, {"version": 1, "compatibility": {chunk_sha: bad_cycle}} | ||
| 1580 | ) | ||
| 1581 | with _fake_native_context(): | ||
| 1582 | with self.assertRaisesRegex(ValueError, "Invalid symbol rotation"): | ||
| 1583 | dec_bad.symbols(0) | ||
| 1584 | |||
| 1585 | # 6. Compatibility does NOT run for non-BC1 codecs, empty cycle, or unknown sha. | ||
| 1586 | bc4_sha = hashlib.sha256(packed_bc4).hexdigest() | ||
| 1587 | dec_bc4 = ct.LocalDecoder(pool, {"version": 1, "compatibility": {bc4_sha: [0, 0]}}) | ||
| 1588 | with _fake_native_context(): | ||
| 1589 | sy4 = dec_bc4.symbols(2) | ||
| 1590 | self.assertEqual(sy4.shape, (512, 12)) | ||
| 1591 | |||
| 1592 | dec_noop = ct.LocalDecoder( | ||
| 1593 | pool, | ||
| 1594 | {"version": 1, "compatibility": {chunk_sha: [], "0" * 64: [0, 1]}}, | ||
| 1595 | ) | ||
| 1596 | with _fake_native_context(): | ||
| 1597 | self.assertEqual(dec_noop.symbols(0).tobytes(), expected_sy.tobytes()) | ||
| 1598 | |||
| 1599 | def test_read_chunk_errors_and_all_codecs(self): | ||
| 1600 | # Raw (codec 0), zlib (codec 8), and bad-length zlib chunk | ||
| 1601 | raw_bytes = bytes((i & 0xFF) for i in range(4096)) | ||
| 1602 | zlib_bytes = zlib.compress(raw_bytes) | ||
| 1603 | bad_zlib = zlib.compress(raw_bytes[:2048]) | ||
| 1604 | |||
| 1605 | # Codec 6 (BC6H) and Codec 7 (BC7) | ||
| 1606 | packed_bc6h = _encode_bc6h_solid(256) | ||
| 1607 | packed_bc7 = _encode_bc7_mode6_solid(256) | ||
| 1608 | |||
| 1609 | pool, _ = self._open_pool( | ||
| 1610 | "codecs.ttpf", | ||
| 1611 | [ttm.pack_etpf_record(64, 64, 1, 0, 71, 1, 1, 4, 4096)], | ||
| 1612 | [ | ||
| 1613 | (0, raw_bytes, 4096), | ||
| 1614 | (8, zlib_bytes, 4096), | ||
| 1615 | (8, bad_zlib, 4096), | ||
| 1616 | (6, packed_bc6h, 4096), | ||
| 1617 | (7, packed_bc7, 4096), | ||
| 1618 | ], | ||
| 1619 | ) | ||
| 1620 | cal = { | ||
| 1621 | "version": 1, | ||
| 1622 | "bc6h": {}, | ||
| 1623 | "bc7": _empty_bc7_section(), | ||
| 1624 | } | ||
| 1625 | dec = ct.LocalDecoder(pool, cal) | ||
| 1626 | |||
| 1627 | # Size/block-size/codec mismatches (including unknown codec 99) | ||
| 1628 | with self.assertRaisesRegex(ValueError, "Block size and codec disagree"): | ||
| 1629 | dec.read_chunk(0, 7, "base") # 4096 % 7 != 0 | ||
| 1630 | with self.assertRaisesRegex(ValueError, "Block size and codec disagree"): | ||
| 1631 | dec.read_chunk(3, 8, "base") # codec 6 is 16-byte blocks, not 8 | ||
| 1632 | orig_chunks = list(pool.chunks) | ||
| 1633 | try: | ||
| 1634 | pool.chunks = orig_chunks + [(0, 4096, 0, 4096, 99, 0)] | ||
| 1635 | with self.assertRaisesRegex(ValueError, "Block size and codec disagree"): | ||
| 1636 | dec.read_chunk(len(orig_chunks), 16, "base") | ||
| 1637 | finally: | ||
| 1638 | pool.chunks = orig_chunks | ||
| 1639 | |||
| 1640 | # Raw & zlib | ||
| 1641 | b_raw, m_raw = dec.read_chunk(0, 8, "base") | ||
| 1642 | self.assertIsNone(m_raw) | ||
| 1643 | self.assertEqual(b_raw.tobytes(), raw_bytes) | ||
| 1644 | b_z, m_z = dec.read_chunk(1, 16, "base") | ||
| 1645 | self.assertIsNone(m_z) | ||
| 1646 | self.assertEqual(b_z.tobytes(), raw_bytes) | ||
| 1647 | with self.assertRaisesRegex(ValueError, "Invalid raw chunk length"): | ||
| 1648 | dec.read_chunk(2, 8, "base") | ||
| 1649 | |||
| 1650 | # BC6H delegates to bcpack._bc6h_blocks | ||
| 1651 | with _fake_native_context(): | ||
| 1652 | b6, m6 = dec.read_chunk(3, 16, "base") | ||
| 1653 | self.assertIsNone(m6) | ||
| 1654 | self.assertEqual(b6.tobytes(), bcpack.decode(packed_bc6h, 6, 4096)) | ||
| 1655 | |||
| 1656 | # BC7 profile cascades: early (1 call), base (early stop if all valid), base->secondary, refined->3 | ||
| 1657 | call_seeds = [] | ||
| 1658 | |||
| 1659 | def rebuild_early_stop(s_ptr, count, lab_ptr, seed_ptr, anc_ptr, out_ptr, ok_ptr): | ||
| 1660 | call_seeds.append(_read_u8_buf(seed_ptr, 8)) | ||
| 1661 | _write_u8_buf(out_ptr, b"\x11" * (count * 16)) | ||
| 1662 | _write_u8_buf(ok_ptr, b"\x01" * count) | ||
| 1663 | |||
| 1664 | with _fake_native_context(rebuild_fn=rebuild_early_stop): | ||
| 1665 | b7_base, m7_base = dec.read_chunk(4, 16, "base") | ||
| 1666 | self.assertEqual(len(call_seeds), 1) | ||
| 1667 | self.assertTrue(m7_base.all()) | ||
| 1668 | self.assertEqual(b7_base.tobytes(), b"\x11" * 4096) | ||
| 1669 | |||
| 1670 | call_seeds.clear() | ||
| 1671 | dec.read_chunk(4, 16, "early") | ||
| 1672 | self.assertEqual(len(call_seeds), 1) | ||
| 1673 | |||
| 1674 | # Partial fill across base -> secondary -> refined | ||
| 1675 | cal2 = {"version": 1, "bc7": _empty_bc7_section()} | ||
| 1676 | # Mark first byte of each seed so mocked rebuild distinguishes them | ||
| 1677 | cal2["bc7"]["seeds"]["base"][0][0] = [1, 8] | ||
| 1678 | cal2["bc7"]["seeds"]["secondary"][0][0] = [2, 8] | ||
| 1679 | cal2["bc7"]["seeds"]["refined"][0][0] = [3, 8] | ||
| 1680 | dec2 = ct.LocalDecoder(pool, cal2) | ||
| 1681 | seen_tags = [] | ||
| 1682 | |||
| 1683 | def rebuild_cascading(s_ptr, count, lab_ptr, seed_ptr, anc_ptr, out_ptr, ok_ptr): | ||
| 1684 | tag = _read_u8_buf(seed_ptr, 1)[0] | ||
| 1685 | seen_tags.append(tag) | ||
| 1686 | out_buf = bytearray(count * 16) | ||
| 1687 | ok_buf = bytearray(count) | ||
| 1688 | for idx in range(count): | ||
| 1689 | if (tag == 1 and idx % 3 == 0) or (tag == 2 and idx % 3 == 1): | ||
| 1690 | out_buf[idx * 16 : (idx + 1) * 16] = bytes([tag]) * 16 | ||
| 1691 | ok_buf[idx] = 1 | ||
| 1692 | elif tag == 3 and idx == 2: | ||
| 1693 | out_buf[idx * 16 : (idx + 1) * 16] = bytes([3]) * 16 | ||
| 1694 | ok_buf[idx] = 1 | ||
| 1695 | _write_u8_buf(out_ptr, bytes(out_buf)) | ||
| 1696 | _write_u8_buf(ok_ptr, bytes(ok_buf)) | ||
| 1697 | |||
| 1698 | with _fake_native_context(rebuild_fn=rebuild_cascading): | ||
| 1699 | blocks, valid = dec2.read_chunk(4, 16, "refined") | ||
| 1700 | self.assertEqual(seen_tags, [1, 2, 3]) | ||
| 1701 | self.assertTrue(bool(valid[0]) and bool(valid[1]) and bool(valid[2])) | ||
| 1702 | self.assertFalse(bool(valid[5])) # 5 % 3 == 2, != 2 | ||
| 1703 | self.assertEqual(blocks.tobytes()[:48], b"\x01" * 16 + b"\x02" * 16 + b"\x03" * 16) | ||
| 1704 | |||
| 1705 | def test_surface_bounds_multichunk_and_bc7_adjustments(self): | ||
| 1706 | # Chunk 0: 4096 bytes raw (bs=16, 256 blocks) | ||
| 1707 | # Chunk 1: 4096 bytes BC7 (bs=16, 256 blocks) | ||
| 1708 | c0 = b"".join(bytes([i & 0xFF]) * 16 for i in range(256)) | ||
| 1709 | c1 = _encode_bc7_mode6_solid(256) | ||
| 1710 | pool, base = self._open_pool( | ||
| 1711 | "surface.ttpf", | ||
| 1712 | [ttm.pack_etpf_record(64, 64, 1, 0, 98, 1, 1, 4, 4096)], | ||
| 1713 | [(0, c0, 4096), (7, c1, 4096)], | ||
| 1714 | ) | ||
| 1715 | cal = {"version": 1, "bc7": _empty_bc7_section()} | ||
| 1716 | dec = ct.LocalDecoder(pool, cal) | ||
| 1717 | |||
| 1718 | # Empty address array returns empty bytes cleanly | ||
| 1719 | self.assertEqual(dec.surface(np.array([], dtype="int64"), 16, "base"), b"") | ||
| 1720 | |||
| 1721 | # Out of bounds | ||
| 1722 | for bad_at in ([base - 16], [base + 8192], [base, base + 10000]): | ||
| 1723 | with self.subTest(bad_at=bad_at): | ||
| 1724 | with self.assertRaisesRegex(ValueError, "Texture exceeds virtual pool"): | ||
| 1725 | dec.surface(np.array(bad_at, dtype="int64"), 16, "base") | ||
| 1726 | |||
| 1727 | # Non-monotonic multi-chunk lookup where unreferenced blocks in chunk 1 remain unresolved | ||
| 1728 | def rebuild_partial(s_ptr, count, lab_ptr, seed_ptr, anc_ptr, out_ptr, ok_ptr): | ||
| 1729 | seed_bytes = _read_u8_buf(seed_ptr, 256 * 56 * 2) | ||
| 1730 | # Check if adjustment patched seed[7, 3] = (99, 8) | ||
| 1731 | patched = seed_bytes[(7 * 56 + 3) * 2 : (7 * 56 + 3) * 2 + 2] == bytes([99, 8]) | ||
| 1732 | out_buf = bytearray(count * 16) | ||
| 1733 | ok_buf = bytearray(count) | ||
| 1734 | for idx in range(count): | ||
| 1735 | if idx == 10: | ||
| 1736 | out_buf[idx * 16 : (idx + 1) * 16] = b"\xAA" * 16 | ||
| 1737 | ok_buf[idx] = 1 | ||
| 1738 | elif idx == 20 and patched: | ||
| 1739 | out_buf[idx * 16 : (idx + 1) * 16] = b"\xBB" * 16 | ||
| 1740 | ok_buf[idx] = 1 | ||
| 1741 | _write_u8_buf(out_ptr, bytes(out_buf)) | ||
| 1742 | _write_u8_buf(ok_ptr, bytes(ok_buf)) | ||
| 1743 | |||
| 1744 | with _fake_native_context(rebuild_fn=rebuild_partial): | ||
| 1745 | # Request block 10 of chunk 1 (resolved), block 5 of chunk 0, block 0 of chunk 0 | ||
| 1746 | at_ok = np.array([base + 4096 + 10 * 16, base + 5 * 16, base], dtype="int64") | ||
| 1747 | got_ok = dec.surface(at_ok, 16, "base") | ||
| 1748 | self.assertEqual(got_ok, b"\xAA" * 16 + bytes([5]) * 16 + bytes([0]) * 16) | ||
| 1749 | |||
| 1750 | # Request unresolved block 20 with profile != "refined" -> Missing calibrated blocks | ||
| 1751 | at_miss = np.array([base + 4096 + 10 * 16, base + 4096 + 20 * 16], dtype="int64") | ||
| 1752 | with self.assertRaisesRegex(ValueError, "Missing calibrated blocks"): | ||
| 1753 | dec.surface(at_miss, 16, "base") | ||
| 1754 | |||
| 1755 | # Refined profile: compute exact sha256 key expected by LocalDecoder.surface | ||
| 1756 | sy1 = dec.symbols(1) | ||
| 1757 | miss_ix = np.array([20], dtype="<i8") | ||
| 1758 | adj_key = hashlib.sha256(sy1.tobytes() + miss_ix.tobytes()).hexdigest() | ||
| 1759 | |||
| 1760 | # Bad fitted endpoint bounds | ||
| 1761 | for bad_adj in ( | ||
| 1762 | [(256, 0, 0)], | ||
| 1763 | [(-1, 0, 0)], | ||
| 1764 | [(0, 24, 0)], | ||
| 1765 | [(0, -1, 0)], | ||
| 1766 | [(0, 0, 256)], | ||
| 1767 | [(0, 0, -1)], | ||
| 1768 | ): | ||
| 1769 | cal["bc7"]["adjustments"][adj_key] = bad_adj | ||
| 1770 | with self.assertRaisesRegex(ValueError, "Invalid fitted endpoint"): | ||
| 1771 | dec.surface(at_miss, 16, "refined") | ||
| 1772 | |||
| 1773 | # Valid bounds that still fail to resolve block 20 -> Incomplete calibrated endpoints | ||
| 1774 | cal["bc7"]["adjustments"][adj_key] = [(7, 3, 42)] | ||
| 1775 | with self.assertRaisesRegex(ValueError, "Incomplete calibrated endpoints"): | ||
| 1776 | dec.surface(at_miss, 16, "refined") | ||
| 1777 | |||
| 1778 | # Valid adjustment resolves block 20 without mutating cached refined seed! | ||
| 1779 | cal["bc7"]["adjustments"][adj_key] = [(7, 3, 99)] | ||
| 1780 | got_ref = dec.surface(at_miss, 16, "refined") | ||
| 1781 | self.assertEqual(got_ref, b"\xAA" * 16 + b"\xBB" * 16) | ||
| 1782 | self.assertEqual(dec.seed("refined").tobytes()[(7 * 56 + 3) * 2 : (7 * 56 + 3) * 2 + 2], b"\x00\x08") | ||
| 1783 | |||
| 1784 | def test_dds_end_to_end_codecs_and_layouts(self): | ||
| 1785 | # 1. BC3 (fmt 77, codec 3), BC4 (fmt 80, codec 4), BC5 (fmt 83, codec 5), | ||
| 1786 | # BC6H (fmt 95, codec 6), BC7 (fmt 98, codec 7) across 4K/64K, partial mips, | ||
| 1787 | # non-square, all-tail, single-mip, and multi-chunk spans. | ||
| 1788 | for fmt, codec, w, h, mips, mode in ( | ||
| 1789 | (77, 3, 64, 32, 6, 4), # BC3, 4K tile, non-square | ||
| 1790 | (80, 4, 16, 16, 5, 4), # BC4, 4K tile, all-tail (first_tail == 0) | ||
| 1791 | (83, 5, 64, 64, 1, 4), # BC5, 4K tile, single-mip | ||
| 1792 | (95, 6, 64, 64, 5, 4), # BC6H, 4K tile | ||
| 1793 | (98, 7, 16, 16, 1, 0), # BC7, 64K tile, small single-mip | ||
| 1794 | ): | ||
| 1795 | with self.subTest(fmt=fmt, codec=codec, dims=(w, h, mips)): | ||
| 1796 | tile = ttpf.tile_bytes(mode) | ||
| 1797 | lay = ttpf.surface_layout(w, h, fmt, mips, tile) | ||
| 1798 | linear = ttm.solid_chain(lay, fmt) | ||
| 1799 | tiled = bytearray(lay["size"]) | ||
| 1800 | for m in lay["mips"]: | ||
| 1801 | ttm.retile_to(lay, m, linear[m["index"]], tiled) | ||
| 1802 | |||
| 1803 | eb = lay["element_bytes"] | ||
| 1804 | nblocks = lay["size"] // eb | ||
| 1805 | if codec == 3: | ||
| 1806 | inv_pair = {p: i for i, p in enumerate(bcpack_tables.BC3_ALPHA_PAIR)} | ||
| 1807 | inv_quad = {v: i for i, v in enumerate(bcpack_tables.BC3_COLOUR_QUADRANT)} | ||
| 1808 | lanes = [[] for _ in range(12)] | ||
| 1809 | prev = (128, 128, 0, 0, 0, 0, 0, 0) | ||
| 1810 | for i in range(nblocks): | ||
| 1811 | blk = tiled[i * 16 : (i + 1) * 16] | ||
| 1812 | a0, a1 = blk[0], blk[1] | ||
| 1813 | abits = int.from_bytes(blk[2:8], "little") | ||
| 1814 | c0, c1, r0, r1, r2, r3 = struct.unpack_from("<HHBBBB", blk, 8) | ||
| 1815 | ep = ( | ||
| 1816 | a0, a1, | ||
| 1817 | (c0 >> 11) & 31, (c0 >> 5) & 63, c0 & 31, | ||
| 1818 | (c1 >> 11) & 31, (c1 >> 5) & 63, c1 & 31, | ||
| 1819 | ) | ||
| 1820 | mods = bcpack._BC3_MODS | ||
| 1821 | deltas = [((ep[k] - prev[k] + mods[k] // 2) % mods[k]) - mods[k] // 2 for k in range(8)] | ||
| 1822 | # Use d=0 on block 0, d=1 afterwards | ||
| 1823 | if i == 0: | ||
| 1824 | lanes[0].extend([0, 0]) | ||
| 1825 | else: | ||
| 1826 | d1a, d1b = tb._deint4(tb._zig(1) & 255) | ||
| 1827 | lanes[0].extend([d1a, d1b]) | ||
| 1828 | lanes[1].extend([0, 0]) | ||
| 1829 | lanes[2].extend([tb._zig(deltas[0]), tb._zig(deltas[1])]) | ||
| 1830 | for r in range(4): | ||
| 1831 | row = (abits >> (12 * r)) & 0xFFF | ||
| 1832 | lanes[3 + r].extend([ | ||
| 1833 | inv_pair[(row & 7, (row >> 3) & 7)], | ||
| 1834 | inv_pair[((row >> 6) & 7, (row >> 9) & 7)], | ||
| 1835 | ]) | ||
| 1836 | lanes[7].extend([tb._zig(deltas[2]), tb._zig(deltas[5])]) | ||
| 1837 | lanes[8].extend([tb._zig(deltas[3]), tb._zig(deltas[6])]) | ||
| 1838 | lanes[9].extend([tb._zig(deltas[4]), tb._zig(deltas[7])]) | ||
| 1839 | qa = (r0 & 15) | ((r1 & 15) << 4) | ||
| 1840 | qb = (r0 >> 4) | ((r1 >> 4) << 4) | ||
| 1841 | qc = (r2 & 15) | ((r3 & 15) << 4) | ||
| 1842 | qd = (r2 >> 4) | ((r3 >> 4) << 4) | ||
| 1843 | lanes[10].extend([inv_quad[qa], inv_quad[qb]]) | ||
| 1844 | lanes[11].extend([inv_quad[qc], inv_quad[qd]]) | ||
| 1845 | prev = ep | ||
| 1846 | packed_chunk = _encode_bc3_from_lanes(lanes) | ||
| 1847 | elif codec == 4: | ||
| 1848 | inv_pair = {p: i for i, p in enumerate(bcpack_tables.BC4_PAIR)} | ||
| 1849 | lanes = [[] for _ in range(12)] | ||
| 1850 | for i in range(nblocks): | ||
| 1851 | blk = tiled[i * 8 : (i + 1) * 8] | ||
| 1852 | a0, a1 = blk[0], blk[1] | ||
| 1853 | bits = int.from_bytes(blk[2:8], "little") | ||
| 1854 | lanes[0].append(0) | ||
| 1855 | lanes[1].append(0) | ||
| 1856 | lanes[2].append(tb._zig(((a0 - 128 + 128) % 256) - 128)) | ||
| 1857 | lanes[3].append(tb._zig(((a1 - 128 + 128) % 256) - 128)) | ||
| 1858 | for r in range(4): | ||
| 1859 | row = (bits >> (12 * r)) & 0xFFF | ||
| 1860 | lanes[4 + 2 * r].append(inv_pair[(row & 7, (row >> 3) & 7)]) | ||
| 1861 | lanes[4 + 2 * r + 1].append(inv_pair[((row >> 6) & 7, (row >> 9) & 7)]) | ||
| 1862 | packed_chunk = _encode_bc4_from_lanes(lanes) | ||
| 1863 | elif codec == 5: | ||
| 1864 | inv_pair = {p: i for i, p in enumerate(bcpack_tables.BC5_PAIR)} | ||
| 1865 | lanes = [[] for _ in range(12)] | ||
| 1866 | for i in range(nblocks): | ||
| 1867 | blk = tiled[i * 16 : (i + 1) * 16] | ||
| 1868 | r0, r1 = blk[0], blk[1] | ||
| 1869 | br = int.from_bytes(blk[2:8], "little") | ||
| 1870 | g0, g1 = blk[8], blk[9] | ||
| 1871 | bg = int.from_bytes(blk[10:16], "little") | ||
| 1872 | lanes[0].extend([0, 0]) | ||
| 1873 | lanes[1].extend([0, 0]) | ||
| 1874 | # Compatibility endpoint ordering: half 0 -> (r0, r1), half 1 -> (g0, g1) | ||
| 1875 | lanes[2].extend([tb._zig(((r0 - 128 + 128) % 256) - 128), tb._zig(((g0 - 128 + 128) % 256) - 128)]) | ||
| 1876 | lanes[3].extend([tb._zig(((r1 - 128 + 128) % 256) - 128), tb._zig(((g1 - 128 + 128) % 256) - 128)]) | ||
| 1877 | for ch, bval in enumerate((br, bg)): | ||
| 1878 | for r in range(4): | ||
| 1879 | row = (bval >> (12 * r)) & 0xFFF | ||
| 1880 | lanes[4 + 4 * ch + r].extend([ | ||
| 1881 | inv_pair[(row & 7, (row >> 3) & 7)], | ||
| 1882 | inv_pair[((row >> 6) & 7, (row >> 9) & 7)], | ||
| 1883 | ]) | ||
| 1884 | packed_chunk = _encode_bc5_from_lanes(lanes) | ||
| 1885 | elif codec == 6: | ||
| 1886 | # Use raw solid BC6H blocks with mode 0x0F? Simpler: encode mode-11 blocks and | ||
| 1887 | # verify decoded DDS payload matches bcpack.decode(packed_chunk, 6, ...). | ||
| 1888 | packed_chunk = _encode_bc6h_solid(nblocks) | ||
| 1889 | decoded_bc6 = bcpack.decode(packed_chunk, 6, lay["size"]) | ||
| 1890 | linear = {m["index"]: ttpf.detile(lay, m, decoded_bc6[m["offset"] : m["offset"] + m["region"]]) for m in lay["mips"]} | ||
| 1891 | elif codec == 7: | ||
| 1892 | # Ensure padding blocks are valid mode-6 for encoder | ||
| 1893 | pad_blk = (1 << 6).to_bytes(16, "little") | ||
| 1894 | for off in range(0, len(tiled), 16): | ||
| 1895 | if tiled[off : off + 16] == b"\x00" * 16: | ||
| 1896 | tiled[off : off + 16] = pad_blk | ||
| 1897 | packed_chunk = tb.encode_bc7_mode6_blocks(bytes(tiled)) | ||
| 1898 | |||
| 1899 | pool, base = self._open_pool( | ||
| 1900 | f"pool_{fmt}.ttpf", | ||
| 1901 | [ttm.pack_etpf_record(w, h, mips, 0, fmt, 1, 1, mode, 4096)], | ||
| 1902 | [(codec, packed_chunk, lay["size"])], | ||
| 1903 | ) | ||
| 1904 | cal = { | ||
| 1905 | "version": 1, | ||
| 1906 | "bc3": _bc3_profile_from_tables(), | ||
| 1907 | "bc4": {"custom": {str(k): list(v) for k, v in bcpack_tables.BC4_HISTORY_PROVISIONAL.items()}}, | ||
| 1908 | "bc6h": {}, | ||
| 1909 | "bc7": _empty_bc7_section(), | ||
| 1910 | "entries": {Path(pool.path).name: {"0": "custom"}}, | ||
| 1911 | } | ||
| 1912 | |||
| 1913 | def rebuild_from_tiled(s_ptr, count, lab_ptr, seed_ptr, anc_ptr, out_ptr, ok_ptr, _t=bytes(tiled)): | ||
| 1914 | _write_u8_buf(out_ptr, _t[: count * 16]) | ||
| 1915 | _write_u8_buf(ok_ptr, b"\x01" * count) | ||
| 1916 | |||
| 1917 | dec = ct.LocalDecoder(pool, cal) | ||
| 1918 | with _fake_native_context(rebuild_fn=rebuild_from_tiled): | ||
| 1919 | dds = dec.dds(0) | ||
| 1920 | # Partial mips when mips > 1 | ||
| 1921 | if mips > 1: | ||
| 1922 | dds_part = dec.dds(0, mips=2) | ||
| 1923 | hdr_p = tex_headers.parse_dds_header(dds_part) | ||
| 1924 | self.assertEqual(hdr_p["mips"], 2) | ||
| 1925 | self.assertEqual(dds_part[148:], linear[0] + linear[1]) | ||
| 1926 | |||
| 1927 | hdr = tex_headers.parse_dds_header(dds) | ||
| 1928 | self.assertEqual(hdr["width"], w) | ||
| 1929 | self.assertEqual(hdr["height"], h) | ||
| 1930 | self.assertEqual(hdr["mips"], mips) | ||
| 1931 | self.assertEqual(hdr["dxgi_format"], fmt) | ||
| 1932 | self.assertEqual(hdr["array_size"], 1) | ||
| 1933 | self.assertEqual(dds[148:], b"".join(linear[i] for i in range(mips))) | ||
| 1934 | |||
| 1935 | def test_dds_multichunk_and_2d_array_and_validation_errors(self): | ||
| 1936 | # 2D texture spanning 2 chunks (raw + zlib) plus 2D array and invalid descriptors | ||
| 1937 | lay = ttpf.surface_layout(64, 64, 71, 5, 4096) # size = 8192 = 2 * 4096 pages | ||
| 1938 | lin = ttm.solid_chain(lay, 71) | ||
| 1939 | tiled = bytearray(lay["size"]) | ||
| 1940 | for m in lay["mips"]: | ||
| 1941 | ttm.retile_to(lay, m, lin[m["index"]], tiled) | ||
| 1942 | |||
| 1943 | # 2-slice 2D array using slice-major layout expected by LocalDecoder.dds | ||
| 1944 | arr_lay = ttpf.surface_layout(32, 32, 71, 4, 4096) # 4096 bytes per slice | ||
| 1945 | s0 = bytearray(4096) | ||
| 1946 | s1 = bytearray(4096) | ||
| 1947 | lin0 = ttm.solid_chain(arr_lay, 71, color_fn=lambda x, y, bw, bh: (255, 0, 0)) | ||
| 1948 | lin1 = ttm.solid_chain(arr_lay, 71, color_fn=lambda x, y, bw, bh: (0, 255, 0)) | ||
| 1949 | for m in arr_lay["mips"]: | ||
| 1950 | ttm.retile_to(arr_lay, m, lin0[m["index"]], s0) | ||
| 1951 | ttm.retile_to(arr_lay, m, lin1[m["index"]], s1) | ||
| 1952 | |||
| 1953 | p_dummy = self.root / "multi.ttpf" | ||
| 1954 | chunk0 = bytes(tiled[:4096]) | ||
| 1955 | chunk1 = zlib.compress(bytes(tiled[4096:])) | ||
| 1956 | chunk2 = bytes(s0 + s1) | ||
| 1957 | base0 = ttpf.align(16 + 7 * 24 + 7 * 32, 4096) | ||
| 1958 | # Keep records in non-decreasing base order so Pool.span() maps rec0 and rec1 accurately. | ||
| 1959 | rec_unmapped = ttm.pack_etpf_record(32, 32, 1, 0, 71, 1, 1, 4, 0) | ||
| 1960 | rec0 = ttm.pack_etpf_record(64, 64, 5, 0, 71, 1, 1, 4, base0) | ||
| 1961 | rec_bad_fmt = ttm.pack_etpf_record(32, 32, 1, 0, 28, 1, 1, 4, base0) | ||
| 1962 | rec_bad_dim = ttm.pack_etpf_record(32, 32, 1, 0, 71, 6, 2, 18, base0) | ||
| 1963 | rec_huge = ttm.pack_etpf_record(16384, 16384, 1, 0, 98, 2, 1, 4, base0) | ||
| 1964 | rec1 = ttm.pack_etpf_record(32, 32, 4, 0, 71, 2, 1, 4, base0 + 8192) | ||
| 1965 | rec_cross = ttm.pack_etpf_record(256, 256, 7, 1, 71, 1, 1, 4, base0 + 8192) | ||
| 1966 | |||
| 1967 | write_custom_pool( | ||
| 1968 | p_dummy, | ||
| 1969 | [rec_unmapped, rec0, rec_bad_fmt, rec_bad_dim, rec_huge, rec1, rec_cross], | ||
| 1970 | [(0, chunk0, 4096), (8, chunk1, 4096), (0, chunk2, 8192)], | ||
| 1971 | ) | ||
| 1972 | pool = ttpf.Pool(str(p_dummy)) | ||
| 1973 | self.addCleanup(pool.close) | ||
| 1974 | dec = ct.LocalDecoder(pool, {"version": 1}) | ||
| 1975 | |||
| 1976 | # Multi-chunk 2D texture (index 1) | ||
| 1977 | dds0 = dec.dds(1) | ||
| 1978 | self.assertEqual(dds0[148:], b"".join(lin[i] for i in range(5))) | ||
| 1979 | |||
| 1980 | # 2D array (depth=2, index 5) | ||
| 1981 | dds1 = dec.dds(5) | ||
| 1982 | hdr1 = tex_headers.parse_dds_header(dds1) | ||
| 1983 | self.assertEqual((hdr1["array_size"], hdr1["mips"]), (2, 4)) | ||
| 1984 | expected_arr = b"".join(lin0[i] for i in range(4)) + b"".join(lin1[i] for i in range(4)) | ||
| 1985 | self.assertEqual(dds1[148:], expected_arr) | ||
| 1986 | |||
| 1987 | # Error paths | ||
| 1988 | with self.assertRaisesRegex(ValueError, "supported BCn 2D texture or array"): | ||
| 1989 | dec.dds(2) | ||
| 1990 | with self.assertRaisesRegex(ValueError, "supported BCn 2D texture or array"): | ||
| 1991 | dec.dds(3) | ||
| 1992 | for bad_mips in (0, -1, 6): | ||
| 1993 | with self.assertRaisesRegex(ValueError, "Mip count outside descriptor range"): | ||
| 1994 | dec.dds(1, mips=bad_mips) | ||
| 1995 | with self.assertRaisesRegex(ValueError, "Texture has no mapped allocation"): | ||
| 1996 | dec.dds(0) | ||
| 1997 | with self.assertRaisesRegex(ValueError, "Texture crosses its allocation boundary"): | ||
| 1998 | dec.dds(6) | ||
| 1999 | with self.assertRaisesRegex(ValueError, "DDS exceeds output limit"): | ||
| 2000 | dec.dds(4) | ||
| 2001 | |||
| 2002 | def test_dds_no_tail_64k_tile_layout(self): | ||
| 2003 | # 512x256 BC7 (fmt 98, bs=16, 64K tile -> bw=64, bh=64) with 2 mips: | ||
| 2004 | # mip 0 is 128x64 blocks (2 tiles), mip 1 is 64x32 blocks (> bw//2=32 -> 1 tile), so tail == 2 == levels. | ||
| 2005 | lay = ttpf.surface_layout(512, 256, 98, 2, 65536) | ||
| 2006 | self.assertEqual(lay["first_tail"], 2) | ||
| 2007 | lin0 = bytes([0xAA] * (128 * 64 * 16)) | ||
| 2008 | lin1 = bytes([0xBB] * (64 * 32 * 16)) | ||
| 2009 | tiled = bytearray(lay["size"]) | ||
| 2010 | ttm.retile_to(lay, lay["mips"][0], lin0, tiled) | ||
| 2011 | ttm.retile_to(lay, lay["mips"][1], lin1, tiled) | ||
| 2012 | pool, _ = self._open_pool( | ||
| 2013 | "notail.ttpf", | ||
| 2014 | [ttm.pack_etpf_record(512, 256, 2, 0, 98, 1, 1, 0, 4096)], | ||
| 2015 | [(8, zlib.compress(bytes(tiled)), lay["size"])], | ||
| 2016 | ) | ||
| 2017 | dec = ct.LocalDecoder(pool, {"version": 1}) | ||
| 2018 | dds = dec.dds(0) | ||
| 2019 | self.assertEqual(dds[148:], lin0 + lin1) | ||
| 2020 | |||
| 2021 | def test_all_supported_formats_and_entries_fallback(self): | ||
| 2022 | self.assertEqual(ct.LocalDecoder.formats, frozenset((71, 72, 77, 78, 80, 83, 95, 96, 98, 99))) | ||
| 2023 | base0 = ttpf.align(16 + 10 * 24 + 10 * 32, 4096) | ||
| 2024 | records = [ | ||
| 2025 | ttm.pack_etpf_record(16, 16, 1, 0, fmt, 1, 1, 4, base0) | ||
| 2026 | for fmt in sorted(ct.LocalDecoder.formats) | ||
| 2027 | ] | ||
| 2028 | pool, _ = self._open_pool("all_fmts.ttpf", records, [(0, b"\x5A" * 4096, 4096)]) | ||
| 2029 | dec = ct.LocalDecoder( | ||
| 2030 | pool, | ||
| 2031 | {"version": 1, "entries": {"other.ttpf": {"0": "early"}, "all_fmts.ttpf": {"9": "custom"}}}, | ||
| 2032 | ) | ||
| 2033 | seen_profiles = [] | ||
| 2034 | orig_surface = dec.surface | ||
| 2035 | |||
| 2036 | def spy_surface(at, bs, profile): | ||
| 2037 | seen_profiles.append(profile) | ||
| 2038 | return orig_surface(at, bs, profile) | ||
| 2039 | |||
| 2040 | with mock.patch.object(dec, "surface", side_effect=spy_surface): | ||
| 2041 | for idx, fmt in enumerate(sorted(ct.LocalDecoder.formats)): | ||
| 2042 | dds = dec.dds(idx) | ||
| 2043 | hdr = tex_headers.parse_dds_header(dds) | ||
| 2044 | bs = 8 if fmt in (71, 72, 80) else 16 | ||
| 2045 | self.assertEqual(hdr["dxgi_format"], fmt) | ||
| 2046 | self.assertEqual(hdr["pitch_linear"], 4 * 4 * bs) | ||
| 2047 | self.assertEqual(dds[148:], b"\x5A" * (16 * bs)) | ||
| 2048 | self.assertEqual(seen_profiles, ["base"] * 9 + ["custom"]) | ||
| 2049 | |||
| 2050 | def test_invalid_bc1_and_bc7_config_shapes(self): | ||
| 2051 | bc1_packed = tb.encode_bc1_blocks(b"\x00" * 4096) | ||
| 2052 | bc7_packed = _encode_bc7_mode6_solid(256) | ||
| 2053 | pool, _ = self._open_pool( | ||
| 2054 | "bad_cfg.ttpf", | ||
| 2055 | [ttm.pack_etpf_record(64, 64, 1, 0, 71, 1, 1, 4, 4096)], | ||
| 2056 | [(1, bc1_packed, 4096), (7, bc7_packed, 4096)], | ||
| 2057 | ) | ||
| 2058 | bad_bc1 = ct.LocalDecoder( | ||
| 2059 | pool, {"version": 1, "bc1": {"endpoints": [[0] * 6], "selectors": [[0] * 256] * 4}} | ||
| 2060 | ) | ||
| 2061 | with _fake_native_context(), self.assertRaisesRegex(ValueError, "Invalid calibration field"): | ||
| 2062 | bad_bc1.read_chunk(0, 8, "base") | ||
| 2063 | |||
| 2064 | bad_bc7 = ct.LocalDecoder( | ||
| 2065 | pool, {"version": 1, "bc7": {"labels": [[0, 0, 0, 0]], "anchors": [0] * 128}} | ||
| 2066 | ) | ||
| 2067 | with _fake_native_context(), self.assertRaisesRegex(ValueError, "Invalid calibration field"): | ||
| 2068 | bad_bc7.read_chunk(1, 16, "base") | ||
| 2069 | |||
| 2070 | |||
| 2071 | class TestExportFileAndCli(unittest.TestCase): | ||
| 2072 | def setUp(self): | ||
| 2073 | tmp = tempfile.TemporaryDirectory() | ||
| 2074 | self.addCleanup(tmp.cleanup) | ||
| 2075 | self.root = Path(tmp.name) | ||
| 2076 | self.pool_path = self.root / "pool.ttpf" | ||
| 2077 | self.lay, self.linear, _ = ttm.build_bc1_bcpack_pool(self.pool_path) | ||
| 2078 | self.profile = self.root / "profile.json" | ||
| 2079 | self.profile.write_text(json.dumps(synthetic_profile()), encoding="utf-8") | ||
| 2080 | |||
| 2081 | def test_export_file_atomic_link_replace_and_cleanup(self): | ||
| 2082 | pool = ttpf.Pool(str(self.pool_path)) | ||
| 2083 | self.addCleanup(pool.close) | ||
| 2084 | out = self.root / "out.dds" | ||
| 2085 | |||
| 2086 | # 1. Create new file (force=False) | ||
| 2087 | with _fake_native_context(): | ||
| 2088 | rc = ct.export_file(pool, 0, out, None, False, self.profile) | ||
| 2089 | self.assertEqual(rc, 0) | ||
| 2090 | data = out.read_bytes() | ||
| 2091 | self.assertEqual(data[:4], b"DDS ") | ||
| 2092 | self.assertEqual(data[148:], b"".join(self.linear[i] for i in sorted(self.linear))) | ||
| 2093 | # No leftover temporary files | ||
| 2094 | self.assertEqual(sorted(p.name for p in self.root.iterdir()), ["out.dds", "pool.ttpf", "profile.json"]) | ||
| 2095 | |||
| 2096 | # 2. Existing target with force=False raises FileExistsError, keeps target intact, cleans tmp | ||
| 2097 | out.write_bytes(b"SENTINEL") | ||
| 2098 | with _fake_native_context(): | ||
| 2099 | with self.assertRaises(FileExistsError): | ||
| 2100 | ct.export_file(pool, 0, out, None, False, self.profile) | ||
| 2101 | self.assertEqual(out.read_bytes(), b"SENTINEL") | ||
| 2102 | self.assertEqual(sorted(p.name for p in self.root.iterdir()), ["out.dds", "pool.ttpf", "profile.json"]) | ||
| 2103 | |||
| 2104 | # 3. Existing target with force=True replaces target atomically and cleans tmp | ||
| 2105 | with _fake_native_context(): | ||
| 2106 | rc_force = ct.export_file(pool, 0, out, 2, True, self.profile) | ||
| 2107 | self.assertEqual(rc_force, 0) | ||
| 2108 | replaced = out.read_bytes() | ||
| 2109 | self.assertEqual(tex_headers.parse_dds_header(replaced)["mips"], 2) | ||
| 2110 | self.assertEqual(replaced[148:], self.linear[0] + self.linear[1]) | ||
| 2111 | self.assertEqual(sorted(p.name for p in self.root.iterdir()), ["out.dds", "pool.ttpf", "profile.json"]) | ||
| 2112 | |||
| 2113 | # 4. Cache is cleared even if dds() fails | ||
| 2114 | clear_calls = [] | ||
| 2115 | |||
| 2116 | with _fake_native_context(), \ | ||
| 2117 | mock.patch.object(ct.LocalDecoder, "dds", side_effect=ValueError("boom")): | ||
| 2118 | orig_init = ct.LocalDecoder.__init__ | ||
| 2119 | |||
| 2120 | def tracked_init(self_dec, p, c): | ||
| 2121 | orig_init(self_dec, p, c) | ||
| 2122 | orig_cc = self_dec.read_chunk.cache_clear | ||
| 2123 | self_dec.read_chunk.cache_clear = lambda: (clear_calls.append(1), orig_cc())[1] | ||
| 2124 | |||
| 2125 | with mock.patch.object(ct.LocalDecoder, "__init__", tracked_init): | ||
| 2126 | with self.assertRaisesRegex(ValueError, "boom"): | ||
| 2127 | ct.export_file(pool, 0, self.root / "unused.dds", None, False, self.profile) | ||
| 2128 | self.assertEqual(len(clear_calls), 1) | ||
| 2129 | |||
| 2130 | # 5. Missing or invalid profile JSON | ||
| 2131 | with self.assertRaises(FileNotFoundError): | ||
| 2132 | ct.export_file(pool, 0, self.root / "u.dds", None, False, self.root / "missing.json") | ||
| 2133 | bad_json = self.root / "bad.json" | ||
| 2134 | bad_json.write_text("{not json", encoding="utf-8") | ||
| 2135 | with self.assertRaises(json.JSONDecodeError): | ||
| 2136 | ct.export_file(pool, 0, self.root / "u.dds", None, False, bad_json) | ||
| 2137 | |||
| 2138 | def test_ttpf_mips_cli_calibration_paths(self): | ||
| 2139 | out = self.root / "cli.dds" | ||
| 2140 | |||
| 2141 | def run_cli(*argv): | ||
| 2142 | out_buf, err_buf = io.StringIO(), io.StringIO() | ||
| 2143 | with mock.patch.dict(sys.modules, {"calibrated_texture": ct}), \ | ||
| 2144 | _fake_native_context(), \ | ||
| 2145 | redirect_stdout(out_buf), redirect_stderr(err_buf): | ||
| 2146 | rc = ttpf.main(list(argv)) | ||
| 2147 | return rc, out_buf.getvalue(), err_buf.getvalue() | ||
| 2148 | |||
| 2149 | # Success | ||
| 2150 | rc, _, err = run_cli("export", str(self.pool_path), "0", str(out), "--calibration", str(self.profile)) | ||
| 2151 | self.assertEqual(rc, 0, err) | ||
| 2152 | dds = out.read_bytes() | ||
| 2153 | self.assertEqual(dds[:4], b"DDS ") | ||
| 2154 | self.assertEqual(dds[148:], b"".join(self.linear[i] for i in sorted(self.linear))) | ||
| 2155 | |||
| 2156 | # Refuses overwrite without --force | ||
| 2157 | out.write_bytes(b"KEEP_ME") | ||
| 2158 | rc2, _, err2 = run_cli("export", str(self.pool_path), "0", str(out), "--calibration", str(self.profile)) | ||
| 2159 | self.assertEqual(rc2, 2) | ||
| 2160 | self.assertIn("calibrated export failed", err2) | ||
| 2161 | self.assertNotIn("Traceback", err2) | ||
| 2162 | self.assertEqual(out.read_bytes(), b"KEEP_ME") | ||
| 2163 | |||
| 2164 | # Overwrites with --force and --mips | ||
| 2165 | rc3, _, err3 = run_cli( | ||
| 2166 | "export", str(self.pool_path), "0", str(out), | ||
| 2167 | "--calibration", str(self.profile), "--mips", "1", "--force", | ||
| 2168 | ) | ||
| 2169 | self.assertEqual(rc3, 0, err3) | ||
| 2170 | self.assertEqual(tex_headers.parse_dds_header(out.read_bytes())["mips"], 1) | ||
| 2171 | |||
| 2172 | # Rejects --calibration + --history together | ||
| 2173 | rc4, _, err4 = run_cli( | ||
| 2174 | "export", str(self.pool_path), "0", str(out), | ||
| 2175 | "--calibration", str(self.profile), "--history", str(self.profile), "--force", | ||
| 2176 | ) | ||
| 2177 | self.assertEqual(rc4, 2) | ||
| 2178 | self.assertIn("choose either --calibration or --history", err4) | ||
| 2179 | |||
| 2180 | # Bad profile version returns exit code 2 cleanly | ||
| 2181 | self.profile.write_text('{"version": 99}', encoding="utf-8") | ||
| 2182 | rc5, _, err5 = run_cli( | ||
| 2183 | "export", str(self.pool_path), "0", str(out), | ||
| 2184 | "--calibration", str(self.profile), "--force", | ||
| 2185 | ) | ||
| 2186 | self.assertEqual(rc5, 2) | ||
| 2187 | self.assertIn("Unsupported calibration version", err5) | ||
| 2188 | self.assertNotIn("Traceback", err5) | ||
| 2189 | |||
| 2190 | |||
| 2191 | if __name__ == "__main__": | ||
| 2192 | unittest.main() | ||
diff --git a/tests/test_cf_ref_edge_fixes.py b/tests/test_cf_ref_edge_fixes.py new file mode 100644 index 000000000..2ea11772f --- /dev/null +++ b/tests/test_cf_ref_edge_fixes.py | |||
| @@ -0,0 +1,294 @@ | |||
| 1 | """Regression tests for tools/cf_ref.py s_cmp_* validation and exec_hi/vcc_hi mask ops. | ||
| 2 | |||
| 3 | Standard library only; uses hand-written synthetic .s listings (no game data, GPU, or llvm-mc). | ||
| 4 | |||
| 5 | Run from the repository root: | ||
| 6 | python -I tests/test_cf_ref_edge_fixes.py -v | ||
| 7 | """ | ||
| 8 | import os | ||
| 9 | import sys | ||
| 10 | import tempfile | ||
| 11 | import unittest | ||
| 12 | |||
| 13 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 14 | sys.path.insert(0, os.path.join(ROOT, "tools")) | ||
| 15 | |||
| 16 | import cf_ref # noqa: E402 | ||
| 17 | import cpu_ref # noqa: E402 | ||
| 18 | from shader_ir import parse_file # noqa: E402 | ||
| 19 | |||
| 20 | MASK32 = 0xFFFFFFFF | ||
| 21 | MASK64 = 0xFFFFFFFFFFFFFFFF | ||
| 22 | _VOP3_NO_E64 = {"v_mul_lo_u32", "v_mbcnt_lo_u32_b32", "v_mbcnt_hi_u32_b32"} | ||
| 23 | |||
| 24 | |||
| 25 | def _enc_bytes(size): | ||
| 26 | return "; encoding: [" + ",".join(["0x00"] * size) + "]" | ||
| 27 | |||
| 28 | |||
| 29 | def _guess_size(text): | ||
| 30 | op = text.split()[0] | ||
| 31 | if op == "exp" or op.endswith("_e64") or op in _VOP3_NO_E64: | ||
| 32 | return 8 | ||
| 33 | for tok in text.replace(",", " ").split()[1:]: | ||
| 34 | if tok.startswith("0x") or (tok.lstrip("-").isdigit() and not (-16 <= int(tok) <= 64)): | ||
| 35 | return 8 | ||
| 36 | return 4 | ||
| 37 | |||
| 38 | |||
| 39 | def assemble(items, name="test"): | ||
| 40 | pc = 0 | ||
| 41 | labels = {} | ||
| 42 | sized = [] | ||
| 43 | for item in items: | ||
| 44 | if isinstance(item, tuple) and item[0] == "lbl": | ||
| 45 | labels[item[1]] = pc | ||
| 46 | continue | ||
| 47 | if isinstance(item, tuple) and item[0] == "br": | ||
| 48 | sized.append((item, pc, 4)) | ||
| 49 | pc += 4 | ||
| 50 | else: | ||
| 51 | text, size = item if isinstance(item, tuple) else (item, _guess_size(item)) | ||
| 52 | sized.append((text, pc, size)) | ||
| 53 | pc += size | ||
| 54 | |||
| 55 | lines = [f"; {name} code 0x0..0x{pc:x}"] | ||
| 56 | for item, at, size in sized: | ||
| 57 | if isinstance(item, tuple) and item[0] == "br": | ||
| 58 | _, op, target = item | ||
| 59 | delta = labels[target] - (at + 4) | ||
| 60 | if delta % 4 != 0: | ||
| 61 | raise ValueError(f"branch target {target} is not 4-byte aligned") | ||
| 62 | text = f"{op} {delta // 4}" | ||
| 63 | else: | ||
| 64 | text = item | ||
| 65 | lines.append(f"\t{text} {_enc_bytes(size)}") | ||
| 66 | return "\n".join(lines) + "\n" | ||
| 67 | |||
| 68 | |||
| 69 | def lane_id_prologue(wave): | ||
| 70 | insns = ["v_mbcnt_lo_u32_b32 v0, -1, 0"] | ||
| 71 | if wave == 64: | ||
| 72 | insns.append("v_mbcnt_hi_u32_b32 v0, -1, v0") | ||
| 73 | return insns | ||
| 74 | |||
| 75 | |||
| 76 | class CfRefEdgeFixesTests(unittest.TestCase): | ||
| 77 | def setUp(self): | ||
| 78 | self.tmp = tempfile.TemporaryDirectory(prefix="cf-ref-edge-") | ||
| 79 | self.addCleanup(self.tmp.cleanup) | ||
| 80 | self.n = 0 | ||
| 81 | |||
| 82 | def write_items(self, items): | ||
| 83 | self.n += 1 | ||
| 84 | path = os.path.join(self.tmp.name, f"t{self.n}.s") | ||
| 85 | with open(path, "w", encoding="utf-8", newline="\n") as f: | ||
| 86 | f.write(assemble(items, name=f"t{self.n}")) | ||
| 87 | return path | ||
| 88 | |||
| 89 | def run_items(self, items, wave=32): | ||
| 90 | return cf_ref.run(self.write_items(items), wave=wave) | ||
| 91 | |||
| 92 | def test_s_cmp_unknown_condition_raises_unsupported(self): | ||
| 93 | bad_ops = [ | ||
| 94 | "s_cmp_bad_u32 s0, s1", | ||
| 95 | "s_cmp_bad_i32 s0, s1", | ||
| 96 | "s_cmp_tru_u32 s0, s1", | ||
| 97 | "s_cmp_f_i32 s0, s1", | ||
| 98 | "s_cmp_foo s0, s1", | ||
| 99 | "s_cmp_eq_u64 s[0:1], s[2:3]", | ||
| 100 | "s_cmp_lt_f32 s0, s1", | ||
| 101 | ] | ||
| 102 | for insn in bad_ops: | ||
| 103 | mnemonic = insn.split()[0] | ||
| 104 | with self.subTest(insn=insn): | ||
| 105 | with self.assertRaises(cpu_ref.Unsupported) as cm: | ||
| 106 | self.run_items([insn, "s_endpgm"], wave=32) | ||
| 107 | self.assertIn(mnemonic, str(cm.exception)) | ||
| 108 | |||
| 109 | def test_wave64_exec_hi_mov_preserves_lo_and_controls_upper_lanes(self): | ||
| 110 | # Set exec_lo to lanes {0, 1} and exec_hi to lanes {32, 34}, preserving exec_lo. | ||
| 111 | # Then verify active lanes 32..63 run, inactive ones do not, and exec_hi clears cleanly. | ||
| 112 | res = self.run_items(lane_id_prologue(64) + [ | ||
| 113 | "v_mov_b32 v1, 0", | ||
| 114 | "v_mov_b32 v2, 0", | ||
| 115 | "v_mov_b32 v3, 0", | ||
| 116 | "s_cmp_eq_u32 1, 1", # SCC = 1; s_mov_b32 exec_hi must preserve SCC | ||
| 117 | "s_mov_b32 exec_lo, 0x00000003", | ||
| 118 | "s_mov_b32 exec_hi, 0x00000005", | ||
| 119 | "s_mov_b32 s0, scc", | ||
| 120 | "v_mov_b32 v1, 77", | ||
| 121 | "exp mrt0 v0, v1, v2, v3 done vm", | ||
| 122 | "s_mov_b32 exec_hi, 0", | ||
| 123 | "s_endpgm", | ||
| 124 | ], wave=64) | ||
| 125 | self.assertEqual(res["sgpr"][0], 1) | ||
| 126 | self.assertEqual(sorted(res["exports"]), [0, 1, 32, 34]) | ||
| 127 | for lane in (0, 1, 32, 34): | ||
| 128 | self.assertEqual(res["exports"][lane], (lane, 77, 0, 0)) | ||
| 129 | self.assertEqual(res["exec"], 0x0000000000000003) | ||
| 130 | |||
| 131 | # exec_lo == 0 and exec_hi != 0 must keep EXECZ == 0 (s_cbranch_execnz taken). | ||
| 132 | res_nz = self.run_items([ | ||
| 133 | "s_mov_b32 s0, 0", | ||
| 134 | "s_mov_b32 exec_lo, 0", | ||
| 135 | "s_mov_b32 exec_hi, 0x00010000", | ||
| 136 | ("br", "s_cbranch_execz", "bad"), | ||
| 137 | ("br", "s_cbranch_execnz", "ok"), | ||
| 138 | ("lbl", "bad"), | ||
| 139 | "s_mov_b32 s0, 999", | ||
| 140 | ("lbl", "ok"), | ||
| 141 | "s_add_u32 s0, s0, 1", | ||
| 142 | "s_mov_b32 exec_hi, 0", | ||
| 143 | ("br", "s_cbranch_execnz", "bad2"), | ||
| 144 | "s_add_u32 s0, s0, 2", | ||
| 145 | ("lbl", "bad2"), | ||
| 146 | "s_endpgm", | ||
| 147 | ], wave=64) | ||
| 148 | self.assertEqual(res_nz["sgpr"][0], 3) | ||
| 149 | self.assertEqual(res_nz["exec"], 0) | ||
| 150 | |||
| 151 | def test_wave64_vcc_hi_mov_preserves_lo_and_drives_upper_lanes(self): | ||
| 152 | # Write vcc_lo (lanes 1, 3) then vcc_hi (lanes 33, 63); low 32 bits must stay intact | ||
| 153 | # and VOP2 v_cndmask_b32 must see vcc[63:32] on lanes 32..63. | ||
| 154 | res = self.run_items(lane_id_prologue(64) + [ | ||
| 155 | "s_cmp_eq_u32 1, 1", # SCC = 1; s_mov_b32 vcc_hi must preserve SCC | ||
| 156 | "s_mov_b32 vcc_lo, 0x0000000a", | ||
| 157 | "s_mov_b32 vcc_hi, 0x80000002", | ||
| 158 | "s_mov_b32 s0, scc", | ||
| 159 | "v_mov_b32 v1, 10", | ||
| 160 | "v_mov_b32 v2, 20", | ||
| 161 | "v_cndmask_b32 v3, v1, v2", | ||
| 162 | "v_mov_b32 v4, 0", | ||
| 163 | "exp mrt0 v0, v3, v4, v4 done vm", | ||
| 164 | "s_endpgm", | ||
| 165 | ], wave=64) | ||
| 166 | self.assertEqual(res["sgpr"][0], 1) | ||
| 167 | self.assertEqual(res["vcc"], (0x80000002 << 32) | 0x0000000A) | ||
| 168 | for lane in range(64): | ||
| 169 | want = 20 if lane in (1, 3, 33, 63) else 10 | ||
| 170 | self.assertEqual(res["exports"][lane][1], want) | ||
| 171 | |||
| 172 | # vcc_lo == 0 and vcc_hi != 0 must keep VCCZ == 0 in wave64; clearing vcc_hi sets VCCZ == 1. | ||
| 173 | res_vccz = self.run_items([ | ||
| 174 | "s_mov_b32 s0, 0", | ||
| 175 | "s_mov_b32 vcc_lo, 0", | ||
| 176 | "s_mov_b32 vcc_hi, 0x10", | ||
| 177 | ("br", "s_cbranch_vccz", "bad"), | ||
| 178 | "s_add_u32 s0, s0, 1", | ||
| 179 | "s_mov_b32 vcc_hi, 0", | ||
| 180 | ("br", "s_cbranch_vccnz", "bad"), | ||
| 181 | "s_add_u32 s0, s0, 2", | ||
| 182 | ("br", "s_cbranch_vccz", "done"), | ||
| 183 | ("lbl", "bad"), | ||
| 184 | "s_mov_b32 s0, 999", | ||
| 185 | ("lbl", "done"), | ||
| 186 | "s_endpgm", | ||
| 187 | ], wave=64) | ||
| 188 | self.assertEqual(res_vccz["sgpr"][0], 3) | ||
| 189 | self.assertEqual(res_vccz["vcc"], 0) | ||
| 190 | |||
| 191 | def test_read_exec_hi_and_vcc_hi_in_scalar_ops_wave64(self): | ||
| 192 | res = self.run_items([ | ||
| 193 | "s_mov_b32 exec_lo, 0x11223344", | ||
| 194 | "s_mov_b32 exec_hi, 0x55667788", | ||
| 195 | "s_mov_b32 vcc_lo, 0xaabbccdd", | ||
| 196 | "s_mov_b32 vcc_hi, 0x0f0f0f0f", | ||
| 197 | "s_cmp_eq_u32 1, 2", # SCC = 0; s_mov_b32 must preserve SCC | ||
| 198 | "s_mov_b32 s4, vcc_hi", | ||
| 199 | "s_mov_b32 s5, exec_hi", | ||
| 200 | "s_mov_b32 s6, scc", | ||
| 201 | "s_and_b32 s7, exec_hi, 0x00ff00ff", | ||
| 202 | "s_mov_b32 s8, scc", | ||
| 203 | "s_or_b32 vcc_hi, vcc_hi, 0xf0000000", | ||
| 204 | "s_mov_b32 s9, scc", | ||
| 205 | "s_xnor_b32 s10, exec_hi, 0x55667788", # 32-bit exact complement of XOR -> 0xffffffff -> SCC=1 | ||
| 206 | "s_mov_b32 s11, scc", | ||
| 207 | "s_xor_b32 s12, exec_hi, 0x55667788", # 0 -> SCC=0 | ||
| 208 | "s_mov_b32 s13, scc", | ||
| 209 | "s_xnor_b32 s14, exec_hi, 0xaa998877", # 0 -> SCC=0 (verifies 32-bit mask, not 64-bit) | ||
| 210 | "s_mov_b32 s15, scc", | ||
| 211 | "s_cmp_eq_u32 vcc_hi, 0xff0f0f0f", | ||
| 212 | "s_mov_b32 s16, scc", | ||
| 213 | "s_cmp_lg_u32 exec_hi, 0x55667788", | ||
| 214 | "s_mov_b32 s17, scc", | ||
| 215 | "s_mov_b32 exec_lo, -1", | ||
| 216 | "s_mov_b32 exec_hi, 0", | ||
| 217 | "s_xnor_b32 s18, exec_hi, -1", # 32-bit -1 -> ~(0 ^ 0xffffffff) = 0, SCC=0 | ||
| 218 | "s_mov_b32 s19, scc", | ||
| 219 | "s_mov_b32 exec_hi, -1", | ||
| 220 | "s_xor_b32 s20, exec_hi, -1", # 32-bit -1 -> 0xffffffff ^ 0xffffffff = 0, SCC=0 | ||
| 221 | "s_mov_b32 s21, scc", | ||
| 222 | "s_endpgm", | ||
| 223 | ], wave=64) | ||
| 224 | self.assertEqual(res["sgpr"][4], 0x0F0F0F0F) | ||
| 225 | self.assertEqual(res["sgpr"][5], 0x55667788) | ||
| 226 | self.assertEqual(res["sgpr"][6], 0) | ||
| 227 | self.assertEqual(res["sgpr"][7], 0x00660088) | ||
| 228 | self.assertEqual(res["sgpr"][8], 1) | ||
| 229 | self.assertEqual(res["sgpr"][9], 1) | ||
| 230 | self.assertEqual(res["sgpr"][10], 0xFFFFFFFF) | ||
| 231 | self.assertEqual(res["sgpr"][11], 1) | ||
| 232 | self.assertEqual(res["sgpr"][12], 0) | ||
| 233 | self.assertEqual(res["sgpr"][13], 0) | ||
| 234 | self.assertEqual(res["sgpr"][14], 0) | ||
| 235 | self.assertEqual(res["sgpr"][15], 0) | ||
| 236 | self.assertEqual(res["sgpr"][16], 1) | ||
| 237 | self.assertEqual(res["sgpr"][17], 0) | ||
| 238 | self.assertEqual(res["sgpr"][18], 0) | ||
| 239 | self.assertEqual(res["sgpr"][19], 0) | ||
| 240 | self.assertEqual(res["sgpr"][20], 0) | ||
| 241 | self.assertEqual(res["sgpr"][21], 0) | ||
| 242 | self.assertEqual(res["vcc"], (0xFF0F0F0F << 32) | 0xAABBCCDD) | ||
| 243 | self.assertEqual(res["exec"], MASK64) | ||
| 244 | |||
| 245 | # Full-wave 64-bit register names in _b32 SOP2 ops remain rejected in wave64. | ||
| 246 | with self.assertRaises(cpu_ref.Unsupported): | ||
| 247 | self.run_items(["s_and_b32 vcc, vcc, exec", "s_endpgm"], wave=64) | ||
| 248 | |||
| 249 | def test_wave32_exec_hi_keeps_upper_half_zero_and_vcc_hi_is_scalar(self): | ||
| 250 | # Wave32 runs with EXEC[63:32] == 0 so lanes 32-63 never execute even if exec_hi is written. | ||
| 251 | # vcc_hi holds its own 32-bit value independently of wave32 VCC[31:0] / VCCZ. | ||
| 252 | items = lane_id_prologue(32) + [ | ||
| 253 | "s_mov_b32 exec_lo, 0x0000000f", | ||
| 254 | "s_mov_b32 exec_hi, 0xffffffff", | ||
| 255 | "s_or_b32 exec_hi, exec_hi, 0x1", | ||
| 256 | "s_mov_b32 s0, exec_hi", | ||
| 257 | "s_and_b32 s1, exec_hi, 1", | ||
| 258 | "s_mov_b32 s2, scc", | ||
| 259 | "s_mov_b32 vcc_lo, 0x00000005", | ||
| 260 | "s_mov_b32 vcc_hi, 0xdeadbeef", | ||
| 261 | "s_mov_b32 s3, vcc_hi", | ||
| 262 | "s_and_b32 s4, vcc_hi, 0x0000ffff", | ||
| 263 | "s_mov_b32 vcc_lo, 0", | ||
| 264 | ("br", "s_cbranch_vccnz", "bad"), | ||
| 265 | "s_and_saveexec_b32 vcc_hi, 0x00000003", | ||
| 266 | "s_mov_b32 s5, vcc_hi", | ||
| 267 | "s_mov_b32 exec_lo, vcc_hi", | ||
| 268 | "v_mov_b32 v1, 1", | ||
| 269 | "v_mov_b32 v2, 2", | ||
| 270 | "v_mov_b32 v3, 3", | ||
| 271 | "exp mrt0 v0, v1, v2, v3 done vm", | ||
| 272 | ("br", "s_branch", "done"), | ||
| 273 | ("lbl", "bad"), | ||
| 274 | "s_mov_b32 s3, 0", | ||
| 275 | ("lbl", "done"), | ||
| 276 | "s_endpgm", | ||
| 277 | ] | ||
| 278 | path = self.write_items(items) | ||
| 279 | machine = cf_ref.WaveMachine(parse_file(path), wave=32) | ||
| 280 | res = machine.run() | ||
| 281 | self.assertEqual(machine.exec >> 32, 0) | ||
| 282 | self.assertEqual(res["exec"], 0x0000000F) | ||
| 283 | self.assertEqual(res["vcc"], 0) | ||
| 284 | self.assertEqual(res["sgpr"][0], 0) | ||
| 285 | self.assertEqual(res["sgpr"][1], 0) | ||
| 286 | self.assertEqual(res["sgpr"][2], 0) | ||
| 287 | self.assertEqual(res["sgpr"][3], 0xDEADBEEF) | ||
| 288 | self.assertEqual(res["sgpr"][4], 0x0000BEEF) | ||
| 289 | self.assertEqual(res["sgpr"][5], 0x0000000F) | ||
| 290 | self.assertEqual(sorted(res["exports"]), [0, 1, 2, 3]) | ||
| 291 | |||
| 292 | |||
| 293 | if __name__ == "__main__": | ||
| 294 | unittest.main() | ||
diff --git a/tests/test_csv_line_endings.py b/tests/test_csv_line_endings.py new file mode 100644 index 000000000..8b883349d --- /dev/null +++ b/tests/test_csv_line_endings.py | |||
| @@ -0,0 +1,70 @@ | |||
| 1 | """CSV reports must have the same bytes on every platform. | ||
| 2 | |||
| 3 | `csv.writer` defaults to `lineterminator="\\r\\n"`, so a tool that leaves it at the default writes CRLF on Windows and | ||
| 4 | LF everywhere else, and the same archive gives different report bytes depending on the machine that exported it. | ||
| 5 | `tools/awc_manifest.py` and `tools/awc_shorts.py` pass `lineterminator="\\n"` and `tools/bink_index.py` documents why | ||
| 6 | its stdout writer needs it; this test keeps every other writer on the same convention. No game files are read. | ||
| 7 | """ | ||
| 8 | import os | ||
| 9 | import re | ||
| 10 | import subprocess | ||
| 11 | import sys | ||
| 12 | import tempfile | ||
| 13 | import unittest | ||
| 14 | |||
| 15 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 16 | TOOLS = os.path.join(ROOT, "tools") | ||
| 17 | |||
| 18 | # Every csv writer call in tools/, with the two lines that may continue it. | ||
| 19 | WRITER = re.compile(r"\bcsv\.(?:Dict)?[Ww]riter\(") | ||
| 20 | |||
| 21 | |||
| 22 | def writer_calls(): | ||
| 23 | """Yield (file, line number, the call's source text) for every csv writer constructed in tools/.""" | ||
| 24 | for name in sorted(os.listdir(TOOLS)): | ||
| 25 | if not name.endswith(".py"): | ||
| 26 | continue | ||
| 27 | path = os.path.join(TOOLS, name) | ||
| 28 | with open(path, encoding="utf-8") as f: | ||
| 29 | lines = f.read().splitlines() | ||
| 30 | for index, line in enumerate(lines): | ||
| 31 | if WRITER.search(line): | ||
| 32 | yield name, index + 1, "\n".join(lines[index:index + 3]) | ||
| 33 | |||
| 34 | |||
| 35 | class CsvTerminatorTest(unittest.TestCase): | ||
| 36 | def test_every_csv_writer_sets_an_lf_terminator(self): | ||
| 37 | missing = [f"{name}:{line}" for name, line, source in writer_calls() | ||
| 38 | if 'lineterminator="\\n"' not in source] | ||
| 39 | self.assertEqual(missing, [], "csv writers without lineterminator='\\n' (CRLF on Windows)") | ||
| 40 | |||
| 41 | def run_tool(self, tool, source): | ||
| 42 | out = os.path.join(self.work, os.path.splitext(tool)[0] + ".csv") | ||
| 43 | result = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, tool), source, out], | ||
| 44 | capture_output=True, text=True, check=False) | ||
| 45 | self.assertEqual(result.returncode, 0, result.stderr) | ||
| 46 | self.assertTrue(os.path.isfile(out), result.stdout) | ||
| 47 | with open(out, "rb") as f: | ||
| 48 | return f.read() | ||
| 49 | |||
| 50 | def setUp(self): | ||
| 51 | self.temp = tempfile.TemporaryDirectory() | ||
| 52 | self.work = self.temp.name | ||
| 53 | self.source = os.path.join(self.work, "empty") | ||
| 54 | os.makedirs(self.source) | ||
| 55 | |||
| 56 | def tearDown(self): | ||
| 57 | self.temp.cleanup() | ||
| 58 | |||
| 59 | def test_csv_reports_have_no_carriage_return(self): | ||
| 60 | # These three scan a folder and write a header even when it holds nothing, so they need no archive. | ||
| 61 | for tool in ("page_index.py", "rbf0_index.py", "restofworld_index.py"): | ||
| 62 | with self.subTest(tool=tool): | ||
| 63 | data = self.run_tool(tool, self.source) | ||
| 64 | self.assertNotIn(b"\r", data, f"{tool} wrote a carriage return") | ||
| 65 | self.assertTrue(data.endswith(b"\n"), f"{tool} did not end its last row with a newline") | ||
| 66 | self.assertTrue(data.count(b"\n") >= 1) | ||
| 67 | |||
| 68 | |||
| 69 | if __name__ == "__main__": | ||
| 70 | unittest.main() | ||
diff --git a/tests/test_d3d12_xs_surface.py b/tests/test_d3d12_xs_surface.py index 536a2673a..754355d30 100644 --- a/tests/test_d3d12_xs_surface.py +++ b/tests/test_d3d12_xs_surface.py | |||
| @@ -82,4 +82,9 @@ if __name__ == "__main__": | |||
| 82 | errors, checked, _um = S.check_sdk() | 82 | errors, checked, _um = S.check_sdk() |
| 83 | assert errors == [], errors | 83 | assert errors == [], errors |
| 84 | assert checked == 83 | 84 | assert checked == 83 |
| 85 | if os.environ.get("SCARAB_REF"): | ||
| 86 | errors, _notes = S.check_scarab(os.environ["SCARAB_REF"]) | ||
| 87 | assert errors == [], errors | ||
| 88 | else: | ||
| 89 | print("SCARAB cross-check skipped: SCARAB_REF is not set") | ||
| 85 | print("ok") | 90 | print("ok") |
diff --git a/tests/test_f16_hw_words.py b/tests/test_f16_hw_words.py index 249e2c932..917ee1fb7 100644 --- a/tests/test_f16_hw_words.py +++ b/tests/test_f16_hw_words.py | |||
| @@ -35,6 +35,9 @@ HARDWARE = { | |||
| 35 | "ps_f16_const": (0xAAAA3D00, 0x38005555, 0xAAAA3800, 0x3F000000), | 35 | "ps_f16_const": (0xAAAA3D00, 0x38005555, 0xAAAA3800, 0x3F000000), |
| 36 | "ps_f16_const2": (0x42003D00, 0x3D004200, 0xAAAABC00, 3), | 36 | "ps_f16_const2": (0x42003D00, 0x3D004200, 0xAAAABC00, 3), |
| 37 | "ps_f16_pack": (0x34003C00, 0x38003400, 0x34000000, 0x44004200), | 37 | "ps_f16_pack": (0x34003C00, 0x38003400, 0x34000000, 0x44004200), |
| 38 | # neg/abs on the selected half: a sign flip / clear before packing (SHADER-260; the rule was measured on | ||
| 39 | # gfx1036 and these words follow it, they are not a direct readback of this shader) | ||
| 40 | "ps_f16_pack_mods": (0x4400B400, 0xC4003400, 0x4400C200, 0xB400B400), | ||
| 38 | } | 41 | } |
| 39 | OLD = 0xAAAA5555 | 42 | OLD = 0xAAAA5555 |
| 40 | 43 | ||
| @@ -137,9 +140,18 @@ def ref_pack(): | |||
| 137 | (v0 & w) << 16 | const(2.0) >> 16, (v1 & w) << 16 | v0 >> 16) | 140 | (v0 & w) << 16 | const(2.0) >> 16, (v1 & w) << 16 | v0 >> 16) |
| 138 | 141 | ||
| 139 | 142 | ||
| 143 | def ref_pack_mods(): | ||
| 144 | # -v / |v| on the selected half: NEG flips bit 15, ABS clears it, ABS first. | ||
| 145 | v0, v1, w = 0x42003400, 0x34004400, 0xFFFF | ||
| 146 | lo0, hi0, lo1, hi1 = v0 & w, v0 >> 16, v1 & w, v1 >> 16 | ||
| 147 | return (lo0 ^ 0x8000 | (lo1 & 0x7FFF) << 16, lo0 | (lo1 ^ 0x8000) << 16, | ||
| 148 | hi0 ^ 0x8000 | lo1 << 16, lo0 ^ 0x8000 | (hi1 ^ 0x8000) << 16) | ||
| 149 | |||
| 150 | |||
| 140 | REFERENCE = {"ps_f16_med3_opsel": ref_med3_opsel, "ps_f16_med3_mods": ref_med3_mods, "ps_f16_vop2": ref_vop2, | 151 | REFERENCE = {"ps_f16_med3_opsel": ref_med3_opsel, "ps_f16_med3_mods": ref_med3_mods, "ps_f16_vop2": ref_vop2, |
| 141 | "ps_f16_vop2b": ref_vop2b, "ps_f16_vop1": ref_vop1, "ps_f16_vop1b": ref_vop1b, | 152 | "ps_f16_vop2b": ref_vop2b, "ps_f16_vop1": ref_vop1, "ps_f16_vop1b": ref_vop1b, |
| 142 | "ps_f16_const": ref_const, "ps_f16_const2": ref_const2, "ps_f16_pack": ref_pack} | 153 | "ps_f16_const": ref_const, "ps_f16_const2": ref_const2, "ps_f16_pack": ref_pack, |
| 154 | "ps_f16_pack_mods": ref_pack_mods} | ||
| 143 | NAMES = sorted(HARDWARE) | 155 | NAMES = sorted(HARDWARE) |
| 144 | 156 | ||
| 145 | 157 | ||
diff --git a/tests/test_f16_op_sel.py b/tests/test_f16_op_sel.py index 9db45e65f..64041e7e7 100644 --- a/tests/test_f16_op_sel.py +++ b/tests/test_f16_op_sel.py | |||
| @@ -40,6 +40,8 @@ def left_shifts(spv): | |||
| 40 | OPS = [ | 40 | OPS = [ |
| 41 | ("v_fma_f16", "v_fma_f16 v3, v1, v1, v1", 3), | 41 | ("v_fma_f16", "v_fma_f16 v3, v1, v1, v1", 3), |
| 42 | ("v_med3_f16", "v_med3_f16 v3, v1, v1, v1", 3), | 42 | ("v_med3_f16", "v_med3_f16 v3, v1, v1, v1", 3), |
| 43 | ("v_min3_f16", "v_min3_f16 v3, v1, v1, v1", 3), | ||
| 44 | ("v_max3_f16", "v_max3_f16 v3, v1, v1, v1", 3), | ||
| 43 | ("v_add_f16", "v_add_f16_e64 v3, v1, v1", 2), | 45 | ("v_add_f16", "v_add_f16_e64 v3, v1, v1", 2), |
| 44 | ("v_sub_f16", "v_sub_f16_e64 v3, v1, v1", 2), | 46 | ("v_sub_f16", "v_sub_f16_e64 v3, v1, v1", 2), |
| 45 | ("v_subrev_f16", "v_subrev_f16_e64 v3, v1, v1", 2), | 47 | ("v_subrev_f16", "v_subrev_f16_e64 v3, v1, v1", 2), |
diff --git a/tests/test_f16_op_sel_values.py b/tests/test_f16_op_sel_values.py index 6435652df..d1ae359db 100644 --- a/tests/test_f16_op_sel_values.py +++ b/tests/test_f16_op_sel_values.py | |||
| @@ -29,6 +29,8 @@ OPS = { | |||
| 29 | "v_min_f16": ("v_min_f16_e64 v3, {0}, {1}", 2, min), | 29 | "v_min_f16": ("v_min_f16_e64 v3, {0}, {1}", 2, min), |
| 30 | "v_fma_f16": ("v_fma_f16 v3, {0}, {1}, {2}", 3, lambda a, b, c: a * b + c), | 30 | "v_fma_f16": ("v_fma_f16 v3, {0}, {1}, {2}", 3, lambda a, b, c: a * b + c), |
| 31 | "v_med3_f16": ("v_med3_f16 v3, {0}, {1}, {2}", 3, median), | 31 | "v_med3_f16": ("v_med3_f16 v3, {0}, {1}, {2}", 3, median), |
| 32 | "v_min3_f16": ("v_min3_f16 v3, {0}, {1}, {2}", 3, min), | ||
| 33 | "v_max3_f16": ("v_max3_f16 v3, {0}, {1}, {2}", 3, max), | ||
| 32 | "v_sqrt_f16": ("v_sqrt_f16_e64 v3, {0}", 1, lambda a: a ** 0.5), | 34 | "v_sqrt_f16": ("v_sqrt_f16_e64 v3, {0}", 1, lambda a: a ** 0.5), |
| 33 | "v_rcp_f16": ("v_rcp_f16_e64 v3, {0}", 1, lambda a: 1 / a), | 35 | "v_rcp_f16": ("v_rcp_f16_e64 v3, {0}", 1, lambda a: 1 / a), |
| 34 | } | 36 | } |
diff --git a/tests/test_fma_mix_probe.py b/tests/test_fma_mix_probe.py index db85fcd08..46c49f0cd 100644 --- a/tests/test_fma_mix_probe.py +++ b/tests/test_fma_mix_probe.py | |||
| @@ -65,14 +65,13 @@ class Inputs(unittest.TestCase): | |||
| 65 | 65 | ||
| 66 | 66 | ||
| 67 | class Translator(unittest.TestCase): | 67 | class Translator(unittest.TestCase): |
| 68 | def test_translator_rounds_twice(self): | 68 | def test_translator_rounds_once(self): |
| 69 | # docs/design.md, Known approximations: nearest-mode v_fma_mix* takes the f32 Fma and then narrows. If the | 69 | # docs/design.md, Known approximations: v_fma_mix* rounds once straight to f16 (measured on RDNA2 hardware). |
| 70 | # translator is changed to round once (after a hardware measurement), this test and that sentence change too. | ||
| 71 | got = probe.run_translator() | 70 | got = probe.run_translator() |
| 72 | rule, _ = probe.verdict(list(zip(probe.CASES, got))) | 71 | rule, _ = probe.verdict(list(zip(probe.CASES, got))) |
| 73 | self.assertEqual(rule, probe.DOUBLE) | 72 | self.assertEqual(rule, probe.SINGLE) |
| 74 | for case, w in zip(probe.CASES, got): | 73 | for case, w in zip(probe.CASES, got): |
| 75 | self.assertEqual(w, word(case, BY_HAND[case.name][1]), case.name) | 74 | self.assertEqual(w, word(case, BY_HAND[case.name][0]), case.name) |
| 76 | 75 | ||
| 77 | def test_compute_listing_gives_the_pixel_shader_words(self): | 76 | def test_compute_listing_gives_the_pixel_shader_words(self): |
| 78 | # The Vulkan side's shader (operands from user SGPRs, one store per case) on the CPU interpreter, with the | 77 | # The Vulkan side's shader (operands from user SGPRs, one store per case) on the CPU interpreter, with the |
| @@ -149,7 +148,7 @@ class Command(unittest.TestCase): | |||
| 149 | with contextlib.redirect_stdout(buf): | 148 | with contextlib.redirect_stdout(buf): |
| 150 | rc = probe.main([]) | 149 | rc = probe.main([]) |
| 151 | self.assertEqual(rc, 0) | 150 | self.assertEqual(rc, 0) |
| 152 | self.assertIn("translator: follows double rounding", buf.getvalue()) | 151 | self.assertIn("translator: follows single rounding", buf.getvalue()) |
| 153 | 152 | ||
| 154 | def test_unknown_side_and_missing_build_are_usage_errors(self): | 153 | def test_unknown_side_and_missing_build_are_usage_errors(self): |
| 155 | import contextlib | 154 | import contextlib |
diff --git a/tests/test_fspx_unpack.py b/tests/test_fspx_unpack.py index 3c9c843fc..6d42dab37 100644 --- a/tests/test_fspx_unpack.py +++ b/tests/test_fspx_unpack.py | |||
| @@ -227,6 +227,24 @@ class Cli(unittest.TestCase): | |||
| 227 | self.assertEqual(code, 1) | 227 | self.assertEqual(code, 1) |
| 228 | self.assertIn("FSPX status 5", err) | 228 | self.assertIn("FSPX status 5", err) |
| 229 | 229 | ||
| 230 | def test_short_kind0_unpacks_without_keyerror(self): | ||
| 231 | with tempfile.TemporaryDirectory() as t: | ||
| 232 | src = os.path.join(t, "short.fspx") | ||
| 233 | with open(src, "wb") as f: | ||
| 234 | f.write(make_fspx([(0, struct.pack("<2I", 1, 2)), (6, program())])) | ||
| 235 | out = os.path.join(t, "out") | ||
| 236 | code, _, err = self.run_tool(src, "--out", out) | ||
| 237 | self.assertEqual(code, 0) | ||
| 238 | self.assertEqual(err, "") | ||
| 239 | with open(os.path.join(out, "index.json"), encoding="utf-8") as f: | ||
| 240 | index = json.load(f) | ||
| 241 | self.assertEqual(len(index), 1) | ||
| 242 | self.assertNotIn("threads", index[0]) | ||
| 243 | self.assertNotIn("wave32", index[0]) | ||
| 244 | with open(os.path.join(out, "fspx", "short.json"), encoding="utf-8") as f: | ||
| 245 | meta = json.load(f) | ||
| 246 | self.assertEqual(meta["words"], [1, 2]) | ||
| 247 | |||
| 230 | 248 | ||
| 231 | class TranslatorSidecars(unittest.TestCase): | 249 | class TranslatorSidecars(unittest.TestCase): |
| 232 | """rdna2spirv reads an FSPX program's code and dispatch state from fspx/ when there is no FSSM blob.""" | 250 | """rdna2spirv reads an FSPX program's code and dispatch state from fspx/ when there is no FSSM blob.""" |
diff --git a/tests/test_gamedata_index.py b/tests/test_gamedata_index.py index 1409150dd..832926511 100644 --- a/tests/test_gamedata_index.py +++ b/tests/test_gamedata_index.py | |||
| @@ -150,6 +150,25 @@ class GamedataIndexTest(unittest.TestCase): | |||
| 150 | self.assertEqual(rows[0]["root"], "RootA") | 150 | self.assertEqual(rows[0]["root"], "RootA") |
| 151 | self.assertEqual(rows[0]["type"], "xml") | 151 | self.assertEqual(rows[0]["type"], "xml") |
| 152 | 152 | ||
| 153 | def test_printable_page_directory_stream_is_not_xml(self): | ||
| 154 | # A resource stream with the "0DRP" page marker at +16 whose first 4 KiB are over 95% printable and hold a | ||
| 155 | # "<": data.rpf's 337 such streams were reported as incomplete XML with no root. | ||
| 156 | head = bytes(8) + bytes.fromhex("80ca005000000000") + b"0DRP" + bytes(12) | ||
| 157 | page = head + (b"<abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ>" * 80)[:4096 - len(head)] | ||
| 158 | page += bytes(512) | ||
| 159 | tool = load_tool() | ||
| 160 | self.assertGreater(tool.printable(page), 0.95) # the heuristic alone would call it text | ||
| 161 | self.add(page) | ||
| 162 | self.finish() | ||
| 163 | out = os.path.join(self.root, "index.json") | ||
| 164 | p = self.run_tool(self.carve, "--json", out) | ||
| 165 | self.assertEqual(p.returncode, 0, p.stdout + p.stderr) | ||
| 166 | with open(out, encoding="utf-8") as f: | ||
| 167 | data = json.load(f) | ||
| 168 | self.assertNotIn("xml", data["summary"]["types"]) | ||
| 169 | self.assertEqual(data["summary"]["xml_incomplete"], 0) | ||
| 170 | self.assertEqual([(r["type"], r["detail"]) for r in data["rows"]], [("other", "0DRP")]) | ||
| 171 | |||
| 153 | def test_archive_runs_the_carver_and_reads_roots(self): | 172 | def test_archive_runs_the_carver_and_reads_roots(self): |
| 154 | xml = b'<?xml version="1.0"?>\n<RootA><!-- synthetic fixture, longer than 64 bytes --><Item value="1"/></RootA>' | 173 | xml = b'<?xml version="1.0"?>\n<RootA><!-- synthetic fixture, longer than 64 bytes --><Item value="1"/></RootA>' |
| 155 | blob = b"\x00\x01\x02binary\xff" * 32 | 174 | blob = b"\x00\x01\x02binary\xff" * 32 |
diff --git a/tests/test_hashdict.py b/tests/test_hashdict.py index c517f6a92..b9cc76a9a 100644 --- a/tests/test_hashdict.py +++ b/tests/test_hashdict.py | |||
| @@ -359,6 +359,32 @@ class CarveAndExtraCLITest(unittest.TestCase): | |||
| 359 | self.assertEqual(p_lookup.returncode, 0, p_lookup.stderr) | 359 | self.assertEqual(p_lookup.returncode, 0, p_lookup.stderr) |
| 360 | self.assertIn(f"{lookup_hash} model_prop", p_lookup.stdout) | 360 | self.assertIn(f"{lookup_hash} model_prop", p_lookup.stdout) |
| 361 | 361 | ||
| 362 | def test_one_archive_folder_is_harvested_as_that_archive(self): | ||
| 363 | # <work>/carve/common (its own index.json, as the gamedata_* tools take it) used to give an empty | ||
| 364 | # dictionary with exit 0: only <carve>/<archive>/index.json was looked for. | ||
| 365 | p = self.run_tool(os.path.join(self.carve_dir, "common"), "--out", self.out_json) | ||
| 366 | self.assertEqual(p.returncode, 0, p.stderr) | ||
| 367 | self.assertIn("common: ", p.stdout) | ||
| 368 | with open(self.out_json, encoding="utf-8") as f: | ||
| 369 | d = json.load(f) | ||
| 370 | self.assertEqual(d.get(f"{hashdict.joaat('common_archive_asset'):08x}"), "common_archive_asset") | ||
| 371 | self.assertNotIn(f"{hashdict.joaat('bink2_skipped_asset'):08x}", d) | ||
| 372 | # An archive outside --archives still contributes only its PSIN/RBF0 blobs. | ||
| 373 | p = self.run_tool(os.path.join(self.carve_dir, "custom_pack"), "--out", self.out_json) | ||
| 374 | self.assertEqual(p.returncode, 0, p.stderr) | ||
| 375 | with open(self.out_json, encoding="utf-8") as f: | ||
| 376 | self.assertEqual(json.load(f), {f"{hashdict.joaat('pso_metadata_token'):08x}": "pso_metadata_token"}) | ||
| 377 | |||
| 378 | def test_out_naming_a_one_archive_index_is_refused(self): | ||
| 379 | index = os.path.join(self.carve_dir, "common", "index.json") | ||
| 380 | with open(index, "rb") as f: | ||
| 381 | before = f.read() | ||
| 382 | p = self.run_tool(os.path.join(self.carve_dir, "common"), "--out", index) | ||
| 383 | self.assertEqual(p.returncode, 2, p.stderr) | ||
| 384 | self.assertIn("is one of the inputs", p.stderr) | ||
| 385 | with open(index, "rb") as f: | ||
| 386 | self.assertEqual(f.read(), before) | ||
| 387 | |||
| 362 | def test_build_requires_an_explicit_carve_directory(self): | 388 | def test_build_requires_an_explicit_carve_directory(self): |
| 363 | empty = os.path.join(self.dir, "empty") | 389 | empty = os.path.join(self.dir, "empty") |
| 364 | os.mkdir(empty) | 390 | os.mkdir(empty) |
diff --git a/tests/test_imhex_patterns.py b/tests/test_imhex_patterns.py new file mode 100644 index 000000000..9e0cc1cca --- /dev/null +++ b/tests/test_imhex_patterns.py | |||
| @@ -0,0 +1,170 @@ | |||
| 1 | """Tests for the ImHex patterns in tools/imhex. | ||
| 2 | |||
| 3 | python -I tests/test_imhex_patterns.py | ||
| 4 | |||
| 5 | Every byte here is built by the test: no game file, name or path is used. The RBF0 inputs are first checked with | ||
| 6 | tools/rbf0_index.py, the repository's own parser. When ImHex is installed, each pattern then runs on the same bytes | ||
| 7 | through ImHex's pattern-language CLI (`imhex --pl format ... -f json`) and the decoded fields are compared with the | ||
| 8 | parser's result. ImHex is found through LEONIDA_IMHEX, then PATH, then its default Windows install folder; without it | ||
| 9 | the ImHex half is skipped and the rest still runs. | ||
| 10 | """ | ||
| 11 | import json | ||
| 12 | import os | ||
| 13 | import shutil | ||
| 14 | import struct | ||
| 15 | import subprocess | ||
| 16 | import sys | ||
| 17 | import tempfile | ||
| 18 | import unittest | ||
| 19 | |||
| 20 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 21 | PATTERNS = os.path.join(ROOT, "tools", "imhex") | ||
| 22 | sys.path.insert(0, os.path.join(ROOT, "tools")) | ||
| 23 | |||
| 24 | import rbf0_index # noqa: E402 | ||
| 25 | |||
| 26 | |||
| 27 | def find_imhex(): | ||
| 28 | candidates = [os.environ.get("LEONIDA_IMHEX"), shutil.which("imhex")] | ||
| 29 | if os.name == "nt": | ||
| 30 | candidates.append(os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "ImHex", "imhex.exe")) | ||
| 31 | for c in candidates: | ||
| 32 | if c and os.path.isfile(c): | ||
| 33 | return c | ||
| 34 | return None | ||
| 35 | |||
| 36 | |||
| 37 | IMHEX = find_imhex() | ||
| 38 | |||
| 39 | |||
| 40 | # ---- synthetic inputs ------------------------------------------------------------------------------------------ | ||
| 41 | |||
| 42 | def _name(name): | ||
| 43 | return struct.pack("<H", len(name)) + name | ||
| 44 | |||
| 45 | |||
| 46 | def rbf0_stream(wide): | ||
| 47 | """One resource with every record type of docs/rbf0.md section 3, then bytes past the root close.""" | ||
| 48 | q, d = ("Q", "d") if wide else ("I", "f") | ||
| 49 | q, d, d3 = "<" + q, "<" + d, "<" + d * 3 | ||
| 50 | out = b"RBF0" + (rbf0_index.PROLOGUE if wide else b"") | ||
| 51 | out += bytes([0, 0x00]) + _name(b"root") + struct.pack("<HHH", 0, 0, 1) | ||
| 52 | out += bytes([1, 0x10]) + _name(b"count") + struct.pack(q, 7) # the root's one attribute | ||
| 53 | out += bytes([2, 0x00]) + _name(b"item") + struct.pack("<HHH", 0, 0, 0) | ||
| 54 | out += bytes([3, 0x40]) + _name(b"scale") + struct.pack(d, 1.5) | ||
| 55 | out += bytes([4, 0x50]) + _name(b"pos") + struct.pack(d3, 1.0, -2.0, 0.25) | ||
| 56 | out += bytes([5, 0x60]) + _name(b"label") + struct.pack("<H", 5) + b"probe" | ||
| 57 | out += bytes([6, 0x20]) + _name(b"flag") + bytes([6, 0x30]) # new, then reused | ||
| 58 | out += bytes([3, 0x10]) + struct.pack(q, 9) # reused with another type | ||
| 59 | out += bytes([0xFD, 0xFF]) + struct.pack("<I", 5) + b"text\x00" | ||
| 60 | out += b"\xff\xff" # close item | ||
| 61 | out += b"\xff\xff" # close root: the end | ||
| 62 | return out + b"\x00\x11\x22\x33" # not part of the resource | ||
| 63 | |||
| 64 | |||
| 65 | def rpf9_archive(data_offset=0x100, size=0x140): | ||
| 66 | head = b"9FPR" + struct.pack("<III", data_offset, 0x11, 0x22) | ||
| 67 | toc = bytes((i * 37) & 0xFF for i in range(data_offset - len(head))) | ||
| 68 | body = b"\x78\x9c" + bytes(size - data_offset - 2) | ||
| 69 | return head + toc + body | ||
| 70 | |||
| 71 | |||
| 72 | def pragma_magic(pattern): | ||
| 73 | """The bytes of `#pragma magic [ .. ] @ 0x00` in a pattern file.""" | ||
| 74 | with open(os.path.join(PATTERNS, pattern), encoding="utf-8") as f: | ||
| 75 | for line in f: | ||
| 76 | if line.startswith("#pragma magic"): | ||
| 77 | inside = line[line.index("[") + 1:line.index("]")] | ||
| 78 | return bytes(int(b, 16) for b in inside.split()) | ||
| 79 | return None | ||
| 80 | |||
| 81 | |||
| 82 | # ---- tests ----------------------------------------------------------------------------------------------------- | ||
| 83 | |||
| 84 | class InputsAndMagic(unittest.TestCase): | ||
| 85 | """Runs everywhere: the synthetic inputs are valid RBF0 by the repository's parser, and the magics agree.""" | ||
| 86 | |||
| 87 | def test_synthetic_streams_parse(self): | ||
| 88 | for wide in (True, False): | ||
| 89 | r = rbf0_index.parse_rbf0(rbf0_stream(wide)[:-4]) | ||
| 90 | self.assertEqual(r["status"], "ok", r["error"]) | ||
| 91 | self.assertEqual(r["layout"], "wide-64" if wide else "narrow-32") | ||
| 92 | self.assertEqual(r["elements"], 2) | ||
| 93 | self.assertEqual(r["descriptors"], 7) | ||
| 94 | |||
| 95 | def test_pattern_magics(self): | ||
| 96 | self.assertEqual(pragma_magic("rbf0.hexpat"), rbf0_index.MAGIC) | ||
| 97 | self.assertEqual(pragma_magic("rpf9.hexpat"), b"9FPR") # RPF9 stored little-endian (docs/rpf.md) | ||
| 98 | |||
| 99 | |||
| 100 | @unittest.skipUnless(IMHEX, "ImHex is not installed (set LEONIDA_IMHEX to imhex.exe)") | ||
| 101 | class PatternsInImHex(unittest.TestCase): | ||
| 102 | def setUp(self): | ||
| 103 | self.tmp = tempfile.TemporaryDirectory() | ||
| 104 | self.addCleanup(self.tmp.cleanup) | ||
| 105 | |||
| 106 | def run_pattern(self, pattern, data): | ||
| 107 | """Returns (decoded JSON or None, combined output).""" | ||
| 108 | src = os.path.join(self.tmp.name, "input.bin") | ||
| 109 | out = os.path.join(self.tmp.name, "out.json") | ||
| 110 | if os.path.exists(out): | ||
| 111 | os.remove(out) | ||
| 112 | with open(src, "wb") as f: | ||
| 113 | f.write(data) | ||
| 114 | cmd = [IMHEX, "--pl", "format", "-i", src, "-p", os.path.join(PATTERNS, pattern), "-o", out, "-f", "json"] | ||
| 115 | includes = os.path.join(os.path.dirname(IMHEX), "includes") | ||
| 116 | if os.path.isdir(includes): | ||
| 117 | cmd += ["-I", includes] | ||
| 118 | p = subprocess.run(cmd, capture_output=True, text=True, timeout=120) | ||
| 119 | log = p.stdout + p.stderr | ||
| 120 | if not os.path.exists(out): | ||
| 121 | return None, log | ||
| 122 | with open(out, encoding="utf-8") as f: | ||
| 123 | return json.load(f), log | ||
| 124 | |||
| 125 | def check_rbf0(self, wide): | ||
| 126 | data = rbf0_stream(wide) | ||
| 127 | ref = rbf0_index.parse_rbf0(data[:-4]) | ||
| 128 | got, log = self.run_pattern("rbf0.hexpat", data) | ||
| 129 | self.assertIsNotNone(got, log) | ||
| 130 | self.assertEqual("prologue" in got["header"], wide) | ||
| 131 | records = got["records"] | ||
| 132 | |||
| 133 | names = [r["name"] for r in records if "name" in r] | ||
| 134 | self.assertEqual(names, ref["descriptor_names"]) | ||
| 135 | self.assertEqual(sum(1 for r in records if r["index"] < 0xFD and r["type"] == 0x00), ref["elements"]) | ||
| 136 | ints = [r["value_int"] for r in records if "value_int" in r] | ||
| 137 | self.assertEqual(ints, ref["ints"]) | ||
| 138 | floats = [] | ||
| 139 | for r in records: | ||
| 140 | floats += [r["value_float"]] if "value_float" in r else r.get("value_vec3", []) | ||
| 141 | self.assertEqual(floats, ref["floats"]) | ||
| 142 | strings = [r.get("value_string", r.get("text", "")) for r in records if "value_string" in r or "text" in r] | ||
| 143 | self.assertEqual([s.split("%00")[0] for s in strings], ref["strings"]) | ||
| 144 | self.assertEqual([r["attribute_count"] for r in records if "attribute_count" in r], [1, 0]) | ||
| 145 | # The pattern stops where the root closes, as parse_rbf0 does: the 4 trailing bytes are not records. | ||
| 146 | self.assertEqual(records[-1]["index"], 0xFF) | ||
| 147 | self.assertEqual(sum(1 for r in records if r["index"] == 0xFF), 2) | ||
| 148 | |||
| 149 | def test_rbf0_wide(self): | ||
| 150 | self.check_rbf0(wide=True) | ||
| 151 | |||
| 152 | def test_rbf0_narrow(self): | ||
| 153 | self.check_rbf0(wide=False) | ||
| 154 | |||
| 155 | def test_rpf9_header_and_opaque_toc(self): | ||
| 156 | got, log = self.run_pattern("rpf9.hexpat", rpf9_archive(data_offset=0x100)) | ||
| 157 | self.assertIsNotNone(got, log) | ||
| 158 | self.assertEqual(got["header"]["magic"], "9FPR") | ||
| 159 | self.assertEqual(got["header"]["data_offset"], 0x100) | ||
| 160 | self.assertEqual((got["header"]["u32_08"], got["header"]["u32_0c"]), (0x11, 0x22)) | ||
| 161 | self.assertEqual(len(got["header_rest_and_toc"]), 0x100 - 0x10) | ||
| 162 | |||
| 163 | def test_rpf9_rejects_a_data_offset_past_the_end(self): | ||
| 164 | got, log = self.run_pattern("rpf9.hexpat", rpf9_archive(data_offset=0x100, size=0x140)[:0x20]) | ||
| 165 | self.assertIsNone(got) | ||
| 166 | self.assertIn("data offset is outside the file", log) | ||
| 167 | |||
| 168 | |||
| 169 | if __name__ == "__main__": | ||
| 170 | unittest.main() | ||
diff --git a/tests/test_int_hw_probe.py b/tests/test_int_hw_probe.py new file mode 100644 index 000000000..f2287f9a6 --- /dev/null +++ b/tests/test_int_hw_probe.py | |||
| @@ -0,0 +1,119 @@ | |||
| 1 | """Unit tests for tools/int_hw_probe.py (SHADER-137). Standard library only; no GPU or game files needed.""" | ||
| 2 | import io | ||
| 3 | import json | ||
| 4 | import os | ||
| 5 | import sys | ||
| 6 | import tempfile | ||
| 7 | import unittest | ||
| 8 | import unittest.mock | ||
| 9 | from contextlib import redirect_stderr, redirect_stdout | ||
| 10 | from pathlib import Path | ||
| 11 | |||
| 12 | ROOT = Path(__file__).resolve().parents[1] | ||
| 13 | TOOLS = ROOT / "tools" | ||
| 14 | sys.dont_write_bytecode = True | ||
| 15 | if str(TOOLS) not in sys.path: | ||
| 16 | sys.path.insert(0, str(TOOLS)) | ||
| 17 | |||
| 18 | import int_hw_probe as probe # noqa: E402 | ||
| 19 | from hw_oracle import runner as hw_runner # noqa: E402 | ||
| 20 | |||
| 21 | |||
| 22 | class IntHwProbeTests(unittest.TestCase): | ||
| 23 | def test_cases_unique_and_nonempty(self): | ||
| 24 | cases = probe.build_cases() | ||
| 25 | self.assertGreaterEqual(len(cases), 80) | ||
| 26 | names = [c.name for c in cases] | ||
| 27 | self.assertEqual(len(names), len(set(names))) | ||
| 28 | groups = {c.group for c in cases} | ||
| 29 | self.assertGreaterEqual(len(groups), 19) | ||
| 30 | for key in probe.KNOWN_DIVERGENCES: | ||
| 31 | self.assertIn(key, names) | ||
| 32 | |||
| 33 | def test_wave32_and_wave64_placeholder_expansion(self): | ||
| 34 | by_name = {c.name: c for c in probe.build_cases()} | ||
| 35 | c = by_name["v_mad_u64_u32_inactive_lane"] | ||
| 36 | w32 = "\n".join(c.lines(wave=32)) | ||
| 37 | w64 = "\n".join(c.lines(wave=64)) | ||
| 38 | self.assertIn("s_mov_b32 s14, exec_lo", w32) | ||
| 39 | self.assertIn("v_mad_u64_u32 v[8:9], vcc_lo", w32) | ||
| 40 | self.assertIn("s_mov_b64 s[14:15], exec", w64) | ||
| 41 | self.assertIn("v_mad_u64_u32 v[8:9], vcc,", w64) | ||
| 42 | self.assertNotIn("{", w32) | ||
| 43 | self.assertNotIn("{", w64) | ||
| 44 | |||
| 45 | def test_self_test_and_translator_groups(self): | ||
| 46 | buf = io.StringIO() | ||
| 47 | with redirect_stdout(buf): | ||
| 48 | rc = probe.main(["--self-test"]) | ||
| 49 | self.assertEqual(rc, 0) | ||
| 50 | self.assertIn("self-test:", buf.getvalue()) | ||
| 51 | |||
| 52 | def test_list_groups_and_unknown_group(self): | ||
| 53 | out, err = io.StringIO(), io.StringIO() | ||
| 54 | with redirect_stdout(out): | ||
| 55 | rc = probe.main(["--list-groups"]) | ||
| 56 | self.assertEqual(rc, 0) | ||
| 57 | self.assertIn("valu_cvt_pknorm", out.getvalue()) | ||
| 58 | |||
| 59 | with redirect_stderr(err): | ||
| 60 | rc = probe.main(["--group", "does_not_exist"]) | ||
| 61 | self.assertEqual(rc, 2) | ||
| 62 | self.assertIn("unknown group", err.getvalue()) | ||
| 63 | |||
| 64 | def test_hw_unavailable_returns_77(self): | ||
| 65 | err = io.StringIO() | ||
| 66 | with unittest.mock.patch.object(hw_runner, "open_oracle", side_effect=hw_runner.Unavailable("no GPU")): | ||
| 67 | with redirect_stderr(err): | ||
| 68 | rc = probe.main(["--oracle", "hw", "--group", "salu_bfe_past31"]) | ||
| 69 | self.assertEqual(rc, 77) | ||
| 70 | self.assertIn("no GPU", err.getvalue()) | ||
| 71 | |||
| 72 | def test_known_divergence_vs_strict_and_json_output(self): | ||
| 73 | # Mock hardware oracle returning the measured gfx1035 words for valu_cvt_flr_rpi. | ||
| 74 | measured = { | ||
| 75 | "v_cvt_rpi_precision": [0x00000000, 0x00800001, 0x00FFFFFF, 0x00000000], | ||
| 76 | "v_cvt_flr_rpi_nan_inf": [0x7FFFFFFF, 0x80000000, 0x7FFFFFFF, 0x80000000], | ||
| 77 | "v_cvt_i32_f32_nan_control": [0x00000000, 0x00000000, 0x00000000, 0x00000000], | ||
| 78 | "v_cvt_flr_edges": [0xFFFFFFFE, 0x7FFFFFFF, 0x80000000, 0x7FFFFFFF], | ||
| 79 | } | ||
| 80 | fake_hw = ("device=mock arch=gfx1035", {32: measured, 64: measured}) | ||
| 81 | with tempfile.TemporaryDirectory() as tmp: | ||
| 82 | jpath = os.path.join(tmp, "out.json") | ||
| 83 | out = io.StringIO() | ||
| 84 | with unittest.mock.patch.object(probe, "run_hw", return_value=fake_hw): | ||
| 85 | with redirect_stdout(out): | ||
| 86 | rc = probe.main(["--oracle", "both", "--group", "valu_cvt_flr_rpi", "--json", jpath]) | ||
| 87 | self.assertEqual(rc, 0) | ||
| 88 | self.assertIn("2 match, 2 known divergence, 0 unexpected mismatch, 0 wave32/64 diff", out.getvalue()) | ||
| 89 | data = json.loads(Path(jpath).read_text(encoding="utf-8")) | ||
| 90 | self.assertEqual(data["device"], "device=mock arch=gfx1035") | ||
| 91 | self.assertEqual(len(data["cases"]), 4) | ||
| 92 | |||
| 93 | out2 = io.StringIO() | ||
| 94 | with unittest.mock.patch.object(probe, "run_hw", return_value=fake_hw): | ||
| 95 | with redirect_stdout(out2): | ||
| 96 | rc_strict = probe.main(["--oracle", "both", "--group", "valu_cvt_flr_rpi", "--strict"]) | ||
| 97 | self.assertEqual(rc_strict, 1) | ||
| 98 | |||
| 99 | err = io.StringIO() | ||
| 100 | with unittest.mock.patch.object(probe, "run_hw", return_value=fake_hw): | ||
| 101 | with redirect_stderr(err): | ||
| 102 | rc_dir = probe.main(["--oracle", "both", "--group", "valu_cvt_flr_rpi", "--json", tmp]) | ||
| 103 | self.assertEqual(rc_dir, 2) | ||
| 104 | |||
| 105 | def test_unexpected_mismatch_and_wave_diff_fail(self): | ||
| 106 | bad_hw = ("device=mock arch=gfx1035", { | ||
| 107 | 32: {"s_bfe_i32_past31": [1, 2, 3, 4], "s_bfe_u32_past31": [0, 0, 0, 0], "s_bfe_i32_width0": [0, 0, 0, 0]}, | ||
| 108 | 64: {"s_bfe_i32_past31": [1, 2, 3, 5], "s_bfe_u32_past31": [0, 0, 0, 0], "s_bfe_i32_width0": [0, 0, 0, 0]}, | ||
| 109 | }) | ||
| 110 | out = io.StringIO() | ||
| 111 | with unittest.mock.patch.object(probe, "run_hw", return_value=bad_hw): | ||
| 112 | with redirect_stdout(out): | ||
| 113 | rc = probe.main(["--oracle", "both", "--group", "salu_bfe_past31"]) | ||
| 114 | self.assertEqual(rc, 1) | ||
| 115 | self.assertIn("WAVE_DIFF", out.getvalue()) | ||
| 116 | |||
| 117 | |||
| 118 | if __name__ == "__main__": | ||
| 119 | unittest.main() | ||
diff --git a/tests/test_make_game_assets_pools.py b/tests/test_make_game_assets_pools.py index 9716b5ad7..0de945dfe 100644 --- a/tests/test_make_game_assets_pools.py +++ b/tests/test_make_game_assets_pools.py | |||
| @@ -39,7 +39,7 @@ class AssetsPoolsTest(unittest.TestCase): | |||
| 39 | pass | 39 | pass |
| 40 | 40 | ||
| 41 | def pool(self, rel, size=100): | 41 | def pool(self, rel, size=100): |
| 42 | path = os.path.join(self.game, rel) | 42 | path = os.path.join(self.game, *rel.split("/")) |
| 43 | os.makedirs(os.path.dirname(path), exist_ok=True) | 43 | os.makedirs(os.path.dirname(path), exist_ok=True) |
| 44 | with open(path, "wb") as f: | 44 | with open(path, "wb") as f: |
| 45 | f.write(b"x" * size) | 45 | f.write(b"x" * size) |
diff --git a/tests/test_make_game_preflight.py b/tests/test_make_game_preflight.py index eb6964bb1..f1950cd34 100644 --- a/tests/test_make_game_preflight.py +++ b/tests/test_make_game_preflight.py | |||
| @@ -654,9 +654,26 @@ class PathAndGameSelectionTest(PreflightTestBase): | |||
| 654 | self.assert_fails(make_game.choose_game, | 654 | self.assert_fails(make_game.choose_game, |
| 655 | match="More than one copy found: choose one with --game.") | 655 | match="More than one copy found: choose one with --game.") |
| 656 | 656 | ||
| 657 | def default_out_in(self, platform, icloud_documents): | ||
| 658 | """default_out() with a temporary home folder; icloud_documents makes the folder macOS keeps in iCloud | ||
| 659 | Drive when Desktop & Documents sync is on (~/Library/Mobile Documents/com~apple~CloudDocs/Documents).""" | ||
| 660 | with tempfile.TemporaryDirectory() as home: | ||
| 661 | if icloud_documents: | ||
| 662 | os.makedirs(os.path.join(home, "Library", "Mobile Documents", "com~apple~CloudDocs", "Documents")) | ||
| 663 | with mock.patch.object(make_game.os.path, "expanduser", lambda p: home + p[1:] if p.startswith("~") else p), \ | ||
| 664 | mock.patch.object(make_game.sys, "platform", platform): | ||
| 665 | return os.path.relpath(make_game.default_out(), home) | ||
| 666 | |||
| 657 | def test_default_out_matches_documents_folder(self): | 667 | def test_default_out_matches_documents_folder(self): |
| 658 | expected = os.path.join(os.path.expanduser("~"), "Documents", "Leonida") | 668 | for platform in ("win32", "linux", "darwin"): |
| 659 | self.assertEqual(make_game.default_out(), expected) | 669 | self.assertEqual(self.default_out_in(platform, False), os.path.join("Documents", "Leonida"), platform) |
| 670 | |||
| 671 | def test_default_out_leaves_icloud_synced_documents_on_a_mac(self): | ||
| 672 | # Before: with iCloud Desktop & Documents sync on, ~/Documents/Leonida (and its work folder, hundreds of GB | ||
| 673 | # made from the game) went into iCloud Drive, which uploads it and can evict the work files from the disk. | ||
| 674 | self.assertEqual(self.default_out_in("darwin", True), "Leonida") | ||
| 675 | # Only macOS keeps Documents in iCloud Drive this way; elsewhere the folder means nothing. | ||
| 676 | self.assertEqual(self.default_out_in("linux", True), os.path.join("Documents", "Leonida")) | ||
| 660 | 677 | ||
| 661 | def test_constants_definitions(self): | 678 | def test_constants_definitions(self): |
| 662 | self.assertEqual(make_game.STAGES, ["check", "shaders", "assets", "runtime", "pipelines"]) | 679 | self.assertEqual(make_game.STAGES, ["check", "shaders", "assets", "runtime", "pipelines"]) |
diff --git a/tests/test_make_game_wave64.py b/tests/test_make_game_wave64.py index 4a37bfb1e..3e2bfa939 100644 --- a/tests/test_make_game_wave64.py +++ b/tests/test_make_game_wave64.py | |||
| @@ -118,6 +118,20 @@ class DetectionGapsTest(unittest.TestCase): | |||
| 118 | text = real_format(("Big GPU", 64, ALL)) + "VkPhysicalDeviceProperties:\n\tdeviceName = Old GPU\n" | 118 | text = real_format(("Big GPU", 64, ALL)) + "VkPhysicalDeviceProperties:\n\tdeviceName = Old GPU\n" |
| 119 | self.assertIsNone(make_game.smallest_max_subgroup(text)) # one device says nothing: unknown, so on | 119 | self.assertIsNone(make_game.smallest_max_subgroup(text)) # one device says nothing: unknown, so on |
| 120 | 120 | ||
| 121 | def test_a_layered_api_name_is_not_another_device(self): | ||
| 122 | # VK_KHR_maintenance7 lists a layered driver's underlying API (MoltenVK on Metal) with its own deviceName, | ||
| 123 | # indented deeper and printed before the subgroup block: it is the same device, not one without a size. | ||
| 124 | layered = ("GPU0:\nVkPhysicalDeviceProperties:\n\tdeviceName = Apple M2 Max\n" | ||
| 125 | "VkPhysicalDeviceLayeredApiPropertiesListKHR:\n\tpLayeredApis: count = 1\n\t\t0:\n" | ||
| 126 | "\t\t\tlayeredAPI = PHYSICAL_DEVICE_LAYERED_API_METAL_KHR\n\t\t\tdeviceName = Apple M2 Max\n" | ||
| 127 | "VkPhysicalDeviceSubgroupSizeControlProperties:\n\tmaxSubgroupSize = 32\n") | ||
| 128 | self.assertEqual(make_game.smallest_max_subgroup(layered), 32) | ||
| 129 | layered_json = ('{"VkPhysicalDeviceProperties": {\n\t\t"deviceName": "Apple M2 Max"},\n' | ||
| 130 | '\t"VkPhysicalDeviceLayeredApiPropertiesListKHR": {"pLayeredApis": [\n' | ||
| 131 | '\t\t\t{"layeredAPI": 3,\n\t\t\t "deviceName": "Apple M2 Max"}]},\n' | ||
| 132 | '\t"VkPhysicalDeviceSubgroupSizeControlProperties": {\n\t\t"maxSubgroupSize": 32}}') | ||
| 133 | self.assertEqual(make_game.smallest_max_subgroup(layered_json), 32) | ||
| 134 | |||
| 121 | def test_a_device_printing_the_size_twice_does_not_hide_one_that_prints_none(self): | 135 | def test_a_device_printing_the_size_twice_does_not_hide_one_that_prints_none(self): |
| 122 | twice = ("VkPhysicalDeviceProperties:\n\tdeviceName = A\n" | 136 | twice = ("VkPhysicalDeviceProperties:\n\tdeviceName = A\n" |
| 123 | "VkPhysicalDeviceSubgroupSizeControlProperties:\n\tmaxSubgroupSize = 64\n" | 137 | "VkPhysicalDeviceSubgroupSizeControlProperties:\n\tmaxSubgroupSize = 64\n" |
| @@ -163,6 +177,46 @@ class DetectionGapsTest(unittest.TestCase): | |||
| 163 | self.assertTrue(self.decide(real_format(("A", 32, ALL)), '{"native64": true}')) # vulkaninfo wins: on | 177 | self.assertTrue(self.decide(real_format(("A", 32, ALL)), '{"native64": true}')) # vulkaninfo wins: on |
| 164 | 178 | ||
| 165 | 179 | ||
| 180 | class Rdna2AmdWindowsTest(unittest.TestCase): | ||
| 181 | """#857: AMD's Windows compiler for RDNA2 crashes on emulated LDS compute shaders. When the runtime's GPU is one | ||
| 182 | and runs wave64 natively, auto leaves emulation off even if another device (an Intel iGPU) is 32-wide.""" | ||
| 183 | |||
| 184 | RX6700 = '{"device": "AMD Radeon RX 6700", "native64": true, "rdna2_amd_windows": true}' | ||
| 185 | |||
| 186 | def decide(self, vulkaninfo, tool, mode="auto"): | ||
| 187 | def fake_run(args, **kw): | ||
| 188 | if os.path.basename(str(args[-1])) == "vk_subgroup_info.py": | ||
| 189 | return subprocess.CompletedProcess(args, 0 if "native64" in tool else 1, stdout=tool, stderr="") | ||
| 190 | return subprocess.CompletedProcess(args, 0, stdout=vulkaninfo, stderr="") | ||
| 191 | logged = [] | ||
| 192 | with mock.patch.object(make_game.shutil, "which", return_value="vulkaninfo"), \ | ||
| 193 | mock.patch.object(make_game.subprocess, "run", side_effect=fake_run), \ | ||
| 194 | mock.patch.object(make_game, "log", logged.append): | ||
| 195 | return make_game.wave64_emulate(mode), logged | ||
| 196 | |||
| 197 | def test_intel_igpu_and_rdna2_card_leaves_it_off(self): | ||
| 198 | on, logged = self.decide(real_format(("Intel iGPU", 32, ALL), ("AMD Radeon RX 6700", 64, ALL)), self.RX6700) | ||
| 199 | self.assertFalse(on) | ||
| 200 | self.assertIn("#857", logged[-1]) | ||
| 201 | self.assertIn("AMD Radeon RX 6700", logged[-1]) | ||
| 202 | |||
| 203 | def test_other_runtime_gpus_keep_emulation_on(self): | ||
| 204 | two = real_format(("Intel iGPU", 32, ALL), ("Big GPU", 64, ALL)) | ||
| 205 | for label, tool in (("rdna3", '{"native64": true, "rdna2_amd_windows": false}'), | ||
| 206 | ("older_tool_without_the_key", '{"native64": true}'), | ||
| 207 | ("rdna2_without_native64", '{"native64": false, "rdna2_amd_windows": true}'), | ||
| 208 | ("unreadable", '{"error": "no Vulkan loader found"}'), | ||
| 209 | ("not_json", "not json")): | ||
| 210 | with self.subTest(case=label): | ||
| 211 | self.assertTrue(self.decide(two, tool)[0]) | ||
| 212 | |||
| 213 | def test_rdna2_only_pc_is_unchanged(self): | ||
| 214 | self.assertFalse(self.decide(real_format(("AMD Radeon RX 6700", 64, ALL)), self.RX6700)[0]) | ||
| 215 | |||
| 216 | def test_explicit_on_is_taken_as_given(self): | ||
| 217 | self.assertTrue(self.decide(real_format(("AMD Radeon RX 6700", 64, ALL)), self.RX6700, mode="on")[0]) | ||
| 218 | |||
| 219 | |||
| 166 | class KeepEmulatedFlagTest(unittest.TestCase): | 220 | class KeepEmulatedFlagTest(unittest.TestCase): |
| 167 | """Only the default auto may keep emulated shaders; an explicit on or off is taken as given.""" | 221 | """Only the default auto may keep emulated shaders; an explicit on or off is taken as given.""" |
| 168 | 222 | ||
diff --git a/tests/test_manifest.py b/tests/test_manifest.py index ae335871a..52afc1cbc 100644 --- a/tests/test_manifest.py +++ b/tests/test_manifest.py | |||
| @@ -401,9 +401,9 @@ class ManifestAtomicCreateTest(unittest.TestCase): | |||
| 401 | f.write(b"atomic create payload") | 401 | f.write(b"atomic create payload") |
| 402 | self.out = os.path.join(self.tmp.name, "manifest.json") | 402 | self.out = os.path.join(self.tmp.name, "manifest.json") |
| 403 | 403 | ||
| 404 | def create(self): | 404 | def create(self, jobs=1): |
| 405 | with contextlib.redirect_stdout(io.StringIO()): | 405 | with contextlib.redirect_stdout(io.StringIO()): |
| 406 | return manifest.create(self.pkg, self.out, jobs=1) | 406 | return manifest.create(self.pkg, self.out, jobs=jobs) |
| 407 | 407 | ||
| 408 | def test_create_preserves_an_existing_partial_sibling(self): | 408 | def test_create_preserves_an_existing_partial_sibling(self): |
| 409 | sibling = self.out + ".partial" | 409 | sibling = self.out + ".partial" |
| @@ -452,6 +452,55 @@ class ManifestAtomicCreateTest(unittest.TestCase): | |||
| 452 | self.assertEqual(self.create(), 0) | 452 | self.assertEqual(self.create(), 0) |
| 453 | self.assertEqual(sorted(manifest.load_manifest(self.out)), ["added.dat", "sample.dat"]) | 453 | self.assertEqual(sorted(manifest.load_manifest(self.out)), ["added.dat", "sample.dat"]) |
| 454 | 454 | ||
| 455 | def test_size_change_before_open_keeps_the_previous_manifest(self): | ||
| 456 | self.assertEqual(self.create(), 0) | ||
| 457 | with open(self.out, "rb") as f: | ||
| 458 | previous = f.read() | ||
| 459 | source = os.path.join(self.pkg, "sample.dat") | ||
| 460 | |||
| 461 | def open_after_growth(path, mode, **kwargs): | ||
| 462 | if path == source and mode == "rb": | ||
| 463 | with open(source, "ab") as f: | ||
| 464 | f.write(b"more bytes") | ||
| 465 | return open(path, mode, **kwargs) | ||
| 466 | |||
| 467 | for jobs in (1, 2): | ||
| 468 | with self.subTest(jobs=jobs): | ||
| 469 | with patch.object(manifest, "open", side_effect=open_after_growth, create=True): | ||
| 470 | with self.assertRaisesRegex(manifest.ManifestError, r"sample\.dat.*changed"): | ||
| 471 | self.create(jobs=jobs) | ||
| 472 | with open(self.out, "rb") as f: | ||
| 473 | self.assertEqual(f.read(), previous) | ||
| 474 | |||
| 475 | def test_same_size_change_during_read_keeps_the_previous_manifest(self): | ||
| 476 | self.assertEqual(self.create(), 0) | ||
| 477 | with open(self.out, "rb") as f: | ||
| 478 | previous = f.read() | ||
| 479 | source = os.path.join(self.pkg, "sample.dat") | ||
| 480 | |||
| 481 | def open_with_edit(path, mode, **kwargs): | ||
| 482 | stream = open(path, mode, **kwargs) | ||
| 483 | if path == source and mode == "rb": | ||
| 484 | original_read = stream.read | ||
| 485 | |||
| 486 | def read_then_edit(size): | ||
| 487 | chunk = original_read(size) | ||
| 488 | stream.read = original_read | ||
| 489 | stamp = os.stat(source) | ||
| 490 | with open(source, "r+b") as f: | ||
| 491 | f.write(b"X") | ||
| 492 | os.utime(source, ns=(stamp.st_atime_ns, stamp.st_mtime_ns + 2_000_000_000)) | ||
| 493 | return chunk | ||
| 494 | |||
| 495 | stream.read = read_then_edit | ||
| 496 | return stream | ||
| 497 | |||
| 498 | with patch.object(manifest, "open", side_effect=open_with_edit, create=True): | ||
| 499 | with self.assertRaisesRegex(manifest.ManifestError, r"sample\.dat.*changed"): | ||
| 500 | self.create() | ||
| 501 | with open(self.out, "rb") as f: | ||
| 502 | self.assertEqual(f.read(), previous) | ||
| 503 | |||
| 455 | 504 | ||
| 456 | class ManifestBelowNormalTest(unittest.TestCase): | 505 | class ManifestBelowNormalTest(unittest.TestCase): |
| 457 | def test_below_normal_callable(self): | 506 | def test_below_normal_callable(self): |
diff --git a/tests/test_navmesh_index.py b/tests/test_navmesh_index.py index a420adc90..ef720db70 100644 --- a/tests/test_navmesh_index.py +++ b/tests/test_navmesh_index.py | |||
| @@ -217,6 +217,41 @@ class NavmeshIndexTest(unittest.TestCase): | |||
| 217 | with open(carved, "rb") as f: | 217 | with open(carved, "rb") as f: |
| 218 | self.assertEqual(f.read(), page(pages=4), f"{flag} touched the input") | 218 | self.assertEqual(f.read(), page(pages=4), f"{flag} touched the input") |
| 219 | 219 | ||
| 220 | def test_report_path_linked_to_a_scanned_file_is_scanned_input(self): | ||
| 221 | # Before: a report path the pattern doesn't match was let through even when it is the same file as one the | ||
| 222 | # scan reads. A hard link does that on any filesystem, and so does PAGE.BIN for page.bin on a | ||
| 223 | # case-insensitive macOS or Linux volume, where fnmatch doesn't fold case: the report truncated the input. | ||
| 224 | folder = os.path.join(self.root, "carve") | ||
| 225 | os.makedirs(folder) | ||
| 226 | carved = os.path.join(folder, "page.bin") | ||
| 227 | with open(carved, "wb") as f: | ||
| 228 | f.write(page(pages=4)) | ||
| 229 | linked = os.path.join(folder, "report.json") | ||
| 230 | try: | ||
| 231 | os.link(carved, linked) | ||
| 232 | except (OSError, NotImplementedError) as e: | ||
| 233 | self.skipTest(f"no hard links here: {e}") | ||
| 234 | module = load_tool_module() | ||
| 235 | self.assertTrue(module.is_scanned_input(linked, folder, None)) | ||
| 236 | for flag in ("--out", "--csv"): | ||
| 237 | r = subprocess.run([sys.executable, "-I", TOOL, folder, flag, linked], | ||
| 238 | cwd=ROOT, capture_output=True, text=True, check=False) | ||
| 239 | self.assertEqual(r.returncode, 2, r.stderr) | ||
| 240 | self.assertIn("would overwrite the input", r.stderr) | ||
| 241 | with open(carved, "rb") as f: | ||
| 242 | self.assertEqual(f.read(), page(pages=4), f"{flag} touched the input") | ||
| 243 | |||
| 244 | def test_unscanned_file_in_input_folder_is_not_scanned_input(self): | ||
| 245 | folder = os.path.join(self.root, "carve") | ||
| 246 | os.makedirs(folder) | ||
| 247 | with open(os.path.join(folder, "page.bin"), "wb") as f: | ||
| 248 | f.write(page(pages=4)) | ||
| 249 | report = os.path.join(folder, "report.json") | ||
| 250 | with open(report, "wb") as f: | ||
| 251 | f.write(b"previous report") | ||
| 252 | module = load_tool_module() | ||
| 253 | self.assertFalse(module.is_scanned_input(report, folder, None)) | ||
| 254 | |||
| 220 | def test_sibling_folder_with_shared_prefix_is_not_scanned_input(self): | 255 | def test_sibling_folder_with_shared_prefix_is_not_scanned_input(self): |
| 221 | folder = os.path.join(self.root, "carve") | 256 | folder = os.path.join(self.root, "carve") |
| 222 | sibling = os.path.join(self.root, "carve2") | 257 | sibling = os.path.join(self.root, "carve2") |
diff --git a/tests/test_opus_tags.py b/tests/test_opus_tags.py index 13c9720c9..3eb8215eb 100644 --- a/tests/test_opus_tags.py +++ b/tests/test_opus_tags.py | |||
| @@ -139,6 +139,17 @@ class TestFolder(unittest.TestCase): | |||
| 139 | self.assertEqual(self.tags("story", "bank_02", "1FFFFFFF.ogg"), ["TITLE=door_slam_03"]) | 139 | self.assertEqual(self.tags("story", "bank_02", "1FFFFFFF.ogg"), ["TITLE=door_slam_03"]) |
| 140 | self.assertEqual(self.tags("story", "bank_01", "00000123.ogg"), []) | 140 | self.assertEqual(self.tags("story", "bank_01", "00000123.ogg"), []) |
| 141 | 141 | ||
| 142 | def test_duplicate_id_stream_gets_the_same_tags(self): | ||
| 143 | # awc_opus.py names a bank's second stream with an id already used <id>~2 (export_stems); it has the same | ||
| 144 | # id, so it is the same name and dialogue line. | ||
| 145 | stem = awc_opus.export_stems([0x0ABCDEF1, 0x0ABCDEF1])[1] | ||
| 146 | make_ogg(os.path.join(self.opus, "story", "bank_01", stem + ".ogg")) | ||
| 147 | dialogue, langs = T.load_dialogue(self.dialogue) | ||
| 148 | stats = T.tag_folder(self.opus, T.load_names(self.names, "story"), dialogue, langs) | ||
| 149 | self.assertEqual((stats["ogg files"], stats["tagged"], stats["without a name"]), (4, 3, 1)) | ||
| 150 | self.assertEqual(self.tags("story", "bank_01", stem + ".ogg"), self.tags("story", "bank_01", "0ABCDEF1.ogg")) | ||
| 151 | self.assertIn("TITLE=heistau_abcd_01", self.tags("story", "bank_01", stem + ".ogg")) | ||
| 152 | |||
| 142 | def test_second_run_replaces_its_own_tags(self): | 153 | def test_second_run_replaces_its_own_tags(self): |
| 143 | names = T.load_names(self.names, "story") | 154 | names = T.load_names(self.names, "story") |
| 144 | T.tag_folder(self.opus, names) | 155 | T.tag_folder(self.opus, names) |
diff --git a/tests/test_pe_inspect.py b/tests/test_pe_inspect.py index f4dd76356..0534be001 100644 --- a/tests/test_pe_inspect.py +++ b/tests/test_pe_inspect.py | |||
| @@ -636,5 +636,33 @@ class TruncatedImageTest(unittest.TestCase): | |||
| 636 | self.assertLessEqual(len(exports), pe_inspect.MAX_ENTRIES + 2) | 636 | self.assertLessEqual(len(exports), pe_inspect.MAX_ENTRIES + 2) |
| 637 | 637 | ||
| 638 | 638 | ||
| 639 | class DeclaredOptionalHeaderSizeTest(unittest.TestCase): | ||
| 640 | """Reject optional headers smaller than the fields the parser reads.""" | ||
| 641 | |||
| 642 | def test_declared_optional_header_too_small(self): | ||
| 643 | for is64 in (False, True): | ||
| 644 | for declared_size in (0, 2, 71): | ||
| 645 | with self.subTest(is64=is64, declared_size=declared_size): | ||
| 646 | data = bytearray(build_image(is64=is64)) | ||
| 647 | pe_offset = struct.unpack_from("<I", data, 0x3C)[0] | ||
| 648 | struct.pack_into("<H", data, pe_offset + 20, declared_size) | ||
| 649 | |||
| 650 | with self.assertRaisesRegex( | ||
| 651 | pe_inspect.PeFormatError, "truncated optional header" | ||
| 652 | ): | ||
| 653 | pe_inspect.PeImage(bytes(data)) | ||
| 654 | |||
| 655 | def test_declared_optional_header_extends_beyond_file(self): | ||
| 656 | for is64 in (False, True): | ||
| 657 | with self.subTest(is64=is64): | ||
| 658 | data = bytearray(build_image(is64=is64)) | ||
| 659 | pe_offset = struct.unpack_from("<I", data, 0x3C)[0] | ||
| 660 | struct.pack_into("<H", data, pe_offset + 20, 0xFFFF) | ||
| 661 | |||
| 662 | with self.assertRaisesRegex( | ||
| 663 | pe_inspect.PeFormatError, "truncated optional header" | ||
| 664 | ): | ||
| 665 | pe_inspect.PeImage(bytes(data)) | ||
| 666 | |||
| 639 | if __name__ == "__main__": | 667 | if __name__ == "__main__": |
| 640 | unittest.main() | 668 | unittest.main() |
diff --git a/tests/test_rdna2spirv_cli.py b/tests/test_rdna2spirv_cli.py index 64dfca3bb..353f79cdb 100644 --- a/tests/test_rdna2spirv_cli.py +++ b/tests/test_rdna2spirv_cli.py | |||
| @@ -215,6 +215,34 @@ class ValidatedOutput(unittest.TestCase): | |||
| 215 | self.assertEqual(json.loads(self.index.read_text(encoding="utf-8")), previous) | 215 | self.assertEqual(json.loads(self.index.read_text(encoding="utf-8")), previous) |
| 216 | self.assertEqual(other.read_bytes(), b"unrelated module") | 216 | self.assertEqual(other.read_bytes(), b"unrelated module") |
| 217 | 217 | ||
| 218 | def test_unsupported_clears_retried_shader_but_preserves_unrelated_output(self): | ||
| 219 | # s_barrier is compute-only, so this PS is Unsupported before any SPIR-V tool runs. A module an | ||
| 220 | # earlier run published for it must not survive: the index is make_game.py's proof of completion. | ||
| 221 | self.src.write_text("\ts_barrier\n\ts_endpgm\n", encoding="utf-8") | ||
| 222 | other = self.out / "cs_other.spv" | ||
| 223 | other.write_bytes(b"unrelated module") | ||
| 224 | previous = {"cs_other": {"stage": "cs"}} | ||
| 225 | self.module.write_bytes(b"old module") | ||
| 226 | self.index.write_text(json.dumps({**previous, "ps_fixture": {"stage": "ps"}}), encoding="utf-8") | ||
| 227 | output = self.translate() | ||
| 228 | self.assertIn("s_barrier outside compute", output) | ||
| 229 | self.assertFalse(self.module.exists()) | ||
| 230 | self.assertEqual(json.loads(self.index.read_text(encoding="utf-8")), previous) | ||
| 231 | self.assertEqual(other.read_bytes(), b"unrelated module") | ||
| 232 | self.assertEqual(list(self.out.glob("*.tmp")), []) | ||
| 233 | |||
| 234 | def test_translator_error_clears_retried_shader(self): | ||
| 235 | self.module.write_bytes(b"old module") | ||
| 236 | self.index.write_text(json.dumps({"ps_fixture": {"stage": "ps"}}), encoding="utf-8") | ||
| 237 | output = io.StringIO() | ||
| 238 | with mock.patch.object(rdna2spirv, "translate", side_effect=ValueError("synthetic translator error")), \ | ||
| 239 | mock.patch.object(sys, "argv", [TOOL, str(self.src), "--out", str(self.out)]), \ | ||
| 240 | redirect_stdout(output): | ||
| 241 | rdna2spirv.main() | ||
| 242 | self.assertIn("translator error ValueError", output.getvalue()) | ||
| 243 | self.assertFalse(self.module.exists()) | ||
| 244 | self.assertEqual(json.loads(self.index.read_text(encoding="utf-8")), {}) | ||
| 245 | |||
| 218 | def test_validation_success_publishes_binary_and_metadata(self): | 246 | def test_validation_success_publishes_binary_and_metadata(self): |
| 219 | self.assertIn("1 pass spirv-val", self.translate()) | 247 | self.assertIn("1 pass spirv-val", self.translate()) |
| 220 | self.assertEqual(self.module.read_bytes(), b"new module") | 248 | self.assertEqual(self.module.read_bytes(), b"new module") |
| @@ -223,3 +251,26 @@ class ValidatedOutput(unittest.TestCase): | |||
| 223 | 251 | ||
| 224 | if __name__ == "__main__": | 252 | if __name__ == "__main__": |
| 225 | unittest.main() | 253 | unittest.main() |
| 254 | |||
| 255 | |||
| 256 | class EmptyShader(unittest.TestCase): | ||
| 257 | """A .s with no tab-indented instruction parses to an empty shader. | ||
| 258 | |||
| 259 | It used to translate to a module that passes spirv-val, lands in index.json and does no work at all, which is | ||
| 260 | what a hand-written or re-indented .s looks like: found while writing a fixture with spaces instead of tabs. | ||
| 261 | """ | ||
| 262 | |||
| 263 | def test_no_instructions_is_reported_and_no_module_is_published(self): | ||
| 264 | with tempfile.TemporaryDirectory() as tmp: | ||
| 265 | src = os.path.join(tmp, "disasm") | ||
| 266 | os.mkdir(src) | ||
| 267 | with open(os.path.join(src, "ps_empty.s"), "w", encoding="utf-8") as f: | ||
| 268 | f.write("; ps_empty code 0x0..0x0 (synthetic), gfx1013, 0 invalid words\n s_endpgm\n") | ||
| 269 | with open(os.path.join(tmp, "ps_empty.dxbc"), "wb") as f: | ||
| 270 | f.write(b"DXBC" + bytes(28)) | ||
| 271 | out = os.path.join(tmp, "spirv") | ||
| 272 | p = subprocess.run([sys.executable, "-I", TOOL, src, "--out", out], capture_output=True, text=True) | ||
| 273 | self.assertEqual(p.returncode, 0, p.stderr) | ||
| 274 | self.assertIn("0 translated", p.stdout, p.stdout) | ||
| 275 | self.assertIn("no instructions (nothing tab-indented?)", p.stdout, p.stdout) | ||
| 276 | self.assertFalse(os.path.exists(os.path.join(out, "ps_empty.spv"))) | ||
diff --git a/tests/test_run_gpu_tests.py b/tests/test_run_gpu_tests.py index 69a9fafba..b431ced6a 100644 --- a/tests/test_run_gpu_tests.py +++ b/tests/test_run_gpu_tests.py | |||
| @@ -303,5 +303,49 @@ class Wave32LaneDumps(unittest.TestCase): | |||
| 303 | self.assertIsNone(rgt.narrow_subgroup_skip(out)) | 303 | self.assertIsNone(rgt.narrow_subgroup_skip(out)) |
| 304 | 304 | ||
| 305 | 305 | ||
| 306 | class ComputedIJWithoutPerVertexInputs(unittest.TestCase): | ||
| 307 | """ps_ij_computed (SHADER-177): without PerVertexKHR inputs (--bary-fallback, --f16-interp-fallback, the latter on | ||
| 308 | by default on MoltenVK) the translator refuses the computed I/J pair, so there is no .spv. Both runners SKIP it | ||
| 309 | there, before their missing-.spv check; a missing .spv without a fallback stays a translation failure.""" | ||
| 310 | NAME = "ps_ij_computed" | ||
| 311 | |||
| 312 | def run_suite(self, bary, f16): | ||
| 313 | with tempfile.TemporaryDirectory() as tmp: | ||
| 314 | args = SimpleNamespace(filter=self.NAME, build=tmp, llvm_mc="unused") | ||
| 315 | env = {"LEONIDA_BARY_FALLBACK": "1" if bary else "0", "LEONIDA_F16_INTERP_FALLBACK": "1" if f16 else "0"} | ||
| 316 | out = io.StringIO() | ||
| 317 | with (patch.dict(rgt.os.environ, env), | ||
| 318 | patch.object(rgt, "assemble_to_s", side_effect=lambda _mc, _src, dst, _name: Path(dst).touch()), | ||
| 319 | patch.object(rgt, "spirv_as"), | ||
| 320 | patch.object(rgt, "run_cmd", return_value=(0, "1 shaders: 0 translated, 0 pass spirv-val")), # refused | ||
| 321 | contextlib.redirect_stdout(out), contextlib.redirect_stderr(out)): | ||
| 322 | rc = rgt.run_suite(args, tmp) | ||
| 323 | return rc, out.getvalue() | ||
| 324 | |||
| 325 | def test_run_gpu_tests_skips_under_either_fallback(self): | ||
| 326 | for bary, f16 in ((True, False), (False, True)): | ||
| 327 | with self.subTest(bary=bary, f16=f16): | ||
| 328 | rc, out = self.run_suite(bary, f16) | ||
| 329 | self.assertIn("SKIP (computed I/J pairs need PerVertexKHR inputs", out) | ||
| 330 | self.assertIn("0/1 passed, 1 skipped", out) | ||
| 331 | self.assertNotIn("missing .spv", out) | ||
| 332 | self.assertEqual(rc, 0, out) | ||
| 333 | |||
| 334 | def test_run_gpu_tests_missing_spv_without_fallback_still_fails(self): | ||
| 335 | rc, out = self.run_suite(False, False) | ||
| 336 | self.assertIn("missing .spv (translation failed)", out) | ||
| 337 | self.assertEqual(rc, 1, out) | ||
| 338 | |||
| 339 | def test_check_py_skips_before_its_spv_check(self): | ||
| 340 | import check | ||
| 341 | with tempfile.TemporaryDirectory() as tmp: | ||
| 342 | for bary, f16 in ((True, False), (False, True)): | ||
| 343 | with self.subTest(bary=bary, f16=f16), \ | ||
| 344 | patch.object(check, "BARY_FALLBACK", bary), patch.object(check, "F16_HALVES", f16): | ||
| 345 | self.assertIsInstance(check.pixel_test("unused", tmp, self.NAME), check.Skip) | ||
| 346 | with patch.object(check, "BARY_FALLBACK", False), patch.object(check, "F16_HALVES", False): | ||
| 347 | self.assertEqual(check.pixel_test("unused", tmp, self.NAME), f"missing {self.NAME}.spv") | ||
| 348 | |||
| 349 | |||
| 306 | if __name__ == "__main__": | 350 | if __name__ == "__main__": |
| 307 | unittest.main() | 351 | unittest.main() |
diff --git a/tests/test_run_wine_tests.py b/tests/test_run_wine_tests.py index 165eb25b3..c37f525f4 100644 --- a/tests/test_run_wine_tests.py +++ b/tests/test_run_wine_tests.py | |||
| @@ -211,6 +211,70 @@ class RunTestTest(unittest.TestCase): | |||
| 211 | os.path.normcase(os.path.realpath(self.artifact / "sub"))) | 211 | os.path.normcase(os.path.realpath(self.artifact / "sub"))) |
| 212 | 212 | ||
| 213 | 213 | ||
| 214 | @unittest.skipIf(os.name == "nt", "the runner and its dosdevices links are for Linux and macOS") | ||
| 215 | class DriveMapTest(unittest.TestCase): | ||
| 216 | def setUp(self): | ||
| 217 | self._tmp = tempfile.TemporaryDirectory() | ||
| 218 | base = Path(self._tmp.name) | ||
| 219 | self.root = base / "checkout" | ||
| 220 | (self.root / "runtime" / "build" / "generated").mkdir(parents=True) | ||
| 221 | (self.root / "runtime" / "build" / "generated" / "cs.spv").write_text("spirv", encoding="utf-8") | ||
| 222 | self.prefix = base / "prefix" | ||
| 223 | (self.prefix / "dosdevices").mkdir(parents=True) | ||
| 224 | self.link = self.prefix / "dosdevices" / "d:" | ||
| 225 | |||
| 226 | def tearDown(self): | ||
| 227 | self._tmp.cleanup() | ||
| 228 | |||
| 229 | def test_the_drive_leads_to_the_checkout_and_is_removed_afterwards(self): | ||
| 230 | with rwt.DriveMap("D:/a/Leonida/Leonida", str(self.root), str(self.prefix)) as drive: | ||
| 231 | seen = self.link / "a" / "Leonida" / "Leonida" / "runtime" / "build" / "generated" / "cs.spv" | ||
| 232 | self.assertEqual(seen.read_text(encoding="utf-8"), "spirv") | ||
| 233 | self.assertIn("drive d: maps", drive.note) | ||
| 234 | scratch = drive.scratch | ||
| 235 | self.assertFalse(os.path.lexists(self.link)) | ||
| 236 | self.assertFalse(os.path.exists(scratch)) | ||
| 237 | self.assertTrue((self.root / "runtime" / "build" / "generated" / "cs.spv").is_file()) # links only | ||
| 238 | |||
| 239 | def test_backslashes_and_a_lower_case_drive_are_accepted(self): | ||
| 240 | with rwt.DriveMap("d:\\work\\leonida\\", str(self.root), str(self.prefix)): | ||
| 241 | self.assertTrue((self.link / "work" / "leonida" / "runtime" / "build").is_dir()) | ||
| 242 | |||
| 243 | def test_a_drive_the_prefix_already_has_is_left_alone(self): | ||
| 244 | other = self.prefix / "elsewhere" | ||
| 245 | other.mkdir() | ||
| 246 | os.symlink(other, self.link) | ||
| 247 | with rwt.DriveMap("D:/a/Leonida/Leonida", str(self.root), str(self.prefix)) as drive: | ||
| 248 | self.assertIn("already set", drive.note) | ||
| 249 | self.assertEqual(os.readlink(self.link), str(other)) | ||
| 250 | |||
| 251 | def test_no_prefix_or_no_drive_letter_maps_nothing(self): | ||
| 252 | with rwt.DriveMap("D:/a/b", str(self.root), str(self.prefix / "absent")) as drive: | ||
| 253 | self.assertIn("no Wine prefix", drive.note) | ||
| 254 | with rwt.DriveMap("/home/runner/work", str(self.root), str(self.prefix)) as drive: | ||
| 255 | self.assertIn("no drive letter", drive.note) | ||
| 256 | self.assertFalse(os.path.lexists(self.link)) | ||
| 257 | |||
| 258 | def test_main_maps_the_drive_while_the_tests_run(self): | ||
| 259 | # The "Wine" here is the Python interpreter, so the program reads the drive through its dosdevices link, which | ||
| 260 | # is where Wine resolves D:/win/root/... too. | ||
| 261 | probe = self.root / "probe.py" | ||
| 262 | target = self.link / "win" / "root" / "runtime" / "build" / "generated" / "cs.spv" | ||
| 263 | probe.write_text(f"import sys\nsys.exit(0 if open({str(target)!r}).read() == 'spirv' else 1)\n", encoding="utf-8") | ||
| 264 | listing = self.root / "ctest.json" | ||
| 265 | listing.write_text(json.dumps({"tests": [ctest_entry("compiled_in_path", [WINDOWS_ROOT + "/probe.py"])]}), | ||
| 266 | encoding="utf-8") | ||
| 267 | argv = ["run_wine_tests.py", "--tests", str(listing), "--windows-root", WINDOWS_ROOT, | ||
| 268 | "--root", str(self.root), "--wine", sys.executable.replace(os.sep, "/")] | ||
| 269 | out = io.StringIO() | ||
| 270 | with mock.patch.dict(os.environ, {"WINEPREFIX": str(self.prefix)}), mock.patch.object(sys, "argv", argv), \ | ||
| 271 | contextlib.redirect_stdout(out): | ||
| 272 | code = rwt.main() | ||
| 273 | self.assertEqual(code, 0, out.getvalue()) | ||
| 274 | self.assertIn("[PASS] compiled_in_path", out.getvalue()) | ||
| 275 | self.assertFalse(os.path.lexists(self.link)) | ||
| 276 | |||
| 277 | |||
| 214 | class MainTest(unittest.TestCase): | 278 | class MainTest(unittest.TestCase): |
| 215 | def setUp(self): | 279 | def setUp(self): |
| 216 | self._tmp = tempfile.TemporaryDirectory() | 280 | self._tmp = tempfile.TemporaryDirectory() |
| @@ -219,6 +283,10 @@ class MainTest(unittest.TestCase): | |||
| 219 | self.artifact.mkdir() | 283 | self.artifact.mkdir() |
| 220 | for name, code in (("ok.py", 0), ("bad.py", 1)): | 284 | for name, code in (("ok.py", 0), ("bad.py", 1)): |
| 221 | (self.artifact / name).write_text(f"import sys\nsys.exit({code})\n", encoding="utf-8") | 285 | (self.artifact / name).write_text(f"import sys\nsys.exit({code})\n", encoding="utf-8") |
| 286 | # main() maps the checkout's drive into $WINEPREFIX: keep it away from a real prefix (~/.wine). | ||
| 287 | env = mock.patch.dict(os.environ, {"WINEPREFIX": str(self.root / "no-prefix")}) | ||
| 288 | env.start() | ||
| 289 | self.addCleanup(env.stop) | ||
| 222 | 290 | ||
| 223 | def tearDown(self): | 291 | def tearDown(self): |
| 224 | self._tmp.cleanup() | 292 | self._tmp.cleanup() |
diff --git a/tests/test_shader_checks.py b/tests/test_shader_checks.py index 0f97716ab..c4bd7c042 100644 --- a/tests/test_shader_checks.py +++ b/tests/test_shader_checks.py | |||
| @@ -29,11 +29,12 @@ WAVE32_WORDS = {n: w for n, w in check.CS_DUMPS if n in check.WAVE32_DUMPS and n | |||
| 29 | 29 | ||
| 30 | # All check.py cases, including the four vk_store_test shaders and the three mesh fixtures, and TEST-184's | 30 | # All check.py cases, including the four vk_store_test shaders and the three mesh fixtures, and TEST-184's |
| 31 | # vk_store_test "words" fixtures and image_get_lod draws. | 31 | # vk_store_test "words" fixtures and image_get_lod draws. |
| 32 | TOTAL = (len(check.COMPUTE) + 3 + len(check.CS_DUMPS) + len(check.W64X_DUMPS) + len(check.W64X_PARTIAL) + 4 | 32 | TOTAL = (len(check.COMPUTE) + 4 + len(check.CS_DUMPS) + len(check.W64X_DUMPS) + len(check.W64X_PARTIAL) + 4 |
| 33 | + len(check.PIXEL_TESTS) + len(check.CLIP_TESTS) + len(check.BOUNDS) + len(check.GLOBAL_OFFSET) | 33 | + len(check.PIXEL_TESTS) + len(check.CLIP_TESTS) + len(check.BOUNDS) + len(check.GLOBAL_OFFSET) |
| 34 | + len(check.MIP_TEST_PASSES) + len(check.GRADIENT_TESTS) | 34 | + len(check.MIP_TEST_PASSES) + len(check.GRADIENT_TESTS) |
| 35 | + len(check.STORE_WORDS) + len(check.GET_LOD_TESTS) | 35 | + len(check.STORE_WORDS) + len(check.GET_LOD_TESTS) |
| 36 | + len(check.TEXTURE_CONSTANTS) + 9) # three mesh fixtures, ps_tex, four compute fixtures and ps_ssharp | 36 | + len(check.TEXTURE_CONSTANTS) + 10) # three mesh fixtures, ps_tex, ps_imgatomic, four compute fixtures and |
| 37 | # ps_ssharp | ||
| 37 | CVT = {bits: [u, s] for bits, u, s in check.CVT_F32_SAT_CASES} | 38 | CVT = {bits: [u, s] for bits, u, s in check.CVT_F32_SAT_CASES} |
| 38 | 39 | ||
| 39 | 40 | ||
| @@ -65,6 +66,10 @@ class Wave64Checks(unittest.TestCase): | |||
| 65 | if fmt[1] is not None: | 66 | if fmt[1] is not None: |
| 66 | dump.write_bytes(fmt[1]) | 67 | dump.write_bytes(fmt[1]) |
| 67 | return fmt[0], "out[0..7] = 0 0 0 0 0 0 0 0\n" # stdout is not the oracle | 68 | return fmt[0], "out[0..7] = 0 0 0 0 0 0 0 0\n" # stdout is not the oracle |
| 69 | if name == "cs_fmt_sint32": | ||
| 70 | self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), "64")) | ||
| 71 | Path(env["VKC_DUMP"]).write_bytes(struct.pack("<64I", *check.FMT_SINT32_WORDS)) | ||
| 72 | return 0, "" | ||
| 68 | if name == "cs_fmt_xy_xyz": | 73 | if name == "cs_fmt_xy_xyz": |
| 69 | self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), "192")) | 74 | self.assertEqual((args, env["VKC_OUT_WORDS"]), (("1", "dump"), "192")) |
| 70 | Path(env["VKC_DUMP"]).write_bytes(GOOD_XY_XYZ) | 75 | Path(env["VKC_DUMP"]).write_bytes(GOOD_XY_XYZ) |
| @@ -322,6 +327,24 @@ class PixelDeviceLimits(unittest.TestCase): | |||
| 322 | self.assertIsInstance(problem, check.Skip) | 327 | self.assertIsInstance(problem, check.Skip) |
| 323 | self.assertIn("no subgroup width", problem) | 328 | self.assertIn("no subgroup width", problem) |
| 324 | 329 | ||
| 330 | @staticmethod | ||
| 331 | def readlane_pixels(words=(0x40000079, 0x40000010, 0x40000064, 0x400000be)): | ||
| 332 | return struct.pack("<4I", *words) * (64 * 64) | ||
| 333 | |||
| 334 | def test_wave64_pixel_shader_skips_where_64_cannot_be_required(self): | ||
| 335 | out = "device: fake (subgroup 8..8)\nok 64x64\n" | ||
| 336 | problem = self.run_pixel("ps_w64x_readlane", 0, out, data=self.readlane_pixels((0, 0, 0, 0))) | ||
| 337 | self.assertIsInstance(problem, check.Skip) | ||
| 338 | self.assertIn("64-wide fragment subgroup", problem) | ||
| 339 | self.assertIn("8..8", problem) | ||
| 340 | |||
| 341 | def test_wave64_pixel_shader_is_judged_when_64_was_required(self): | ||
| 342 | out = "device: fake (subgroup 32..64)\nfragment subgroup size: 64 required\nok 64x64\n" | ||
| 343 | self.assertEqual(self.run_pixel("ps_w64x_readlane", 0, out, data=self.readlane_pixels()), "") | ||
| 344 | problem = self.run_pixel("ps_w64x_readlane", 0, out, data=self.readlane_pixels((0, 0, 0, 0))) | ||
| 345 | self.assertNotIsInstance(problem, check.Skip) | ||
| 346 | self.assertIn("pixels differ", problem) | ||
| 347 | |||
| 325 | def test_bitmask_perm_skips_when_variable_device_runs_narrow_fragment_subgroup(self): | 348 | def test_bitmask_perm_skips_when_variable_device_runs_narrow_fragment_subgroup(self): |
| 326 | out = "device: Intel(R) HD Graphics 530 (subgroup 8..32)\nok 64x64\n" | 349 | out = "device: Intel(R) HD Graphics 530 (subgroup 8..32)\nok 64x64\n" |
| 327 | for width in (8, 16): | 350 | for width in (8, 16): |
diff --git a/tests/test_shader_link_check.py b/tests/test_shader_link_check.py new file mode 100644 index 000000000..cbaf7a39f --- /dev/null +++ b/tests/test_shader_link_check.py | |||
| @@ -0,0 +1,459 @@ | |||
| 1 | """Shader-stage matching with hand-written modules and a synthetic pipeline manifest.""" | ||
| 2 | import contextlib | ||
| 3 | import io | ||
| 4 | import json | ||
| 5 | from pathlib import Path | ||
| 6 | import struct | ||
| 7 | import subprocess | ||
| 8 | import sys | ||
| 9 | import tempfile | ||
| 10 | import unittest | ||
| 11 | from unittest.mock import patch | ||
| 12 | |||
| 13 | ROOT = Path(__file__).resolve().parents[1] | ||
| 14 | sys.path.insert(0, str(ROOT / "tools")) | ||
| 15 | import shader_link_check as link # noqa: E402 | ||
| 16 | import spirv_interface as spv # noqa: E402 | ||
| 17 | import spirv_stubs # noqa: E402 | ||
| 18 | |||
| 19 | |||
| 20 | class ModuleFixture: | ||
| 21 | """Binary interface declarations. Drivers are exercised by separate GLSL fixtures.""" | ||
| 22 | |||
| 23 | MODELS = {"vs": 0, "gs": 3, "ms": 5365, "ps": 4, "cs": 5} | ||
| 24 | |||
| 25 | def __init__(self, stage, start_id=1): | ||
| 26 | self.stage = stage | ||
| 27 | self.next_id = start_id | ||
| 28 | self.code = [] | ||
| 29 | self.entries = [] | ||
| 30 | self.ids = [] | ||
| 31 | self.uint = self.emit_type(spv.OP_TYPE_INT, 32, 0) | ||
| 32 | |||
| 33 | def allocate(self): | ||
| 34 | self.next_id += 1 | ||
| 35 | return self.next_id - 1 | ||
| 36 | |||
| 37 | def emit(self, opcode, *args): | ||
| 38 | self.code.extend([((len(args) + 1) << 16) | opcode, *args]) | ||
| 39 | |||
| 40 | def emit_type(self, opcode, *args): | ||
| 41 | result = self.allocate() | ||
| 42 | self.emit(opcode, result, *args) | ||
| 43 | return result | ||
| 44 | |||
| 45 | def literal(self, value): | ||
| 46 | result = self.allocate() | ||
| 47 | self.emit(spv.OP_CONSTANT, self.uint, result, value) | ||
| 48 | return result | ||
| 49 | |||
| 50 | def numeric(self, width=32, components=1, kind="f"): | ||
| 51 | if kind == "f": | ||
| 52 | element = self.emit_type(spv.OP_TYPE_FLOAT, width) | ||
| 53 | else: | ||
| 54 | element = self.emit_type(spv.OP_TYPE_INT, width, int(kind == "i")) | ||
| 55 | return element if components == 1 else self.emit_type(spv.OP_TYPE_VECTOR, element, components) | ||
| 56 | |||
| 57 | def array(self, element, length): | ||
| 58 | return self.emit_type(spv.OP_TYPE_ARRAY, element, self.literal(length)) | ||
| 59 | |||
| 60 | def decorate(self, identifier, decoration, *operands): | ||
| 61 | self.emit(spv.OP_DECORATE, identifier, decoration, *operands) | ||
| 62 | |||
| 63 | def member(self, identifier, member, decoration, *operands): | ||
| 64 | self.emit(spv.OP_MEMBER_DECORATE, identifier, member, decoration, *operands) | ||
| 65 | |||
| 66 | def variable(self, storage, shape, location=None, component=None, index=None, *flags): | ||
| 67 | pointer = self.emit_type(spv.OP_TYPE_POINTER, storage, shape) | ||
| 68 | identifier = self.allocate() | ||
| 69 | self.emit(spv.OP_VARIABLE, pointer, identifier, storage) | ||
| 70 | self.ids.append(identifier) | ||
| 71 | for decoration, value in ((spv.DEC_LOCATION, location), (spv.DEC_COMPONENT, component), | ||
| 72 | (spv.DEC_INDEX, index)): | ||
| 73 | if value is not None: | ||
| 74 | self.decorate(identifier, decoration, value) | ||
| 75 | for decoration in flags: | ||
| 76 | self.decorate(identifier, decoration) | ||
| 77 | return identifier | ||
| 78 | |||
| 79 | def entry(self, name, ids, stage=None): | ||
| 80 | raw = name.encode("utf-8") + b"\x00" | ||
| 81 | raw += bytes(-len(raw) % 4) | ||
| 82 | string = struct.unpack(f"<{len(raw) // 4}I", raw) | ||
| 83 | function = self.allocate() | ||
| 84 | args = (self.MODELS[stage or self.stage], function, *string, *ids) | ||
| 85 | self.entries.extend([((len(args) + 1) << 16) | spv.OP_ENTRY_POINT, *args]) | ||
| 86 | |||
| 87 | def binary(self, big_endian=False): | ||
| 88 | if not self.entries: | ||
| 89 | self.entry("main", self.ids) | ||
| 90 | words = [spv.SPIRV_MAGIC, 0x00010500, 0, self.next_id, 0, *self.entries, *self.code] | ||
| 91 | endian = ">" if big_endian else "<" | ||
| 92 | return struct.pack(f"{endian}{len(words)}I", *words) | ||
| 93 | |||
| 94 | def reflect(self, entry="main", **kwargs): | ||
| 95 | return spv.reflect_module(self.binary(), entry=entry, **kwargs) | ||
| 96 | |||
| 97 | |||
| 98 | def simple(stage, storage, location, component=None, width=32, components=4, kind="f", array_count=None): | ||
| 99 | shader = ModuleFixture(stage, start_id=5 if storage == spv.STORAGE_INPUT else 1) | ||
| 100 | shape = shader.numeric(width, components, kind) | ||
| 101 | if array_count is not None: | ||
| 102 | shape = shader.array(shape, array_count) | ||
| 103 | shader.variable(storage, shape, location, component) | ||
| 104 | return shader | ||
| 105 | |||
| 106 | |||
| 107 | def output(location=0, **kwargs): | ||
| 108 | return simple("vs", spv.STORAGE_OUTPUT, location, **kwargs) | ||
| 109 | |||
| 110 | |||
| 111 | def input(location=0, **kwargs): | ||
| 112 | return simple("ps", spv.STORAGE_INPUT, location, **kwargs) | ||
| 113 | |||
| 114 | |||
| 115 | def kinds(producer, consumer, **kwargs): | ||
| 116 | return [item.kind for item in link.compare_stages(producer.reflect(), consumer.reflect(), **kwargs)] | ||
| 117 | |||
| 118 | |||
| 119 | class ReflectTest(unittest.TestCase): | ||
| 120 | def test_reads_other_byte_order(self): | ||
| 121 | shader = output() | ||
| 122 | self.assertEqual(spv.reflect_module(shader.binary(big_endian=True)), shader.reflect()) | ||
| 123 | |||
| 124 | def test_skips_correctly_decorated_builtins(self): | ||
| 125 | shader = ModuleFixture("vs") | ||
| 126 | position = shader.variable(spv.STORAGE_OUTPUT, shader.numeric(32, 4)) | ||
| 127 | shader.decorate(position, spv.DEC_BUILTIN, 0) | ||
| 128 | self.assertEqual(shader.reflect().outputs, ()) | ||
| 129 | |||
| 130 | def test_skips_builtin_block(self): | ||
| 131 | shader = ModuleFixture("gs") | ||
| 132 | block = shader.emit_type(spv.OP_TYPE_STRUCT, shader.numeric(32, 4)) | ||
| 133 | shader.decorate(block, spv.DEC_BLOCK) | ||
| 134 | shader.member(block, 0, spv.DEC_BUILTIN, 0) | ||
| 135 | shader.variable(spv.STORAGE_INPUT, shader.array(block, 3)) | ||
| 136 | self.assertEqual(shader.reflect().inputs, ()) | ||
| 137 | |||
| 138 | def test_missing_location_is_an_error(self): | ||
| 139 | shader = ModuleFixture("vs") | ||
| 140 | shader.variable(spv.STORAGE_OUTPUT, shader.numeric()) | ||
| 141 | with self.assertRaisesRegex(spv.InterfaceError, "missing a Location"): | ||
| 142 | shader.reflect() | ||
| 143 | |||
| 144 | def test_64_bit_vector_spans_locations_and_can_share_remaining_components(self): | ||
| 145 | shader = output(width=64, components=3) | ||
| 146 | shader.variable(spv.STORAGE_OUTPUT, shader.numeric(32, 2), 1, 2) | ||
| 147 | declarations = shader.reflect().outputs | ||
| 148 | self.assertEqual(len(declarations), 2) | ||
| 149 | used = list(declarations[0].varyings[0].occupied()) | ||
| 150 | self.assertEqual(used[-1], spv.Address(1, 1)) | ||
| 151 | |||
| 152 | def test_rejects_component_overlap(self): | ||
| 153 | shader = output(width=64, components=3) | ||
| 154 | shader.variable(spv.STORAGE_OUTPUT, shader.numeric(), 1, 1) | ||
| 155 | with self.assertRaisesRegex(spv.InterfaceError, "overlap.*location 1, component 1"): | ||
| 156 | shader.reflect() | ||
| 157 | |||
| 158 | def test_keeps_fragment_dual_source_outputs_separate(self): | ||
| 159 | shader = ModuleFixture("ps") | ||
| 160 | shape = shader.numeric(32, 4) | ||
| 161 | shader.variable(spv.STORAGE_OUTPUT, shape, 0, index=0) | ||
| 162 | shader.variable(spv.STORAGE_OUTPUT, shape, 0, index=1) | ||
| 163 | self.assertEqual([d.varyings[0].address.index for d in shader.reflect().outputs], [0, 1]) | ||
| 164 | |||
| 165 | def test_rejects_vector_that_spills_32_bits_into_another_location(self): | ||
| 166 | shader = input(component=2, components=3) | ||
| 167 | with self.assertRaisesRegex(spv.InterfaceError, "extends beyond its Location"): | ||
| 168 | shader.reflect() | ||
| 169 | |||
| 170 | def test_rejects_unbounded_expansion(self): | ||
| 171 | shader = output(array_count=spv.MAX_EXPANDED_LOCATIONS + 1) | ||
| 172 | with self.assertRaisesRegex(spv.InterfaceError, "too many interface locations"): | ||
| 173 | shader.reflect() | ||
| 174 | |||
| 175 | def test_uses_selected_entry_interface_ids(self): | ||
| 176 | shader = ModuleFixture("ps") | ||
| 177 | first = shader.variable(spv.STORAGE_INPUT, shader.numeric(), 2) | ||
| 178 | second = shader.variable(spv.STORAGE_INPUT, shader.numeric(), 6) | ||
| 179 | shader.entry("main", [first]) | ||
| 180 | shader.entry("other", [second]) | ||
| 181 | self.assertEqual(shader.reflect().inputs[0].varyings[0].address.location, 2) | ||
| 182 | self.assertEqual(shader.reflect("other").inputs[0].varyings[0].address.location, 6) | ||
| 183 | |||
| 184 | def test_same_name_in_different_stages_requires_stage_to_select(self): | ||
| 185 | shader = ModuleFixture("vs") | ||
| 186 | shader.entry("main", []) | ||
| 187 | shader.entry("main", [], stage="ps") | ||
| 188 | with self.assertRaisesRegex(spv.InterfaceError, "ambiguous"): | ||
| 189 | shader.reflect() | ||
| 190 | self.assertEqual(shader.reflect(stage="ps").stage, "ps") | ||
| 191 | |||
| 192 | def test_entry_can_reference_resources_other_than_io(self): | ||
| 193 | shader = ModuleFixture("ps") | ||
| 194 | shader.variable(2, shader.numeric()) # Uniform, a different interface. | ||
| 195 | self.assertEqual(shader.reflect().inputs, ()) | ||
| 196 | |||
| 197 | def test_grouped_decorations_apply_to_members_and_variables(self): | ||
| 198 | shader = ModuleFixture("vs") | ||
| 199 | struct_type = shader.emit_type(spv.OP_TYPE_STRUCT, shader.numeric(32, 2)) | ||
| 200 | shader.decorate(struct_type, spv.DEC_BLOCK) | ||
| 201 | block = shader.variable(spv.STORAGE_OUTPUT, struct_type) | ||
| 202 | scalar = shader.variable(spv.STORAGE_OUTPUT, shader.numeric()) | ||
| 203 | group = shader.allocate() | ||
| 204 | shader.emit(spv.OP_DECORATION_GROUP, group) | ||
| 205 | shader.decorate(group, spv.DEC_LOCATION, 2) | ||
| 206 | shader.emit(spv.OP_GROUP_MEMBER_DECORATE, group, struct_type, 0) | ||
| 207 | shader.emit(spv.OP_GROUP_DECORATE, group, scalar) | ||
| 208 | component_group = shader.allocate() | ||
| 209 | shader.emit(spv.OP_DECORATION_GROUP, component_group) | ||
| 210 | shader.decorate(component_group, spv.DEC_COMPONENT, 2) | ||
| 211 | shader.emit(spv.OP_GROUP_DECORATE, component_group, scalar) | ||
| 212 | declarations = shader.reflect().outputs | ||
| 213 | self.assertEqual([d.symbol for d in declarations], [block, scalar]) | ||
| 214 | self.assertEqual([d.varyings[0].address for d in declarations], [spv.Address(2), spv.Address(2, 2)]) | ||
| 215 | |||
| 216 | def test_conflicting_decoration_group_is_rejected(self): | ||
| 217 | shader = output() | ||
| 218 | group = shader.allocate() | ||
| 219 | shader.emit(spv.OP_DECORATION_GROUP, group) | ||
| 220 | shader.decorate(group, spv.DEC_LOCATION, 5) | ||
| 221 | shader.emit(spv.OP_GROUP_DECORATE, group, shader.ids[0]) | ||
| 222 | with self.assertRaisesRegex(spv.InterfaceError, "conflicting Location"): | ||
| 223 | shader.reflect() | ||
| 224 | |||
| 225 | def test_malformed_header_instruction_and_references(self): | ||
| 226 | shader = output() | ||
| 227 | with self.assertRaisesRegex(spv.InterfaceError, "complete"): | ||
| 228 | spv.reflect_module(shader.binary() + b"\x00") | ||
| 229 | with self.assertRaisesRegex(spv.InterfaceError, "magic"): | ||
| 230 | spv.reflect_module(b"\x00" * 4 + shader.binary()[4:]) | ||
| 231 | with self.assertRaisesRegex(spv.InterfaceError, "instruction length"): | ||
| 232 | spv.reflect_module(shader.binary()[:-4]) | ||
| 233 | with self.assertRaisesRegex(spv.InterfaceError, "instruction length"): | ||
| 234 | spv.reflect_module(shader.binary() + bytes(4)) | ||
| 235 | missing = ModuleFixture("vs") | ||
| 236 | missing.entry("main", [missing.allocate()]) | ||
| 237 | with self.assertRaisesRegex(spv.InterfaceError, "missing variable"): | ||
| 238 | missing.reflect() | ||
| 239 | |||
| 240 | def test_passthrough_geometry_gets_explicit_unsupported_diagnostic(self): | ||
| 241 | shader = simple("gs", spv.STORAGE_INPUT, 0, array_count=3) | ||
| 242 | shader.decorate(shader.ids[0], spv.DEC_PASSTHROUGH_NV) | ||
| 243 | with self.assertRaisesRegex(spv.InterfaceError, "passthrough"): | ||
| 244 | shader.reflect() | ||
| 245 | |||
| 246 | |||
| 247 | class LinkingTest(unittest.TestCase): | ||
| 248 | def test_matches_the_projects_generated_partner_modules(self): | ||
| 249 | vertex = spv.reflect_module(spirv_stubs.build_vs_stub([2, 9]), stage="vs") | ||
| 250 | pixel = spv.reflect_module(spirv_stubs.build_ps_stub([9, 2], flat_locations=[2]), stage="ps") | ||
| 251 | self.assertEqual(link.compare_stages(vertex, pixel), []) | ||
| 252 | |||
| 253 | def test_numeric_match_ignores_module_local_ids_and_optional_component_zero(self): | ||
| 254 | self.assertEqual(kinds(output(), input(component=0)), []) | ||
| 255 | |||
| 256 | def test_unconsumed_outputs_are_allowed(self): | ||
| 257 | producer = output() | ||
| 258 | producer.variable(spv.STORAGE_OUTPUT, producer.numeric(), 7) | ||
| 259 | self.assertEqual(kinds(producer, input()), []) | ||
| 260 | |||
| 261 | def test_missing_output_and_conflicting_start_are_distinct(self): | ||
| 262 | self.assertEqual(kinds(output(), input(3)), ["missing-output"]) | ||
| 263 | self.assertEqual(kinds(output(), input(component=2, components=2)), ["location-mismatch"]) | ||
| 264 | |||
| 265 | def test_float_width_and_integer_sign_are_part_of_type(self): | ||
| 266 | self.assertEqual(kinds(output(components=2, width=16), input(components=2)), ["type-mismatch"]) | ||
| 267 | self.assertEqual(kinds(output(components=2, kind="u"), input(components=2, kind="i")), ["type-mismatch"]) | ||
| 268 | |||
| 269 | def test_maintenance4_relaxes_only_a_wider_vector_output(self): | ||
| 270 | self.assertEqual(kinds(output(), input(components=2)), ["type-mismatch"]) | ||
| 271 | self.assertEqual(kinds(output(), input(components=2), maintenance4=True), []) | ||
| 272 | self.assertEqual(kinds(output(components=2), input(), maintenance4=True), ["type-mismatch"]) | ||
| 273 | self.assertEqual(kinds(output(), input(components=1), maintenance4=True), ["type-mismatch"]) | ||
| 274 | |||
| 275 | def test_maintenance4_does_not_unwrap_and_relax_aggregate_shapes(self): | ||
| 276 | producer = output(array_count=3) | ||
| 277 | consumer = input(components=2, array_count=3) | ||
| 278 | self.assertEqual(kinds(producer, consumer, maintenance4=True), ["type-mismatch"]) | ||
| 279 | self.assertEqual(kinds(output(), simple("gs", spv.STORAGE_INPUT, 0, components=2, array_count=3), | ||
| 280 | maintenance4=True), ["type-mismatch"]) | ||
| 281 | |||
| 282 | def test_geometry_input_strips_outer_array_only(self): | ||
| 283 | geometry = ModuleFixture("gs") | ||
| 284 | member = geometry.array(geometry.numeric(32, 4), 2) | ||
| 285 | geometry.variable(spv.STORAGE_INPUT, geometry.array(member, 3), 0) | ||
| 286 | self.assertEqual(kinds(output(array_count=2), geometry), []) | ||
| 287 | self.assertEqual(kinds(output(array_count=3), geometry), ["type-mismatch"]) | ||
| 288 | |||
| 289 | def test_fragment_per_vertex_matches_non_array_vertex_output(self): | ||
| 290 | fragment = simple("ps", spv.STORAGE_INPUT, 0, array_count=3) | ||
| 291 | fragment.decorate(fragment.ids[0], spv.DEC_PER_VERTEX) | ||
| 292 | self.assertEqual(kinds(output(), fragment), []) | ||
| 293 | self.assertEqual(kinds(output(array_count=3), fragment), ["type-mismatch"]) | ||
| 294 | |||
| 295 | def test_mesh_primitive_output_matches_fragment_domain(self): | ||
| 296 | mesh = simple("ms", spv.STORAGE_OUTPUT, 0, array_count=37) | ||
| 297 | mesh.decorate(mesh.ids[0], spv.DEC_PER_PRIMITIVE) | ||
| 298 | fragment = input() | ||
| 299 | self.assertEqual(kinds(mesh, fragment), ["per-primitive-mismatch"]) | ||
| 300 | fragment.decorate(fragment.ids[0], spv.DEC_PER_PRIMITIVE) | ||
| 301 | self.assertEqual(kinds(mesh, fragment), []) | ||
| 302 | |||
| 303 | def test_matching_structure_members_keep_order_and_locations(self): | ||
| 304 | def block(stage, storage, locations): | ||
| 305 | shader = ModuleFixture(stage) | ||
| 306 | shape = shader.emit_type(spv.OP_TYPE_STRUCT, shader.numeric(32, 2), shader.numeric(32, 2)) | ||
| 307 | shader.decorate(shape, spv.DEC_BLOCK) | ||
| 308 | for i, location in enumerate(locations): | ||
| 309 | shader.member(shape, i, spv.DEC_LOCATION, location) | ||
| 310 | shader.variable(storage, shape) | ||
| 311 | return shader | ||
| 312 | |||
| 313 | producer = block("vs", spv.STORAGE_OUTPUT, (1, 3)) | ||
| 314 | self.assertEqual(kinds(producer, block("ps", spv.STORAGE_INPUT, (1, 3))), []) | ||
| 315 | self.assertEqual(kinds(producer, block("ps", spv.STORAGE_INPUT, (1, 2))), ["location-mismatch"]) | ||
| 316 | self.assertEqual(kinds(producer, block("ps", spv.STORAGE_INPUT, (3, 1))), ["location-mismatch"]) | ||
| 317 | self.assertEqual(kinds(producer, input(location=1, components=2)), ["structure-mismatch"]) | ||
| 318 | |||
| 319 | def test_location_on_structure_allocates_consecutive_members(self): | ||
| 320 | shader = ModuleFixture("vs") | ||
| 321 | wide = shader.numeric(64, 3) | ||
| 322 | shape = shader.emit_type(spv.OP_TYPE_STRUCT, wide, shader.numeric()) | ||
| 323 | shader.variable(spv.STORAGE_OUTPUT, shape, 5) | ||
| 324 | declarations = shader.reflect().outputs | ||
| 325 | self.assertEqual([v.address.location for v in declarations[0].varyings], [5, 7]) | ||
| 326 | |||
| 327 | def test_matrix_and_array_of_columns_are_distinct_types(self): | ||
| 328 | vertices = ModuleFixture("vs") | ||
| 329 | column = vertices.numeric(32, 2) | ||
| 330 | vertices.variable(spv.STORAGE_OUTPUT, vertices.emit_type(spv.OP_TYPE_MATRIX, column, 3), 0) | ||
| 331 | fragment = ModuleFixture("ps") | ||
| 332 | column = fragment.numeric(32, 2) | ||
| 333 | fragment.variable(spv.STORAGE_INPUT, fragment.emit_type(spv.OP_TYPE_MATRIX, column, 3), 0) | ||
| 334 | self.assertEqual(kinds(vertices, fragment), []) | ||
| 335 | self.assertEqual(kinds(vertices, input(components=2, array_count=3)), ["type-mismatch"]) | ||
| 336 | |||
| 337 | |||
| 338 | class CommandLineTest(unittest.TestCase): | ||
| 339 | def setUp(self): | ||
| 340 | directory = tempfile.TemporaryDirectory() | ||
| 341 | self.addCleanup(directory.cleanup) | ||
| 342 | self.directory = Path(directory.name) | ||
| 343 | self.vs = self.module("vertex", output()) | ||
| 344 | self.ps = self.module("pixel", input()) | ||
| 345 | self.bad = self.module("bad_pixel", input(location=8)) | ||
| 346 | self.manifest = self.directory / "pairs.json" | ||
| 347 | self.report = self.directory / "report.json" | ||
| 348 | |||
| 349 | def module(self, name, builder): | ||
| 350 | path = self.directory / (name + ".spv") | ||
| 351 | path.write_bytes(builder.binary()) | ||
| 352 | return path | ||
| 353 | |||
| 354 | def command(self, *args): | ||
| 355 | return subprocess.run([sys.executable, "-I", ROOT / "tools" / "shader_link_check.py", *args], | ||
| 356 | capture_output=True, text=True, timeout=15) | ||
| 357 | |||
| 358 | def write_manifest(self, *items): | ||
| 359 | self.manifest.write_text(json.dumps({"version": 1, "pipelines": items}), encoding="utf-8") | ||
| 360 | |||
| 361 | def run_batch(self, *extra): | ||
| 362 | return self.command("batch", self.manifest, "--shader-dir", self.directory, *extra) | ||
| 363 | |||
| 364 | def test_direct_match(self): | ||
| 365 | result = self.command("check", "--vs", self.vs, "--ps", self.ps) | ||
| 366 | self.assertEqual(result.returncode, 0, result.stderr) | ||
| 367 | self.assertIn("compatible (1 links checked)", result.stdout) | ||
| 368 | |||
| 369 | def test_incompatible_pipeline_returns_one_and_reports_location(self): | ||
| 370 | result = self.command("check", "--vs", self.vs, "--ps", self.bad) | ||
| 371 | self.assertEqual(result.returncode, 1) | ||
| 372 | self.assertIn("vs -> ps at location 8, component 0 [missing-output]", result.stdout) | ||
| 373 | |||
| 374 | def test_wrong_stage_and_missing_module_return_two(self): | ||
| 375 | result = self.command("check", "--vs", self.ps, "--ps", self.directory / "missing.spv") | ||
| 376 | self.assertEqual(result.returncode, 2) | ||
| 377 | self.assertIn("is ps, expected vs", result.stdout) | ||
| 378 | self.assertIn("[module-error]", result.stdout) | ||
| 379 | self.assertNotIn("Traceback", result.stderr) | ||
| 380 | |||
| 381 | def test_invalid_slot_combination_returns_two(self): | ||
| 382 | result = self.command("check", "--vs", self.vs, "--ms", self.vs, "--ps", self.ps) | ||
| 383 | self.assertEqual(result.returncode, 2) | ||
| 384 | self.assertIn("expected vs+ps", result.stderr) | ||
| 385 | |||
| 386 | def test_batch_checks_other_pipelines_after_an_error_and_reports_all(self): | ||
| 387 | self.write_manifest({"name": "broken", "vs": "vertex", "ps": "missing"}, | ||
| 388 | {"name": "bad", "vs": "vertex", "ps": "bad_pixel"}, | ||
| 389 | {"name": "valid", "vs": "vertex", "ps": "pixel"}) | ||
| 390 | result = self.run_batch("--report", self.report, "--quiet") | ||
| 391 | self.assertEqual(result.returncode, 2, result.stderr) | ||
| 392 | self.assertNotIn("valid: compatible", result.stdout) | ||
| 393 | report = json.loads(self.report.read_bytes()) | ||
| 394 | self.assertEqual(report["summary"], {"compatible": 1, "incompatible": 1, "invalid": 1}) | ||
| 395 | self.assertEqual([pipeline["name"] for pipeline in report["pipelines"]], ["broken", "bad", "valid"]) | ||
| 396 | self.assertEqual(report["pipelines"][1]["problems"][0]["location"]["location"], 8) | ||
| 397 | self.assertNotIn(b"\r\n", self.report.read_bytes()) | ||
| 398 | |||
| 399 | def test_three_stage_chain_does_not_compare_across_geometry(self): | ||
| 400 | geometry = simple("gs", spv.STORAGE_INPUT, 0, array_count=3) | ||
| 401 | geometry.variable(spv.STORAGE_OUTPUT, geometry.numeric(32, 4), 8) | ||
| 402 | gs = self.module("geometry", geometry) | ||
| 403 | result = self.command("check", "--vs", self.vs, "--gs", gs, "--ps", self.bad) | ||
| 404 | self.assertEqual(result.returncode, 0, result.stdout + result.stderr) | ||
| 405 | self.assertIn("compatible (2 links checked)", result.stdout) | ||
| 406 | |||
| 407 | def test_alternate_entry_names_are_resolved_per_stage(self): | ||
| 408 | shader = input() | ||
| 409 | shader.entry("ColorMain", shader.ids) | ||
| 410 | self.module("alternative", shader) | ||
| 411 | self.write_manifest({"name": "alt", "vs": "vertex", "ps": {"shader": "alternative", "entry": "ColorMain"}}) | ||
| 412 | result = self.run_batch() | ||
| 413 | self.assertEqual(result.returncode, 0, result.stdout + result.stderr) | ||
| 414 | |||
| 415 | def test_bad_manifest_fields_return_clean_error(self): | ||
| 416 | cases = [ | ||
| 417 | {"version": True, "pipelines": []}, | ||
| 418 | {"pipelines": [{"name": "x", "vs": "../vertex", "ps": "pixel"}]}, | ||
| 419 | {"pipelines": [{"name": "x", "vs": "vertex", "ps": "pixel"}] * 2}, | ||
| 420 | {"pipelines": [{"name": "x", "vs": "vertex", "ps": {"path": "pixel.spv"}}]}, | ||
| 421 | ] | ||
| 422 | for document in cases: | ||
| 423 | with self.subTest(document=document): | ||
| 424 | self.manifest.write_text(json.dumps(document), encoding="utf-8") | ||
| 425 | result = self.run_batch() | ||
| 426 | self.assertEqual(result.returncode, 2) | ||
| 427 | self.assertIn("shader_link_check: error:", result.stderr) | ||
| 428 | self.assertNotIn("Traceback", result.stderr) | ||
| 429 | |||
| 430 | def test_report_preserves_inputs(self): | ||
| 431 | original = self.vs.read_bytes() | ||
| 432 | result = self.command("check", "--vs", self.vs, "--ps", self.ps, "--report", self.vs) | ||
| 433 | self.assertEqual(result.returncode, 2) | ||
| 434 | self.assertEqual(self.vs.read_bytes(), original) | ||
| 435 | self.write_manifest({"name": "x", "vs": "vertex", "ps": "pixel"}) | ||
| 436 | result = self.run_batch("--report", self.manifest) | ||
| 437 | self.assertEqual(result.returncode, 2) | ||
| 438 | self.assertTrue(json.loads(self.manifest.read_text())["pipelines"]) | ||
| 439 | |||
| 440 | def test_inspect_keeps_types_and_components(self): | ||
| 441 | shader = self.module("with_component", input(location=3, component=2, components=2)) | ||
| 442 | result = self.command("inspect", shader) | ||
| 443 | self.assertEqual(result.returncode, 0) | ||
| 444 | self.assertEqual(json.loads(result.stdout)["inputs"][0]["varyings"], | ||
| 445 | [{"location": 3, "component": 2, "index": 0, "type": "vec2<f32>", | ||
| 446 | "per_primitive": False}]) | ||
| 447 | |||
| 448 | def test_shader_is_reflected_once_for_repeated_pipelines(self): | ||
| 449 | self.write_manifest(*({"name": f"pair-{i}", "vs": "vertex", "ps": "pixel"} for i in range(20))) | ||
| 450 | output_stream = io.StringIO() | ||
| 451 | with patch.object(link, "reflect_module", wraps=link.reflect_module) as reflect: | ||
| 452 | with contextlib.redirect_stdout(output_stream): | ||
| 453 | result = link.main(["batch", str(self.manifest), "--shader-dir", str(self.directory), "--quiet"]) | ||
| 454 | self.assertEqual(result, 0) | ||
| 455 | self.assertEqual(reflect.call_count, 2) | ||
| 456 | |||
| 457 | |||
| 458 | if __name__ == "__main__": | ||
| 459 | unittest.main(verbosity=2) | ||
diff --git a/tests/test_spirv_gs_to_compute.py b/tests/test_spirv_gs_to_compute.py index c551051cb..6439177a9 100644 --- a/tests/test_spirv_gs_to_compute.py +++ b/tests/test_spirv_gs_to_compute.py | |||
| @@ -134,3 +134,11 @@ def test_phi_from_entry_block_names_the_split_block(tmp_path): | |||
| 134 | subprocess.run(["spirv-as", str(sa), "-o", str(sv), "--target-env", "vulkan1.2"], check=True) | 134 | subprocess.run(["spirv-as", str(sa), "-o", str(sv), "--target-env", "vulkan1.2"], check=True) |
| 135 | r = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", str(sv)], capture_output=True, text=True) | 135 | r = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", str(sv)], capture_output=True, text=True) |
| 136 | assert r.returncode == 0, r.stderr | 136 | assert r.returncode == 0, r.stderr |
| 137 | |||
| 138 | |||
| 139 | def test_help_is_a_clean_exit_zero(capsys): | ||
| 140 | for flag in ("-h", "--help"): | ||
| 141 | assert gsc.main(["spirv_gs_to_compute.py", flag]) == 0 | ||
| 142 | out = capsys.readouterr().out | ||
| 143 | assert "spirv_gs_to_compute.py in.spv out.spv" in out | ||
| 144 | assert "SPIRV-Tools" in out | ||
diff --git a/tests/test_spirv_metal_set0.py b/tests/test_spirv_metal_set0.py index 93b5286bd..e2ffe24a5 100644 --- a/tests/test_spirv_metal_set0.py +++ b/tests/test_spirv_metal_set0.py | |||
| @@ -56,3 +56,9 @@ def test_rewrite_sizes_arrays_and_spaces_bindings(): | |||
| 56 | assert "msl_arr_b2" not in out | 56 | assert "msl_arr_b2" not in out |
| 57 | # each new type comes after the pointer type it replaces, so its operands are already declared | 57 | # each new type comes after the pointer type it replaces, so its operands are already declared |
| 58 | assert out.index("%ptr_img = OpTypePointer") < out.index("%msl_cap_b0") | 58 | assert out.index("%ptr_img = OpTypePointer") < out.index("%msl_cap_b0") |
| 59 | |||
| 60 | |||
| 61 | def test_help_is_a_clean_exit_zero(capsys): | ||
| 62 | for flag in ("-h", "--help"): | ||
| 63 | assert m.main(["spirv_metal_set0.py", flag]) == 0 | ||
| 64 | assert "Usage: spirv_metal_set0.py" in capsys.readouterr().out | ||
diff --git a/tests/test_spirv_metal_set0_extra.py b/tests/test_spirv_metal_set0_extra.py new file mode 100644 index 000000000..5b03f429e --- /dev/null +++ b/tests/test_spirv_metal_set0_extra.py | |||
| @@ -0,0 +1,1043 @@ | |||
| 1 | """Expanded stdlib-only unit tests for tools/spirv_metal_set0.py. | ||
| 2 | |||
| 3 | Covers bindless capacity parsing from vulkan_bindless.h and custom headers, | ||
| 4 | metal_ids() layout math, rewrite() across all 26 bindings, non-set-0 / | ||
| 5 | push-constant / non-runtime-array / pre-sized / raw-ID / error branches, | ||
| 6 | synthetic SPIR-V binary word header/magic/endianness/bounds handling, | ||
| 7 | out-of-place vs in-place CLI execution via mocked spirv-dis/spirv-as, | ||
| 8 | --print-layout, invalid argument handling, and __main__ entry guard. | ||
| 9 | |||
| 10 | Standard library only; no spirv-dis/spirv-as/spirv-val binary, no GPU, | ||
| 11 | and no game data. | ||
| 12 | |||
| 13 | python -I tests/test_spirv_metal_set0_extra.py -v | ||
| 14 | """ | ||
| 15 | import contextlib | ||
| 16 | import io | ||
| 17 | import os | ||
| 18 | import re | ||
| 19 | import runpy | ||
| 20 | import struct | ||
| 21 | import subprocess | ||
| 22 | import sys | ||
| 23 | import tempfile | ||
| 24 | import unittest | ||
| 25 | from unittest import mock | ||
| 26 | import warnings | ||
| 27 | |||
| 28 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 29 | TOOLS_DIR = os.path.join(ROOT, "tools") | ||
| 30 | TOOL_PATH = os.path.join(TOOLS_DIR, "spirv_metal_set0.py") | ||
| 31 | if TOOLS_DIR not in sys.path: | ||
| 32 | sys.path.insert(0, TOOLS_DIR) | ||
| 33 | |||
| 34 | import spirv_metal_set0 as m # noqa: E402 | ||
| 35 | |||
| 36 | |||
| 37 | SPIRV_MAGIC = 0x07230203 | ||
| 38 | SPIRV_VERSION_1_0 = 0x00010000 | ||
| 39 | SPIRV_VERSION_1_5 = 0x00010500 | ||
| 40 | |||
| 41 | OP_MEMORY_MODEL = 14 | ||
| 42 | OP_CAPABILITY = 17 | ||
| 43 | OP_TYPE_VOID = 19 | ||
| 44 | OP_TYPE_INT = 21 | ||
| 45 | OP_TYPE_FLOAT = 22 | ||
| 46 | OP_TYPE_IMAGE = 25 | ||
| 47 | OP_TYPE_SAMPLER = 26 | ||
| 48 | OP_TYPE_ARRAY = 28 | ||
| 49 | OP_TYPE_RUNTIME_ARRAY = 29 | ||
| 50 | OP_TYPE_STRUCT = 30 | ||
| 51 | OP_TYPE_POINTER = 32 | ||
| 52 | OP_CONSTANT = 43 | ||
| 53 | OP_VARIABLE = 59 | ||
| 54 | OP_DECORATE = 71 | ||
| 55 | |||
| 56 | CAP_SHADER = 1 | ||
| 57 | CAP_RUNTIME_DESCRIPTOR_ARRAY = 5301 | ||
| 58 | ADDR_LOGICAL = 0 | ||
| 59 | MEM_GLSL450 = 1 | ||
| 60 | |||
| 61 | DEC_BLOCK = 2 | ||
| 62 | DEC_BINDING = 33 | ||
| 63 | DEC_DESCRIPTOR_SET = 34 | ||
| 64 | |||
| 65 | SC_UNIFORM_CONSTANT = 0 | ||
| 66 | SC_PUSH_CONSTANT = 9 | ||
| 67 | SC_STORAGE_BUFFER = 12 | ||
| 68 | |||
| 69 | STORAGE_CLASS_BY_NAME = { | ||
| 70 | "UniformConstant": SC_UNIFORM_CONSTANT, | ||
| 71 | "PushConstant": SC_PUSH_CONSTANT, | ||
| 72 | "StorageBuffer": SC_STORAGE_BUFFER, | ||
| 73 | } | ||
| 74 | STORAGE_CLASS_BY_CODE = {v: k for k, v in STORAGE_CLASS_BY_NAME.items()} | ||
| 75 | |||
| 76 | DIM_BY_CODE = {0: "1D", 1: "2D", 2: "3D"} | ||
| 77 | DIM_BY_NAME = {v: k for k, v in DIM_BY_CODE.items()} | ||
| 78 | |||
| 79 | FMT_BY_CODE = {0: "Unknown", 33: "R32ui"} | ||
| 80 | FMT_BY_NAME = {v: k for k, v in FMT_BY_CODE.items()} | ||
| 81 | |||
| 82 | |||
| 83 | def _encode_inst(opcode: int, *operands: int) -> list[int]: | ||
| 84 | """Encode one SPIR-V instruction into 32-bit binary words.""" | ||
| 85 | wc = 1 + len(operands) | ||
| 86 | return [(wc << 16) | opcode, *operands] | ||
| 87 | |||
| 88 | |||
| 89 | def _pack_spv( | ||
| 90 | inst_words: list[int], | ||
| 91 | *, | ||
| 92 | version: int = SPIRV_VERSION_1_5, | ||
| 93 | generator: int = 0, | ||
| 94 | bound: int | None = None, | ||
| 95 | schema: int = 0, | ||
| 96 | endian: str = "<", | ||
| 97 | ) -> bytes: | ||
| 98 | """Pack a 5-word SPIR-V header and instruction stream into binary bytes.""" | ||
| 99 | if bound is None: | ||
| 100 | max_id = 0 | ||
| 101 | pos = 0 | ||
| 102 | while pos < len(inst_words): | ||
| 103 | wc = inst_words[pos] >> 16 | ||
| 104 | op = inst_words[pos] & 0xFFFF | ||
| 105 | if wc < 1 or pos + wc > len(inst_words): | ||
| 106 | break | ||
| 107 | ops = inst_words[pos + 1 : pos + wc] | ||
| 108 | if op in (OP_TYPE_VOID, OP_TYPE_INT, OP_TYPE_FLOAT, OP_TYPE_IMAGE, OP_TYPE_SAMPLER, | ||
| 109 | OP_TYPE_ARRAY, OP_TYPE_RUNTIME_ARRAY, OP_TYPE_STRUCT, OP_TYPE_POINTER): | ||
| 110 | max_id = max(max_id, ops[0]) | ||
| 111 | elif op in (OP_CONSTANT, OP_VARIABLE): | ||
| 112 | max_id = max(max_id, ops[1]) | ||
| 113 | elif op == OP_DECORATE: | ||
| 114 | max_id = max(max_id, ops[0]) | ||
| 115 | pos += wc | ||
| 116 | bound = max_id + 1 | ||
| 117 | words = [SPIRV_MAGIC, version, generator, bound, schema, *inst_words] | ||
| 118 | return struct.pack(f"{endian}{len(words)}I", *words) | ||
| 119 | |||
| 120 | |||
| 121 | def _decode_spv(data: bytes) -> tuple[tuple[int, int, int, int, int], list[tuple[int, list[int]]]]: | ||
| 122 | """Validate SPIR-V binary header/endianness/word-bounds and decode instructions.""" | ||
| 123 | if len(data) < 20 or len(data) % 4 != 0: | ||
| 124 | raise ValueError(f"invalid SPIR-V byte length: {len(data)}") | ||
| 125 | words = list(struct.unpack(f"<{len(data) // 4}I", data)) | ||
| 126 | magic, version, generator, bound, schema = words[:5] | ||
| 127 | if magic == 0x03022307: | ||
| 128 | raise ValueError("wrong endianness (big-endian SPIR-V magic)") | ||
| 129 | if magic != SPIRV_MAGIC: | ||
| 130 | raise ValueError(f"bad SPIR-V magic: {magic:#010x}") | ||
| 131 | if bound < 1: | ||
| 132 | raise ValueError(f"invalid SPIR-V ID bound: {bound}") | ||
| 133 | if schema != 0: | ||
| 134 | raise ValueError(f"unsupported non-zero schema: {schema}") | ||
| 135 | insts = [] | ||
| 136 | pos = 5 | ||
| 137 | while pos < len(words): | ||
| 138 | wc = words[pos] >> 16 | ||
| 139 | op = words[pos] & 0xFFFF | ||
| 140 | if wc < 1 or pos + wc > len(words): | ||
| 141 | raise ValueError(f"truncated or zero-length instruction at word {pos}") | ||
| 142 | insts.append((op, words[pos + 1 : pos + wc])) | ||
| 143 | pos += wc | ||
| 144 | return (magic, version, generator, bound, schema), insts | ||
| 145 | |||
| 146 | |||
| 147 | def _synthetic_spv_to_disasm(data: bytes) -> str: | ||
| 148 | """Decode synthetic SPIR-V binary words into spirv-dis-style assembly text.""" | ||
| 149 | header, insts = _decode_spv(data) | ||
| 150 | _, version, generator, bound, schema = header | ||
| 151 | major = (version >> 16) & 0xFF | ||
| 152 | minor = (version >> 8) & 0xFF | ||
| 153 | lines = [ | ||
| 154 | "; SPIR-V", | ||
| 155 | f"; Version: {major}.{minor}", | ||
| 156 | f"; Generator: {generator}", | ||
| 157 | f"; Bound: {bound}", | ||
| 158 | f"; Schema: {schema}", | ||
| 159 | ] | ||
| 160 | indent = " " * 15 | ||
| 161 | def lhs(res_id: int) -> str: | ||
| 162 | return f"%{res_id}".rjust(12) | ||
| 163 | |||
| 164 | for op, ops in insts: | ||
| 165 | if op == OP_CAPABILITY: | ||
| 166 | name = {CAP_SHADER: "Shader", CAP_RUNTIME_DESCRIPTOR_ARRAY: "RuntimeDescriptorArray"}[ops[0]] | ||
| 167 | lines.append(f"{indent}OpCapability {name}") | ||
| 168 | elif op == OP_MEMORY_MODEL: | ||
| 169 | lines.append(f"{indent}OpMemoryModel Logical GLSL450") | ||
| 170 | elif op == OP_DECORATE: | ||
| 171 | if ops[1] == DEC_DESCRIPTOR_SET: | ||
| 172 | lines.append(f"{indent}OpDecorate %{ops[0]} DescriptorSet {ops[2]}") | ||
| 173 | elif ops[1] == DEC_BINDING: | ||
| 174 | lines.append(f"{indent}OpDecorate %{ops[0]} Binding {ops[2]}") | ||
| 175 | elif ops[1] == DEC_BLOCK: | ||
| 176 | lines.append(f"{indent}OpDecorate %{ops[0]} Block") | ||
| 177 | else: | ||
| 178 | raise ValueError(f"unsupported decoration {ops[1]}") | ||
| 179 | elif op == OP_TYPE_VOID: | ||
| 180 | lines.append(f"{lhs(ops[0])} = OpTypeVoid") | ||
| 181 | elif op == OP_TYPE_INT: | ||
| 182 | lines.append(f"{lhs(ops[0])} = OpTypeInt {ops[1]} {ops[2]}") | ||
| 183 | elif op == OP_TYPE_FLOAT: | ||
| 184 | lines.append(f"{lhs(ops[0])} = OpTypeFloat {ops[1]}") | ||
| 185 | elif op == OP_TYPE_IMAGE: | ||
| 186 | dim = DIM_BY_CODE[ops[2]] | ||
| 187 | fmt = FMT_BY_CODE[ops[7]] | ||
| 188 | lines.append( | ||
| 189 | f"{lhs(ops[0])} = OpTypeImage %{ops[1]} {dim} {ops[3]} {ops[4]} {ops[5]} {ops[6]} {fmt}" | ||
| 190 | ) | ||
| 191 | elif op == OP_TYPE_SAMPLER: | ||
| 192 | lines.append(f"{lhs(ops[0])} = OpTypeSampler") | ||
| 193 | elif op == OP_TYPE_ARRAY: | ||
| 194 | lines.append(f"{lhs(ops[0])} = OpTypeArray %{ops[1]} %{ops[2]}") | ||
| 195 | elif op == OP_TYPE_RUNTIME_ARRAY: | ||
| 196 | lines.append(f"{lhs(ops[0])} = OpTypeRuntimeArray %{ops[1]}") | ||
| 197 | elif op == OP_TYPE_STRUCT: | ||
| 198 | members = " ".join(f"%{m_id}" for m_id in ops[1:]) | ||
| 199 | lines.append(f"{lhs(ops[0])} = OpTypeStruct {members}".rstrip()) | ||
| 200 | elif op == OP_TYPE_POINTER: | ||
| 201 | sc = STORAGE_CLASS_BY_CODE[ops[1]] | ||
| 202 | lines.append(f"{lhs(ops[0])} = OpTypePointer {sc} %{ops[2]}") | ||
| 203 | elif op == OP_CONSTANT: | ||
| 204 | lines.append(f"{lhs(ops[1])} = OpConstant %{ops[0]} {ops[2]}") | ||
| 205 | elif op == OP_VARIABLE: | ||
| 206 | sc = STORAGE_CLASS_BY_CODE[ops[2]] | ||
| 207 | lines.append(f"{lhs(ops[1])} = OpVariable %{ops[0]} {sc}") | ||
| 208 | else: | ||
| 209 | raise ValueError(f"unsupported opcode {op}") | ||
| 210 | return "\n".join(lines) + "\n" | ||
| 211 | |||
| 212 | |||
| 213 | def _synthetic_disasm_to_spv(text: str, target_env: str) -> bytes: | ||
| 214 | """Assemble synthetic spirv-dis text (including rewritten %msl_* IDs) into SPIR-V words.""" | ||
| 215 | id_map: dict[str, int] = {} | ||
| 216 | next_id = 1 | ||
| 217 | |||
| 218 | def resolve(tok: str) -> int: | ||
| 219 | nonlocal next_id | ||
| 220 | if tok in id_map: | ||
| 221 | return id_map[tok] | ||
| 222 | if tok[1:].isdigit(): | ||
| 223 | val = int(tok[1:]) | ||
| 224 | id_map[tok] = val | ||
| 225 | next_id = max(next_id, val + 1) | ||
| 226 | return val | ||
| 227 | val = next_id | ||
| 228 | next_id += 1 | ||
| 229 | id_map[tok] = val | ||
| 230 | return val | ||
| 231 | |||
| 232 | # Pre-register numeric IDs so newly synthesized %msl_* names never collide. | ||
| 233 | for tok in re.findall(r"%\S+", text): | ||
| 234 | if tok[1:].isdigit(): | ||
| 235 | resolve(tok) | ||
| 236 | |||
| 237 | inst_words: list[int] = [] | ||
| 238 | for raw in text.splitlines(): | ||
| 239 | line = raw.strip() | ||
| 240 | if not line or line.startswith(";"): | ||
| 241 | continue | ||
| 242 | if line.startswith("OpCapability "): | ||
| 243 | cap = {"Shader": CAP_SHADER, "RuntimeDescriptorArray": CAP_RUNTIME_DESCRIPTOR_ARRAY}[line.split()[1]] | ||
| 244 | inst_words.extend(_encode_inst(OP_CAPABILITY, cap)) | ||
| 245 | elif line == "OpMemoryModel Logical GLSL450": | ||
| 246 | inst_words.extend(_encode_inst(OP_MEMORY_MODEL, ADDR_LOGICAL, MEM_GLSL450)) | ||
| 247 | elif line.startswith("OpDecorate "): | ||
| 248 | parts = line.split() | ||
| 249 | tid = resolve(parts[1]) | ||
| 250 | if parts[2] == "DescriptorSet": | ||
| 251 | inst_words.extend(_encode_inst(OP_DECORATE, tid, DEC_DESCRIPTOR_SET, int(parts[3]))) | ||
| 252 | elif parts[2] == "Binding": | ||
| 253 | inst_words.extend(_encode_inst(OP_DECORATE, tid, DEC_BINDING, int(parts[3]))) | ||
| 254 | elif parts[2] == "Block": | ||
| 255 | inst_words.extend(_encode_inst(OP_DECORATE, tid, DEC_BLOCK)) | ||
| 256 | else: | ||
| 257 | raise ValueError(f"unsupported OpDecorate: {line}") | ||
| 258 | else: | ||
| 259 | lhs, rhs = [p.strip() for p in line.split("=", 1)] | ||
| 260 | rid = resolve(lhs) | ||
| 261 | parts = rhs.split() | ||
| 262 | opname = parts[0] | ||
| 263 | if opname == "OpTypeVoid": | ||
| 264 | inst_words.extend(_encode_inst(OP_TYPE_VOID, rid)) | ||
| 265 | elif opname == "OpTypeInt": | ||
| 266 | inst_words.extend(_encode_inst(OP_TYPE_INT, rid, int(parts[1]), int(parts[2]))) | ||
| 267 | elif opname == "OpTypeFloat": | ||
| 268 | inst_words.extend(_encode_inst(OP_TYPE_FLOAT, rid, int(parts[1]))) | ||
| 269 | elif opname == "OpTypeImage": | ||
| 270 | inst_words.extend(_encode_inst( | ||
| 271 | OP_TYPE_IMAGE, | ||
| 272 | rid, | ||
| 273 | resolve(parts[1]), | ||
| 274 | DIM_BY_NAME[parts[2]], | ||
| 275 | int(parts[3]), | ||
| 276 | int(parts[4]), | ||
| 277 | int(parts[5]), | ||
| 278 | int(parts[6]), | ||
| 279 | FMT_BY_NAME[parts[7]], | ||
| 280 | )) | ||
| 281 | elif opname == "OpTypeSampler": | ||
| 282 | inst_words.extend(_encode_inst(OP_TYPE_SAMPLER, rid)) | ||
| 283 | elif opname == "OpTypeArray": | ||
| 284 | inst_words.extend(_encode_inst(OP_TYPE_ARRAY, rid, resolve(parts[1]), resolve(parts[2]))) | ||
| 285 | elif opname == "OpTypeRuntimeArray": | ||
| 286 | inst_words.extend(_encode_inst(OP_TYPE_RUNTIME_ARRAY, rid, resolve(parts[1]))) | ||
| 287 | elif opname == "OpTypeStruct": | ||
| 288 | inst_words.extend(_encode_inst(OP_TYPE_STRUCT, rid, *[resolve(p) for p in parts[1:]])) | ||
| 289 | elif opname == "OpTypePointer": | ||
| 290 | inst_words.extend(_encode_inst(OP_TYPE_POINTER, rid, STORAGE_CLASS_BY_NAME[parts[1]], resolve(parts[2]))) | ||
| 291 | elif opname == "OpConstant": | ||
| 292 | inst_words.extend(_encode_inst(OP_CONSTANT, resolve(parts[1]), rid, int(parts[2]))) | ||
| 293 | elif opname == "OpVariable": | ||
| 294 | inst_words.extend(_encode_inst(OP_VARIABLE, resolve(parts[1]), rid, STORAGE_CLASS_BY_NAME[parts[2]])) | ||
| 295 | else: | ||
| 296 | raise ValueError(f"unsupported op: {line}") | ||
| 297 | |||
| 298 | ver = SPIRV_VERSION_1_5 if target_env == "spv1.5" else SPIRV_VERSION_1_0 | ||
| 299 | return _pack_spv(inst_words, version=ver, bound=next_id) | ||
| 300 | |||
| 301 | |||
| 302 | def _build_mixed_bindless_spv_words() -> list[int]: | ||
| 303 | """Build synthetic SPIR-V instruction words with set-0, set-1, and PushConstant resources.""" | ||
| 304 | # IDs: | ||
| 305 | # 1=uint, 2=float, 3=img2d, 4=smp, 5=rt_img, 6=rt_smp, 7=ptr_img, 8=ptr_smp | ||
| 306 | # 9=rt_map, 10=struct_map, 11=ptr_map, 12=ptr_pc_u32 | ||
| 307 | # 13=images (set 0, b0), 14=samplers (set 0, b1), 15=desc_map (set 0, b2) | ||
| 308 | # 16=push_consts, 17=set1_var (set 1, b0) | ||
| 309 | words: list[int] = [] | ||
| 310 | words.extend(_encode_inst(OP_CAPABILITY, CAP_SHADER)) | ||
| 311 | words.extend(_encode_inst(OP_CAPABILITY, CAP_RUNTIME_DESCRIPTOR_ARRAY)) | ||
| 312 | words.extend(_encode_inst(OP_MEMORY_MODEL, ADDR_LOGICAL, MEM_GLSL450)) | ||
| 313 | words.extend(_encode_inst(OP_DECORATE, 13, DEC_DESCRIPTOR_SET, 0)) | ||
| 314 | words.extend(_encode_inst(OP_DECORATE, 13, DEC_BINDING, 0)) | ||
| 315 | words.extend(_encode_inst(OP_DECORATE, 14, DEC_DESCRIPTOR_SET, 0)) | ||
| 316 | words.extend(_encode_inst(OP_DECORATE, 14, DEC_BINDING, 1)) | ||
| 317 | words.extend(_encode_inst(OP_DECORATE, 15, DEC_DESCRIPTOR_SET, 0)) | ||
| 318 | words.extend(_encode_inst(OP_DECORATE, 15, DEC_BINDING, 2)) | ||
| 319 | words.extend(_encode_inst(OP_DECORATE, 10, DEC_BLOCK)) | ||
| 320 | words.extend(_encode_inst(OP_DECORATE, 17, DEC_DESCRIPTOR_SET, 1)) | ||
| 321 | words.extend(_encode_inst(OP_DECORATE, 17, DEC_BINDING, 0)) | ||
| 322 | words.extend(_encode_inst(OP_TYPE_INT, 1, 32, 0)) | ||
| 323 | words.extend(_encode_inst(OP_TYPE_FLOAT, 2, 32)) | ||
| 324 | words.extend(_encode_inst(OP_TYPE_IMAGE, 3, 2, 1, 0, 0, 0, 1, 0)) | ||
| 325 | words.extend(_encode_inst(OP_TYPE_SAMPLER, 4)) | ||
| 326 | words.extend(_encode_inst(OP_TYPE_RUNTIME_ARRAY, 5, 3)) | ||
| 327 | words.extend(_encode_inst(OP_TYPE_RUNTIME_ARRAY, 6, 4)) | ||
| 328 | words.extend(_encode_inst(OP_TYPE_POINTER, 7, SC_UNIFORM_CONSTANT, 5)) | ||
| 329 | words.extend(_encode_inst(OP_TYPE_POINTER, 8, SC_UNIFORM_CONSTANT, 6)) | ||
| 330 | words.extend(_encode_inst(OP_TYPE_RUNTIME_ARRAY, 9, 1)) | ||
| 331 | words.extend(_encode_inst(OP_TYPE_STRUCT, 10, 9)) | ||
| 332 | words.extend(_encode_inst(OP_TYPE_POINTER, 11, SC_STORAGE_BUFFER, 10)) | ||
| 333 | words.extend(_encode_inst(OP_TYPE_POINTER, 12, SC_PUSH_CONSTANT, 1)) | ||
| 334 | words.extend(_encode_inst(OP_VARIABLE, 7, 13, SC_UNIFORM_CONSTANT)) | ||
| 335 | words.extend(_encode_inst(OP_VARIABLE, 8, 14, SC_UNIFORM_CONSTANT)) | ||
| 336 | words.extend(_encode_inst(OP_VARIABLE, 11, 15, SC_STORAGE_BUFFER)) | ||
| 337 | words.extend(_encode_inst(OP_VARIABLE, 12, 16, SC_PUSH_CONSTANT)) | ||
| 338 | words.extend(_encode_inst(OP_VARIABLE, 7, 17, SC_UNIFORM_CONSTANT)) | ||
| 339 | return words | ||
| 340 | |||
| 341 | |||
| 342 | def _make_fake_spirv_tools(dis_name="spirv-dis", asm_name="spirv-as"): | ||
| 343 | """Return a subprocess.run replacement backed by the synthetic SPIR-V binary codec.""" | ||
| 344 | calls: list[list[str]] = [] | ||
| 345 | |||
| 346 | def fake_run(cmd, check=False, capture_output=False, text=False, input=None): | ||
| 347 | calls.append(list(cmd)) | ||
| 348 | exe = cmd[0] | ||
| 349 | if exe == dis_name: | ||
| 350 | in_path = cmd[1] | ||
| 351 | try: | ||
| 352 | with open(in_path, "rb") as f: | ||
| 353 | data = f.read() | ||
| 354 | disasm = _synthetic_spv_to_disasm(data) | ||
| 355 | except (OSError, ValueError) as exc: | ||
| 356 | if check: | ||
| 357 | raise subprocess.CalledProcessError(1, cmd, output="", stderr=str(exc)) from exc | ||
| 358 | return subprocess.CompletedProcess(cmd, 1, "", str(exc)) | ||
| 359 | return subprocess.CompletedProcess(cmd, 0, disasm, "") | ||
| 360 | if exe == asm_name: | ||
| 361 | # Expect: [asm, "--target-env", target, "-", "-o", out_path] | ||
| 362 | target_env = cmd[cmd.index("--target-env") + 1] | ||
| 363 | out_path = cmd[cmd.index("-o") + 1] | ||
| 364 | try: | ||
| 365 | out_bytes = _synthetic_disasm_to_spv(input, target_env) | ||
| 366 | with open(out_path, "wb") as f: | ||
| 367 | f.write(out_bytes) | ||
| 368 | except (OSError, ValueError) as exc: | ||
| 369 | if check: | ||
| 370 | raise subprocess.CalledProcessError(1, cmd, output="", stderr=str(exc)) from exc | ||
| 371 | return subprocess.CompletedProcess(cmd, 1, "", str(exc)) | ||
| 372 | return subprocess.CompletedProcess(cmd, 0, "", "") | ||
| 373 | raise AssertionError(f"unexpected subprocess command: {cmd!r}") | ||
| 374 | |||
| 375 | return fake_run, calls | ||
| 376 | |||
| 377 | |||
| 378 | class TestCapacities(unittest.TestCase): | ||
| 379 | def test_default_bindless_header_all_26_entries_and_cross_check(self): | ||
| 380 | counts = m.capacities() | ||
| 381 | expected = [4096, 1024, 1, 1024, 1024] + [256] * 21 | ||
| 382 | self.assertEqual(counts, expected) | ||
| 383 | self.assertEqual(len(counts), 26) | ||
| 384 | self.assertEqual(sum(counts), 12545) | ||
| 385 | |||
| 386 | with open(m.BINDLESS_H, encoding="utf-8") as f: | ||
| 387 | hdr = f.read() | ||
| 388 | self.assertIn("inline constexpr std::uint32_t binding_count = 26;", hdr) | ||
| 389 | self.assertIn("inline constexpr std::array<Binding, 26> bindings =", hdr) | ||
| 390 | |||
| 391 | def test_custom_header_parsing_variants(self): | ||
| 392 | cases = [ | ||
| 393 | ("empty_table", "std::array<Binding, 0> bindings = {{}};\n", []), | ||
| 394 | ( | ||
| 395 | "single_line", | ||
| 396 | "std::array<Binding, 1> bindings = {{{VK_DESCRIPTOR_TYPE_SAMPLER, 7}}};\n", | ||
| 397 | [7], | ||
| 398 | ), | ||
| 399 | ( | ||
| 400 | "multiline_mixed_types_and_comments", | ||
| 401 | """ | ||
| 402 | // unrelated header prefix | ||
| 403 | inline constexpr std::array<Binding, 4> bindings = {{ | ||
| 404 | {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 128}, | ||
| 405 | {VK_DESCRIPTOR_TYPE_SAMPLER, 32}, | ||
| 406 | {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}, | ||
| 407 | {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 64}, | ||
| 408 | }}; | ||
| 409 | """, | ||
| 410 | [128, 32, 1, 64], | ||
| 411 | ), | ||
| 412 | ] | ||
| 413 | with tempfile.TemporaryDirectory() as tmp: | ||
| 414 | for name, body, expected in cases: | ||
| 415 | with self.subTest(case=name): | ||
| 416 | p = os.path.join(tmp, f"{name}.h") | ||
| 417 | with open(p, "w", encoding="utf-8") as f: | ||
| 418 | f.write(body) | ||
| 419 | self.assertEqual(m.capacities(p), expected) | ||
| 420 | |||
| 421 | def test_missing_file_raises_file_not_found(self): | ||
| 422 | with tempfile.TemporaryDirectory() as tmp: | ||
| 423 | missing = os.path.join(tmp, "missing_bindless.h") | ||
| 424 | with self.assertRaises(FileNotFoundError): | ||
| 425 | m.capacities(missing) | ||
| 426 | |||
| 427 | def test_missing_or_mismatched_bindings_table_raises_system_exit(self): | ||
| 428 | bad_headers = [ | ||
| 429 | ("empty_file", "", "no `bindings` table"), | ||
| 430 | ("wrong_type_name", "std::array<int, 1> bindings = {{ {VK_DESCRIPTOR_TYPE_SAMPLER, 4} }};", "no `bindings` table"), | ||
| 431 | ( | ||
| 432 | "too_few_entries", | ||
| 433 | "std::array<Binding, 3> bindings = {{ {VK_DESCRIPTOR_TYPE_SAMPLER, 1}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2} }};", | ||
| 434 | "`bindings` declares 3 entries, found 2", | ||
| 435 | ), | ||
| 436 | ( | ||
| 437 | "too_many_entries", | ||
| 438 | "std::array<Binding, 1> bindings = {{ {VK_DESCRIPTOR_TYPE_SAMPLER, 1}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2} }};", | ||
| 439 | "`bindings` declares 1 entries, found 2", | ||
| 440 | ), | ||
| 441 | ( | ||
| 442 | "unmatched_entry_syntax", | ||
| 443 | "std::array<Binding, 1> bindings = {{ {NOT_A_VK_DESCRIPTOR, 1} }};", | ||
| 444 | "`bindings` declares 1 entries, found 0", | ||
| 445 | ), | ||
| 446 | ] | ||
| 447 | with tempfile.TemporaryDirectory() as tmp: | ||
| 448 | for name, body, msg_part in bad_headers: | ||
| 449 | with self.subTest(case=name): | ||
| 450 | p = os.path.join(tmp, f"{name}.h") | ||
| 451 | with open(p, "w", encoding="utf-8") as f: | ||
| 452 | f.write(body) | ||
| 453 | with self.assertRaises(SystemExit) as ctx: | ||
| 454 | m.capacities(p) | ||
| 455 | self.assertIn(p, str(ctx.exception)) | ||
| 456 | self.assertIn(msg_part, str(ctx.exception)) | ||
| 457 | |||
| 458 | |||
| 459 | class TestMetalIds(unittest.TestCase): | ||
| 460 | def test_empty_single_and_zero_capacities(self): | ||
| 461 | self.assertEqual(m.metal_ids([]), []) | ||
| 462 | self.assertEqual(m.metal_ids([42]), [0]) | ||
| 463 | self.assertEqual(m.metal_ids([10, 0, 5, 0, 1]), [0, 10, 10, 15, 15]) | ||
| 464 | |||
| 465 | def test_vulkan_bindless_ids_contiguous_and_non_overlapping(self): | ||
| 466 | counts = m.capacities() | ||
| 467 | ids = m.metal_ids(counts) | ||
| 468 | self.assertEqual(len(ids), 26) | ||
| 469 | self.assertEqual(ids[0], 0) | ||
| 470 | self.assertEqual(ids[:6], [0, 4096, 5120, 5121, 6145, 7169]) | ||
| 471 | self.assertEqual(ids[8], 7937) | ||
| 472 | self.assertEqual(ids[20], 11009) | ||
| 473 | self.assertEqual(ids[25], 12289) | ||
| 474 | for b in range(len(counts) - 1): | ||
| 475 | self.assertEqual(ids[b + 1], ids[b] + counts[b]) | ||
| 476 | self.assertEqual(ids[-1] + counts[-1], sum(counts)) | ||
| 477 | |||
| 478 | seen_total = 0 | ||
| 479 | for b in range(len(counts)): | ||
| 480 | if b > 0: | ||
| 481 | self.assertGreater(ids[b], ids[b - 1] + counts[b - 1] - 1) | ||
| 482 | seen_total += counts[b] | ||
| 483 | self.assertEqual(seen_total, 12545) | ||
| 484 | |||
| 485 | |||
| 486 | class TestRewrite(unittest.TestCase): | ||
| 487 | def test_all_26_vulkan_bindless_bindings(self): | ||
| 488 | counts = m.capacities() | ||
| 489 | ids = m.metal_ids(counts) | ||
| 490 | lines = [ | ||
| 491 | " OpCapability Shader", | ||
| 492 | " OpCapability RuntimeDescriptorArray", | ||
| 493 | " OpMemoryModel Logical GLSL450", | ||
| 494 | ] | ||
| 495 | for b in range(26): | ||
| 496 | lines.append(f" OpDecorate %v{b} DescriptorSet 0") | ||
| 497 | lines.append(f" OpDecorate %v{b} Binding {b}") | ||
| 498 | lines.extend([ | ||
| 499 | " %uint = OpTypeInt 32 0", | ||
| 500 | " %float = OpTypeFloat 32", | ||
| 501 | " %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown", | ||
| 502 | " %smp = OpTypeSampler", | ||
| 503 | " %rt_map = OpTypeRuntimeArray %uint", | ||
| 504 | " %map = OpTypeStruct %rt_map", | ||
| 505 | " %ptr_map = OpTypePointer StorageBuffer %map", | ||
| 506 | ]) | ||
| 507 | for b in range(26): | ||
| 508 | if b == 2: | ||
| 509 | continue | ||
| 510 | elem = "%smp" if b == 1 else "%img2d" | ||
| 511 | lines.append(f" %rt_b{b} = OpTypeRuntimeArray {elem}") | ||
| 512 | lines.append(f" %ptr_b{b} = OpTypePointer UniformConstant %rt_b{b}") | ||
| 513 | for b in range(26): | ||
| 514 | if b == 2: | ||
| 515 | lines.append(" %v2 = OpVariable %ptr_map StorageBuffer") | ||
| 516 | else: | ||
| 517 | lines.append(f" %v{b} = OpVariable %ptr_b{b} UniformConstant") | ||
| 518 | |||
| 519 | out = m.rewrite("\n".join(lines) + "\n", counts) | ||
| 520 | out_lines = out.splitlines() | ||
| 521 | |||
| 522 | for b in range(26): | ||
| 523 | self.assertIn(f" OpDecorate %v{b} Binding {ids[b]}", out_lines) | ||
| 524 | if b == 2: | ||
| 525 | self.assertIn(" %v2 = OpVariable %ptr_map StorageBuffer", out_lines) | ||
| 526 | self.assertNotIn("%msl_cap_b2 ", out) | ||
| 527 | self.assertNotIn("%msl_arr_b2 ", out) | ||
| 528 | self.assertNotIn("%msl_ptr_b2 ", out) | ||
| 529 | else: | ||
| 530 | elem = "%smp" if b == 1 else "%img2d" | ||
| 531 | cap_line = f"%msl_cap_b{b} = OpConstant %uint {counts[b]}" | ||
| 532 | arr_line = f"%msl_arr_b{b} = OpTypeArray {elem} %msl_cap_b{b}" | ||
| 533 | ptr_line = f"%msl_ptr_b{b} = OpTypePointer UniformConstant %msl_arr_b{b}" | ||
| 534 | orig_ptr_line = f" %ptr_b{b} = OpTypePointer UniformConstant %rt_b{b}" | ||
| 535 | idx = out_lines.index(orig_ptr_line) | ||
| 536 | self.assertEqual(out_lines[idx + 1 : idx + 4], [cap_line, arr_line, ptr_line]) | ||
| 537 | self.assertIn(f" %v{b} = OpVariable %msl_ptr_b{b} UniformConstant", out_lines) | ||
| 538 | |||
| 539 | def test_push_constants_and_other_descriptor_sets_untouched(self): | ||
| 540 | module = """\ | ||
| 541 | OpDecorate %set0_img DescriptorSet 0 | ||
| 542 | OpDecorate %set0_img Binding 0 | ||
| 543 | OpDecorate %set0_smp DescriptorSet 0 | ||
| 544 | OpDecorate %set0_smp Binding 1 | ||
| 545 | OpDecorate %set1_in DescriptorSet 1 | ||
| 546 | OpDecorate %set1_in Binding 0 | ||
| 547 | OpDecorate %set1_high DescriptorSet 1 | ||
| 548 | OpDecorate %set1_high Binding 99 | ||
| 549 | OpDecorate %set2_uc DescriptorSet 2 | ||
| 550 | OpDecorate %set2_uc Binding 0 | ||
| 551 | %uint = OpTypeInt 32 0 | ||
| 552 | %float = OpTypeFloat 32 | ||
| 553 | %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown | ||
| 554 | %smp = OpTypeSampler | ||
| 555 | %rt_img = OpTypeRuntimeArray %img2d | ||
| 556 | %rt_smp = OpTypeRuntimeArray %smp | ||
| 557 | %ptr_img = OpTypePointer UniformConstant %rt_img | ||
| 558 | %ptr_smp = OpTypePointer UniformConstant %rt_smp | ||
| 559 | %ptr_pc = OpTypePointer PushConstant %uint | ||
| 560 | %ptr_s1hi = OpTypePointer UniformConstant %rt_img | ||
| 561 | %ptr_s2uc = OpTypePointer UniformConstant %rt_img | ||
| 562 | %set0_img = OpVariable %ptr_img UniformConstant | ||
| 563 | %set0_smp = OpVariable %ptr_smp UniformConstant | ||
| 564 | %user_data = OpVariable %ptr_pc PushConstant | ||
| 565 | %set1_in = OpVariable %ptr_img StorageBuffer | ||
| 566 | %set1_high = OpVariable %ptr_s1hi UniformConstant | ||
| 567 | %set2_uc = OpVariable %ptr_s2uc UniformConstant | ||
| 568 | """ | ||
| 569 | out = m.rewrite(module, [8, 4]) | ||
| 570 | self.assertIn("OpDecorate %set0_img Binding 0", out) | ||
| 571 | self.assertIn("OpDecorate %set0_smp Binding 8", out) | ||
| 572 | # Set 1 (including binding 99 >= len(counts)), Set 2, and PushConstant stay untouched. | ||
| 573 | self.assertIn("OpDecorate %set1_in DescriptorSet 1", out) | ||
| 574 | self.assertIn("OpDecorate %set1_in Binding 0", out) | ||
| 575 | self.assertIn("OpDecorate %set1_high DescriptorSet 1", out) | ||
| 576 | self.assertIn("OpDecorate %set1_high Binding 99", out) | ||
| 577 | self.assertIn("OpDecorate %set2_uc DescriptorSet 2", out) | ||
| 578 | self.assertIn("OpDecorate %set2_uc Binding 0", out) | ||
| 579 | self.assertIn("%user_data = OpVariable %ptr_pc PushConstant", out) | ||
| 580 | self.assertIn("%set1_in = OpVariable %ptr_img StorageBuffer", out) | ||
| 581 | self.assertIn("%set1_high = OpVariable %ptr_s1hi UniformConstant", out) | ||
| 582 | self.assertIn("%set2_uc = OpVariable %ptr_s2uc UniformConstant", out) | ||
| 583 | |||
| 584 | def test_non_runtime_array_set0_resources_rebind_without_retyping_or_uint32(self): | ||
| 585 | # No OpTypeInt 32 0 is present, yet none of these set-0 bindings use OpTypeRuntimeArray | ||
| 586 | # under OpTypePointer UniformConstant, so rewriting succeeds without raising. | ||
| 587 | module = """\ | ||
| 588 | OpDecorate %single DescriptorSet 0 | ||
| 589 | OpDecorate %single Binding 0 | ||
| 590 | OpDecorate %fixed DescriptorSet 0 | ||
| 591 | OpDecorate %fixed Binding 1 | ||
| 592 | OpDecorate %ubo DescriptorSet 0 | ||
| 593 | OpDecorate %ubo Binding 2 | ||
| 594 | OpDecorate %mismatch DescriptorSet 0 | ||
| 595 | OpDecorate %mismatch Binding 3 | ||
| 596 | OpDecorate %dangling DescriptorSet 0 | ||
| 597 | OpDecorate %dangling Binding 4 | ||
| 598 | %float = OpTypeFloat 32 | ||
| 599 | %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown | ||
| 600 | %sint = OpTypeInt 32 1 | ||
| 601 | %c16 = OpConstant %sint 16 | ||
| 602 | %fixed_arr = OpTypeArray %img2d %c16 | ||
| 603 | %ubo_blk = OpTypeStruct %float | ||
| 604 | %ptr_single = OpTypePointer UniformConstant %img2d | ||
| 605 | %ptr_fixed = OpTypePointer UniformConstant %fixed_arr | ||
| 606 | %ptr_ubo = OpTypePointer Uniform %ubo_blk | ||
| 607 | %ptr_mis_sb = OpTypePointer StorageBuffer %fixed_arr | ||
| 608 | %ptr_dangling = OpTypePointer UniformConstant %missing_pointee | ||
| 609 | %single = OpVariable %ptr_single UniformConstant | ||
| 610 | %fixed = OpVariable %ptr_fixed UniformConstant | ||
| 611 | %ubo = OpVariable %ptr_ubo Uniform | ||
| 612 | %mismatch = OpVariable %ptr_mis_sb UniformConstant | ||
| 613 | %dangling = OpVariable %ptr_dangling UniformConstant | ||
| 614 | """ | ||
| 615 | counts = [10, 20, 1, 5, 2] | ||
| 616 | out = m.rewrite(module, counts) | ||
| 617 | self.assertIn("OpDecorate %single Binding 0", out) | ||
| 618 | self.assertIn("OpDecorate %fixed Binding 10", out) | ||
| 619 | self.assertIn("OpDecorate %ubo Binding 30", out) | ||
| 620 | self.assertIn("OpDecorate %mismatch Binding 31", out) | ||
| 621 | self.assertIn("OpDecorate %dangling Binding 36", out) | ||
| 622 | self.assertIn("%single = OpVariable %ptr_single UniformConstant", out) | ||
| 623 | self.assertIn("%fixed = OpVariable %ptr_fixed UniformConstant", out) | ||
| 624 | self.assertIn("%ubo = OpVariable %ptr_ubo Uniform", out) | ||
| 625 | self.assertIn("%mismatch = OpVariable %ptr_mis_sb UniformConstant", out) | ||
| 626 | self.assertIn("%dangling = OpVariable %ptr_dangling UniformConstant", out) | ||
| 627 | self.assertNotIn("%msl_", out) | ||
| 628 | |||
| 629 | def test_partial_decorations_and_missing_var_def(self): | ||
| 630 | module = """\ | ||
| 631 | OpDecorate %only_set DescriptorSet 0 | ||
| 632 | OpDecorate %only_bind Binding 1 | ||
| 633 | OpDecorate %orphan DescriptorSet 0 | ||
| 634 | OpDecorate %orphan Binding 1 | ||
| 635 | %u = OpTypeInt 32 0 | ||
| 636 | """ | ||
| 637 | out = m.rewrite(module, [5, 7]) | ||
| 638 | self.assertIn("OpDecorate %only_set DescriptorSet 0", out) | ||
| 639 | self.assertIn("OpDecorate %only_bind Binding 1", out) | ||
| 640 | self.assertIn("OpDecorate %orphan Binding 5", out) | ||
| 641 | self.assertNotIn("%msl_", out) | ||
| 642 | |||
| 643 | def test_raw_numeric_ids_custom_uint_and_crlf_and_shared_pointer(self): | ||
| 644 | module = ( | ||
| 645 | "; Header comment\r\n" | ||
| 646 | "OpName %10 \"images\"\r\n" | ||
| 647 | "OpDecorate %10 DescriptorSet 0\r\n" | ||
| 648 | "OpDecorate %10 Binding 1\r\n" | ||
| 649 | "OpDecorate %11 DescriptorSet 0\r\n" | ||
| 650 | "OpDecorate %11 Binding 0\r\n" | ||
| 651 | "%1 = OpTypeVoid\r\n" | ||
| 652 | "%2 = OpTypeInt 32 1\r\n" | ||
| 653 | "%3 = OpTypeInt 64 0\r\n" | ||
| 654 | "%4 = OpTypeInt 32 0\r\n" | ||
| 655 | "%5 = OpTypeFloat 32\r\n" | ||
| 656 | "%6 = OpTypeImage %5 2D 0 0 0 1 Unknown\r\n" | ||
| 657 | "%7 = OpTypeRuntimeArray %6\r\n" | ||
| 658 | "%8 = OpTypePointer UniformConstant %7\r\n" | ||
| 659 | "%9 = OpTypePointer Function %5\r\n" | ||
| 660 | "%10 = OpVariable %8 UniformConstant\r\n" | ||
| 661 | "%11 = OpVariable %8 UniformConstant\r\n" | ||
| 662 | ) | ||
| 663 | out = m.rewrite(module, [16, 8]) | ||
| 664 | self.assertNotIn("\r\n", out) | ||
| 665 | self.assertTrue(out.endswith("\n")) | ||
| 666 | self.assertIn("OpDecorate %11 Binding 0", out) | ||
| 667 | self.assertIn("OpDecorate %10 Binding 16", out) | ||
| 668 | # First OpTypeInt 32 0 is %4 (not %2 signed or %3 64-bit). | ||
| 669 | self.assertIn("%msl_cap_b0 = OpConstant %4 16", out) | ||
| 670 | self.assertIn("%msl_cap_b1 = OpConstant %4 8", out) | ||
| 671 | self.assertIn("%11 = OpVariable %msl_ptr_b0 UniformConstant", out) | ||
| 672 | self.assertIn("%10 = OpVariable %msl_ptr_b1 UniformConstant", out) | ||
| 673 | # Sorted binding order (b0 then b1) inserted immediately after %8, not after %9. | ||
| 674 | lines = out.splitlines() | ||
| 675 | idx8 = lines.index("%8 = OpTypePointer UniformConstant %7") | ||
| 676 | self.assertEqual(lines[idx8 + 1 : idx8 + 7], [ | ||
| 677 | "%msl_cap_b0 = OpConstant %4 16", | ||
| 678 | "%msl_arr_b0 = OpTypeArray %6 %msl_cap_b0", | ||
| 679 | "%msl_ptr_b0 = OpTypePointer UniformConstant %msl_arr_b0", | ||
| 680 | "%msl_cap_b1 = OpConstant %4 8", | ||
| 681 | "%msl_arr_b1 = OpTypeArray %6 %msl_cap_b1", | ||
| 682 | "%msl_ptr_b1 = OpTypePointer UniformConstant %msl_arr_b1", | ||
| 683 | ]) | ||
| 684 | idx9 = lines.index("%9 = OpTypePointer Function %5") | ||
| 685 | self.assertEqual(lines[idx9 + 1], "%10 = OpVariable %msl_ptr_b1 UniformConstant") | ||
| 686 | |||
| 687 | def test_empty_and_no_set0_modules(self): | ||
| 688 | self.assertEqual(m.rewrite("", [4]), "\n") | ||
| 689 | plain = "OpCapability Shader\nOpMemoryModel Logical GLSL450\n" | ||
| 690 | self.assertEqual(m.rewrite(plain, [4]), plain) | ||
| 691 | |||
| 692 | def test_out_of_bounds_set0_binding_raises_system_exit(self): | ||
| 693 | for b, counts in ((2, [10, 20]), (26, m.capacities()), (100, m.capacities())): | ||
| 694 | with self.subTest(binding=b, count_len=len(counts)): | ||
| 695 | text = f"OpDecorate %bad DescriptorSet 0\nOpDecorate %bad Binding {b}\n" | ||
| 696 | with self.assertRaises(SystemExit) as ctx: | ||
| 697 | m.rewrite(text, counts) | ||
| 698 | self.assertIn("%bad", str(ctx.exception)) | ||
| 699 | self.assertIn(f"binding {b}", str(ctx.exception)) | ||
| 700 | |||
| 701 | def test_missing_uint32_type_raises_when_runtime_array_rewritten(self): | ||
| 702 | base = """\ | ||
| 703 | OpDecorate %images DescriptorSet 0 | ||
| 704 | OpDecorate %images Binding 0 | ||
| 705 | {int_decl} | ||
| 706 | %float = OpTypeFloat 32 | ||
| 707 | %img2d = OpTypeImage %float 2D 0 0 0 1 Unknown | ||
| 708 | %rt_img = OpTypeRuntimeArray %img2d | ||
| 709 | %ptr_img = OpTypePointer UniformConstant %rt_img | ||
| 710 | %images = OpVariable %ptr_img UniformConstant | ||
| 711 | """ | ||
| 712 | for label, int_decl in ( | ||
| 713 | ("no_int", ""), | ||
| 714 | ("signed_32", "%s32 = OpTypeInt 32 1"), | ||
| 715 | ("unsigned_64", "%u64 = OpTypeInt 64 0"), | ||
| 716 | ): | ||
| 717 | with self.subTest(case=label): | ||
| 718 | with self.assertRaises(SystemExit) as ctx: | ||
| 719 | m.rewrite(base.format(int_decl=int_decl), [4096]) | ||
| 720 | self.assertIn("no 32-bit uint type", str(ctx.exception)) | ||
| 721 | |||
| 722 | |||
| 723 | class TestMainAndCli(unittest.TestCase): | ||
| 724 | def _call_main(self, argv): | ||
| 725 | out, err = io.StringIO(), io.StringIO() | ||
| 726 | # tools/spirv_metal_set0.py:31 uses open(path).read() without a context manager, which emits | ||
| 727 | # ResourceWarning under unittest's default filter on redirected stderr; isolate tool stderr here. | ||
| 728 | with warnings.catch_warnings(): | ||
| 729 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 730 | with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): | ||
| 731 | code = m.main(argv) | ||
| 732 | return code, out.getvalue(), err.getvalue() | ||
| 733 | |||
| 734 | def test_print_layout_outputs_26_formatted_ranges_without_subprocess(self): | ||
| 735 | with mock.patch.object(m.subprocess, "run") as run_mock: | ||
| 736 | code, out, err = self._call_main(["spirv_metal_set0.py", "--print-layout"]) | ||
| 737 | run_mock.assert_not_called() | ||
| 738 | self.assertEqual(code, 0) | ||
| 739 | self.assertEqual(err, "") | ||
| 740 | lines = out.splitlines() | ||
| 741 | self.assertEqual(len(lines), 26) | ||
| 742 | self.assertEqual(lines[0], "binding 0: 4096 descriptors at IDs 0..4095") | ||
| 743 | self.assertEqual(lines[1], "binding 1: 1024 descriptors at IDs 4096..5119") | ||
| 744 | self.assertEqual(lines[2], "binding 2: 1 descriptors at IDs 5120..5120") | ||
| 745 | self.assertEqual(lines[3], "binding 3: 1024 descriptors at IDs 5121..6144") | ||
| 746 | self.assertEqual(lines[4], "binding 4: 1024 descriptors at IDs 6145..7168") | ||
| 747 | self.assertEqual(lines[25], "binding 25: 256 descriptors at IDs 12289..12544") | ||
| 748 | |||
| 749 | def test_print_layout_uses_capacities_table(self): | ||
| 750 | with mock.patch.object(m, "capacities", return_value=[3, 1, 2]): | ||
| 751 | code, out, err = self._call_main(["spirv_metal_set0.py", "--print-layout"]) | ||
| 752 | self.assertEqual(code, 0) | ||
| 753 | self.assertEqual(err, "") | ||
| 754 | self.assertEqual(out.splitlines(), [ | ||
| 755 | "binding 0: 3 descriptors at IDs 0..2", | ||
| 756 | "binding 1: 1 descriptors at IDs 3..3", | ||
| 757 | "binding 2: 2 descriptors at IDs 4..5", | ||
| 758 | ]) | ||
| 759 | |||
| 760 | def test_invalid_argc_returns_2_and_prints_usage_to_stderr(self): | ||
| 761 | bad_argvs = [ | ||
| 762 | [], | ||
| 763 | ["spirv_metal_set0.py"], | ||
| 764 | ["spirv_metal_set0.py", "in.spv"], | ||
| 765 | ["spirv_metal_set0.py", "--unknown"], | ||
| 766 | ["spirv_metal_set0.py", "--print-layout", "in.spv", "out.spv"], | ||
| 767 | ["spirv_metal_set0.py", "in.spv", "out.spv", "extra"], | ||
| 768 | ] | ||
| 769 | for argv in bad_argvs: | ||
| 770 | with self.subTest(argv=argv), mock.patch.object(m.subprocess, "run") as run_mock: | ||
| 771 | code, out, err = self._call_main(argv) | ||
| 772 | run_mock.assert_not_called() | ||
| 773 | self.assertEqual(code, 2) | ||
| 774 | self.assertEqual(out, "") | ||
| 775 | self.assertIn("Usage: spirv_metal_set0.py in.spv out.spv", err) | ||
| 776 | self.assertIn("--print-layout", err) | ||
| 777 | |||
| 778 | def test_print_layout_with_extra_arg_falls_through_to_two_arg_mode(self): | ||
| 779 | with mock.patch.object( | ||
| 780 | m.subprocess, | ||
| 781 | "run", | ||
| 782 | side_effect=[ | ||
| 783 | subprocess.CompletedProcess([], 0, "OpCapability Shader\n", ""), | ||
| 784 | subprocess.CompletedProcess([], 0, "", ""), | ||
| 785 | ], | ||
| 786 | ) as run_mock: | ||
| 787 | code, out, err = self._call_main(["spirv_metal_set0.py", "--print-layout", "out.spv"]) | ||
| 788 | self.assertEqual((code, out, err), (0, "", "")) | ||
| 789 | self.assertEqual(run_mock.call_args_list[0].args[0], ["spirv-dis", "--print-layout"]) | ||
| 790 | self.assertEqual( | ||
| 791 | run_mock.call_args_list[1].args[0], | ||
| 792 | ["spirv-as", "--target-env", "vulkan1.2", "-", "-o", "out.spv"], | ||
| 793 | ) | ||
| 794 | |||
| 795 | def test_cli_subprocess_isolated_print_layout_and_bad_args(self): | ||
| 796 | r_layout = subprocess.run( | ||
| 797 | [sys.executable, "-I", TOOL_PATH, "--print-layout"], | ||
| 798 | capture_output=True, | ||
| 799 | text=True, | ||
| 800 | cwd=ROOT, | ||
| 801 | ) | ||
| 802 | self.assertEqual(r_layout.returncode, 0, r_layout.stderr) | ||
| 803 | self.assertEqual(r_layout.stderr, "") | ||
| 804 | self.assertEqual(len(r_layout.stdout.splitlines()), 26) | ||
| 805 | self.assertEqual(r_layout.stdout.splitlines()[0], "binding 0: 4096 descriptors at IDs 0..4095") | ||
| 806 | |||
| 807 | for args in ([], ["only_one.spv"], ["a.spv", "b.spv", "c.spv"]): | ||
| 808 | with self.subTest(args=args): | ||
| 809 | r = subprocess.run( | ||
| 810 | [sys.executable, "-I", TOOL_PATH, *args], | ||
| 811 | capture_output=True, | ||
| 812 | text=True, | ||
| 813 | cwd=ROOT, | ||
| 814 | ) | ||
| 815 | self.assertEqual(r.returncode, 2) | ||
| 816 | self.assertEqual(r.stdout, "") | ||
| 817 | self.assertIn("Usage: spirv_metal_set0.py in.spv out.spv", r.stderr) | ||
| 818 | self.assertNotIn("Traceback", r.stderr) | ||
| 819 | |||
| 820 | def test_synthetic_spv_out_of_place_and_in_place_binary_round_trip(self): | ||
| 821 | in_bytes = _pack_spv(_build_mixed_bindless_spv_words(), version=SPIRV_VERSION_1_5) | ||
| 822 | fake_run, calls = _make_fake_spirv_tools() | ||
| 823 | |||
| 824 | with tempfile.TemporaryDirectory() as tmp: | ||
| 825 | unicode_dir = os.path.join(tmp, "dir-\u00e9-\u2603") | ||
| 826 | os.makedirs(unicode_dir) | ||
| 827 | in_path = os.path.join(unicode_dir, "in.spv") | ||
| 828 | out_path = os.path.join(unicode_dir, "out.spv") | ||
| 829 | with open(in_path, "wb") as f: | ||
| 830 | f.write(in_bytes) | ||
| 831 | |||
| 832 | with mock.patch.dict(os.environ, {}, clear=False), \ | ||
| 833 | mock.patch.object(m.subprocess, "run", side_effect=fake_run): | ||
| 834 | os.environ.pop("SPIRV_DIS", None) | ||
| 835 | os.environ.pop("SPIRV_AS", None) | ||
| 836 | code, out, err = self._call_main(["spirv_metal_set0.py", in_path, out_path]) | ||
| 837 | |||
| 838 | self.assertEqual(code, 0) | ||
| 839 | self.assertEqual(out, "") | ||
| 840 | self.assertEqual(err, "") | ||
| 841 | self.assertEqual(calls, [ | ||
| 842 | ["spirv-dis", in_path], | ||
| 843 | ["spirv-as", "--target-env", "spv1.5", "-", "-o", out_path], | ||
| 844 | ]) | ||
| 845 | |||
| 846 | # Original input file is preserved untouched for out-of-place conversion. | ||
| 847 | with open(in_path, "rb") as f: | ||
| 848 | self.assertEqual(f.read(), in_bytes) | ||
| 849 | |||
| 850 | with open(out_path, "rb") as f: | ||
| 851 | out_bytes = f.read() | ||
| 852 | header, insts = _decode_spv(out_bytes) | ||
| 853 | self.assertEqual(header[0], SPIRV_MAGIC) | ||
| 854 | self.assertEqual(header[1], SPIRV_VERSION_1_5) | ||
| 855 | self.assertEqual(header[4], 0) | ||
| 856 | |||
| 857 | decs = [ops for op, ops in insts if op == OP_DECORATE] | ||
| 858 | bindings_by_id = {ops[0]: ops[2] for ops in decs if ops[1] == DEC_BINDING} | ||
| 859 | sets_by_id = {ops[0]: ops[2] for ops in decs if ops[1] == DEC_DESCRIPTOR_SET} | ||
| 860 | self.assertEqual(sets_by_id, {13: 0, 14: 0, 15: 0, 17: 1}) | ||
| 861 | # Set-0 bindings rewritten per vulkan_bindless.h; set-1 binding 0 stays 0. | ||
| 862 | self.assertEqual(bindings_by_id, {13: 0, 14: 4096, 15: 5120, 17: 0}) | ||
| 863 | |||
| 864 | consts = {ops[1]: ops[2] for op, ops in insts if op == OP_CONSTANT} | ||
| 865 | arrays = {ops[0]: (ops[1], consts[ops[2]]) for op, ops in insts if op == OP_TYPE_ARRAY} | ||
| 866 | ptrs = {ops[0]: (ops[1], ops[2]) for op, ops in insts if op == OP_TYPE_POINTER} | ||
| 867 | vars_by_id = {ops[1]: (ops[0], ops[2]) for op, ops in insts if op == OP_VARIABLE} | ||
| 868 | |||
| 869 | # %13 (images) and %14 (samplers) are retyped to sized arrays [4096] and [1024]; | ||
| 870 | # %15 (desc_map StorageBuffer), %16 (PushConstant), and %17 (set 1) keep original types. | ||
| 871 | self.assertEqual(arrays[ptrs[vars_by_id[13][0]][1]], (3, 4096)) | ||
| 872 | self.assertEqual(arrays[ptrs[vars_by_id[14][0]][1]], (4, 1024)) | ||
| 873 | self.assertEqual(vars_by_id[15], (11, SC_STORAGE_BUFFER)) | ||
| 874 | self.assertEqual(vars_by_id[16], (12, SC_PUSH_CONSTANT)) | ||
| 875 | self.assertEqual(vars_by_id[17], (7, SC_UNIFORM_CONSTANT)) | ||
| 876 | |||
| 877 | # In-place conversion: argv[1] == argv[2]. | ||
| 878 | inplace_path = os.path.join(unicode_dir, "inplace.spv") | ||
| 879 | with open(inplace_path, "wb") as f: | ||
| 880 | f.write(in_bytes) | ||
| 881 | calls.clear() | ||
| 882 | with mock.patch.object(m.subprocess, "run", side_effect=fake_run): | ||
| 883 | code, out, err = self._call_main(["spirv_metal_set0.py", inplace_path, inplace_path]) | ||
| 884 | self.assertEqual(code, 0) | ||
| 885 | self.assertEqual(out, "") | ||
| 886 | self.assertEqual(err, "") | ||
| 887 | self.assertEqual(calls, [ | ||
| 888 | ["spirv-dis", inplace_path], | ||
| 889 | ["spirv-as", "--target-env", "spv1.5", "-", "-o", inplace_path], | ||
| 890 | ]) | ||
| 891 | with open(inplace_path, "rb") as f: | ||
| 892 | self.assertEqual(f.read(), out_bytes) | ||
| 893 | |||
| 894 | def test_target_env_extraction_and_env_var_overrides(self): | ||
| 895 | cases = [ | ||
| 896 | ("; Version: 1.0\n", "spv1.0"), | ||
| 897 | ("; SPIR-V\n; Version: 1.5\n", "spv1.5"), | ||
| 898 | ("; Version: 1.6\n", "spv1.6"), | ||
| 899 | ("; SPIR-V without version comment\n", "vulkan1.2"), | ||
| 900 | ] | ||
| 901 | for header_text, expected_target in cases: | ||
| 902 | with self.subTest(expected_target=expected_target): | ||
| 903 | disasm = header_text + "OpCapability Shader\n" | ||
| 904 | seen_cmds = [] | ||
| 905 | |||
| 906 | def run_stub(cmd, check=False, capture_output=False, text=False, input=None): | ||
| 907 | seen_cmds.append((list(cmd), check, capture_output, text, input)) | ||
| 908 | if len(seen_cmds) == 1: | ||
| 909 | return subprocess.CompletedProcess(cmd, 0, disasm, "") | ||
| 910 | return subprocess.CompletedProcess(cmd, 0, "", "") | ||
| 911 | |||
| 912 | with mock.patch.dict(os.environ, {"SPIRV_DIS": "/opt/bin/dis", "SPIRV_AS": "/opt/bin/as"}), \ | ||
| 913 | mock.patch.object(m.subprocess, "run", side_effect=run_stub): | ||
| 914 | code, out, err = self._call_main(["spirv_metal_set0.py", "in.spv", "out.spv"]) | ||
| 915 | |||
| 916 | self.assertEqual((code, out, err), (0, "", "")) | ||
| 917 | self.assertEqual(seen_cmds[0][0], ["/opt/bin/dis", "in.spv"]) | ||
| 918 | self.assertTrue(seen_cmds[0][1]) | ||
| 919 | self.assertTrue(seen_cmds[0][2]) | ||
| 920 | self.assertTrue(seen_cmds[0][3]) | ||
| 921 | self.assertEqual(seen_cmds[1][0], ["/opt/bin/as", "--target-env", expected_target, "-", "-o", "out.spv"]) | ||
| 922 | self.assertTrue(seen_cmds[1][1]) | ||
| 923 | self.assertTrue(seen_cmds[1][3]) | ||
| 924 | self.assertEqual(seen_cmds[1][4], disasm) | ||
| 925 | |||
| 926 | def test_invalid_spirv_binary_words_and_missing_or_directory_paths(self): | ||
| 927 | fake_run, calls = _make_fake_spirv_tools() | ||
| 928 | valid_words = _build_mixed_bindless_spv_words() | ||
| 929 | |||
| 930 | bad_inputs = [ | ||
| 931 | ("empty_file", b""), | ||
| 932 | ("truncated_header_8B", struct.pack("<2I", SPIRV_MAGIC, SPIRV_VERSION_1_5)), | ||
| 933 | ("unaligned_21B", _pack_spv([], bound=1) + b"\x00"), | ||
| 934 | ("big_endian_magic", struct.pack(">5I", SPIRV_MAGIC, SPIRV_VERSION_1_5, 0, 2, 0)), | ||
| 935 | ("wrong_magic", struct.pack("<5I", 0xDEADBEEF, SPIRV_VERSION_1_5, 0, 2, 0)), | ||
| 936 | ("non_zero_schema", _pack_spv([], bound=1, schema=1)), | ||
| 937 | ("zero_bound", _pack_spv([], bound=0)), | ||
| 938 | ("zero_word_count_inst", _pack_spv([OP_CAPABILITY], bound=2)), | ||
| 939 | ("truncated_inst_bounds", _pack_spv(valid_words[:-1], bound=18)), | ||
| 940 | ] | ||
| 941 | with tempfile.TemporaryDirectory() as tmp: | ||
| 942 | for label, blob in bad_inputs: | ||
| 943 | with self.subTest(case=label): | ||
| 944 | calls.clear() | ||
| 945 | in_path = os.path.join(tmp, f"{label}.spv") | ||
| 946 | out_path = os.path.join(tmp, f"{label}.out.spv") | ||
| 947 | with open(in_path, "wb") as f: | ||
| 948 | f.write(blob) | ||
| 949 | with mock.patch.object(m.subprocess, "run", side_effect=fake_run): | ||
| 950 | with self.assertRaises(subprocess.CalledProcessError): | ||
| 951 | m.main(["spirv_metal_set0.py", in_path, out_path]) | ||
| 952 | self.assertEqual(calls, [["spirv-dis", in_path]]) | ||
| 953 | self.assertFalse(os.path.exists(out_path)) | ||
| 954 | |||
| 955 | # Missing input file and directory passed as input file both fail at spirv-dis. | ||
| 956 | missing_in = os.path.join(tmp, "does_not_exist.spv") | ||
| 957 | dir_in = os.path.join(tmp, "a_directory") | ||
| 958 | os.makedirs(dir_in) | ||
| 959 | for label, bad_path in (("missing_file", missing_in), ("directory_input", dir_in)): | ||
| 960 | with self.subTest(case=label): | ||
| 961 | calls.clear() | ||
| 962 | out_path = os.path.join(tmp, f"{label}.out.spv") | ||
| 963 | with mock.patch.object(m.subprocess, "run", side_effect=fake_run): | ||
| 964 | with self.assertRaises(subprocess.CalledProcessError): | ||
| 965 | m.main(["spirv_metal_set0.py", bad_path, out_path]) | ||
| 966 | self.assertEqual(calls, [["spirv-dis", bad_path]]) | ||
| 967 | self.assertFalse(os.path.exists(out_path)) | ||
| 968 | |||
| 969 | def test_spirv_as_failure_missing_executable_and_rewrite_abort(self): | ||
| 970 | with tempfile.TemporaryDirectory() as tmp: | ||
| 971 | in_path = os.path.join(tmp, "in.spv") | ||
| 972 | out_path = os.path.join(tmp, "out.spv") | ||
| 973 | with open(in_path, "wb") as f: | ||
| 974 | f.write(_pack_spv(_build_mixed_bindless_spv_words())) | ||
| 975 | |||
| 976 | # 1. Missing spirv-dis binary raises FileNotFoundError before calling spirv-as. | ||
| 977 | with mock.patch.object(m.subprocess, "run", side_effect=FileNotFoundError("no spirv-dis")) as run_mock: | ||
| 978 | with self.assertRaises(FileNotFoundError): | ||
| 979 | m.main(["spirv_metal_set0.py", in_path, out_path]) | ||
| 980 | self.assertEqual(run_mock.call_count, 1) | ||
| 981 | self.assertFalse(os.path.exists(out_path)) | ||
| 982 | |||
| 983 | # 2. rewrite() SystemExit aborts before spirv-as is invoked. | ||
| 984 | bad_spv = _pack_spv([ | ||
| 985 | *_encode_inst(OP_DECORATE, 2, DEC_DESCRIPTOR_SET, 0), | ||
| 986 | *_encode_inst(OP_DECORATE, 2, DEC_BINDING, 99), | ||
| 987 | ], bound=3) | ||
| 988 | with open(in_path, "wb") as f: | ||
| 989 | f.write(bad_spv) | ||
| 990 | fake_run, calls = _make_fake_spirv_tools() | ||
| 991 | with mock.patch.object(m.subprocess, "run", side_effect=fake_run): | ||
| 992 | with self.assertRaises(SystemExit) as ctx: | ||
| 993 | m.main(["spirv_metal_set0.py", in_path, out_path]) | ||
| 994 | self.assertIn("binding 99", str(ctx.exception)) | ||
| 995 | self.assertEqual(calls, [["spirv-dis", in_path]]) | ||
| 996 | self.assertFalse(os.path.exists(out_path)) | ||
| 997 | |||
| 998 | # 3. spirv-as failure raises CalledProcessError. | ||
| 999 | dis_ok = subprocess.CompletedProcess(["spirv-dis", in_path], 0, "; Version: 1.5\nOpCapability Shader\n", "") | ||
| 1000 | asm_fail = subprocess.CalledProcessError(1, ["spirv-as"], stderr="bad asm") | ||
| 1001 | with mock.patch.object(m.subprocess, "run", side_effect=[dis_ok, asm_fail]) as run_mock: | ||
| 1002 | with self.assertRaises(subprocess.CalledProcessError): | ||
| 1003 | m.main(["spirv_metal_set0.py", in_path, out_path]) | ||
| 1004 | self.assertEqual(run_mock.call_count, 2) | ||
| 1005 | |||
| 1006 | def test_main_guard_handles_stdout_reconfigure_errors_and_exit_codes(self): | ||
| 1007 | class _Stream(io.StringIO): | ||
| 1008 | def __init__(self, exc): | ||
| 1009 | super().__init__() | ||
| 1010 | self._exc = exc | ||
| 1011 | |||
| 1012 | def reconfigure(self, **_kwargs): | ||
| 1013 | raise self._exc | ||
| 1014 | |||
| 1015 | for exc in (AttributeError("no reconfigure"), ValueError("bad"), OSError("io")): | ||
| 1016 | with self.subTest(exc=type(exc).__name__): | ||
| 1017 | out_stream = _Stream(exc) | ||
| 1018 | err_stream = io.StringIO() | ||
| 1019 | with warnings.catch_warnings(): | ||
| 1020 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 1021 | with mock.patch.object(sys, "argv", ["spirv_metal_set0.py", "--print-layout"]), \ | ||
| 1022 | mock.patch.object(sys, "stdout", out_stream), \ | ||
| 1023 | mock.patch.object(sys, "stderr", err_stream): | ||
| 1024 | with self.assertRaises(SystemExit) as ctx: | ||
| 1025 | runpy.run_path(TOOL_PATH, run_name="__main__") | ||
| 1026 | self.assertEqual(ctx.exception.code, 0) | ||
| 1027 | self.assertEqual(err_stream.getvalue(), "") | ||
| 1028 | self.assertEqual(len(out_stream.getvalue().splitlines()), 26) | ||
| 1029 | |||
| 1030 | err_stream = io.StringIO() | ||
| 1031 | with warnings.catch_warnings(): | ||
| 1032 | warnings.simplefilter("ignore", ResourceWarning) | ||
| 1033 | with mock.patch.object(sys, "argv", ["spirv_metal_set0.py"]), \ | ||
| 1034 | mock.patch.object(sys, "stdout", io.StringIO()), \ | ||
| 1035 | mock.patch.object(sys, "stderr", err_stream): | ||
| 1036 | with self.assertRaises(SystemExit) as ctx: | ||
| 1037 | runpy.run_path(TOOL_PATH, run_name="__main__") | ||
| 1038 | self.assertEqual(ctx.exception.code, 2) | ||
| 1039 | self.assertIn("Usage: spirv_metal_set0.py in.spv out.spv", err_stream.getvalue()) | ||
| 1040 | |||
| 1041 | |||
| 1042 | if __name__ == "__main__": | ||
| 1043 | unittest.main() | ||
diff --git a/tests/test_story_index.py b/tests/test_story_index.py index d116637fe..97697e157 100644 --- a/tests/test_story_index.py +++ b/tests/test_story_index.py | |||
| @@ -240,8 +240,8 @@ class ArchiveTest(unittest.TestCase): | |||
| 240 | class _FailingWriter: | 240 | class _FailingWriter: |
| 241 | """A csv writer that fails once the header and first row have hit the staged file.""" | 241 | """A csv writer that fails once the header and first row have hit the staged file.""" |
| 242 | 242 | ||
| 243 | def __init__(self, fileobj): | 243 | def __init__(self, fileobj, **kwargs): |
| 244 | self._w = real_csv_writer(fileobj) | 244 | self._w = real_csv_writer(fileobj, **kwargs) |
| 245 | self._n = 0 | 245 | self._n = 0 |
| 246 | 246 | ||
| 247 | def writerow(self, row): | 247 | def writerow(self, row): |
diff --git a/tests/test_tex_export.py b/tests/test_tex_export.py index e639d0ed9..d42fae028 100644 --- a/tests/test_tex_export.py +++ b/tests/test_tex_export.py | |||
| @@ -469,3 +469,79 @@ def test_stale_export_entry_is_not_counted(eq, tmp_path, monkeypatch, capsys): | |||
| 469 | out, code, text = png_main(tmp_path, monkeypatch, capsys, [t], carve, "--png") | 469 | out, code, text = png_main(tmp_path, monkeypatch, capsys, [t], carve, "--png") |
| 470 | assert text.splitlines()[0].startswith("1 textures: {'error:FileNotFoundError': 1}") | 470 | assert text.splitlines()[0].startswith("1 textures: {'error:FileNotFoundError': 1}") |
| 471 | assert text.splitlines()[1] == "png: {}" | 471 | assert text.splitlines()[1] == "png: {}" |
| 472 | |||
| 473 | # ---- bad index / --out guards (#1607's class in main) ---- | ||
| 474 | |||
| 475 | def _argv(monkeypatch, index, carve, out, *extra): | ||
| 476 | monkeypatch.setattr(sys, "argv", ["tex_export.py", str(index), str(carve), str(out), *extra]) | ||
| 477 | |||
| 478 | |||
| 479 | def test_main_reports_a_non_list_index_as_one_error_line(tmp_path, monkeypatch, capsys): | ||
| 480 | index = tmp_path / "textures_index.json" | ||
| 481 | index.write_text('{"files": []}', encoding="utf-8") | ||
| 482 | out = tmp_path / "out" | ||
| 483 | _argv(monkeypatch, index, tmp_path, out) | ||
| 484 | assert T.main() == 2 | ||
| 485 | err = capsys.readouterr().err | ||
| 486 | assert err.startswith("ERROR: cannot read "), err | ||
| 487 | assert len(err.strip().splitlines()) == 1, err | ||
| 488 | assert not out.exists() | ||
| 489 | |||
| 490 | |||
| 491 | def test_main_reports_an_index_row_without_keys(tmp_path, monkeypatch, capsys): | ||
| 492 | index = tmp_path / "textures_index.json" | ||
| 493 | index.write_text('[{"gpu": 0}]', encoding="utf-8") | ||
| 494 | _argv(monkeypatch, index, tmp_path, tmp_path / "out") | ||
| 495 | assert T.main() == 2 | ||
| 496 | err = capsys.readouterr().err | ||
| 497 | assert "ERROR: cannot read " in err, err | ||
| 498 | assert "row has no 'archive'" in err, err | ||
| 499 | assert "Traceback" not in err | ||
| 500 | |||
| 501 | |||
| 502 | def test_main_rejects_an_out_that_is_a_file(tmp_path, monkeypatch, capsys): | ||
| 503 | index = tmp_path / "textures_index.json" | ||
| 504 | index.write_text("[]", encoding="utf-8") | ||
| 505 | out = tmp_path / "existing.txt" | ||
| 506 | out.write_text("x", encoding="utf-8") | ||
| 507 | _argv(monkeypatch, index, tmp_path, out) | ||
| 508 | assert T.main() == 2 | ||
| 509 | err = capsys.readouterr().err | ||
| 510 | assert "is a file, not a folder" in err, err | ||
| 511 | assert out.read_text(encoding="utf-8") == "x" | ||
| 512 | |||
| 513 | |||
| 514 | def test_main_reports_an_out_under_an_existing_file(tmp_path, monkeypatch, capsys): | ||
| 515 | index = tmp_path / "textures_index.json" | ||
| 516 | index.write_text("[]", encoding="utf-8") | ||
| 517 | blocker = tmp_path / "file.txt" | ||
| 518 | blocker.write_text("x", encoding="utf-8") | ||
| 519 | _argv(monkeypatch, index, tmp_path, blocker / "sub") | ||
| 520 | assert T.main() == 2 | ||
| 521 | err = capsys.readouterr().err | ||
| 522 | assert "ERROR: cannot create " in err, err | ||
| 523 | assert "Traceback" not in err | ||
| 524 | |||
| 525 | |||
| 526 | def test_main_reports_a_dangling_symlink_out(tmp_path, monkeypatch, capsys): | ||
| 527 | index = tmp_path / "textures_index.json" | ||
| 528 | index.write_text("[]", encoding="utf-8") | ||
| 529 | link = tmp_path / "dangling-out" | ||
| 530 | try: | ||
| 531 | os.symlink(str(tmp_path / "missing-target"), str(link)) | ||
| 532 | except (OSError, NotImplementedError): | ||
| 533 | pytest.skip("symlinks are not available") | ||
| 534 | _argv(monkeypatch, index, tmp_path, link) | ||
| 535 | assert T.main() == 2 | ||
| 536 | err = capsys.readouterr().err | ||
| 537 | assert "ERROR: cannot create " in err, err | ||
| 538 | assert "Traceback" not in err | ||
| 539 | |||
| 540 | |||
| 541 | def test_main_still_accepts_an_empty_list(tmp_path, monkeypatch, capsys): | ||
| 542 | index = tmp_path / "textures_index.json" | ||
| 543 | index.write_text("[]", encoding="utf-8") | ||
| 544 | out = tmp_path / "out" | ||
| 545 | _argv(monkeypatch, index, tmp_path, out) | ||
| 546 | assert T.main() in (None, 0) # main() has no explicit return; sys.exit(None) is exit 0 | ||
| 547 | assert (out / "export_log.json").is_file() \ No newline at end of file | ||
diff --git a/tests/test_text_tables.py b/tests/test_text_tables.py index 670b92df6..2714d2b90 100644 --- a/tests/test_text_tables.py +++ b/tests/test_text_tables.py | |||
| @@ -178,6 +178,62 @@ class TestCli(unittest.TestCase): | |||
| 178 | with open(outs["strings"], encoding="utf-8", newline="") as fh: | 178 | with open(outs["strings"], encoding="utf-8", newline="") as fh: |
| 179 | strings = list(csv.DictReader(fh)) | 179 | strings = list(csv.DictReader(fh)) |
| 180 | self.assertIn(("ZZ_MENU_TITLE", "das Menü"), {(s["label"], s["text"]) for s in strings}) | 180 | self.assertIn(("ZZ_MENU_TITLE", "das Menü"), {(s["label"], s["text"]) for s in strings}) |
| 181 | self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")], | ||
| 182 | "staging files must not be left behind") | ||
| 183 | |||
| 184 | def test_failed_later_write_leaves_earlier_reports_intact(self): | ||
| 185 | with tempfile.TemporaryDirectory() as tmp: | ||
| 186 | src = os.path.join(tmp, "src") | ||
| 187 | os.mkdir(src) | ||
| 188 | write(os.path.join(src, "conv.pso"), CONV) | ||
| 189 | dialogue = os.path.join(tmp, "dialogue.csv") | ||
| 190 | old = "OLD GOOD REPORT\n" | ||
| 191 | with open(dialogue, "w", encoding="utf-8") as fh: | ||
| 192 | fh.write(old) | ||
| 193 | tables = os.path.join(tmp, "tables.csv") | ||
| 194 | os.mkdir(tables) # a later output that cannot be written | ||
| 195 | with contextlib.redirect_stderr(io.StringIO()) as err: | ||
| 196 | self.assertEqual(T.main([src, "--dialogue", dialogue, "--tables", tables]), 2) | ||
| 197 | self.assertIn("cannot write", err.getvalue()) | ||
| 198 | with open(dialogue, encoding="utf-8") as fh: | ||
| 199 | self.assertEqual(fh.read(), old) | ||
| 200 | self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")]) | ||
| 201 | |||
| 202 | @unittest.skipUnless(os.name == "nt", "Windows denies os.replace on a file held open by a reader") | ||
| 203 | def test_reader_holding_a_later_report_keeps_all_reports(self): | ||
| 204 | with tempfile.TemporaryDirectory() as tmp: | ||
| 205 | src = os.path.join(tmp, "src") | ||
| 206 | os.mkdir(src) | ||
| 207 | write(os.path.join(src, "conv.pso"), CONV) | ||
| 208 | dialogue = os.path.join(tmp, "dialogue.csv") | ||
| 209 | tables = os.path.join(tmp, "tables.csv") | ||
| 210 | old_dialogue, old_tables = "OLD DIALOGUE\n", "OLD TABLES\n" | ||
| 211 | for path, text in ((dialogue, old_dialogue), (tables, old_tables)): | ||
| 212 | with open(path, "w", encoding="utf-8") as fh: | ||
| 213 | fh.write(text) | ||
| 214 | with open(tables, "rb"): # a reader keeps the second output open | ||
| 215 | with contextlib.redirect_stderr(io.StringIO()) as err: | ||
| 216 | self.assertEqual(T.main([src, "--dialogue", dialogue, "--tables", tables]), 2) | ||
| 217 | self.assertIn("cannot write", err.getvalue()) | ||
| 218 | with open(dialogue, encoding="utf-8") as fh: | ||
| 219 | self.assertEqual(fh.read(), old_dialogue) | ||
| 220 | with open(tables, encoding="utf-8") as fh: | ||
| 221 | self.assertEqual(fh.read(), old_tables) | ||
| 222 | self.assertFalse([f for f in os.listdir(tmp) if f.startswith(".text_tables-")], | ||
| 223 | "staging and backup files must not be left behind") | ||
| 224 | |||
| 225 | def test_two_outputs_naming_one_file_are_refused(self): | ||
| 226 | with tempfile.TemporaryDirectory() as tmp: | ||
| 227 | src = os.path.join(tmp, "src") | ||
| 228 | os.mkdir(src) | ||
| 229 | write(os.path.join(src, "conv.pso"), CONV) | ||
| 230 | out = os.path.join(tmp, "same.csv") | ||
| 231 | with contextlib.redirect_stderr(io.StringIO()) as err: | ||
| 232 | with self.assertRaises(SystemExit) as cm: | ||
| 233 | T.main([src, "--dialogue", out, "--tables", out]) | ||
| 234 | self.assertEqual(cm.exception.code, 2) | ||
| 235 | self.assertIn("distinct", err.getvalue()) | ||
| 236 | self.assertFalse(os.path.exists(out), "no report may be written before the check") | ||
| 181 | 237 | ||
| 182 | def test_missing_input(self): | 238 | def test_missing_input(self): |
| 183 | with contextlib.redirect_stderr(io.StringIO()): | 239 | with contextlib.redirect_stderr(io.StringIO()): |
diff --git a/tests/test_values.py b/tests/test_values.py index 012122ab3..7bfbe77e9 100644 --- a/tests/test_values.py +++ b/tests/test_values.py | |||
| @@ -87,6 +87,10 @@ CASES = { | |||
| 87 | "v_pack_b32_f16_neg_lo": ("v_pack_b32_f16 v3, neg(v1), v2", 0xAAAA3C00, 0xBBBB4000, 0, 0x4000BC00), | 87 | "v_pack_b32_f16_neg_lo": ("v_pack_b32_f16 v3, neg(v1), v2", 0xAAAA3C00, 0xBBBB4000, 0, 0x4000BC00), |
| 88 | "v_pack_b32_f16_neg_hi_sel": ("v_pack_b32_f16 v3, v1, neg(v2) op_sel:[0,1,0]", 0xAAAA3C00, 0x4000BBBB, 0, | 88 | "v_pack_b32_f16_neg_hi_sel": ("v_pack_b32_f16 v3, v1, neg(v2) op_sel:[0,1,0]", 0xAAAA3C00, 0x4000BBBB, 0, |
| 89 | 0xC0003C00), | 89 | 0xC0003C00), |
| 90 | # `abs` is the ISA's sign clear (|S|), applied before `neg`; it has no hardware run of this instruction yet. | ||
| 91 | "v_pack_b32_f16_abs_lo": ("v_pack_b32_f16 v3, abs(v1), v2", 0xAAAABC00, 0xBBBB4000, 0, 0x40003C00), | ||
| 92 | "v_pack_b32_f16_abs_snan": ("v_pack_b32_f16 v3, abs(v1), v2", 0xAAAAFC01, 0xBBBB4000, 0, 0x40007C01), | ||
| 93 | "v_pack_b32_f16_neg_abs": ("v_pack_b32_f16 v3, -abs(v1), v2", 0xAAAA3C00, 0xBBBB4000, 0, 0x4000BC00), | ||
| 90 | # 16-bit float add keeps the other half of the destination (GFX10 partial write; see docs/design.md). | 94 | # 16-bit float add keeps the other half of the destination (GFX10 partial write; see docs/design.md). |
| 91 | # These pin the translator's keep; they do not reproduce the AMD driver quirk in valu_fuzz f16 | 95 | # These pin the translator's keep; they do not reproduce the AMD driver quirk in valu_fuzz f16 |
| 92 | # seed 3 programme 38, where the same keep is lost on the GPU (driver 26.11.1, RX 9070). | 96 | # seed 3 programme 38, where the same keep is lost on the GPU (driver 26.11.1, RX 9070). |
diff --git a/tests/test_vk_subgroup_info.py b/tests/test_vk_subgroup_info.py index 45f90e0b9..d8ca4ed0f 100644 --- a/tests/test_vk_subgroup_info.py +++ b/tests/test_vk_subgroup_info.py | |||
| @@ -66,6 +66,8 @@ class FakeDevice: | |||
| 66 | ) | 66 | ) |
| 67 | fragment_shader_barycentric: bool = True | 67 | fragment_shader_barycentric: bool = True |
| 68 | driver_id: int = 1 # VK_DRIVER_ID_AMD_PROPRIETARY | 68 | driver_id: int = 1 # VK_DRIVER_ID_AMD_PROPRIETARY |
| 69 | vendor_id: int = 0 | ||
| 70 | device_id: int = 0 | ||
| 69 | 71 | ||
| 70 | 72 | ||
| 71 | class FakeVulkan: | 73 | class FakeVulkan: |
| @@ -159,6 +161,8 @@ class FakeVulkan: | |||
| 159 | base = addr + 16 | 161 | base = addr + 16 |
| 160 | ctypes.c_uint32.from_address(base + vk_info.PROPS_API_VERSION).value = dev.api_version | 162 | ctypes.c_uint32.from_address(base + vk_info.PROPS_API_VERSION).value = dev.api_version |
| 161 | ctypes.c_uint32.from_address(base + vk_info.PROPS_DEVICE_TYPE).value = dev.device_type | 163 | ctypes.c_uint32.from_address(base + vk_info.PROPS_DEVICE_TYPE).value = dev.device_type |
| 164 | ctypes.c_uint32.from_address(base + vk_info.PROPS_VENDOR_ID).value = dev.vendor_id | ||
| 165 | ctypes.c_uint32.from_address(base + vk_info.PROPS_DEVICE_ID).value = dev.device_id | ||
| 162 | raw_name = dev.name.encode("utf-8") if isinstance(dev.name, str) else dev.name | 166 | raw_name = dev.name.encode("utf-8") if isinstance(dev.name, str) else dev.name |
| 163 | name_bytes = raw_name[:256].ljust(256, b"\x00") | 167 | name_bytes = raw_name[:256].ljust(256, b"\x00") |
| 164 | ctypes.memmove(base + vk_info.PROPS_DEVICE_NAME, name_bytes, 256) | 168 | ctypes.memmove(base + vk_info.PROPS_DEVICE_NAME, name_bytes, 256) |
| @@ -521,6 +525,67 @@ class QueryTest(unittest.TestCase): | |||
| 521 | self.assertEqual(res["device"], expected_name) | 525 | self.assertEqual(res["device"], expected_name) |
| 522 | self.assertEqual(vk.destroyed_instances, [FakeVulkan.INSTANCE_HANDLE]) | 526 | self.assertEqual(vk.destroyed_instances, [FakeVulkan.INSTANCE_HANDLE]) |
| 523 | 527 | ||
| 528 | def test_leonida_vk_device_filters_case_insensitively_and_fails_on_no_match(self): | ||
| 529 | igpu = FakeDevice( | ||
| 530 | name="AMD Radeon(TM) 780M Graphics", | ||
| 531 | device_type=1, | ||
| 532 | subgroup_size=64, | ||
| 533 | min_subgroup_size=32, | ||
| 534 | max_subgroup_size=64, | ||
| 535 | ) | ||
| 536 | dgpu = FakeDevice( | ||
| 537 | name="NVIDIA GeForce RTX 4070", | ||
| 538 | device_type=vk_info.VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU, | ||
| 539 | subgroup_size=32, | ||
| 540 | min_subgroup_size=32, | ||
| 541 | max_subgroup_size=32, | ||
| 542 | ) | ||
| 543 | other_dgpu = FakeDevice( | ||
| 544 | name="AMD Radeon RX 7900 XTX", | ||
| 545 | device_type=vk_info.VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU, | ||
| 546 | subgroup_size=64, | ||
| 547 | min_subgroup_size=32, | ||
| 548 | max_subgroup_size=64, | ||
| 549 | ) | ||
| 550 | old_match = FakeDevice( | ||
| 551 | name="Legacy Radeon 1.2", | ||
| 552 | api_version=(1 << 22) | (2 << 12), | ||
| 553 | ) | ||
| 554 | |||
| 555 | # Unset or empty selects the last discrete GPU as usual. | ||
| 556 | for empty in ("",): | ||
| 557 | with mock.patch.dict(vk_info.os.environ, {"LEONIDA_VK_DEVICE": empty}): | ||
| 558 | res, _ = self._run_query(igpu, dgpu) | ||
| 559 | self.assertEqual(res["device"], "NVIDIA GeForce RTX 4070") | ||
| 560 | self.assertFalse(res["native64"]) | ||
| 561 | |||
| 562 | # Case-insensitive substring can select the integrated GPU over a later discrete GPU. | ||
| 563 | for filt in ("780m", "RADEON(tm) 780M", "amd radeon"): | ||
| 564 | with self.subTest(filter=filt), mock.patch.dict(vk_info.os.environ, {"LEONIDA_VK_DEVICE": filt}): | ||
| 565 | res, vk = self._run_query(igpu, dgpu) | ||
| 566 | self.assertEqual(res["device"], "AMD Radeon(TM) 780M Graphics") | ||
| 567 | self.assertTrue(res["native64"]) | ||
| 568 | # Non-matching discrete GPU was skipped before feature/queue queries. | ||
| 569 | self.assertEqual(vk.features_calls, [vk._device_handles[0]]) | ||
| 570 | self.assertEqual(vk.queue_calls, [vk._device_handles[0], vk._device_handles[0]]) | ||
| 571 | |||
| 572 | # Among multiple matching devices, the runtime's discrete/last-discrete rule still applies. | ||
| 573 | with mock.patch.dict(vk_info.os.environ, {"LEONIDA_VK_DEVICE": "radeon"}): | ||
| 574 | res, _ = self._run_query(igpu, dgpu, other_dgpu) | ||
| 575 | self.assertEqual(res["device"], "AMD Radeon RX 7900 XTX") | ||
| 576 | with mock.patch.dict(vk_info.os.environ, {"LEONIDA_VK_DEVICE": "geforce"}): | ||
| 577 | res, _ = self._run_query(igpu, dgpu, other_dgpu) | ||
| 578 | self.assertEqual(res["device"], "NVIDIA GeForce RTX 4070") | ||
| 579 | |||
| 580 | # A filter that matches no device (or only an unsuitable device) raises RuntimeError and destroys the instance. | ||
| 581 | for filt, devs in (("nomatch", (igpu, dgpu)), ("legacy", (old_match, dgpu))): | ||
| 582 | with self.subTest(no_match=filt), mock.patch.dict(vk_info.os.environ, {"LEONIDA_VK_DEVICE": filt}): | ||
| 583 | vk = FakeVulkan(devices=devs) | ||
| 584 | with mock.patch.object(vk_info, "load_vulkan", return_value=vk): | ||
| 585 | with self.assertRaisesRegex(RuntimeError, rf"LEONIDA_VK_DEVICE={filt}"): | ||
| 586 | vk_info.query() | ||
| 587 | self.assertEqual(vk.destroyed_instances, [FakeVulkan.INSTANCE_HANDLE]) | ||
| 588 | |||
| 524 | def test_native64_conditions_and_boundaries(self): | 589 | def test_native64_conditions_and_boundaries(self): |
| 525 | both = vk_info.VK_SHADER_STAGE_COMPUTE_BIT | vk_info.VK_SHADER_STAGE_MESH_BIT_EXT | 590 | both = vk_info.VK_SHADER_STAGE_COMPUTE_BIT | vk_info.VK_SHADER_STAGE_MESH_BIT_EXT |
| 526 | cases = [ | 591 | cases = [ |
| @@ -559,6 +624,10 @@ class QueryTest(unittest.TestCase): | |||
| 559 | "mesh_in_supported_stages": True, | 624 | "mesh_in_supported_stages": True, |
| 560 | "native64": want_native64, | 625 | "native64": want_native64, |
| 561 | "per_vertex_inputs": True, | 626 | "per_vertex_inputs": True, |
| 627 | "vendor_id": 0, | ||
| 628 | "device_id": 0, | ||
| 629 | "driver_id": 1, | ||
| 630 | "rdna2_amd_windows": False, | ||
| 562 | }) | 631 | }) |
| 563 | 632 | ||
| 564 | def test_per_vertex_inputs(self): | 633 | def test_per_vertex_inputs(self): |
| @@ -569,6 +638,33 @@ class QueryTest(unittest.TestCase): | |||
| 569 | res, _vk = self._run_query(FakeDevice(fragment_shader_barycentric=bary, driver_id=driver)) | 638 | res, _vk = self._run_query(FakeDevice(fragment_shader_barycentric=bary, driver_id=driver)) |
| 570 | self.assertIs(res["per_vertex_inputs"], want) | 639 | self.assertIs(res["per_vertex_inputs"], want) |
| 571 | 640 | ||
| 641 | def test_rdna2_amd_windows(self): | ||
| 642 | """#857: RDNA2 by PCI device ID, and only under AMD's proprietary driver (RADV takes the same modules).""" | ||
| 643 | amd, radv = vk_info.VK_DRIVER_ID_AMD_PROPRIETARY, 3 | ||
| 644 | cases = (("rx6700", 0x1002, 0x73DF, amd, True), ("rx6800", 0x1002, 0x73BF, amd, True), | ||
| 645 | ("navi24", 0x1002, 0x743F, amd, True), ("granite_ridge_igpu", 0x1002, 0x13C0, amd, True), | ||
| 646 | ("raphael_igpu", 0x1002, 0x164E, amd, True), ("rx6700_radv", 0x1002, 0x73DF, radv, False), | ||
| 647 | ("rdna3_7900xtx", 0x1002, 0x744C, amd, False), ("rdna4_9070xt", 0x1002, 0x7550, amd, False), | ||
| 648 | ("rdna3_780m", 0x1002, 0x15BF, amd, False), ("nvidia_same_id", 0x10DE, 0x73DF, 4, False)) | ||
| 649 | for label, vendor, device, driver, want in cases: | ||
| 650 | with self.subTest(case=label): | ||
| 651 | self.assertIs(vk_info.rdna2_amd_windows(vendor, device, driver), want) | ||
| 652 | res, _vk = self._run_query(FakeDevice(vendor_id=vendor, device_id=device, driver_id=driver)) | ||
| 653 | self.assertEqual((res["vendor_id"], res["device_id"], res["driver_id"]), (vendor, device, driver)) | ||
| 654 | self.assertIs(res["rdna2_amd_windows"], want) | ||
| 655 | |||
| 656 | def test_rdna2_answer_is_for_the_runtime_gpu(self): | ||
| 657 | """An Intel iGPU next to an RX 6700: the runtime takes the discrete card, and so does the answer.""" | ||
| 658 | intel = FakeDevice(name="Intel iGPU", device_type=1, vendor_id=0x8086, device_id=0xA780, driver_id=5, | ||
| 659 | min_subgroup_size=8, max_subgroup_size=32) | ||
| 660 | rx = FakeDevice(name="AMD Radeon RX 6700", vendor_id=0x1002, device_id=0x73DF) | ||
| 661 | for devs in ((intel, rx), (rx, intel)): | ||
| 662 | with self.subTest(order=[d.name for d in devs]): | ||
| 663 | res, _vk = self._run_query(*devs) | ||
| 664 | self.assertEqual(res["device"], "AMD Radeon RX 6700") | ||
| 665 | self.assertTrue(res["rdna2_amd_windows"]) | ||
| 666 | self.assertTrue(res["native64"]) | ||
| 667 | |||
| 572 | def test_native64_uses_default_size_without_required_mesh_stage(self): | 668 | def test_native64_uses_default_size_without_required_mesh_stage(self): |
| 573 | dev = FakeDevice( | 669 | dev = FakeDevice( |
| 574 | subgroup_size=64, | 670 | subgroup_size=64, |
diff --git a/tests/test_world_index.py b/tests/test_world_index.py index a5e873857..93ca58e68 100644 --- a/tests/test_world_index.py +++ b/tests/test_world_index.py | |||
| @@ -4,6 +4,7 @@ | |||
| 4 | """ | 4 | """ |
| 5 | import contextlib | 5 | import contextlib |
| 6 | import csv | 6 | import csv |
| 7 | import errno | ||
| 7 | import importlib.util | 8 | import importlib.util |
| 8 | import io | 9 | import io |
| 9 | import json | 10 | import json |
| @@ -13,6 +14,7 @@ import sys | |||
| 13 | import tempfile | 14 | import tempfile |
| 14 | import unittest | 15 | import unittest |
| 15 | import zlib | 16 | import zlib |
| 17 | from unittest import mock | ||
| 16 | 18 | ||
| 17 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | 19 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 18 | 20 | ||
| @@ -351,9 +353,20 @@ class WorldIndexTest(unittest.TestCase): | |||
| 351 | self.assert_report_collision([source, "--out", upper, "--csv", lower], | 353 | self.assert_report_collision([source, "--out", upper, "--csv", lower], |
| 352 | "--out and --csv must use different paths") | 354 | "--out and --csv must use different paths") |
| 353 | self.assertEqual(os.listdir(folder), []) | 355 | self.assertEqual(os.listdir(folder), []) |
| 354 | accent = os.path.join(folder, "café.json") # composed é | 356 | # Case folding and Unicode normalization are separate filesystem behaviors. |
| 355 | self.assert_report_collision([source, "--out", accent, "--csv", os.path.join(folder, "CAFÉ.json")], | 357 | composed = os.path.join(folder, "caf\u00e9.json") |
| 356 | "--out and --csv must use different paths") | 358 | decomposed = os.path.join(folder, "cafe\u0301.json") |
| 359 | with open(composed, "wb"): | ||
| 360 | pass | ||
| 361 | aliases = os.path.exists(decomposed) | ||
| 362 | os.unlink(composed) | ||
| 363 | reports = [source, "--out", composed, "--csv", decomposed] | ||
| 364 | if aliases: | ||
| 365 | self.assert_report_collision(reports, "--out and --csv must use different paths") | ||
| 366 | self.assertEqual(os.listdir(folder), []) | ||
| 367 | else: | ||
| 368 | self.assertEqual(WI.main(reports), 0) | ||
| 369 | self.assertFalse(os.path.samefile(composed, decomposed)) | ||
| 357 | else: | 370 | else: |
| 358 | self.assertEqual(WI.main([source, "--out", upper, "--csv", lower]), 0) | 371 | self.assertEqual(WI.main([source, "--out", upper, "--csv", lower]), 0) |
| 359 | with open(upper, encoding="utf-8") as f: | 372 | with open(upper, encoding="utf-8") as f: |
| @@ -436,6 +449,34 @@ class WorldIndexTest(unittest.TestCase): | |||
| 436 | with open(entities, "rb") as f: | 449 | with open(entities, "rb") as f: |
| 437 | self.assertEqual(f.read(), previous) | 450 | self.assertEqual(f.read(), previous) |
| 438 | 451 | ||
| 452 | def test_failed_directory_walk_keeps_existing_reports(self): | ||
| 453 | carve = os.path.join(self.dir, "carve") | ||
| 454 | blocked = os.path.join(carve, "unreadable") | ||
| 455 | os.makedirs(blocked) | ||
| 456 | with open(os.path.join(carve, "resource.bin"), "wb") as f: | ||
| 457 | f.write(make_resource()) | ||
| 458 | summary = os.path.join(self.dir, "summary.json") | ||
| 459 | entities = os.path.join(self.dir, "entities.jsonl") | ||
| 460 | previous = b'{"previous":true}\n' | ||
| 461 | for report in (summary, entities): | ||
| 462 | with open(report, "wb") as f: | ||
| 463 | f.write(previous) | ||
| 464 | |||
| 465 | scandir = os.scandir | ||
| 466 | |||
| 467 | def scan(path): | ||
| 468 | if path == blocked: | ||
| 469 | raise PermissionError(errno.EACCES, "permission denied", blocked) | ||
| 470 | return scandir(path) | ||
| 471 | |||
| 472 | err = io.StringIO() | ||
| 473 | with mock.patch.object(WI.os, "scandir", side_effect=scan), contextlib.redirect_stderr(err): | ||
| 474 | self.assertEqual(WI.main([carve, "--out", summary, "--entities-out", entities]), 2) | ||
| 475 | self.assertIn("unreadable", err.getvalue()) | ||
| 476 | for report in (summary, entities): | ||
| 477 | with open(report, "rb") as f: | ||
| 478 | self.assertEqual(f.read(), previous) | ||
| 479 | |||
| 439 | def test_summary_write_failure_keeps_existing_placement_report(self): | 480 | def test_summary_write_failure_keeps_existing_placement_report(self): |
| 440 | source = os.path.join(self.dir, "resource.bin") | 481 | source = os.path.join(self.dir, "resource.bin") |
| 441 | with open(source, "wb") as f: | 482 | with open(source, "wb") as f: |
| @@ -568,6 +609,22 @@ class WorldIndexTest(unittest.TestCase): | |||
| 568 | rows, _ = WI.scan_path(self.carve([blob[:0x150], blob[0x150:]], gap=0x10)) | 609 | rows, _ = WI.scan_path(self.carve([blob[:0x150], blob[0x150:]], gap=0x10)) |
| 569 | self.assertEqual(rows, []) | 610 | self.assertEqual(rows, []) |
| 570 | 611 | ||
| 612 | def test_carved_file_inflate_cap_matches_directory_scan(self): | ||
| 613 | resource = make_resource() | ||
| 614 | path = os.path.join(self.dir, "sample.bin") | ||
| 615 | with open(path, "wb") as f: | ||
| 616 | f.write(resource) | ||
| 617 | |||
| 618 | for source in (path, self.dir): | ||
| 619 | for cap, expected in ((len(resource) - 1, 0), (len(resource), 1)): | ||
| 620 | with self.subTest(source=source, cap=cap): | ||
| 621 | entities = [] | ||
| 622 | rows, stats = WI.scan_path(source, max_inflate=cap, collect=entities) | ||
| 623 | self.assertEqual(len(rows), expected) | ||
| 624 | self.assertEqual(len(entities), expected) | ||
| 625 | self.assertEqual(stats["files"], expected) | ||
| 626 | self.assertEqual(stats["scanned_bytes"], expected * len(resource)) | ||
| 627 | |||
| 571 | def test_directory_inflate_cap_does_not_exclude_large_archives(self): | 628 | def test_directory_inflate_cap_does_not_exclude_large_archives(self): |
| 572 | resource = make_resource() | 629 | resource = make_resource() |
| 573 | cap = len(resource) | 630 | cap = len(resource) |