diff --git a/CMakeLists.txt b/CMakeLists.txt index 20ff1a897..ca89f6b29 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1380,6 +1380,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. @@ -2693,6 +2694,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 2ffac44a4..5d18a2cce 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1492,6 +1492,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 48842bcdc..19557a669 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -185,6 +185,12 @@ void load_translation(Translation& tr, const std::string& rtv_request = {}) log("x2w-draw invalid d16srv 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 303325cfd..d8917fe11 100644 --- a/tests/desktop_gpu.h +++ b/tests/desktop_gpu.h @@ -26,6 +26,8 @@ void check_startup_image_3d(ID3D12Device* device, const char* vertex_path, const bool one_dimensional = false, bool two_dimensional = false); void check_startup_image_load_d16(ID3D12Device* device, const char* vertex_path, const char* pixel_path, bool depth16, std::uint32_t words[64]); +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 d24e46b9b..d32de744d 100644 --- a/tests/offscreen_check.cpp +++ b/tests/offscreen_check.cpp @@ -1260,6 +1260,20 @@ OperationResult run_startup_image_load_d16(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; @@ -1450,6 +1464,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-image-load-d16", 7, 7, nullptr, kNoGate, run_startup_image_load_d16}, 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);', 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..89b31d07d --- /dev/null +++ b/tests/startup_pixel_image_store_check.py @@ -0,0 +1,265 @@ +"""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. + +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 +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(', 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(' 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)), + ('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 + # 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])') + # 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: + 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') + + # Exec not known at translation time: the store, and only the store line, is guarded by the lane's bit. + for constant, words in ((1, EXEC_ON), (2, EXEC_OFF)): + decoded = D.decode_instruction(cmpx_eq(constant), 0)[2] + assert decoded == 'v_cmpx_eq_u32_e32 %d, v0' % constant, decoded + ps = translate(words).hlsl_ps() + assert ' exec = ((0x%08xu == v0) ? 1u : 0u);' % constant in ps, ps + assert ' ' + GUARDED_LINE in ps, ps + assert ps.count(STORE_LINE) == 1, ps + # With exec known (the entry mask) the store is not guarded. + assert GUARDED_LINE not in translate(WORDS).hlsl_ps() + print('exec after v_cmpx: %s' % GUARDED_LINE) + + # 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 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) + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + vs = compile_hlsl(dxc, 'dxc', FULLSCREEN_VS, 'fullscreen', 'vs_6_0', directory) + + def draw(text, label, want=expected): + 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', want], + 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, 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) + on, off = translate(EXEC_ON).hlsl_ps(), translate(EXEC_OFF).hlsl_ps() + for label, text, want in (('exec on', on, expected), ('exec off', off, untouched_bits)): + run = draw(text, label.replace(' ', '_'), want) + if run.returncode: + raise AssertionError('%s draw failed\n%s\n%s' % (label, run.stdout, run.stderr)) + print('draw %s: texel (1, 2) = %s, all other texels untouched' % (label, want)) + # Control: the exec-off shader with the guard removed from the store writes the texel. + unguarded = off.replace(GUARDED_LINE, STORE_LINE) + assert unguarded != off + run = draw(unguarded, 'exec_off_unguarded', untouched_bits) + 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)' % mismatch_line(run.stderr)) + + +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 b91a0a0d1..5fb89fc9b 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -2181,6 +2181,54 @@ 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])) + 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: + 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: @@ -3125,6 +3173,7 @@ def read(fmt, data, offset): class Pipeline: uses_pack16_rne = False srv_formats = () + 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, ps_attr_map=None, srv_formats=(), pk_u8_s0_contract=False): @@ -3207,11 +3256,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): + 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,)) + 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'] + def sampler(self, key, comparison=False, lod_limits=False): if not isinstance(key[0], int): raise Unsupported('sampler from a descriptor') @@ -3275,6 +3339,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: @@ -3394,7 +3460,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']): @@ -3406,6 +3473,11 @@ def manifest(self): lines.append('srv %d %s %s' % (r['index'], r['kind'], where)) if r.get('d16_exact'): lines.append('d16srv %d exact' % r['index']) + 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(): prefixed = key[0] in ('cmp', 'lod') lines.append('%s %d %s' % ({'cmp': 'smpc', 'lod': 'smpl'}.get(key[0], 'smp'), i, @@ -3452,6 +3524,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())]