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
1 change: 1 addition & 0 deletions build.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,7 @@ def build_target(tools, target, dxc, d3d12_reference=None):
game = tools.compile(src / "game.cpp", objects)
subprocess.run([sys.executable, str(src / "shader_fixture.py"), "xbox_shader.h"], cwd=objects, check=True)
subprocess.run([sys.executable, str(src / "raster_fixture.py"), "raster_shader.h"], cwd=objects, check=True)
subprocess.run([sys.executable, str(src / "wave_alloc_fixture.py"), "wave_alloc_shader.h"], cwd=objects, check=True)
selftest = tools.compile(src / "selftest.cpp", objects, f"/I{objects}")
xmem, d3d, gameinput = OUTPUT / "xmem-smoke", OUTPUT / "d3d12-smoke", OUTPUT / "gameinput"
tools.link(objects / "lanes.exe", course, screen, controls, game, selftest, xmem / "xmem.lib",
Expand Down
65 changes: 63 additions & 2 deletions examples/lanes/selftest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#include "xbox_shader.h"
#include "raster_shader.h"
#include "reclaim_shader.h"
#include "wave_alloc_shader.h"
#include <algorithm>
#include <memory>

Expand All @@ -33,6 +34,10 @@ constexpr std::array<UINT, 18> scarlett_profile{
// scenario that needs that release must already count as failed.
constexpr DWORD deadline_ms = 2000;

// Sentinel written to the wave-alloc UAV so a shader that never stores is
// distinguishable from one that stored the expected value (0).
constexpr UINT kWaveAllocSentinel = 0xdeadbeefu;

// Xbox command-list and queue slots (GDK gen9/d3d12_xs.h).
constexpr size_t slot_copy_memory = 62, slot_write32 = 71, slot_write64 = 72, slot_wait64 = 74,
slot_dispatch_flagged = 80, slot_copy_texture = 83, slot_build = 119,
Expand Down Expand Up @@ -630,6 +635,62 @@ void raster_tables(ID3D12Device* device) {
}
}


// A console shader whose wave32 masked DPP exclusive prefix the translator must
// lower to `WavePrefixSum`. The old translator rejects it with "unrecognized
// masked DPP prologue", so this scenario fails without the wave-alloc lowering.
// The shader stores the exclusive-prefix result (0 for the single active lane)
// to a UAV; the scenario reads it back and requires it to be the expected
// value, so a numerical miscompile of the lowering is caught here.
void wave_alloc_scenario(ID3D12Device* device) {
D3D12_ROOT_PARAMETER params[1]{};
params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV;
params[0].Descriptor = {0, 0};
D3D12_ROOT_SIGNATURE_DESC signature{};
signature.NumParameters = 1;
signature.pParameters = params;
ComPtr<ID3DBlob> serialized;
check(D3D12SerializeRootSignature(&signature, D3D_ROOT_SIGNATURE_VERSION_1, &serialized, nullptr),
"serialize wave-alloc root signature");
ComPtr<ID3D12RootSignature> root;
check(device->CreateRootSignature(0, serialized->GetBufferPointer(), serialized->GetBufferSize(),
IID_PPV_ARGS(&root)), "create wave-alloc root signature");
D3D12_COMPUTE_PIPELINE_STATE_DESC shader{};
shader.pRootSignature = root.Get();
shader.CS = {wave_alloc_shader, sizeof(wave_alloc_shader)};
ComPtr<ID3D12PipelineState> pipeline;
check(method<CreateComputePipeline>(device, device_create_compute)(device, &shader, 0, nullptr,
IID_PPV_ARGS(&pipeline)),
"create pipeline from the wave-alloc console shader");
auto output = buffer(device, D3D12_HEAP_TYPE_DEFAULT, sizeof(UINT), D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
// Seed the UAV with a sentinel so a missing store is distinguishable from the
// expected value (0) in the readback.
auto sentinel = buffer(device, D3D12_HEAP_TYPE_UPLOAD, sizeof(UINT), D3D12_RESOURCE_STATE_GENERIC_READ);
compute_fixture::upload(sentinel.Get(), &kWaveAllocSentinel, sizeof(kWaveAllocSentinel));
auto proof = buffer(device, D3D12_HEAP_TYPE_READBACK, sizeof(UINT), D3D12_RESOURCE_STATE_COPY_DEST);
Queue compute(device, D3D12_COMMAND_LIST_TYPE_COMPUTE);
auto* list = compute.list.Get();
list->CopyBufferRegion(output.Get(), 0, sentinel.Get(), 0, sizeof(UINT));
method<SetRoot>(list, slot_compute_root)(list, root.Get());
list->SetPipelineState(pipeline.Get());
method<SetUav>(list, slot_root_uav)(list, 0, output->GetGPUVirtualAddress());
compute_fixture::transition(list, output.Get(), D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
list->Dispatch(1, 1, 1);
compute_fixture::transition(list, output.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
D3D12_RESOURCE_STATE_COPY_SOURCE);
list->CopyBufferRegion(proof.Get(), 0, output.Get(), 0, sizeof(UINT));
compute.submit();
compute.finish("dispatch of the wave-alloc console shader");
D3D12_RANGE range{0, sizeof(UINT)}, empty{};
void* mapped{};
check(proof->Map(0, &range, &mapped), "map wave-alloc proof");
const UINT row = *static_cast<const UINT*>(mapped);
proof->Unmap(0, &empty);
if (row != 0u) throw std::runtime_error("wave-alloc shader stored the wrong prefix result (or stored nothing)");
}

ComPtr<ID3D12PipelineState> compute_pipeline(ID3D12Device* device, ComPtr<ID3D12RootSignature>& root,
D3D12_SHADER_BYTECODE bytecode) {
D3D12_ROOT_PARAMETER params[2]{};
Expand Down Expand Up @@ -1660,6 +1721,7 @@ constexpr Scenario scenarios[] = {
{L"xbox-shader", xbox_shader_scenario},
{L"wave64-shader", wave64_shader_scenario},
{L"raster-tables", raster_tables},
{L"wave-alloc", wave_alloc_scenario},
};

// A fresh Scarlett device on the requested adapter. The factory is reached
Expand Down Expand Up @@ -1711,8 +1773,7 @@ const wchar_t* const selftest_scenarios[] = {L"labels", L"cross-queue
L"indirect-dispatch", L"gpu-indirect-dispatch",
L"dispatch-wait", L"texture-readback", L"ray-tracing-builder",
L"thread-dimensions", L"descriptor-reclaim",
L"xbox-shader", L"wave64-shader",
L"raster-tables"};
L"xbox-shader", L"wave64-shader", L"raster-tables", L"wave-alloc"};
const unsigned selftest_scenario_count = static_cast<unsigned>(std::size(selftest_scenarios));
static_assert(std::size(selftest_scenarios) == std::size(scenarios));

Expand Down
71 changes: 71 additions & 0 deletions examples/lanes/wave_alloc_fixture.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""The synthetic Xbox compute shader the Lanes self-test loads for the
wave-alloc self-test.

It is a small hand-written console program: a constant input, a wave32 masked
DPP exclusive-prefix (the pattern the translator lowers to `WavePrefixSum`),
and an `s_endpgm`. The prefix result is stored to a UAV so the self-test can
read it back and check the shader's arithmetic, not just that it dispatched.
Not taken from any game.
"""
import hashlib
from pathlib import Path
import struct
import sys

sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from tools.reference.scarlett_worker_fixture import container, pack # noqa: E402

CODE = (
0x7e000281, # v_mov_b32 v0, 1
0xbe803dc1, # s_or_saveexec_b32 s0, -1
0xd5010001, # v_cndmask_b32 v1, 0, v0, s0
0x00020080,
0x7e040301, # v_mov_b32 v2, v1
0x4a0404fa, # v_add_nc_u32 v2, 250, v2 (DPP row_shr)
0xff091102,
0x4a0404fa,
0xff011202,
0x4a0404fa,
0xff011402,
0x4a0404fa,
0xff011802,
0xbefe03ff, # s_mov_b32 ExecLo, 0xffff0000
0xffff0000,
0xd7780003, # v_permlanex16_b32 v3, v2, -1, -1
0x03058302,
0x4a040503, # v_add_nc_u32 v2, v3, v2
0xbefe03c1, # s_mov_b32 ExecLo, -1
0x4c040302, # v_sub_nc_u32 v2, v2, v1
0xbefe0300, # s_mov_b32 ExecLo, s0
0x7e080302, # v_mov_b32 v4, v2
0x7e100280, # v_mov_b32 v8, 0 (address of the result in the UAV)
0xf4080402, # s_load_dwordx4 s[16:19], s[4:5], 0
0xfa000000,
0xbf8cc07f, # s_waitcnt lgkmcnt(0)
0xe0701000, # buffer_store_dword v4, v8, s[16:19], 0 (offset 0)
0x80040408,
0xbf810000, # s_endpgm
)
# Root signature 1.0 with a single UAV table for the result buffer.
UAV_ROOT = pack([1, 1, 24, 0, 0, 0, 0, 0, 36, 1, 44, 1, 1, 0, 0, 0])


def shader():
base = container(list(CODE), width=32, resources=[(7, 0, 0, 0)])
root = b"RTS0" + pack([64]) + UAV_ROOT
first, second = struct.unpack_from("<II", base, 32)
root_at = len(base) + 4
directory = pack([root_at + len(root), 3, first + 4, second + 4, root_at])
return base[:24] + directory + base[first:] + root


def header(data):
values = ",".join(str(byte) for byte in data)
return ("// Generated from wave_alloc_fixture.py.\n"
f"constexpr unsigned char wave_alloc_shader[] = {{{values}}};\n"
"// The name its translation is cached under.\n"
f"constexpr wchar_t wave_alloc_shader_digest[] = L\"{hashlib.sha256(data).hexdigest()}\";\n")


if __name__ == "__main__":
Path(sys.argv[1]).write_text(header(shader()))
59 changes: 57 additions & 2 deletions project_tuxbox/verify.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,12 @@ class LanesShader:
"""The Lanes console shader in a prefix's translation cache."""

def __init__(self, host, data=None):
from examples.lanes.shader_fixture import shader
if data is None:
from examples.lanes.shader_fixture import shader
data = shader()
from .shader_prep import SOURCE_CACHE

self.data = shader() if data is None else data
self.data = data
self.key = hashlib.sha256(self.data).hexdigest()
self.sources = Path(host.env["WINEPREFIX"]) / SOURCE_CACHE
self.root = self.sources.parent
Expand Down Expand Up @@ -154,6 +156,48 @@ def lanes_wave_shader(host, check, gpu_args, pci, memory_symbols):
host.env[name] = value


def lanes_wave_alloc(host, check, gpu_args, pci, memory_symbols, work):
"""Translate the wave32 masked DPP shader and verify the provider loads it.

The wave-alloc scenario creates a pipeline from a console shader whose wave32
masked DPP exclusive prefix the translator must lower to `WavePrefixSum`.
Without the wave-alloc lowering the compiler rejects the shader, so the
provider never loads a translation and this gate fails.
"""
from .runtime_shaders import shader_session
from examples.lanes.wave_alloc_fixture import shader as wave_alloc_shader

lanes = LanesShader(host, wave_alloc_shader())
key, root, forget = lanes.key, lanes.root, lanes.forget

saved = {name: host.env.get(name) for name in ("TUXBOX_LOG", "WINEDEBUG", "TUXBOX_SHADER_SESSION")}
host.env.update(TUXBOX_LOG="1", WINEDEBUG="-all,+debugstr")
host.env.pop("TUXBOX_SHADER_SESSION", None)
loaded = f"prepared compute shader loaded, source SHA-256 {key}"

def expect_loaded(output):
return None if loaded in output else "the provider did not load the translated shader"

def launch(name, log_check):
return check(name, "lanes/lanes.exe", ["--selftest", "wave-alloc", *gpu_args, "--report"],
rf"lanes-selftest PASS pci={pci} scenario=wave-alloc passed=1",
providers={"lanes/xmem.dll": memory_symbols, "lanes/GameInput.dll": ("#1",),
"lanes/d3d12_xs.dll": ("D3D12XboxCreateDevice",)},
config="lanes/MicrosoftGame.config", device_factory="xbox", log_check=log_check)

try:
forget()
with shader_session(root, host.env, lambda line: None):
launch("lanes-shader-cache-wave-alloc", expect_loaded)
forget()
finally:
for name, value in saved.items():
if value is None:
host.env.pop(name, None)
else:
host.env[name] = value


def cpu_model():
if sys.platform == "linux" and Path("/proc/cpuinfo").exists():
for line in Path("/proc/cpuinfo").read_text().splitlines():
Expand Down Expand Up @@ -683,6 +727,11 @@ def exports_receipt(_imports):
"lanes/d3d12_xs.dll": (*graphics_symbols, "D3D12XboxCreateDevice")},
config="lanes/MicrosoftGame.config", device_factory="xbox")
if "lanes-selftest" in selected:
# The descriptor-reclaim selftest asserts the console's 1,000,000-descriptor
# limit; force it so the OOM case is deterministic on GPUs that support larger
# shader-visible heaps (the provider otherwise caps at the GPU's maximum).
saved_limit = host.env.get("TUXBOX_DESCRIPTOR_HEAP_LIMIT")
host.env["TUXBOX_DESCRIPTOR_HEAP_LIMIT"] = "1000000"
for scenario in LANES_SCENARIOS:
check(f"lanes-selftest-{scenario}", "lanes/lanes.exe",
["--selftest", scenario, *gpu_args, "--report"],
Expand All @@ -691,6 +740,10 @@ def exports_receipt(_imports):
"lanes/d3d12_xs.dll": ("D3D12XboxCreateDevice",)},
config="lanes/MicrosoftGame.config", device_factory="xbox",
dependencies=("lanes/XboxBvhBuilder.dll",) if scenario == "ray-tracing-builder" else ())
if saved_limit is None:
host.env.pop("TUXBOX_DESCRIPTOR_HEAP_LIMIT", None)
else:
host.env["TUXBOX_DESCRIPTOR_HEAP_LIMIT"] = saved_limit
if "lanes-benchmark" in selected:
# Console shaders are only translated on the Proton backend, so the
# pipeline readings exist there alone.
Expand All @@ -711,6 +764,7 @@ def exports_receipt(_imports):
if "lanes-shader-cache" in selected and host.backend == "proton":
lanes_shader_cache(host, check, gpu_args, pci, memory_symbols, work)
lanes_wave_shader(host, check, gpu_args, pci, memory_symbols)
lanes_wave_alloc(host, check, gpu_args, pci, memory_symbols, work)
if "lanes-raster-tables" in selected and host.backend == "proton":
lanes_raster_tables(host, check, gpu_args, pci, memory_symbols)
if "cpu-benchmark" in selected:
Expand Down Expand Up @@ -824,6 +878,7 @@ def exports_receipt(_imports):
"lanes-wave-shader-narrow": "A 64-lane console shader translated for 32-lane waves while the game runs",
"lanes-wave-shader-host": "A 64-lane console shader with the translation this graphics card needs",
"lanes-raster-tables": "Console raster programs drawn under the root reflected from their two descriptor tables",
"lanes-shader-cache-wave-alloc": "A wave32 masked DPP exclusive prefix lowered to WavePrefixSum and loaded by the provider",
"lanes-package-replay": "Lanes gameplay replay (earlier guest with desktop graphics)", "cpu-replay": "8,388,608-move CPU replay",
}

