upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src
diff options
context:
space:
mode:
authorJan Trencansky <jan.trencansky@protonmail.com>2026-11-25 18:18:55 -0500
committerJan Trencansky <jan.trencansky@protonmail.com>2026-11-25 18:18:55 -0500
commitd4fb292344088e7925ddeb3bbceb5a9ac46de8c2 (patch)
tree551a4e8b93953b3b481b3a30739ca73eb45615e8 /runtime/src
parent244387529b6fb4992b601704d32016e7beeadd28 (diff)
parentffcfe68f12891826a2b15e19f31149d8bb44e778 (diff)
Merge main into rt-title-hud-vram-budget
Brings in #2137 (LEONIDA_DEV_OVERLAY), which the next commit extends. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/src')
-rw-r--r--runtime/src/base_reservation.h5
-rw-r--r--runtime/src/dev_overlay.h278
-rw-r--r--runtime/src/dev_status.h51
-rw-r--r--runtime/src/frame_pacer.h40
-rw-r--r--runtime/src/gfx10_descriptors.h10
-rw-r--r--runtime/src/large_module_gate.h293
-rw-r--r--runtime/src/main.cpp12
-rw-r--r--runtime/src/pe_loader.cpp35
-rw-r--r--runtime/src/root_signature.cpp11
-rw-r--r--runtime/src/root_signature.h8
-rw-r--r--runtime/src/submit_phases.h44
-rw-r--r--runtime/src/vulkan_backend.h30
-rw-r--r--runtime/src/vulkan_replay.h142
13 files changed, 897 insertions, 62 deletions
diff --git a/runtime/src/base_reservation.h b/runtime/src/base_reservation.h
index b76c28c70..5ccfe1aaa 100644
--- a/runtime/src/base_reservation.h
+++ b/runtime/src/base_reservation.h
@@ -63,7 +63,10 @@ inline void* commit_reserved(std::uint64_t base, std::uint64_t size) {
63} 63}
64 64
65// The preferred range of `image` when it has no relocations and that range is not free in this process; nullopt 65// The preferred range of `image` when it has no relocations and that range is not free in this process; nullopt
66// when the image can be mapped as it is (or is not a readable PE32+, which the loader reports itself). 66// when the image can be mapped as it is (or is not a readable PE32+, which the loader reports itself). Without a
67// relocation directory the loader refuses to move an image that has IMAGE_FILE_RELOCS_STRIPPED, and moves one with
68// the flag clear with nothing fixed up: that is right only for an image with no absolute addresses in it, so its
69// range is kept free either way. An image with a relocation table is moved and fixed up whatever the flag says.
67inline std::optional<Range> needed(const std::filesystem::path& image) { 70inline std::optional<Range> needed(const std::filesystem::path& image) {
68 std::ifstream file(image, std::ios::binary); 71 std::ifstream file(image, std::ios::binary);
69 IMAGE_DOS_HEADER dos{}; 72 IMAGE_DOS_HEADER dos{};
diff --git a/runtime/src/dev_overlay.h b/runtime/src/dev_overlay.h
new file mode 100644
index 000000000..fe38031db
--- /dev/null
+++ b/runtime/src/dev_overlay.h
@@ -0,0 +1,278 @@
1#pragma once
2// LEONIDA_DEV_OVERLAY=1 (off by default, Windows): a small click-through window over the top left corner of the title's
3// window that says how the boot is doing: frames and submissions a second, where a submission's CPU time goes and which
4// phase runs now, pipeline builds, indirect draws, CPU, memory. It is its own window with its own thread and GDI text,
5// so it keeps counting while the title shows no frames for seconds (pipeline builds, a stalled submission), it is in no
6// captured frame, and it changes nothing the GPU does. It only reads counters: submit_phases.h, indirect_draw_stats.h
7// and dev_status.h. LEONIDA_TITLE_HUD (shims/title_hud.h) is the other view: frame times, memory and compile time in the
8// window's title bar.
9#include "dev_status.h"
10#include "indirect_draw_stats.h"
11#include "submit_phases.h"
12
13#ifdef _WIN32
14#ifndef NOMINMAX
15#define NOMINMAX
16#endif
17#include <windows.h>
18#include <psapi.h>
19#ifdef _MSC_VER
20#pragma comment(lib, "user32.lib")
21#pragma comment(lib, "gdi32.lib")
22#pragma comment(lib, "psapi.lib")
23#endif
24#endif
25
26#include <algorithm>
27#include <cstdint>
28#include <cstdio>
29#include <cstdlib>
30#include <string>
31#include <thread>
32#include <vector>
33
34namespace leonida::dev_overlay {
35
36// The counters between two looks. A total that went down was reset by its own log line: what it holds is the new part.
37inline std::uint64_t grown(std::uint64_t now, std::uint64_t& before) {
38 const std::uint64_t by = now >= before ? now - before : now;
39 before = now;
40 return by;
41}
42
43struct Sample {
44 double seconds = 0;
45 double frames = 0, submissions = 0; // a second
46 double phase_ms[submit_phases::kCount]{}; // a submission
47 int phase = -1; // running now
48 double phase_for = 0; // seconds it has been
49 unsigned building = 0;
50 std::uint64_t built = 0;
51 std::string build; // the last one started
52 unsigned long long drawn = 0, skipped = 0; // indirect draws so far
53 double cores = 0, process_gb = 0, free_gb = 0;
54};
55
56// The text of one sample: pure, for the test.
57inline std::vector<std::string> lines(const Sample& s, double age) {
58 char text[160];
59 std::vector<std::string> out;
60 std::snprintf(text, sizeof text, "Leonida dev %.0f s %.1f fps %.1f submissions/s", age, s.frames, s.submissions);
61 out.emplace_back(text);
62 double total = 0;
63 for (const double ms : s.phase_ms) total += ms;
64 std::snprintf(text, sizeof text, "CPU/submission %.1f ms: descriptors %.1f, textures %.1f, copies %.1f, replay %.1f", total,
65 s.phase_ms[submit_phases::heaps], s.phase_ms[submit_phases::textures],
66 s.phase_ms[submit_phases::shadows] + s.phase_ms[submit_phases::geometry],
67 s.phase_ms[submit_phases::replay]);
68 out.emplace_back(text);
69 static const char* const now[submit_phases::kCount] = {"waiting for the GPU", "fixing descriptors", "copying title memory",
70 "copying geometry", "refreshing textures", "recording and submitting"};
71 if (s.phase >= 0 && s.phase < int(submit_phases::kCount))
72 std::snprintf(text, sizeof text, "now: %s%s", now[s.phase],
73 s.phase_for >= 1 ? (" for " + std::to_string(int(s.phase_for)) + " s").c_str() : "");
74 else
75 std::snprintf(text, sizeof text, "now: the title's own code");
76 out.emplace_back(text);
77 if (s.building)
78 std::snprintf(text, sizeof text, "pipelines: %llu built, %u building (%.50s)",
79 static_cast<unsigned long long>(s.built), s.building, s.build.c_str());
80 else
81 std::snprintf(text, sizeof text, "pipelines: %llu built", static_cast<unsigned long long>(s.built));
82 out.emplace_back(text);
83 std::snprintf(text, sizeof text, "indirect draws: %llu drawn, %llu skipped", s.drawn, s.skipped);
84 out.emplace_back(text);
85 std::snprintf(text, sizeof text, "%.1f cores, %.1f GB used, %.1f GB RAM free", s.cores, s.process_gb, s.free_gb);
86 out.emplace_back(text);
87 return out;
88}
89
90inline bool enabled() {
91 static const bool on = [] {
92#ifdef _WIN32
93 char value[3]{};
94 std::size_t length = 0;
95 return getenv_s(&length, value, sizeof value, "LEONIDA_DEV_OVERLAY") == 0 && length == 2 && value[0] == '1';
96#else
97 const char* value = std::getenv("LEONIDA_DEV_OVERLAY");
98 return value && value[0] == '1' && !value[1];
99#endif
100 }();
101 return on;
102}
103
104#ifdef _WIN32
105class Overlay {
106public:
107 void run() {
108 WNDCLASSW type{};
109 type.lpfnWndProc = &Overlay::procedure;
110 type.hInstance = GetModuleHandleW(nullptr);
111 type.lpszClassName = L"LeonidaDevOverlay";
112 if (!RegisterClassW(&type)) return;
113 window_ = CreateWindowExW(WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE | WS_EX_TOPMOST | WS_EX_TOOLWINDOW,
114 type.lpszClassName, L"", WS_POPUP, 0, 0, 10, 10, nullptr, nullptr, type.hInstance, this);
115 if (!window_) return;
116 SetWindowLongPtrW(window_, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));
117 SetLayeredWindowAttributes(window_, 0, 205, LWA_ALPHA);
118 font_ = CreateFontW(-14, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,
119 CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, FIXED_PITCH | FF_MODERN, L"Consolas");
120 look();
121 SetTimer(window_, 1, 500, nullptr);
122 MSG message;
123 while (GetMessageW(&message, nullptr, 0, 0) > 0) DispatchMessageW(&message);
124 }
125
126private:
127 static LRESULT CALLBACK procedure(HWND window, UINT message, WPARAM w, LPARAM l) {
128 auto* self = reinterpret_cast<Overlay*>(GetWindowLongPtrW(window, GWLP_USERDATA));
129 if (self && message == WM_TIMER) {
130 self->look();
131 return 0;
132 }
133 if (self && message == WM_PAINT) {
134 self->paint();
135 return 0;
136 }
137 if (message == WM_NCHITTEST) return HTTRANSPARENT;
138 return DefWindowProcW(window, message, w, l);
139 }
140
141 // The process's largest visible top-level window is the title's.
142 struct Search {
143 HWND own, found;
144 std::int64_t area;
145 };
146 static BOOL CALLBACK consider(HWND window, LPARAM parameter) {
147 auto& search = *reinterpret_cast<Search*>(parameter);
148 DWORD process = 0;
149 GetWindowThreadProcessId(window, &process);
150 RECT r{};
151 if (process != GetCurrentProcessId() || window == search.own || !IsWindowVisible(window) || IsIconic(window) ||
152 !GetClientRect(window, &r))
153 return TRUE;
154 const std::int64_t area = std::int64_t(r.right) * r.bottom;
155 if (area > search.area) search = {search.own, window, area};
156 return TRUE;
157 }
158
159 void look() {
160 namespace sp = submit_phases;
161 sp::Totals& totals = sp::totals();
162 const std::int64_t now = sp::now_ns();
163 Sample s;
164 s.seconds = before_ ? double(now - before_) * 1e-9 : 0;
165 const std::uint64_t frames = grown(totals.present_serial.load(std::memory_order_relaxed), frames_);
166 const std::uint64_t submissions = grown(totals.all_submissions.load(std::memory_order_relaxed), submissions_);
167 std::uint64_t ns[sp::kCount];
168 for (unsigned p = 0; p < sp::kCount; ++p) ns[p] = grown(totals.ns[p].load(std::memory_order_relaxed), ns_[p]);
169 // A stall longer than a look leaves nothing to divide by: the figures then cover the last two seconds.
170 window_frames_ += frames;
171 window_submissions_ += submissions;
172 window_seconds_ += s.seconds;
173 for (unsigned p = 0; p < sp::kCount; ++p) window_ns_[p] += ns[p];
174 if (window_seconds_ >= 2 || !before_) {
175 shown_ = {};
176 if (window_seconds_ > 0) {
177 shown_.frames = double(window_frames_) / window_seconds_;
178 shown_.submissions = double(window_submissions_) / window_seconds_;
179 }
180 for (unsigned p = 0; p < sp::kCount; ++p) {
181 if (window_submissions_) shown_.phase_ms[p] = double(window_ns_[p]) * 1e-6 / double(window_submissions_);
182 window_ns_[p] = 0;
183 }
184 window_frames_ = window_submissions_ = 0;
185 window_seconds_ = 0;
186 }
187 s.frames = shown_.frames;
188 s.submissions = shown_.submissions;
189 std::copy(std::begin(shown_.phase_ms), std::end(shown_.phase_ms), std::begin(s.phase_ms));
190 before_ = now;
191
192 const sp::Running running = sp::running();
193 s.phase = running.phase;
194 if (s.phase >= 0) s.phase_for = std::max(0.0, double(now - running.since) * 1e-9);
195 dev_status::Builds& builds = dev_status::builds();
196 s.building = builds.active.load(std::memory_order_relaxed);
197 s.built = builds.done.load(std::memory_order_relaxed);
198 s.build = builds.last();
199 const auto& draws = indirect_stats::counts().values;
200 s.drawn = draws[std::size_t(indirect_stats::Event::emitted)].load(std::memory_order_relaxed);
201 s.skipped = draws[std::size_t(indirect_stats::Event::record_skip)].load(std::memory_order_relaxed) +
202 draws[std::size_t(indirect_stats::Event::replay_skip)].load(std::memory_order_relaxed);
203 FILETIME created{}, exited{}, kernel{}, user{};
204 if (GetProcessTimes(GetCurrentProcess(), &created, &exited, &kernel, &user)) {
205 const auto ticks = [](const FILETIME& f) { return (std::uint64_t(f.dwHighDateTime) << 32) | f.dwLowDateTime; };
206 const std::uint64_t used = grown(ticks(kernel) + ticks(user), cpu_);
207 if (s.seconds > 0) s.cores = double(used) * 1e-7 / s.seconds;
208 }
209 PROCESS_MEMORY_COUNTERS memory{sizeof memory};
210 if (GetProcessMemoryInfo(GetCurrentProcess(), &memory, sizeof memory))
211 s.process_gb = double(memory.WorkingSetSize) / double(1u << 30);
212 MEMORYSTATUSEX status{sizeof status};
213 if (GlobalMemoryStatusEx(&status)) s.free_gb = double(status.ullAvailPhys) / double(1u << 30);
214 lines_ = lines(s, sp::process_age());
215 place();
216 }
217
218 void place() {
219 Search search{window_, nullptr, 0};
220 EnumWindows(&Overlay::consider, reinterpret_cast<LPARAM>(&search));
221 // Shown only over the title while it is the window in front, so the topmost text is never over anything else.
222 if (!search.found || GetForegroundWindow() != search.found) {
223 ShowWindow(window_, SW_HIDE);
224 return;
225 }
226 POINT corner{8, 8};
227 ClientToScreen(search.found, &corner);
228 std::size_t longest = 0;
229 for (const auto& line : lines_) longest = std::max(longest, line.size());
230 SetWindowPos(window_, HWND_TOPMOST, corner.x, corner.y, int(longest) * 8 + 12, int(lines_.size()) * 17 + 8,
231 SWP_NOACTIVATE | SWP_SHOWWINDOW);
232 InvalidateRect(window_, nullptr, FALSE);
233 }
234
235 void paint() {
236 PAINTSTRUCT ps;
237 HDC dc = BeginPaint(window_, &ps);
238 RECT area;
239 GetClientRect(window_, &area);
240 HDC memory = CreateCompatibleDC(dc);
241 HBITMAP bitmap = CreateCompatibleBitmap(dc, area.right, area.bottom);
242 HGDIOBJ old_bitmap = SelectObject(memory, bitmap), old_font = SelectObject(memory, font_);
243 FillRect(memory, &area, static_cast<HBRUSH>(GetStockObject(BLACK_BRUSH)));
244 SetBkMode(memory, TRANSPARENT);
245 int y = 4;
246 for (std::size_t i = 0; i < lines_.size(); ++i, y += 17) {
247 SetTextColor(memory, i == 0 ? RGB(120, 255, 140) : RGB(235, 235, 235));
248 TextOutA(memory, 6, y, lines_[i].data(), int(lines_[i].size()));
249 }
250 BitBlt(dc, 0, 0, area.right, area.bottom, memory, 0, 0, SRCCOPY);
251 SelectObject(memory, old_bitmap);
252 SelectObject(memory, old_font);
253 DeleteObject(bitmap);
254 DeleteDC(memory);
255 EndPaint(window_, &ps);
256 }
257
258 HWND window_ = nullptr;
259 HFONT font_ = nullptr;
260 std::vector<std::string> lines_;
261 std::int64_t before_ = 0;
262 std::uint64_t frames_ = 0, submissions_ = 0, cpu_ = 0, ns_[submit_phases::kCount]{};
263 std::uint64_t window_frames_ = 0, window_submissions_ = 0, window_ns_[submit_phases::kCount]{};
264 double window_seconds_ = 0;
265 Sample shown_;
266};
267#endif
268
269// Once per process; nothing without LEONIDA_DEV_OVERLAY=1.
270inline void start() {
271#ifdef _WIN32
272 if (!enabled()) return;
273 std::fprintf(stderr, "[rt] dev overlay on (LEONIDA_DEV_OVERLAY=1)\n");
274 std::thread([] { static Overlay overlay; overlay.run(); }).detach();
275#endif
276}
277
278} // namespace leonida::dev_overlay
diff --git a/runtime/src/dev_status.h b/runtime/src/dev_status.h
new file mode 100644
index 000000000..3efc9bf4f
--- /dev/null
+++ b/runtime/src/dev_status.h
@@ -0,0 +1,51 @@
1#pragma once
2// What the runtime is building now, for the dev overlay (dev_overlay.h). Always on: two relaxed atomics a build, and a
3// short copy under a lock for the name.
4#include <algorithm>
5#include <atomic>
6#include <cstdint>
7#include <cstring>
8#include <mutex>
9#include <string>
10
11namespace leonida::dev_status {
12
13struct Builds {
14 std::atomic<unsigned> active{0};
15 std::atomic<std::uint64_t> done{0};
16
17 std::string last() {
18 std::lock_guard lock(mutex_);
19 return name_;
20 }
21 void name(const char* text) {
22 std::lock_guard lock(mutex_);
23 const std::size_t n = std::min(std::strlen(text), sizeof name_ - 1);
24 std::memcpy(name_, text, n);
25 name_[n] = 0;
26 }
27
28private:
29 std::mutex mutex_;
30 char name_[96]{};
31};
32inline Builds& builds() {
33 static Builds instance;
34 return instance;
35}
36
37// One pipeline build, from construction to destruction.
38struct Build {
39 explicit Build(const char* name) {
40 builds().name(name);
41 builds().active.fetch_add(1, std::memory_order_relaxed);
42 }
43 ~Build() {
44 builds().active.fetch_sub(1, std::memory_order_relaxed);
45 builds().done.fetch_add(1, std::memory_order_relaxed);
46 }
47 Build(const Build&) = delete;
48 Build& operator=(const Build&) = delete;
49};
50
51} // namespace leonida::dev_status
diff --git a/runtime/src/frame_pacer.h b/runtime/src/frame_pacer.h
index 2c9f1fd7e..5588d73ea 100644
--- a/runtime/src/frame_pacer.h
+++ b/runtime/src/frame_pacer.h
@@ -19,6 +19,10 @@
19// * A frame is "in flight" from PresentX until the vblank that shows it. Frames show one per vblank, in order. 19// * A frame is "in flight" from PresentX until the vblank that shows it. Frames show one per vblank, in order.
20// WaitFrameEventX does not return while `latency` frames are in flight. A frame presented while the origin event 20// WaitFrameEventX does not return while `latency` frames are in flight. A frame presented while the origin event
21// is not armed is not paced (PresentX does not hold it for a vblank): it shows at once and is never in flight. 21// is not armed is not paced (PresentX does not hold it for a vblank): it shows at once and is never in flight.
22// * At most `latency` frames are in flight. A present into a full queue (several presents with no wait between
23// them) replaces the newest queued frame and takes its vblank, like a mailbox: the replaced frame is never shown,
24// and the older ones keep their vblanks. So the queue, and the next wait, never reach further than `latency`
25// vblanks ahead, however many presents came in between.
22// * A wait that comes late (after the next origin already passed) returns at once with the newest passed origin; 26// * A wait that comes late (after the next origin already passed) returns at once with the newest passed origin;
23// the missed origins are skipped, not queued. 27// the missed origins are skipped, not queued.
24// * Tokens are 1, 2, 3, ... (0 is the null token), one per successful wait, never reused, across suspend/resume. 28// * Tokens are 1, 2, 3, ... (0 is the null token), one per successful wait, never reused, across suspend/resume.
@@ -266,8 +270,9 @@ public:
266 270
267 // GetFrameStatisticsX(token, type_mask, &count, array). `count` is the room in `out` on entry and the number of 271 // GetFrameStatisticsX(token, type_mask, &count, array). `count` is the room in `out` on entry and the number of
268 // entries written on return. S_OK when every producible requested type was written (event, present, display), 272 // entries written on return. S_OK when every producible requested type was written (event, present, display),
269 // S_FALSE with count 0 or fewer when they are not (there yet, or the token is unknown or has aged out of the 273 // S_FALSE with count 0 or fewer when they are not (there yet, the frame was replaced in a full queue and never
270 // last 64). With a null `out`, count only receives how many entries are available. 274 // shown, or the token is unknown or has aged out of the last 64). With a null `out`, count only receives how many
275 // entries are available.
271 std::int32_t get_frame_statistics(std::uint64_t token, std::uint32_t type_mask, std::uint32_t* count, 276 std::int32_t get_frame_statistics(std::uint64_t token, std::uint32_t type_mask, std::uint32_t* count,
272 FrameStatistic* out) { 277 FrameStatistic* out) {
273 if (!count) return pacer_hr::invalid_arg; 278 if (!count) return pacer_hr::invalid_arg;
@@ -359,12 +364,10 @@ public:
359 if (r.token == token) { r.presented = r.displayed = true; r.present_us = r.display_us = now; } 364 if (r.token == token) { r.presented = r.displayed = true; r.present_us = r.display_us = now; }
360 return; 365 return;
361 } 366 }
362 // The vblank after now, and not before the one after the previous queued frame. 367 const bool queued_before = !pending_.empty();
363 const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0; 368 std::uint64_t flip = queue_flip_locked(now);
364 std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_;
365 if (!pending_.empty()) flip = std::max(flip, pending_.back().flip_us + period_us_);
366 float percent = 0.0f; 369 float percent = 0.0f;
367 if (sync == PresentSync::immediate && pending_.empty()) { 370 if (sync == PresentSync::immediate && !queued_before) {
368 flip = now; 371 flip = now;
369 std::uint64_t late_us = 0; 372 std::uint64_t late_us = 0;
370 for (const Record& r : records_) 373 for (const Record& r : records_)
@@ -386,9 +389,7 @@ public:
386 record_present_timing_locked(now, 0); 389 record_present_timing_locked(now, 0);
387 if (!interval_set_ || !any_armed_locked() || uncapped_) return; 390 if (!interval_set_ || !any_armed_locked() || uncapped_) return;
388 retire_locked(now); 391 retire_locked(now);
389 const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0; 392 const std::uint64_t flip = queue_flip_locked(now);
390 std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_;
391 if (!pending_.empty()) flip = std::max(flip, pending_.back().flip_us + period_us_);
392 pending_.push_back(Pending{0, flip, 0.0f}); 393 pending_.push_back(Pending{0, flip, 0.0f});
393 cv_.notify_all(); 394 cv_.notify_all();
394 } 395 }
@@ -484,6 +485,25 @@ private:
484 bool presented = false, displayed = false; 485 bool presented = false, displayed = false;
485 }; 486 };
486 487
488 // The vblank a frame presented now is queued for: the vblank after now, and not before the one after the previous
489 // queued frame. At most `latency_` frames are in flight, so with the queue full the newest queued frame is
490 // replaced (dropped: never shown) and the new one takes its vblank; the older ones keep theirs. A queue longer
491 // than the latency (after SetFrameIntervalX lowered it) is cut back the same way, from the newest end.
492 std::uint64_t queue_flip_locked(std::uint64_t now) {
493 if (pending_.size() >= latency_) { // latency_ is at least 1, so the queue is not empty
494 std::uint64_t flip = 0;
495 while (pending_.size() >= latency_) {
496 flip = pending_.back().flip_us;
497 pending_.pop_back();
498 }
499 return flip;
500 }
501 const std::uint64_t since = now > epoch_us_ ? now - epoch_us_ : 0;
502 std::uint64_t flip = epoch_us_ + (since / period_us_ + 1) * period_us_;
503 if (!pending_.empty()) flip = std::max(flip, pending_.back().flip_us + period_us_);
504 return flip;
505 }
506
487 void record_present_timing_locked(std::uint64_t now, std::uint64_t token) { 507 void record_present_timing_locked(std::uint64_t now, std::uint64_t token) {
488 ++presents_recorded_; 508 ++presents_recorded_;
489 if (has_last_present_ && now >= last_present_us_) { 509 if (has_last_present_ && now >= last_present_us_) {
diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h
index 219e0a8c5..acfa590f8 100644
--- a/runtime/src/gfx10_descriptors.h
+++ b/runtime/src/gfx10_descriptors.h
@@ -236,6 +236,16 @@ inline constexpr VkImageViewType vulkan_view_type(ImageType type) {
236 } 236 }
237} 237}
238 238
239inline constexpr VkImageSubresourceRange vulkan_subresource_range(const Image& image, VkImageAspectFlags aspects) {
240 const bool volume = image.type == ImageType::image_3d;
241 return {aspects, image.first_mip, image.mip_count, volume ? 0u : image.first_layer,
242 volume ? 1u : image.layer_count};
243}
244
245inline constexpr bool has_hardware_volume_uav_slice_offset(const ImageWords& words, const Image& image) {
246 return image.type == ImageType::image_3d && image.first_layer != 0 && detail::get(words[5], 0, 4) == 1;
247}
248
239// ---- formats ---- 249// ---- formats ----
240 250
241// One row for each Vulkan format: its GFX10_FORMAT code, and the DST_SEL that reads its channels as R, G, B, A 251// One row for each Vulkan format: its GFX10_FORMAT code, and the DST_SEL that reads its channels as R, G, B, A
diff --git a/runtime/src/large_module_gate.h b/runtime/src/large_module_gate.h
new file mode 100644
index 000000000..f66420bc2
--- /dev/null
+++ b/runtime/src/large_module_gate.h
@@ -0,0 +1,293 @@
1// How many large SPIR-V modules vk_pipeline_check and the runtime let into the driver at once, by a memory budget.
2//
3// Measured on RADV GFX1201 (Mesa 25.3.6) with the Mesa shader cache off: a 5.7 MB translated ray-tracing compute
4// module peaks at 1.96 GB of process memory compiling alone (~330 bytes per SPIR-V byte), a 0.36 MB one at 94 MB.
5// Compiling the large ones strictly one at a time left the other threads idle: 40 modules (27 over 4 MiB) on 6
6// threads took 308 s exclusively and 75 s in parallel, 7.0 GB and 8.7 GB peak. kBytesPerSpirvByte keeps a margin
7// over the measurement. The NVIDIA 621.24 driver (RTX 3080) took 85 to 131 bytes per SPIR-V byte for synthetic compute
8// modules of 128 KiB to 4 MiB (docs/d3d12_vulkan.md, "Large pipelines").
9//
10// The process grew past one module's peak even one at a time because glibc keeps freed memory in per-thread arenas
11// (6 threads: 6.2 GB; MALLOC_ARENA_MAX=1: 2.1 GB, same modules). release_free_memory() hands it back after each
12// large module.
13#pragma once
14
15#include <algorithm>
16#include <condition_variable>
17#include <cstddef>
18#include <cstdint>
19#include <cstdio>
20#include <functional>
21#include <list>
22#include <mutex>
23#include <optional>
24#include <string>
25#include <utility>
26
27#ifdef _WIN32
28#ifndef NOMINMAX
29#define NOMINMAX
30#endif
31#include <windows.h>
32#endif
33#if defined(__GLIBC__)
34#include <malloc.h>
35#endif
36
37namespace leonida {
38
39inline constexpr uint64_t kBytesPerSpirvByte = 512;
40
41inline uint64_t large_module_estimate(uint64_t spirv_bytes) { return spirv_bytes * kBytesPerSpirvByte; }
42
43#if defined(__linux__)
44// The first unsigned number in a file ("max" and unreadable files give no value).
45inline bool read_u64_file(const std::string& path, uint64_t& value) {
46 std::FILE* f = std::fopen(path.c_str(), "r");
47 if (!f) return false;
48 unsigned long long v = 0;
49 const bool ok = std::fscanf(f, "%llu", &v) == 1;
50 std::fclose(f);
51 value = v;
52 return ok;
53}
54
55// The room left under the cgroup v2 memory.max of this process and of every cgroup above it (a container or
56// systemd-run -p MemoryMax=...), or UINT64_MAX when none sets a limit. cgroup_root is a parameter for the tests.
57inline uint64_t cgroup_memory_room(const std::string& self_cgroup_file = "/proc/self/cgroup",
58 const std::string& cgroup_root = "/sys/fs/cgroup") {
59 std::FILE* f = std::fopen(self_cgroup_file.c_str(), "r");
60 if (!f) return UINT64_MAX;
61 char line[4096];
62 std::string rel;
63 while (std::fgets(line, sizeof(line), f)) {
64 std::string l(line);
65 if (l.rfind("0::", 0) == 0) { // the cgroup v2 line
66 rel = l.substr(3);
67 while (!rel.empty() && (rel.back() == '\n' || rel.back() == '\r')) rel.pop_back();
68 break;
69 }
70 }
71 std::fclose(f);
72 uint64_t room = UINT64_MAX;
73 for (std::string dir = rel; !dir.empty();) {
74 // In a cgroup namespace, "/" can be a constrained cgroup mounted as the visible root.
75 const std::string base = dir == "/" ? cgroup_root : cgroup_root + dir;
76 uint64_t max = 0, current = 0;
77 if (read_u64_file(base + "/memory.max", max) && read_u64_file(base + "/memory.current", current))
78 room = std::min(room, max > current ? max - current : 0);
79 const auto slash = dir.find_last_of('/');
80 if (dir == "/" || slash == std::string::npos) break;
81 dir.resize(slash == 0 ? 1 : slash);
82 }
83 return room;
84}
85#endif
86
87// Memory the OS could give this process now, or 0 when it can't tell (then the caller keeps the old exclusive gate).
88inline uint64_t available_memory_bytes() {
89#ifdef _WIN32
90 MEMORYSTATUSEX status{};
91 status.dwLength = sizeof(status);
92 return GlobalMemoryStatusEx(&status) ? uint64_t(status.ullAvailPhys) : 0;
93#elif defined(__linux__)
94 std::FILE* f = std::fopen("/proc/meminfo", "r");
95 if (!f) return 0;
96 char line[256];
97 unsigned long long kb = 0;
98 bool found = false;
99 while (std::fgets(line, sizeof(line), f))
100 if (std::sscanf(line, "MemAvailable: %llu kB", &kb) == 1) { found = true; break; }
101 std::fclose(f);
102 if (!found) return 0;
103 const uint64_t room = cgroup_memory_room();
104 return std::max<uint64_t>(1, std::min(uint64_t(kb) * 1024, room)); // 0 would mean "unknown"
105#else
106 return 0;
107#endif
108}
109
110// What large compiles may use of the free RAM and of the room under the commit limit: three quarters of the smaller. (On
111// Windows an allocation that the limit has no room for fails, whatever RAM is free.)
112inline uint64_t large_compile_share(uint64_t free_ram, uint64_t commit_room) {
113 return std::min(free_ram, commit_room) / 4 * 3;
114}
115
116// The same of the memory that is free at this moment. 0 when it is unknown: then they compile one at a time.
117inline uint64_t large_compile_budget_bytes() {
118#ifdef _WIN32
119 MEMORYSTATUSEX status{};
120 status.dwLength = sizeof(status);
121 if (!GlobalMemoryStatusEx(&status)) return 0;
122 return large_compile_share(status.ullAvailPhys, status.ullAvailPageFile);
123#else
124 return large_compile_share(available_memory_bytes(), UINT64_MAX);
125#endif
126}
127
128// LEONIDA_BIG_COMPILE_BUDGET_MB: a fixed budget in MiB instead of the share of the free memory (0: one at a time). Unset
129// or empty, and text that is not a number: none. `valid` is false for the latter.
130struct LargeCompileBudget {
131 std::optional<uint64_t> fixed{};
132 bool valid = true;
133};
134
135inline LargeCompileBudget large_compile_budget(const char* text) {
136 if (!text || !*text) return {};
137 uint64_t mib = 0;
138 for (const char* c = text; *c; ++c) {
139 if (*c < '0' || *c > '9') return {std::nullopt, false};
140 mib = std::min<uint64_t>(mib * 10 + uint64_t(*c - '0'), UINT64_MAX >> 20);
141 }
142 return {mib << 20, true};
143}
144
145// Return memory freed by the driver's compiler to the OS (glibc keeps it in the arena of the thread that freed it).
146inline void release_free_memory() {
147#if defined(__GLIBC__)
148 malloc_trim(0);
149#endif
150}
151
152// Lets large modules in while their estimates fit the budget and fewer than max_inflight are in. One always gets in
153// when none is, so a module bigger than the whole budget still compiles (alone among the large ones).
154//
155// The second constructor is the runtime's: the budget is read again whenever a place is given or returned, and the
156// modules get in in the order they came, those a submission waits for (demand) before the others (speculative). While the
157// first in line does not fit, the next behind it that does may pass, as long as all that have passed it would fit the
158// budget together with it. So, with the budget as it is, it waits at most for those that were in when it became the first,
159// however many come after it, and one larger than the budget is not passed. A speculative one gets in only while no demand
160// waits and no submission has a Demand, and only within a quarter of the budget, so that a demand finds the rest free. An
161// estimate counts in full until its module leaves, although the driver has allocated part of it by then and the budget is
162// that much smaller: what is in has not taken all it is going to.
163class LargeModuleGate {
164public:
165 enum class Work { demand, speculative };
166
167 LargeModuleGate(uint64_t budget, unsigned max_inflight)
168 : budget_(budget), max_inflight_(max_inflight ? max_inflight : 1) {}
169 explicit LargeModuleGate(std::function<uint64_t()> budget)
170 : budget_(0), max_inflight_(UINT32_MAX), read_budget_(std::move(budget)) {}
171
172 bool admits(uint64_t estimate) const {
173 std::lock_guard<std::mutex> g(mu_);
174 return admits_locked(estimate, budget());
175 }
176 void enter(uint64_t estimate, Work work = Work::demand) {
177 std::unique_lock<std::mutex> l(mu_);
178 if (!read_budget_) {
179 cv_.wait(l, [&] { return admits_locked(estimate, limit_for(work)); });
180 } else {
181 auto& queue = waiting_[work == Work::demand ? 0 : 1];
182 const auto me = queue.insert(queue.end(), Waiter{estimate});
183 cv_.wait(l, [&] {
184 return (work == Work::demand || (waiting_[0].empty() && !demanded_)) && next_locked(work) == &*me;
185 });
186 if (me != queue.begin()) queue.front().passed += estimate;
187 queue.erase(me);
188 }
189 used_ += estimate;
190 ++inflight_;
191 if (!waiting_[0].empty() || !waiting_[1].empty()) cv_.notify_all(); // the next in the queue may fit as well
192 }
193 void leave(uint64_t estimate) {
194 {
195 std::lock_guard<std::mutex> g(mu_);
196 used_ -= estimate;
197 --inflight_;
198 }
199 cv_.notify_all();
200 }
201 unsigned inflight() const {
202 std::lock_guard<std::mutex> g(mu_);
203 return inflight_;
204 }
205 size_t waiting(Work work) const { // in order: the threads in enter(), with a budget that is read
206 std::lock_guard<std::mutex> g(mu_);
207 return waiting_[work == Work::demand ? 0 : 1].size();
208 }
209 uint64_t budget() const { return read_budget_ ? read_budget_() : budget_; }
210 unsigned max_inflight() const { return max_inflight_; }
211
212 // A submission that has large modules to build: until it ends, the places that its modules leave between one and the
213 // next are not taken by speculative ones.
214 class Demand {
215 public:
216 explicit Demand(LargeModuleGate& gate) : gate_(gate) {
217 std::lock_guard<std::mutex> g(gate_.mu_);
218 ++gate_.demanded_;
219 }
220 ~Demand() {
221 {
222 std::lock_guard<std::mutex> g(gate_.mu_);
223 --gate_.demanded_;
224 }
225 gate_.cv_.notify_all();
226 }
227 Demand(const Demand&) = delete;
228 Demand& operator=(const Demand&) = delete;
229
230 private:
231 LargeModuleGate& gate_;
232 };
233
234 // Holds a place from construction until destruction (or release()), then hands freed memory back.
235 class Ticket {
236 public:
237 Ticket() = default;
238 Ticket(LargeModuleGate& gate, uint64_t estimate, Work work = Work::demand) : gate_(&gate), estimate_(estimate) {
239 gate.enter(estimate, work);
240 }
241 Ticket(Ticket&& o) noexcept : gate_(o.gate_), estimate_(o.estimate_) { o.gate_ = nullptr; }
242 Ticket& operator=(Ticket&& o) noexcept {
243 if (this != &o) { release(); gate_ = o.gate_; estimate_ = o.estimate_; o.gate_ = nullptr; }
244 return *this;
245 }
246 Ticket(const Ticket&) = delete;
247 Ticket& operator=(const Ticket&) = delete;
248 ~Ticket() { release(); }
249 void release() {
250 if (!gate_) return;
251 gate_->leave(estimate_);
252 gate_ = nullptr;
253 release_free_memory();
254 }
255 private:
256 LargeModuleGate* gate_ = nullptr;
257 uint64_t estimate_ = 0;
258 };
259
260private:
261 struct Waiter {
262 uint64_t estimate;
263 uint64_t passed = 0; // the estimates of those that have passed it while it was the first in line
264 };
265
266 uint64_t limit_for(Work work) const { return work == Work::demand ? budget() : budget() / 4; }
267 bool admits_locked(uint64_t estimate, uint64_t limit) const {
268 return inflight_ == 0 || (inflight_ < max_inflight_ && used_ + estimate <= limit);
269 }
270 // The one in line that gets in now, if any: the first, or else the first that fits and may pass it.
271 const Waiter* next_locked(Work work) const {
272 const auto& queue = waiting_[work == Work::demand ? 0 : 1];
273 const uint64_t limit = limit_for(work);
274 for (const Waiter& w : queue) {
275 const Waiter& first = queue.front();
276 if (&w != &first && first.passed + w.estimate + first.estimate > limit) continue;
277 if (admits_locked(w.estimate, limit)) return &w;
278 }
279 return nullptr;
280 }
281
282 const uint64_t budget_;
283 const unsigned max_inflight_;
284 const std::function<uint64_t()> read_budget_;
285 mutable std::mutex mu_;
286 std::condition_variable cv_;
287 std::list<Waiter> waiting_[2]; // demand, speculative: one for each thread in enter(), in the order they came
288 uint64_t used_ = 0;
289 unsigned inflight_ = 0;
290 unsigned demanded_ = 0; // the Demands
291};
292
293} // namespace leonida
diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp
index 094aaa321..1b55264fb 100644
--- a/runtime/src/main.cpp
+++ b/runtime/src/main.cpp
@@ -149,6 +149,7 @@ void start_title_peek(std::uint8_t* base) {
149#include "mods.h" 149#include "mods.h"
150#include "pe_loader.h" 150#include "pe_loader.h"
151#include "thread_stacks.h" 151#include "thread_stacks.h"
152#include "dev_overlay.h"
152#include "thread_sampler.h" 153#include "thread_sampler.h"
153#include "title_page_watch.h" 154#include "title_page_watch.h"
154#include "title_geometry_watch.h" 155#include "title_geometry_watch.h"
@@ -541,7 +542,9 @@ int wmain(int argc, wchar_t** argv) {
541 std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str()); 542 std::fprintf(stderr, "error: %s has no entry point\n", main_module.name.c_str());
542 return 1; 543 return 1;
543 } 544 }
544 const std::wstring paths = L"console paths: GAME: -> " + game_dir.native() + L", writes -> " + overlay_dir.native(); 545 const std::filesystem::path scratch_dir = rt::fs::scratch_dir();
546 const std::wstring paths = L"console paths: GAME: -> " + game_dir.native() + L", writes -> " +
547 overlay_dir.native() + L", T: -> " + scratch_dir.native();
545 const HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); 548 const HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
546 DWORD mode; 549 DWORD mode;
547 bool printed = false; 550 bool printed = false;
@@ -554,13 +557,16 @@ int wmain(int argc, wchar_t** argv) {
554 if (!printed) { 557 if (!printed) {
555 const auto game = game_dir.u8string(); 558 const auto game = game_dir.u8string();
556 const auto overlay = overlay_dir.u8string(); 559 const auto overlay = overlay_dir.u8string();
557 std::printf("console paths: GAME: -> %s, writes -> %s\n", 560 const auto scratch = scratch_dir.u8string();
558 reinterpret_cast<const char*>(game.c_str()), reinterpret_cast<const char*>(overlay.c_str())); 561 std::printf("console paths: GAME: -> %s, writes -> %s, T: -> %s\n",
562 reinterpret_cast<const char*>(game.c_str()), reinterpret_cast<const char*>(overlay.c_str()),
563 reinterpret_cast<const char*>(scratch.c_str()));
559 } 564 }
560 std::printf("running %s\n", main_module.name.c_str()); 565 std::printf("running %s\n", main_module.name.c_str());
561 std::fflush(stdout); 566 std::fflush(stdout);
562 keep_title_watchdog_kicked(main_module.base); 567 keep_title_watchdog_kicked(main_module.base);
563 start_title_peek(main_module.base); 568 start_title_peek(main_module.base);
569 leonida::dev_overlay::start(); // LEONIDA_DEV_OVERLAY=1
564 leonida::thread_sampler::start(main_module.base, main_module.size); // LEONIDA_SAMPLE_MS (diagnostic) 570 leonida::thread_sampler::start(main_module.base, main_module.size); // LEONIDA_SAMPLE_MS (diagnostic)
565#ifdef LEONIDA_VULKAN_DEVICE 571#ifdef LEONIDA_VULKAN_DEVICE
566 SetConsoleCtrlHandler(&stop_compiles_on_console_exit, TRUE); 572 SetConsoleCtrlHandler(&stop_compiles_on_console_exit, TRUE);
diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp
index 3558cffb5..fc73f37f5 100644
--- a/runtime/src/pe_loader.cpp
+++ b/runtime/src/pe_loader.cpp
@@ -1721,10 +1721,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string&
1721 if (!m->base) 1721 if (!m->base)
1722 m->base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage, 1722 m->base = static_cast<uint8_t*>(VirtualAlloc(reinterpret_cast<void*>(oh.ImageBase), oh.SizeOfImage,
1723 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); 1723 MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
1724 if (!m->base) { 1724 if (!m->base) { // whether the image may move is decided at the relocation step below
1725 const auto relocs = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC);
1726 if (!relocs.Size)
1727 throw std::runtime_error(m->name + ": preferred base is taken and the image has no relocations");
1728 m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); 1725 m->base = static_cast<uint8_t*>(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
1729 if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed"); 1726 if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed");
1730 } 1727 }
@@ -1749,10 +1746,19 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string&
1749 } 1746 }
1750 1747
1751 int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase); 1748 int64_t delta = reinterpret_cast<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase);
1752 if (delta) { 1749 // A moved image with a relocation table is fixed up, whatever IMAGE_FILE_RELOCS_STRIPPED says. Without a table,
1753 m->relocated = true; 1750 // the flag refuses the move; with the flag clear the image is moved and nothing is fixed up, so it is trusted to
1754 const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC); 1751 // hold no absolute addresses. The Windows 11 loader does all three (runtime/README.md); that move is logged so
1755 if (!dir.Size) throw std::runtime_error(m->name + ": the image has no relocations and isn't at its base"); 1752 // it shows in traces. base_reservation::needed still keeps the main image's range free when it has no
1753 // relocation directory, so a main image is moved this way only where the range could not be had.
1754 const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_BASERELOC);
1755 if (delta) m->relocated = true;
1756 if (delta && !dir.Size && (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED))
1757 throw std::runtime_error(m->name + ": preferred base is taken and the image's relocations are stripped");
1758 if (delta && !dir.Size)
1759 std::fprintf(stderr, "[rt] loader: %s: preferred base %#llx is taken, moved to %p with no relocations\n",
1760 m->name.c_str(), static_cast<unsigned long long>(oh.ImageBase), static_cast<void*>(m->base));
1761 if (delta && dir.Size) {
1756 require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table"); 1762 require_range(m->name, dir.VirtualAddress, dir.Size, m->size, "the relocation table");
1757 auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress); 1763 auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress);
1758 auto* end = reinterpret_cast<uint8_t*>(block) + dir.Size; 1764 auto* end = reinterpret_cast<uint8_t*>(block) + dir.Size;
@@ -2123,7 +2129,10 @@ void Loader::bind_imports(Module& m) {
2123 const uint64_t headers_end = nt->OptionalHeader.SizeOfHeaders; 2129 const uint64_t headers_end = nt->OptionalHeader.SizeOfHeaders;
2124 2130
2125 // Thunk tables have no length field: they end at a zero entry, so each step is checked against the image. 2131 // Thunk tables have no length field: they end at a zero entry, so each step is checked against the image.
2126 auto bind_thunks = [&](const std::string& dll, uint64_t lookup_rva, uint64_t iat_rva) { 2132 // `delayed`: a delay import that binds to an unimplemented thunk is traced. Windows' delay-load helper would raise
2133 // 0xC06D007E (module) or 0xC06D007F (procedure) at its first call, which a title can catch for a fallback; the
2134 // thunk returns 0 instead, so the trace names each such import before any image code runs.
2135 auto bind_thunks = [&](const std::string& dll, uint64_t lookup_rva, uint64_t iat_rva, bool delayed) {
2127 for (;; lookup_rva += sizeof(IMAGE_THUNK_DATA64), iat_rva += sizeof(IMAGE_THUNK_DATA64)) { 2136 for (;; lookup_rva += sizeof(IMAGE_THUNK_DATA64), iat_rva += sizeof(IMAGE_THUNK_DATA64)) {
2128 require_range(m.name, lookup_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import lookup table"); 2137 require_range(m.name, lookup_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import lookup table");
2129 require_range(m.name, iat_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import address table"); 2138 require_range(m.name, iat_rva, sizeof(IMAGE_THUNK_DATA64), m.size, "an import address table");
@@ -2141,6 +2150,10 @@ void Loader::bind_imports(Module& m) {
2141 throw std::runtime_error(m.name + ": an import address table lands in the headers"); 2150 throw std::runtime_error(m.name + ": an import address table lands in the headers");
2142 at<IMAGE_THUNK_DATA64>(m.base, static_cast<uint32_t>(iat_rva))->u1.Function = 2151 at<IMAGE_THUNK_DATA64>(m.base, static_cast<uint32_t>(iat_rva))->u1.Function =
2143 reinterpret_cast<uint64_t>(resolve(m, dll, name, ord, by_ord)); 2152 reinterpret_cast<uint64_t>(resolve(m, dll, name, ord, by_ord));
2153 if (delayed && startup_trace::enabled() && m.imports.back().binding == Binding::Unimplemented)
2154 startup_trace::event("delay_import_unimplemented",
2155 "\"module\":" + startup_trace::quote(m.name) + ",\"import\":" +
2156 startup_trace::quote(dll + "!" + m.imports.back().name));
2144 } 2157 }
2145 }; 2158 };
2146 2159
@@ -2153,7 +2166,7 @@ void Loader::bind_imports(Module& m) {
2153 if (!d->Name) break; 2166 if (!d->Name) break;
2154 std::string dll = read_string(m.name, m.base, m.size, d->Name, "an imported DLL name"); 2167 std::string dll = read_string(m.name, m.base, m.size, d->Name, "an imported DLL name");
2155 uint32_t lookup = d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk; 2168 uint32_t lookup = d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk;
2156 bind_thunks(dll, lookup, d->FirstThunk); 2169 bind_thunks(dll, lookup, d->FirstThunk, false);
2157 } 2170 }
2158 } 2171 }
2159 // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. 2172 // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run.
@@ -2176,7 +2189,7 @@ void Loader::bind_imports(Module& m) {
2176 // thunk addresses as name RVAs. 2189 // thunk addresses as name RVAs.
2177 if (!d->ImportNameTableRVA) 2190 if (!d->ImportNameTableRVA)
2178 throw std::runtime_error(m.name + ": a delay-import descriptor has no name table"); 2191 throw std::runtime_error(m.name + ": a delay-import descriptor has no name table");
2179 bind_thunks(dll, d->ImportNameTableRVA, d->ImportAddressTableRVA); 2192 bind_thunks(dll, d->ImportNameTableRVA, d->ImportAddressTableRVA, true);
2180 } 2193 }
2181 } 2194 }
2182} 2195}
diff --git a/runtime/src/root_signature.cpp b/runtime/src/root_signature.cpp
index 10dd1e02c..41d3f6c5a 100644
--- a/runtime/src/root_signature.cpp
+++ b/runtime/src/root_signature.cpp
@@ -17,10 +17,8 @@ PackResult pack(const RootSignature& sig) {
17 out.error = "unknown root parameter type"; 17 out.error = "unknown root parameter type";
18 return out; 18 return out;
19 } 19 }
20 if (p.type == ParamType::Constants && p.num_values == 0) { 20 // A constant parameter of 0 values is valid (the host serializer warns, CreateRootSignature answers S_OK):
21 out.error = "root constant parameter needs at least 1 dword"; 21 // it takes no dwords, so it gets no provenance entry and the parameters after it pack as if it were absent.
22 return out;
23 }
24 const uint32_t dwords = p.type == ParamType::Table ? 2 22 const uint32_t dwords = p.type == ParamType::Table ? 2
25 : p.type == ParamType::Descriptor ? 2 23 : p.type == ParamType::Descriptor ? 2
26 : p.num_values; 24 : p.num_values;
@@ -71,15 +69,12 @@ StagePackResult pack_stage(const RootSignature& sig, Stage stage) {
71 out.error = "unknown root parameter type"; 69 out.error = "unknown root parameter type";
72 return out; 70 return out;
73 } 71 }
74 if (p.type == ParamType::Constants && p.num_values == 0) {
75 out.error = "root constant parameter needs at least 1 dword";
76 return out;
77 }
78 cost += param_cost(p.type, p.num_values); 72 cost += param_cost(p.type, p.num_values);
79 if (cost > kMaxD3d12Cost) { 73 if (cost > kMaxD3d12Cost) {
80 out.error = "root signature exceeds the 64-dword D3D12 cost limit"; 74 out.error = "root signature exceeds the 64-dword D3D12 cost limit";
81 return out; 75 return out;
82 } 76 }
77 // 0 for a constant parameter of 0 values, which then shares its first SGPR with the next parameter.
83 const uint64_t dwords = stage_dwords(p.type, p.num_values); 78 const uint64_t dwords = stage_dwords(p.type, p.num_values);
84 if (!spilling && next + dwords <= kMaxUserSgprs) { 79 if (!spilling && next + dwords <= kMaxUserSgprs) {
85 first.push_back(static_cast<uint32_t>(next)); 80 first.push_back(static_cast<uint32_t>(next));
diff --git a/runtime/src/root_signature.h b/runtime/src/root_signature.h
index e7976fc73..559f4c54d 100644
--- a/runtime/src/root_signature.h
+++ b/runtime/src/root_signature.h
@@ -114,7 +114,8 @@ constexpr uint32_t kMaxD3d12Cost = 64;
114// Packs root parameters in order. Static samplers consume no dwords. 114// Packs root parameters in order. Static samplers consume no dwords.
115// Fails (ok == false) when the signature needs more than 32 user SGPRs 115// Fails (ok == false) when the signature needs more than 32 user SGPRs
116// (spill layout unknown: refuse, do not guess) or exceeds the 64-dword 116// (spill layout unknown: refuse, do not guess) or exceeds the 64-dword
117// D3D12 cost limit, or holds more than 64 root parameters. 117// D3D12 cost limit, or holds more than 64 root parameters. A constant
118// parameter of 0 values takes no dwords, as on the host.
118[[nodiscard]] PackResult pack(const RootSignature& sig); 119[[nodiscard]] PackResult pack(const RootSignature& sig);
119 120
120// The console layout of root arguments in a stage's user SGPRs (docs/d3d12_vulkan.md section 3.5, D3D-448). 121// The console layout of root arguments in a stage's user SGPRs (docs/d3d12_vulkan.md section 3.5, D3D-448).
@@ -183,8 +184,9 @@ struct StagePackResult {
183}; 184};
184 185
185// Lays the parameters out for `stage` in the console layout. Fails like pack() on more than 64 parameters, an 186// Lays the parameters out for `stage` in the console layout. Fails like pack() on more than 64 parameters, an
186// unknown parameter type, a constant parameter of 0 values, or the 64-dword cost limit. Compute spills any trailing 187// unknown parameter type or the 64-dword cost limit. Compute spills any trailing parameters from the first one
187// parameters from the first one that does not fit whole into spill_dword; non-compute stages refuse any spill. 188// that does not fit whole into spill_dword; non-compute stages refuse any spill. A constant parameter of 0 values
189// takes no SGPRs and no spill dwords.
188[[nodiscard]] StagePackResult pack_stage(const RootSignature& sig, Stage stage); 190[[nodiscard]] StagePackResult pack_stage(const RootSignature& sig, Stage stage);
189 191
190// D3D12 cost of one parameter against the 64-dword limit. 192// D3D12 cost of one parameter against the 64-dword limit.
diff --git a/runtime/src/submit_phases.h b/runtime/src/submit_phases.h
index 84ea77b02..230240b57 100644
--- a/runtime/src/submit_phases.h
+++ b/runtime/src/submit_phases.h
@@ -40,6 +40,10 @@ struct Totals {
40 std::atomic<std::int64_t> last_log{0}; 40 std::atomic<std::int64_t> last_log{0};
41 std::atomic<std::uint64_t> presents{0}; // frames the presenter showed (VulkanPresenter), since the last line 41 std::atomic<std::uint64_t> presents{0}; // frames the presenter showed (VulkanPresenter), since the last line
42 std::atomic<std::uint64_t> present_serial{0}; // the same, never reset (LEONIDA_REFRESH_PER_FRAME) 42 std::atomic<std::uint64_t> present_serial{0}; // the same, never reset (LEONIDA_REFRESH_PER_FRAME)
43 // Threads whose innermost Scope is this phase now, and when the first of them entered it (steady_clock). Counted
44 // per phase, since queues submit from several threads: one value would go stale when their scopes overlap.
45 std::atomic<unsigned> active[kCount]{};
46 std::atomic<std::int64_t> active_since[kCount]{};
43 std::atomic<std::uint32_t> thread{0}; // the thread of the last submission (the thread sampler reports it apart) 47 std::atomic<std::uint32_t> thread{0}; // the thread of the last submission (the thread sampler reports it apart)
44}; 48};
45inline Totals& totals() { 49inline Totals& totals() {
@@ -86,12 +90,48 @@ inline void add(Phase p, std::uint64_t ns) {
86struct Scope { 90struct Scope {
87 Phase phase; 91 Phase phase;
88 std::int64_t start = now_ns(); 92 std::int64_t start = now_ns();
89 explicit Scope(Phase p) : phase(p) {} 93 int outer; // the phase of this thread's Scope around this one, -1 for none
90 ~Scope() { add(phase, std::uint64_t(now_ns() - start)); } 94 explicit Scope(Phase p) : phase(p), outer(innermost()) {
95 if (outer >= 0) leave(outer);
96 enter(int(p), start);
97 innermost() = int(p);
98 }
99 ~Scope() {
100 const std::int64_t end = now_ns();
101 add(phase, std::uint64_t(end - start));
102 leave(int(phase));
103 if (outer >= 0) enter(outer, end);
104 innermost() = outer;
105 }
106 static int& innermost() {
107 thread_local int phase_of_this_thread = -1;
108 return phase_of_this_thread;
109 }
110 static void enter(int p, std::int64_t at) {
111 Totals& t = totals();
112 if (t.active[p].fetch_add(1, std::memory_order_relaxed) == 0) t.active_since[p].store(at, std::memory_order_relaxed);
113 }
114 static void leave(int p) { totals().active[p].fetch_sub(1, std::memory_order_relaxed); }
91 Scope(const Scope&) = delete; 115 Scope(const Scope&) = delete;
92 Scope& operator=(const Scope&) = delete; 116 Scope& operator=(const Scope&) = delete;
93}; 117};
94 118
119// The phase that some thread has been in longest, -1 when none is in one.
120struct Running {
121 int phase = -1;
122 std::int64_t since = 0;
123};
124inline Running running() {
125 Totals& t = totals();
126 Running r;
127 for (unsigned p = 0; p < kCount; ++p) {
128 if (!t.active[p].load(std::memory_order_relaxed)) continue;
129 const std::int64_t since = t.active_since[p].load(std::memory_order_relaxed);
130 if (r.phase < 0 || since < r.since) r = {int(p), since};
131 }
132 return r;
133}
134
95// After each submission: counts it, and prints the line when the period has passed. One thread wins the line. 135// After each submission: counts it, and prints the line when the period has passed. One thread wins the line.
96inline void submitted() { 136inline void submitted() {
97 Totals& t = totals(); 137 Totals& t = totals();
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index d0a863421..68ab9b194 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -130,7 +130,8 @@ struct VulkanDeviceFunctions {
130 X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) X(vkMergePipelineCaches) \ 130 X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) X(vkMergePipelineCaches) \
131 X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \ 131 X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \
132 X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ 132 X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \
133 X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) 133 X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) \
134 X(vkCmdBeginQueryIndexedEXT) X(vkCmdEndQueryIndexedEXT)
134#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr; 135#define LEONIDA_VK_MEMBER(name) PFN_##name name = nullptr;
135 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER) 136 LEONIDA_VK_DEVICE_FUNCTIONS(LEONIDA_VK_MEMBER)
136#undef LEONIDA_VK_MEMBER 137#undef LEONIDA_VK_MEMBER
@@ -165,6 +166,9 @@ struct VulkanDeviceFunctions {
165 return vkCmdBeginRendering && vkCmdEndRendering && vkCmdBindVertexBuffers2 && vkCmdSetPrimitiveTopology && 166 return vkCmdBeginRendering && vkCmdEndRendering && vkCmdBindVertexBuffers2 && vkCmdSetPrimitiveTopology &&
166 vkCmdSetPrimitiveRestartEnable; 167 vkCmdSetPrimitiveRestartEnable;
167 } 168 }
169 // VK_EXT_transform_feedback is enabled on the device: the indexed-query entry points are loaded, so an
170 // SO_STATISTICS heap can be a real transform-feedback pool (D3D-302).
171 bool transform_feedback = false;
168}; 172};
169 173
170// Both kinds of compute resolve use the same storage buffer, descriptor set and pipeline layout. 174// Both kinds of compute resolve use the same storage buffer, descriptor set and pipeline layout.
@@ -1090,6 +1094,8 @@ public:
1090 GraphicsIndirectCapabilities indirect = {}) 1094 GraphicsIndirectCapabilities indirect = {})
1091 : device_(device), tracker_(separate_depth_stencil_layouts), ray_tracing_(ray_tracing) { 1095 : device_(device), tracker_(separate_depth_stencil_layouts), ray_tracing_(ray_tracing) {
1092 loaded_ = vk.load(get, device); 1096 loaded_ = vk.load(get, device);
1097 // VK_EXT_transform_feedback: enabled on the device when its indexed-query entry points resolved (D3D-302).
1098 vk.transform_feedback = vk.vkCmdBeginQueryIndexedEXT && vk.vkCmdEndQueryIndexedEXT;
1093 if (loaded_ && gpu_labels_.initialize(device, get)) { 1099 if (loaded_ && gpu_labels_.initialize(device, get)) {
1094 replay_.gpu_label = [this](VkCommandBuffer cb, const label::Write& write) { gpu_labels_.record(cb, write); }; 1100 replay_.gpu_label = [this](VkCommandBuffer cb, const label::Write& write) { gpu_labels_.record(cb, write); };
1095 } 1101 }
@@ -1125,6 +1131,11 @@ public:
1125 replay_.reset_query_pool = vk.vkCmdResetQueryPool; 1131 replay_.reset_query_pool = vk.vkCmdResetQueryPool;
1126 replay_.begin_query = vk.vkCmdBeginQuery; 1132 replay_.begin_query = vk.vkCmdBeginQuery;
1127 replay_.end_query = vk.vkCmdEndQuery; 1133 replay_.end_query = vk.vkCmdEndQuery;
1134 // VK_EXT_transform_feedback (D3D-302), loaded when the device enabled it: indexed SO_STATISTICS queries.
1135 if (vk.transform_feedback) {
1136 replay_.begin_query_indexed = vk.vkCmdBeginQueryIndexedEXT;
1137 replay_.end_query_indexed = vk.vkCmdEndQueryIndexedEXT;
1138 }
1128 replay_.write_timestamp = vk.vkCmdWriteTimestamp; 1139 replay_.write_timestamp = vk.vkCmdWriteTimestamp;
1129 replay_.copy_query_pool_results = vk.vkCmdCopyQueryPoolResults; 1140 replay_.copy_query_pool_results = vk.vkCmdCopyQueryPoolResults;
1130 replay_.bind_pipeline = vk.vkCmdBindPipeline; 1141 replay_.bind_pipeline = vk.vkCmdBindPipeline;
@@ -1572,6 +1583,14 @@ public:
1572 std::unique_lock lock(pipeline_mutex_); 1583 std::unique_lock lock(pipeline_mutex_);
1573 pipeline_workers_.swap(workers); 1584 pipeline_workers_.swap(workers);
1574 } 1585 }
1586 // For the large pipelines of a submission: the memory they may use while they compile together
1587 // (PipelineCompiles::build), and what is kept while they do (LargeModuleGate::Demand). None (the default): they compile
1588 // one after another.
1589 void set_large_compiles(std::function<std::uint64_t()> budget, std::function<std::shared_ptr<void>()> demand) {
1590 std::unique_lock lock(pipeline_mutex_);
1591 large_compile_budget_ = std::move(budget);
1592 large_compile_demand_ = std::move(demand);
1593 }
1575 PipelineWorkers::Stats pipeline_worker_stats() { 1594 PipelineWorkers::Stats pipeline_worker_stats() {
1576 std::shared_lock lock(pipeline_mutex_); 1595 std::shared_lock lock(pipeline_mutex_);
1577 return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{}; 1596 return pipeline_workers_ ? pipeline_workers_->stats() : PipelineWorkers::Stats{};
@@ -2189,6 +2208,8 @@ private:
2189 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_; 2208 std::unordered_map<std::uintptr_t, ComputePipeline> pipelines_;
2190 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_; 2209 std::unordered_map<std::uintptr_t, GraphicsPipeline> graphics_pipelines_;
2191 std::unique_ptr<PipelineWorkers> pipeline_workers_; 2210 std::unique_ptr<PipelineWorkers> pipeline_workers_;
2211 std::function<std::uint64_t()> large_compile_budget_;
2212 std::function<std::shared_ptr<void>()> large_compile_demand_;
2192 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_; 2213 std::unordered_map<std::uint64_t, VkAccelerationStructureKHR> acceleration_structures_;
2193 LayoutTracker tracker_; 2214 LayoutTracker tracker_;
2194 std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only 2215 std::mutex storage_mutex_; // a leaf lock: guards storage_pending_ and zero_pending_ only
@@ -3168,10 +3189,13 @@ private:
3168 recycle_khr_as_queries(khr_guard.as_queries); 3189 recycle_khr_as_queries(khr_guard.as_queries);
3169 geometry.clear(); 3190 geometry.clear();
3170 3191
3192 std::shared_ptr<void> demand;
3193 if (context_.large_compile_demand_ && compiles.any_large()) demand = context_.large_compile_demand_();
3171 if (context_.pipeline_workers_) 3194 if (context_.pipeline_workers_)
3172 compiles.build(run_compiles); 3195 compiles.build(run_compiles, context_.large_compile_budget_);
3173 else 3196 else
3174 compiles.build_serial(); 3197 compiles.build_serial();
3198 demand.reset();
3175 const ReplayResult compile_result = check_compiled_pipelines(compiles, prepare_result); 3199 const ReplayResult compile_result = check_compiled_pipelines(compiles, prepare_result);
3176 if (compile_result != ReplayResult::success) return compile_result; 3200 if (compile_result != ReplayResult::success) return compile_result;
3177 prior_compiles = std::move(compiles); 3201 prior_compiles = std::move(compiles);
@@ -3181,7 +3205,7 @@ private:
3181 const PipelineCompiles* prior = has_prior_compiles ? &prior_compiles : nullptr; 3205 const PipelineCompiles* prior = has_prior_compiles ? &prior_compiles : nullptr;
3182 prepare_result = context_.pipeline_workers_ 3206 prepare_result = context_.pipeline_workers_
3183 ? build_pipelines(compiles, std::span(prepared).first(lists.size()), prepare_result, 3207 ? build_pipelines(compiles, std::span(prepared).first(lists.size()), prepare_result,
3184 run_compiles, prior) 3208 run_compiles, context_.large_compile_budget_, prior)
3185 : build_pipelines_serial(compiles, std::span(prepared).first(lists.size()), 3209 : build_pipelines_serial(compiles, std::span(prepared).first(lists.size()),
3186 prepare_result, prior); 3210 prepare_result, prior);
3187 replay.compiles = nullptr; 3211 replay.compiles = nullptr;
diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h
index b735fbaa6..d84f26ccf 100644
--- a/runtime/src/vulkan_replay.h
+++ b/runtime/src/vulkan_replay.h
@@ -60,6 +60,7 @@
60#include <limits> 60#include <limits>
61#include <map> 61#include <map>
62#include <memory> 62#include <memory>
63#include <mutex>
63#include <optional> 64#include <optional>
64#include <type_traits> 65#include <type_traits>
65#include <unordered_map> 66#include <unordered_map>
@@ -843,14 +844,19 @@ struct OcclusionResult {
843// A D3D12 query heap on Vulkan. The host tracks which queries hold a result. A resolve of a query that 844// A D3D12 query heap on Vulkan. The host tracks which queries hold a result. A resolve of a query that
844// was never ended writes zeros instead of waiting on it. 845// was never ended writes zeros instead of waiting on it.
845struct QueryPool { 846struct QueryPool {
846 // Null for a stream-output statistics heap: the layer has no stream output (PSOs with StreamOutput entries are 847 // Null for a stream-output statistics heap on a device without VK_EXT_transform_feedback (D3D-302): every
847 // refused), so every SO_STATISTICS_STREAMn query counts 0 written and 0 needed, and a resolve fills zeros. 848 // SO_STATISTICS_STREAMn query then counts 0 written and 0 needed, and a resolve fills zeros. With the feature
849 // it is a VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT pool, begun/ended indexed on the stream.
848 VkQueryPool pool = VK_NULL_HANDLE; 850 VkQueryPool pool = VK_NULL_HANDLE;
849 std::uint32_t heap_type = 0; // d3d12_query_heap 851 std::uint32_t heap_type = 0; // d3d12_query_heap
850 std::uint32_t count = 0; 852 std::uint32_t count = 0;
851 bool precise = false; // occlusionQueryPrecise: D3D12_QUERY_TYPE_OCCLUSION counts exact samples 853 bool precise = false; // occlusionQueryPrecise: D3D12_QUERY_TYPE_OCCLUSION counts exact samples
852 std::vector<bool> ended; 854 std::vector<bool> ended;
853 std::unordered_map<std::uint32_t, OcclusionResult> occlusion; 855 std::unordered_map<std::uint32_t, OcclusionResult> occlusion;
856 // Transform-feedback streams the pool can query (D3D-302): 0 when it has no pool, otherwise the device's
857 // maxTransformFeedbackStreams clamped to D3D12's four. SO_STATISTICS_STREAMn with n at or above this runs nothing
858 // and resolves zero.
859 std::uint32_t streams = 0;
854}; 860};
855 861
856// A compute pipeline as replay needs it. code_base is the console VA of the shader's FSSM blob (push-constant 862// A compute pipeline as replay needs it. code_base is the console VA of the shader's FSSM blob (push-constant
@@ -868,8 +874,9 @@ struct ComputePipeline {
868 // What `build` would return when it is built already and nobody is building it, else null; builds nothing. Null: a 874 // What `build` would return when it is built already and nobody is building it, else null; builds nothing. Null: a
869 // first use is always built where prepare() meets it. Not used with async_build. See PipelineCompiles. 875 // first use is always built where prepare() meets it. Not used with async_build. See PipelineCompiles.
870 VkPipeline (*built)(void*) = nullptr; 876 VkPipeline (*built)(void*) = nullptr;
871 bool large = false; // compiled one after another with the other large ones (PipelineCompiles) 877 bool large = false; // PipelineCompiles limits how many of these compile at once
872 bool skipped = false; // never built on request (LEONIDA_SKIP_COMPUTE): its dispatches are dropped 878 bool skipped = false; // never built on request (LEONIDA_SKIP_COMPUTE): its dispatches are dropped
879 std::uint64_t estimate = 0; // large: the bytes of memory its compile is expected to take
873}; 880};
874 881
875// A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it 882// A graphics pipeline as replay needs it: the formats its attachments must have and which vertex-input slots it
@@ -903,6 +910,7 @@ struct GraphicsPipeline {
903 std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count 910 std::uint32_t samples = 1; // rasterizationSamples; every bound attachment must have this count
904 bool async_build = false; 911 bool async_build = false;
905 bool nonunit_vertex_divisor = false; // an actual instance divisor > 1, not a zero-stride emulation 912 bool nonunit_vertex_divisor = false; // an actual instance divisor > 1, not a zero-stride emulation
913 std::uint64_t estimate = 0; // as ComputePipeline::estimate
906}; 914};
907 915
908// The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base. 916// The 144-byte push-constant block every translated shader declares: s0..s31, heap base, code base.
@@ -1000,7 +1008,7 @@ public:
1000 User user; 1008 User user;
1001 }; 1009 };
1002 // A compile takes the driver some hundred bytes of memory for each byte of SPIR-V (docs/pipeline_check.md): graphics 1010 // A compile takes the driver some hundred bytes of memory for each byte of SPIR-V (docs/pipeline_check.md): graphics
1003 // pipelines of this much or more are `large`. 1011 // pipelines of this much or more are `large`. For compute pipelines the D3D12 layer decides.
1004 static constexpr std::uint64_t large_spirv_bytes = 1u << 20; 1012 static constexpr std::uint64_t large_spirv_bytes = 1u << 20;
1005 1013
1006 Ticket add(const GraphicsPipeline& pipeline, std::uint32_t flags) { 1014 Ticket add(const GraphicsPipeline& pipeline, std::uint32_t flags) {
@@ -1009,6 +1017,9 @@ public:
1009 Ticket add(const ComputePipeline& pipeline, User user) { return add({nullptr, &pipeline, 0}, user); } 1017 Ticket add(const ComputePipeline& pipeline, User user) { return add({nullptr, &pipeline, 0}, user); }
1010 1018
1011 bool empty() const { return jobs_.empty(); } 1019 bool empty() const { return jobs_.empty(); }
1020 bool any_large() const {
1021 return std::any_of(jobs_.begin(), jobs_.end(), [](const Job& job) { return is_large(job); });
1022 }
1012 std::size_t size() const { return jobs_.size(); } 1023 std::size_t size() const { return jobs_.size(); }
1013 VkPipeline built(Ticket ticket) const { return jobs_[ticket - 1].built; } 1024 VkPipeline built(Ticket ticket) const { return jobs_[ticket - 1].built; }
1014 const std::vector<Use>& uses() const { return uses_; } // in the order of the commands 1025 const std::vector<Use>& uses() const { return uses_; } // in the order of the commands
@@ -1030,26 +1041,64 @@ public:
1030 return lookup(job.graphics, job.compute, job.flags, unused); 1041 return lookup(job.graphics, job.compute, job.flags, unused);
1031 } 1042 }
1032 1043
1033 // Compiles all of them through run(count, job) (PipelineWorkers::run): the large ones one after another, as without 1044 // Compiles all of them through run(count, job) (PipelineWorkers::run). The large ones share budget() bytes of memory:
1034 // workers, beside the others. Jobs already attempted in `prior` reuse that outcome without re-invoking build(). 1045 // the largest first, as many at once as their estimates fit, one at least; while the next one does not fit, the
1046 // others are compiled first. No budget, or 0: the large ones one after another, as without workers, beside the others.
1035 template<typename Run> 1047 template<typename Run>
1036 void build(Run&& run, const PipelineCompiles* prior = nullptr) { 1048 void build(Run&& run, const std::function<std::uint64_t()>& read_budget = {},
1049 const PipelineCompiles* prior = nullptr) {
1037 std::vector<std::size_t> single, large; 1050 std::vector<std::size_t> single, large;
1038 for (std::size_t i = 0; i < jobs_.size(); ++i) { 1051 for (std::size_t i = 0; i < jobs_.size(); ++i) {
1039 if (prior && prior->lookup(jobs_[i].graphics, jobs_[i].compute, jobs_[i].flags, jobs_[i].built)) continue; 1052 if (prior && prior->lookup(jobs_[i].graphics, jobs_[i].compute, jobs_[i].flags, jobs_[i].built)) continue;
1040 (is_large(jobs_[i]) ? large : single).push_back(i); 1053 (is_large(jobs_[i]) ? large : single).push_back(i);
1041 } 1054 }
1042 if (single.empty() && large.empty()) return; 1055 if (single.empty() && large.empty()) return;
1056 // The first jobs of the run are lanes, which take large ones until none is left: no more of them than there are
1057 // large ones that fit the budget together (the smallest), so that no thread waits here for room in vain.
1058 std::size_t lanes = large.empty() ? 0 : 1;
1059 const std::uint64_t budget = lanes && read_budget ? read_budget() : 0;
1060 if (budget) {
1061 std::stable_sort(large.begin(), large.end(), [this](std::size_t a, std::size_t b) {
1062 return estimate(jobs_[a]) > estimate(jobs_[b]);
1063 });
1064 std::uint64_t sum = estimate(jobs_[large.back()]);
1065 while (lanes < large.size() && (sum += estimate(jobs_[large[large.size() - 1 - lanes]])) <= budget) ++lanes;
1066 }
1043 const auto compile = [this](std::size_t i) { 1067 const auto compile = [this](std::size_t i) {
1044 Job& job = jobs_[i]; 1068 Job& job = jobs_[i];
1045 job.built = job.graphics ? job.graphics->variant(job.flags) : job.compute->build(job.compute->build_context); 1069 job.built = job.graphics ? job.graphics->variant(job.flags) : job.compute->build(job.compute->build_context);
1046 }; 1070 };
1047 const std::size_t chain = large.empty() ? 0 : 1; // the large ones are one unit, the first 1071 std::mutex mutex; // guards the four below
1048 run(chain + single.size(), [&](std::size_t i) { 1072 std::size_t next_single = 0, next_large = 0, compiling = 0;
1049 if (i >= chain) 1073 std::uint64_t reserved = 0; // the estimates of the large ones compiling
1050 compile(single[i - chain]); 1074 run(lanes + single.size(), [&](std::size_t i) {
1051 else 1075 std::unique_lock lock(mutex);
1052 for (const std::size_t each : large) compile(each); 1076 if (i >= lanes) {
1077 if (next_single == single.size()) return; // a lane has taken it
1078 const std::size_t index = single[next_single++];
1079 lock.unlock();
1080 compile(index);
1081 return;
1082 }
1083 while (next_large < large.size()) {
1084 const std::uint64_t need = estimate(jobs_[large[next_large]]);
1085 const bool fits = !compiling || reserved + need <= budget;
1086 if (!fits && next_single < single.size()) {
1087 const std::size_t index = single[next_single++];
1088 lock.unlock();
1089 compile(index);
1090 lock.lock();
1091 continue;
1092 }
1093 const std::size_t index = large[next_large++];
1094 ++compiling;
1095 reserved += need;
1096 lock.unlock();
1097 compile(index);
1098 lock.lock();
1099 --compiling;
1100 reserved -= need;
1101 }
1053 }); 1102 });
1054 } 1103 }
1055 1104
@@ -1081,6 +1130,9 @@ private:
1081 VkPipeline built = VK_NULL_HANDLE; 1130 VkPipeline built = VK_NULL_HANDLE;
1082 }; 1131 };
1083 static bool is_large(const Job& job) { return job.graphics ? job.graphics->large : job.compute->large; } 1132 static bool is_large(const Job& job) { return job.graphics ? job.graphics->large : job.compute->large; }
1133 static std::uint64_t estimate(const Job& job) {
1134 return job.graphics ? job.graphics->estimate : job.compute->estimate;
1135 }
1084 Ticket add(const Job& job, User user) { 1136 Ticket add(const Job& job, User user) {
1085 const void* const pipeline = job.graphics ? static_cast<const void*>(job.graphics) : job.compute; 1137 const void* const pipeline = job.graphics ? static_cast<const void*>(job.graphics) : job.compute;
1086 const auto [it, added] = tickets_.try_emplace({pipeline, job.flags}, Ticket(jobs_.size() + 1)); 1138 const auto [it, added] = tickets_.try_emplace({pipeline, job.flags}, Ticket(jobs_.size() + 1));
@@ -1128,6 +1180,10 @@ struct ReplayFunctions {
1128 PFN_vkCmdResetQueryPool reset_query_pool = nullptr; // queries, with fill_buffer for unavailable results 1180 PFN_vkCmdResetQueryPool reset_query_pool = nullptr; // queries, with fill_buffer for unavailable results
1129 PFN_vkCmdBeginQuery begin_query = nullptr; 1181 PFN_vkCmdBeginQuery begin_query = nullptr;
1130 PFN_vkCmdEndQuery end_query = nullptr; 1182 PFN_vkCmdEndQuery end_query = nullptr;
1183 // VK_EXT_transform_feedback (D3D-302): SO_STATISTICS queries begin/end indexed on a stream. Null when the device
1184 // lacks the feature.
1185 PFN_vkCmdBeginQueryIndexedEXT begin_query_indexed = nullptr;
1186 PFN_vkCmdEndQueryIndexedEXT end_query_indexed = nullptr;
1131 PFN_vkCmdWriteTimestamp write_timestamp = nullptr; 1187 PFN_vkCmdWriteTimestamp write_timestamp = nullptr;
1132 PFN_vkCmdCopyQueryPoolResults copy_query_pool_results = nullptr; 1188 PFN_vkCmdCopyQueryPoolResults copy_query_pool_results = nullptr;
1133 // Set only where a copy of timestamp results is not ordered after the timestamps written before it (MoltenVK on 1189 // Set only where a copy of timestamp results is not ordered after the timestamps written before it (MoltenVK on
@@ -3014,9 +3070,10 @@ inline ReplayResult finish_compiled_pipelines(const PipelineCompiles& compiles,
3014// have returned had they built each pipeline themselves. 3070// have returned had they built each pipeline themselves.
3015template<typename Run> 3071template<typename Run>
3016ReplayResult build_pipelines(PipelineCompiles& compiles, std::span<PreparedList> lists, ReplayResult result, 3072ReplayResult build_pipelines(PipelineCompiles& compiles, std::span<PreparedList> lists, ReplayResult result,
3017 Run&& run, const PipelineCompiles* prior = nullptr) { 3073 Run&& run, const std::function<std::uint64_t()>& budget = {},
3074 const PipelineCompiles* prior = nullptr) {
3018 if (compiles.empty()) return result; 3075 if (compiles.empty()) return result;
3019 compiles.build(run, prior); 3076 compiles.build(run, budget, prior);
3020 return finish_compiled_pipelines(compiles, lists, result, prior); 3077 return finish_compiled_pipelines(compiles, lists, result, prior);
3021} 3078}
3022 3079
@@ -3339,6 +3396,8 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3339 out.unpredicated_copies = 0; 3396 out.unpredicated_copies = 0;
3340 const bool queries = vk.reset_query_pool && vk.begin_query && vk.end_query && vk.write_timestamp && 3397 const bool queries = vk.reset_query_pool && vk.begin_query && vk.end_query && vk.write_timestamp &&
3341 vk.copy_query_pool_results && vk.fill_buffer && vk.query_pool; 3398 vk.copy_query_pool_results && vk.fill_buffer && vk.query_pool;
3399 // An SO_STATISTICS query on a real transform-feedback heap additionally needs the indexed begin/end (D3D-302).
3400 const bool so_queries = vk.begin_query_indexed && vk.end_query_indexed;
3342 // Vulkan allows one active query per type. Overlapping ordinary and binary occlusion share one physical 3401 // Vulkan allows one active query per type. Overlapping ordinary and binary occlusion share one physical
3343 // segment pool, and overlapping statistics split into the statistics pool (D3D-252); a physical query of a 3402 // segment pool, and overlapping statistics split into the statistics pool (D3D-252); a physical query of a
3344 // type is still open at most once at any point, because each event closes the one open slot and opens a new 3403 // type is still open at most once at any point, because each event closes the one open slot and opens a new
@@ -3346,6 +3405,10 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3346 VkDeviceAddress indirect_list_budget = 0; 3405 VkDeviceAddress indirect_list_budget = 0;
3347 std::size_t ordinary_active = 0, binary_active = 0, statistics_active_count = 0; 3406 std::size_t ordinary_active = 0, binary_active = 0, statistics_active_count = 0;
3348 bool overlaps = false, statistics_overlaps = false, statistics_active = false; 3407 bool overlaps = false, statistics_overlaps = false, statistics_active = false;
3408 // Streams with an active SO_STATISTICS query in this list, one bit each (D3D-302). Two active transform-feedback
3409 // queries on one stream break VUID-vkCmdBeginQueryIndexedEXT-queryPool-04753 anywhere in the command buffer,
3410 // whatever their pools, so prepare refuses a second Begin on an active stream.
3411 std::uint32_t so_active = 0;
3349 out.wrote_readback = false; 3412 out.wrote_readback = false;
3350 out.readback_src_stages = 0; 3413 out.readback_src_stages = 0;
3351 3414
@@ -3894,7 +3957,23 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
3894 overlaps |= begin && (ordinary_active || binary_active); 3957 overlaps |= begin && (ordinary_active || binary_active);
3895 if (begin) ++binary_active; else --binary_active; 3958 if (begin) ++binary_active; else --binary_active;
3896 } else if (is_so_statistics(range.type)) { 3959 } else if (is_so_statistics(range.type)) {
3897 // No Vulkan query runs for it (QueryPool::pool is null), so it overlaps nothing. 3960 // A real transform-feedback heap queries on a stream (D3D-302). Stream n runs only when the
3961 // heap's pool covers it; then the indexed commands are required. Without a pool (the feature is
3962 // off or has no transformFeedbackQueries) or past maxTransformFeedbackStreams it runs nothing
3963 // and resolves zero. Two overlapping queries on one stream cannot both be active in one command
3964 // buffer, even in two heaps (VUID-vkCmdBeginQueryIndexedEXT-queryPool-04753), so a second Begin
3965 // is refused.
3966 const std::uint32_t stream = range.type - d3d12_query::so_statistics_stream0;
3967 if (heap->pool && stream < heap->streams) {
3968 if (!so_queries) return unsupported_at(__LINE__);
3969 const std::uint32_t bit = 1u << stream; // stream < heap->streams <= 4
3970 if (begin) {
3971 if (so_active & bit) return ReplayResult::invalid_query;
3972 so_active |= bit;
3973 } else {
3974 so_active &= ~bit;
3975 }
3976 }
3898 } else { 3977 } else {
3899 statistics_overlaps |= begin && statistics_active_count; 3978 statistics_overlaps |= begin && statistics_active_count;
3900 if (begin) ++statistics_active_count; else --statistics_active_count; 3979 if (begin) ++statistics_active_count; else --statistics_active_count;
@@ -4208,12 +4287,16 @@ public:
4208 query.statistics_end != detail::PreparedQuery::no_segment; 4287 query.statistics_end != detail::PreparedQuery::no_segment;
4209 const std::uint32_t size = query_result_size(resolve.type); 4288 const std::uint32_t size = query_result_size(resolve.type);
4210 const auto offset = list.commands[query.command].binding.buffer_offset + resolve.offset; 4289 const auto offset = list.commands[query.command].binding.buffer_offset + resolve.offset;
4290 // A stream past the pool's maxTransformFeedbackStreams ran nothing (D3D-302): its resolve is zeros.
4291 const std::uint32_t so_stream =
4292 is_so_statistics(resolve.type) ? resolve.type - d3d12_query::so_statistics_stream0 : 0;
4293 const bool so_runs = !is_so_statistics(resolve.type) || so_stream < query.heap->streams;
4211 for (std::uint32_t i = 0; i < resolve.count; ++i) { 4294 for (std::uint32_t i = 0; i < resolve.count; ++i) {
4212 const auto index = resolve.first + i; 4295 const auto index = resolve.first + i;
4213 const auto value = lookup(*query.heap, index); 4296 const auto value = lookup(*query.heap, index);
4214 if (binary && value.ended && !uncounted) return unsupported_at(__LINE__); 4297 if (binary && value.ended && !uncounted) return unsupported_at(__LINE__);
4215 needs_binary |= binary && value.ended; 4298 needs_binary |= binary && value.ended;
4216 detail::QueryResolveRun run{value.ended ? query.heap->pool : VK_NULL_HANDLE, 4299 detail::QueryResolveRun run{value.ended && so_runs ? query.heap->pool : VK_NULL_HANDLE,
4217 index, 1, offset + VkDeviceSize(i) * size}; 4300 index, 1, offset + VkDeviceSize(i) * size};
4218 if (value.occlusion.segments) { 4301 if (value.occlusion.segments) {
4219 if (resolve.type != d3d12_query::occlusion && !binary && !statistics) 4302 if (resolve.type != d3d12_query::occlusion && !binary && !statistics)
@@ -4337,17 +4420,34 @@ inline void emit_query(const PreparedList& list, const detail::PreparedQuery& qu
4337 begin_statistics(); 4420 begin_statistics();
4338 return; 4421 return;
4339 } 4422 }
4340 // A heap without a Vulkan pool (stream-output statistics: the layer has no stream output) runs nothing for 4423 // A heap without a Vulkan pool (stream-output statistics on a device without VK_EXT_transform_feedback) runs
4341 // BeginQuery and EndQuery; its resolves were planned as zero fills. 4424 // nothing for BeginQuery and EndQuery; its resolves were planned as zero fills.
4342 if (!heap.pool && !std::holds_alternative<ResolveQueries>(command)) return; 4425 if (!heap.pool && !std::holds_alternative<ResolveQueries>(command)) return;
4426 // An SO_STATISTICS_STREAMn query begins/ends indexed on that stream (D3D-302): the query type's stream index is
4427 // the `index` argument of vkCmdBeginQueryIndexedEXT / vkCmdEndQueryIndexedEXT. A stream past the pool's
4428 // maxTransformFeedbackStreams runs nothing, like a heap without a pool: its resolves were planned as zero fills.
4429 const auto so_stream = [](std::uint32_t type) -> std::uint32_t {
4430 return is_so_statistics(type) ? type - d3d12_query::so_statistics_stream0 : 0;
4431 };
4432 const auto so_runs = [&](std::uint32_t type) {
4433 return !is_so_statistics(type) || so_stream(type) < heap.streams;
4434 };
4343 if (const auto* begin = std::get_if<BeginQuery>(&command)) { 4435 if (const auto* begin = std::get_if<BeginQuery>(&command)) {
4436 if (!so_runs(begin->type)) return;
4344 vk.reset_query_pool(cb, heap.pool, begin->index, 1); 4437 vk.reset_query_pool(cb, heap.pool, begin->index, 1);
4345 const bool precise = begin->type == d3d12_query::occlusion && heap.precise; 4438 if (is_so_statistics(begin->type)) {
4346 vk.begin_query(cb, heap.pool, begin->index, precise ? VK_QUERY_CONTROL_PRECISE_BIT : 0); 4439 vk.begin_query_indexed(cb, heap.pool, begin->index, so_stream(begin->type), 0);
4440 } else {
4441 const bool precise = begin->type == d3d12_query::occlusion && heap.precise;
4442 vk.begin_query(cb, heap.pool, begin->index, precise ? VK_QUERY_CONTROL_PRECISE_BIT : 0);
4443 }
4347 } else if (const auto* end = std::get_if<EndQuery>(&command)) { 4444 } else if (const auto* end = std::get_if<EndQuery>(&command)) {
4445 if (!so_runs(end->type)) return;
4348 if (end->type == d3d12_query::timestamp) { 4446 if (end->type == d3d12_query::timestamp) {
4349 vk.reset_query_pool(cb, heap.pool, end->index, 1); 4447 vk.reset_query_pool(cb, heap.pool, end->index, 1);
4350 vk.write_timestamp(cb, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, heap.pool, end->index); 4448 vk.write_timestamp(cb, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, heap.pool, end->index);
4449 } else if (is_so_statistics(end->type)) {
4450 vk.end_query_indexed(cb, heap.pool, end->index, so_stream(end->type));
4351 } else { 4451 } else {
4352 vk.end_query(cb, heap.pool, end->index); 4452 vk.end_query(cb, heap.pool, end->index);
4353 } 4453 }