From f14d392d3acf065f2f130bc876f17a4b397249b6 Mon Sep 17 00:00:00 2001 From: rasptum <348594691+rasptum@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:38:15 -0500 Subject: [PATCH 1/9] startup: lower pixel-stage image_store to a typed UAV store gfx2hlsl refused image_store in every stage (#1996 item F). In a pixel stage, image_store with dim:SQ_RSRC_IMG_2D and dmask:0xf now becomes w[uint2(x, y)] = asfloat(uint4(data)) on a RWTexture2D at its own u register, under the lane's exec bit, and the manifest becomes version 2 with "uav tex2d table ". Semantics: MIMG opcode 0x08 (LLVM AMDGPU MIMGInstructions.td, IMAGE_STORE defined through MIMG_Store): VDATA is the source, VADDR the integer texel address (x, y for dim 2D), SRSRC the image descriptor, and the DMASK channels are written in order from consecutive VDATA registers. Mesa ACO (visit_image_store) emits the same form with DMASK from the write mask. A typed UAV store writes every channel, so only DMASK 0xf is exact; a partial mask, other dimensions, d16, a16, tfe, lwe, r128, unorm, image_store_mip, a store outside a pixel stage and a load and store of the same image are refused by name. glc, slc and dlc are accepted. The translated graphics path does not bind UAVs yet: d3d12_draw.inl logs and does not use a translation whose manifest has a uav line, instead of rejecting it as an invalid sampler-heap line. startup_pixel_image_store_check.py decodes the hand-assembled program with disasm_rdna2, checks the translation, the refusals, and that the program is refused again with the lowering removed. The draw stores four values at texel (1, 2) of a 4x4 image through offscreen_check --startup-image-store, reads all 16 texels back, and checks that deleting the store or exchanging x and y is detected. Refs #1996 Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 11 ++ docs/startup-runtime.md | 11 ++ src/startup_stubs/d3d12_draw.inl | 6 + tests/desktop_gpu.h | 2 + tests/offscreen_check.cpp | 15 ++ tests/startup_image_store.cpp | 166 ++++++++++++++++++++ tests/startup_pixel_image_store_check.py | 184 +++++++++++++++++++++++ tools/startup/gfx2hlsl.py | 70 ++++++++- 8 files changed, 464 insertions(+), 1 deletion(-) create mode 100644 tests/startup_image_store.cpp create mode 100644 tests/startup_pixel_image_store_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 26fbe94bb..85e597e36 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1159,6 +1159,7 @@ foreach(mutation IN ITEMS sampler-alone bind-unrestorable) set_tests_properties(startup_heap_indexed_root_${mutation}_control PROPERTIES WILL_FAIL TRUE) endforeach() target_sources(offscreen_check PRIVATE tests/startup_image_3d.cpp) +target_sources(offscreen_check PRIVATE tests/startup_image_store.cpp) target_sources(offscreen_check PRIVATE tests/startup_flat_param.cpp) # The storage root handed to the executable ends in a separator and is never cut off # (src/startup_stubs/storage_root.h); the mutated run is the negative control. @@ -2366,6 +2367,16 @@ if(EXISTS "${INTAKE_PYTHON}") "$" ${adapter}) set_tests_properties(startup_image_load_mip_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) endforeach() + # gfx2hlsl pixel-stage image_store (#1996 item F): translation controls and refusals, then a desktop draw + # that reads every texel of the stored image back. + add_test(NAME startup_pixel_image_store_controls COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_pixel_image_store_check.py") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_pixel_image_store_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_SOURCE_DIR}/tests/startup_pixel_image_store_check.py" draw "${DXC_EXECUTABLE}" + "$" ${adapter}) + set_tests_properties(startup_pixel_image_store_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() # gfx2hlsl 2D array images: translation controls, then a desktop draw that names the slice's texel. add_test(NAME startup_image_2d_array_controls COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/startup_image_2d_array_check.py") diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index f20261bc1..76c32f8b7 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1135,6 +1135,17 @@ These are measured on one executable; treat them as hypotheses for others. a `float3` of the three address registers in order; 1D images are refused. A source-built pixel stage draws one texel of a 2x2x2 texture on WARP and hardware with DXC and FXC (`ctest --preset release --no-tests=error -R "^startup_image_3d_"`). +- **Pixel-stage image stores.** In a pixel stage, `image_store` with `dim:SQ_RSRC_IMG_2D` and + `dmask:0xf` becomes a typed store to a `RWTexture2D` at its own `u` register, under the + lane's exec bit, and the manifest becomes version 2 with a `uav tex2d table
` + line. The cache-policy + bits are accepted. A partial channel mask (a typed store writes all four channels), other dimensions, + `d16`, `a16`, `tfe`, `lwe`, `r128`, `unorm`, `image_store_mip`, a store outside a pixel stage, and a + program that loads and stores the same image are refused by name. The runtime does not bind UAVs on the + translated graphics path yet: it logs and does not use a translation whose manifest has a `uav` line. + A hand-assembled program stores four distinct values at texel (1, 2). The desktop draw reads all 16 + texels of a 4x4 image back; deleting the store or exchanging x and y must fail. Run + `ctest --preset release --no-tests=error -R '^startup_pixel_image_store_' -V`. - **Explicit mip loads.** For 2D textures, 2D arrays and 3D textures, `image_load_mip` passes the final address register to `Texture.Load` as the mip level (`int4(x, y, slice, mip)` for an array, whose four registers are x, y, slice and mip). Ordinary `image_load` still reads mip zero. diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index f12dd8038..238e606f2 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -173,6 +173,12 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) log("x2w-draw invalid write mask manifest line for %016llx: %s", tr.key, line.c_str()); return; } + } else if (line.compare(0, 4, "uav ") == 0) { + // tools/startup/gfx2hlsl.py lowers a pixel-stage image_store to a u-register store, but the + // translated root signature has no UAV range and no view is made from the title's descriptor yet. + log("x2w-draw pipeline %016llx stores to an image (%s); pixel-stage UAVs are not bound yet, translation not used", + tr.key, line.c_str()); + return; } else if (!tr.samplers.read_manifest_line(line.c_str())) { log("x2w-draw invalid sampler heap manifest for %016llx", tr.key); return; diff --git a/tests/desktop_gpu.h b/tests/desktop_gpu.h index ec622933d..991d1a448 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -24,6 +24,8 @@ float check_startup_sampler_heap(ID3D12Device* device, const char* vertex_path, void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const char* pixel_path, float z, float color[4], const char* sampler_line, bool array = false, UINT levels = 1, bool one_dimensional = false, bool two_dimensional = false); +int check_startup_image_store(ID3D12Device* device, const char* vertex_path, const char* pixel_path, UINT x, UINT y, + const std::uint32_t expected[4]); void check_startup_flat_param(ID3D12Device* device, const char* vertex_path, const char* pixel_path, std::uint32_t* words, UINT width = 1, UINT height = 1); void dump_raw_uav(ID3D12Device* device, const char* shader_path, const char* groups, diff --git a/tests/offscreen_check.cpp b/tests/offscreen_check.cpp index ca6ee27e4..5413c83db 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -1226,6 +1226,20 @@ OperationResult run_startup_image_3d(const OperationContext& ctx) return {OutcomeKind::pass, nullptr}; } +// --startup-image-store : the translated pixel stage stores to +// u0 (tests/startup_image_store.cpp); texel (x, y) must hold the four hex words and every other texel -1.0. +OperationResult run_startup_image_store(const OperationContext& ctx) +{ + unsigned x = 0, y = 0; + std::uint32_t expected[4]{}; + if (std::sscanf(ctx.argv[5], "%u,%u", &x, &y) != 2) return {OutcomeKind::fail, "texel is not x,y"}; + if (std::sscanf(ctx.argv[6], "%8x,%8x,%8x,%8x", &expected[0], &expected[1], &expected[2], &expected[3]) != 4) + return {OutcomeKind::fail, "expected value is not four hex words"}; + if (check_startup_image_store(ctx.device, ctx.argv[3], ctx.argv[4], x, y, expected)) + return {OutcomeKind::fail, "image store readback differs"}; + return {OutcomeKind::pass, nullptr}; +} + OperationResult run_startup_packed_position(const OperationContext& ctx) { constexpr UINT width = 13, height = 7; @@ -1416,6 +1430,7 @@ const OperationSpec kOperations[] = { {"--startup-image-1d", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-2d", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-3d", 7, 8, nullptr, kNoGate, run_startup_image_3d}, + {"--startup-image-store", 7, 7, nullptr, kNoGate, run_startup_image_store}, {"--startup-image-2d-array", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-image-2d-array-mips", 7, 8, nullptr, kNoGate, run_startup_image_3d}, {"--startup-packed-position", 5, 5, nullptr, kNoGate, run_startup_packed_position}, diff --git a/tests/startup_image_store.cpp b/tests/startup_image_store.cpp new file mode 100644 index 000000000..a428055be --- /dev/null +++ b/tests/startup_image_store.cpp @@ -0,0 +1,166 @@ +// Desktop readback for tools/startup/gfx2hlsl.py's pixel-stage image_store (#1996 item F). +// +// The translated pixel shader stores to w0 : register(u0), a RWTexture2D, and reads its entry +// constants from cbuffer entry : register(b0). This draws one pixel with that shader and a source-built +// full-screen vertex shader into a 4x4 R32G32B32A32_FLOAT texture whose texels all start as -1.0, then +// reads every texel back. The caller names the one texel it expects the store to change and its value; +// every other texel must still hold -1.0. +#include "desktop_gpu.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +using Microsoft::WRL::ComPtr; + +namespace { +constexpr UINT entry_constants = 4; +constexpr UINT side = 4; +constexpr std::uint32_t untouched = 0xbf800000; // -1.0f + +std::vector read_shader(const char* path) +{ + std::ifstream file(path, std::ios::binary); + std::vector bytes((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + if (bytes.empty()) throw std::runtime_error(std::string("Cannot read shader ") + path); + return bytes; +} + +ComPtr store_root(ID3D12Device* device) +{ + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER params[2]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants = {0, 0, entry_constants}; + 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; + const D3D12_ROOT_SIGNATURE_DESC desc{2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr blob, errors; + check(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, &errors), "Serialize image store root"); + ComPtr root; + check(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root)), + "Create image store root"); + return root; +} +} // namespace + +// Returns 0 when texel (x, y) holds expected and every other texel holds -1.0; otherwise prints the first +// differing texel as "texel_mismatch x=.. y=.. expected=.. actual=.." and returns 1. +int check_startup_image_store(ID3D12Device* device, const char* vertex_path, const char* pixel_path, UINT x, UINT y, + const std::uint32_t expected[4]) +{ + if (x >= side || y >= side) throw std::runtime_error("Expected a texel inside the 4x4 image"); + const auto vs = read_shader(vertex_path); + const auto ps = read_shader(pixel_path); + const auto root = store_root(device); + + 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 image store PSO"); + + D3D12_RESOURCE_DESC td{}; + td.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + td.Width = side; + td.Height = side; + td.DepthOrArraySize = 1; + td.MipLevels = 1; + td.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + td.SampleDesc.Count = 1; + td.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + const auto image = resource(device, td, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST); + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 bytes = 0; + device->GetCopyableFootprints(&td, 0, 1, 0, &footprint, nullptr, nullptr, &bytes); + const auto upload = make_buffer(device, bytes, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + const auto readback = make_buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + void* mapped = nullptr; + const D3D12_RANGE none{0, 0}; + check(upload->Map(0, &none, &mapped), "Map image store upload"); + for (UINT row = 0; row < side; ++row) + for (UINT word = 0; word < side * 4; ++word) + std::memcpy(static_cast(mapped) + footprint.Offset + row * footprint.Footprint.RowPitch + 4 * word, + &untouched, 4); + upload->Unmap(0, nullptr); + + D3D12_RESOURCE_DESC rd = td; + rd.Width = rd.Height = 1; + rd.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + const D3D12_CLEAR_VALUE clear{DXGI_FORMAT_R32G32B32A32_FLOAT, {0.0f, 0.0f, 0.0f, 0.0f}}; + const auto target = resource(device, rd, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_RENDER_TARGET, &clear); + + D3D12_DESCRIPTOR_HEAP_DESC hd{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}; + ComPtr views, rtvs; + check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&views)), "Create image store view heap"); + device->CreateUnorderedAccessView(image.Get(), nullptr, nullptr, views->GetCPUDescriptorHandleForHeapStart()); + hd = {D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}; + check(device->CreateDescriptorHeap(&hd, IID_PPV_ARGS(&rtvs)), "Create image store 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(); + D3D12_TEXTURE_COPY_LOCATION texture_location{image.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + D3D12_TEXTURE_COPY_LOCATION upload_location{upload.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + upload_location.PlacedFootprint = footprint; + list->CopyTextureRegion(&texture_location, 0, 0, 0, &upload_location, nullptr); + transition(list, image.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->ClearRenderTargetView(rtv, clear.Color, 0, nullptr); + list->SetGraphicsRootSignature(root.Get()); + ID3D12DescriptorHeap* heaps[]{views.Get()}; + list->SetDescriptorHeaps(1, heaps); + const std::uint32_t constants[entry_constants] = {0, 0, 0, 0}; // ud0 = 0: plain triangles + list->SetGraphicsRoot32BitConstants(0, entry_constants, 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, image.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION readback_location{readback.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + readback_location.PlacedFootprint = footprint; + list->CopyTextureRegion(&readback_location, 0, 0, 0, &texture_location, nullptr); + commands.submit_and_wait(device); + + const D3D12_RANGE read{0, static_cast(bytes)}; + check(readback->Map(0, &read, &mapped), "Map image store readback"); + int result = 0; + for (UINT ty = 0; ty < side && !result; ++ty) + for (UINT tx = 0; tx < side && !result; ++tx) { + std::uint32_t texel[4]; + std::memcpy(texel, static_cast(mapped) + footprint.Offset + ty * footprint.Footprint.RowPitch + + 16 * tx, sizeof(texel)); + const bool stored = tx == x && ty == y; + const std::uint32_t want[4] = {stored ? expected[0] : untouched, stored ? expected[1] : untouched, + stored ? expected[2] : untouched, stored ? expected[3] : untouched}; + if (std::memcmp(texel, want, sizeof(texel)) != 0) { + std::fprintf(stderr, "texel_mismatch x=%u y=%u expected=%08x,%08x,%08x,%08x actual=%08x,%08x,%08x,%08x\n", + tx, ty, want[0], want[1], want[2], want[3], texel[0], texel[1], texel[2], texel[3]); + result = 1; + } + } + readback->Unmap(0, &none); + if (!result) std::printf("image store: texel (%u, %u) written, %u others untouched\n", x, y, side * side - 1); + return result; +} diff --git a/tests/startup_pixel_image_store_check.py b/tests/startup_pixel_image_store_check.py new file mode 100644 index 000000000..d09520e2b --- /dev/null +++ b/tests/startup_pixel_image_store_check.py @@ -0,0 +1,184 @@ +"""Check gfx2hlsl's pixel-stage image_store on a hand-assembled gfx1013 program (#1996 item F). + +The pixel program loads an image descriptor from descriptor table 0, sets the texel address (1, 2) and +four distinct binary32 values, stores them with image_store ... dmask:0xf dim:SQ_RSRC_IMG_2D, and exports +the same values to mrt0. The words were assembled by hand from the MIMG layout and are decoded back by +tools/disasm_rdna2.py here; --llvm-mc reassembles the source and compares the words. + +Without arguments: translation controls and refusals. With draw: also compile the translation with DXC and +draw it through offscreen_check --startup-image-store, which reads every texel of a 4x4 image back. Negative +controls: the translator refuses the program when the lowering is removed, and the translated shader with +its store deleted, or with x and y exchanged, leaves texel (1, 2) at its starting value. +""" +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +sys.path.insert(0, str(HERE.parent / 'tools')) +from startup_image_3d_check import FULLSCREEN_VS, G, VS_WORDS, assemble, compile_hlsl, root_blob # noqa: E402 +import disasm_rdna2 as D # noqa: E402 + +VALUES = (1.0, 2.0, 3.0, 4.0) +BITS = ['%08x' % struct.unpack(' w0 : register(u0);' in ps, ps + assert ' ' + STORE_LINE in ps, ps + assert 'register(t' not in ps, ps + assert 'uav 0 tex2d table 0 0' in manifest and 'srv ' not in manifest, manifest + assert manifest.startswith('x2w-manifest 2\n'), manifest + print('store: %s manifest uav 0 tex2d table 0 0' % STORE_LINE) + + # Cache-policy bits do not change the written texel. + for name, store in (('glc', patched(1, 0x20)), ('slc', patched(3, 0x02)), ('dlc', patched(0, 0x80))): + assert D.decode_instruction(store, 0)[2].endswith(' ' + name), D.decode_instruction(store, 0) + assert STORE_LINE in translate(with_store(store)).hlsl_ps(), name + print('glc, slc and dlc accepted') + + # Refusals, each by name: packed data or addresses, fault-status returns, a 128-bit descriptor, unorm, + # a partial channel mask and other image dimensions. + cases = (('d16', patched(7, 0x80)), ('a16', patched(7, 0x40)), ('tfe', patched(2, 0x01)), + ('lwe', patched(2, 0x02)), ('r128', patched(1, 0x80)), ('reserved', patched(1, 0x40)), + ('unorm', patched(1, 0x10)), + ('dmask 0x7', patched(1, 0, 0x07)), ('dmask 0x1', patched(1, 0, 0x01)), + ('SQ_RSRC_IMG_3D', bytes.fromhex('100f20f000040400')), + ('SQ_RSRC_IMG_2D_ARRAY', bytes.fromhex('280f20f000040400')), + ('SQ_RSRC_IMG_1D', bytes.fromhex('000f20f000040400'))) + for name, store in cases: + decoded = D.decode_instruction(store, 0)[2] + message = refused(with_store(store), 'image_store') + print('refused %-20s %s' % (name + ':', message)) + assert decoded.startswith('image_store'), decoded + refused(with_store(bytes.fromhex('080f24f000040400')), 'image_store_mip') + print('refused image_store_mip (not lowered)') + try: + pipe.vs.op_image_store(['v[4:7]', 'v[0:1]', 's[16:23]'], ['dmask:0xf', 'dim:SQ_RSRC_IMG_2D']) + except G.Unsupported as error: + assert 'outside a pixel stage' in str(error), error + else: + raise AssertionError('vertex-stage image_store accepted') + print('refused image_store outside a pixel stage') + + # Reading and storing the same image in one program would need a read-write view: refused. + load = bytes.fromhex('080f00f000080400') # image_load v[8:11], v[0:1], s[16:23] dmask:0xf dim:2D + assert D.decode_instruction(load, 0)[2].startswith('image_load v[8:11]'), D.decode_instruction(load, 0) + refused(PREFIX + load + STORE + SUFFIX, 'both read and stored') + assert translate(PREFIX + load + SUFFIX).manifest().startswith('x2w-manifest 1\n') + print('refused a load and a store of the same image') + + # Negative control: without the lowering the program is refused as before. + lowering = G.Stage.op_image_store + del G.Stage.op_image_store + try: + refused(WORDS, 'image_store') + finally: + G.Stage.op_image_store = lowering + print('control: with op_image_store removed the program is refused') + + +def check_binary(llvm_mc): + built = assemble(llvm_mc, SOURCE) + if built != WORDS: + raise AssertionError('assembled %s, recorded %s' % (built.hex(), WORDS.hex())) + print('fixture words match llvm-mc') + + +def check_draw(dxc, renderer, adapter): + source = translate(WORDS).hlsl_ps() + expected = ','.join(BITS) + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + vs = compile_hlsl(dxc, 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', directory) + + def draw(text, label): + ps = compile_hlsl(dxc, 'dxc', text, label, 'ps_6_0', directory) + return subprocess.run([renderer, adapter, '--startup-image-store', str(vs), str(ps), '1,2', expected], + capture_output=True, text=True) + + run = draw(source, 'store') + sys.stdout.write(run.stdout) + if run.returncode == 77: + sys.exit(77) + if run.returncode: + raise AssertionError('store draw failed\n%s\n%s' % (run.stdout, run.stderr)) + print('draw: texel (1, 2) = %s, all other texels untouched' % expected) + untouched = 'actual=' + ','.join(['bf800000'] * 4) + for label, text, needle in ( + ('store deleted', source.replace(STORE_LINE, ''), 'x=1 y=2 expected=%s %s' % (expected, untouched)), + ('x and y exchanged', source.replace('w0[uint2(v0, v1)]', 'w0[uint2(v1, v0)]'), 'x=2 y=1')): + assert text != source, label + run = draw(text, label.replace(' ', '_')) + if run.returncode == 0 or 'texel_mismatch ' + needle not in run.stderr: + raise AssertionError('control %s was not detected\n%s\n%s' % (label, run.stdout, run.stderr)) + print('control %s: fails as expected (%s)' % (label, run.stderr.strip().splitlines()[0])) + + +def main(): + controls() + if len(sys.argv) == 1: + return + mode, *args = sys.argv[1:] + if mode == 'binary': + check_binary(*args) + elif mode == 'draw': + check_draw(*args) + else: + raise SystemExit(__doc__) + + +if __name__ == '__main__': + main() diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 6c816ffb2..2614761d3 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1462,6 +1462,50 @@ def op_image_load(self, ops, mods): def op_image_load_mip(self, ops, mods): self.image(ops, mods, 'load_mip') + def op_image_store(self, ops, mods): + """image_store in a pixel stage: a typed store of four channels to one texel of a 2D image. + + MIMG opcode 0x08 (LLVM AMDGPU MIMGInstructions.td, IMAGE_STORE via MIMG_Store): VDATA is the + source, VADDR the integer texel address (x, y for dim 2D) and SRSRC the image descriptor; the + channels selected by DMASK are written in order from consecutive VDATA registers. HLSL's typed UAV + store writes every channel of the view, so only DMASK 0xf is exact here; a partial mask would need a + read-modify-write and is refused. The data is stored as float4, so the bound view must be of a + float or normalized format (the runtime side is not part of this lowering). The store runs under the + lane's exec bit, like the other per-lane writes, and D3D drops UAV writes from helper lanes as the + hardware drops them for lanes outside exec. + """ + name = 'image_store' + if self.kind != 'ps': + raise Unsupported('%s outside a pixel stage' % name) + if len(ops) != 3: + raise Unsupported('%s with %d operands' % (name, len(ops))) + for m in mods: + if not (m.startswith(('dim:', 'dmask:')) or m in ('dlc', 'glc', 'slc')): + raise Unsupported('%s modifier %s' % (name, m)) + dims = [m[4:] for m in mods if m.startswith('dim:')] + masks = [m[6:] for m in mods if m.startswith('dmask:')] + if len(dims) != 1 or len(masks) != 1: + raise Unsupported('%s without exactly one dim and dmask' % name) + if dims[0] != 'SQ_RSRC_IMG_2D': + raise Unsupported('%s on %s: only 2D images are lowered' % (name, dims[0])) + if int(masks[0], 0) != 0xf: + raise Unsupported('%s with dmask %s: a typed UAV store writes all four channels' % (name, masks[0])) + data = reg_range(ops[0]) + if not data or data[0] != 'v' or data[2] - data[1] != 3: + raise Unsupported('%s data %s: four VGPRs expected' % (name, ops[0])) + coords = ops[1] + if coords.startswith('['): + cs = [c.strip() for c in coords[1:-1].split(',')] + else: + r = reg_range(coords) + cs = ['v%d' % n for n in range(r[1], r[2] + 1)] if r and r[0] == 'v' else [] + if len(cs) != 2: + raise Unsupported('%s with %d address registers: x and y expected' % (name, len(cs))) + image = self.pipe.uav(self.descriptor(ops[2]), 'tex2d') + value = 'asfloat(uint4(%s))' % ', '.join(self.u('v%d' % n) for n in range(data[1], data[1] + 4)) + body = '%s[uint2(%s, %s)] = %s;' % (image, self.u(cs[0]), self.u(cs[1]), value) + self.emit(body if self.exec_known else 'if (exec & 1) ' + body) + def op_image_gather4_lz(self, ops, mods): name = 'image_gather4_lz' if self.kind != 'ps' or len(ops) != 4: @@ -2114,6 +2158,7 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap self.uses_sampler_heap = False self.resources = {} # key -> dict(index, kind) + self.uavs = {} # key -> dict(index, kind): images a pixel stage stores to (u registers) self.samplers = {} # key -> index self.uds = [] # entry-constant sources self.notes = set() # shortcuts taken (written to the manifest as comments) @@ -2154,11 +2199,26 @@ def ud(self, source): return self.uds.index(source) def resource(self, key, kind): + if key in self.stored_images(): + raise Unsupported('resource %s is both read and stored to' % (key,)) r = self.resources.setdefault(key, dict(index=len(self.resources), kind=kind)) if r['kind'] != kind: raise Unsupported('resource %s used as %s and %s' % (key, r['kind'], kind)) return 'r%d' % r['index'] + def stored_images(self): + # Pipelines that tests assemble without __init__ have no uavs attribute: they store to no image. + return self.__dict__.setdefault('uavs', {}) + + def uav(self, key, kind): + if key in self.resources: + raise Unsupported('resource %s is both read and stored to' % (key,)) + uavs = self.stored_images() + r = uavs.setdefault(key, dict(index=len(uavs), kind=kind)) + if r['kind'] != kind: + raise Unsupported('stored image %s used as %s and %s' % (key, r['kind'], kind)) + return 'w%d' % r['index'] + def sampler(self, key, comparison=False): if not isinstance(key[0], int): raise Unsupported('sampler from a descriptor') @@ -2217,6 +2277,8 @@ def common(self): 'cbuffer entry : register(b0) { %s };' % ' '.join('uint ud%d;' % i for i in range(len(self.uds)))] for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): out.append('%s r%d : register(t%d);' % ({'buf': 'ByteAddressBuffer', 'tex1d': 'Texture1D', 'tex2d': 'Texture2D', 'tex2da': 'Texture2DArray', 'tex3d': 'Texture3D'}[r['kind']], r['index'], r['index'])) + for key, r in sorted(self.stored_images().items(), key=lambda kv: kv[1]['index']): + out.append('%s w%d : register(u%d);' % ({'tex2d': 'RWTexture2D'}[r['kind']], r['index'], r['index'])) for key, i in self.samplers.items(): out.append('%s q%d : register(s%d);' % ('SamplerComparisonState' if key[0] == 'cmp' else 'SamplerState', i, i)) if self.uses_sampler_heap: @@ -2291,7 +2353,8 @@ def hlsl_ps(self): return '\n'.join(out) + '\n' def manifest(self): - lines = ['x2w-manifest 1', 'ud %d' % len(self.uds)] + # A manifest that names a writable view is version 2, so a runtime that reads only version 1 lines can tell. + lines = ['x2w-manifest %d' % (2 if self.stored_images() else 1), 'ud %d' % len(self.uds)] for i, source in enumerate(self.uds): lines.append('udsrc %d %s' % (i, ' '.join(str(x) for x in source))) for key, r in sorted(self.resources.items(), key=lambda kv: kv[1]['index']): @@ -2301,6 +2364,11 @@ def manifest(self): if where is None: raise Unsupported('resource through %s' % (source,)) lines.append('srv %d %s %s' % (r['index'], r['kind'], where)) + for key, r in sorted(self.stored_images().items(), key=lambda kv: kv[1]['index']): + source, off = key + if source[0] != 'table': + raise Unsupported('stored image through %s' % (source,)) + lines.append('uav %d %s table %d %d' % (r['index'], r['kind'], source[1] if len(source) > 1 else 0, off or 0)) for key, i in self.samplers.items(): comparison = key[0] == 'cmp' lines.append('%s %d %s' % ('smpc' if comparison else 'smp', i, ' '.join('0x%x' % w for w in key[comparison:]))) From 733bd1345b1588ed6aa6a19f676c30b9f7fceda3 Mon Sep 17 00:00:00 2001 From: rasptum <348594691+rasptum@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:14:03 -0500 Subject: [PATCH 2/9] startup: check the image_store dmask guard itself The two encoded partial-mask controls only asserted that image_store was refused. The decoder sizes VDATA from the mask (v[4:6], v4), so with the dmask guard disabled the data-register check still refused them and the controls passed. Each now asserts the dmask reason, and a new control calls the handler with v[4:7] and dmask 0x7, which only the mask guard can refuse; another passes dmask 0xf with three data registers and asserts the data reason. With the guard replaced by `if False:` the check fails. Co-Authored-By: Claude Opus 5.5 --- tests/startup_pixel_image_store_check.py | 25 +++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/tests/startup_pixel_image_store_check.py b/tests/startup_pixel_image_store_check.py index d09520e2b..89e82969f 100644 --- a/tests/startup_pixel_image_store_check.py +++ b/tests/startup_pixel_image_store_check.py @@ -94,7 +94,6 @@ def controls(): cases = (('d16', patched(7, 0x80)), ('a16', patched(7, 0x40)), ('tfe', patched(2, 0x01)), ('lwe', patched(2, 0x02)), ('r128', patched(1, 0x80)), ('reserved', patched(1, 0x40)), ('unorm', patched(1, 0x10)), - ('dmask 0x7', patched(1, 0, 0x07)), ('dmask 0x1', patched(1, 0, 0x01)), ('SQ_RSRC_IMG_3D', bytes.fromhex('100f20f000040400')), ('SQ_RSRC_IMG_2D_ARRAY', bytes.fromhex('280f20f000040400')), ('SQ_RSRC_IMG_1D', bytes.fromhex('000f20f000040400'))) @@ -103,6 +102,30 @@ def controls(): message = refused(with_store(store), 'image_store') print('refused %-20s %s' % (name + ':', message)) assert decoded.startswith('image_store'), decoded + # A partial channel mask, encoded: the decoder sizes VDATA from the mask (v[4:6], v4), so each must be + # refused for the mask itself, which the translator checks before the data registers. + for mask, data in ((0x7, 'v[4:6]'), (0x1, 'v4')): + store = patched(1, 0, mask) + decoded = D.decode_instruction(store, 0)[2] + assert decoded.startswith('image_store %s, ' % data) and 'dmask:%#x' % mask in decoded, decoded + message = refused(with_store(store), 'dmask %#x' % mask, 'writes all four channels') + print('refused %-20s %s' % ('dmask %#x:' % mask, message)) + # The same partial mask with four data registers, through the handler: only the mask guard can refuse it. + try: + pipe.ps.op_image_store(['v[4:7]', 'v[0:1]', 's[16:23]'], ['dmask:0x7', 'dim:SQ_RSRC_IMG_2D']) + except G.Unsupported as error: + assert 'dmask 0x7' in str(error) and 'writes all four channels' in str(error), error + else: + raise AssertionError('a partial dmask with four data registers was accepted') + print('refused dmask 0x7 with four data registers (v[4:7])') + # Four data registers are required for the full mask: three are refused for the data, not the mask. + try: + pipe.ps.op_image_store(['v[4:6]', 'v[0:1]', 's[16:23]'], ['dmask:0xf', 'dim:SQ_RSRC_IMG_2D']) + except G.Unsupported as error: + assert 'four VGPRs expected' in str(error), error + else: + raise AssertionError('dmask 0xf with three data registers was accepted') + print('refused dmask 0xf with three data registers (v[4:6])') refused(with_store(bytes.fromhex('080f24f000040400')), 'image_store_mip') print('refused image_store_mip (not lowered)') try: From 352bae3d881af4d6199fdcc627b5f67ccf908131 Mon Sep 17 00:00:00 2001 From: rasptum <348594691+rasptum@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:14:03 -0500 Subject: [PATCH 3/9] startup: give Pipeline.uavs a class default instead of a __dict__ fallback Pipelines that tests assemble without __init__ store to no image. A class attribute of None now says so; the first store creates the instance's own map. Co-Authored-By: Claude Opus 5.5 --- tools/startup/gfx2hlsl.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 2614761d3..277526191 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2140,6 +2140,8 @@ def parse_root(blob): class Pipeline: + uavs = None # key -> dict(index, kind): images a pixel stage stores to (u registers); None until the first store + def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=(), ps_hw_inputs=None, vs_fetch=None, refusals=None, decoded=None): self.root = parse_root(root_blob) @@ -2158,7 +2160,6 @@ def __init__(self, vs_code, ps_code, root_blob, sampler_heap=None, rtv_formats=( self.sampler_heap = os.environ.get('X2W_SAMPLER_HEAP') == '1' if sampler_heap is None else sampler_heap self.uses_sampler_heap = False self.resources = {} # key -> dict(index, kind) - self.uavs = {} # key -> dict(index, kind): images a pixel stage stores to (u registers) self.samplers = {} # key -> index self.uds = [] # entry-constant sources self.notes = set() # shortcuts taken (written to the manifest as comments) @@ -2207,14 +2208,14 @@ def resource(self, key, kind): return 'r%d' % r['index'] def stored_images(self): - # Pipelines that tests assemble without __init__ have no uavs attribute: they store to no image. - return self.__dict__.setdefault('uavs', {}) + return self.uavs or {} def uav(self, key, kind): if key in self.resources: raise Unsupported('resource %s is both read and stored to' % (key,)) - uavs = self.stored_images() - r = uavs.setdefault(key, dict(index=len(uavs), kind=kind)) + if self.uavs is None: + self.uavs = {} + r = self.uavs.setdefault(key, dict(index=len(self.uavs), kind=kind)) if r['kind'] != kind: raise Unsupported('stored image %s used as %s and %s' % (key, r['kind'], kind)) return 'w%d' % r['index'] From 96c1a55b381d3b3f464c857f571b8fdd5106d425 Mon Sep 17 00:00:00 2001 From: rasptum <348594691+rasptum@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:14:04 -0500 Subject: [PATCH 4/9] docs: rewrap the pixel-stage image store bullet Co-Authored-By: Claude Opus 5.5 --- docs/startup-runtime.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 76c32f8b7..f9b8fcfd0 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1137,13 +1137,13 @@ These are measured on one executable; treat them as hypotheses for others. (`ctest --preset release --no-tests=error -R "^startup_image_3d_"`). - **Pixel-stage image stores.** In a pixel stage, `image_store` with `dim:SQ_RSRC_IMG_2D` and `dmask:0xf` becomes a typed store to a `RWTexture2D` at its own `u` register, under the - lane's exec bit, and the manifest becomes version 2 with a `uav tex2d table
` - line. The cache-policy - bits are accepted. A partial channel mask (a typed store writes all four channels), other dimensions, - `d16`, `a16`, `tfe`, `lwe`, `r128`, `unorm`, `image_store_mip`, a store outside a pixel stage, and a - program that loads and stores the same image are refused by name. The runtime does not bind UAVs on the - translated graphics path yet: it logs and does not use a translation whose manifest has a `uav` line. - A hand-assembled program stores four distinct values at texel (1, 2). The desktop draw reads all 16 + lane's exec bit, and the manifest becomes version 2 with a + `uav tex2d table
` line. The cache-policy bits are accepted. A partial + channel mask (a typed store writes all four channels), other dimensions, `d16`, `a16`, `tfe`, + `lwe`, `r128`, `unorm`, `image_store_mip`, a store outside a pixel stage, and a program that loads + and stores the same image are refused by name. The runtime does not bind UAVs on the translated + graphics path yet: it logs and does not use a translation whose manifest has a `uav` line. A + hand-assembled program stores four distinct values at texel (1, 2). The desktop draw reads all 16 texels of a 4x4 image back; deleting the store or exchanging x and y must fail. Run `ctest --preset release --no-tests=error -R '^startup_pixel_image_store_' -V`. - **Explicit mip loads.** For 2D textures, 2D arrays and 3D textures, `image_load_mip` passes the final From 2aa673d53884b5d40252d0a1e68679ca09831006 Mon Sep 17 00:00:00 2001 From: rasptum <348594691+rasptum@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:13:31 -0500 Subject: [PATCH 5/9] startup: refuse malformed image_store dmask text by name int(masks[0], 0) raised ValueError on mask text that is not an integer; it is now an Unsupported refusal ("not an integer"), with a control. Co-Authored-By: Claude Opus 5.5 --- tests/startup_pixel_image_store_check.py | 8 ++++++++ tools/startup/gfx2hlsl.py | 6 +++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/tests/startup_pixel_image_store_check.py b/tests/startup_pixel_image_store_check.py index 89e82969f..48ae6c798 100644 --- a/tests/startup_pixel_image_store_check.py +++ b/tests/startup_pixel_image_store_check.py @@ -126,6 +126,14 @@ def controls(): else: raise AssertionError('dmask 0xf with three data registers was accepted') print('refused dmask 0xf with three data registers (v[4:6])') + # Mask text that is not an integer is a named refusal, not a ValueError. + try: + pipe.ps.op_image_store(['v[4:7]', 'v[0:1]', 's[16:23]'], ['dmask:0xz', 'dim:SQ_RSRC_IMG_2D']) + except G.Unsupported as error: + assert str(error) == 'image_store with dmask 0xz: not an integer', error + else: + raise AssertionError('a malformed dmask was accepted') + print('refused dmask 0xz (not an integer)') refused(with_store(bytes.fromhex('080f24f000040400')), 'image_store_mip') print('refused image_store_mip (not lowered)') try: diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 277526191..e1aa1bd51 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -1488,7 +1488,11 @@ def op_image_store(self, ops, mods): raise Unsupported('%s without exactly one dim and dmask' % name) if dims[0] != 'SQ_RSRC_IMG_2D': raise Unsupported('%s on %s: only 2D images are lowered' % (name, dims[0])) - if int(masks[0], 0) != 0xf: + try: + mask = int(masks[0], 0) + except ValueError: + raise Unsupported('%s with dmask %s: not an integer' % (name, masks[0])) from None + if mask != 0xf: raise Unsupported('%s with dmask %s: a typed UAV store writes all four channels' % (name, masks[0])) data = reg_range(ops[0]) if not data or data[0] != 'v' or data[2] - data[1] != 3: From 7ee19fa945ed5c347a54cdb8efa63bfae1403b94 Mon Sep 17 00:00:00 2001 From: rasptum <348594691+rasptum@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:13:52 -0500 Subject: [PATCH 6/9] startup: check the image_store exec guard Two variants put v_cmpx_eq_u32 before the store so exec is not known at translation time. The controls assert that the emitted store is guarded by the lane's exec bit, and the draw mode reads the image back: with the lane on the texel is written, with every lane off it keeps its starting value, and the exec-off shader with the guard removed must write it. Co-Authored-By: Claude Opus 5.5 --- tests/startup_pixel_image_store_check.py | 49 +++++++++++++++++++++++- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/tests/startup_pixel_image_store_check.py b/tests/startup_pixel_image_store_check.py index 48ae6c798..3eba97cab 100644 --- a/tests/startup_pixel_image_store_check.py +++ b/tests/startup_pixel_image_store_check.py @@ -9,6 +9,11 @@ draw it through offscreen_check --startup-image-store, which reads every texel of a 4x4 image back. Negative controls: the translator refuses the program when the lowering is removed, and the translated shader with its store deleted, or with x and y exchanged, leaves texel (1, 2) at its starting value. + +The store runs under the lane's exec bit. Two variants put v_cmpx_eq_u32 before the store, so exec is not +known at translation time: with 1 == v0 the lane stays on and the texel is written, with 2 == v0 every lane +is off and the texel keeps its starting value. A control draws the exec-off variant with the guard removed +from the store and must see the texel written. """ import struct import subprocess @@ -45,6 +50,17 @@ SUFFIX = bytes.fromhex('703f8cbf' '0f1800f804050607' '000081bf') WORDS = PREFIX + STORE + SUFFIX STORE_LINE = 'w0[uint2(v0, v1)] = asfloat(uint4(v4, v5, v6, v7));' +GUARDED_LINE = 'if (exec & 1) ' + STORE_LINE + + +def cmpx_eq(constant): + """v_cmpx_eq_u32_e32 , v0: VOPC (bits 31:25 = 0x3e), opcode 0xd2, VSRC1 v0, SRC0 an inline + integer 1..64 (0x80 + n). In gfx10 the VOPC v_cmpx form writes only exec.""" + return struct.pack(' Date: Wed, 25 Nov 2026 01:21:09 -0500 Subject: [PATCH 7/9] startup: keep compute buffer UAVs out of the pixel-stage image list ComputePipeline (#2182) maps buffer descriptors to u indices in self.uavs and declares them itself; the inherited common() and manifest() read stored_images() as pixel-stage image entries, which a compute program cannot have. startup_gfx2hlsl_compute_check.py fails without this. Co-Authored-By: Claude Opus 5.5 --- tools/startup/gfx2hlsl.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index 873737977..f7e5aefe4 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -3471,6 +3471,11 @@ def uav(self, key): raise Unsupported('descriptor %s used for a load and a store' % (key,)) return 'u%d' % self.uavs.setdefault(key, len(self.uavs)) + def stored_images(self): + # self.uavs here maps buffer descriptors to u indices (declared and listed by common() and manifest() + # below); the pixel-stage image stores that Pipeline.stored_images lists do not occur in a compute program. + return {} + def common(self): out = [line for line in super().common() if self.uds or not line.startswith('cbuffer entry')] return out + ['RWByteAddressBuffer u%d : register(u%d);' % (i, i) for i in sorted(self.uavs.values())] From 81ca8985e5613c9d3a310df132f4dc3d12ccda0e Mon Sep 17 00:00:00 2001 From: rasptum <348594691+rasptum@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:50:44 -0500 Subject: [PATCH 8/9] startup: name the texel_mismatch line in the image store controls The controls printed the first stderr line as the reason, which on a machine with several adapters is an adapter notice. They now print the texel_mismatch report they already assert on. Co-Authored-By: Claude Opus 5.5 --- tests/startup_pixel_image_store_check.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/tests/startup_pixel_image_store_check.py b/tests/startup_pixel_image_store_check.py index 3eba97cab..89b31d07d 100644 --- a/tests/startup_pixel_image_store_check.py +++ b/tests/startup_pixel_image_store_check.py @@ -196,6 +196,11 @@ def check_binary(llvm_mc): print('fixture words match llvm-mc') +def mismatch_line(stderr): + """The texel_mismatch report: on a machine with several adapters stderr starts with adapter notices.""" + return next(line for line in stderr.splitlines() if 'texel_mismatch ' in line) + + def check_draw(dxc, renderer, adapter): source = translate(WORDS).hlsl_ps() expected = ','.join(BITS) @@ -223,7 +228,7 @@ def draw(text, label, want=expected): run = draw(text, label.replace(' ', '_')) if run.returncode == 0 or 'texel_mismatch ' + needle not in run.stderr: raise AssertionError('control %s was not detected\n%s\n%s' % (label, run.stdout, run.stderr)) - print('control %s: fails as expected (%s)' % (label, run.stderr.strip().splitlines()[0])) + print('control %s: fails as expected (%s)' % (label, mismatch_line(run.stderr))) # Exec after v_cmpx: an active lane writes the texel, an inactive one leaves it at its starting value. untouched_bits = ','.join(['bf800000'] * 4) @@ -240,7 +245,7 @@ def draw(text, label, want=expected): needle = 'texel_mismatch x=1 y=2 expected=%s actual=%s' % (untouched_bits, expected) if run.returncode == 0 or needle not in run.stderr: raise AssertionError('control exec guard removed was not detected\n%s\n%s' % (run.stdout, run.stderr)) - print('control exec guard removed: fails as expected (%s)' % run.stderr.strip().splitlines()[0]) + print('control exec guard removed: fails as expected (%s)' % mismatch_line(run.stderr)) def main(): From 949497eb4d5521cf6fdbdeeb1f2a52810279585f Mon Sep 17 00:00:00 2001 From: rasptum <348594691+rasptum@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:35:32 -0500 Subject: [PATCH 9/9] startup: check that a compute program lists no pixel-stage image stores The compute stage's buffer stores live in self.uavs (descriptor key -> u index), which the shared common() and manifest() must not read as #2155's image stores. The control asserts stored_images() is empty before any output is built, then no RWTexture2D declaration, the `x2w-manifest 2` / `stage cs` header and the single kind-less uav line. With ComputePipeline.stored_images removed it fails at that assertion. Co-Authored-By: Claude Opus 5.5 --- tests/startup_gfx2hlsl_compute_check.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/startup_gfx2hlsl_compute_check.py b/tests/startup_gfx2hlsl_compute_check.py index 70ab2a1ac..ebce86f47 100644 --- a/tests/startup_gfx2hlsl_compute_check.py +++ b/tests/startup_gfx2hlsl_compute_check.py @@ -230,7 +230,14 @@ def patch(words, old, new): def check_controls(): a = translate('A') + # The compute stage keeps its buffer stores in self.uavs as descriptor key -> u index, while the pixel stage's + # image stores (#2155) are listed by stored_images() through the shared common() and manifest(). A compute + # program must list no image stores: no RWTexture2D declaration and no `uav tex2d` line. + assert a.uavs and a.stored_images() == {}, (a.uavs, a.stored_images()) hlsl, manifest = a.hlsl_cs(), a.manifest() + assert not any(line.startswith('RWTexture2D') for line in hlsl.splitlines()), hlsl + assert manifest.splitlines()[:2] == ['x2w-manifest 2', 'stage cs'], manifest + assert [line for line in manifest.splitlines() if line.startswith('uav ')] == ['uav 0 table 1 16'], manifest for line in ('[numthreads(2, 3, 4)]', 'void main(uint3 gid : SV_GroupID, uint3 tid : SV_GroupThreadID) {', ' s7 = gid.x;', ' s8 = gid.y;', ' s9 = gid.z;', ' v0 = tid.x;', ' v1 = tid.y;', ' v2 = tid.z;', 'ByteAddressBuffer r0 : register(t0);', 'RWByteAddressBuffer u0 : register(u0);',