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
5 changes: 5 additions & 0 deletions docs/experiments.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ The compute fixture checks arithmetic, lane selection and disabled sources.
Full-mask row shifts and rotates stay inside each 16-lane row and apply
BOUND_CTRL to unusable sources. [Experiment and reproduction commands](experiments/native-dpp-row.md)

## Guest permlane16 and permlanex16 in direct compute

VOP3A row permutations select lanes using uniform packed selectors.
[Experiment and reproduction commands](experiments/native-permlane.md)

## Guest lane reads and writes in direct compute

`v_readlane_b32` and `v_writelane_b32` lower with a constant or SGPR lane; lane writes ignore EXEC.
Expand Down
45 changes: 45 additions & 0 deletions docs/experiments/native-permlane.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Permlane16 and permlanex16 in direct C++ compute

Issue #3021 lowers `v_permlane16_b32` (VOP3A opcode 0x377) and
`v_permlanex16_b32` (0x378). S0 and the destination are VGPRs. The uniform
selectors are SGPRs, inline constants, or a trailing 32-bit literal. S1 and
S2 can each reference the same literal word. Selectors refuse `vcc_lo` and,
on the wave64 path, `vcc_hi`. In wave32, `vcc_hi` is ordinary scalar data.

S1 packs the selectors for row lanes 0 through 7 and S2 for lanes 8 through
15. Each lane extracts its four-bit selector at runtime. Permlane16 reads the
selected lane in its own row and permlanex16 reads from the paired row in the
same physical wave32. Guest wave64 uses two physical wave32s, with s126 and
s127 supplying guest EXEC for the lower and upper halves respectively.

VOP3A op_sel bits 0 and 1 encode FI and BOUND_CTRL. By analogy with DPP, FI
allows reading a source whose guest EXEC bit is clear. Without FI, an
inactive source supplies zero with BOUND_CTRL or preserves the destination
otherwise. Destination writes obey guest EXEC. Other modifier bits and
nonuniform selectors are refused. Thread counts must be divisible by 16 for
permlane16 and by 32 for permlanex16.

`native_permlane_controls` covers the literal form, six refusals, and
compilation of a split-wave64 container with distinct EXEC halves.
`native_permlane_hardware` uses sparse guest EXEC in 64-thread wave32 groups.
It compares lane-dependent selectors, including a shared literal in S1 and
S2, and inline zero against a CPU reference, including every sentinel word
outside the two groups' stores.

```powershell
cmake --build --preset dev --target compile_dxil native_store_replay
ctest --preset dev --no-tests=error -R '^native_permlane_(controls|hardware)$'
```

On Windows 11 with an NVIDIA GeForce RTX 5080 and DXC from the Windows SDK 10.0.26100, on `main` (`6057071b`)
plus this branch, `native_permlane_controls` and `native_permlane_hardware` passed. The six original readbacks matched a
CPU reference in all 2,064 words. Three manual mutants each fail the hardware check: reading the same row for
`x16`, swapping S1 and S2, and ignoring BOUND_CTRL. The inactive-source rule is assumed from DPP; the readback
checks the lowering against that model, not RDNA2 itself. On `main`, the wave64 branch of `lower_permlane`
is compiled by the container control. Slot 67 requests use the wave32 model until #3006 lands, so readback
exercises wave32 only.

