Skip to content

feat(runtime): optimize resource detile loops with bit-shifts and typed moves - #9429

Closed
Cryptoteep wants to merge 1 commit into
ProjectLeonida:mainfrom
Cryptoteep:feat/runtime-fast-detiling-shifts
Closed

Cryptoteep wants to merge 1 commit into
ProjectLeonida:mainfrom
Cryptoteep:feat/runtime-fast-detiling-shifts

Conversation

@Cryptoteep

Copy link
Copy Markdown
Contributor

Summary

  • Replaces per-texel integer divisions and modulos (x / tile_w, x % tile_w, y / tile_h, y % tile_h) in detile_typed and tile_typed (runtime/src/resource_detile.h) with compile-time power-of-two bit shifts (>> shift_w, >> shift_h) and bitwise masks (& mask_w, & mask_h).
  • TileShape dimensions for 64 KiB GFX10 swizzle tiles (SW_64KB_D) are always compile-time powers of two (64, 128, 256 for 16, 8, 4, 2, 1 BPE).
  • Replaces generic std::memcpy(&dst, &src, Bpe) per pixel with typed Element<Bpe> unaligned struct copy, and increments linear_off += Bpe linearly instead of calculating row index on every inner iteration.

Performance & Hardware Motivation

  • On fixed-frequency CPUs without Turbo Boost (e.g. Intel CC150 @ locked 3.50 GHz), 64-bit integer idiv instructions incur ~15-20 cycles of execution latency.
  • Detiling or surface readback on a single 4096×4096 texture previously required over 33 million integer division/modulo instructions. Switching to bit shifts and typed unaligned moves eliminates this pipeline stall completely, significantly accelerating texture detiling and readback throughput.