Expand Down
36 changes: 34 additions & 2 deletions tools/shader-compiler/src/hlsl/driver/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,11 @@ pub(in crate::hlsl) fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Opti
let generic_waves = !lone_lane::on() && !wave_cull && !page_waves;
let election = if generic_waves && !resolve_wave32 { straight_election(ex, &insns) } else { None };
let allocation_wave64 = generic_waves && mark_wave_allocations(&mut insns, resolve_wave32, election)?;
if ex.stage == Stage::Pixel { wave_alloc::prepare(&mut insns); }
let wave_alloc_width = if ex.stage == Stage::Pixel || ex.stage == Stage::Compute {
wave_alloc::prepare(&mut insns, ex.stage)?
} else {
None
};
let reflection = reflection_compact::prepare(ex, &mut insns);
group_extrema::prepare_exchanges(ex, &mut insns)?;
let group_extrema = group_extrema::prepare(ex, &mut insns);
Expand All @@ -163,6 +167,18 @@ pub(in crate::hlsl) fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Opti
fspx_wave.filter(|&width| width == 32)
} else if straight_exchange { None }
else { lower_wave_reductions(&mut insns)? };
// A masked DPP prefix/total scan is a whole-wave collective: the host wave must
// match the guest wave width (32 or 64 lanes). Only compute shaders need this
// constraint — a pixel is a wave of its own.
let required_wave_size = if ex.stage == Stage::Compute {
match (required_wave_size, wave_alloc_width) {
(None, w) => w,
(Some(a), Some(b)) if a != b => return Err("conflicting wave widths for wave allocation and reduction".into()),
(a, _) => a,
}
} else {
required_wave_size
};
let required_wave_size = if resolve_wave32 {
if matches!(required_wave_size, Some(64)) || insns.iter().any(is_quad_exchange) {
return Err("resolve Wave32 requires a compatible wave reduction".into());
Expand Down Expand Up @@ -348,7 +364,23 @@ pub(in crate::hlsl) fn translate_outputs_once(ex: &ShaderExtract, feeds_ps: Opti
Err(reason) => {
let ordinary = ex.stage == Stage::Compute && !em.wave_cull && !em.page_waves
&& !em.resolve_wave32 && !lone_lane::on();
em.lockstep = Some(ordinary.then(|| lockstep::prove(&em.insns, width)).flatten().ok_or(reason)?);
if !ordinary {
return Err(reason);
}
match lockstep::prove(&em.insns, width) {
Some(votes) => em.lockstep = Some(votes),
None => {
// Lockstep cannot prove this program; lower the totals that
// wave_sum rejects on control flow to WaveActiveSum, a
// whole-wave op that is safe in divergent control flow, and
// re-validate the reductions that remain.
wave_alloc::lower_problematic_totals(&mut em.insns, width)?;
match wave_sum::check_control_flow(&em.insns, width) {
Ok(guards) => em.reduction_execz_guards = guards,
Err(reason) => return Err(reason),
}
}
}
}
}
let [x, y, z] = compute_group(ex);
Expand Down
Loading
Loading