From 551708c42ba15bb8eddc4b5fc4be97bf5d7a7c91 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 27 Nov 2026 13:49:36 +0000 Subject: [PATCH 1/4] shader: lower pixel structured-to-raw buffer loads Track the structured-to-raw descriptor conversion in a pixel stage and lower a non-indexed buffer load as a raw byte-address read bounded by the converted byte count. Co-authored-by: SimSalabimse --- CMakeLists.txt | 10 + docs/experiments.md | 11 + .../startup_gfx2hlsl_ps_raw_descriptor.txt | 1 + tests/desktop_gpu.h | 5 + tests/offscreen_check.cpp | 29 +++ tests/startup_flat_param.cpp | 121 +++++++++ ...tartup_gfx2hlsl_ps_raw_descriptor_check.py | 246 ++++++++++++++++++ tools/startup/gfx2hlsl.py | 50 +++- 8 files changed, 467 insertions(+), 6 deletions(-) create mode 100644 tests/checks/python-linux/startup_gfx2hlsl_ps_raw_descriptor.txt create mode 100644 tests/startup_gfx2hlsl_ps_raw_descriptor_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 31a51f2c82..6247a23879 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3771,6 +3771,16 @@ if(EXISTS "${INTAKE_PYTHON}") # Vertex-stage buffer stores lower to RWByteAddressBuffer Store* under manifest version 2 (#1723). add_test(NAME startup_gfx2hlsl_buffer_store COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_buffer_store_check.py") + # Pixel-stage structured-to-raw buffer loads: translation controls, then a one-pixel draw on WARP and hardware. + add_test(NAME startup_gfx2hlsl_ps_raw_descriptor COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_gfx2hlsl_ps_raw_descriptor_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py" draw + "${DXC_EXECUTABLE}" "$" ${adapter} + $<$:${STARTUP_FXC}>) + set_tests_properties(startup_gfx2hlsl_ps_raw_descriptor_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + endforeach() # Output modifiers on float-result conversions (#1705). add_test(NAME startup_gfx2hlsl_vcvt_omod COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_vcvt_omod_check.py") diff --git a/docs/experiments.md b/docs/experiments.md index 31f0e9db7d..162a5a7c9e 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -402,6 +402,17 @@ The descriptor modifications that compute buffer stores accept are accepted here ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_buffer_store$' --output-on-failure ``` +## Pixel structured-to-raw buffer loads + +A non-indexed `buffer_load_dword` in a pixel stage lowers a descriptor that went through the structured-to-raw conversion. The conversion is the one compute and vertex stores already record: `s_bfe_u32` of DW1 with `0xe0010` (optionally `s_max_u32` with 1), `s_and_b32` of DW1 with `0xc000ffff`, `s_mul_i32` of DW2 by that stride, then `s_and_b32` of DW3 with `0xcfffffff` and `s_or_b32` with `0x30000000`. The four words are tracked in the pixel stage the same way. The load is a raw byte-address read. Each dword is kept when its end byte is at or before the 32-bit product `NUM_RECORDS * stride` (`NUM_RECORDS * max(stride, 1)` when the extract was clamped); a wrapped address reads as zero. The entry constants are that view's `stride` and `numrecords`. The graphics stand-in fills `stride` and does not yet publish `numrecords`, so a completed pipeline still needs that constant before a draw applies the bound. The offscreen fixture supplies both and compares the pixel with a CPU model of the same product. An in-place word rewrite, a conversion missing the byte-count multiply or the raw out-of-range step, and an `idxen` load stay refused (`buffer load through a modified descriptor`, or `indexed load through a modified descriptor` for `idxen`). + +```powershell +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_ps_raw_descriptor$' --output-on-failure +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_ps_raw_descriptor_(warp|hardware)$' --output-on-failure +``` + +The draw runs on the Windows test PC. A capability skip (77) is separate from a pass. + ## Shared-exponent target stand-in `startup_packed_target` checks the selection rule with synthetic format support diff --git a/tests/checks/python-linux/startup_gfx2hlsl_ps_raw_descriptor.txt b/tests/checks/python-linux/startup_gfx2hlsl_ps_raw_descriptor.txt new file mode 100644 index 0000000000..35601c5307 --- /dev/null +++ b/tests/checks/python-linux/startup_gfx2hlsl_ps_raw_descriptor.txt @@ -0,0 +1 @@ +tests/startup_gfx2hlsl_ps_raw_descriptor_check.py diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index a49d48dd87..7f28a71584 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -38,6 +38,11 @@ void check_startup_flat_param(ID3D12Device* device, const char* vertex_path, con std::uint32_t* words, UINT width = 1, UINT height = 1, D3D12_CULL_MODE cull = D3D12_CULL_MODE_NONE, BOOL front_ccw = FALSE, UINT vertices = 3, const std::uint32_t* constants = nullptr); +// One pixel. The pixel stage reads t0 as a raw buffer (a descriptor table) and b0 as entry constants. +// source_dwords is the number of 32-bit elements in the raw view; the readback is the four exported words. +void check_startup_raw_buffer(ID3D12Device* device, const char* vertex_path, const char* pixel_path, + const std::uint32_t* constants, UINT constant_count, + const std::uint32_t* source, UINT source_dwords, std::uint32_t words[4]); void check_startup_entry_words(ID3D12Device* device, const char* vertex_path, const char* pixel_path, const std::uint32_t* entry, UINT entry_count, std::uint32_t* words, UINT width = 1, UINT height = 1); diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index 72ab9bc6f4..fe1b3b2cf6 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -1583,6 +1583,34 @@ OperationResult run_startup_flat_param(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } +static std::vector parse_hex_words(std::string_view text); + +// --startup-raw-buffer : draws one pixel whose +// pixel stage reads a raw buffer at t0 (a descriptor table) and entry constants at b0. and +// are comma-separated 8-digit hex words. is the four words the target must hold. +OperationResult run_startup_raw_buffer(const OperationContext& ctx) +{ + const auto constants = parse_hex_words(ctx.argv[5]); + const auto source = parse_hex_words(ctx.argv[6]); + const auto expected = parse_hex_words(ctx.argv[7]); + if (constants.empty() || constants.size() > 64) + return {OutcomeKind::fail, "entry constants are not 1..64 hex words"}; + if (source.empty() || source.size() > 4096) + return {OutcomeKind::fail, "source buffer is not 1..4096 hex words"}; + if (expected.size() != 4) + return {OutcomeKind::fail, "expected value is not four hex words"}; + std::uint32_t words[4]{}; + check_startup_raw_buffer(ctx.device, ctx.argv[3], ctx.argv[4], constants.data(), UINT(constants.size()), + source.data(), UINT(source.size()), words); + if (std::memcmp(words, expected.data(), sizeof(words)) != 0) { + std::fprintf(stderr, "startup_raw_buffer mismatch expected=%08x,%08x,%08x,%08x " + "actual=%08x,%08x,%08x,%08x\n", + expected[0], expected[1], expected[2], expected[3], words[0], words[1], words[2], words[3]); + return {OutcomeKind::fail, "raw buffer readback differs"}; + } + return {OutcomeKind::pass, nullptr}; +} + // Comma-separated 8-digit hex words, in order. An empty list or any other shape returns nothing. static std::vector parse_hex_words(std::string_view text) { @@ -1749,6 +1777,7 @@ const OperationSpec kOperations[] = { {"--startup-packed-position", 5, 5, nullptr, kNoGate, run_startup_packed_position}, {"--startup-sharedexp-target", 3, 3, nullptr, kNoGate, run_startup_sharedexp_target}, {"--startup-flat-param", 6, 7, nullptr, kNoGate, run_startup_flat_param}, + {"--startup-raw-buffer", 8, 8, nullptr, kNoGate, run_startup_raw_buffer}, {"--startup-entry-words", 7, 7, nullptr, kNoGate, run_startup_entry_words}, {"--startup-pixel-words", 8, 8, validate_pixel_words_args, kNoGate, run_startup_pixel_words}, {"--raster-reference", 10, 10, validate_raster_args, kNoGate, run_startup_pixel_words}, diff --git a/tests/startup_flat_param.cpp b/tests/startup_flat_param.cpp index 7c92eb02b8..c59b0261c1 100644 --- a/tests/startup_flat_param.cpp +++ b/tests/startup_flat_param.cpp @@ -125,3 +125,124 @@ void check_startup_flat_param(ID3D12Device* device, const char* vertex_path, con readback->Unmap(0, &none); std::printf("startup_flat_param words=%08x,%08x,%08x,%08x\n", words[0], words[1], words[2], words[3]); } + +void check_startup_raw_buffer(ID3D12Device* device, const char* vertex_path, const char* pixel_path, + const std::uint32_t* constants, UINT constant_count, + const std::uint32_t* source, UINT source_dwords, std::uint32_t words[4]) +{ + if (constant_count < 1 || constant_count > 64) + throw std::runtime_error("raw buffer draw needs 1..64 entry constants"); + if (source_dwords < 1 || source_dwords > 4096) + throw std::runtime_error("raw buffer draw needs 1..4096 source dwords"); + const auto vs = read_blob(vertex_path); + const auto ps = read_blob(pixel_path); + + D3D12_DESCRIPTOR_RANGE range{}; + range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; + range.NumDescriptors = 1; + range.BaseShaderRegister = 0; + range.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND; + D3D12_ROOT_PARAMETER params[2]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants = {0, 0, constant_count}; + params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[1].DescriptorTable = {1, &range}; + params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL; + D3D12_ROOT_SIGNATURE_DESC rs{}; + rs.NumParameters = 2; + rs.pParameters = params; + ComPtr signature, errors; + if (FAILED(D3D12SerializeRootSignature(&rs, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &errors))) + throw std::runtime_error(errors ? static_cast(errors->GetBufferPointer()) + : "Serialize raw buffer root signature"); + ComPtr root; + check(device->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&root)), + "Create raw buffer root signature"); + + D3D12_GRAPHICS_PIPELINE_STATE_DESC pd{}; + pd.pRootSignature = root.Get(); + pd.VS = {vs.data(), vs.size()}; + pd.PS = {ps.data(), ps.size()}; + pd.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pd.SampleMask = UINT_MAX; + pd.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pd.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pd.RasterizerState.DepthClipEnable = TRUE; + pd.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + pd.NumRenderTargets = 1; + pd.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + pd.SampleDesc.Count = 1; + ComPtr pipeline; + check(device->CreateGraphicsPipelineState(&pd, IID_PPV_ARGS(&pipeline)), "Create raw buffer PSO"); + + D3D12_RESOURCE_DESC rd{}; + rd.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rd.Width = 1; + rd.Height = 1; + rd.DepthOrArraySize = 1; + rd.MipLevels = 1; + rd.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + rd.SampleDesc.Count = 1; + rd.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + const D3D12_CLEAR_VALUE clear{DXGI_FORMAT_R32G32B32A32_FLOAT, {-1.0f, -1.0f, -1.0f, -1.0f}}; + const auto target = resource(device, rd, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_RENDER_TARGET, &clear); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 readback_size = 0; + device->GetCopyableFootprints(&rd, 0, 1, 0, &footprint, nullptr, nullptr, &readback_size); + const auto readback = make_buffer(device, readback_size, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + + const auto input = make_buffer(device, UINT64(source_dwords) * sizeof(std::uint32_t), D3D12_HEAP_TYPE_UPLOAD, + D3D12_RESOURCE_STATE_GENERIC_READ); + void* upload = nullptr; + check(input->Map(0, nullptr, &upload), "Map raw buffer upload"); + std::memcpy(upload, source, UINT64(source_dwords) * sizeof(std::uint32_t)); + input->Unmap(0, nullptr); + D3D12_DESCRIPTOR_HEAP_DESC views_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr views; + check(device->CreateDescriptorHeap(&views_desc, IID_PPV_ARGS(&views)), "Create raw buffer SRV heap"); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Buffer.NumElements = source_dwords; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + device->CreateShaderResourceView(input.Get(), &srv, views->GetCPUDescriptorHandleForHeapStart()); + + D3D12_DESCRIPTOR_HEAP_DESC rtv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}; + ComPtr rtvs; + check(device->CreateDescriptorHeap(&rtv_desc, IID_PPV_ARGS(&rtvs)), "Create raw buffer RTV heap"); + const auto rtv = rtvs->GetCPUDescriptorHandleForHeapStart(); + device->CreateRenderTargetView(target.Get(), nullptr, rtv); + + ComputeCommands commands(device, pipeline.Get(), D3D12_COMMAND_LIST_TYPE_DIRECT); + auto* list = commands.list.Get(); + list->ClearRenderTargetView(rtv, clear.Color, 0, nullptr); + list->SetGraphicsRootSignature(root.Get()); + ID3D12DescriptorHeap* heaps[] = {views.Get()}; + list->SetDescriptorHeaps(1, heaps); + list->SetGraphicsRoot32BitConstants(0, constant_count, constants, 0); + list->SetGraphicsRootDescriptorTable(1, views->GetGPUDescriptorHandleForHeapStart()); + const D3D12_VIEWPORT viewport{0, 0, 1, 1, 0, 1}; + const D3D12_RECT scissor{0, 0, 1, 1}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->DrawInstanced(3, 1, 0, 0); + transition(list, target.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION out{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + out.PlacedFootprint = footprint; + D3D12_TEXTURE_COPY_LOCATION in{target.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + list->CopyTextureRegion(&out, 0, 0, 0, &in, nullptr); + commands.submit_and_wait(device); + + void* mapped = nullptr; + const D3D12_RANGE read{0, static_cast(readback_size)}; + const D3D12_RANGE none{0, 0}; + check(readback->Map(0, &read, &mapped), "Map raw buffer readback"); + std::memcpy(words, static_cast(mapped) + footprint.Offset, 4 * sizeof(*words)); + readback->Unmap(0, &none); + std::printf("startup_raw_buffer words=%08x,%08x,%08x,%08x\n", words[0], words[1], words[2], words[3]); +} diff --git a/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py b/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py new file mode 100644 index 0000000000..8137f80f76 --- /dev/null +++ b/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py @@ -0,0 +1,246 @@ +"""Pixel-stage structured-to-raw buffer loads in tools/startup/gfx2hlsl.py. + + (no arguments) translation controls and the CPU model, pure Python + draw [fxc] + translate, compile and draw one pixel. The readback must match the + CPU model of a raw byte-address load bounded by NUM_RECORDS * stride. + Dropping that bound must read the word past the bound. + +The fixture is source-built. A pixel stage loads one table descriptor, clears its stride, scales NUM_RECORDS +by the extracted stride and sets OOB_SELECT to raw, then reads four dwords with buffer_load_dword offen. +""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parent / 'tools' / 'startup')) +import gfx2hlsl as G # noqa: E402 + +MODIFIED = 'buffer load through a modified descriptor' +INDEXED = 'indexed load through a modified descriptor' +STRIDE = 8 +RECORDS = 4 +# Nine words the resource holds, then padding so the raw view's element count is a multiple of four. +# Word 8 sits past the converted byte count (8 * 4 = 32) and must read back as zero. +SOURCE = (0x3f800000, 0x40000000, 0x40400000, 0x40800000, 0x40a00000, 0x40c00000, 0x40e00000, 0x41000000, + 0xdeadbeef, 0, 0, 0) +OFFSETS = (0, 12, 28, 32) +DESC = 16 +TMP = 20 + +SOP2 = {'s_and_b32': 0x0e, 's_or_b32': 0x10, 's_max_u32': 0x09, 's_mul_i32': 0x26, 's_bfe_u32': 0x27} + +# One descriptor table. Graphics user data starts at s8; the pixel stage loads s[16:19] from that pointer. +RTS0 = b''.join((struct.pack('<6I', 2, 1, 24, 0, 0, 0), struct.pack('<3I', 0, 0, 36), + struct.pack('<2I', 1, 44), struct.pack('<6I', 0, 1, 0, 0, 0, 0))) +PART = b'RTS0' + struct.pack(' limit: + return 0 + return SOURCE[address // 4] + + +def expected_words(): + return tuple(cpu_load(offset) for offset in OFFSETS) + + +def ud_index(manifest, kind): + found = [int(line.split()[1]) for line in manifest.splitlines() + if line.startswith('udsrc ') and line.split()[2] == kind] + if len(found) != 1: + raise AssertionError('udsrc %s: %s' % (kind, manifest)) + return found[0] + + +def must_refuse(label, ps, message): + try: + translate(ps) + except G.Unsupported as error: + if str(error) != message: + raise AssertionError('%s: refused with %r, expected %r' % (label, str(error), message)) + print('%s: refused (%s)' % (label, message)) + return + raise AssertionError('%s: translated' % label) + + +def controls(): + pipe = translate(program(conversion())) + ps, manifest = pipe.hlsl_ps(), pipe.manifest() + stride, records = ud_index(manifest, 'stride'), ud_index(manifest, 'numrecords') + assert 'ByteAddressBuffer r0 : register(t0);' in ps, ps + assert 'srv 0 buf table 0 0' in manifest, manifest + limit = '{ uint lim = ud%d * ud%d;' % (stride, records) + for index, offset in enumerate(OFFSETS): + # The immediate is part of the address. A one-dword load then reads a + 0 inside the bound. + line = 'v%d = (a + 4u >= a && a + 4u <= lim) ? r0.Load(a + 0) : 0u;' % (1 + index) + assert limit in ps and ('a = v0 + %d;' % offset) in ps and line in ps, ps + print('raw conversion: four offen loads bounded by ud%d * ud%d' % (stride, records)) + + clamped = translate(program(conversion(clamp=True))) + cps, cmanifest = clamped.hlsl_ps(), clamped.manifest() + cstride, crecords = ud_index(cmanifest, 'stride'), ud_index(cmanifest, 'numrecords') + assert '{ uint lim = max(ud%d, 1u) * ud%d;' % (cstride, crecords) in cps, cps + print('clamped raw conversion: bound is max(stride, 1) * NUM_RECORDS') + + stride0 = program(sop2('s_and_b32', DESC + 1, DESC + 1, 255, 0xc000ffff)) + text = translate(stride0).hlsl_ps() + assert 'v1 = r0.Load(a + 0);' in text and 'uint lim' not in text, text + print('stride clear only: unbounded raw load') + + missing_count = (sop2('s_bfe_u32', TMP, DESC + 1, 255, 0xe0010) + + sop2('s_and_b32', DESC + 1, DESC + 1, 255, 0xc000ffff) + + sop2('s_and_b32', DESC + 3, DESC + 3, 255, 0xcfffffff) + + sop2('s_or_b32', DESC + 3, DESC + 3, 255, 0x30000000)) + missing_oob = (sop2('s_bfe_u32', TMP, DESC + 1, 255, 0xe0010) + + sop2('s_and_b32', DESC + 1, DESC + 1, 255, 0xc000ffff) + + sop2('s_mul_i32', DESC + 2, DESC + 2, TMP)) + must_refuse('missing byte count', program(missing_count), MODIFIED) + must_refuse('missing OOB step', program(missing_oob), MODIFIED) + must_refuse('in-place word rewrite', program(sop2('s_and_b32', DESC + 2, DESC + 2, 128)), MODIFIED) + must_refuse('idxen load', program(conversion(), idxen=True), INDEXED) + + model = expected_words() + assert model == (SOURCE[0], SOURCE[3], SOURCE[7], 0), model + assert cpu_load(32, stride=0, records=4) == 0 + assert cpu_load(0xffffffff) == 0 + print('CPU model: %s' % ','.join('%08x' % word for word in model)) + + +def compile_hlsl(compiler, kind, source, out, profile, directory): + path = directory / ('%s.hlsl' % out) + path.write_text(source, encoding='ascii') + if kind == 'fxc': + args = [compiler, '/nologo', '/T', profile, '/E', 'main', '/Fo', str(directory / ('%s.cso' % out)), str(path)] + else: + args = [compiler, '-T', profile, '-E', 'main', '-Fo', str(directory / ('%s.cso' % out)), str(path)] + subprocess.run(args, check=True, capture_output=True, text=True) + return directory / ('%s.cso' % out) + + +def entry_constants(manifest): + count = int(next(line.split()[1] for line in manifest.splitlines() if line.startswith('ud '))) + words = [0] * count + words[ud_index(manifest, 'stride')] = STRIDE + words[ud_index(manifest, 'numrecords')] = RECORDS + return words + + +def draw_once(renderer, adapter, vs, ps, constants, expected): + args = [renderer, adapter, '--startup-raw-buffer', str(vs), str(ps), + ','.join('%08x' % word for word in constants), + ','.join('%08x' % word for word in SOURCE), + ','.join('%08x' % word for word in expected)] + run = subprocess.run(args, capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout + run.stderr) + raise SystemExit(77) + return run + + +def check_draw(dxc, renderer, adapter, fxc=None): + pipe = translate(program(conversion())) + translated, manifest = pipe.hlsl_ps(), pipe.manifest() + constants = entry_constants(manifest) + expected = expected_words() + unbound = translated.replace('a + 4u <= lim', 'a + 4u <= 0xffffffffu') + assert unbound != translated + compilers = [('dxc', dxc, 'vs_6_0', 'ps_6_0')] + ([('fxc', fxc, 'vs_5_1', 'ps_5_1')] if fxc else []) + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + for kind, compiler, vs_profile, ps_profile in compilers: + vs = compile_hlsl(compiler, kind, FULLSCREEN_VS, 'vs_%s' % kind, vs_profile, directory) + ps = compile_hlsl(compiler, kind, translated, 'ps_%s' % kind, ps_profile, directory) + run = draw_once(renderer, adapter, vs, ps, constants, expected) + if run.returncode: + raise AssertionError('%s\n%s\n%s' % (kind, run.stdout, run.stderr)) + print('%s: readback %s' % (kind, ','.join('%08x' % word for word in expected))) + mutant = compile_hlsl(compiler, kind, unbound, 'ps_unbound_%s' % kind, ps_profile, directory) + failed = draw_once(renderer, adapter, vs, mutant, constants, expected) + if failed.returncode == 0 or 'deadbeef' not in failed.stderr: + raise AssertionError('%s unbound control\n%s\n%s' % (kind, failed.stdout, failed.stderr)) + print('%s: dropping the bound reads the word past NUM_RECORDS * stride' % kind) + + +def main(): + if len(sys.argv) == 1: + controls() + return + mode, *args = sys.argv[1:] + if mode == 'draw': + controls() + check_draw(*args) + return + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 3382f7a845..392d3424ae 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -966,7 +966,9 @@ def raw_descriptor_alu(base, syms, constants): return ('descnum', 'stride', word) if plain and field == 2 and base == 's_mul_i32': if syms[other] in (('descnum', kind, desc_word(word, word[3] - 1)) for kind in ('stride', 'stride_min1')): - return word + ('byte_count',) + # The clamp (s_max_u32 with 1) makes a stride of 0 count as one byte per record. The extra tag is + # how a pixel load bounds the read by that product; stores accept either tag. + return word + (('byte_count', 'min1') if syms[other][1] == 'stride_min1' else ('byte_count',)) if field == 3: if plain and base == 's_and_b32' and constants[other] == 0xcfffffff: return word + ('oob0',) @@ -975,6 +977,17 @@ def raw_descriptor_alu(base, syms, constants): return None +def raw_conversion_shapes(loaded): + """The two four-word forms of one descriptor load after the structured-to-raw conversion. + + Word 1 has its stride cleared, word 2 is the byte count (the plain product, or the product after the stride + was clamped to at least 1), and word 3 selects raw out-of-range behavior.""" + cleared = loaded[1] + ('stride0',) + oob = loaded[3] + ('oob3',) + return ((loaded[0], cleared, loaded[2] + ('byte_count',), oob), + (loaded[0], cleared, loaded[2] + ('byte_count', 'min1'), oob)) + + def smem_offset(tok): """The SMEM offset operand as a token: 'off' (no offset operand) is the literal 0, anything else unchanged.""" return '0' if tok == 'off' else tok @@ -5722,7 +5735,7 @@ def src_sym(t): d = dst[1] own = self.sym.get(d) raw = (raw_descriptor_alu(base, syms, [self.const_u32(t) for t in srcs]) - if getattr(self, 'kind', None) in ('cs', 'vs') and len(syms) == 2 else None) + if getattr(self, 'kind', None) in ('cs', 'vs', 'ps') and len(syms) == 2 else None) if base in ('s_mov_b32', 's_mov_b64'): self.sym[d] = syms[0] if pair: @@ -6850,8 +6863,24 @@ def op_buffer_load_dword(self, ops, mods, count=1): dst = reg_range(ops[0]) buf, address = self.buffer_address(ops, mods) self.emit('a = %s;' % address) - for i in range(count): - self.set_v(dst[1] + i, '%s.Load(a + %d)' % (buf, 4 * i)) + # A pixel load through the full conversion is a raw byte-address read. The hardware compares the address + # against the converted NUM_RECORDS, which is the 32-bit product of the original record count and stride + # (at least 1 when the extract was clamped). The entry constants are that view's stride and record count. + bound = getattr(self, 'raw_load_bound', None) if getattr(self, 'kind', None) == 'ps' else None + if bound: + index = self.pipe.resources[bound[0]]['index'] + stride = self.pipe.ud(('stride', index)) + records = self.pipe.ud(('numrecords', index)) + factor = 'max(ud%d, 1u)' % stride if bound[1] else 'ud%d' % stride + self.emit('{ uint lim = %s * ud%d;' % (factor, records)) + for i in range(count): + end = 4 * (i + 1) + self.set_v(dst[1] + i, + '(a + %du >= a && a + %du <= lim) ? %s.Load(a + %d) : 0u' % (end, end, buf, 4 * i)) + self.emit('}') + else: + for i in range(count): + self.set_v(dst[1] + i, '%s.Load(a + %d)' % (buf, 4 * i)) def op_buffer_load_dwordx2(self, ops, mods): self.op_buffer_load_dword(ops, mods, 2) @@ -6984,7 +7013,10 @@ def load_descriptor(self, tok, what, *, stride0_ok=False, raw_conversion_ok=Fals and word 3 OOB_SELECT set to raw mode (`oob3` via 0x30000000). Permitted when the load is non-indexed and the resulting byte range is validated. Any other scalar ALU modifications or unproven overwrites raise Unsupported. + A pixel-stage load that matches the full conversion records raw_load_bound so the read can be limited + to the converted byte count. """ + self.raw_load_bound = None key = self.descriptor(tok) rsrc = reg_range(tok) first = self.sym.get(rsrc[1]) if rsrc and rsrc[0] == 's' and rsrc[2] - rsrc[1] == 3 else None @@ -6996,7 +7028,13 @@ def load_descriptor(self, tok, what, *, stride0_ok=False, raw_conversion_ok=Fals cleared = loaded[1] + ('stride0',) valid = valid or actual == (loaded[0], cleared, *loaded[2:]) if not valid and raw_conversion_ok: - valid = actual == (loaded[0], cleared, loaded[2] + ('byte_count',), loaded[3] + ('oob3',)) + shapes = raw_conversion_shapes(loaded) + if actual == shapes[0]: + valid = True + self.raw_load_bound = (key, False) + elif actual == shapes[1]: + valid = True + self.raw_load_bound = (key, True) if (not valid or key in getattr(self.pipe, 'other_modified', ()) or (key in getattr(self.pipe, 'modified', ()) and not stride0_ok)): raise Unsupported('%s through a modified descriptor' % what) @@ -7017,7 +7055,7 @@ def store_descriptor(self, tok, words, what, stride0_ok=False, raw_conversion_ok cleared = loaded[1] + ('stride0',) valid = valid or actual == (loaded[0], cleared, *loaded[2:]) if not valid and raw_conversion_ok: - valid = actual == (loaded[0], cleared, loaded[2] + ('byte_count',), loaded[3] + ('oob3',)) + valid = actual in raw_conversion_shapes(loaded) if (not valid or key in getattr(self.pipe, 'other_modified', ()) or (key in getattr(self.pipe, 'modified', ()) and not stride0_ok)): raise Unsupported('%s through a modified descriptor' % what) From 327d134caac0a5d04272244da19ff1e1e676d387 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 27 Nov 2026 22:50:52 +0000 Subject: [PATCH 2/4] shader: keep pixel raw buffer loads inside the converted count A pixel load through the structured-to-raw conversion adds each address term with an overflow check before the range compare. A typed buffer load through that descriptor stays refused. The draw stand-in stores numrecords from dword 2 of the table descriptor and refuses an unknown udsrc line. Co-authored-by: SimSalabimse --- docs/experiments.md | 2 +- src/startup_stubs/d3d12_draw.inl | 42 +-- src/startup_stubs/udsrc_line.h | 55 ++++ ...tartup_gfx2hlsl_ps_raw_descriptor_check.py | 244 +++++++++++++++--- tools/startup/gfx2hlsl.py | 22 +- 5 files changed, 313 insertions(+), 52 deletions(-) create mode 100644 src/startup_stubs/udsrc_line.h diff --git a/docs/experiments.md b/docs/experiments.md index 4278e7224e..133c675396 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -413,7 +413,7 @@ ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_buffer_store$' --outpu ## Pixel structured-to-raw buffer loads -A non-indexed `buffer_load_dword` in a pixel stage lowers a descriptor that went through the structured-to-raw conversion. The conversion is the one compute and vertex stores already record: `s_bfe_u32` of DW1 with `0xe0010` (optionally `s_max_u32` with 1), `s_and_b32` of DW1 with `0xc000ffff`, `s_mul_i32` of DW2 by that stride, then `s_and_b32` of DW3 with `0xcfffffff` and `s_or_b32` with `0x30000000`. The four words are tracked in the pixel stage the same way. The load is a raw byte-address read. Each dword is kept when its end byte is at or before the 32-bit product `NUM_RECORDS * stride` (`NUM_RECORDS * max(stride, 1)` when the extract was clamped); a wrapped address reads as zero. The entry constants are that view's `stride` and `numrecords`. The graphics stand-in fills `stride` and does not yet publish `numrecords`, so a completed pipeline still needs that constant before a draw applies the bound. The offscreen fixture supplies both and compares the pixel with a CPU model of the same product. An in-place word rewrite, a conversion missing the byte-count multiply or the raw out-of-range step, and an `idxen` load stay refused (`buffer load through a modified descriptor`, or `indexed load through a modified descriptor` for `idxen`). +A non-indexed `buffer_load_dword` in a pixel stage lowers a descriptor that went through the structured-to-raw conversion. The conversion is the one compute and vertex stores already record: `s_bfe_u32` of DW1 with `0xe0010` (optionally `s_max_u32` with 1), `s_and_b32` of DW1 with `0xc000ffff`, `s_mul_i32` of DW2 by that stride, then `s_and_b32` of DW3 with `0xcfffffff` and `s_or_b32` with `0x30000000`. The four words are tracked in the pixel stage the same way. The load is a raw byte-address read. Each dword is kept when its end byte is at or before the 32-bit product `NUM_RECORDS * stride` (`NUM_RECORDS * max(stride, 1)` when the extract was clamped); a wrapped address reads as zero. The entry constants are that view's `stride` and `numrecords`. The graphics stand-in fills `stride` from DW1 and `numrecords` from DW2 of a table buffer descriptor. An unknown `udsrc` kind refuses the translation, so a later line is not dropped while the shader still runs. Each address term is added with an overflow check before the range compare, so a sum that wraps is zero even when the truncated address would have landed in range. A `dwordx2` or `dwordx4` that crosses the product keeps the in-range dwords and zeroes the rest. A stride of 0 makes the product 0. A non-zero `soffset` is another term of the same sum. The conversion may run on an `s_mov` copy of the loaded words. A typed `tbuffer_load_format` through the converted descriptor stays refused. The offscreen fixture compares one pixel with a CPU model of the same product. A word overwritten by anything other than this conversion, a conversion missing the byte-count multiply or the raw out-of-range step, a stride taken from a different descriptor, and an `idxen` load stay refused (`buffer load through a modified descriptor`, or `indexed load through a modified descriptor` for `idxen`). An address that is not a multiple of four is not refused. DW1 swizzle, `ADD_TID` and the DW3 format field are kept and not checked. ```powershell ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_ps_raw_descriptor$' --output-on-failure diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 2b0bacd23e..d2c77dcbd3 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -10,6 +10,7 @@ // upload ring / a private descriptor heap. #include "startup_stubs/typed_uav_load.h" +#include "startup_stubs/udsrc_line.h" // A pixel-stage image store (#1996 item F, #2742): tools/startup/gfx2hlsl.py writes 'uav N tex2d|tex2da table P O' // for the RWTexture2D or RWTexture2DArray at u, whose descriptor is at byte O of the title's @@ -154,7 +155,11 @@ const char* pixel_uav_view(ID3D12Device* device, const D3D12_RESOURCE_DESC& reso struct Translation { struct Srv { int kind, source, a, b; }; // kind 0 buffer, 1 2D texture, 2 2D array, 3 3D texture, 4 1D texture; source 0 table(param a, byte b), 1 vertex stream a, 2 root parameter a - enum UdKind { rect, base_vertex, start_instance, root_constant, stride, mrt_bits, d16_unorm16, desc_word3 }; + enum UdKind { + rect = udsrc_rect, base_vertex = udsrc_base_vertex, start_instance = udsrc_start_instance, + root_constant = udsrc_root_constant, stride = udsrc_stride, mrt_bits = udsrc_mrt_bits, + d16_unorm16 = udsrc_d16_unorm16, desc_word3 = udsrc_desc_word3, num_records = udsrc_num_records + }; struct Ud { int kind, a, b; }; int state = 0; // 1 ready, 2 unavailable x2w_startup::ManifestRetry manifest_retry; // Only an absent manifest can become ready on a later draw. @@ -419,6 +424,7 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) const bool previously_missing = tr.manifest_retry.pending(); tr.manifest_retry.found(); bool matched_rtv = false; + UdSrcParsed udsrc; for (std::size_t at = 0; at < manifest.size();) { std::size_t end = manifest.find('\n', at); if (end == std::string::npos) end = manifest.size(); @@ -438,17 +444,13 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) // so a translation whose stores would be silently skipped is never drawn (#1723). log("x2w-draw unsupported manifest version for %016llx", tr.key); return; - } else if (std::sscanf(line.c_str(), "udsrc %d %15s %d %d", &i, source, &x, &y) >= 2) { - Translation::Ud ud{-1, x, y}; - if (!std::strcmp(source, "rect")) ud.kind = Translation::rect; - else if (!std::strcmp(source, "basevertex")) ud.kind = Translation::base_vertex; - else if (!std::strcmp(source, "startinstance")) ud.kind = Translation::start_instance; - else if (!std::strcmp(source, "rootconst")) ud.kind = Translation::root_constant; - else if (!std::strcmp(source, "stride")) ud.kind = Translation::stride; - else if (!std::strcmp(source, "d16unorm16") && x >= 0 && x < 32) ud.kind = Translation::d16_unorm16; - else if (!std::strcmp(source, "descword3")) ud.kind = Translation::desc_word3; - else if (!std::strcmp(source, "mrtbits") && !rtv_request.empty()) ud.kind = Translation::mrt_bits; - if (static_cast(i) == tr.uds.size() && ud.kind >= 0) tr.uds.push_back(ud); + } else if (!accept_udsrc_line(line.c_str(), static_cast(tr.uds.size()), !rtv_request.empty(), &udsrc)) { + // An unknown kind or a gap used to be skipped. The shader's constant slot then read 0, and every + // udsrc after the gap was skipped too because its index no longer matched the next slot. + log("x2w-draw unsupported udsrc for %016llx: %s", tr.key, line.c_str()); + return; + } else if (udsrc.is_udsrc) { + tr.uds.push_back({udsrc.kind, udsrc.a, udsrc.b}); } else if (std::sscanf(line.c_str(), "srv %d %15s %15s %d %d", &i, kind, source, &x, &y) >= 4) { const int texture_kind = !std::strcmp(kind, "tex2d") ? 1 : !std::strcmp(kind, "tex2da") ? 2 : !std::strcmp(kind, "tex3d") ? 3 : !std::strcmp(kind, "tex1d") ? 4 : 0; @@ -2069,6 +2071,8 @@ bool indirect_shader_entry(ID3DBlob* blob, const Translation& translation, bool if (ud.kind == Translation::stride && ud.a >= 0 && static_cast(ud.a) < translation.srvs.size() && (translation.srvs[ud.a].source == 0 || (indexed && translation.srvs[ud.a].source == 1)) && translation.srvs[ud.a].kind == 0) continue; + if (ud.kind == Translation::num_records && ud.a >= 0 && static_cast(ud.a) < translation.srvs.size() && + translation.srvs[ud.a].source == 0 && translation.srvs[ud.a].kind == 0) continue; if (ud.kind != Translation::root_constant && ud.kind != Translation::rect && ud.kind != Translation::d16_unorm16) return false; } @@ -2251,6 +2255,7 @@ struct IndirectBufferView { ID3D12Resource* resource = nullptr; u64 offset = 0, bytes = 0; UINT stride = 0; + UINT records = 0; bool upload = false; }; @@ -2266,7 +2271,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor return IndirectBufferView{}; }; u64 address = 0, offset = 0, bytes = 0; - UINT stride = 0; + UINT stride = 0, records = 0; const Wrapper* owner = nullptr; bool own_memory = false; if (why) *why = nullptr; @@ -2315,6 +2320,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor } else { address = words[0] | (u64{words[1] & 0xffff} << 32); stride = (words[1] >> 16) & 0x3fff; + records = words[2]; bytes = u64{stride ? stride : 1} * words[2]; } if (!bytes) return refuse("an input buffer descriptor has zero records"); @@ -2326,7 +2332,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor Wrapper* device = self->own().list_device; if (address) { if (const auto allocation = list_upload_range(self, address, bytes); allocation.resource) { - if (!owner) return {allocation.resource, allocation.offset, bytes, stride, true}; + if (!owner) return {allocation.resource, allocation.offset, bytes, stride, true, records}; return refuse("an input buffer view token names the list's upload memory"); } const auto placed = placed_buffer_range(device, address, bytes); @@ -2338,7 +2344,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor if (!alias.resource) return refuse(in_upload ? "an input range crosses the end of its upload allocation" : "an input is in title memory outside any placed buffer"); - return {alias.resource, alias.offset, bytes, stride}; + return {alias.resource, alias.offset, bytes, stride, false, records}; } owner = placed.owner; native = static_cast(owner->own().real); @@ -2368,7 +2374,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor const auto desc = native->GetDesc(); if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || (desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) || offset > desc.Width || bytes > desc.Width - offset) return refuse("an input range is outside its desktop buffer"); - return {native, offset, bytes, stride, upload}; + return {native, offset, bytes, stride, upload, records}; } struct FormattedBufferDescriptor { @@ -2642,6 +2648,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI InterlockedExchange(&draw_heap_cursor, static_cast(views)); } std::uint32_t strides[32] = {}; + std::uint32_t record_counts[32] = {}; // Only the vertices this draw can reference are copied: [vertex_first, vertex_first + vertex_count). // The shader adds the "base vertex" entry value to the vertex index, so that value is biased by // -vertex_first and each stream's view starts at vertex_first. @@ -2864,6 +2871,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI if (!view.upload) require_state(self, view.resource, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); strides[i] = view.stride; + record_counts[i] = view.records; buffer_view(dest, view.resource, view.offset, static_cast(view.bytes)); continue; } @@ -2898,6 +2906,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI // A hardware buffer descriptor the title wrote itself: base address, stride and record count. address = words[0] | (static_cast(words[1] & 0xffff) << 32); strides[i] = (words[1] >> 16) & 0x3fff; + record_counts[i] = words[2]; bytes = static_cast(strides[i] ? strides[i] : 1) * words[2]; } const std::size_t view_bytes = bytes; // before the 16 MiB copy cap @@ -3035,6 +3044,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI : ud.kind == Translation::start_instance ? start_instance : ud.kind == Translation::root_constant ? ((ud.a >= 0 && ud.a < 16 && ud.b >= 0 && ud.b < 8) ? pass.constants[ud.a][ud.b] : 0) : ud.kind == Translation::stride && ud.a >= 0 && ud.a < 32 ? strides[ud.a] + : ud.kind == Translation::num_records && ud.a >= 0 && ud.a < 32 ? record_counts[ud.a] : ud.kind == Translation::d16_unorm16 && ud.a >= 0 && ud.a < 32 ? d16_unorm16[ud.a] : ud.kind == Translation::desc_word3 ? formatted_buffers[ud.a].words[3] : 0; } diff --git a/src/startup_stubs/udsrc_line.h b/src/startup_stubs/udsrc_line.h new file mode 100644 index 0000000000..19c121123f --- /dev/null +++ b/src/startup_stubs/udsrc_line.h @@ -0,0 +1,55 @@ +#pragma once +// Manifest `udsrc` lines for a translated draw. Kind numbers are Translation::UdKind in d3d12_draw.inl. +#include +#include + +enum { + udsrc_rect = 0, + udsrc_base_vertex = 1, + udsrc_start_instance = 2, + udsrc_root_constant = 3, + udsrc_stride = 4, + udsrc_mrt_bits = 5, + udsrc_d16_unorm16 = 6, + udsrc_desc_word3 = 7, + udsrc_num_records = 8 +}; + +struct UdSrcParsed { + bool is_udsrc = false; + int kind = -1; + int index = 0; + int a = 0; + int b = 0; +}; + +// A line that is not `udsrc` leaves is_udsrc clear and returns true so the caller can try another kind of line. +// An unknown kind, a gap, or an index that is not the next slot returns false: the translation is not used, +// so a later udsrc line is not dropped while the shader still runs. +// mrtbits is known only when the manifest is paired with an RTV request. d16unorm16 needs a view index in 0..31. +inline bool accept_udsrc_line(const char* line, int next_index, bool rtv_request, UdSrcParsed* out) +{ + out->is_udsrc = false; + out->kind = -1; + if (std::strncmp(line, "udsrc ", 6) != 0) return true; + int index = 0, a = 0, b = 0; + char source[16] = ""; + if (std::sscanf(line, "udsrc %d %15s %d %d", &index, source, &a, &b) < 2) return false; + int kind = -1; + if (!std::strcmp(source, "rect")) kind = udsrc_rect; + else if (!std::strcmp(source, "basevertex")) kind = udsrc_base_vertex; + else if (!std::strcmp(source, "startinstance")) kind = udsrc_start_instance; + else if (!std::strcmp(source, "rootconst")) kind = udsrc_root_constant; + else if (!std::strcmp(source, "stride")) kind = udsrc_stride; + else if (!std::strcmp(source, "d16unorm16") && a >= 0 && a < 32) kind = udsrc_d16_unorm16; + else if (!std::strcmp(source, "descword3")) kind = udsrc_desc_word3; + else if (!std::strcmp(source, "mrtbits") && rtv_request) kind = udsrc_mrt_bits; + else if (!std::strcmp(source, "numrecords")) kind = udsrc_num_records; + if (kind < 0 || index != next_index || next_index < 0 || next_index >= 32) return false; + out->is_udsrc = true; + out->kind = kind; + out->index = index; + out->a = a; + out->b = b; + return true; +} diff --git a/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py b/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py index 8137f80f76..a2b950cbe2 100644 --- a/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py +++ b/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py @@ -56,57 +56,100 @@ def sop2(op, sdst, ssrc0, ssrc1, literal=None): return word if literal is None else word + struct.pack('> 3) & 1) << 21) | (((srsrc // 4) & 0x1f) << 16) + w1 |= ((vdata & 0xff) << 8) | (vaddr & 0xff) + return struct.pack('= base + base = total & 0xffffffff + return ok, base + + +def raw_dwords(parts, count, stride=STRIDE, records=RECORDS): + ok, address = add_u32(parts) + limit = (stride * records) & 0xffffffff + words = [] + for i in range(count): + end = (address + 4 * (i + 1)) & 0xffffffff + if not ok or end < address or end > limit: + words.append(0) + else: + words.append(SOURCE[address // 4 + i]) + return tuple(words) + + def cpu_load(address, stride=STRIDE, records=RECORDS): """One raw dword: in range when the 32-bit end byte does not wrap and is at or before the product.""" - limit = (stride * records) & 0xffffffff - end = (address + 4) & 0xffffffff - if end < address or end > limit: - return 0 - return SOURCE[address // 4] + return raw_dwords((address,), 1, stride, records)[0] def expected_words(): @@ -132,23 +175,38 @@ def must_refuse(label, ps, message): raise AssertionError('%s: translated' % label) +def bound_open(stride, records, clamped=False): + factor = 'max(ud%d, 1u)' % stride if clamped else 'ud%d' % stride + return '{ uint lim = %s * ud%d; uint base = 0; bool ok = true;' % (factor, records) + + +def assert_bounded(ps, stride, records, offsets, count=1, clamped=False, terms=None): + assert bound_open(stride, records, clamped) in ps, ps + assert 'a = v0 +' not in ps, ps + for term in terms or ('v0',): + assert 'ok = ok && base + (%s) >= base; base += %s;' % (term, term) in ps, ps + for index, offset in enumerate(offsets): + assert 'ok = ok && base + (%d) >= base; base += %d;' % (offset, offset) in ps, ps + for lane in range(count): + end = 4 * (lane + 1) + line = 'v%d = (ok && a + %du >= a && a + %du <= lim) ? r0.Load(a + %d) : 0u;' % ( + 1 + index * count + lane, end, end, 4 * lane) + assert line in ps, ps + + def controls(): pipe = translate(program(conversion())) ps, manifest = pipe.hlsl_ps(), pipe.manifest() stride, records = ud_index(manifest, 'stride'), ud_index(manifest, 'numrecords') assert 'ByteAddressBuffer r0 : register(t0);' in ps, ps assert 'srv 0 buf table 0 0' in manifest, manifest - limit = '{ uint lim = ud%d * ud%d;' % (stride, records) - for index, offset in enumerate(OFFSETS): - # The immediate is part of the address. A one-dword load then reads a + 0 inside the bound. - line = 'v%d = (a + 4u >= a && a + 4u <= lim) ? r0.Load(a + 0) : 0u;' % (1 + index) - assert limit in ps and ('a = v0 + %d;' % offset) in ps and line in ps, ps + assert_bounded(ps, stride, records, OFFSETS) print('raw conversion: four offen loads bounded by ud%d * ud%d' % (stride, records)) clamped = translate(program(conversion(clamp=True))) cps, cmanifest = clamped.hlsl_ps(), clamped.manifest() cstride, crecords = ud_index(cmanifest, 'stride'), ud_index(cmanifest, 'numrecords') - assert '{ uint lim = max(ud%d, 1u) * ud%d;' % (cstride, crecords) in cps, cps + assert_bounded(cps, cstride, crecords, OFFSETS, clamped=True) print('clamped raw conversion: bound is max(stride, 1) * NUM_RECORDS') stride0 = program(sop2('s_and_b32', DESC + 1, DESC + 1, 255, 0xc000ffff)) @@ -156,6 +214,60 @@ def controls(): assert 'v1 = r0.Load(a + 0);' in text and 'uint lim' not in text, text print('stride clear only: unbounded raw load') + # A dwordx2 at byte 28 covers bytes 28 and 32. Only the first dword is inside the 32-byte limit. + cross2 = finish(smem_load_x4(DESC, 8) + conversion() + v_mov(0, 0) + + encode_mubuf(0x0d, imm=28, offen=1, vdata=1)) + x2 = translate(cross2) + assert_bounded(x2.hlsl_ps(), ud_index(x2.manifest(), 'stride'), ud_index(x2.manifest(), 'numrecords'), + (28,), count=2) + assert raw_dwords((0, 28), 2) == (SOURCE[7], 0) + print('dwordx2: the dword that crosses NUM_RECORDS * stride is zero') + + # A dwordx4 at byte 24 covers 24, 28, 32 and 36. The last two dwords are out. + cross4 = finish(smem_load_x4(DESC, 8) + conversion() + v_mov(0, 0) + + encode_mubuf(0x0e, imm=24, offen=1, vdata=1)) + x4 = translate(cross4) + assert_bounded(x4.hlsl_ps(), ud_index(x4.manifest(), 'stride'), ud_index(x4.manifest(), 'numrecords'), + (24,), count=4) + assert raw_dwords((0, 24), 4) == (SOURCE[6], SOURCE[7], 0, 0) + print('dwordx4: two dwords inside the limit, then two zeros') + + assert raw_dwords((0,), 1, stride=0, records=4) == (0,) + assert raw_dwords((4,), 1, stride=0, records=4) == (0,) + print('stride 0: the product is zero, so every positive end is out of range') + + # soffset is an inline 8 in s21. v0 is 0, so the addresses are 8+4 and 8+28. + shifted = finish(smem_load_x4(DESC, 8) + conversion() + s_mov(21, 128 + 8) + v_mov(0, 0) + + encode_mubuf(0x0c, imm=4, offen=1, vdata=1, soffset=21) + + encode_mubuf(0x0c, imm=28, offen=1, vdata=2, soffset=21), + exports=(1, 2, 1, 2)) + shifted_ps = translate(shifted).hlsl_ps() + assert 'base + (0x00000008u)' in shifted_ps and 'base + (4)' in shifted_ps and 'base + (28)' in shifted_ps, shifted_ps + assert raw_dwords((0, 8, 4), 1) == (SOURCE[3],) + assert raw_dwords((0, 8, 28), 1) == (0,) + print('non-zero soffset: byte 12 is in range and byte 36 is not') + + # The conversion runs on a copy of the loaded words, not on the registers the load wrote. + copied = b''.join(s_mov(24 + i, DESC + i) for i in range(4)) + copy_ps = translate(program(copied + conversion(base=24, tmp=28), srsrc=24)).hlsl_ps() + assert 'uint lim' in copy_ps and 'r0.Load(a + 0)' in copy_ps, copy_ps + print('copied descriptor: the bound follows the s_mov copies') + + # v0 is 0xfffffffc. Adding 12, 28 or 32 wraps before the range test, so those loads are zero + # rather than the words at the truncated addresses 8, 24 and 28. + wrapped = program(conversion(), v0=0xfffffffc, offsets=(12, 28, 32, 0)) + wrapped_ps = translate(wrapped).hlsl_ps() + assert 'ok = ok && base + (v0) >= base; base += v0;' in wrapped_ps, wrapped_ps + assert raw_dwords((0xfffffffc, 12), 1) == (0,) + assert raw_dwords((0xfffffffc, 28), 1) == (0,) + assert raw_dwords((0xfffffffc, 32), 1) == (0,) + assert (SOURCE[2], SOURCE[6], SOURCE[7]) == (0x40400000, 0x40e00000, 0x41000000) + print('address wrap: a term that overflows the 32-bit sum reads zero') + + typed = finish(smem_load_x4(DESC, 8) + conversion() + v_mov(0, 0) + + encode_mtbuf(0, 22, imm=32, offen=1, vdata=1), exports=(1, 1, 1, 1)) + must_refuse('typed buffer load', typed, MODIFIED) + missing_count = (sop2('s_bfe_u32', TMP, DESC + 1, 255, 0xe0010) + sop2('s_and_b32', DESC + 1, DESC + 1, 255, 0xc000ffff) + sop2('s_and_b32', DESC + 3, DESC + 3, 255, 0xcfffffff) @@ -163,16 +275,40 @@ def controls(): missing_oob = (sop2('s_bfe_u32', TMP, DESC + 1, 255, 0xe0010) + sop2('s_and_b32', DESC + 1, DESC + 1, 255, 0xc000ffff) + sop2('s_mul_i32', DESC + 2, DESC + 2, TMP)) + wrong_mask = conversion().replace(struct.pack('= 0 && ud.a < 32 ? record_counts[ud.a]' in draw + assert 'x2w-draw unsupported udsrc' in draw + driver = r""" +#include "udsrc_line.h" +int main() { + UdSrcParsed parsed{}; + if (!accept_udsrc_line("udsrc 0 rect", 0, false, &parsed) || !parsed.is_udsrc || parsed.kind != udsrc_rect) + return 1; + if (!accept_udsrc_line("udsrc 4 numrecords 0", 4, false, &parsed) || parsed.kind != udsrc_num_records || parsed.a != 0) + return 2; + if (accept_udsrc_line("udsrc 5 notakind 0", 5, false, &parsed)) + return 3; + if (accept_udsrc_line("udsrc 6 stride 0", 5, false, &parsed)) + return 4; + if (!accept_udsrc_line("udsrc 5 stride 0", 5, false, &parsed) || parsed.kind != udsrc_stride) + return 5; + if (!accept_udsrc_line("srv 0 buf table 0 0", 0, false, &parsed) || parsed.is_udsrc) + return 6; + if (accept_udsrc_line("udsrc 0 mrtbits", 0, false, &parsed)) + return 7; + if (!accept_udsrc_line("udsrc 0 mrtbits", 0, true, &parsed) || parsed.kind != udsrc_mrt_bits) + return 8; + return 0; +} +""" + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + source = directory / 'udsrc_main.cpp' + source.write_text(driver, encoding='ascii') + binary = directory / 'udsrc_main' + built = subprocess.run( + ['g++', '-std=c++17', '-Wall', '-Wextra', '-I', str(root / 'src/startup_stubs'), str(source), '-o', str(binary)], + capture_output=True, text=True) + if built.returncode: + raise AssertionError(built.stderr) + run = subprocess.run([str(binary)], capture_output=True, text=True) + if run.returncode: + raise AssertionError('udsrc driver exit %s' % run.returncode) + print('udsrc: numrecords is stored, and an unknown kind or a gap refuses the manifest') + + def main(): if len(sys.argv) == 1: controls() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 74de7e1032..53f1cc4c71 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -6876,7 +6876,7 @@ def op_s_buffer_load_dwordx8(self, ops, mods): def op_s_buffer_load_dwordx16(self, ops, mods): self.op_s_buffer_load_dword(ops, mods, 16) - def buffer_address(self, ops, mods, *, is_formatted=False): + def buffer_address(self, ops, mods, *, is_formatted=False, raw_conversion_ok=None): # MUBUF and MTBUF share the same address calculation: optional index * stride (idxen), # optional byte VGPR offset (offen), scalar byte offset (soffset) and 12-bit immediate # offset. Cache-policy flags (glc, slc, dlc) do not change the loaded bytes; lds, tfe @@ -6891,8 +6891,11 @@ def buffer_address(self, ops, mods, *, is_formatted=False): raise Unsupported('buffer load with %d operands, expected 4' % len(ops)) idxen, offen = 'idxen' in mods, 'offen' in mods what = 'indexed load' if idxen else 'buffer load' + # A typed MTBUF load does not use the raw bound (raw_conversion_ok is False there). Leaving the + # conversion accepted would read past NUM_RECORDS * stride as an ordinary Load. + allow_raw = (not idxen) if raw_conversion_ok is None else bool(raw_conversion_ok) and not idxen if not is_formatted: - key = self.load_descriptor(ops[2], what, stride0_ok=not idxen, raw_conversion_ok=not idxen) + key = self.load_descriptor(ops[2], what, stride0_ok=not idxen, raw_conversion_ok=allow_raw) else: key = self.descriptor(ops[2]) buf = self.pipe.resource(key, 'buf') @@ -6932,6 +6935,7 @@ def buffer_address(self, ops, mods, *, is_formatted=False): if soffset is not None: terms.append(soffset) terms.append('%d' % offset) + self.address_terms = terms return buf, ' + '.join(terms) def op_buffer_load_dword(self, ops, mods, count=1): @@ -6942,23 +6946,28 @@ def op_buffer_load_dword(self, ops, mods, count=1): raise Unsupported('buffer load with 0 operands, expected 4') dst = reg_range(ops[0]) buf, address = self.buffer_address(ops, mods) - self.emit('a = %s;' % address) # A pixel load through the full conversion is a raw byte-address read. The hardware compares the address # against the converted NUM_RECORDS, which is the 32-bit product of the original record count and stride # (at least 1 when the extract was clamped). The entry constants are that view's stride and record count. + # Each term of the address is added first: a wrapped sum is out of range even when the truncated value + # would have landed inside the buffer. bound = getattr(self, 'raw_load_bound', None) if getattr(self, 'kind', None) == 'ps' else None if bound: index = self.pipe.resources[bound[0]]['index'] stride = self.pipe.ud(('stride', index)) records = self.pipe.ud(('numrecords', index)) factor = 'max(ud%d, 1u)' % stride if bound[1] else 'ud%d' % stride - self.emit('{ uint lim = %s * ud%d;' % (factor, records)) + self.emit('{ uint lim = %s * ud%d; uint base = 0; bool ok = true;' % (factor, records)) + for term in self.address_terms: + self.emit('ok = ok && base + (%s) >= base; base += %s;' % (term, term)) + self.emit('a = base;') for i in range(count): end = 4 * (i + 1) self.set_v(dst[1] + i, - '(a + %du >= a && a + %du <= lim) ? %s.Load(a + %d) : 0u' % (end, end, buf, 4 * i)) + '(ok && a + %du >= a && a + %du <= lim) ? %s.Load(a + %d) : 0u' % (end, end, buf, 4 * i)) self.emit('}') else: + self.emit('a = %s;' % address) for i in range(count): self.set_v(dst[1] + i, '%s.Load(a + %d)' % (buf, 4 * i)) @@ -7353,7 +7362,8 @@ def tbuffer(self, ops, mods, count): dst = reg_range(ops[0]) formats = [m for m in mods if m.startswith('format:')] fmt = formats[0][8:-1] if formats else 'BUF_FMT_8_UNORM' # the disassembler omits the default format - buf, address = self.buffer_address(ops, [m for m in mods if not m.startswith('format:')]) + buf, address = self.buffer_address( + ops, [m for m in mods if not m.startswith('format:')], raw_conversion_ok=False) self.emit('a = %s;' % address) self.load_format(fmt, buf, dst[1], count) From abe809d3d152c463730c6e9d243cd04e44ae3924 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 27 Nov 2026 23:00:48 +0000 Subject: [PATCH 3/4] runtime: assign indirect buffer views by member name Brace initialization put the upload flag in records and narrowed the record count into the bool. The view is filled by member name, including the compute root returns. Co-authored-by: SimSalabimse --- src/startup_stubs/d3d12_compute_dispatch.inl | 4 ++-- src/startup_stubs/d3d12_draw.inl | 19 ++++++++++++++++--- ...tartup_gfx2hlsl_ps_raw_descriptor_check.py | 5 +++++ 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index ff61716664..1b40d31bdc 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -301,7 +301,7 @@ IndirectBufferView compute_root_srv_buffer(Wrapper* self, const Pass& pass, int if (bytes < 4) return refuse("a compute root SRV has fewer than 4 aligned bytes in its upload allocation"); words[2] = static_cast(bytes); - return {allocation.resource, allocation.offset, bytes, 0, true}; + return indirect_buffer_view(allocation.resource, allocation.offset, bytes, 0, 0, true); } Wrapper* device = self->own().list_device; const auto first = placed_buffer_range(device, address, 4); @@ -336,7 +336,7 @@ IndirectBufferView compute_root_srv_buffer(Wrapper* self, const Pass& pass, int offset > desc.Width || bytes > desc.Width - offset) return refuse("a compute root SRV range is outside its desktop buffer"); words[2] = static_cast(bytes); - return {native, offset, bytes, 0, false}; + return indirect_buffer_view(native, offset, bytes, 0, 0, false); } // Both callers have an open list and a slot 67 request. The indirect caller has checked the signature and argument range. diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index d2c77dcbd3..cf109b0492 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2259,6 +2259,19 @@ struct IndirectBufferView { bool upload = false; }; +// Named members: a brace initializer put the bool in records and narrowed records into upload (MSVC C2397). +IndirectBufferView indirect_buffer_view(ID3D12Resource* resource, u64 offset, u64 bytes, UINT stride, UINT records, bool upload) +{ + IndirectBufferView view; + view.resource = resource; + view.offset = offset; + view.bytes = bytes; + view.stride = stride; + view.records = records; + view.upload = upload; + return view; +} + // For indirect draws, bind the complete descriptor range on a known GPU backing. There is no // fallback to copying an unrelated or stale title allocation into the draw upload ring. // why, when given, receives the condition an empty result failed on. @@ -2332,7 +2345,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor Wrapper* device = self->own().list_device; if (address) { if (const auto allocation = list_upload_range(self, address, bytes); allocation.resource) { - if (!owner) return {allocation.resource, allocation.offset, bytes, stride, true, records}; + if (!owner) return indirect_buffer_view(allocation.resource, allocation.offset, bytes, stride, records, true); return refuse("an input buffer view token names the list's upload memory"); } const auto placed = placed_buffer_range(device, address, bytes); @@ -2344,7 +2357,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor if (!alias.resource) return refuse(in_upload ? "an input range crosses the end of its upload allocation" : "an input is in title memory outside any placed buffer"); - return {alias.resource, alias.offset, bytes, stride, false, records}; + return indirect_buffer_view(alias.resource, alias.offset, bytes, stride, records, false); } owner = placed.owner; native = static_cast(owner->own().real); @@ -2374,7 +2387,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor const auto desc = native->GetDesc(); if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || (desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) || offset > desc.Width || bytes > desc.Width - offset) return refuse("an input range is outside its desktop buffer"); - return {native, offset, bytes, stride, upload, records}; + return indirect_buffer_view(native, offset, bytes, stride, records, upload); } struct FormattedBufferDescriptor { diff --git a/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py b/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py index a2b950cbe2..647ac0de76 100644 --- a/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py +++ b/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py @@ -375,6 +375,11 @@ def check_udsrc(): assert 'record_counts[i] = words[2];' in draw assert 'records = words[2];' in draw assert 'record_counts[i] = view.records;' in draw + # records is a UINT and upload is a bool after it. Assigning by name avoids narrowing the count into the bool. + assert 'view.records = records;' in draw and 'view.upload = upload;' in draw + assert 'return {allocation.resource' not in draw and 'return {native, offset, bytes, stride' not in draw + compute = (root / 'src/startup_stubs/d3d12_compute_dispatch.inl').read_text(encoding='utf-8') + assert 'return {allocation.resource' not in compute and 'return {native, offset, bytes, 0, false}' not in compute assert 'ud.kind == Translation::num_records && ud.a >= 0 && ud.a < 32 ? record_counts[ud.a]' in draw assert 'x2w-draw unsupported udsrc' in draw driver = r""" From 587a3decd6a61a69d8672b157993b43261bfdd42 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 27 Nov 2026 23:11:25 +0000 Subject: [PATCH 4/4] test: build the udsrc parser check with the project compiler The parser cases live in a small C++ target the Windows build compiles with MSVC. The Python check runs that binary, and compiles the same source with cl or g++ when CTest has not handed it one. Co-authored-by: SimSalabimse --- CMakeLists.txt | 10 ++- docs/experiments.md | 2 +- ...tartup_gfx2hlsl_ps_raw_descriptor_check.py | 82 +++++++++++-------- tests/startup_udsrc_line_check.cpp | 25 ++++++ 4 files changed, 85 insertions(+), 34 deletions(-) create mode 100644 tests/startup_udsrc_line_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 14dd8e8d03..128283b4dc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3807,14 +3807,22 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_gfx2hlsl_buffer_store COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_buffer_store_check.py") # Pixel-stage structured-to-raw buffer loads: translation controls, then a one-pixel draw on WARP and hardware. + # The udsrc cases are a compiled target (MSVC here, the same source rebuilt by the Python check elsewhere). + add_executable(startup_udsrc_line_check tests/startup_udsrc_line_check.cpp) + target_compile_features(startup_udsrc_line_check PRIVATE cxx_std_17) + target_include_directories(startup_udsrc_line_check PRIVATE src/startup_stubs) + add_test(NAME startup_gfx2hlsl_ps_raw_descriptor_udsrc COMMAND startup_udsrc_line_check) + set(udsrc_check_env "X2W_UDSRC_CHECK=$;X2W_CXX=${CMAKE_CXX_COMPILER}") add_test(NAME startup_gfx2hlsl_ps_raw_descriptor COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py") + set_tests_properties(startup_gfx2hlsl_ps_raw_descriptor PROPERTIES ENVIRONMENT "${udsrc_check_env}") foreach(adapter IN ITEMS warp hardware) add_test(NAME startup_gfx2hlsl_ps_raw_descriptor_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py" draw "${DXC_EXECUTABLE}" "$" ${adapter} $<$:${STARTUP_FXC}>) - set_tests_properties(startup_gfx2hlsl_ps_raw_descriptor_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + set_tests_properties(startup_gfx2hlsl_ps_raw_descriptor_${adapter} PROPERTIES + TIMEOUT 180 SKIP_RETURN_CODE 77 ENVIRONMENT "${udsrc_check_env}") endforeach() # Output modifiers on float-result conversions (#1705). add_test(NAME startup_gfx2hlsl_vcvt_omod COMMAND "${INTAKE_PYTHON}" -B diff --git a/docs/experiments.md b/docs/experiments.md index 133c675396..36cad8eb7f 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -417,7 +417,7 @@ A non-indexed `buffer_load_dword` in a pixel stage lowers a descriptor that went ```powershell ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_ps_raw_descriptor$' --output-on-failure -ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_ps_raw_descriptor_(warp|hardware)$' --output-on-failure +ctest --preset dev --no-tests=error -R '^startup_gfx2hlsl_ps_raw_descriptor_(warp|hardware|udsrc)$' --output-on-failure ``` The draw runs on the Windows test PC. A capability skip (77) is separate from a pass. diff --git a/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py b/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py index 647ac0de76..0bb9141f66 100644 --- a/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py +++ b/tests/startup_gfx2hlsl_ps_raw_descriptor_check.py @@ -1,6 +1,6 @@ """Pixel-stage structured-to-raw buffer loads in tools/startup/gfx2hlsl.py. - (no arguments) translation controls and the CPU model, pure Python + (no arguments) translation controls, the CPU model and the udsrc parser draw [fxc] translate, compile and draw one pixel. The readback must match the CPU model of a raw byte-address load bounded by NUM_RECORDS * stride. @@ -9,6 +9,8 @@ The fixture is source-built. A pixel stage loads one table descriptor, clears its stride, scales NUM_RECORDS by the extracted stride and sets OOB_SELECT to raw, then reads four dwords with buffer_load_dword offen. """ +import os +import shutil import struct import subprocess import sys @@ -382,43 +384,59 @@ def check_udsrc(): assert 'return {allocation.resource' not in compute and 'return {native, offset, bytes, 0, false}' not in compute assert 'ud.kind == Translation::num_records && ud.a >= 0 && ud.a < 32 ? record_counts[ud.a]' in draw assert 'x2w-draw unsupported udsrc' in draw - driver = r""" -#include "udsrc_line.h" -int main() { - UdSrcParsed parsed{}; - if (!accept_udsrc_line("udsrc 0 rect", 0, false, &parsed) || !parsed.is_udsrc || parsed.kind != udsrc_rect) - return 1; - if (!accept_udsrc_line("udsrc 4 numrecords 0", 4, false, &parsed) || parsed.kind != udsrc_num_records || parsed.a != 0) - return 2; - if (accept_udsrc_line("udsrc 5 notakind 0", 5, false, &parsed)) - return 3; - if (accept_udsrc_line("udsrc 6 stride 0", 5, false, &parsed)) - return 4; - if (!accept_udsrc_line("udsrc 5 stride 0", 5, false, &parsed) || parsed.kind != udsrc_stride) - return 5; - if (!accept_udsrc_line("srv 0 buf table 0 0", 0, false, &parsed) || parsed.is_udsrc) - return 6; - if (accept_udsrc_line("udsrc 0 mrtbits", 0, false, &parsed)) - return 7; - if (!accept_udsrc_line("udsrc 0 mrtbits", 0, true, &parsed) || parsed.kind != udsrc_mrt_bits) - return 8; - return 0; -} -""" + run_udsrc_driver(root) + print('udsrc: numrecords is stored, and an unknown kind or a gap refuses the manifest') + + +def compiler_is_msvc(compiler): + return Path(compiler).name.lower() in ('cl', 'cl.exe') + + +def udsrc_compiler(): + """CMake passes cl on Windows. A direct run uses cl there and g++ elsewhere. Neither is optional.""" + chosen = os.environ.get('X2W_CXX') + if chosen: + return chosen + if os.name == 'nt': + found = shutil.which('cl') + if not found: + raise AssertionError('udsrc parser check needs cl.exe (set X2W_CXX to the MSVC compiler)') + return found + for name in ('g++', 'c++'): + found = shutil.which(name) + if found: + return found + raise AssertionError('udsrc parser check needs g++') + + +def run_udsrc_driver(root): + """Run tests/startup_udsrc_line_check.cpp. CTest passes the binary it just built; otherwise compile it.""" + ready = os.environ.get('X2W_UDSRC_CHECK') + if ready: + binary = Path(ready) + if not binary.is_file(): + raise AssertionError('udsrc check executable is missing: %s' % binary) + run = subprocess.run([str(binary)], capture_output=True, text=True) + if run.returncode: + raise AssertionError('udsrc driver exit %s\n%s%s' % (run.returncode, run.stdout, run.stderr)) + return + compiler = udsrc_compiler() + source = HERE / 'startup_udsrc_line_check.cpp' + include = root / 'src' / 'startup_stubs' with tempfile.TemporaryDirectory() as tmp: directory = Path(tmp) - source = directory / 'udsrc_main.cpp' - source.write_text(driver, encoding='ascii') - binary = directory / 'udsrc_main' - built = subprocess.run( - ['g++', '-std=c++17', '-Wall', '-Wextra', '-I', str(root / 'src/startup_stubs'), str(source), '-o', str(binary)], - capture_output=True, text=True) + binary = directory / ('udsrc_main.exe' if compiler_is_msvc(compiler) else 'udsrc_main') + if compiler_is_msvc(compiler): + command = [compiler, '/nologo', '/std:c++17', '/EHsc', '/W4', '/I', str(include), + str(source), '/Fe%s' % binary, '/Fo%s' % (directory / 'udsrc_main.obj')] + else: + command = [compiler, '-std=c++17', '-Wall', '-Wextra', '-I', str(include), str(source), '-o', str(binary)] + built = subprocess.run(command, cwd=directory, capture_output=True, text=True) if built.returncode: - raise AssertionError(built.stderr) + raise AssertionError(built.stdout + built.stderr) run = subprocess.run([str(binary)], capture_output=True, text=True) if run.returncode: raise AssertionError('udsrc driver exit %s' % run.returncode) - print('udsrc: numrecords is stored, and an unknown kind or a gap refuses the manifest') def main(): diff --git a/tests/startup_udsrc_line_check.cpp b/tests/startup_udsrc_line_check.cpp new file mode 100644 index 0000000000..58a6f95803 --- /dev/null +++ b/tests/startup_udsrc_line_check.cpp @@ -0,0 +1,25 @@ +// The draw stand-in accepts a numrecords udsrc and refuses an unknown kind or a gap. +// Exit codes are the cases tests/startup_gfx2hlsl_ps_raw_descriptor_check.py reports. +#include "udsrc_line.h" + +int main() +{ + UdSrcParsed parsed{}; + if (!accept_udsrc_line("udsrc 0 rect", 0, false, &parsed) || !parsed.is_udsrc || parsed.kind != udsrc_rect) + return 1; + if (!accept_udsrc_line("udsrc 4 numrecords 0", 4, false, &parsed) || parsed.kind != udsrc_num_records || parsed.a != 0) + return 2; + if (accept_udsrc_line("udsrc 5 notakind 0", 5, false, &parsed)) + return 3; + if (accept_udsrc_line("udsrc 6 stride 0", 5, false, &parsed)) + return 4; + if (!accept_udsrc_line("udsrc 5 stride 0", 5, false, &parsed) || parsed.kind != udsrc_stride) + return 5; + if (!accept_udsrc_line("srv 0 buf table 0 0", 0, false, &parsed) || parsed.is_udsrc) + return 6; + if (accept_udsrc_line("udsrc 0 mrtbits", 0, false, &parsed)) + return 7; + if (!accept_udsrc_line("udsrc 0 mrtbits", 0, true, &parsed) || parsed.kind != udsrc_mrt_bits) + return 8; + return 0; +}