On `cpp-migration` (`999e17cd`) plus #3010, a local capture of 2,689 compute requests (counts and instruction
shape only) had 47 requests stop first at one of the two ops. With this change, 34 of them compile and none that compiled before stops: 393 to 427
compiled. The other 13 stop later, 7 of them at "direct scalar move destination". All 47 have the wave32 bit of
#2999 clear; without #3006 they still compile on the wave32 model.
6 changes: 6 additions & 0 deletions src/gfx1013_compute_native.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,12 @@ Inst decode(const string &bytes, unsigned pc,bool direct=false, bool graphics=fa
i.enc = Encoding::Vop1;
i.op -= 0x180;
}
if (direct && !graphics && i.enc == Encoding::Vop3 && (i.op == 0x377 || i.op == 0x378)) {
// The shared extent decoder already counts the trailing literal word.
// S1 and S2 may both reference that word.
if (i.src[0] == 255)
refuse(pc, "permlane S0 cannot be a literal");
}
lit = std::find(i.src.begin(), i.src.end(), 255) != i.src.end();
} else
refuse(pc, "unsupported instruction " + string(encoded.name) + " " + hexword(a));
Expand Down
47 changes: 47 additions & 0 deletions src/gfx1013_direct_compute.inl
Original file line number Diff line number Diff line change
Expand Up @@ -2882,6 +2882,51 @@ struct DirectCompute {
} else
vector_write(i.dst, place_subword(i, z));
}
void lower_permlane(const Inst &i, unsigned threads) {
const bool cross_row = i.name == "v_permlanex16_b32";
if (threads % (cross_row ? 32 : 16))
refuse(i.pc, string(i.name) + " needs a thread count divisible by " + (cross_row ? "32" : "16"));

// VOP3A retains op_sel in word 0 bits 11..14: bit 0 is FI and bit 1 is BOUND_CTRL.
const unsigned op_sel = (i.a >> 11) & 15;
if ((op_sel & ~3u) || i.neg || i.abs || i.clamp || i.scale)
refuse(i.pc, "unsupported permlane modifier or op_sel");
const bool fi = op_sel & 1;
const bool bound_zero = op_sel & 2;

// D and S0 are VGPRs. S1 and S2 are uniform SGPRs or constants.
if (i.src[0] < 256)
refuse(i.pc, "permlane S0 must be a VGPR");
for (unsigned reg : {i.src[1], i.src[2]})
if (reg > 105 && (wave64 || reg != 107) && !constant32(i, reg))
refuse(i.pc, "permlane selectors must be uniform SGPRs or constants");

// S1 packs the nibbles for row lanes 0..7 and S2 packs those for 8..15.
auto row_lane = ir.binary("and", lane, "15");
auto selectors = select(cmp("uge", row_lane, "8"), operand32(i, i.src[2]), operand32(i, i.src[1]));
auto shift = ir.binary("shl", ir.binary("and", row_lane, "7"), "2");
auto pick = ir.binary("and", ir.binary("lshr", selectors, shift), "15");

// Permlane16 uses the current row; permlanex16 toggles row bit 4.
// Both rows of the pair are in the same physical wave32, even for guest wave64.
auto row_base = ir.binary("and", lane, "4294967280");
if (cross_row)
row_base = ir.binary("xor", row_base, "16");
auto source_lane = ir.binary("or", row_base, pick);
auto src = operand32(i, i.src[0]);
auto value = ir.invoke("i32", "waveReadLaneAt.i32", 117, {{"i32",src},{"i32",source_lane}}, "nounwind");

// Assume DPP's inactive-source rule: FI bypasses the guest EXEC test.
// Otherwise an inactive source yields zero with BOUND_CTRL or preserves D.
if (!fi) {
auto exec = wave64 ? select(upper_half, read(127), read(126)) : read(126);
auto source_bit = ir.binary("shl", "1", source_lane);
auto source_usable = cmp("ne", ir.binary("and", exec, source_bit), "0");
value = select(source_usable, value, bound_zero ? "0" : read(i.dst));
}
// Guest EXEC still predicates the destination write.
vector_write(i.dst, value);
}
void lower_dpp(const Inst &i, const State &state, unsigned threads) {
// All lane selections stay in one physical wave32 for split guest wave64.
// Shader control flow stays wave-uniform. Guest EXEC predicates VGPR
Expand Down Expand Up @@ -3043,6 +3088,8 @@ struct DirectCompute {
}
} else if (i.dpp_control)
lower_dpp(i, p.before[k], x*y*z);
else if (i.name == "v_permlane16_b32" || i.name == "v_permlanex16_b32")
lower_permlane(i, x*y*z);
else if (i.name == "s_endpgm")
ir.body << " ret void\n";
// Hardware scheduling and register-dependency waits have no SGPR
Expand Down
11 changes: 11 additions & 0 deletions tests/cmake/native_permlane.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
if(TARGET compile_dxil AND TARGET native_store_replay AND
EXISTS "${DXC_BIN_DIR}/dxcompiler.dll" AND EXISTS "${DXC_BIN_DIR}/dxil.dll")
add_test(NAME native_permlane_controls COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_SOURCE_DIR}/tests/native_permlane_check.py" controls
"$<TARGET_FILE:compile_dxil>" "${DXC_BIN_DIR}")
set_tests_properties(native_permlane_controls PROPERTIES TIMEOUT 60)
add_test(NAME native_permlane_hardware COMMAND "${INTAKE_PYTHON}" -B
"${CMAKE_SOURCE_DIR}/tests/native_permlane_check.py" hardware
"$<TARGET_FILE:native_store_replay>" "${DXC_BIN_DIR}")
set_tests_properties(native_permlane_hardware PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60)
endif()
146 changes: 146 additions & 0 deletions tests/native_permlane_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
"""Direct compute permlane with sparse guest EXEC."""
from pathlib import Path
import struct
import subprocess
import sys
import tempfile

