From 9a7e98a3f0a2a3286b431c4069ce1b576b991bdf Mon Sep 17 00:00:00 2001 From: R0D4X Date: Thu, 26 Nov 2026 13:36:37 +0100 Subject: [PATCH] startup: support pixel-stage 2D-array image_store and UAV binding --- src/startup_stubs/d3d12_draw.inl | 55 ++++++--- tests/startup_pixel_image_store_check.py | 63 +++++++++- tests/startup_pixel_uav.cpp | 138 +++++++++++++++++++++- tests/startup_pixel_uav_check.py | 142 +++++++++++++++++++---- tools/startup/gfx2hlsl.py | 2 +- 5 files changed, 356 insertions(+), 44 deletions(-) diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 6b4e009435..8e05e5d7a9 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -9,11 +9,12 @@ // buffers named by the hardware descriptors in its tables, textures behind view tokens) into an // upload ring / a private descriptor heap. -// A pixel-stage image store (#1996 item F): tools/startup/gfx2hlsl.py writes 'uav N tex2d table P O' for the -// RWTexture2D at u, whose descriptor is at byte O of the title's root table P. Only that form is -// read; a view qualifier or a 'channels' field, as in the compute line, is refused. +// 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 +// root table P. Only that form is read; a view qualifier or a 'channels' field, as in the compute line, is refused. struct PixelUav { unsigned index = 0, parameter = 0, offset = 0; + bool array = false; }; constexpr unsigned pixel_uav_limit = 8; @@ -34,7 +35,8 @@ const char* read_pixel_uav_line(const std::string& line, PixelUav& out) if (w.size() < 2 || w[0] != "uav" || !number(w[1], out.index)) return "malformed view index"; if (w.size() < 3) return "missing view kind"; if (w[2] == "raw" || w[2] == "table") return "buffer view (raw uav) is not bound"; - if (w[2] != "tex2d") return "only tex2d views are bound"; + if (w[2] != "tex2d" && w[2] != "tex2da") return "only tex2d and tex2da views are bound"; + out.array = w[2] == "tex2da"; if (w.size() > 3 && (w[3] == "float" || w[3] == "uint" || w[3] == "sint")) return "a view qualifier is not read for pixel stores"; if (w.size() < 4 || w[3] != "table") return "view source is not a table"; if (w.size() < 6) return "missing table parameter or offset"; @@ -84,18 +86,29 @@ bool srgb_uav_format(DXGI_FORMAT format) format == DXGI_FORMAT_B8G8R8X8_UNORM_SRGB; } -// The view of mip 0 of a 2D texture for a pixel UAV. resource is the desktop description, title_view the title's -// own view (nullptr when it passed none) with console format values already mapped. Returns nullptr and fills -// out, or the reason the binding is refused. +// The view of mip 0 of a 2D or 2D-array texture for a pixel UAV. resource is the desktop description, title_view +// the title's own view (nullptr when it passed none) with console format values already mapped, and array is true +// for a manifest 'tex2da' view. Returns nullptr and fills out, or the reason the binding is refused. const char* pixel_uav_view(ID3D12Device* device, const D3D12_RESOURCE_DESC& resource, - const D3D12_UNORDERED_ACCESS_VIEW_DESC* title_view, D3D12_UNORDERED_ACCESS_VIEW_DESC& out) + const D3D12_UNORDERED_ACCESS_VIEW_DESC* title_view, bool array, + D3D12_UNORDERED_ACCESS_VIEW_DESC& out) { if (resource.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return "resource is not a 2D texture"; - if (resource.DepthOrArraySize != 1) return "resource is a texture array"; + if (!array && resource.DepthOrArraySize != 1) return "resource is a texture array"; if (resource.SampleDesc.Count != 1) return "resource is multisampled"; if (!(resource.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)) return "resource lacks ALLOW_UNORDERED_ACCESS"; DXGI_FORMAT format = resource.Format; - if (title_view) { + if (array) { + if (!title_view || title_view->ViewDimension != D3D12_UAV_DIMENSION_TEXTURE2DARRAY) + return "view is not a 2D array texture view"; + const auto& a = title_view->Texture2DArray; + if (a.MipSlice != 0) return "view names a mip other than 0"; + if (a.PlaneSlice != 0) return "view names a plane other than 0"; + if (a.FirstArraySlice >= resource.DepthOrArraySize || !a.ArraySize || + a.ArraySize > resource.DepthOrArraySize - a.FirstArraySlice) + return "array view slice range is outside the resource"; + if (title_view->Format != DXGI_FORMAT_UNKNOWN) format = title_view->Format; + } else if (title_view) { if (title_view->ViewDimension != D3D12_UAV_DIMENSION_TEXTURE2D) return "view is not a 2D texture view"; if (title_view->Texture2D.MipSlice != 0) return "view names a mip other than 0"; if (title_view->Texture2D.PlaneSlice != 0) return "view names a plane other than 0"; @@ -110,7 +123,12 @@ const char* pixel_uav_view(ID3D12Device* device, const D3D12_RESOURCE_DESC& reso return "format has no typed UAV store on this device"; out = {}; out.Format = format; - out.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + if (array) { + out.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + out.Texture2DArray = title_view->Texture2DArray; + } else { + out.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + } return nullptr; } @@ -2080,7 +2098,7 @@ bool resolve_pixel_uavs(const Translation& tr, const Pass& pass, PixelUavBinding title_view.Format = desktop_format(title_view.Format); } const D3D12_RESOURCE_DESC desc = texture->GetDesc(); - const char* reason = pixel_uav_view(device_of(the_device), desc, described ? &title_view : nullptr, out[i].view); + const char* reason = pixel_uav_view(device_of(the_device), desc, described ? &title_view : nullptr, uav.array, out[i].view); if (reason) { static LONG refused_view; if (first_calls(refused_view, 16)) @@ -2539,9 +2557,16 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI require_state(self, uav_bindings[j].resource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); device_of(the_device)->CreateUnorderedAccessView(uav_bindings[j].resource, nullptr, &uav_bindings[j].view, dest); static LONG shown; - if (first_calls(shown, 6)) - log("x2w-draw %016llx uav %u: resource %p format %d mip 0", tr->key, j, static_cast(uav_bindings[j].resource), - uav_bindings[j].view.Format); + if (first_calls(shown, 6)) { + if (uav_bindings[j].view.ViewDimension == D3D12_UAV_DIMENSION_TEXTURE2DARRAY) + log("x2w-draw %016llx uav %u: resource %p format %d array [%u..%u) mip 0", tr->key, j, + static_cast(uav_bindings[j].resource), uav_bindings[j].view.Format, + uav_bindings[j].view.Texture2DArray.FirstArraySlice, + uav_bindings[j].view.Texture2DArray.FirstArraySlice + uav_bindings[j].view.Texture2DArray.ArraySize); + else + log("x2w-draw %016llx uav %u: resource %p format %d mip 0", tr->key, j, + static_cast(uav_bindings[j].resource), uav_bindings[j].view.Format); + } } static LONG checks; if ((InterlockedIncrement(&checks) & 63) == 1) check_device("translated draw views", 0); diff --git a/tests/startup_pixel_image_store_check.py b/tests/startup_pixel_image_store_check.py index 7c1c0c4aca..d87ead7525 100644 --- a/tests/startup_pixel_image_store_check.py +++ b/tests/startup_pixel_image_store_check.py @@ -45,12 +45,32 @@ s_endpgm """ STORE = bytes.fromhex('080f20f000040400') +ARRAY_STORE = bytes.fromhex('280f20f000040400') PREFIX = bytes.fromhex('04040cf4000000fa' '8102007e' '8202027e' 'f202087e' 'f4020a7e' 'ff020c7e00004040' 'f6020e7e' '7fc08cbf') 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 +ARRAY_SOURCE = SOURCE.replace( + 'image_store v[4:7], v[0:1], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D', + 'v_mov_b32 v2, 1\nimage_store v[4:7], v[0:2], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY', +) +ARRAY_STORE_LINE = 'w0[uint3(v0, v1, v2)] = asfloat(uint4(v4, v5, v6, v7));' +ARRAY_GUARDED_LINE = 'if (exec & 1) ' + ARRAY_STORE_LINE + + +def mov_v2_inline(constant): + """v_mov_b32_e32 v2, : VOP1 opcode 0x01, vdst=2, inline integer 0..64 (0x80 + n).""" + return struct.pack(', manifest tex2da. + array_text = D.decode_instruction(ARRAY_STORE, 0)[2] + assert array_text == 'image_store v[4:7], v[0:2], s[16:23] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY', array_text + array_pipe = translate(ARRAY_WORDS) + array_ps, array_manifest = array_pipe.hlsl_ps(), array_pipe.manifest() + assert 'RWTexture2DArray w0 : register(u0);' in array_ps, array_ps + assert ' ' + ARRAY_STORE_LINE in array_ps, array_ps + assert 'register(t' not in array_ps, array_ps + assert 'uav 0 tex2da table 0 0' in array_manifest and 'srv ' not in array_manifest, array_manifest + assert array_manifest.startswith('x2w-manifest 2\n'), array_manifest + print('array store: %s manifest uav 0 tex2da table 0 0' % ARRAY_STORE_LINE) + # Refusals, each by name: packed data or addresses, fault-status returns, a 128-bit descriptor, # 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)), ('SQ_RSRC_IMG_3D', bytes.fromhex('100f20f000040400')), - ('SQ_RSRC_IMG_2D_ARRAY', bytes.fromhex('280f20f000040400')), + ('SQ_RSRC_IMG_CUBE', bytes.fromhex('180f20f000040400')), ('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 + # 2D-array requires three address registers and still refuses pixel d16. + try: + array_pipe.ps.op_image_store(['v[4:7]', 'v[0:1]', 's[16:23]'], ['dmask:0xf', 'dim:SQ_RSRC_IMG_2D_ARRAY']) + except G.Unsupported as error: + assert 'x, y and layer expected' in str(error), error + else: + raise AssertionError('2D-array store with two address registers was accepted') + try: + array_pipe.ps.op_image_store(['v[4:5]', 'v[0:2]', 's[16:23]'], ['dmask:0xf', 'dim:SQ_RSRC_IMG_2D_ARRAY', 'd16']) + except G.Unsupported as error: + assert 'modifier d16' in str(error), error + else: + raise AssertionError('pixel 2D-array d16 store was accepted') + print('refused 2D-array with two address registers and pixel d16') # 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')): @@ -177,6 +225,12 @@ def controls(): 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() + for constant, words in ((1, ARRAY_EXEC_ON), (2, ARRAY_EXEC_OFF)): + ps = translate(words).hlsl_ps() + assert ' exec = ((0x%08xu == v0) ? 1u : 0u);' % constant in ps, ps + assert ' ' + ARRAY_GUARDED_LINE in ps, ps + assert ps.count(ARRAY_STORE_LINE) == 1, ps + assert ARRAY_GUARDED_LINE not in array_ps print('exec after v_cmpx: %s' % GUARDED_LINE) # Negative control: without the lowering the program is refused as before. @@ -190,9 +244,10 @@ def controls(): def check_binary(llvm_mc): - built = assemble(llvm_mc, SOURCE) - if built != WORDS: - raise AssertionError('assembled %s, recorded %s' % (built.hex(), WORDS.hex())) + for label, src, expected in (('2d', SOURCE, WORDS), ('2d_array', ARRAY_SOURCE, ARRAY_WORDS)): + built = assemble(llvm_mc, src) + if built != expected: + raise AssertionError('%s: assembled %s, recorded %s' % (label, built.hex(), expected.hex())) print('fixture words match llvm-mc') diff --git a/tests/startup_pixel_uav.cpp b/tests/startup_pixel_uav.cpp index 36a6546293..92b887f801 100644 --- a/tests/startup_pixel_uav.cpp +++ b/tests/startup_pixel_uav.cpp @@ -31,15 +31,19 @@ namespace { using Microsoft::WRL::ComPtr; template Word ptr(T* value) { return reinterpret_cast(value); } -constexpr UINT side = 4, mips = 2, textures = 4; +constexpr UINT side = 4, mips = 2, textures = 4, array_slices = 6; // The sentinel of word c of texel (x, y) of mip m of texture t; tests/startup_pixel_uav_check.py makes the same. std::uint32_t sentinel(UINT t, UINT m, UINT texel, UINT c) { return 0xc0000000u | (t << 12) | (m << 8) | (texel << 2) | c; } +std::uint32_t array_sentinel(UINT s, UINT m, UINT texel, UINT c) { return 0xd0000000u | (s << 12) | (m << 8) | (texel << 2) | c; } struct Fixture { ID3D12Device* desktop = nullptr; + bool array_mode = false; void* resources[textures]{}; ComPtr natives[textures]; + void* array_resources[3]{}; + ComPtr array_natives[3]; } fixture; ComPtr native_of(void* guest, void* wrapped) @@ -63,6 +67,13 @@ D3D12_RESOURCE_DESC texture_desc(UINT t) D3D12_TEXTURE_LAYOUT_UNKNOWN, t == 2 ? D3D12_RESOURCE_FLAG_NONE : D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; } +D3D12_RESOURCE_DESC array_texture_desc(UINT t) +{ + return {D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, side, side, array_slices, mips, + t == 2 ? DXGI_FORMAT_R32G32B32A32_TYPELESS : DXGI_FORMAT_R32G32B32A32_FLOAT, {1, 0}, + D3D12_TEXTURE_LAYOUT_UNKNOWN, t == 1 ? D3D12_RESOURCE_FLAG_NONE : D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; +} + struct Copier { ComPtr queue; ComPtr allocator; @@ -167,6 +178,64 @@ bool copy_all(ID3D12Device* device, bool to_textures, std::vector return true; } +// Fills every subresource of the 6-slice array texture with its sentinels (to_texture) or copies them all back. +bool copy_array(ID3D12Device* device, bool to_texture, std::vector* words) +{ + constexpr UINT subresources = array_slices * mips; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprints[subresources]{}; + UINT64 total = 0; + const auto desc = array_texture_desc(0); + device->GetCopyableFootprints(&desc, 0, subresources, 0, footprints, nullptr, nullptr, &total); + if (!total || total == ~UINT64{0}) return false; + auto staging = buffer(device, to_texture ? D3D12_HEAP_TYPE_UPLOAD : D3D12_HEAP_TYPE_READBACK, total, + to_texture ? D3D12_RESOURCE_STATE_GENERIC_READ : D3D12_RESOURCE_STATE_COPY_DEST); + Copier copier; + if (!staging || !copier.open(device)) return false; + unsigned char* memory = nullptr; + if (to_texture) { + if (FAILED(staging->Map(0, nullptr, reinterpret_cast(&memory)))) return false; + for (UINT s = 0; s < array_slices; ++s) + for (UINT m = 0; m < mips; ++m) { + const UINT sub = s * mips + m, n = side >> m; + for (UINT y = 0; y < n; ++y) + for (UINT x = 0; x < n; ++x) + for (UINT c = 0; c < 4; ++c) { + const std::uint32_t value = array_sentinel(s, m, y * n + x, c); + std::memcpy(memory + footprints[sub].Offset + y * footprints[sub].Footprint.RowPitch + (x * 4 + c) * 4, + &value, 4); + } + } + staging->Unmap(0, nullptr); + } + auto* texture = fixture.array_natives[0].Get(); + const auto state = to_texture ? D3D12_RESOURCE_STATE_COPY_DEST : D3D12_RESOURCE_STATE_COPY_SOURCE; + barrier(copier.list.Get(), texture, D3D12_RESOURCE_STATE_COMMON, state); + for (UINT sub = 0; sub < subresources; ++sub) { + D3D12_TEXTURE_COPY_LOCATION placed{staging.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + placed.PlacedFootprint = footprints[sub]; + D3D12_TEXTURE_COPY_LOCATION subresource{texture, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + subresource.SubresourceIndex = sub; + if (to_texture) copier.list->CopyTextureRegion(&subresource, 0, 0, 0, &placed, nullptr); + else copier.list->CopyTextureRegion(&placed, 0, 0, 0, &subresource, nullptr); + } + barrier(copier.list.Get(), texture, state, D3D12_RESOURCE_STATE_COMMON); + if (!copier.run()) return false; + if (to_texture) return true; + if (FAILED(staging->Map(0, nullptr, reinterpret_cast(&memory)))) return false; + for (UINT s = 0; s < array_slices; ++s) + for (UINT m = 0; m < mips; ++m) { + const UINT sub = s * mips + m, n = side >> m; + for (UINT y = 0; y < n; ++y) + for (UINT x = 0; x < n * 4; ++x) { + std::uint32_t value = 0; + std::memcpy(&value, memory + footprints[sub].Offset + y * footprints[sub].Footprint.RowPitch + x * 4, 4); + words->push_back(value); + } + } + staging->Unmap(0, nullptr); + return true; +} + ID3D12InfoQueue* debug_messages() { static ComPtr queue; @@ -181,6 +250,71 @@ int draw_pixel_uavs(ID3D12Device* desktop, void* guest, void* list) GetEnvironmentVariableA("X2W_TEST_PIXEL_UAV", mode, sizeof(mode)); const std::string which(mode); fixture.desktop = desktop; + fixture.array_mode = which.rfind("arr-", 0) == 0; + if (fixture.array_mode) { + using Create = HRESULT (WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, UINT, const void*, + void*, UINT, const void*, REFIID, void**); + const auto create = reinterpret_cast((*static_cast(guest))[127]); + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT}; + for (UINT t = 0; t < 3; ++t) { + const auto desc = array_texture_desc(t); + if (FAILED(create(guest, &heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0, nullptr, + __uuidof(ID3D12Resource), &fixture.array_resources[t])) || !fixture.array_resources[t]) + return 70; + fixture.array_natives[t] = native_of(guest, fixture.array_resources[t]); + if (!fixture.array_natives[t]) return 71; + } + const auto plain_desc = texture_desc(0); + if (FAILED(create(guest, &heap, 0, &plain_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, nullptr, 0, nullptr, + __uuidof(ID3D12Resource), &fixture.resources[0])) || !fixture.resources[0]) + return 70; + if (!copy_array(desktop, true, nullptr)) return 72; + + struct Extended { + D3D12_DESCRIPTOR_HEAP_DESC desc; + Word address, bytes; + } heap_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE}, 0, 0}; + void* desc_heap = nullptr; + if (FAILED(static_cast(invoke(guest, 14, ptr(&heap_desc), ptr(&__uuidof(ID3D12DescriptorHeap)), ptr(&desc_heap))))) + return 73; + const Word cpu = invoke(desc_heap, 9), gpu = invoke(desc_heap, 10); + const UINT stride = static_cast(invoke(guest, 15, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)); + if (!cpu || !gpu || stride < 32) return 73; + + D3D12_UNORDERED_ACCESS_VIEW_DESC arr_view{DXGI_FORMAT_R32G32B32A32_FLOAT, D3D12_UAV_DIMENSION_TEXTURE2DARRAY}; + arr_view.Texture2DArray = {0, 1, 4, 0}; // FirstArraySlice=1, ArraySize=4 -> physical slices 1..4 + invoke(guest, 19, ptr(fixture.array_resources[0]), 0, ptr(&arr_view), cpu + 0 * stride); + D3D12_UNORDERED_ACCESS_VIEW_DESC plain_view{DXGI_FORMAT_R32G32B32A32_FLOAT, D3D12_UAV_DIMENSION_TEXTURE2D}; + invoke(guest, 19, ptr(fixture.resources[0]), 0, ptr(&plain_view), cpu + 1 * stride); + invoke(guest, 19, ptr(fixture.array_resources[0]), 0, 0, cpu + 2 * stride); + D3D12_UNORDERED_ACCESS_VIEW_DESC mip1 = arr_view; + mip1.Texture2DArray.MipSlice = 1; + invoke(guest, 19, ptr(fixture.array_resources[0]), 0, ptr(&mip1), cpu + 3 * stride); + D3D12_SHADER_RESOURCE_VIEW_DESC arr_srv{DXGI_FORMAT_R32G32B32A32_FLOAT, D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING}; + arr_srv.Texture2DArray = {0, 1, 1, 4, 0, 0.0f}; + invoke(guest, 18, ptr(fixture.array_resources[0]), ptr(&arr_srv), cpu + 4 * stride); + invoke(guest, 19, ptr(fixture.array_resources[1]), 0, ptr(&arr_view), cpu + 5 * stride); + D3D12_UNORDERED_ACCESS_VIEW_DESC integer = arr_view; + integer.Format = DXGI_FORMAT_R32G32B32A32_UINT; + invoke(guest, 19, ptr(fixture.array_resources[2]), 0, ptr(&integer), cpu + 6 * stride); + + struct Case { const char* name; int entry; int srv_entry; }; + static const Case cases[] = { + {"arr-ok", 0, -1}, {"arr-2d-view", 1, -1}, {"arr-default", 2, -1}, {"arr-mip1", 3, -1}, + {"arr-srv-and-uav", 0, 4}, {"arr-no-ua", 5, -1}, {"arr-uint", 6, -1}, + }; + const Case* chosen = nullptr; + for (const Case& c : cases) + if (which == c.name) chosen = &c; + if (!chosen) return 74; + std::printf("pixel uav case %s: table entry %d, title descriptor stride %u\n", chosen->name, chosen->entry, stride); + invoke(list, 32, 1, ptr(&desc_heap)); + if (chosen->entry >= 0) invoke(list, 36, 0, gpu + Word(chosen->entry) * stride); + if (chosen->srv_entry >= 0) invoke(list, 36, 1, gpu + Word(chosen->srv_entry) * stride); + invoke(list, 12, 3, 1); + return 0; + } for (UINT t = 0; t < textures; ++t) { using Create = HRESULT (WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, UINT, const D3D12_RESOURCE_DESC*, UINT, const void*, void*, UINT, const void*, REFIID, void**); @@ -272,7 +406,7 @@ int draw_pixel_uavs(ID3D12Device* desktop, void* guest, void* list) int report_pixel_uavs(const char* pixels) { std::vector words; - const bool copied = copy_all(fixture.desktop, false, &words); + const bool copied = fixture.array_mode ? copy_array(fixture.desktop, false, &words) : copy_all(fixture.desktop, false, &words); if (copied) { std::ofstream out(std::string(pixels) + ".uav", std::ios::binary); out.write(reinterpret_cast(words.data()), static_cast(words.size() * 4)); diff --git a/tests/startup_pixel_uav_check.py b/tests/startup_pixel_uav_check.py index df0d13f92e..8fd0594b59 100644 --- a/tests/startup_pixel_uav_check.py +++ b/tests/startup_pixel_uav_check.py @@ -32,9 +32,12 @@ sys.path.insert(0, str(HERE)) from startup_stream_check import container, gfx2hlsl # noqa: E402 from startup_stream_draw_check import vertex # noqa: E402 -from startup_pixel_image_store_check import BITS, EXEC_OFF, EXEC_ON, GUARDED_LINE, STORE_LINE, WORDS # noqa: E402 +from startup_pixel_image_store_check import ( # noqa: E402 + ARRAY_EXEC_OFF, ARRAY_EXEC_ON, ARRAY_GUARDED_LINE, ARRAY_STORE_LINE, ARRAY_WORDS, ARRAY_WORDS_LAST, + BITS, EXEC_OFF, EXEC_ON, GUARDED_LINE, STORE_LINE, WORDS, +) -SIDE, MIPS, TEXTURES = 4, 2, 4 +SIDE, MIPS, TEXTURES, ARRAY_SLICES = 4, 2, 4, 6 WRITTEN = [int(b, 16) for b in BITS] CLEAR, WHITE = bytes((0, 0, 255, 255)), bytes((255, 255, 255, 255)) DRAWN_LINE = 'x2w-draw draw(3, 1, start 0, base 0) pipeline' @@ -63,7 +66,7 @@ ('a.float-line', 'uav 0 tex2d float table 0 0', None, 'uav line refused (a view qualifier is not read for pixel stores)'), ('a.compute-line', 'uav 0 tex2d float table 0 0 channels 4', None, 'uav line refused (a view qualifier is not read for pixel stores)'), - ('a.tex2da-line', 'uav 0 tex2da table 0 0', None, 'uav line refused (only tex2d views are bound)'), + ('a.tex3d-line', 'uav 0 tex3d table 0 0', None, 'uav line refused (only tex2d and tex2da views are bound)'), ('a.buffer-line', 'uav 0 raw table 0 0', None, 'uav line refused (buffer view (raw uav) is not bound)'), ('a.uint-line', 'uav 0 tex2d uint table 0 0', None, 'uav line refused (a view qualifier is not read for pixel stores)'), ('a.channels-field', 'uav 0 tex2d table 0 0 channels 4', None, @@ -72,10 +75,48 @@ ) +ARRAY_CASES = ( + ('arr-2d-view', 'uav 0 refused: view is not a 2D array texture view', None), + ('arr-default', 'uav 0 refused: view is not a 2D array texture view', None), + ('arr-mip1', 'uav 0 refused: view names a mip other than 0', None), + ('arr-srv-and-uav', 'uav 0 refused: the texture is also an SRV of this draw', + ('uav 0 tex2da table 0 0', 'uav 0 tex2da table 0 0\nsrv 0 tex2da table 1 0')), + ('arr-no-ua', 'uav 0 refused: resource lacks ALLOW_UNORDERED_ACCESS', None), + ('arr-uint', 'uav 0 refused: integer format for a float view', None), +) + + def sentinel(t, m, texel, c): return 0xc0000000 | t << 12 | m << 8 | texel << 2 | c +def array_sentinel(s, m, texel, c): + return 0xd0000000 | s << 12 | m << 8 | texel << 2 | c + + +def expected_array_words(written_slice): + words = [] + for s in range(ARRAY_SLICES): + for m in range(MIPS): + n = SIDE >> m + for texel in range(n * n): + for c in range(4): + hit = s == written_slice and m == 0 and texel == 2 * n + 1 + words.append(WRITTEN[c] if hit else array_sentinel(s, m, texel, c)) + return words + + +def describe_array(index): + for s in range(ARRAY_SLICES): + for m in range(MIPS): + n = SIDE >> m + if index < n * n * 4: + texel, c = divmod(index, 4) + return 'slice %d mip %d texel (%d, %d) word %d' % (s, m, texel % n, texel // n, c) + index -= n * n * 4 + return 'word past the end' + + def expected_words(written): words = [] for t in range(TEXTURES): @@ -103,21 +144,21 @@ def describe(index): class Program: """One pixel program published and translated into its own cache.""" - def __init__(self, directory, consumer, words, env): - self.directory, self.consumer = directory, consumer + def __init__(self, directory, consumer, words, env, kind='tex2d'): + self.directory, self.consumer, self.kind = directory, consumer, kind directory.mkdir() self.cache = directory / 'cache' self.cache.mkdir() self.vs, self.ps, self.root = (directory / name for name in ('vs', 'ps', 'root')) self.vs.write_bytes(vertex()) self.ps.write_bytes(container(0, list(struct.unpack('<%dI' % (len(words) // 4), words)))) - publish = dict(env, X2W_SHADER_CACHE=str(self.cache), X2W_TEST_PIXEL_UAV='a') + publish = dict(env, X2W_SHADER_CACHE=str(self.cache), X2W_TEST_PIXEL_UAV='arr-ok' if kind == 'tex2da' else 'a') publish.pop('X2W_TEST_DEBUG_LAYER', None) subprocess.run([consumer, self.vs, self.ps, self.root], env=publish, check=True) subprocess.run([sys.executable, '-B', gfx2hlsl.__file__, '--pending', self.cache], env=publish, check=True) self.manifest, = self.cache.glob('*.txt') lines = self.manifest.read_text(encoding='ascii').splitlines() - assert lines[0] == 'x2w-manifest 2' and 'uav 0 tex2d table 0 0' in lines and not any( + assert lines[0] == 'x2w-manifest 2' and ('uav 0 %s table 0 0' % kind) in lines and not any( line.startswith('srv ') for line in lines), lines @@ -143,7 +184,7 @@ def run_case(program, name, env, backend, cache=None): return run.returncode, run.stdout + run.stderr, log, pixels, words -def verdict(name, result, written, reason, drawn): +def verdict(name, result, written, reason, drawn, array=False): """None when the case holds, otherwise the first difference.""" returncode, out, log, pixels, words = result if returncode: @@ -152,17 +193,18 @@ def verdict(name, result, written, reason, drawn): return 'device removed or no report\n%s' % out[-3000:] if 'debug layer: on' in out and 'debug layer: on, errors: 0' not in out: return 'debug layer errors\n%s' % out[-3000:] - want = expected_words(written) + want = expected_array_words(written) if array else expected_words(written) if len(words) != len(want): return '%d texture words read back, expected %d' % (len(words), len(want)) for i, (got, expected) in enumerate(zip(words, want)): if got != expected: - return 'texel_mismatch %s: got %08x, expected %08x' % (describe(i), got, expected) + return 'texel_mismatch %s: got %08x, expected %08x' % ( + describe_array(i) if array else describe(i), got, expected) if (DRAWN_LINE in log) != drawn: return 'translated draw %s' % ('missing' if drawn else 'present although refused') if reason and reason not in log: return 'reason "%s" not logged\n%s' % (reason, log[-3000:]) - if drawn is not None and name in ('a', 'b'): + if drawn is not None and name in ('a', 'b', 'arr-ok'): rows = [pixels[i:i + 32] for i in range(0, len(pixels), 32)] want_row = WHITE * 4 + CLEAR * 4 if len(rows) != 4 or any(row != want_row for row in rows): @@ -172,14 +214,14 @@ def verdict(name, result, written, reason, drawn): return None -def recompile_without_guard(program, folder): - """A copy of the exec-off cache whose pixel shader stores without the exec guard.""" - cache = folder / 'cache_unguarded' +def recompile_mutated(program, folder, tag, old, new): + """A copy of the cache whose pixel shader has old replaced with new.""" + cache = folder / tag shutil.copytree(program.cache, cache) hlsl, = cache.glob('*.ps.hlsl') text = hlsl.read_text() - assert (' ' + GUARDED_LINE) in text, text - hlsl.write_text(text.replace(GUARDED_LINE, STORE_LINE)) + assert old in text, (old, text) + hlsl.write_text(text.replace(old, new)) fxc = gfx2hlsl.find_fxc() if not fxc: return None @@ -189,6 +231,10 @@ def recompile_without_guard(program, folder): return cache +def recompile_without_guard(program, folder): + return recompile_mutated(program, folder, 'cache_unguarded', GUARDED_LINE, STORE_LINE) + + def check(directory, consumer, backend): env = dict(os.environ, X2W_D3D12_PERMISSIVE='1', X2W_D3D12_LIST_NOOP='1', X2W_D3D12_RENDER='1', X2W_D3D12_DEBUG='0', X2W_D3D12_DEVICE_NOOP='1', X2W_TEST_DEBUG_LAYER='1') @@ -197,12 +243,12 @@ def check(directory, consumer, backend): store = Program(directory / 'store', consumer, WORDS, env) failures = [] - def expect(program, name, written, reason, drawn, cache=None): + def expect(program, name, written, reason, drawn, cache=None, array=False): result = run_case(program, name, env, backend, cache) if result[0] == 77: print(result[1]) sys.exit(77) - problem = verdict(name, result, written, reason, drawn) + problem = verdict(name, result, written, reason, drawn, array=array) adapter = next((line for line in result[1].splitlines() if line.startswith('adapter=')), '') layer = next((line for line in result[1].splitlines() if line.startswith('debug layer:')), 'debug layer: ?') stride = next((line.rsplit(' ', 1)[1] for line in result[1].splitlines() if 'title descriptor stride' in line), '?') @@ -214,9 +260,13 @@ def expect(program, name, written, reason, drawn, cache=None): if line.startswith(('debug layer', 'device removed')): print(' ' + line) else: - what = ('texel (1, 2) of texture %s written, every other word unchanged' % 'ABCD'[written] if written is not None - else 'every word unchanged') - print('%-13s %s; %s%s [%s; %s]' % (name + ':', 'drawn' if drawn else 'refused', what, + if array: + what = ('texel (1, 2) of slice %d written, all other words of 6 slices unchanged' % written + if written is not None else 'all 6 slices unchanged') + else: + what = ('texel (1, 2) of texture %s written, every other word unchanged' % 'ABCD'[written] + if written is not None else 'every word unchanged') + print('%-16s %s; %s%s [%s; %s]' % (name + ':', 'drawn' if drawn else 'refused', what, (' (' + reason + ')') if reason else '', adapter, layer)) return problem @@ -257,9 +307,57 @@ def expect(program, name, written, reason, drawn, cache=None): failures.append('control exec guard removed was not detected: %s' % problem) else: print('control exec guard removed: fails as expected (%s)' % problem) + # 2D-array pixel UAV path (#2742): FirstArraySlice=1, ArraySize=4 -> relative layers 1 and 3 hit physical slices 2 and 4. + arr_mid = Program(directory / 'arr_mid', consumer, ARRAY_WORDS, env, kind='tex2da') + arr_last = Program(directory / 'arr_last', consumer, ARRAY_WORDS_LAST, env, kind='tex2da') + expect(arr_mid, 'arr-ok', 2, None, True, array=True) + expect(arr_last, 'arr-ok.last', 4, None, True, array=True) + wrong_layer = recompile_mutated(arr_mid, directory, 'cache_wrong_layer', + 'uint3(v0, v1, v2)', 'uint3(v0, v1, v2 + 1u)') + if wrong_layer is None: + print('control array wrong layer: no fxc, not run') + else: + result = run_case(arr_mid, 'arr-ok.wrong-layer', env, backend, wrong_layer) + problem = verdict('arr-ok', result, 2, None, True, array=True) + needle = 'texel_mismatch slice 2 mip 0 texel (1, 2) word 0: got %08x, expected %08x' % ( + array_sentinel(2, 0, 9, 0), WRITTEN[0]) + if not problem or not problem.startswith(needle): + failures.append('control array wrong layer was not detected: %s' % problem) + else: + print('control array wrong layer: fails as expected (%s)' % problem) + for name, reason, edit in ARRAY_CASES: + text = arr_mid.manifest.read_text(encoding='ascii') + if edit: + assert edit[0] in text + arr_mid.manifest.write_text(text.replace(edit[0], edit[1]), encoding='ascii') + try: + expect(arr_mid, name, None, reason, False, array=True) + finally: + if edit: + arr_mid.manifest.write_text(text, encoding='ascii') + arr_exec_on = Program(directory / 'arr_exec_on', consumer, ARRAY_EXEC_ON, env, kind='tex2da') + arr_exec_off = Program(directory / 'arr_exec_off', consumer, ARRAY_EXEC_OFF, env, kind='tex2da') + for program in (arr_exec_on, arr_exec_off): + assert (' ' + ARRAY_GUARDED_LINE) in next(program.cache.glob('*.ps.hlsl')).read_text() + expect(arr_exec_on, 'arr-ok.exec-on', 2, None, True, array=True) + expect(arr_exec_off, 'arr-ok.exec-off', None, None, True, array=True) + arr_unguarded = recompile_mutated(arr_exec_off, directory, 'cache_arr_unguarded', + ARRAY_GUARDED_LINE, ARRAY_STORE_LINE) + if arr_unguarded is None: + print('control array exec guard removed: no fxc, not run') + else: + result = run_case(arr_exec_off, 'arr-ok.exec-off-unguarded', env, backend, arr_unguarded) + problem = verdict('arr-ok', result, None, None, True, array=True) + needle = 'texel_mismatch slice 2 mip 0 texel (1, 2) word 0: got %08x, expected %08x' % ( + WRITTEN[0], array_sentinel(2, 0, 9, 0)) + if not problem or not problem.startswith(needle): + failures.append('control array exec guard removed was not detected: %s' % problem) + else: + print('control array exec guard removed: fails as expected (%s)' % problem) + if failures: raise SystemExit('\n'.join(failures)) - print('%s: %d cases and the exec guard control' % (backend, len(CASES) + len(LINES) + 2)) + print('%s: %d cases and the exec/layer controls' % (backend, len(CASES) + len(LINES) + len(ARRAY_CASES) + 6)) return 0 diff --git a/tools/startup/gfx2hlsl.py b/tools/startup/gfx2hlsl.py index dd6747010b..00fcb75d19 100644 --- a/tools/startup/gfx2hlsl.py +++ b/tools/startup/gfx2hlsl.py @@ -7443,7 +7443,7 @@ def op_image_store(self, ops, mods): if len(dims) != 1 or len(masks) != 1: raise Unsupported('%s without exactly one dim and dmask' % name) array = dims[0] == 'SQ_RSRC_IMG_2D_ARRAY' - if dims[0] != 'SQ_RSRC_IMG_2D' and (not array or self.kind != 'cs'): + if dims[0] not in ('SQ_RSRC_IMG_2D', 'SQ_RSRC_IMG_2D_ARRAY'): raise Unsupported('%s on %s: only 2D images are lowered' % (name, dims[0])) try: mask = int(masks[0], 0)