Skip to content
Merged
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
1 change: 1 addition & 0 deletions .github/workflows/windows.yml
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,7 @@ jobs:
tests/startup_gfx2hlsl_sad_check.py \
tests/startup_gfx2hlsl_sad_hi_msad_check.py \
tests/startup_gfx2hlsl_scalar_brev_fold_check.py \
tests/startup_gfx2hlsl_const_copy_join_check.py \
tests/startup_gfx2hlsl_s_bit_scan_check.py \
tests/startup_gfx2hlsl_pack_b32_f16_check.py \
tests/startup_inline_sampler_check.py \
Expand Down
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,7 @@ python3 -m venv out/pe-env
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_f32_nan_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_sopk_signext_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_scalar_brev_fold_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_const_copy_join_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_pack_b32_f16_check.py
./out/pe-env/bin/python -B tests/run_checks_parallel_check.py
./out/pe-env/bin/python -B tests/startup_gfx2hlsl_handler_arity_check.py
Expand Down
3 changes: 3 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3494,6 +3494,9 @@ if(EXISTS "${INTAKE_PYTHON}")
# s_brev_b32 of a known constant folds to a known word (a sampler built from it is a constant descriptor).
add_test(NAME startup_gfx2hlsl_scalar_brev_fold COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_scalar_brev_fold_check.py")
# A copy of a plain constant scalar register still assigns at run time and drops its constant at a join.
add_test(NAME startup_gfx2hlsl_const_copy_join COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_const_copy_join_check.py")
# v_pack_b32_f16 with op_sel and the neg/abs source modifiers, evaluated against a bit reference.
add_test(NAME startup_gfx2hlsl_pack_b32_f16 COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_pack_b32_f16_check.py")
Expand Down
9 changes: 6 additions & 3 deletions docs/startup-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,9 +208,12 @@ The translation is refused when:
- either header has another size;
- the code reads an attribute the table does not list.

The shader cache revision is `x2w-startup-shader-18`. Revision 18 preserves the sign of zero in
floating-point min, max, min3, max3 and med3. The matching compute (`x2w-startup-shader-18cs`) and fixed
slot 57 mesh (`x2w-startup-mesh-57-3`) keys advance because those stages use the shared lowering.
The shader cache revision is `x2w-startup-shader-19`. Revision 19 folds `s_mov_b32` from a scalar register that
holds a plain constant, so later reads of the copy use the constant word. The matching compute
(`x2w-startup-shader-19cs`) key advances because that stage uses the shared lowering. The fixed slot 57 mesh
(`x2w-startup-mesh-57-3`) key stays, because that shader is not translated from guest code.
Revisions before 19 read a register copied from a constant as a run-time value.
Revision 18 preserves the sign of zero in floating-point min, max, min3, max3 and med3.
Revisions before 17 lower `v_med3_f32` through a branchless median, which returns the smaller of the
other two operands when a source is NaN.
Revisions before 16 lower `v_fract_f32` through a bare `frac` instead of the clamped `fract32` helper.
Expand Down
4 changes: 2 additions & 2 deletions src/startup_stubs/d3d12_draw.inl
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ Translation* cached_translation(const void* a, std::size_t a_bytes, const void*
{
// Keep pre-fix desktop bytecode and manifests out of this ABI's cache.
// tools/startup/gfx2hlsl.py hashes the same bytes, without a trailing NUL.
constexpr char revision[] = "x2w-startup-shader-18";
constexpr char revision[] = "x2w-startup-shader-19";
const u64 seed = fnv_bytes(revision, sizeof(revision) - 1);
u64 key = fnv_bytes(root_blob.data(), root_blob.size(), fnv_bytes(b, b_bytes, fnv_bytes(a, a_bytes, seed)));
// A stream's input layout (stream_input_layout) feeds the vertex fetch, so it is part of the key.
Expand Down Expand Up @@ -474,7 +474,7 @@ u64 publish_compute_request(const void* desc)
std::vector<unsigned char> fields(sizeof(words));
words[0] = words[1] = words[3] = words[5] = words[7] = words[9] = words[10] = 0;
std::memcpy(fields.data(), words, sizeof(words));
constexpr char compute_revision[] = "x2w-startup-shader-18cs"; // tools/startup/gfx2hlsl.py compute_key
constexpr char compute_revision[] = "x2w-startup-shader-19cs"; // tools/startup/gfx2hlsl.py compute_key
u64 key = fnv_bytes(compute_revision, sizeof(compute_revision) - 1);
const std::vector<unsigned char>* order[] = {&code, &data, &root_blob, &fields, &state_a, &state_b};
for (const auto* part : order) key = fnv_part(*part, key);
Expand Down
4 changes: 2 additions & 2 deletions tests/startup_compute_request_offline_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@
DESC = struct.pack('<12Q', 0, 0, 24, 0, 20, 0, len(CODE), 0, len(DATA), 0, 0, 11)
STATE_A = struct.pack('<3Q', 1, 0x2c, 0xfff0000000000003)
STATE_B = struct.pack('<5I', 0x1234abcd, 0xffff0000, 0, 0, 0)
KEY = 0x375fa7c3f8f4a3dd # framed key at revision 18cs
KEY = 0x63ac0aa21c46da1c # framed key at revision 19cs


def framed_key():
h = 1469598103934665603
for b in b'x2w-startup-shader-18cs':
for b in b'x2w-startup-shader-19cs':
h = ((h ^ b) * 1099511628211) & 0xffffffffffffffff
for part in (CODE, DATA, ROOT, DESC, STATE_A, STATE_B):
for b in struct.pack('<Q', len(part)) + part:
Expand Down
4 changes: 2 additions & 2 deletions tests/startup_gfx2hlsl_buffer_store_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,8 +212,8 @@ def main():
'%s %s' % (result, fail_reason(name)))

# 8. The cache revision moved, so a translation from before the store lowering is never loaded.
check('cache key uses revision 18', G.pipeline_key(b'a', b'b', ROOT) ==
G.fnv(ROOT, G.fnv(b'b', G.fnv(b'a', G.fnv(b'x2w-startup-shader-18')))))
check('cache key uses revision 19', G.pipeline_key(b'a', b'b', ROOT) ==
G.fnv(ROOT, G.fnv(b'b', G.fnv(b'a', G.fnv(b'x2w-startup-shader-19')))))

if failures:
print('FAILED: ' + ', '.join(failures))
Expand Down
96 changes: 96 additions & 0 deletions tests/startup_gfx2hlsl_const_copy_join_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"""`s_mov_b32` copy of a plain constant SGPR in tools/startup/gfx2hlsl.py: run-time write and join.

The copy folds the constant into later reads (revision x2w-startup-shader-19), and these two cases pin what must
stay true next to the fold:
- the copy still assigns its register at run time (`s12 = ...;` is emitted), so a reader the fold does not reach
(a branch target after a join) sees a real value;
- at a join where one arm rewrites the copy at run time, the copy's constant is dropped, so a read after the join
uses the register and not the stale constant.

The instruction words are built from the SOP1 / SOP2 / SOPC / SOPP field layout that `tools/disasm_rdna2.py` decodes.
"""
import os
import struct
import sys

here = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(here, '..', 'tools'))
sys.path.insert(0, os.path.join(here, '..', 'tools', 'startup'))
import gfx2hlsl as G # noqa: E402

failures = []


def check(label, condition, detail=''):
print(f"{label}: {'ok' if condition else 'MISMATCH'}")
if not condition:
failures.append(label)
if detail:
print(' ' + detail)


def sop1(op, sdst, ssrc0):
return struct.pack('<I', 0xBE800000 | ((sdst & 0x7F) << 16) | ((op & 0xFF) << 8) | (ssrc0 & 0xFF))


def sop2(op, sdst, ssrc0, ssrc1):
return struct.pack('<I', (0b10 << 30) | ((op & 0x7F) << 23) | ((sdst & 0x7F) << 16) | ((ssrc1 & 0xFF) << 8)
| (ssrc0 & 0xFF))


def sopc(op, ssrc0, ssrc1):
return struct.pack('<I', 0xBF000000 | ((op & 0x7F) << 16) | ((ssrc1 & 0xFF) << 8) | (ssrc0 & 0xFF))


def sopp(op, simm=0):
return struct.pack('<I', 0xBF800000 | ((op & 0x7F) << 16) | (simm & 0xFFFF))


MOV, ADD, CMP_EQ, ENDPGM, CBRANCH_SCC0 = 0x03, 0x00, 0x06, 0x01, 0x04
INLINE_1, INLINE_3, INLINE_5 = 129, 131, 133
S4, S6, S12, S13, S15 = 4, 6, 12, 13, 15
CONST_WORD = '0x00000005u'


class Pipeline:
"""Just enough pipeline state for Stage.translate()."""

def __init__(self):
self.resources, self.notes, self.modified = {}, set(), set()


def blocks_of(code):
stage = G.Stage.__new__(G.Stage)
stage.pipe = Pipeline()
stage.kind = 'ps'
stage.lines, stage.sym = [], {}
stage.used_s, stage.used_v, stage.masks = set(), set(), set()
stage.attrs = {}
stage.exec_known = True
stage.ins = G.decode(code)
stage.force_joined = {}
stage.translate()
return {off: lines for off, lines, _ in stage.blocks}


COPY = [sop1(MOV, S15, INLINE_5), sop1(MOV, S12, S15)] # s15 = 5; s12 = s15
READ = sop2(ADD, S13, S12, INLINE_1) # s13 = s12 + 1

# Straight line: the read folds the constant, and the copy is still written at run time.
straight = blocks_of(b''.join(COPY + [READ, sopp(ENDPGM)]))
text = '\n'.join(l for lines in straight.values() for l in lines)
check('straight line: the copy is still assigned at run time', 's12 = ' in text, text)
check('straight line: the read folds the copied constant', 's12 + ' not in text and CONST_WORD in text, text)

# Skip: s_cmp_eq_u32 s4, 3; s_cbranch_scc0 JOIN; s_mov_b32 s12, s6 (run-time rewrite); JOIN: read.
join_at = 4 * (len(COPY) + 3)
skip = (COPY + [sopc(CMP_EQ, S4, INLINE_3), sopp(CBRANCH_SCC0, 1), sop1(MOV, S12, S6), READ, sopp(ENDPGM)])
joined = blocks_of(b''.join(skip))
after = '\n'.join(joined.get(join_at, []))
check('join: a read after a run-time rewrite on one arm uses the register', 's12' in after, repr(joined))
check('join: the stale constant is not folded into the read', CONST_WORD not in after, after)

if failures:
print('FAIL: ' + ', '.join(failures))
sys.exit(1)
print('startup_gfx2hlsl_const_copy_join_check: ok')
4 changes: 2 additions & 2 deletions tests/startup_gfx2hlsl_fract_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,8 +170,8 @@ def float_capped(word):
repr((seed and seed.group(1), literal and literal.group(1))))
check('the two literals are identical', seed and literal and seed.group(1) == literal.group(1),
repr((seed and seed.group(1), literal and literal.group(1))))
check('the revision is x2w-startup-shader-18, after the fix to the cap and the signed-zero min and max',
bool(seed and seed.group(1) == 'x2w-startup-shader-18'), repr(seed and seed.group(1)))
check('the revision is x2w-startup-shader-19, after the fold of a copy of a plain constant scalar register',
bool(seed and seed.group(1) == 'x2w-startup-shader-19'), repr(seed and seed.group(1)))


def key_from_seed(word):
Expand Down
2 changes: 1 addition & 1 deletion tests/startup_indirect_draw_indexed.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ ComPtr<IUnknown> translated_pipeline(ID3D12Device* guest, ID3D12RootSignature* r
bool needs_start, bool table_buffer = false, bool indexed = false, bool rect = false)
{
// The opaque guest programs identify synthetic cache entries. The actual bound shaders are source-built DXBC.
constexpr char revision[] = "x2w-startup-shader-18";
constexpr char revision[] = "x2w-startup-shader-19";
static std::uint32_t vertex_ids[]{0xe0000101, 0xe0000102, 0xe0000103};
static std::uint32_t pixel_ids[]{0xe0000202, 0xe0000203, 0xe0000204};
auto& vertex_id = vertex_ids[indexed ? 2 : needs_start];
Expand Down
91 changes: 84 additions & 7 deletions tests/startup_inline_sampler_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@
WRAP_SOURCE = CLAMP_SOURCE.replace('s_bfm_b32 s24, s28, 33', 's_bfm_b32 s24, 0, 33')
WRAP_WORDS = CLAMP_WORDS.replace(bytes.fromhex('1ca11892'), bytes.fromhex('80a11892'))

# The clamp sampler with word 0 built in s29 and copied into s24 (s_mov_b32 s24, s29): only the copy fold lets
# the four words be read as constants, so the draw below depends on it.
COPY_CLAMP_SOURCE = CLAMP_SOURCE.replace('s_bfm_b32 s24, s28, 33', 's_bfm_b32 s29, s28, 33\ns_mov_b32 s24, s29')
COPY_CLAMP_WORDS = CLAMP_WORDS.replace(bytes.fromhex('1ca11892'), bytes.fromhex('1ca11d92' '1d0398be'))

# s9 is root constant 1. Overwrite a previously folded word to check that the
# run-time write clears its constant value before the sampler is consumed.
DYNAMIC_SOURCE = CLAMP_SOURCE.replace('v_mov_b32 v0,', 's_bfm_b32 s24, s9, 33\nv_mov_b32 v0,')
Expand Down Expand Up @@ -74,12 +79,78 @@ def bare_stage(symbols=None):
except AttributeError:
pass

# llc builds a constant sampler by copying one zeroed SGPR into the other words (s_mov_b32 s25, s24).
COPY_WORDS = IMAGE_WORDS.replace(
bytes.fromhex('800398be' '800399be' '80039abe' '80039bbe'),
bytes.fromhex('800398be' '180399be' '18039abe' '18039bbe'),
)


def check_copied_constant_sampler():
"""A sampler word copied from a constant SGPR is that constant, not an unknown value."""
assert COPY_WORDS != IMAGE_WORDS
expected = [l for l in translate(IMAGE_WORDS).manifest().splitlines() if l.startswith('smp ')]
got = [l for l in translate(COPY_WORDS).manifest().splitlines() if l.startswith('smp ')]
assert got == expected and got, (got, expected)
print('copied constant sampler folds to %s' % got[0])


def copy_symbol(symbols, copy='s_mov_b32 s12, s15'):
"""The symbol s12 holds after `copy` runs on a bare stage that starts with `symbols`."""
class Pipe:
sampler_heap = False

stage = G.Stage.__new__(G.Stage)
stage.pipe, stage.sym, stage.lines = Pipe(), dict(symbols), []
stage.used_s, stage.used_v, stage.uniform_v, stage.exec_known = set(), set(), set(), True
stage.has_branches, stage.masks = False, set()
stage.one(copy.split()[0], copy)
return stage.sym.get(12)


def check_copy_only_folds_plain_constants():
"""Only a plain ('const', value) copies as a constant; every other source must not fold."""
assert copy_symbol({15: ('const', 0)}) == ('const', 0)
# The default-sampler placeholder is tagged 'unassigned': a copy of it is no run-time constant.
assert copy_symbol({15: ('const', 0, 'unassigned')}) != ('const', 0)
# A register that holds a root constant or nothing known is not a constant.
assert copy_symbol({15: ('ud', 1)}) != ('const', 1)
assert copy_symbol({}) is None
# A copy of a plain constant takes that constant's value.
assert copy_symbol({15: ('const', 7)}) == ('const', 7)
print('copies fold only plain constants')


def check_copied_sampler_after_overwrite():
"""A sampler word copied after its source was rewritten by a run-time value or another constant."""
prefix = bytes.fromhex('800398be') # s_mov_b32 s24, 0
copies = bytes.fromhex('180399be' '18039abe' '18039bbe')
anchor = prefix + copies
assert anchor in COPY_WORDS
runtime = COPY_WORDS.replace(anchor, prefix + bytes.fromhex('090398be') + copies) # s24 = s9 (root constant)
try:
translate(runtime)
except G.Unsupported as error:
assert 'holds' in str(error), error
else:
raise AssertionError('a sampler copied from a run-time register was accepted')
# s28 = 0, then s28 = 1, then s27 = s28; s24..s26 stay literal zeros
one = COPY_WORDS.replace(anchor, bytes.fromhex('800398be' '800399be' '80039abe' '80039cbe' '81039cbe' '1c039bbe'))
smp = [l for l in translate(one).manifest().splitlines() if l.startswith('smp ')]
assert smp == ['smp 0 0x0 0x0 0x0 0x1'], smp
print('copy after overwrite: run-time source refused, new constant wins (%s)' % smp[0])


def controls():
check_compare_sampler_constant()
check_copied_constant_sampler()
check_copy_only_folds_plain_constants()
check_copied_sampler_after_overwrite()
fixtures = []
for name, code, words in (
('clamp', CLAMP_WORDS, (0x2, 0, 0x00100000, 0)),
('wrap', WRAP_WORDS, (0, 0, 0x00100000, 0)),
('copied clamp', COPY_CLAMP_WORDS, (0x2, 0, 0x00100000, 0)),
):
pipe = translate(code)
manifest = pipe.manifest()
Expand All @@ -98,23 +169,25 @@ def controls():
print('root-constant mask width: inline sampler refused (%s)' % error)
else:
raise AssertionError('run-time write to s24 was accepted as an inline sampler')
(clamp_ps, clamp_line), (_, wrap_line) = fixtures
return clamp_ps, clamp_line, wrap_line
(clamp_ps, clamp_line), (_, wrap_line), (copy_ps, copy_line) = fixtures
assert copy_line == clamp_line, (copy_line, clamp_line)
return clamp_ps, clamp_line, wrap_line, copy_ps


def check_binary(llvm_mc):
for name, source, recorded in (
('clamp', CLAMP_SOURCE, CLAMP_WORDS),
('wrap', WRAP_SOURCE, WRAP_WORDS),
('root constant', DYNAMIC_SOURCE, DYNAMIC_WORDS),
('copied clamp', COPY_CLAMP_SOURCE, COPY_CLAMP_WORDS),
):
built = assemble(llvm_mc, source)
assert built == recorded, '%s: assembled %s, recorded %s' % (name, built.hex(), recorded.hex())
print('all three fixture programs match llvm-mc')
print('all four fixture programs match llvm-mc')


def check_draw(dxc, renderer, adapter, fxc=None):
ps, clamp, wrap = controls()
ps, clamp, wrap, copy_ps = controls()
expected_clamp = texel(1, 0, 0)
expected_wrap = texel(0, 0, 0)
compilers = [('dxc', dxc, 'vs_6_0', 'ps_6_0')]
Expand All @@ -129,9 +202,13 @@ def check_draw(dxc, renderer, adapter, fxc=None):
for kind, compiler, vs_profile, ps_profile in compilers:
vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, 'fullscreen', vs_profile, directory)
shader = compile_hlsl(compiler, kind, ps, 'inline_sampler', ps_profile, directory)
command = [renderer, adapter, '--startup-image-3d', str(vs), str(shader), '0.25', expected_clamp]
# Hold shader, texture, and reference fixed. Only the manifest sampler changes.
for label, line, result in (('clamp', clamp, 0), ('wrap control', wrap, 1)):
copy_shader = compile_hlsl(compiler, kind, copy_ps, 'inline_sampler_copy', ps_profile, directory)
# Hold shader, texture, and reference fixed. Only the manifest sampler changes. The copied-word shader
# is drawn with its own sampler (must read the clamped texel) and with the wrap sampler (must mismatch).
for label, shader_path, line, result in (('clamp', shader, clamp, 0), ('wrap control', shader, wrap, 1),
('copied-word clamp', copy_shader, clamp, 0),
('copied-word wrap control', copy_shader, wrap, 1)):
command = [renderer, adapter, '--startup-image-3d', str(vs), str(shader_path), '0.25', expected_clamp]
run = subprocess.run([*command, line], capture_output=True, text=True)
print(run.stdout, end='', flush=True)
if run.returncode == 77:
Expand Down
2 changes: 1 addition & 1 deletion tests/startup_packed_position_provenance_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ def refused(label, cache, key, reason):
cache = Path(tmp)
bare = G.pipeline_key(VS_WORDS, ps_words(4), root_blob())
check('without a description the key is unchanged',
bare == G.fnv(root_blob(), G.fnv(ps_words(4), G.fnv(VS_WORDS, G.fnv(b'x2w-startup-shader-18')))))
bare == G.fnv(root_blob(), G.fnv(ps_words(4), G.fnv(VS_WORDS, G.fnv(b'x2w-startup-shader-19')))))
keys = [put_request(cache, ps_words(4), masks) for masks in (TARGET, SAME_V4, DECOY)]
check('same stages, root and layout with three mask pairs: three request identities',
len(set(keys)) == 3 and bare not in keys
Expand Down
2 changes: 1 addition & 1 deletion tests/startup_resource_retire_title.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ constexpr UINT draw_side = 4; // 4x4 R8G8B8A8_UNORM target
constexpr UINT draw_covered = 3; // scissor leaves the last row and column untouched as the sentinel
constexpr int draw_seed = 77;
constexpr UINT draw_clear_pixel = 0xffff00ffu; // ClearRenderTargetView({1, 0, 1, 1}) in R8G8B8A8_UNORM
constexpr char draw_revision[] = "x2w-startup-shader-18"; // d3d12_draw.inl cached_translation
constexpr char draw_revision[] = "x2w-startup-shader-19"; // d3d12_draw.inl cached_translation

constexpr char draw_vertex_shader[] = R"(
struct Varying { float4 position : SV_Position; };
Expand Down
Loading
Loading