from native_compute_clear_check import write_request
from native_direct_container_check import compute
from native_dpp_mirror_check import vop2
from native_scalar_lds_check import scalar, sop1


SENTINEL = 0x69696969
ACTIVE = 0xFFFFFEFD # Disable physical lanes 1 and 8 in each wave32.
SELECTORS = (1, 8, 3, 0, 15, 2, 9, 4, 8, 1, 14, 5, 2, 11, 6, 7)

# VOP3A word 0: opcode 25:16 (377/378), FI 11, BOUND_CTRL 12, v1 destination.
# Word 1: S0 8:0 (258 = v2), S1 17:9, S2 26:18. A selector of 255
# references the shared third word. Keep the CPU model separate from the machine words.
CASES = (
("cross-literal-bound", True, False, True, SELECTORS,
(0xD7781001, 0x0035FF02, 0x492F0381)), # x16 BC, v2/literal/s13
("cross-sgprs-fi", True, True, False, SELECTORS,
(0xD7780801, 0x00341902)), # x16 FI, v2/s12/s13
("cross-inline-zero", True, False, False, (0,) * 16,
(0xD7780001, 0x02010102)), # x16, v2/inline 0/inline 0
("same-literal-bound", False, False, True, SELECTORS,
(0xD7771001, 0x0035FF02, 0x492F0381)), # permlane16 BC, v2/literal/s13
("same-sgprs", False, False, False, SELECTORS,
(0xD7770001, 0x00341902)), # permlane16, v2/s12/s13
("cross-s2-literal", True, False, False, SELECTORS,
(0xD7780001, 0x03FC1902, 0x76B25E18)), # x16, v2/s12/literal
("cross-shared-literal", True, False, False, (1, 8, 3, 0, 15, 2, 9, 4) * 2,
(0xD7780001, 0x03FDFF02, 0x492F0381)), # x16, v2/literal/literal
)


def program(instruction):
# Each group writes 64 words starting after eight guards.
# Initialize the destination and a distinct source while EXEC is full.
return [
sop1(3, 20, 4), sop1(3, 21, 128), 0xF408080A, 0xFA000020,
scalar(0x1E, 7, 5, 136), vop2(0x1A, 8, 130, 0), vop2(0x25, 8, 7, 8),
vop2(0x25, 1, 145, 0), vop2(0x25, 2, 148, 0),
sop1(3, 12, 255), 0x492F0381, sop1(3, 13, 255), 0x76B25E18,
sop1(3, 126, 255), ACTIVE, *instruction,
# Restore EXEC so the store observes preserved destinations too.
sop1(3, 126, 193), 0xE0701000, 0x80080108, 0xBF810000,
]


def reference(cross_row, fi, bound_zero, selectors):
result = list(range(17, 81))
enabled = [bool(ACTIVE & (1 << (lane % 32))) for lane in range(64)]
for half in (0, 32):
rows = (half, half + 16)
source_rows = rows[::-1] if cross_row else rows
for destination, source in zip(rows, source_rows):
for offset, peer in enumerate(selectors):
lane = destination + offset
if enabled[lane]:
if fi or enabled[source + peer]:
result[lane] = 20 + source + peer
elif bound_zero:
result[lane] = 0
return tuple(result)