Verification

  • Claimed in Coordinating who works on what (54) (moved to #9065) #8868 (comment)
  • Verified bit-exact with runtime/test/resource_detile_test.cpp under MSVC (cl /EHsc /std:c++20 /O2): "resource detile: all 64 KiB GFX10 swizzle round-trip and validation checks passed".
  • Verified clean with python -I scripts/check_no_game_data.py runtime/src/resource_detile.h (0 game data).
  • Portable standard C++20 (<bit>, std::countr_zero), no GPU or game data required.

…ed moves

Replaces per-texel integer divisions and modulos (x / tile_w, x % tile_w,
y / tile_h, y % tile_h) in detile_typed and tile_typed with power-of-two
bit shifts (>> shift_w, >> shift_h) and bitwise masks (& mask_w, & mask_h).
Tile dimensions (tile_w, tile_h) are compile-time powers of two (64, 128, 256)
for 64 KiB GFX10 swizzle tiles.

Replaces std::memcpy per texel with typed unaligned Element<Bpe> assignments,
and advances linear row offsets incrementally. Eliminates millions of 64-bit
integer division instructions and function call overhead during texture detiling
and surface readback on x86-64 CPUs.

Verified with runtime/test/resource_detile_test.cpp (all round-trip and validation
checks pass bit-exact, 0 game data).
@shdann

shdann commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Please correct the claim of more than 33 million integer division instructions for a 4096 x 4096 surface. I checked the optimized x64 code with MSVC 19.51.36260. Both the parent (6312c05) and the PR (07d62a6) emit zero div or idiv instructions across all ten tile and detile specializations (1, 2, 4, 8 and 16 bytes per element). For example, the parent already uses shr by 7 and masks with 127 for 4-byte elements. At 16 bytes, the parent already emits unaligned XMM moves for the fixed-size copy.

To reproduce one specialization, put this in probe.cpp:

#include "resource_detile.h"
template void leonida::detail::detile_typed<4>(
    std::span<const std::byte>, std::span<std::byte>,
    std::uint32_t, std::uint32_t, std::uint32_t);

At each revision, run this from an x64 MSVC shell:

cl /nologo /O2 /EHsc /std:c++20 /I runtime\src /c /FA /Faprobe.asm probe.cpp

Inspect detile_typed<4> in probe.asm. The divisors are compile-time constants on the parent. The existing resource_detile_test passes at both revisions. A before/after timing would establish whether the offset or copy changes improve throughput.

AI-assisted.

@LukeOsland1

Copy link
Copy Markdown
Contributor

Independent MSVC /O2 measurement of 07d62a6 against 6312c05. Ryzen 7 9800X3D, Windows 11 build 26300, MSVC 19.51.36248 (/O2 /EHsc /std:c++20 /DNDEBUG). Same synthetic four-byte elements on both revisions. Seven interleaved processes per revision and surface, seven samples per process. The table gives the median of the process medians.

Surface Parent tile PR tile Parent detile PR detile
4096×64 154.6 µs 211.6 µs 177.4 µs 226.0 µs
1920×1080 1.550 ms 1.798 ms 1.651 ms 1.904 ms
4096×2160 7.666 ms 8.169 ms 13.602 ms 14.181 ms

All round trips passed and parent and head tiled outputs compared byte-for-byte equal at all three sizes. The strongest timing difference was 4096×64 tiling: process medians ranged from 152–197 µs on parent and 202–225 µs on head. At 4096×2160 the ranges overlap for both directions.

On this compiler the optimized parent four-byte inner loops already used shifts and masks, and the fixed-size memcpy compiled down to a dword move. I found no divide instruction there. This CPU/compiler combination therefore does not reproduce the proposed speedup. Other element sizes and toolchains were outside this measurement. No game files. AI-assisted with Codex.

Claim: #9401 (comment)

@Zipettte

Copy link
Copy Markdown

Tested on AMD Radeon RX 7700 XT (RDNA3), AMD Windows driver 32.0.32029.2010, Windows 11, MSVC 14.51 Release, at 07d62a6. Full ctest -j 8, out of 239 tests:

No regression. The only failures are the same 5 as on main dde82f2 on this card (vk_queue_query_sync, d3d12_vulkan_device tiles == 1, d3d12_texture_tiles, d3d12_depth_resolve, d3d12_pipeline_library_host; tracked in #8426). Every test this PR adds or touches passes.

AI-assisted (Claude Code).

@ddaikodaiko

Copy link
Copy Markdown

Windows check of 07d62a6: Windows 10 Pro 10.0.19045, MSVC 19.44.35229, Windows SDK 10.0.26100, CMake 3.31 + Ninja. No game files.

cmake --build runtime\build --target resource_detile_test -j 10
ctest --test-dir runtime\build -R "^resource_detile$" --output-on-failure
  -> 1/1 Test #37: resource_detile ... Passed 0.19 sec

The bit-shift/typed-move rewrite is bit-identical to the reference on MSVC as well; only correctness was checked, not speed.

@sgonzalez-glitch

Copy link
Copy Markdown

Tested 07d62a68e (as part of #9429, #9505, #9516, #9547, #9549 and #9558 merged together onto main 5d74c2723) on NVIDIA GeForce RTX 2080, driver 621.24 (32.0.16.2124), Windows 11, MSVC 19.44 RelWithDebInfo: pass.

AI-assisted: yes

@Nevrche

Nevrche commented Nov 23, 2026

Copy link
Copy Markdown

Tested 07d62a68e on Windows 10 Pro 22H2 (19045), MSVC 19.44.35230, VS 2022 generator, RelWithDebInfo, NVIDIA GTX 1050 Ti (32.0.15.8266): pass.

Test Result
resource_detile Passed 0.20 s
d3d12_buffer_tiles Passed 1.28 s
d3d12_texture_tiles Passed 1.41 s

3/3 passed in 2.94 s, no warnings from the changed header. These compare the detiled output against the expected patterns, so the bit-shift and typed-move rewrite produces the same bytes as before on this build.

AI-assisted.

@OGShotz

OGShotz commented Nov 23, 2026

Copy link
Copy Markdown

Tested 07d62a6 on Windows 11 x64 with MSVC 19.44 (toolset 14.44.35207) at /O2, on an AMD Ryzen 7 3700X, CPU only (AI-assisted).

  • resource_detile_test.cpp builds and passes.
  • I ran a separate benchmark harness (detile_surface_64k and tile_surface_64k, median of 7 runs, the same pseudo-random input; the output checksum matches main). This branch is about 5–15% faster than main on most surfaces. That's within run-to-run noise for the small ones, and the 512x512 R8 tile was slower (0.307 → 0.608 ms):
Surface detile main → PR tile main → PR
4096x4096 R8 44.3 → 41.5 ms 36.3 → 32.8 ms
4096x4096 RGBA8 91.8 → 81.6 ms 52.3 → 48.9 ms
4096x4096 BC7 11.9 → 9.9 ms 7.1 → 6.2 ms

Three things to look at:

  1. The division change likely does nothing. tile_w and tile_h are already constexpr unsigned powers of two, so the compiler already turns x / tile_w and x % tile_w into a shift and a mask. The description's argument about 33 million idiv instructions doesn't apply to this code.
  2. reinterpret_cast<Element<Bpe>*> on the std::byte spans reads and writes through a type for which no object exists at that address. Under the strict-aliasing rules that's undefined behaviour, which the fixed-size std::memcpy it replaces avoided. Compilers already lower that memcpy to a single load and store for these sizes.
  3. It overlaps resource_detile: strip-mined cache-line micro-tile copies, 1.2x-14.6x faster, bit-identical (PERF-RESOURCE-DETILE) #9399, which replaces both detile_typed and tile_typed entirely. On the same harness, resource_detile: strip-mined cache-line micro-tile copies, 1.2x-14.6x faster, bit-identical (PERF-RESOURCE-DETILE) #9399 measured 3–15x faster: 4096x4096 RGBA8 detile in 26.1 ms against 81.6 ms here, and 512x512 R8 in 0.012 ms. Whichever lands second has to rebase onto the other.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants