upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/test
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/test')
-rw-r--r--runtime/test/descriptor_table_test.cpp234
-rw-r--r--runtime/test/root_signature_oracle_test.cpp120
-rw-r--r--runtime/test/root_signature_test.cpp221
-rw-r--r--runtime/test/shaders/build.py24
-rw-r--r--runtime/test/shaders/check.py6
-rw-r--r--runtime/test/shaders/cs_smem_soffset_imm.asm61
-rw-r--r--runtime/test/vk_texture_test.cpp27
-rw-r--r--runtime/test/vulkan_loader.h11
8 files changed, 671 insertions, 33 deletions
diff --git a/runtime/test/descriptor_table_test.cpp b/runtime/test/descriptor_table_test.cpp
new file mode 100644
index 000000000..f9c2ba186
--- /dev/null
+++ b/runtime/test/descriptor_table_test.cpp
@@ -0,0 +1,234 @@
1// Unit tests for the descriptor hash table (set 0, binding 2 contract).
2// Tests FNV-1a hashing, T#/S# key generation, probe resolution, dynamic resizing,
3// GPU buffer serialization, and multithreaded insertion.
4#include "../src/descriptor_table.h"
5
6#include <cassert>
7#include <cstdio>
8#include <cstring>
9#include <random>
10#include <thread>
11#include <vector>
12
13#define EXPECT(condition) do { \
14 if (!(condition)) { \
15 std::fprintf(stderr, "assertion failed: %s at %s:%d\n", #condition, __FILE__, __LINE__); \
16 return 1; \
17 } \
18} while (0)
19
20using namespace leonida;
21
22int test_fnv1a_hash_matches_contract() {
23 // Verified against vk_texture_test.cpp key_hash and rdna2spirv.py desc_probe
24 const std::uint32_t zeros[8] = {0, 0, 0, 0, 0, 0, 0, 0};
25 std::uint32_t expected_zero_hash = 2166136261u;
26 for (int i = 0; i < 8; ++i) expected_zero_hash = (expected_zero_hash ^ 0) * 16777619u;
27 EXPECT(hash_descriptor_key(zeros) == expected_zero_hash);
28
29 const std::uint32_t sample_key[8] = {
30 0x12345678, 0x9abcdef0, 0x11223344, 0x55667788,
31 0x99aabbcc, 0xddeeff00, 0x01020304, 0x05060708
32 };
33 std::uint32_t expected_hash = 2166136261u;
34 for (int i = 0; i < 8; ++i) expected_hash = (expected_hash ^ sample_key[i]) * 16777619u;
35 EXPECT(hash_descriptor_key(sample_key) == expected_hash);
36 return 0;
37}
38
39int test_ssharp_key_padding() {
40 const std::uint32_t ssharp[4] = {0x92, 0xc00000, 0x14500000, 0x0};
41 const auto key = make_ssharp_key(ssharp);
42 EXPECT(key[0] == 0x92);
43 EXPECT(key[1] == 0xc00000);
44 EXPECT(key[2] == 0x14500000);
45 EXPECT(key[3] == 0x0);
46 EXPECT(key[4] == 0xFFFFFFFFu);
47 EXPECT(key[5] == 0xFFFFFFFFu);
48 EXPECT(key[6] == 0xFFFFFFFFu);
49 EXPECT(key[7] == 0xFFFFFFFFu);
50 return 0;
51}
52
53int test_basic_insertion_and_lookup() {
54 DescriptorTable table(16);
55 EXPECT(table.capacity() == 16);
56 EXPECT(table.mask() == 15);
57 EXPECT(table.size() == 0);
58
59 const std::uint32_t tsharp[8] = {
60 0x1000, 0x2000, 0x3000, 0x4000,
61 0x5000, 0x6000, 0x7000, 0x8000
62 };
63 EXPECT(table.lookup(tsharp) == 0);
64 EXPECT(!table.contains(tsharp));
65
66 EXPECT(table.insert(tsharp, 1));
67 EXPECT(table.size() == 1);
68 EXPECT(table.contains(tsharp));
69 EXPECT(table.lookup(tsharp) == 1);
70
71 // Duplicate key updates in place
72 EXPECT(table.insert(tsharp, 42));
73 EXPECT(table.size() == 1);
74 EXPECT(table.lookup(tsharp) == 42);
75
76 // S# key
77 const std::uint32_t ssharp[4] = {0xa, 0xb, 0xc, 0xd};
78 const auto skey = make_ssharp_key(ssharp);
79 EXPECT(table.insert(skey, 7));
80 EXPECT(table.size() == 2);
81 EXPECT(table.lookup(skey) == 7);
82 EXPECT(table.lookup(tsharp) == 42);
83 return 0;
84}
85
86int test_load_factor_and_growth() {
87 // Start with 16 slots. Load factor threshold 50% means max 8 entries before growth.
88 DescriptorTable table(16);
89 EXPECT(table.capacity() == 16);
90
91 std::vector<DescriptorKey> keys;
92 for (std::uint32_t i = 1; i <= 20; ++i) {
93 std::uint32_t k[8] = {i, i * 2, i * 3, i * 4, i * 5, i * 6, i * 7, i * 8};
94 keys.push_back(make_tsharp_key(k));
95 EXPECT(table.insert(keys.back(), i + 100));
96 }
97
98 EXPECT(table.size() == 20);
99 EXPECT(table.capacity() >= 64); // Doubled from 16 -> 32 -> 64
100 EXPECT(table.mask() == table.capacity() - 1);
101
102 // Verify all 20 keys resolve to their exact indices after growths
103 for (std::uint32_t i = 1; i <= 20; ++i) {
104 EXPECT(table.lookup(keys[i - 1]) == i + 100);
105 }
106 return 0;
107}
108
109int test_probe_collision_resolution() {
110 DescriptorTable table(64);
111
112 // Create 4 distinct keys that share the exact same hash
113 // We can forge keys that share hash or test linear collision handling
114 std::uint32_t k1[8] = {1, 0, 0, 0, 0, 0, 0, 0};
115 std::uint32_t k2[8] = {2, 0, 0, 0, 0, 0, 0, 0};
116 std::uint32_t k3[8] = {3, 0, 0, 0, 0, 0, 0, 0};
117
118 EXPECT(table.insert(k1, 10));
119 EXPECT(table.insert(k2, 20));
120 EXPECT(table.insert(k3, 30));
121
122 EXPECT(table.lookup(k1) == 10);
123 EXPECT(table.lookup(k2) == 20);
124 EXPECT(table.lookup(k3) == 30);
125 return 0;
126}
127
128int test_gpu_buffer_serialization() {
129 DescriptorTable table(16);
130 const std::uint32_t t1[8] = {10, 20, 30, 40, 50, 60, 70, 80};
131 const std::uint32_t s1[4] = {1, 2, 3, 4};
132 const auto skey = make_ssharp_key(s1);
133
134 EXPECT(table.insert(t1, 5));
135 EXPECT(table.insert(skey, 9));
136
137 const auto gpu_buf = table.build_gpu_buffer(false);
138 EXPECT(gpu_buf.size() == 1 + 16 * 10);
139 EXPECT(gpu_buf[0] == 15); // mask
140
141 // Verify lookup by traversing the generated buffer using the exact shader logic
142 const auto shader_lookup = [&](const std::uint32_t key[8]) -> std::uint32_t {
143 const std::uint32_t mask = gpu_buf[0];
144 const std::uint32_t h = hash_descriptor_key(key);
145 for (std::uint32_t k = 0; k < 8; ++k) {
146 const std::uint32_t slot = (h + k) & mask;
147 const std::size_t base = 1 + slot * 10;
148 bool match = true;
149 for (std::size_t j = 0; j < 8; ++j) {
150 if (gpu_buf[base + j] != key[j]) {
151 match = false;
152 break;
153 }
154 }
155 if (match) {
156 return gpu_buf[base + 8]; // index
157 }
158 }
159 return 0;
160 };
161
162 EXPECT(shader_lookup(t1) == 5);
163 EXPECT(shader_lookup(skey.data()) == 9);
164
165 const std::uint32_t missing[8] = {99, 99, 99, 99, 99, 99, 99, 99};
166 EXPECT(shader_lookup(missing) == 0);
167
168 // Test write_to_buffer
169 std::vector<std::uint32_t> raw_copy(gpu_buf.size());
170 table.write_to_buffer(raw_copy.data(), true);
171 EXPECT(raw_copy[0] == 15);
172 for (std::size_t s = 0; s < 16; ++s) {
173 EXPECT(raw_copy[1 + s * 10 + 9] == 0); // clear_pad = true
174 }
175 return 0;
176}
177
178int test_multithreaded_insert_and_lookup() {
179 DescriptorTable table(32);
180 constexpr int kThreads = 4;
181 constexpr int kPerThread = 50;
182
183 std::vector<std::thread> workers;
184 for (int t = 0; t < kThreads; ++t) {
185 workers.emplace_back([&table, t] {
186 for (int i = 0; i < kPerThread; ++i) {
187 const std::uint32_t id = static_cast<std::uint32_t>(t * kPerThread + i + 1);
188 std::uint32_t key[8] = {id, id * 3, id * 7, id * 11, id * 13, id * 17, id * 19, id * 23};
189 table.insert(key, id);
190 }
191 });
192 }
193
194 for (auto& w : workers) {
195 w.join();
196 }
197
198 EXPECT(table.size() == kThreads * kPerThread);
199 for (int t = 0; t < kThreads; ++t) {
200 for (int i = 0; i < kPerThread; ++i) {
201 const std::uint32_t id = static_cast<std::uint32_t>(t * kPerThread + i + 1);
202 std::uint32_t key[8] = {id, id * 3, id * 7, id * 11, id * 13, id * 17, id * 19, id * 23};
203 EXPECT(table.lookup(key) == id);
204 }
205 }
206 return 0;
207}
208
209int test_clear_resets_table() {
210 DescriptorTable table(16);
211 std::uint32_t k[8] = {1, 2, 3, 4, 5, 6, 7, 8};
212 table.insert(k, 100);
213 EXPECT(table.size() == 1);
214 EXPECT(table.lookup(k) == 100);
215
216 table.clear();
217 EXPECT(table.size() == 0);
218 EXPECT(table.lookup(k) == 0);
219 return 0;
220}
221
222int main() {
223 EXPECT(test_fnv1a_hash_matches_contract() == 0);
224 EXPECT(test_ssharp_key_padding() == 0);
225 EXPECT(test_basic_insertion_and_lookup() == 0);
226 EXPECT(test_load_factor_and_growth() == 0);
227 EXPECT(test_probe_collision_resolution() == 0);
228 EXPECT(test_gpu_buffer_serialization() == 0);
229 EXPECT(test_multithreaded_insert_and_lookup() == 0);
230 EXPECT(test_clear_resets_table() == 0);
231
232 std::printf("descriptor_table_test: all tests passed (0 failures)\n");
233 return 0;
234}
diff --git a/runtime/test/root_signature_oracle_test.cpp b/runtime/test/root_signature_oracle_test.cpp
new file mode 100644
index 000000000..d60dfae3a
--- /dev/null
+++ b/runtime/test/root_signature_oracle_test.cpp
@@ -0,0 +1,120 @@
1// Windows oracle for the RTS0 parser hypothesis (needs a real PC d3d12.lib).
2//
3// Builds synthetic versioned root-signature descriptors by hand (no game
4// data), serializes each with Microsoft's D3D12SerializeVersionedRootSignature,
5// and requires rt::rootsig::parse_rts0 to recover the same model. If the
6// hypothesis layout in root_signature.cpp ever disagrees with the real
7// serializer, this fails loudly here instead of corrupting draws silently.
8// NOT portable: runs on Windows CI only, like root_sig_test.cpp.
9#include <windows.h>
10#include <d3d12.h>
11
12#include <cstdint>
13#include <cstdio>
14#include <vector>
15
16#include "root_signature.h"
17
18namespace {
19
20int g_failures = 0;
21
22void check(bool condition, const char* what) {
23 std::printf("%s %s\n", condition ? "PASS" : "FAIL", what);
24 if (!condition) ++g_failures;
25}
26
27struct Blobs {
28 ID3DBlob* blob = nullptr;
29 ID3DBlob* error = nullptr;
30 ~Blobs() {
31 if (blob) blob->Release();
32 if (error) error->Release();
33 }
34};
35
36D3D12_VERSIONED_ROOT_SIGNATURE_DESC make_desc(
37 const D3D12_ROOT_PARAMETER1* params, uint32_t nparams) {
38 D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc{};
39 desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
40 desc.Desc_1_1.NumParameters = nparams;
41 desc.Desc_1_1.pParameters = params;
42 desc.Desc_1_1.NumStaticSamplers = 0;
43 desc.Desc_1_1.pStaticSamplers = nullptr;
44 desc.Desc_1_1.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE;
45 return desc;
46}
47
48bool parse_blob(ID3DBlob* blob, rt::rootsig::RootSignature& model) {
49 const auto* bytes = static_cast<const uint8_t*>(blob->GetBufferPointer());
50 const size_t size = blob->GetBufferSize();
51 // Diagnostics first: if the layout hypothesis is wrong, the CI log shows
52 // the real bytes instead of just a crash or a bare failure.
53 std::printf("oracle blob: %zu bytes: ", size);
54 for (size_t i = 0; i < 32 && i < size; ++i) {
55 std::printf("%02x", bytes[i]);
56 }
57 std::printf("\n");
58 std::fflush(stdout);
59 const rt::rootsig::DecodeResult d = rt::rootsig::parse_rts0(bytes, size);
60 if (!d.ok) {
61 std::printf("oracle parse failed: %s\n", d.error.c_str());
62 return false;
63 }
64 model = d.sig;
65 return true;
66}
67
68} // namespace
69
70int main() {
71 using namespace rt::rootsig;
72
73 // 4 constants (VS-visible) + 1 CBV: parses back to the same model and
74 // packs to 6 dwords, exactly like the portable packer says for 1.1.
75 D3D12_ROOT_PARAMETER1 params[2]{};
76 params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
77 params[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
78 params[0].Constants.ShaderRegister = 0;
79 params[0].Constants.RegisterSpace = 0;
80 params[0].Constants.Num32BitValues = 4;
81 params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
82 params[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
83 params[1].Descriptor.ShaderRegister = 2;
84 params[1].Descriptor.RegisterSpace = 0;
85 params[1].Descriptor.Flags = D3D12_ROOT_DESCRIPTOR_FLAG_NONE;
86
87 const D3D12_VERSIONED_ROOT_SIGNATURE_DESC desc = make_desc(params, 2);
88 Blobs blobs;
89 const HRESULT hr =
90 D3D12SerializeVersionedRootSignature(&desc, &blobs.blob, &blobs.error);
91 check(hr == S_OK, "Microsoft serializer accepts the synthetic desc");
92 if (hr != S_OK) {
93 if (blobs.error != nullptr) {
94 std::printf("serializer error: %s\n",
95 static_cast<const char*>(blobs.error->GetBufferPointer()));
96 }
97 std::printf("%d FAILURES\n", g_failures + 1);
98 return 1;
99 }
100
101 RootSignature model;
102 check(parse_blob(blobs.blob, model), "oracle blob parses");
103 if (g_failures != 0) {
104 // Never index into a model that failed to parse (that segfaulted CI).
105 std::printf("%d FAILURES\n", g_failures);
106 return 1;
107 }
108 check(model.params.size() == 2, "oracle model has 2 params");
109 check(model.params[0].type == ParamType::Constants &&
110 model.params[0].num_values == 4 &&
111 model.params[0].visibility == Visibility::Vertex,
112 "oracle constants match");
113 check(model.params[1].type == ParamType::Descriptor,
114 "oracle CBV matches");
115 const PackResult packed = pack(model);
116 check(packed.ok && packed.dword_count == 6, "oracle model packs to 6 dwords");
117
118 if (g_failures != 0) std::printf("%d FAILURES\n", g_failures);
119 return g_failures == 0 ? 0 : 1;
120}
diff --git a/runtime/test/root_signature_test.cpp b/runtime/test/root_signature_test.cpp
new file mode 100644
index 000000000..92ef8347f
--- /dev/null
+++ b/runtime/test/root_signature_test.cpp
@@ -0,0 +1,221 @@
1// Portable tests for runtime/src/root_signature.{h,cpp} (no windows.h).
2//
3// Own main + PASS/FAIL lines like the other runtime tests; returns nonzero
4// on any failure so CTest gates on it. Everything here is hand-built: no
5// game data, no DXBC, no serializer needed.
6#include <cstdint>
7#include <cstdio>
8#include <vector>
9
10#include "root_signature.h"
11
12namespace {
13
14int g_failures = 0;
15
16void check(bool condition, const char* what) {
17 std::printf("%s %s\n", condition ? "PASS" : "FAIL", what);
18 if (!condition) ++g_failures;
19}
20
21rt::rootsig::RootParameter consts(uint32_t n) {
22 rt::rootsig::RootParameter p;
23 p.type = rt::rootsig::ParamType::Constants;
24 p.num_values = n;
25 return p;
26}
27
28rt::rootsig::RootParameter view() {
29 rt::rootsig::RootParameter p;
30 p.type = rt::rootsig::ParamType::Descriptor;
31 return p;
32}
33
34rt::rootsig::RootParameter table() {
35 rt::rootsig::RootParameter p;
36 p.type = rt::rootsig::ParamType::Table;
37 p.ranges.push_back({0, 8});
38 return p;
39}
40
41void put_u32(std::vector<uint8_t>& out, uint32_t v) {
42 out.push_back(static_cast<uint8_t>(v));
43 out.push_back(static_cast<uint8_t>(v >> 8));
44 out.push_back(static_cast<uint8_t>(v >> 16));
45 out.push_back(static_cast<uint8_t>(v >> 24));
46}
47
48// Hand-built RTS0 payload in the offset-table layout the maintainer
49// described: header, parameter table, then payloads at their offsets.
50std::vector<uint8_t> build_payload() {
51 std::vector<uint8_t> p;
52 put_u32(p, 2); // version 1.1
53 put_u32(p, 2); // 2 params
54 put_u32(p, 24); // params table offset
55 put_u32(p, 0); // 0 samplers
56 put_u32(p, 0); // samplers offset
57 put_u32(p, 0x03000000u); // Xbox flags
58 // entry 0: constants at 48; entry 1: CBV descriptor at 60.
59 put_u32(p, 1);
60 put_u32(p, 0);
61 put_u32(p, 48);
62 put_u32(p, 2);
63 put_u32(p, 4);
64 put_u32(p, 60);
65 put_u32(p, 7); // register (ignored by packer)
66 put_u32(p, 0); // space
67 put_u32(p, 3); // 3 values
68 put_u32(p, 0); // register
69 put_u32(p, 0); // space
70 put_u32(p, 0); // 1.1 descriptor flags
71 return p;
72}
73
74} // namespace
75
76int main() {
77 using namespace rt::rootsig;
78
79 // Mixed signature: 4 constants + CBV + table + 1 static sampler.
80 {
81 RootSignature sig;
82 sig.params = {consts(4), view(), table()};
83 StaticSampler s;
84 s.shader_register = 3;
85 sig.static_samplers = {s};
86 const PackResult r = pack(sig);
87 check(r.ok, "mixed signature packs");
88 check(r.dword_count == 8, "mixed signature uses 8 dwords");
89 check(r.d3d12_cost == 4 + 2 + 1, "mixed signature costs 7");
90 check(r.provenance.size() == 8 && r.provenance[0].param_index == 0 &&
91 r.provenance[0].sub_index == 0 && r.provenance[4].param_index == 1 &&
92 r.provenance[4].sub_index == 0 && r.provenance[5].sub_index == 1 &&
93 r.provenance[6].param_index == 2,
94 "provenance tracks param and sub-dword");
95 }
96
97 // Exactly 32 dwords still fits.
98 {
99 RootSignature sig;
100 for (int i = 0; i < 16; ++i) sig.params.push_back(view());
101 const PackResult r = pack(sig);
102 check(r.ok && r.dword_count == 32, "16 views fill 32 dwords");
103 }
104
105 // 34 dwords: spill is refused loudly, never truncated.
106 {
107 RootSignature sig;
108 for (int i = 0; i < 17; ++i) sig.params.push_back(view());
109 const PackResult r = pack(sig);
110 check(!r.ok && r.error.find("spill") != std::string::npos,
111 "17 views refused as spill");
112 }
113
114 // 65 constants exceed the 64-dword D3D12 cost limit.
115 {
116 RootSignature sig;
117 sig.params = {consts(65)};
118 const PackResult r = pack(sig);
119 check(!r.ok && r.error.find("64-dword") != std::string::npos,
120 "65 constants refused by cost limit");
121 }
122
123 // Canonical codec round-trips byte-exactly, sampler included.
124 {
125 RootSignature sig;
126 sig.version = Version::V1_0;
127 sig.params = {consts(2), table()};
128 sig.flags = 0x03000000u; // Xbox high byte survives the model
129 StaticSampler s;
130 s.filter = 21;
131 s.mip_lod_bias = 0.5f;
132 sig.static_samplers = {s};
133 const std::vector<uint8_t> bytes = encode_canonical(sig);
134 const DecodeResult d = decode_canonical(bytes.data(), bytes.size());
135 check(d.ok, "canonical round-trip decodes");
136 check(d.sig.params.size() == 2 && d.sig.params[0].num_values == 2 &&
137 d.sig.params[1].ranges.size() == 1 &&
138 d.sig.static_samplers.size() == 1 && d.sig.flags == 0x03000000u &&
139 d.sig.static_samplers[0].filter == 21,
140 "canonical round-trip preserves model");
141 }
142
143 // Canonical decoder controls: bad magic, truncation, trailing bytes.
144 {
145 const std::vector<uint8_t> bad = {0, 1, 2, 3};
146 check(!decode_canonical(bad.data(), bad.size()).ok, "bad magic rejected");
147 RootSignature sig;
148 sig.params = {consts(1)};
149 const std::vector<uint8_t> bytes = encode_canonical(sig);
150 check(!decode_canonical(bytes.data(), bytes.size() - 1).ok,
151 "truncated canonical rejected");
152 std::vector<uint8_t> trailed = bytes;
153 trailed.push_back(0);
154 check(!decode_canonical(trailed.data(), trailed.size()).ok,
155 "trailing bytes rejected");
156 }
157
158 // RTS0 hypothesis: a hand-built blob per the documented layout parses.
159 // Hand-built RTS0 payload in the offset-table layout the maintainer
160 // described: header, parameter table, then payloads at their offsets.
161 {
162 const std::vector<uint8_t> payload = build_payload();
163 const DecodeResult d = parse_rts0(payload.data(), payload.size());
164 check(d.ok, "hand-built RTS0 parses");
165 check(d.sig.params.size() == 2 && d.sig.params[0].num_values == 3 &&
166 d.sig.flags == 0x03000000u,
167 "RTS0 model matches hand-built blob");
168 const PackResult r = pack(d.sig);
169 check(r.ok && r.dword_count == 3 + 2, "parsed RTS0 packs to 5 dwords");
170 }
171
172 // RTS0 controls: unknown version, wild offsets and truncation fail loudly.
173 {
174 std::vector<uint8_t> blob;
175 put_u32(blob, 9); // unknown version
176 put_u32(blob, 0);
177 put_u32(blob, 0);
178 put_u32(blob, 0);
179 put_u32(blob, 0);
180 put_u32(blob, 0);
181 const DecodeResult d = parse_rts0(blob.data(), blob.size());
182 check(!d.ok, "unknown RTS0 version rejected");
183 std::vector<uint8_t> cut = {1, 0};
184 check(!parse_rts0(cut.data(), cut.size()).ok, "truncated RTS0 rejected");
185 std::vector<uint8_t> wild = build_payload();
186 // Corrupt the params offset to point past the end.
187 wild[8] = 0xFF;
188 wild[9] = 0xFF;
189 wild[10] = 0xFF;
190 wild[11] = 0xFF;
191 check(!parse_rts0(wild.data(), wild.size()).ok, "wild offset rejected");
192 }
193
194 // DXBC container walk: a hand-built container with one RTS0 chunk parses
195 // through the chunk table (same path the MS serializer blob takes).
196 {
197 const std::vector<uint8_t> payload = build_payload();
198 std::vector<uint8_t> blob;
199 blob.insert(blob.end(), {'D', 'X', 'B', 'C'});
200 blob.insert(blob.end(), 16, 0); // hash
201 put_u32(blob, 1); // version
202 put_u32(blob, 0); // file size (patched below)
203 put_u32(blob, 1); // 1 chunk
204 put_u32(blob, 36); // chunk offset: 4 magic + 16 hash + 4 ver + 4 size + 4 count + 4 offset
205 blob.insert(blob.end(), {'R', 'T', 'S', '0'});
206 put_u32(blob, static_cast<uint32_t>(payload.size()));
207 blob.insert(blob.end(), payload.begin(), payload.end());
208 const uint32_t total = static_cast<uint32_t>(blob.size());
209 blob[24] = static_cast<uint8_t>(total);
210 blob[25] = static_cast<uint8_t>(total >> 8);
211 blob[26] = static_cast<uint8_t>(total >> 16);
212 blob[27] = static_cast<uint8_t>(total >> 24);
213 const DecodeResult d = parse_rts0(blob.data(), blob.size());
214 check(d.ok, "DXBC container walk finds RTS0");
215 check(d.sig.params.size() == 2 && d.sig.params[0].num_values == 3,
216 "walked RTS0 model matches payload");
217 }
218
219 if (g_failures != 0) std::printf("%d FAILURES\n", g_failures);
220 return g_failures == 0 ? 0 : 1;
221}
diff --git a/runtime/test/shaders/build.py b/runtime/test/shaders/build.py
index 180d48ec5..09730a2b0 100644
--- a/runtime/test/shaders/build.py
+++ b/runtime/test/shaders/build.py
@@ -3,8 +3,9 @@
3 python3 -I runtime/test/shaders/build.py <out dir> [name ...] 3 python3 -I runtime/test/shaders/build.py <out dir> [name ...]
4 4
5Each .asm is RDNA2 assembly. It is assembled with llvm-mc (LLVM 21+ with the AMDGPU target; set LLVM_MC to its 5Each .asm is RDNA2 assembly. It is assembled with llvm-mc (LLVM 21+ with the AMDGPU target; set LLVM_MC to its
6path, as for the shaders stage). Listings, synthetic FSSM headers and DXBC containers are staged in a temporary 6path or to a whole command, as for the shaders stage). Listings, synthetic FSSM headers and DXBC containers are
7directory. After validation, the build writes <out>/spirv/<name>.spv and the translator metadata. 7staged in a temporary directory. After validation, the build writes <out>/spirv/<name>.spv and the translator
8metadata.
8 9
9Compute shaders can override the default header with leading "; group: X,Y,Z" and "; rsrc2: 0x..." comments. 10Compute shaders can override the default header with leading "; group: X,Y,Z" and "; rsrc2: 0x..." comments.
10The stage comes from the name's prefix. Mesh and geometry shaders (ms_, gs_) also need a DXBC container with 11The stage comes from the name's prefix. Mesh and geometry shaders (ms_, gs_) also need a DXBC container with
@@ -20,10 +21,15 @@ import tempfile
20from pathlib import Path 21from pathlib import Path
21 22
22HERE = os.path.dirname(os.path.abspath(__file__)) 23HERE = os.path.dirname(os.path.abspath(__file__))
23TRANSLATOR = os.path.join(HERE, "..", "..", "..", "tools", "rdna2spirv.py") 24TOOLS = os.path.join(HERE, "..", "..", "..", "tools")
24LLVM_MC = os.environ.get("LLVM_MC", "llvm-mc") 25TRANSLATOR = os.path.join(TOOLS, "rdna2spirv.py")
26sys.path.insert(0, TOOLS)
27import mc_command # noqa: E402
28
29MC = mc_command.mc_command()
30RSRC2, GROUP = 0x8088, (64, 1, 1)
25sys.path.insert(0, HERE) # this script is also run with python -I 31sys.path.insert(0, HERE) # this script is also run with python -I
26from compute_fixture import compute_header 32from compute_fixture import compute_header # noqa: E402
27 33
28 34
29def asm_mattr(path): 35def asm_mattr(path):
@@ -45,12 +51,14 @@ def translate_tests(work, names):
45 fssm.mkdir() 51 fssm.mkdir()
46 for n in names: 52 for n in names:
47 asm_path = os.path.join(HERE, n + ".asm") 53 asm_path = os.path.join(HERE, n + ".asm")
54 raw = Path(asm_path).read_text(encoding="utf-8")
48 mattr = asm_mattr(asm_path) 55 mattr = asm_mattr(asm_path)
49 cmd = [LLVM_MC, "-triple=amdgcn--amdpal", "-mcpu=gfx1013"] 56 cmd = MC + ["-triple=amdgcn--amdpal", "-mcpu=gfx1013"]
50 if mattr: 57 if mattr:
51 cmd.append(f"-mattr={mattr}") 58 cmd.append(f"-mattr={mattr}")
52 cmd += ["-show-encoding", asm_path] 59 cmd.append("-show-encoding")
53 r = subprocess.run(cmd, capture_output=True, text=True) 60 # Feed the text on stdin: an LLVM_MC command that runs in WSL cannot open a Windows path argument.
61 r = subprocess.run(cmd, input=raw, capture_output=True, text=True)
54 if r.returncode or "error:" in r.stderr: 62 if r.returncode or "error:" in r.stderr:
55 sys.exit(f"{n}.asm did not assemble:\n{r.stderr}") 63 sys.exit(f"{n}.asm did not assemble:\n{r.stderr}")
56 # rdna2spirv.py rejects assembler directives such as the "\t.text" llvm-mc prints first. 64 # rdna2spirv.py rejects assembler directives such as the "\t.text" llvm-mc prints first.
diff --git a/runtime/test/shaders/check.py b/runtime/test/shaders/check.py
index 15c2a0c60..75f9a2d50 100644
--- a/runtime/test/shaders/check.py
+++ b/runtime/test/shaders/check.py
@@ -29,7 +29,9 @@ UNSUPPORTED = 77 # a test tool exits with
29COMPUTE = [("cs_lds", "4", "mirror64"), ("cs_exec64", "1", "exec64"), ("cs_bvh", "1", "bvh"), 29COMPUTE = [("cs_lds", "4", "mirror64"), ("cs_exec64", "1", "exec64"), ("cs_bvh", "1", "bvh"),
30 ("cs_workgroup_yz", "2x3x4", "workgroup_yz")] 30 ("cs_workgroup_yz", "2x3x4", "workgroup_yz")]
31CS_STORE = [0x400080ff, 0xe00003ff, 0x3c004000, 0xeeeeeeee, 0x40003c00, 0xbc003800] 31CS_STORE = [0x400080ff, 0xe00003ff, 0x3c004000, 0xeeeeeeee, 0x40003c00, 0xbc003800]
32CS_DUMPS = [("cs_store", CS_STORE), ("cs_wave64_ballot", [32, 16, 24, 40, 8, 48]), 32CS_SMEM = [0x5eed0024, 0x5eed0028, 0x5eed002c, 0x5eed0030, 0x5eed0010, 0x5eed0014, 0x5eed0018, 0x5eed001c]
33WAVE32_DUMPS = ("cs_store", "cs_smem_soffset_imm")
34CS_DUMPS = [("cs_store", CS_STORE), ("cs_smem_soffset_imm", CS_SMEM), ("cs_wave64_ballot", [32, 16, 24, 40, 8, 48]),
33 ("cs_wm_half_ops", [32, 16, 16, 0, 16]), ("cs_wm_half_cmp", [1, 0, 1, 1]), 35 ("cs_wm_half_ops", [32, 16, 16, 0, 16]), ("cs_wm_half_cmp", [1, 0, 1, 1]),
34 ("cs_wm_bfm64", [16, 8, 8, 40]), ("cs_wm_scc_rfl", [55, 48])] 36 ("cs_wm_bfm64", [16, 8, 8, 40]), ("cs_wm_scc_rfl", [55, 48])]
35# Cross-half wave64 tests (x = cross-half): exact results need 64 lanes, or an emulation of them on narrower subgroups. 37# Cross-half wave64 tests (x = cross-half): exact results need 64 lanes, or an emulation of them on narrower subgroups.
@@ -229,7 +231,7 @@ def main():
229 require_wave64=not W64_EMULATED))) 231 require_wave64=not W64_EMULATED)))
230 for name, want in CS_DUMPS: # all but cs_store need a 64-wide subgroup unless wave64 is emulated 232 for name, want in CS_DUMPS: # all but cs_store need a 64-wide subgroup unless wave64 is emulated
231 results.append((name, compute_test(tools, spirv, name, "1", "dump", 233 results.append((name, compute_test(tools, spirv, name, "1", "dump",
232 require_wave64=name != "cs_store" and not W64_EMULATED, 234 require_wave64=name not in WAVE32_DUMPS and not W64_EMULATED,
233 expected_words=want))) 235 expected_words=want)))
234 for name, want in W64X_DUMPS: # without --require-wave64 when LEONIDA_W64_EMULATE=1 236 for name, want in W64X_DUMPS: # without --require-wave64 when LEONIDA_W64_EMULATE=1
235 results.append((name, compute_test(tools, spirv, name, "1", "dump", require_wave64=not W64_EMULATED, 237 results.append((name, compute_test(tools, spirv, name, "1", "dump", require_wave64=not W64_EMULATED,
diff --git a/runtime/test/shaders/cs_smem_soffset_imm.asm b/runtime/test/shaders/cs_smem_soffset_imm.asm
new file mode 100644
index 000000000..399de1860
--- /dev/null
+++ b/runtime/test/shaders/cs_smem_soffset_imm.asm
@@ -0,0 +1,61 @@
1; SMEM loads that carry a register offset AND an immediate (llvm-mc: "sOFF offset:IMM"): address = base + soffset + imm.
2; Measured on an AMD Radeon RX 6800 (gfx1030) by running s_buffer_load_dword/x2/x4/x8 as a raw compute kernel:
3; soffset 8 + imm 4 reads the dword at +12. s_load_dword shares the SMEM encoding; applying the rule to it is an inference.
4; Thread 0 seeds heap bytes 0x10..0x30 with 0x5eed0000 + byte offset, then loads with s8 = 0x10:
5; s_buffer_load_dword s9, s[0:3], s8 offset:0x14 -> byte 0x24 (imm dropped: 0x10, s8 dropped: 0x14)
6; s_load_dword s10, s[4:5], s8 offset:0x18 -> byte 0x28 (imm dropped: 0x10, s8 dropped: 0x18)
7; s_buffer_load_dwordx2 s[12:13], s[0:3], s8 offset:0x1c -> bytes 0x2c, 0x30 (imm dropped: 0x10, 0x14; s8 dropped: 0x1c, 0x20)
8; and writes s9, s10, s12, s13 to out[0..3]; out[4..7] keep the seeds of bytes 0x10..0x1c.
9; All offsets are multiples of 4 and inside the buffer, so alignment and num_records play no part.
10; Run: vk_compute_test cs_smem_soffset_imm.spv 1 dump -> out[0..7] = 0x5eed0024 0x5eed0028 0x5eed002c 0x5eed0030
11; 0x5eed0010 0x5eed0014 0x5eed0018 0x5eed001c (1592590372 1592590376 1592590380 1592590384 1592590352 1592590356
12; 1592590360 1592590364). Same FSSM header as cs_lds.
13v_cmpx_eq_u32_e32 0, v0
14v_mov_b32 v1, 0x5eed0010
15v_mov_b32 v2, 0x10
16buffer_store_dword v1, v2, s[0:3], 0 offen
17v_mov_b32 v1, 0x5eed0014
18v_mov_b32 v2, 0x14
19buffer_store_dword v1, v2, s[0:3], 0 offen
20v_mov_b32 v1, 0x5eed0018
21v_mov_b32 v2, 0x18
22buffer_store_dword v1, v2, s[0:3], 0 offen
23v_mov_b32 v1, 0x5eed001c
24v_mov_b32 v2, 0x1c
25buffer_store_dword v1, v2, s[0:3], 0 offen
26v_mov_b32 v1, 0x5eed0020
27v_mov_b32 v2, 0x20
28buffer_store_dword v1, v2, s[0:3], 0 offen
29v_mov_b32 v1, 0x5eed0024
30v_mov_b32 v2, 0x24
31buffer_store_dword v1, v2, s[0:3], 0 offen
32v_mov_b32 v1, 0x5eed0028
33v_mov_b32 v2, 0x28
34buffer_store_dword v1, v2, s[0:3], 0 offen
35v_mov_b32 v1, 0x5eed002c
36v_mov_b32 v2, 0x2c
37buffer_store_dword v1, v2, s[0:3], 0 offen
38v_mov_b32 v1, 0x5eed0030
39v_mov_b32 v2, 0x30
40buffer_store_dword v1, v2, s[0:3], 0 offen
41s_waitcnt vmcnt(0)
42s_mov_b32 s4, 0
43s_mov_b32 s5, 0
44s_mov_b32 s8, 0x10
45s_buffer_load_dword s9, s[0:3], s8 offset:0x14
46s_load_dword s10, s[4:5], s8 offset:0x18
47s_buffer_load_dwordx2 s[12:13], s[0:3], s8 offset:0x1c
48s_waitcnt lgkmcnt(0)
49v_mov_b32 v1, s9
50v_mov_b32 v2, 0
51buffer_store_dword v1, v2, s[0:3], 0 offen
52v_mov_b32 v1, s10
53v_mov_b32 v2, 4
54buffer_store_dword v1, v2, s[0:3], 0 offen
55v_mov_b32 v1, s12
56v_mov_b32 v2, 8
57buffer_store_dword v1, v2, s[0:3], 0 offen
58v_mov_b32 v1, s13
59v_mov_b32 v2, 12
60buffer_store_dword v1, v2, s[0:3], 0 offen
61s_endpgm
diff --git a/runtime/test/vk_texture_test.cpp b/runtime/test/vk_texture_test.cpp
index a46338bf6..fafc8ef50 100644
--- a/runtime/test/vk_texture_test.cpp
+++ b/runtime/test/vk_texture_test.cpp
@@ -34,23 +34,7 @@ static std::vector<uint32_t> read_spv(const char* p) {
34 return w; 34 return w;
35} 35}
36 36
37// Same hash as the translator's desc_lookup: FNV-1a over the 8 key dwords (whole dwords, not bytes). 37#include "../src/descriptor_table.h"
38static uint32_t key_hash(const uint32_t k[8]) {
39 uint32_t h = 2166136261u;
40 for (int i = 0; i < 8; i++) h = (h ^ k[i]) * 16777619u;
41 return h;
42}
43static void table_insert(std::vector<uint32_t>& t, const uint32_t key[8], uint32_t index) {
44 uint32_t mask = t[0], h = key_hash(key);
45 for (uint32_t k = 0; k < 8; k++) {
46 uint32_t slot = (h + k) & mask, base = slot * 10;
47 if (t[base + 10] == 0xA11CA7ED) continue; // pad dword marks a used slot (host-side only)
48 for (int j = 0; j < 8; j++) t[base + 1 + j] = key[j];
49 t[base + 9] = index;
50 t[base + 10] = 0xA11CA7ED;
51 return;
52 }
53}
54 38
55int main(int argc, char** argv) { 39int main(int argc, char** argv) {
56 if (argc < 9) { std::fprintf(stderr, "usage: vk_texture_test vs fs out ptr_sgpr s0 s1 s2 s3\n"); return 2; } 40 if (argc < 9) { std::fprintf(stderr, "usage: vk_texture_test vs fs out ptr_sgpr s0 s1 s2 s3\n"); return 2; }
@@ -133,11 +117,10 @@ int main(int argc, char** argv) {
133 VkBufferDeviceAddressInfo bdai{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bdai.buffer = heap; 117 VkBufferDeviceAddressInfo bdai{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bdai.buffer = heap;
134 VkDeviceAddress heap_base = vkGetBufferDeviceAddress(dev, &bdai); 118 VkDeviceAddress heap_base = vkGetBufferDeviceAddress(dev, &bdai);
135 // Descriptor hash table: 16 slots. 119 // Descriptor hash table: 16 slots.
136 std::vector<uint32_t> table(1 + 16 * 10 + 10, 0); 120 leonida::DescriptorTable desc_table(16);
137 table[0] = 15; 121 desc_table.insert(tsharp, 1);
138 table_insert(table, tsharp, 1); 122 desc_table.insert(ssharp, 1);
139 table_insert(table, ssharp, 1); 123 const auto table = desc_table.build_gpu_buffer(true);
140 for (uint32_t s = 0; s <= 16; s++) if (s * 10 + 10 < table.size() && table[s * 10 + 10] == 0xA11CA7ED) table[s * 10 + 10] = 0;
141 VkBuffer tb; VkDeviceMemory tbm; void* tbp; 124 VkBuffer tb; VkDeviceMemory tbm; void* tbp;
142 CHECK(make_buffer(table.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &tb, &tbm, &tbp)); 125 CHECK(make_buffer(table.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &tb, &tbm, &tbp));
143 std::memcpy(tbp, table.data(), table.size() * 4); 126 std::memcpy(tbp, table.data(), table.size() * 4);
diff --git a/runtime/test/vulkan_loader.h b/runtime/test/vulkan_loader.h
index 43a54d242..a1a461ef0 100644
--- a/runtime/test/vulkan_loader.h
+++ b/runtime/test/vulkan_loader.h
@@ -1,4 +1,4 @@
1// Loads the Vulkan loader at run time: vulkan-1.dll on Windows, libvulkan.so.1 elsewhere. No import library. 1// Loads the Vulkan loader at run time: vulkan-1.dll on Windows, MoltenVK on macOS, libvulkan.so.1 elsewhere. No import library.
2#pragma once 2#pragma once
3 3
4#ifndef VK_NO_PROTOTYPES 4#ifndef VK_NO_PROTOTYPES
@@ -20,6 +20,15 @@ inline PFN_vkGetInstanceProcAddr load_vulkan() {
20 constexpr auto library_name = "vulkan-1.dll"; 20 constexpr auto library_name = "vulkan-1.dll";
21 static const auto library = LoadLibraryA(library_name); 21 static const auto library = LoadLibraryA(library_name);
22 const auto entry = library ? GetProcAddress(library, "vkGetInstanceProcAddr") : nullptr; 22 const auto entry = library ? GetProcAddress(library, "vkGetInstanceProcAddr") : nullptr;
23#elif defined(__APPLE__)
24 // MoltenVK directly: through the loader it is a portability driver, which every vkCreateInstance here would
25 // have to opt into. The Vulkan SDK installs it in /usr/local/lib (a default search path), Homebrew does not.
26 constexpr auto library_name = "libMoltenVK.dylib";
27 static const auto library = [] {
28 auto handle = dlopen(library_name, RTLD_NOW | RTLD_LOCAL);
29 return handle ? handle : dlopen("/opt/homebrew/lib/libMoltenVK.dylib", RTLD_NOW | RTLD_LOCAL);
30 }();
31 const auto entry = library ? dlsym(library, "vkGetInstanceProcAddr") : nullptr;
23#else 32#else
24 constexpr auto library_name = "libvulkan.so.1"; 33 constexpr auto library_name = "libvulkan.so.1";
25 static const auto library = dlopen(library_name, RTLD_NOW | RTLD_LOCAL); 34 static const auto library = dlopen(library_name, RTLD_NOW | RTLD_LOCAL);