Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions docs/experiments/native-mesh-vector-alu.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,25 @@ and exports the bitcast result through POS0.x.
`python -B tests/native_direct_mesh_check.py <compile_dxil.exe> <dxc dir>`
or `ctest --preset release --no-tests=error -R '^native_direct'`.


## Mesh median and base-2 exponentiation

The mesh vector ALU admits VOP3 `v_med3_f32` and VOP1 or VOP3
`v_exp_f32` through the shared direct float ALU. The median path tests
all three inputs for NaN and selects the folded FMin result in that case.
When all operands are numeric it uses the median expression. The
exponent uses DXIL Exp (opcode 21), which evaluates a base-2 power. Both
operations accept source abs and neg in their valid encoded positions.

Clamp, omod, op_sel, SDWA and DPP stay refused. The wide exponent also
refuses nonzero unused source fields and modifiers on unused operands.
The fixture evaluates the DXIL feeding the position export. It covers a
NaN in each median operand, multiple NaNs, infinities, and positive and
negative exponents.

```powershell
ctest --preset pr --no-tests=error -R '^native_mesh_med3_exp_ir$'
```

The [mesh census](https://github.com/R0Y00/Xbox2Windows/issues/3703#issuecomment-7368154618)
reports 67 first refusals at the median and 23 at the exponent.
8 changes: 5 additions & 3 deletions src/gfx1013_direct_mesh.inl
Original file line number Diff line number Diff line change
Expand Up @@ -3204,12 +3204,14 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout
}
alu.write(i.dst,result);
if (!full_exec) partial_writes.insert(i.dst);
} else if ((i.name=="v_min_f32" || i.name=="v_bfi_b32") &&
} else if ((i.name=="v_min_f32" || i.name=="v_bfi_b32" || i.name=="v_med3_f32" || i.name=="v_exp_f32") &&
(i.dpp_control || i.subword || (i.wide && (i.a&0x7800)) || i.clamp || i.scale)) {
// Only the plain e32/e64 forms: DPP, SDWA, op_sel, clamp and omod stay refused.
// v_min_f32 abs/neg are sign-bit operations in the shared float ALU; v_bfi_b32
// takes no float modifiers there.
refuse(pc,"unsupported mesh "+iname+" operand modifiers");
} else if (i.name=="v_exp_f32" && i.wide && (i.src[1] || i.src[2] || ((i.abs|i.neg)&6))) {
refuse(pc,"unsupported mesh v_exp_f32 unused operands");
} else if (vector_exec && (i.name=="v_trunc_f32" || i.name=="v_floor_f32" ||
i.name=="v_ceil_f32" || i.name=="v_rndne_f32" || i.name=="v_fract_f32" ||
i.name=="v_cvt_u32_f32" || i.name=="v_cvt_i32_f32" || i.name=="v_mul_u32_u24" || i.name=="v_lshl_or_b32" ||
Expand All @@ -3219,9 +3221,9 @@ NativeComputeShader lower_mesh(const string &code, const MeshStageLayout &layout
i.name=="v_subrev_f32" || i.name=="v_fmac_f32" || i.name=="v_fmamk_f32" || i.name=="v_fmaak_f32" ||
i.name=="v_rsq_f32" || i.name=="v_rcp_f32" || i.name=="v_rcp_iflag_f32" || i.name=="v_sqrt_f32" ||
i.name=="v_ashrrev_i32" || i.name=="v_fma_mixlo_f16" || i.name=="v_fma_mixhi_f16" || i.name=="v_fma_mix_f32" || i.name=="v_pack_b32_f16" ||
i.name=="v_log_f32" || i.name=="v_sin_f32" || i.name=="v_cos_f32" ||
i.name=="v_exp_f32" || i.name=="v_log_f32" || i.name=="v_sin_f32" || i.name=="v_cos_f32" ||
i.name.substr(0,15)=="v_cvt_f32_ubyte" || i.name=="v_min_u32" || i.name=="v_max_f32" ||
i.name=="v_min_f32" || i.name=="v_bfi_b32" ||
i.name=="v_min_f32" || i.name=="v_med3_f32" || i.name=="v_bfi_b32" ||
i.name=="v_mad_u32_u24" || i.name=="v_add3_u32" || i.name=="v_xad_u32" || i.name=="v_bfe_u32" || i.name=="v_mov_b32" || i.name=="v_add_nc_u32" || i.name=="v_sub_nc_u32" || i.name=="v_subrev_nc_u32" || i.name=="v_add_co_ci_u32" || i.name=="v_lshlrev_b32" ||
i.name=="v_sub_co_u32" || i.name=="v_subrev_co_u32" ||
i.name=="v_lshrrev_b32" || i.name=="v_or_b32" || i.name=="v_or3_b32" || i.name=="v_and_or_b32" ||
Expand Down
6 changes: 6 additions & 0 deletions tests/cmake/native_mesh_med3_exp.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
if(EXISTS "${INTAKE_PYTHON}" AND TARGET compile_dxil)
add_test(NAME native_mesh_med3_exp_ir
COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/native_mesh_med3_exp_check.py"
"$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}")
set_tests_properties(native_mesh_med3_exp_ir PROPERTIES TIMEOUT 60)
endif()
130 changes: 130 additions & 0 deletions tests/native_mesh_med3_exp_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
"""Evaluate the DXIL feeding POS0.x for mesh median and base-2 exponentiation."""
from functools import lru_cache
import math
from pathlib import Path
import re
import struct
import subprocess
import sys
import tempfile

from native_direct_mesh_check import TRIANGLE_LAYOUT, triangle
from native_mesh_small_alu_pack_check import raw_x, vop3


VALUE = r'%[\w.]+'
EXP = 0x25
MED3 = 0x157


def exp_e32(src):
return 0x7E000000 | (1 << 17) | (EXP << 9) | src


def float_word(value):
return struct.unpack('<I', struct.pack('<f', value))[0]


def word_float(word):
return struct.unpack('<f', struct.pack('<I', word))[0]


def export_word(ir):
"""Interpret the small, constant-input instruction graph reaching POS0.x."""
defs = dict(re.findall(rf'^\s*({VALUE}) = ([^;\n]+)', ir, re.M))
out = re.search(r'call void @dx\.op\.storeVertexOutput\.f32\(i32 171, i32 \d+, '
rf'i32 0, i8 0, float ({VALUE}),', ir)
assert out, ir

@lru_cache(None)
def evaluate(token):
if not token.startswith('%'):
return int(token) & 0xFFFFFFFF
expr = defs[token].strip()
if match := re.fullmatch(r'bitcast (?:i32|float) (\S+) to (?:i32|float)', expr):
return evaluate(match[1])
if match := re.fullmatch(r'(and|xor) i32 (\S+), (\S+)', expr):
a, b = evaluate(match[2]), evaluate(match[3])
return a & b if match[1] == 'and' else a ^ b
if match := re.fullmatch(r'or i1 (\S+), (\S+)', expr):
return evaluate(match[1]) or evaluate(match[2])
if match := re.fullmatch(r'fcmp uno float (\S+), (\S+)', expr):
return any(math.isnan(word_float(evaluate(src))) for src in match.groups())
if match := re.fullmatch(r'select i1 (\S+), float (\S+), float (\S+)', expr):
return evaluate(match[2] if evaluate(match[1]) else match[3])
if match := re.fullmatch(r'call float @dx\.op\.binary\.f32\(i32 (35|36), float (\S+), float (\S+)\)', expr):
a, b = evaluate(match[2]), evaluate(match[3])
av, bv = word_float(a), word_float(b)
if math.isnan(av):
return b
if math.isnan(bv):
return a
key = lambda word: (word_float(word), word != 0x80000000)
return (max if match[1] == '35' else min)(a, b, key=key)
if match := re.fullmatch(r'call float @dx\.op\.unary\.f32\(i32 21, float (\S+)\)', expr):
return float_word(2.0 ** word_float(evaluate(match[1])))
raise AssertionError((token, expr, ir))

return evaluate(out[1])


def main():
compiler, sdk = map(Path, sys.argv[1:])
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
raw = root / 'fixture.m57'
raw.with_suffix('.mslayout').write_text(TRIANGLE_LAYOUT, encoding='ascii')

def run(name, body, refusal=None):
words = raw_x(triangle(), body)
raw.write_bytes(struct.pack(f'<{len(words)}I', *words))
out = root / f'{name}.dxil'
result = subprocess.run([compiler, sdk, root / 'cache', 'gfx1013-raw-ms', raw, out],
capture_output=True, text=True)
if refusal:
assert result.returncode and refusal in result.stderr and not out.exists(), (name, result.stderr)
return None
assert result.returncode == 0, (name, result.stderr)
ir = subprocess.check_output([sdk / 'dxc.exe', '-dumpbin', out], text=True)
return export_word(ir)

nan = 0x7FC00001
# Inline sources are -1, 2 and 4. Literal NaN can occupy any one
# position or be shared by multiple operands of the same instruction.
for name, args, literal, want in (
('median', (246, 243, 244), [], 2.0),
('nan-src0', (255, 246, 244), [nan], 2.0),
('nan-src1', (244, 255, 243), [nan], -1.0),
('nan-src2', (246, 243, 255), [nan], -1.0),
('two-nans', (255, 246, 255), [nan], 4.0),
('three-nans', (255, 255, 255), [nan], math.nan),
('infinity', (255, 243, 244), [float_word(math.inf)], 2.0),
):
got = run(name, vop3(MED3, 1, *args) + literal)
assert (math.isnan(word_float(got)) if math.isnan(want) else got == float_word(want)), (name, got, want)
assert run('median-abs-neg', vop3(MED3, 1, 243, 244, 246, absm=1, neg=2)) == float_word(1.0)

for name, body, want in (
('exp-vop1', [exp_e32(244)], 4.0),
('exp-vop3', vop3(0x180 + EXP, 1, 245, 0), 0.25),
('exp-vop3-abs-neg', vop3(0x180 + EXP, 1, 245, 0, absm=1, neg=1), 0.25),
('exp-negative-zero', [exp_e32(255), 0x80000000], 1.0),
('exp-negative-infinity', [exp_e32(255), float_word(-math.inf)], 0.0),
('exp-positive-infinity', [exp_e32(255), float_word(math.inf)], math.inf),
):
assert run(name, body) == float_word(want), name

for opcode, name, sources in ((MED3, 'v_med3_f32', (242, 244, 246)),
(0x180 + EXP, 'v_exp_f32', (242, 0))):
for mod in ('clamp', 'omod', 'opsel'):
run(f'{name}-{mod}', vop3(opcode, 1, *sources, **{mod: 1}),
f'unsupported mesh {name} operand modifiers')
run('exp-unused-src', vop3(0x180 + EXP, 1, 242, 244), 'unsupported mesh v_exp_f32 unused operands')
run('exp-unused-neg', vop3(0x180 + EXP, 1, 242, 0, neg=2), 'unsupported mesh v_exp_f32 unused operands')
run('median-undefined', vop3(MED3, 1, 300, 244, 246), 'unproven mesh entry register 300')
run('exp-undefined', [exp_e32(300)], 'unproven mesh entry register 300')
print('Mesh median and exponent validated DXIL for 14 cases and 10 refusal controls')


if __name__ == '__main__':
main()
Loading