def request(work, root, instruction, threads=64):
sa = struct.pack("<7I", 0, 0, 0, threads | (1 << 16), 1 | (1 << 20), 0, 0x8A) # bit 20: wave32 (#2999)
return write_request(work, program(instruction), root, sa)


def controls(cli, sdk, work, root):
requests = work / "requests"
requests.mkdir()
good = request(requests, root, CASES[0][-1])
refused = {}
for instruction, threads, error in (
((0xD7782001, 0x00341902), 64, "unsupported permlane modifier or op_sel"), # x16 op_sel[2]
((0xD7788001, 0x00341902), 64, "unsupported permlane modifier or op_sel"), # x16 clamp
((0xD7780001, 0x00360702), 64, "permlane selectors must be uniform"), # v2/v3/s13
((0xD7780001, 0x00341902), 16, "thread count divisible by 32"), # x16 partial pair
((0xD7770001, 0x00341902), 8, "thread count divisible by 16"), # permlane16 partial row
((0xD7780001, 0x00341880), 64, "S0 must be a VGPR")): # inline 0/s12/s13
refused[request(requests, root, instruction, threads)] = error
result = subprocess.run(
[cli, sdk, work / "cache", "gfx1013-direct-cs@0", "--requests", requests, requests],
capture_output=True, text=True)
assert result.returncode and "requests=7 compiled=1 refused=6" in result.stdout, (
result.stdout, result.stderr)
good_key = good.stem.removeprefix("req_")
assert (requests / f"{good_key}.cs.cso").is_file()
for marker, error in refused.items():
key = marker.stem.removeprefix("req_")
reason = (requests / f"{key}.fail").read_text(encoding="utf-8")
assert error in reason, (marker, reason)
assert not (requests / f"{key}.cs.cso").exists()

# Compile a container without its wave32 flag to exercise split guest wave64.
# Give EXEC halves distinct values, then restore both after the permutation.
shader = work / "wave64.cdx"
output = shader.with_suffix(".cso")
words = [vop2(0x25, 1, 145, 0), vop2(0x25, 2, 148, 0),
sop1(3, 13, 255), 0x76B25E18,
sop1(3, 126, 255), ACTIVE, sop1(3, 127, 255), 0xFFFFFF7B,
*CASES[0][-1], sop1(4, 126, 193), 0xBF810000]
shader.write_bytes(compute(struct.pack(f"<{len(words)}I", *words), 64, wave32=False))
result = subprocess.run([cli, sdk, work / "cache", "gfx1013-container-cs", shader, output],
capture_output=True, text=True)
assert result.returncode == 0, (result.stdout, result.stderr)
assert output.read_bytes().startswith(b"DXBC")
return 0


def hardware(replay, sdk, work, root):
for name, cross_row, fi, bound_zero, selectors, instruction in CASES:
marker = request(work, root, instruction)
output = marker.with_suffix(".bin")
result = subprocess.run([replay, sdk, marker, work / "cache", "0", output, "--direct"])
if result.returncode == 77:
return 77
result.check_returncode()
lanes = reference(cross_row, fi, bound_zero, selectors)
expected = (SENTINEL,) * 8 + lanes * 2 + (SENTINEL,) * (2064 - 136)
actual = struct.unpack("<2064I", output.read_bytes())
for index, (got, want) in enumerate(zip(actual, expected)):
assert got == want, (name, index, hex(got), hex(want))
print(f"{name}: 128 results and guards matched")
return 0


def main(mode, tool, sdk):
with tempfile.TemporaryDirectory() as temp:
work = Path(temp)
shader = work / "root.hlsl"
shader.write_text('#define SIG "DescriptorTable(UAV(u0,numDescriptors=8))"')
root = work / "root.bin"
subprocess.run([Path(sdk) / "dxc.exe", "-T", "rootsig_1_1", "-E", "SIG",
"-Fo", root, shader], check=True)
return {"controls": controls, "hardware": hardware}[mode](tool, sdk, work, root.read_bytes())


if __name__ == "__main__":
sys.exit(main(*sys.argv[1:]))
Loading