diff --git a/FEX b/FEX index 1dc6ed4932..3b70cde73c 160000 --- a/FEX +++ b/FEX @@ -1 +1 @@ -Subproject commit 1dc6ed4932bd231df1c53dd7b8043ffdee0ac34a +Subproject commit 3b70cde73c024f7a90db8f33c7986a29ef1559ae diff --git a/app/Madeira/ConfigCatalog.generated.swift b/app/Madeira/ConfigCatalog.generated.swift index 79f4e4c2e9..2b4b9959f0 100644 --- a/app/Madeira/ConfigCatalog.generated.swift +++ b/app/Madeira/ConfigCatalog.generated.swift @@ -85,10 +85,14 @@ extension ConfigCatalog { ConfigOption(key: "env.MADEIRA_WINE_VCRT", title: "", kind: .text, defaultValue: "", category: "App & front end", note: "Layer Microsoft's real VC++ Runtime DLLs ON TOP of the ARM64EC bundle (only for x86_64 guests). These overwrite Wine's stub builtins — Wine then loads the real MS x86_64 implementation (via FEX) instead of its partial ARM64EC reimplement...", choices: [], sources: ["app/Madeira/WineProcessBridge.m"]), ConfigOption(key: "env.MADEIRA_WORKDIR", title: "", kind: .text, defaultValue: "", category: "App & front end", note: "set by the library for one launch: the working folder (Steam's, or the entry's); not a setting", choices: [], sources: ["app/Madeira/WineProcessBridge.m"]), ConfigOption(key: "env.MADEIRA_WOW_HOLD_FOR_GAME", title: "", kind: .bool, defaultValue: "1", category: "App & front end", note: "0: any 32-bit program may take the held window, as before 2026-11-02", choices: [], sources: ["app/Madeira/ContentView.swift"]), + ConfigOption(key: "env.MESA_SHADER_CACHE_DIR", title: "", kind: .text, defaultValue: "", category: "App & front end", note: "KosmicKrisp's cache locations; the same at game start and for a pre-launch compile.", choices: [], sources: ["app/Madeira/WineProcessBridge.m"]), + ConfigOption(key: "env.MESA_SHADER_CACHE_MAX_SIZE", title: "", kind: .text, defaultValue: "", category: "App & front end", note: "KosmicKrisp's cache locations; the same at game start and for a pre-launch compile.", choices: [], sources: ["app/Madeira/WineProcessBridge.m"]), ConfigOption(key: "fexfail", title: "", kind: .text, defaultValue: "", category: "App & front end", note: "ml787: deterministic call-ret allocation failure injection. Documents/madeira-fexfail.txt holds \"reserve:N\" or \"commit:N\". The containment path it exercises only occurs naturally when a title exhausts the emulator's address band, and onl...", choices: [], sources: ["app/Madeira/ContentView.swift"]), + ConfigOption(key: "fossilize", title: "", kind: .text, defaultValue: "", category: "App & front end", note: "done = fossilize_replay_last_done; *total = fossilize_replay_last_total; *seconds = *state == 1 ? madeira_monotonic_seconds() - fossilize_replay_started : fossilize_replay_seconds;", choices: [], sources: ["app/Madeira/WineProcessBridge.m"]), ConfigOption(key: "gl-backend", title: "", kind: .text, defaultValue: "", category: "App & front end", note: "OpenGL backend for the winios GL driver (build/win32u-unix/opengl_ios.c): zink - desktop OpenGL 3.3-4.x: Mesa OSMesa + Zink on MoltenVK, from the bundle's gl/ folder (build/mesa-ios, build/moltenvk-ios) gles - Apple's OpenGL ES 3.0 (EAGL...", choices: [], sources: ["app/Madeira/WineProcessBridge.m"]), ConfigOption(key: "mono-bridge", title: "", kind: .text, defaultValue: "", category: "App & front end", note: "ml727: wine-mono backpatcher bridge A/B. Documents/madeira-mono-bridge.txt == \"1\" sets MADEIRA_WINEMONO_BRIDGE, which arms FEX's Mono code-patching optimisation for wine-mono (recognised since ml712 but activation left opt-in because the...", choices: [], sources: ["app/Madeira/ContentView.swift"]), ConfigOption(key: "mono-suspend", title: "", kind: .text, defaultValue: "", category: "App & front end", note: "ml713: Mono suspend-policy A/B. Documents/madeira-mono-suspend.txt containing \"preemptive\" (or \"coop\"/\"hybrid\") sets MONO_THREADS_SUSPEND for wine-mono, so the comparison needs no rebuild. EXPERIMENT, NOT A FIX, and deliberately not a de...", choices: [], sources: ["app/Madeira/ContentView.swift"]), + ConfigOption(key: "panel-hz", title: "", kind: .text, defaultValue: "", category: "App & front end", note: "madeira-duo (6 Nov 2026): `panel-hz = N` in madeira.cfg pins the panel to N Hz (minimum = preferred = maximum = N) for every FPS limit, overriding the intents below. iPhone ProMotion rates include 120, 80, 60, 48, 40, 30 and 24 (Apple, \"...", choices: [], sources: ["app/Madeira/FPSOverlay.swift"]), ConfigOption(key: "real-suspend", title: "", kind: .text, defaultValue: "", category: "App & front end", note: "this session, or nil to leave it unset. Without it a Wine SuspendThread only snapshots the target's registers while the thread keeps running (ml730, build/wineserver/mach_ios.c). A Unity IL2CPP game's garbage collector suspends every thr...", choices: [], sources: ["app/Madeira/LibraryBCD.swift"]), ConfigOption(key: "remote", title: "", kind: .text, defaultValue: "", category: "App & front end", note: "ml762: remote Metal backend. Documents/madeira-remote.txt holds \" \" and routes winemetal to a Metal daemon on that host instead of the local device. The mode is decided ONCE per process: flipping it later would leave hand...", choices: [], sources: ["app/Madeira/ContentView.swift"]), ConfigOption(key: "remote-batch", title: "", kind: .text, defaultValue: "", category: "App & front end", note: "ml821: coalesced remote messages. Documents/madeira-remote-batch.txt == \"1\" makes the pre-submission flush send many buffer ranges per round trip and drains autorelease pools in one call. It is OPT-IN because the measurement it is meant ...", choices: [], sources: ["app/Madeira/ContentView.swift"]), @@ -104,6 +108,7 @@ extension ConfigCatalog { ConfigOption(key: "env.MADEIRA_AUDIO_GAIN", title: "Game volume at the output (%)", kind: .int, defaultValue: "100", category: "Audio", note: "Percent of the game's level, 10-200; unset or 100 leaves it unchanged. Read once, at the first audio endpoint. Set it in the game's own file.", choices: [], sources: ["build/ntdll-unix/audio_null_ios.c"]), ConfigOption(key: "env.MADEIRA_AUDIO_IO_US", title: "", kind: .text, defaultValue: "", category: "Audio", note: "The shared-mode engine period, in 100 ns units. A client that keeps one period queued (IAudioClient3) must cover a whole RemoteIO slice, or every render callback empties its queue and plays silence for the rest: at least two slices of th...", choices: [], sources: ["build/ntdll-unix/audio_null_ios.c"]), ConfigOption(key: "env.MADEIRA_AUDIO_LEAD_MS", title: "Sound buffer", kind: .choice, defaultValue: "", category: "Audio", note: "How much sound Madeira keeps queued ahead of the speaker (10-500 ms, default 60). If a game's sound crackles or sounds scratchy, a larger buffer usually clears it, at the cost of sound lagging slightly behind the picture: Black Ops II's Zombies crackled at 60 ms and was clean at 150. A game's own config can set it for that game alone. Applies at the next game start.", choices: [("", "60 ms (default)"), ("100", "100 ms"), ("150", "150 ms"), ("200", "200 ms"), ("300", "300 ms")], sources: ["build/ntdll-unix/audio_null_ios.c"]), + ConfigOption(key: "env.MADEIRA_AUDIO_MIX_RATE", title: "Sound mixing rate", kind: .choice, defaultValue: "", category: "Audio", note: "The sample rate Madeira reports for the sound device (8000-96000 Hz, default 48000). A game whose sound engine mixes at the device's rate then mixes that much less audio each second, which is CPU the game gets back; an engine whose game fixed the rate converts at its output instead and gains nothing. FMOD's own default on mobile is 24 kHz \"to reduce CPU cost\"; at 24 kHz sound above 12 kHz is lost. The [ios_audio] create_stream lines in the log give the rate each program opened. Applies at the next game start.", choices: [("", "48 kHz (default)"), ("32000", "32 kHz"), ("24000", "24 kHz")], sources: ["build/ntdll-unix/audio_null_ios.c"]), ConfigOption(key: "env.MADEIRA_AUDIO_PERIOD_MS", title: "", kind: .text, defaultValue: "", category: "Audio", note: "The shared-mode engine period, in 100 ns units. A client that keeps one period queued (IAudioClient3) must cover a whole RemoteIO slice, or every render callback empties its queue and plays silence for the rest: at least two slices of th...", choices: [], sources: ["build/ntdll-unix/audio_null_ios.c"]), ConfigOption(key: "env.MADEIRA_AUDIO_RESUME", title: "Bring game audio back after an interruption", kind: .bool, defaultValue: "0", category: "Audio", note: "Default off: after a call, Siri, an alarm or a suspension the sound stays off until the game restarts. 1: the audio session is activated again and the output restarted; while iOS holds it stopped the game's audio clock keeps running. Logged as [audio] interruption began / ended. Read when the session starts.", choices: [], sources: ["build/ntdll-unix/audio_null_ios.c"]), ConfigOption(key: "env.MADEIRA_AUDIO_SPATIAL", title: "", kind: .text, defaultValue: "", category: "Audio", note: "0: no spatial audio (a game falls back to a plain stream); unset or 1: Wine's spatial audio, as before", choices: [], sources: ["build/ntdll-unix/audio_null_ios.c"]), @@ -128,6 +133,7 @@ extension ConfigCatalog { ConfigOption(key: "env.MADEIRA_POWER_PROBE", title: "Log GPU and device power every 5 s", kind: .bool, defaultValue: "0", category: "Debugging / logs", note: "1: every 5 s a [power] line next to [xp]'s CPU energy: the GPU energy and time the driver charged to the app's coalition, the SoC's Energy Model counters (IOReport) and the battery's voltage and current (the whole device while unplugged), each source named unavailable once when the system gives nothing; and [power-t], the threads that used the most energy. Off (default): nothing is read. Needs the [xp] sampler. Read at session start.", choices: [], sources: ["build/ntdll-unix/server_ios.c"]), ConfigOption(key: "addr-scan", title: "Quicker GPU-address lookups", kind: .bool, defaultValue: "1", category: "Direct3D 12", note: "Default on. Finding the buffer behind a GPU address (every vertex buffer, index buffer and root descriptor a game records) walks back only over entries that can still reach the address, instead of over every buffer within the largest buffer's size of it (124 MB in Horizon Zero Dawn). The same buffer is found. 0: the old walk. Read once per game start.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "ags-rewrite", title: "D3D12 AMD AGS 64-bit atomics rewrite", kind: .text, defaultValue: "", category: "Direct3D 12", note: "ml1149: read once; madeira.cfg ags-rewrite = 0 turns the rewrite off.", choices: [], sources: ["madeira-d3d12/src/unix/madeira_ir_unix.mm"]), + ConfigOption(key: "api-census", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "the tables kept their trampolines (build_vtables returned early)", choices: [], sources: ["madeira-d3d12/src/pe/madeira_list_journal.inc.c"]), ConfigOption(key: "async-present-ahead", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "ml1121: bounded run-ahead. Present enqueues and returns; the application may start the next frame while the worker encodes this one, but no more than async-present-ahead presents (default 1) may be queued behind it.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "async-submit", title: "D3D12 asynchronous submission", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "ml1120: asynchronous submission", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "attachless-split", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "ml910/ml913 madeira-bcd skin-check: before the pass, its captures are blits ml1311: madeira.cfg attachless-split = 1 gives every draw of an attachment-less pass its own encoder. On Apple GPUs the fragment work of consecutive draws in one...", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), @@ -142,7 +148,8 @@ extension ConfigCatalog { ConfigOption(key: "cbv-snapshot", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "fix attempt: copy N bytes (1 = 4096) of every UPLOAD-heap root CBV at replay and bind the copy", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "clear-defer", title: "Clears wait for the pass that draws to their target", kind: .bool, defaultValue: "1", category: "Direct3D 12", note: "On by default. A whole render-target or depth-stencil clear becomes the clear the next render pass that draws to that target starts with: a clear no longer ends the pass in progress unless it is one of that pass's own targets, and needs no pass of its own (which wrote the whole target to memory and read it back later). A barrier or copy that names the cleared texture, or a pass or clear that uses it through another view, applies the clear first, so nothing sees it uncleared. 0: every clear ends the open pass and goes before the next pass on its own, as before. Read once per game start.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "clear-rects", title: "Clear only the rectangles a game asks for", kind: .bool, defaultValue: "0", category: "Direct3D 12", note: "Default off: a render-target or depth-stencil clear with rectangles clears the whole view, as before. 1: only the rectangles are cleared, in a small pass of their own (as DXMT's D3D11 ClearView does); a rectangle that covers the view still clears it the fast way. Horizon Zero Dawn passes rectangles from its first gameplay frames.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), - ConfigOption(key: "cs-concurrent", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "1 = compute encoders are concurrent between barriers (fence modes 1-5); 0 = serial, as before (default)", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "cs-concurrent", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "madeira-duo cs-concurrent: D3D12 orders dispatches only at a UAV or transition barrier, and every barrier here ends the compute encoder (fence-chain 1..5; f6 keeps it open, so stays serial). Inside one encoder the dispatches are independ...", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "cs-create-build", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "madeira-duo: when the game creates a compute pipeline: 3 = one no earlier session created is built inside the create call, on the game's creating thread (the game dispatches it once the call returns, so no frame waits for the compile; a ...", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "cs-dump", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "cs-split", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "fix: 1 = every compute dispatch ends its compute encoder, so the next one waits on the encoder fence (FSR 3 black squares: ordering inside an encoder); 2 = only FidelityFX ('CS' entry) dispatches", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "d3d12-bc-decode", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "1: decode BC uploads (no native BC), 0: raw copies", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), @@ -166,6 +173,9 @@ extension ConfigCatalog { ConfigOption(key: "default-buffer-swap-max-mb", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "default-buffer-swap moves buffers only while the moved total stays at or below this many MB; 0 = no limit", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "default-buffer-swap-mb", title: "", kind: .int, defaultValue: "64", category: "Direct3D 12", note: "fix: default-buffer-swap: the smallest DEFAULT buffer moved, in MB (at least 8)", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "default-buffer-swap-wire", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "1 = VirtualLock (mlock) default-buffer-swap's storage so its pages stay resident; 0 = pageable (as before)", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "dep-trace", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "madeira-duo diagnostic: seconds between dependency traces (0 = off)", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "dep-trace-min-cmds", title: "", kind: .int, defaultValue: "300", category: "Direct3D 12", note: "a call with fewer recorded commands starts no trace", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "dep-trace-min-enc", title: "", kind: .int, defaultValue: "50", category: "Direct3D 12", note: "a traced command buffer with fewer encoders is not one of the three", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "desc-guard", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "diagnostic: log descriptor writes into shader-visible slots a running batch still uses", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "draw-dedup", title: "Leave out render state the encoder already has", kind: .bool, defaultValue: "1", category: "Direct3D 12", note: "Default on. A draw no longer sends Metal the pipeline, viewport, scissor, depth-stencil state, blend colour, rasterizer state or buffer bindings the render encoder already holds from the draw before it; a buffer bound again with only a new offset is sent as an offset. Every draw still runs with exactly the state it set (about half of a Horizon Zero Dawn draw's Metal calls were such repeats). 0: every draw sends all of it, as before. Read once per game start.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "dump-shaders", title: "", kind: .text, defaultValue: "", category: "Direct3D 12", note: "ml1106: madeira.cfg dump-shaders = mdc_x,mdc_y -> Documents/capture/shader_.dxbc, written BEFORE the cache lookup so a cached shader is dumped too.", choices: [], sources: ["madeira-d3d12/src/unix/madeira_ir_unix.mm"]), @@ -182,6 +192,7 @@ extension ConfigCatalog { ConfigOption(key: "env.MADEIRA_D3D12_CS_DUMP", title: "", kind: .text, defaultValue: "", category: "Direct3D 12", note: "400 files into C:\\madeira-cs on every run cost startup time for a diagnostic that is only wanted while chasing one kernel.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "env.MADEIRA_D3D12_DXIL_CACHE", title: "", kind: .bool, defaultValue: "", category: "Direct3D 12", note: "", choices: [], sources: ["madeira-d3d12/src/unix/madeira_ir_unix.mm"]), ConfigOption(key: "env.MADEIRA_D3D12_DXIL_CACHE_MB", title: "", kind: .text, defaultValue: "", category: "Direct3D 12", note: "", choices: [], sources: ["madeira-d3d12/src/unix/madeira_ir_unix.mm"]), + ConfigOption(key: "env.MADEIRA_D3D12_DXIL_LOOSE_SCAN", title: "", kind: .text, defaultValue: "", category: "Direct3D 12", note: "madeira-duo (16 Nov 2026): with d3d12-shader-pack on, new entries go to the pack and loose ones are only read (and moved into the pack on a hit), so the loose bound has nothing to bound. The scan still stat()ed every leftover loose entry...", choices: [], sources: ["madeira-d3d12/src/unix/madeira_ir_unix.mm"]), ConfigOption(key: "env.MADEIRA_D3D12_ONEPASS", title: "", kind: .bool, defaultValue: "", category: "Direct3D 12", note: "ml1990: one conversion call instead of two. The size-then-fill protocol ran the whole compiler for the size query and again for the fill (the DXIL path had no cache to catch the second). A first buffer of four times the input plus 64 KB ...", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c", "madeira-d3d12/src/unix/madeira_ir_unix.mm"]), ConfigOption(key: "env.MADEIRA_D3D12_RS_DESERIALIZER", title: "", kind: .text, defaultValue: "", category: "Direct3D 12", note: "Read once. The switch exists so a device regression can be separated from this path without a rebuild.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "env.MADEIRA_D3D12_TYPED_UAV_LOAD", title: "", kind: .text, defaultValue: "", category: "Direct3D 12", note: "ml1970: FORMAT_SUPPORT below already reports UAV_TYPED_LOAD for every uncompressed colour format (Metal read-write textures), but this option stays FALSE by default: reporting it can move an engine that already runs onto different render...", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), @@ -194,6 +205,7 @@ extension ConfigCatalog { ConfigOption(key: "f6-compute-open", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "ml1116 ml1134: see f6_begin ml1137: counts only madeira-bcd f6-rar", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "f6-rar", title: "Experiment: fence-chain 6 ignores read-to-read barriers", kind: .bool, defaultValue: "0", category: "Direct3D 12", note: "Default off; only with fence-chain = 6. 1: a ResourceBarrier whose every transition goes from read states to read states (or is the first half of a split barrier) no longer makes the next GPU pass wait for all earlier ones, and no longer ends an overlapping render pass (which writes its targets to memory and reads them back). Direct3D 12 orders nothing at such a barrier; a game that relied on it anyway would show flicker. Read once per game start; [perf] f6-rar lines count them.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "fence-chain", title: "D3D12 fence chain mode", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "ml1114: 2 was clamped to 1 in ml1110-ml1113", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c", "app/Madeira/FPSOverlay.swift"]), + ConfigOption(key: "fence-chain-frag", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "madeira-duo: 1 = with fence-chain 3, a render pass waits at its fragment stage unless a compute/blit encoder ended since the last vertex-stage wait (ml1118's rule); 0 = at its vertex stage (as before)", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "fence-early", title: "Fences advance when the GPU reached their batch", kind: .bool, defaultValue: "0", category: "Direct3D 12", note: "Default off. 1: a job whose command buffers have no query results advances its fence right after the GPU's shared event, and its buffers are retired in order on a second thread; under the CPU clamp the completion bookkeeping took 2-5 ms per job, which a game that polls its fences many times a frame waited for. Jobs with query results, a full ring or upload-guard take the old order. Read once per game start; [perf] fence-early lines show it.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "fence-poll-backoff", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "N >= 2 = a thread that polls one unchanged fence N times in a row (each within 50 us) sleeps until it moves, at most fence-poll-backoff-us; 0 = the locked read, as before", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "fence-poll-backoff-us", title: "", kind: .int, defaultValue: "200", category: "Direct3D 12", note: "fence-poll-backoff: the longest sleep in microseconds (20..2000), rounded up to whole milliseconds", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), @@ -201,49 +213,75 @@ extension ConfigCatalog { ConfigOption(key: "fi-field-check", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "diagnostic: every N presents (1 = 60) read back FSR 3's R32 vector fields before its Setup pass and after each later FidelityFX dispatch of that frame; log texels whose low half is a NaN/Inf half-float ([fi-field])", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "fi-nan-clean", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "fix: after each FidelityFX dispatch that binds one of the R32 vector fields FSR 3's Setup pass binds, a helper kernel zeroes the field's texels whose vector half (bits 0..15) is a NaN/Inf half-float (HFW's black squares); 2 = also when b...", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "fi-setup-zero", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "fix: zero-fill the R32 UAV textures of FSR 3's frame-interpolation Setup pass with a blit just before it (black squares: is Setup's own clear lost?)", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "frame-timeline", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "QPC seconds - Metal seconds, smallest seen local time - UTC, FILETIME units", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "fullscreen-window", title: "Full screen moves the game's window over the whole screen", kind: .bool, defaultValue: "0", category: "Direct3D 12", note: "Default off. 1: when a Direct3D 12 game switches to full screen, its window is moved to the screen's top-left corner and over the whole screen first, as Windows does; the game then sizes it to the chosen mode. Without it a game that only resizes its window (Red Dead Redemption 2) keeps it where it was, beside the Wine desktop. Read once per session.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "gpu-fault-info", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "Batch command buffers are created with encoder execution status (madeira_ctl op 8, winemetal in DXMT), and a failed one logs its faulted encoders by label (op 9). After the first fault every encoder is labelled, a compute encoder runs ON...", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "gpu-fault-skip", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "gpu-sync", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "diagnostic: every ExecuteCommandLists commits its batch and waits until the GPU has finished it (no CPU/GPU overlap at all; slow)", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "gs-null-fragment", title: "Empty fragment function for pipelines without a pixel shader", kind: .bool, defaultValue: "1", category: "Direct3D 12", note: "Default on. Metal aborts on a mesh pipeline (geometry shader or tessellation emulation) with rasterization on and no fragment function, while D3D allows a pipeline with no pixel shader. On: such a pipeline gets an empty fragment function and writes no render target, as in D3D; depth and stencil work as before. Horizon Zero Dawn's pipeline thread died without it and the game stopped after its first frame. 0: such a pipeline is refused instead (the geometry shader is dropped). Pipelines with a pixel shader are not touched. Read once per session.", choices: [], sources: ["dxmt/src/winemetal/unix/winemetal_unix.c"]), ConfigOption(key: "heap-backing", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "ml1145", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "hitch-ecl-ms", title: "", kind: .int, defaultValue: "33", category: "Direct3D 12", note: "hitch recorder: log a replay slower than this (0 = off)", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "hitch-ms", title: "", kind: .int, defaultValue: "50", category: "Direct3D 12", note: "hitch recorder: log a frame slower than this (0 = off)", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "hp-release", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "madeira-duo hp-release: a runtime texture heap with nothing left in it goes back to the system (one empty heap is kept as a spare). The heaps used to stay at the peak of every area load: 8 x 64 MB reserved for 163 MB live in prof12b, all...", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "ind-count", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "diagnostic: log N frames (1 = 3000) of per-pipeline ExecuteIndirect instance / threadgroup totals read back from the GPU; one-frame dips are flagged", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "ind-count-from", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "ind-count: the first present logged", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "ind-probe", title: "ExecuteIndirect probe (diagnostic)", kind: .bool, defaultValue: "1", category: "Direct3D 12", note: "Default on. Every 3 s per pipeline, the first argument record of an ExecuteIndirect is read back by a small compute pass and logged as a [probe] line, 1500 lines at most. Each probe ends the open render pass. 0: no probes (Red Dead Redemption 2's list, build 476).", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "indirect-fast", title: "Encode ExecuteIndirect records without per-record setup", kind: .bool, defaultValue: "0", category: "Direct3D 12", note: "Default off. 1: after the first record of an ExecuteIndirect, the other records (which share all state but their offset) are encoded 64 at a time with only their offset and the indirect draw or dispatch, instead of the whole per-draw setup each. For games that issue thousands of indirect records a frame (Red Dead Redemption 2), where that setup costs more CPU time than the GPU spends. DXIL and DXBC pipelines (DXBC from build 470); pipelines with tessellation or geometry stages, diagnostics and captures keep the per-record path. Read once per session.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "jr-pe-entries", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "the tables kept their trampolines (build_vtables returned early)", choices: [], sources: ["madeira-d3d12/src/pe/madeira_list_journal.inc.c"]), + ConfigOption(key: "list-journal", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "the tables kept their trampolines (build_vtables returned early)", choices: [], sources: ["madeira-d3d12/src/pe/madeira_list_journal.inc.c"]), ConfigOption(key: "metalfx-upscale", title: "MetalFX upscaling factor", kind: .choice, defaultValue: "", category: "Direct3D 12", note: "Scales the presented picture with Apple's MetalFX spatial scaler (Direct3D 11 and 12). Usually set per game in Game details > Display.", choices: [("", "Off"), ("1.5", "1.5x"), ("2", "2x")], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c", "app/Madeira/ContentView.swift"]), ConfigOption(key: "mip0-full", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "fix: a texture created with MipLevels 0 gets the full mip chain and GetDesc answers its count, as D3D12 does (FSR 3.1 frame generation's inpainting pyramid: Horizon Forbidden West's black squares); 0 = one level, GetDesc answers 0", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "msc-bounds-check", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "0: shaders converted without D3D12's robust buffer access (bounds check), as env MADEIRA_IR_NO_BOUNDS_CHECK=1", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c", "madeira-d3d12/src/unix/madeira_ir_unix.mm"]), ConfigOption(key: "msc-fail-memo", title: "Remember refused shaders for the session", kind: .bool, defaultValue: "0", category: "Direct3D 12", note: "Default off. 1: a shader the converter refused is not converted again for the next pipeline that uses it (same bytecode, root signature and options) until the game exits. Horizon Zero Dawn converted each refused shader ~6 times, ~30,000 conversions in its first minutes.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "msc-gpu-family", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "madeira-duo: 0 = the device's newest of Apple7-9 (as before); 1006-1010 = convert for that Apple GPU family, if the device reports it", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "msc-ignore-debug-info", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "madeira-duo: converter switches read only by madeira_ir_unix.mm; like dxbc-spaces, a non-default value gets a cache identity of its own", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c", "madeira-d3d12/src/unix/madeira_ir_unix.mm"]), + ConfigOption(key: "msc-min-os", title: "", kind: .text, defaultValue: "", category: "Direct3D 12", note: "madeira-duo: minimum OS the conversion targets, e.g. 26.0 (default 18.0 on iOS)", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "msc-position-inf-nan", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "madeira-bcd: madeira_ir_unix.mm, build 217", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c", "madeira-d3d12/src/unix/madeira_ir_unix.mm"]), ConfigOption(key: "msc-position-invariance", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "0: shaders converted without D3D12's robust buffer access (bounds check), as env MADEIRA_IR_NO_BOUNDS_CHECK=1", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c", "madeira-d3d12/src/unix/madeira_ir_unix.mm"]), ConfigOption(key: "msc-sample-nan-zero", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "madeira-bcd: madeira_ir_unix.mm, build 217", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c", "madeira-d3d12/src/unix/madeira_ir_unix.mm"]), ConfigOption(key: "msc-sampler-lod-bias", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "0: shaders converted without D3D12's robust buffer access (bounds check), as env MADEIRA_IR_NO_BOUNDS_CHECK=1", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c", "madeira-d3d12/src/unix/madeira_ir_unix.mm"]), ConfigOption(key: "msc-strict-nan", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "0: shaders converted without D3D12's robust buffer access (bounds check), as env MADEIRA_IR_NO_BOUNDS_CHECK=1", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c", "madeira-d3d12/src/unix/madeira_ir_unix.mm"]), ConfigOption(key: "msc-unbounded-retry", title: "Retry refused shaders with sized unbounded ranges", kind: .bool, defaultValue: "0", category: "Direct3D 12", note: "Default off. 1: a DXIL shader the converter refuses with code 4 (a resource not in the root signature) is converted once more with the root signature's unbounded descriptor ranges given a size (2048 samplers, 1000000 others). Horizon Zero Dawn's ranges start at register 4 and ~4,900 of its shaders were refused. Once that works for a root signature, its later shaders take the sized ranges first.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "msc-validation", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "madeira-duo: converter switches read only by madeira_ir_unix.mm; like dxbc-spaces, a non-default value gets a cache identity of its own", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c", "madeira-d3d12/src/unix/madeira_ir_unix.mm"]), ConfigOption(key: "occlusion-visible", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "ml1103", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "perf-log", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "ml1108: where does the frame go? GPU busy (union of command-buffer GPU intervals), CPU time blocked in retire, presents -- logged every 5 s from Present. Off with madeira.cfg perf-log = 0.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "present-min-ms", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "diagnostic: Present sleeps so that frames are at least N ms apart (200 = 5 fps), like the main menu's slow first seconds", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "pso-archive", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "compiled pipelines kept in Metal binary archives of our own (1; 0 = Metal's cache only)", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "pso-async", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "madeira.cfg pso-async: 1 = a new render pipeline is built on a background thread and its draws are skipped until it is ready (no frame waits for the compiler); 0 = built at its first draw", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "pso-async-threads", title: "", kind: .int, defaultValue: "2", category: "Direct3D 12", note: "madeira-duo pso-async-threads: a build mostly waits on Metal's compiler service, which compiles several at once. On a new PoE2 map ~550 pipelines miss the archive at ~430 ms each, and with 2 builders enemies stayed invisible for seconds ...", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "pso-create-block", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "madeira-duo: 1 = pipelines drawn in an earlier session are built inside the game's create call, on its thread (no draw finds them unbuilt); 2 = only those already in the pso-archive (a lookup, no compile), the rest go to the background b...", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "pso-create-build", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "madeira-duo: 1 = pipelines drawn in an earlier session are built in the background when the game creates them, 2 = every plain render pipeline; 0 = at their first draw (as before)", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "pso-first-use", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "diagnostic: log every pipeline the first time a command list binds it, with the present it was created at", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "pso-lazy", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "madeira-bcd: madeira.cfg pso-lazy (default 1), see mad_pso_realize", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "pso-lazy-libs", title: "Shader libraries only for pipelines in use", kind: .bool, defaultValue: "0", category: "Direct3D 12", note: "Default off. 1: a pipeline built at its first draw (or dispatch) lets its converted Metal libraries go once the game has created it, and reads them back from the shader cache at that first draw. Horizon Zero Dawn creates ~52,000 pipelines in its menu and draws a few thousand; their libraries held hundreds of MB until iOS closed the game. Needs the shader cache (on by default); with pso-warm, a library stays until its warm-up compile is done.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "pso-origin", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "madeira-duo: 1 = count the pipelines Metal compiles by origin: drawn in an earlier session, created in one, or new ([pso-origin] lines, list in pso-created-.bin; diagnostic, nothing the game sees changes); 0 = off", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "pso-parallel", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "madeira.cfg pso-parallel (default 1): a batch's new pipelines built in parallel", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "pso-placeholder", title: "Placeholder for pipelines whose shaders did not convert", kind: .bool, defaultValue: "0", category: "Direct3D 12", note: "Default off. 1: a graphics pipeline whose vertex or pixel shader did not convert is returned to the game as a placeholder whose draws are skipped, instead of a failure. Horizon Zero Dawn stopped with an \"Error\" box when its settings menu got such a failure.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "pso-seen-record", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "madeira-duo: 1 = remember the pipelines drawn (pso-create-build = 1 does it anyway)", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "pso-share-libs", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "madeira.cfg pso-share-libs (default 1): identical converted libraries share one MTLLibrary. 0 keeps one per pipeline (the table is never trimmed, so this is the switch to compare memory with).", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "pso-slow-ms", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "pso-warm-compute-only", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "1: pso-warm compiles compute pipelines only", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "query-timestamps", title: "Timestamp queries from the CPU clock", kind: .bool, defaultValue: "0", category: "Direct3D 12", note: "Default off: every timestamp resolves to zero. 1: a resolved timestamp is the process's monotonic clock in ns when the resolve is recorded (plus its place in the range), and GetClockCalibration's GPU value is the same clock, for a game that spins on zero timestamps. Nothing is measured on the GPU. Read once per game start.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "queue-trace", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "diagnostic: log the first N ExecuteCommandLists / Signal / Wait calls (1 = 400) with thread, queue type and fence state", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "quiet-log", title: "Cheaper Direct3D 12 logging (no census frames)", kind: .bool, defaultValue: "0", category: "Direct3D 12", note: "1: the Direct3D 12 runtime's log lines skip OutputDebugString (an exception and a server request each, ~0.5 ms a line on the device) and reach the log through Wine's own debug output and stderr only; the census frames between presents 1500 and 3000 and the list 12000-12400 draw dumps are off (each froze the game for 1-2 s); the per-shader \"converted at runtime\" line is kept for the first 64 shaders and then every 1000th. A manual frame capture still works. Default off: the logging as before.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "rcas-fill", title: "", kind: .text, defaultValue: "", category: "Direct3D 12", note: "", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "readback-far", title: "Experiment: empty culling readback", kind: .bool, defaultValue: "0", category: "Direct3D 12", note: "Default off. 1: a readback of a depth pyramid (an R32_FLOAT mip of 1 or more of a texture with 4+ mips, up to 64x64) is not copied; the CPU fills it with 4096, so a game that culls on the CPU against it culls nothing (everything is drawn: slower). A test, not a fix. Read once per game start.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "readback-swap", title: "D3D12 readback buffers on file-backed memory", kind: .bool, defaultValue: "1", category: "Direct3D 12", note: "Default on: like upload buffers (upload-swap), READBACK buffers of 8 MB or more live on file-backed storage, off the memory footprint. 0: READBACK buffers get Metal's own memory (Horizon Zero Dawn: two 32 MB buffers), so what the GPU writes into them reaches the CPU without the file tier between; upload buffers stay where upload-swap puts them. Read once per game start.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "replay-split", title: "Log where Direct3D 12 submission time goes", kind: .bool, defaultValue: "0", category: "Direct3D 12", note: "Default off, logging only. 1: every 5 seconds a [perf] replay split line divides the time ExecuteCommandLists takes per frame into waiting for the queue, preparation, opening a command buffer, each kind of command (draws, dispatches, copies, clears, barriers, render targets, queries, state) and the end of each list. For finding why a game's frame is slow when the GPU is not busy.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "reset-wait-event", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "madeira-duo: 1 = a command list Reset that waits for the submission worker sleeps until the worker wakes it; 0 = it spins (pauses, Sleep(0), then Sleep(1)) as before", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "ring-share", title: "Share argument buffers between command lists", kind: .bool, defaultValue: "0", category: "Direct3D 12", note: "Default off. 1: a command list gives the argument-buffer chunks its replay wrote back as soon as the GPU is done with them, instead of keeping them until it is recorded again; all lists then share one pool. Red Dead Redemption 2 kept 1.5 GB of them (half of its Metal memory) with the switch off.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "root-cbv-fast", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "madeira-duo: 1 = a root CBV/SRV/UAV address inside the buffer the list's previous one resolved to skips the address search (same answer; only committed buffers, only while the address index is unchanged); 0 = every one is searched (as be...", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "rp-carry", title: "Experiment: render passes go on into the next command list", kind: .bool, defaultValue: "0", category: "Direct3D 12", note: "Default off. 1: when a command list ends inside a render pass and the next list of the same submission draws to the same targets first, with only state between the two draws, the pass stays open: its targets are not written to memory and read back. Horizon Zero Dawn records its depth and G-buffer passes in ~20 lists (0.3-0.6 GB a frame of such writes and reads), GTA V Enhanced its G-buffer in ~12. Opt-in: the second list's draws no longer wait for the whole first pass, an ordering Direct3D 12 does not promise but a game might rely on. Read once per game start; [perf] gpu-traffic lines show what it saves.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "rp-discard", title: "Experiment: no load after, no store before DiscardResource", kind: .bool, defaultValue: "0", category: "Direct3D 12", note: "Default off. 1: after a game discards a whole render target or depth buffer (DiscardResource), the next render pass that draws to it does not read its old contents from memory, and a pass whose target is discarded (or cleared whole) next, before any other use in the same submission, does not write it back -- as tile-based GPUs do on Windows. Opt-in: a game that still reads what it discarded (desktop GPUs ignore discards) would show garbage there. Read once per game start; [perf] gpu-traffic lines show the bytes.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "rp-lean", title: "Render passes fill only the targets they use", kind: .bool, defaultValue: "1", category: "Direct3D 12", note: "Default on. A Metal render pass is described with only the colour targets it uses; the bridge filled all eight slots for every pass (~240 Objective-C calls and 8 allocations a pass, a few hundred passes a frame). Metal ignores a slot without a texture, so the pass is the same. Also used by Direct3D 9/10/11 games through DXMT. 0: all eight slots, as before. Read once per game start.", choices: [], sources: ["dxmt/src/winemetal/unix/winemetal_unix.c"]), + ConfigOption(key: "rp-learn-census", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "madeira-duo: seconds between rp-learn-census reports (0 = off)", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "rp-learn-log", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "madeira-duo: rp-learn-store: log each texture learned or ruled out", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "rp-learn-store", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "madeira-duo: 1 = learn which batch-end attachment stores are always wasted and skip them", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "rp-learn-store-n", title: "", kind: .int, defaultValue: "16", category: "Direct3D 12", note: "madeira-duo: rp-learn-store: wasted stores in a row before a texture's batch-end stores are skipped (4-1000)", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "sampler-census", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "diagnostic: log every distinct sampler filter value once with its Metal mapping", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "sampler-max-aniso", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "madeira-duo: N (1..16) caps the anisotropy of every sampler at N (1 = trilinear; less fragment time); 0 = as the game asks", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "shader-cache", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), + ConfigOption(key: "shader-cache-app-key", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "madeira-duo: 0 = the cache directory ignores the app build (only for a pinned converter identity); 1 = every app build starts a new cache", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "shader-cache-native", title: "D3D12 shader cache files read natively", kind: .bool, defaultValue: "1", category: "Direct3D 12", note: "On by default. The Direct3D 12 runtime's shader cache (AppData\\Local\\Madeira\\ShaderCache) is read and written by Madeira itself instead of through Wine's file calls, which asked Wine's server three times per entry (~3.5 ms each in Horizon Zero Dawn's menu, ~1,000 entries a second, with the server on a performance core). The same files either way. 0: Wine's file calls, as before. Read when the game creates its first pipeline.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "skin-check", title: "Diagnostic: check meshes skinned on the GPU", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "Default 0 (off). N: windows of N frames (1 = 8) log every draw that reads a vertex buffer a compute shader wrote, the dispatches that wrote it with every binding, a summary of up to 32 KB of each such stream copied just before the draw, and the shaders' bytecode. For characters drawn with missing faces or spikes (Horizon Zero Dawn); costs time in those frames.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "skin-check-capture", title: "Diagnostic: skin-check copies the streams", kind: .bool, defaultValue: "1", category: "Direct3D 12", note: "On by default with skin-check. 0: log only, with no GPU copies, which add a copy between the skinning dispatches and the draw (to compare what the frames look like).", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), @@ -266,6 +304,7 @@ extension ConfigCatalog { ConfigOption(key: "view-census", title: "Diagnostic: report buffer views that fall back", kind: .bool, defaultValue: "0", category: "Direct3D 12", note: "Default off. 1: typed buffer views that cannot become a Metal texture buffer (the shader then sees no data), views cut short at the end of their resource, and views or constant buffer views past their resource are counted and named in the log, with Metal's minimum alignment for each pixel format typed views use. Changes nothing else.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "vis-trace", title: "Diagnostic: per-frame draws and culling readback", kind: .bool, defaultValue: "0", category: "Direct3D 12", note: "Default off. 1: one log line per present (the HUD's frame number): draws, depth-only and 3+-target draws, indices, dispatches, depth-pyramid readback copies, new offset typed views, and Queue::Wait calls (how many passed before the awaited batch was committed); and every value of the 22x10, 11x5 and 5x2 mips of the pyramid a game culls with, as the GPU wrote them. The GPU also copies each of those mips into Madeira's own memory, and a mip whose readback memory holds something else is flagged (an earlier frame's values: STALE). Read once per game start.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "vsps-fill", title: "", kind: .int, defaultValue: "1", category: "Direct3D 12", note: "0: shaders converted without D3D12's robust buffer access (bounds check), as env MADEIRA_IR_NO_BOUNDS_CHECK=1", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c", "madeira-d3d12/src/unix/madeira_ir_unix.mm"]), + ConfigOption(key: "vtx-census", title: "", kind: .int, defaultValue: "0", category: "Direct3D 12", note: "madeira-duo diagnostic: seconds between vertex census reports (0 = off)", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "write-buffer-immediate", title: "WriteBufferImmediate writes its values", kind: .bool, defaultValue: "0", category: "Direct3D 12", note: "Default off: the method stays a stub (nothing written). 1: the values are written by the GPU in list order and a submission that wrote one is committed at once. CheckFeatureSupport still reports no support either way. Read once per game start.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "env.DXMT_AIRCONV_DUMP", title: "", kind: .text, defaultValue: "", category: "Direct3D 9/10/11 (DXMT)", note: "Env-gated metallib dump: point DXMT_AIRCONV_DUMP at a directory and every DXSOCompile call drops a {kind}_{hash}.metallib there. Disassemble with `xcrun air-objdump -d ` to inspect what AGX actually receives. Only meant for triage ...", choices: [], sources: ["dxmt/src/airconv/dxso_compile.cpp", "dxmt/src/d3d9/d3d9_shader.cpp"]), ConfigOption(key: "env.DXMT_API_CENSUS", title: "", kind: .text, defaultValue: "", category: "Direct3D 9/10/11 (DXMT)", note: "", choices: [], sources: ["dxmt/src/winemetal/wmt_api_census.c"]), @@ -322,6 +361,7 @@ extension ConfigCatalog { ConfigOption(key: "env.DXMT_WSI_MODE_TABLE", title: "", kind: .bool, defaultValue: "32-bit only", category: "Direct3D 9/10/11 (DXMT)", note: "", choices: [], sources: ["dxmt/src/util/wsi_monitor_headless.cpp"]), ConfigOption(key: "env.DXMT_WSI_MONITOR_IDENTITY", title: "", kind: .bool, defaultValue: "32-bit only", category: "Direct3D 9/10/11 (DXMT)", note: "The native frontend (DXMT_MADEIRA) has no user32 boundary and always uses the internal singleton.", choices: [], sources: ["dxmt/src/util/wsi_monitor_headless.cpp"]), ConfigOption(key: "env.DXMT_ZERO_BUFFER_POW2", title: "", kind: .bool, defaultValue: "32-bit only", category: "Direct3D 9/10/11 (DXMT)", note: "MADEIRA (ml1490): with DXMT_ZERO_BUFFER_POW2, grow to the next power of two (at least 1 MB) instead of the exact request. Each growth costs a flushInternal(), and a loading screen asking for slowly rising sizes regrew the buffer 322 time...", choices: [], sources: ["dxmt/src/dxmt/dxmt_resource_initializer.cpp"]), + ConfigOption(key: "env.MADEIRA_D3D11_QUERY_PARK", title: "", kind: .text, defaultValue: "", category: "Direct3D 9/10/11 (DXMT)", note: "phone is heat that throttles the threads doing real work. Once the polls of one query come in a burst (two pending polls less than 250 us apart), this parks the caller on the queue's shared event until the query's value is signaled, at m...", choices: [], sources: ["dxmt/src/d3d11/d3d11_context_imm.cpp"]), ConfigOption(key: "env.MADEIRA_D3D9", title: "", kind: .text, defaultValue: "", category: "Direct3D 9/10/11 (DXMT)", note: "the d3d9 key's value: emulated (default) or native = DXMT's i386 shim; wined3d = Wine's d3d9 on wined3d/OpenGL for 32- and 64-bit programs", choices: [], sources: ["dxmt/src/d3d9shim/d3d9shim_main.c", "app/Madeira/WineProcessBridge.m"]), ConfigOption(key: "env.MADEIRA_D3D9_BATCH_BUDGET", title: "", kind: .text, defaultValue: "", category: "Direct3D 9/10/11 (DXMT)", note: "", choices: [], sources: ["dxmt/src/d3d9/d3d9_device.cpp"]), ConfigOption(key: "env.MADEIRA_D3D9_BATCH_USED", title: "", kind: .text, defaultValue: "", category: "Direct3D 9/10/11 (DXMT)", note: "ml1970: charge used bytes and trim sparse small captures, so retention and the pressure submit follow real work. MADEIRA_D3D9_BATCH_USED=0 restores ml1960's capacity charge and 8 MiB threshold.", choices: [], sources: ["dxmt/src/d3d9/d3d9_device.cpp"]), @@ -347,9 +387,13 @@ extension ConfigCatalog { ConfigOption(key: "env.MADEIRA_MIP_CLAMP_AUTO", title: "", kind: .text, defaultValue: "", category: "Direct3D 9/10/11 (DXMT)", note: "", choices: [], sources: ["dxmt/src/d3d11/d3d11_texture_device.cpp"]), ConfigOption(key: "env.MADEIRA_PRESENT_LIMITER", title: "", kind: .text, defaultValue: "", category: "Direct3D 9/10/11 (DXMT)", note: "sleeps to an absolute deadline on the same timebase the scheduler uses, so it does not accumulate the per-iteration error a relative nanosleep ladder does and it does not quantise to a timer tick -- the failure mode the brief calls out, ...", choices: [], sources: ["dxmt/src/winemetal/unix/winemetal_unix.c"]), ConfigOption(key: "env.MADEIRA_PRESENT_PIXELS", title: "", kind: .bool, defaultValue: "32-bit only", category: "Direct3D 9/10/11 (DXMT)", note: "ml1140: WSI window extents are Windows pixels, not UIKit points. Applying the phone's 3x scale again made a 720p present render into a 4K drawable. Core Animation already maps that drawable onto the host view in points. Keep the correcti...", choices: [], sources: ["dxmt/src/winemetal/unix/winemetal_unix.c"]), + ConfigOption(key: "env.MADEIRA_PSO_ARCHIVE_MAX_AGE", title: "", kind: .text, defaultValue: "", category: "Direct3D 9/10/11 (DXMT)", note: "madeira_arch_q: save the open archive once 10 s have passed without an add. madeira-duo arch-age: or once its oldest unsaved add is MADEIRA_PSO_ARCHIVE_MAX_AGE seconds old (default 20). In a map the adds never stop for 10 s, so a session...", choices: [], sources: ["dxmt/src/winemetal/unix/winemetal_unix.c"]), + ConfigOption(key: "env.MADEIRA_PSO_WARM_YIELD", title: "", kind: .text, defaultValue: "", category: "Direct3D 9/10/11 (DXMT)", note: "the pipelines the game is waiting for. In Path of Exile 2 (log 2026-11-15 01:17) it compiled ~4 compute pipelines a second while new maps loaded and the game's own render pipelines got ~1 a second; 815 warm compiles against 383 render on...", choices: [], sources: ["dxmt/src/winemetal/unix/winemetal_unix.c"]), ConfigOption(key: "env.MADEIRA_VFETCH_ALIGN1", title: "", kind: .text, defaultValue: "", category: "Direct3D 9/10/11 (DXMT)", note: "", choices: [], sources: ["dxmt/src/airconv/dxbc_converter_basicblock.cpp"]), ConfigOption(key: "env.MADEIRA_VFETCH_BOUNDS", title: "", kind: .text, defaultValue: "", category: "Direct3D 9/10/11 (DXMT)", note: "madeira-bcd: vertex fetch bounds (tools/patch-dxmt-vfetch-bounds.py) -- D3D10 reads zero past the end of the binding; route such a fetch to the null-binding branch of pull_vec4_from_addr instead of reading on. Default: SM 4.x shaders onl...", choices: [], sources: ["dxmt/src/airconv/dxbc_converter_basicblock.cpp"]), ConfigOption(key: "env.MADEIRA_WRITE_COMBINED", title: "", kind: .text, defaultValue: "", category: "Direct3D 9/10/11 (DXMT)", note: "ml1178: no write-combined CPU mappings. DXMT asks for MTLCPUCacheModeWriteCombined on what the CPU only writes (dynamic buffers and textures, upload staging). Under FEX's TSO emulation every x86 integer store is an STLR, and a store-rele...", choices: [], sources: ["dxmt/src/winemetal/unix/winemetal_unix.c"]), + ConfigOption(key: "gpu-pass-dump-s", title: "", kind: .int, defaultValue: "30", category: "Direct3D 9/10/11 (DXMT)", note: "", choices: [], sources: ["dxmt/src/winemetal/unix/winemetal_unix.c"]), + ConfigOption(key: "gpu-pass-timing", title: "", kind: .int, defaultValue: "0", category: "Direct3D 9/10/11 (DXMT)", note: "", choices: [], sources: ["dxmt/src/winemetal/unix/winemetal_unix.c"]), ConfigOption(key: "pso-warm", title: "", kind: .int, defaultValue: "0", category: "Direct3D 9/10/11 (DXMT)", note: "pipeline cache warm-up: N background compiles of every lazy pipeline at creation (1-4; 0 = off)", choices: [], sources: ["dxmt/src/winemetal/unix/winemetal_unix.c", "madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "ram-reserve-mb", title: "", kind: .int, defaultValue: "1536", category: "Direct3D 9/10/11 (DXMT)", note: "RAM left to iOS, MB; 0 = limit only", choices: [], sources: ["dxmt/src/winemetal/unix/winemetal_unix.c"]), ConfigOption(key: "sampler-reduction", title: "", kind: .int, defaultValue: "0", category: "Direct3D 9/10/11 (DXMT)", note: "madeira-bcd: native sampler reduction (tools/patch-winemetal-sampler-reduction.py)", choices: [], sources: ["dxmt/src/winemetal/unix/winemetal_unix.c", "madeira-d3d12/src/pe/madeira_d3d12.c"]), @@ -480,6 +524,7 @@ extension ConfigCatalog { ConfigOption(key: "env.MADEIRA_POOL_QUARANTINE", title: "", kind: .text, defaultValue: "", category: "Memory & JIT pool", note: "OUT NON-EXEC off=0xa848000...). The next process started in that session (the windowed taskbar's in-session launcher: services.exe, then steam.exe) got its ntdll copy there and faulted NOEXEC at LdrInitializeThunk's first instruction, fo...", choices: [], sources: ["build/ntdll-unix/virtual_ios.c"]), ConfigOption(key: "env.MADEIRA_POOL_RECYCLE_IMAGES", title: "Images in retired code-buffer space", kind: .bool, defaultValue: "0", category: "Memory & JIT pool", note: "Default off. If other image allocations fail, retired region-C code buffers up to 64 MB may enter the image freelist after a 3-second grace, executable-page and thread-PC checks. Requires pool-low; 64-bit processes only. Live buffers and the pool-low-margin stay unchanged.", choices: [], sources: ["build/ntdll-unix/virtual_ios.c"]), ConfigOption(key: "env.MADEIRA_POOL_SECTION_CLAMP", title: "", kind: .text, defaultValue: "", category: "Memory & JIT pool", note: "EXECUTE from max_protection for good (ml140), so every later hand-out there was born non-executable: device logs 80-83 show [pool-poison] starting exactly at such an image's allocation end, after which every process started later in the ...", choices: [], sources: ["build/ntdll-unix/virtual_ios.c"]), + ConfigOption(key: "env.MADEIRA_POOL_TRIM", title: "", kind: .text, defaultValue: "", category: "Memory & JIT pool", note: "", choices: [], sources: ["build/ntdll-unix/virtual_ios.c"]), ConfigOption(key: "env.MADEIRA_PRELOAD_DLLS", title: "Load these DLLs with the D3D12 device", kind: .text, defaultValue: "", category: "Memory & JIT pool", note: "Default empty. DLL names separated by ';' (e.g. xinput1_4.dll): each program loads and pins them at its first D3D12 device or probe call, while the JIT pool still has room for their copies. RDR2 loads xinput1_4.dll only at its first controller read, and on build 476 the pool was full by then: no controller and no on-screen controls. Restart the session after changing it.", choices: [], sources: ["madeira-d3d12/src/pe/madeira_d3d12.c"]), ConfigOption(key: "env.MADEIRA_RDR2_VA_HOLD", title: "Keep 8960 MB free for Red Dead Redemption 2", kind: .bool, defaultValue: "0", category: "Memory & JIT pool", note: "Default off; only with env.MADEIRA_SC_PA_POOLS = 2. 1: Social Club's layout 2 keeps libcef.dll's PartitionAlloc pools at 256 MB and its metadata at 1 GB, chrome_elf.dll's metadata at 6.25 GB, gives the rest of the app's 4 GB hold to Wine's furniture (3.75 GB more room for threads and allocations), keeps Oilpan's cage at 1 GB so the FEX arena grows to 15 GB, and holds [0x75d0000000, 0x7800000000) from boot for one 8960 MB reserve, the one Red Dead Redemption 2 makes as it starts. Set it only in that game's own file; GTA V keeps layout 2 as it is. Read at session start.", choices: [], sources: ["build/ntdll-unix/virtual_ios.c"]), ConfigOption(key: "env.MADEIRA_REPLY_OWN_WRITABLE", title: "Server replies: a writable page is written in place", kind: .bool, defaultValue: "1", category: "Memory & JIT pool", note: "ml2230: on (default): a server reply whose buffer lies in the JIT pool's address range but on a page that is writable at its own address (a page the pool gave up, which the system reused for a thread stack) is stored there, not through the pool's RW alias, which has no mapping for it. Before, a child process could die in its first reply (log 111: rpcss.exe, and the Steam client waited for it forever). 0: the pool's address range alone decides, as before.", choices: [], sources: ["build/ntdll-unix/server_ios.c"]), @@ -491,6 +536,8 @@ extension ConfigCatalog { ConfigOption(key: "env.MADEIRA_SC_IPC_SPLIT", title: "", kind: .text, defaultValue: "", category: "Memory & JIT pool", note: "", choices: [], sources: ["build/ntdll-unix/virtual_ios.c"]), ConfigOption(key: "env.MADEIRA_SC_PA_POOLS", title: "Room for Social Club's PartitionAlloc pools", kind: .choice, defaultValue: "", category: "Memory & JIT pool", note: "1: Wine boots with the emulator's arena at 0x7d00000000 (12 GB instead of 16 GB) and keeps 0x7c00000000 +4 GB free, so SocialClubHelper.exe's 32 GB PartitionAlloc reservation, which must start on a 32 GB boundary, gets 0x7800000000 (20 GB of it really reserved). 2: also libcef.dll's (0x7000000000) and Oilpan's; the JIT pool's RW alias moves to 0x7900000000. Off by default; set it in the game's own file; read at session start.", choices: [("", "Off"), ("1", "Layout 1 (chrome_elf.dll only)"), ("2", "Layout 2 (chrome_elf, libcef, Oilpan)")], sources: ["build/ntdll-unix/virtual_ios.c", "app/Madeira/StikJITHelper.swift"]), ConfigOption(key: "env.MADEIRA_SC_RENDER_HANDLER", title: "", kind: .text, defaultValue: "", category: "Memory & JIT pool", note: "", choices: [], sources: ["build/ntdll-unix/virtual_ios.c"]), + ConfigOption(key: "env.MADEIRA_SECTION_VIEW_CAP_GB", title: "", kind: .text, defaultValue: "", category: "Memory & JIT pool", note: "bytes; vk6", choices: [], sources: ["build/ntdll-unix/virtual_ios.c"]), + ConfigOption(key: "env.MADEIRA_SECTION_VIEW_GROW", title: "", kind: .text, defaultValue: "", category: "Memory & JIT pool", note: "", choices: [], sources: ["build/ntdll-unix/virtual_ios.c"]), ConfigOption(key: "env.MADEIRA_SHARE_PROBE", title: "", kind: .text, defaultValue: "", category: "Memory & JIT pool", note: "task #34 [share-probe]: DEFAULT-OFF (set MADEIRA_SHARE_PROBE=1). ml79: running it inline here (pre-detach, on explorer's boot thread) wedged the session — exec-at-alias hangs while the debugger is attached. Gated + deferred to a scratch ...", choices: [], sources: ["build/ntdll-unix/virtual_ios.c"]), ConfigOption(key: "env.MADEIRA_SHARED_SECTION_EXEC", title: "", kind: .text, defaultValue: "", category: "Memory & JIT pool", note: "env.MADEIRA_SHARED_SECTION_EXEC = 1", choices: [], sources: ["build/ntdll-unix/virtual_ios.c"]), ConfigOption(key: "env.MADEIRA_SHARED_SECTION_PRIVATE", title: "", kind: .text, defaultValue: "", category: "Memory & JIT pool", note: "0 fails the load of an image whose shared writable section is not aligned to the host page, as before; otherwise that section is mapped private.", choices: [], sources: ["build/ntdll-unix/virtual_ios.c"]), @@ -628,6 +675,7 @@ extension ConfigCatalog { ConfigOption(key: "inproc-sync", title: "Madsync (in-process sync)", kind: .bool, defaultValue: "0", category: "Synchronisation", note: "1 selects madsync (Settings > Sync engine > Madsync). Unset: fastsync, the default engine; 0 without env.MADEIRA_FASTSYNC: Wine standard sync.", choices: [], sources: ["build/madeira_cfg.h", "build/madsync/madsync.c", "app/Madeira/DockInstallers.swift"]), ConfigOption(key: "madsync-lock-spin", title: "", kind: .int, defaultValue: "256", category: "Synchronisation", note: "ml1124: the lock is held for well under a microsecond; a contended pthread_mutex_lock sleeps in the kernel (__psynch_mutexwait, ~20 us measured on average in ph-rdr74, 3.4 k times a second). Spin on trylock first. madeira.cfg madsync-loc...", choices: [], sources: ["build/madsync/madsync.c"]), ConfigOption(key: "madsync-spin-us", title: "", kind: .int, defaultValue: "0", category: "Synchronisation", note: "ml1122: madeira.cfg madsync-spin-us (default 0 = sleep at once)", choices: [], sources: ["build/madsync/madsync.c"]), + ConfigOption(key: "yield-depress", title: "", kind: .int, defaultValue: "1", category: "Synchronisation", note: "madeira-duo (6 Nov 2026): no priority depression. Darwin's sched_yield is swtch_pri(0), which drops the thread to priority 0 for up to one quantum (10 ms) whenever anything else is runnable (xnu syscall_subr.c, thread_depress_abstime; Ap...", choices: [], sources: ["wine/dlls/ntdll/unix/sync.c"]), ConfigOption(key: "yield-sleep-us", title: "", kind: .int, defaultValue: "100", category: "Synchronisation", note: "ml1124: madeira.cfg yield-sleep-us (default 100, 0 = never sleep), yield-streak (256)", choices: [], sources: ["wine/dlls/ntdll/unix/sync.c"]), ConfigOption(key: "yield-streak", title: "", kind: .int, defaultValue: "256", category: "Synchronisation", note: "ml1124: madeira.cfg yield-sleep-us (default 100, 0 = never sleep), yield-streak (256)", choices: [], sources: ["wine/dlls/ntdll/unix/sync.c"]), ConfigOption(key: "d3d11", title: "Direct3D 10/11 runtime (x64)", kind: .choice, defaultValue: "", category: "Vulkan routes", note: "Unset: DXMT, Direct3D 10/11 on Metal. \"dxvk\": this session's d3d11.dll, d3d10core.dll and dxgi.dll are DXVK's (Direct3D 10/11 and DXGI on Vulkan, the bundle's vulkan/ folder), replacing DXMT for Direct3D 10/11 and DXGI; Vulkan is on (see vulkan). DXVK's DXGI only presents for Vulkan devices, so Direct3D 12 pairs with vkd3d-proton: with d3d12 unset this implies d3d12 = vkd3d. x64 programs only; read at session start; also from a game's own lines. Experimental, not device-tested.", choices: [("", "DXMT (default)"), ("dxvk", "DXVK on Vulkan")], sources: ["app/Madeira/WineProcessBridge.m"]), @@ -697,6 +745,7 @@ extension ConfigCatalog { ConfigOption(key: "env.MADEIRA_SCREEN_H", title: "", kind: .text, defaultValue: "", category: "Windows, display & input", note: "MADEIRA_SCREEN_W/H: the virtual monitor's session default size, exported by the app before Wine starts (1024x768 when unset); a program's ChangeDisplaySettings changes the current size from there. MADEIRA_SCREEN_SRC names where the defau...", choices: [], sources: ["build/win32u-unix/sysparams_ios.c", "dxmt/src/util/wsi_monitor_headless.cpp", "wine/server/winstation.c"]), ConfigOption(key: "env.MADEIRA_SCREEN_SRC", title: "", kind: .text, defaultValue: "", category: "Windows, display & input", note: "MADEIRA_SCREEN_W/H: the virtual monitor's session default size, exported by the app before Wine starts (1024x768 when unset); a program's ChangeDisplaySettings changes the current size from there. MADEIRA_SCREEN_SRC names where the defau...", choices: [], sources: ["build/win32u-unix/sysparams_ios.c"]), ConfigOption(key: "env.MADEIRA_SCREEN_W", title: "", kind: .text, defaultValue: "", category: "Windows, display & input", note: "MADEIRA_SCREEN_W/H: the virtual monitor's session default size, exported by the app before Wine starts (1024x768 when unset); a program's ChangeDisplaySettings changes the current size from there. MADEIRA_SCREEN_SRC names where the defau...", choices: [], sources: ["build/win32u-unix/sysparams_ios.c", "dxmt/src/d3d9/d3d9_device.cpp", "dxmt/src/util/wsi_monitor_headless.cpp"]), + ConfigOption(key: "env.MADEIRA_SNAP_BORDERLESS", title: "", kind: .text, defaultValue: "", category: "Windows, display & input", note: "", choices: [], sources: ["wine/dlls/win32u/window.c"]), ConfigOption(key: "env.MADEIRA_SURF_SENTINEL", title: "", kind: .text, defaultValue: "", category: "Windows, display & input", note: "them, and I reported the first as settled when the data did not support it. * Fix: after each flush, stamp every currently-zero pixel with a sentinel. That leaves NO zero pixels behind, so the next flush classifies every pixel with no bo...", choices: [], sources: ["app/Madeira/Winios/Winios.m"]), ConfigOption(key: "env.MADEIRA_SURF_SEQ", title: "", kind: .text, defaultValue: "", category: "Windows, display & input", note: "Also drives MADEIRA_SURF_SEQ: bursts of N CONSECUTIVE frames, so the black regions that change every frame can be measured frame-to-frame offline. The 2s-throttled first/latest dump structurally cannot show that. Dirty rect goes in the f...", choices: [], sources: ["app/Madeira/Winios/Winios.m"]), ConfigOption(key: "env.MADEIRA_TINY_WINDOW_FIX", title: "Size a tiny game window to the screen", kind: .bool, defaultValue: "0", category: "Windows, display & input", note: "Default off. 1: a window a swapchain presents into whose client area stays under 160x120 for 3 seconds while the swapchain draws 320x200 or more is sized to the virtual screen (at most twice per window). Needs a desktop (Dock) session. Logged as [tiny-win]. Read at session start.", choices: [], sources: ["build/win32u-unix/driver_ios.c"]), @@ -767,7 +816,10 @@ extension ConfigCatalog { ConfigOption(key: "env.MADEIRA_POWER_GOV_MW", title: "", kind: .text, defaultValue: "", category: "Wine core (ntdll)", note: "process CPU power target (mW) while a game presents; unset/0 = off", choices: [], sources: ["build/ntdll-unix/server_ios.c"]), ConfigOption(key: "env.MADEIRA_PROBES", title: "", kind: .text, defaultValue: "", category: "Wine core (ntdll)", note: "Madeira: MADEIRA_PROBES picks which always-on profilers start, for timing runs: unset/1 = all (as before); \"light\" = only the xprobe ([xp]/[xp-t]/[xp-api], counters read 4x a second, no thread is ever suspended); 0 = none. The thread sam...", choices: [], sources: ["build/ntdll-unix/server_ios.c"]), ConfigOption(key: "env.MADEIRA_PROC_GATE_STEAM", title: "", kind: .text, defaultValue: "", category: "Wine core (ntdll)", note: "ml1357: the full Windows Steam client (steam.exe, started by the in-session launcher or a library entry) runs its own crash reporter, hardware survey and GPU probes. These names were refused because, before ml937, a helper's crash or sel...", choices: [], sources: ["build/ntdll-unix/process_ios.c"]), - ConfigOption(key: "env.MADEIRA_QUIET", title: "", kind: .text, defaultValue: "", category: "Wine core (ntdll)", note: "ml1128 ml1129", choices: [], sources: ["build/ntdll-unix/server_ios.c", "dxmt/src/winemetal/unix/winemetal_unix.c", "app/Madeira/Winios/Winios.m"]), + ConfigOption(key: "env.MADEIRA_PROF", title: "", kind: .text, defaultValue: "", category: "Wine core (ntdll)", note: "ml1128 madeira-duo [prof]: MADEIRA_PROF=1, CPU-time weighted samples of every thread to madeira-prof-*.bin", choices: [], sources: ["build/ntdll-unix/server_ios.c"]), + ConfigOption(key: "env.MADEIRA_PROF_HZ", title: "", kind: .text, defaultValue: "", category: "Wine core (ntdll)", note: "", choices: [], sources: ["build/ntdll-unix/server_ios.c"]), + ConfigOption(key: "env.MADEIRA_PROF_THREADS", title: "", kind: .text, defaultValue: "", category: "Wine core (ntdll)", note: "with MADEIRA_PROF: parts of thread names separated by ';' (FMOD;Main); only threads whose name contains one are sampled or suspended, for a long, cheap profile of a few threads; unset: every thread", choices: [], sources: ["build/ntdll-unix/server_ios.c"]), + ConfigOption(key: "env.MADEIRA_QUIET", title: "", kind: .text, defaultValue: "", category: "Wine core (ntdll)", note: "ml1129", choices: [], sources: ["build/ntdll-unix/server_ios.c", "dxmt/src/winemetal/unix/winemetal_unix.c", "app/Madeira/Winios/Winios.m"]), ConfigOption(key: "env.MADEIRA_RTCS_LOG", title: "", kind: .text, defaultValue: "", category: "Wine core (ntdll)", note: "all: every \"[rtcs] pre\" line; N: at most N a second per thread (default 10, 0 none)", choices: [], sources: ["build/ntdll-unix/loader_ios.c"]), ConfigOption(key: "env.MADEIRA_SC_CEF", title: "Social Club's Chromium in one process", kind: .bool, defaultValue: "1", category: "Wine core (ntdll)", note: "On by default; 0 turns it off. SocialClubHelper.exe runs --single-process with PartitionAllocBackupRefPtr disabled and V8 --jitless (MADEIRA_JITLESS = 0 keeps V8's JIT), its --type= children are refused, and a process with socialclub.dll mapped that is not the helper (the game) gets no JIT-pool copy of libcef.dll: its load fails, as it did when the pool was full. No effect on programs without Social Club.", choices: [], sources: ["build/ntdll-unix/process_ios.c", "build/ntdll-unix/virtual_ios.c"]), ConfigOption(key: "env.MADEIRA_SC_CEF_FLAGS", title: "Extra SocialClubHelper.exe switches", kind: .text, defaultValue: "", category: "Wine core (ntdll)", note: "Appended verbatim to SocialClubHelper.exe's command line while env.MADEIRA_SC_CEF is on, e.g. --disable-gpu or --enable-logging=file --v=1. A --js-flags= in it gets --jitless as its first flag (Chromium keeps only the last --js-flags=), unless MADEIRA_JITLESS = 0.", choices: [], sources: ["build/ntdll-unix/process_ios.c"]), @@ -818,14 +870,19 @@ extension ConfigCatalog { ConfigOption(key: "env.MADEIRA_ARENA_TEST", title: "", kind: .text, defaultValue: "", category: "x86 emulation (FEX)", note: "", choices: [], sources: ["FEX/Source/Windows/Common/ArenaSelfTest.cpp"]), ConfigOption(key: "env.MADEIRA_BLOCK_RING", title: "", kind: .text, defaultValue: "", category: "x86 emulation (FEX)", note: "ml1205: the block-entry ring, when MADEIRA_BLOCK_RING is set (32 KB per thread, never freed).", choices: [], sources: ["FEX/FEXCore/Source/Interface/Core/Core.cpp", "FEX/FEXCore/Source/Interface/Core/JIT/JIT.cpp"]), ConfigOption(key: "env.MADEIRA_CALLRET_RESET_RATE", title: "", kind: .text, defaultValue: "", category: "x86 emulation (FEX)", note: "MADEIRA: rate-limit the call-ret reset that follows a code invalidation. * On the iOS host nothing reads the stack's contents: the RET shortcut (BranchOps.cpp, ml305) and the EnterEC return (Dispatcher.cpp) are compiled out, so a skipped...", choices: [], sources: ["FEX/FEXCore/Source/Interface/Core/Core.cpp"]), + ConfigOption(key: "env.MADEIRA_FEX_ALIAS_FIRST", title: "", kind: .text, defaultValue: "", category: "x86 emulation (FEX)", note: "madeira-duo (20 Nov 2026): alias-first. A pool-copy alias never gets a block (ml315 below), so the fast path's FindBlock under CodeInvalidationMutex could only miss for one, and then ml315 redirected it. Path of Exile 2 calls x64 code in...", choices: [], sources: ["FEX/FEXCore/Source/Interface/Core/Core.cpp"]), ConfigOption(key: "env.MADEIRA_FEX_AVX", title: "", kind: .text, defaultValue: "", category: "x86 emulation (FEX)", note: "iOS-Madeira: MADEIRA_FEX_AVX=2, AVX without AVX2 (see HideAVX2 in CPUID.h). Exactly \"2\"; \"1\" and unset are unchanged.", choices: [], sources: ["FEX/FEXCore/Source/Interface/Core/CPUID.cpp", "FEX/Source/Windows/Common/CPUFeatures.cpp", "build/ntdll-unix/virtual_ios.c"]), ConfigOption(key: "env.MADEIRA_FEX_BRANCH_HISTORY", title: "", kind: .text, defaultValue: "", category: "x86 emulation (FEX)", note: "Recorder emitted only for this executable, before CTX/JIT creation.", choices: [], sources: ["FEX/Source/Windows/ARM64EC/Module.cpp"]), + ConfigOption(key: "env.MADEIRA_FEX_BYTELOOP", title: "", kind: .text, defaultValue: "", category: "x86 emulation (FEX)", note: "madeira-duo byte-copy-loop (OpDispatchBuilder::MatchByteCopyLoop): a block that is exactly a byte-at-a-time copy loop becomes one forward MemCpy. Only where TSO is off for the whole block (the TSO loop orders every byte store, MemCpy doe...", choices: [], sources: ["FEX/FEXCore/Source/Interface/Core/Core.cpp"]), ConfigOption(key: "env.MADEIRA_FEX_CALLRET_ELIDE", title: "64-bit JIT without the call-return shadow stack", kind: .bool, defaultValue: "1", category: "x86 emulation (FEX)", note: "Default on. The 64-bit (ARM64EC) JIT no longer keeps FEX's call-return shadow stack, which nothing reads on iOS: 9 instructions less per guest CALL and per RET, and linked calls become `bl`, so the CPU's return predictor follows guest calls. 0: the stack as before. Read when a program starts.", choices: [], sources: ["FEX/Source/Windows/ARM64EC/Module.cpp"]), + ConfigOption(key: "env.MADEIRA_FEX_CB_FAST", title: "", kind: .text, defaultValue: "", category: "x86 emulation (FEX)", note: "MADEIRA: cache-hit fast path. Nearly every call here is a lookup that L3 answers (the emitted dispatcher only probes L1, and L2 is off on iOS), and the reports, RIP checks and telemetry below ran on every one of them: IosJitReverseTransl...", choices: [], sources: ["FEX/FEXCore/Source/Interface/Core/Core.cpp"]), ConfigOption(key: "env.MADEIRA_FEX_EC_BITMAP_CACHE", title: "Native-code check with the thread's bitmap pointer", kind: .bool, defaultValue: "1", category: "x86 emulation (FEX)", note: "Default on. The 64-bit JIT's dispatcher tests the native-code bitmap through a pointer kept in the thread's state instead of walking TPIDRRO_EL0, the TEB and the PEB: 4 instructions less on every call into a system DLL through its import table. 0: the walk as before. Read when a program starts.", choices: [], sources: ["FEX/Source/Windows/ARM64EC/Module.cpp"]), ConfigOption(key: "env.MADEIRA_FEX_EC_EXIT_LEAN", title: "Lean exit from the JIT into native code", kind: .bool, defaultValue: "1", category: "x86 emulation (FEX)", note: "Default on while AFP is off (the default). Calls from the 64-bit JIT into native (ARM64EC) code use a shorter stub: no FPCR read, the CPU area and suspend doorbell from the thread's state, the call counted per thread instead of with an atomic, and the alias lookup starting at the thread's own last hit; 31 instructions instead of 44. [xp-api] x64->EC rates lag by under 64 calls per thread. 0: ExitFunctionEC as before. Read when a program starts.", choices: [], sources: ["FEX/Source/Windows/ARM64EC/Module.cpp"]), ConfigOption(key: "env.MADEIRA_FEX_EC_RET", title: "Returns from native code through the return predictor", kind: .bool, defaultValue: "1", category: "x86 emulation (FEX)", note: "Default on. A guest call into native (ARM64EC) code leaves the JIT with BLR and its return comes back with RET after an L1 lookup (10 instructions instead of 22), so the CPU's return-address predictor stays in step with the guest's calls. 0: BR and the dispatcher loop as before. Read when a program starts.", choices: [], sources: ["FEX/Source/Windows/ARM64EC/Module.cpp"]), ConfigOption(key: "env.MADEIRA_FEX_EC_RET_DIRECT", title: "Returns from native code straight into the JIT", kind: .bool, defaultValue: "1", category: "x86 emulation (FEX)", note: "Default on. When a native (ARM64EC) function returns to the game's x64 code, the return enters the 64-bit JIT at once instead of testing the native-code bitmap first; the JIT's dispatcher already tests every address it has no translation for. 11 instructions less per return from a system DLL. 0: the test as before. Read when a program starts.", choices: [], sources: ["FEX/Source/Windows/ARM64EC/Module.cpp"]), ConfigOption(key: "env.MADEIRA_FEX_FAIL_CALLRET", title: "", kind: .text, defaultValue: "", category: "x86 emulation (FEX)", note: "MADEIRA_FEX_FAIL_CALLRET=threadstate:N fails the Nth thread-state allocation, so this containment path can be proven rather than assumed -- it only occurs naturally once the band is exhausted.", choices: [], sources: ["FEX/FEXCore/Source/Interface/Core/Core.cpp", "FEX/Source/Windows/Common/CallRetStack.h"]), + ConfigOption(key: "env.MADEIRA_FEX_FREE_SKIP", title: "", kind: .text, defaultValue: "", category: "x86 emulation (FEX)", note: "MADEIRA: MADEIRA_FEX_FREE_SKIP=0 turns off InvalidateCacheRange's cached-page bounds check (and, in InvalidationTracker, the skip for frees of never-executable memory). Read once.", choices: [], sources: ["FEX/FEXCore/Source/Interface/Core/LookupCache.h", "FEX/Source/Windows/Common/InvalidationTracker.cpp"]), + ConfigOption(key: "env.MADEIRA_FEX_L1_HASH", title: "", kind: .text, defaultValue: "", category: "x86 emulation (FEX)", note: "MADEIRA: the L1 index is (rip ^ rip >> 17) & mask instead of rip & mask. 92% of x64 block entries are 16-byte aligned, so the plain mask used 1/16 of the slots and most L1 misses were conflicts between blocks that were already compiled (...", choices: [], sources: ["FEX/FEXCore/Source/Interface/Core/LookupCache.h"]), ConfigOption(key: "env.MADEIRA_FEX_PRELOADED_IMAGES", title: "FEX: record images loaded before it starts", kind: .bool, defaultValue: "1", category: "x86 emulation (FEX)", note: "ml2260: on (default): when FEX starts in a 64-bit process it records the code sections of every image already loaded (kernel32, kernelbase, ucrtbase are mapped for it before its notifications work). Before, their x64 export thunks were not known as code: a 64-bit x64 program's call into one ended it with c0000005 (log 120: the DirectX redistributable's x64 helper, at its first kernel32 call). 0: as before.", choices: [], sources: ["FEX/Source/Windows/ARM64EC/Module.cpp"]), ConfigOption(key: "env.MADEIRA_FEX_SMC_FASTPATH", title: "", kind: .text, defaultValue: "", category: "x86 emulation (FEX)", note: "madeira-bcd: smc-store-fastpath v1. MADEIRA_FEX_SMC_FASTPATH=0 restores the locked path.", choices: [], sources: ["FEX/Source/Windows/ARM64EC/Module.cpp"]), ConfigOption(key: "env.MADEIRA_INVALIDATION_NESTED", title: "", kind: .text, defaultValue: "", category: "x86 emulation (FEX)", note: "MADEIRA: CodeInvalidationMutex is not recursive. When this thread already write-owns it, a second exclusive lock parks the thread behind itself, and every other thread queues behind it for good (log 56: one thread waiting on the lock it ...", choices: [], sources: ["FEX/Source/Windows/Common/InvalidationTracker.cpp"]), @@ -833,6 +890,8 @@ extension ConfigCatalog { ConfigOption(key: "env.MADEIRA_IR_TOPO_MIN", title: "", kind: .text, defaultValue: "", category: "x86 emulation (FEX)", note: "ml599b: only sweep BIG functions. ml599 swept every block after every pass on every compile and that alone stalled the renderer -- it spent as much time in ValidateBlockTopology as in the whole x86 decoder, and Steam never reached the UI...", choices: [], sources: ["FEX/FEXCore/Source/Interface/IR/PassManager.cpp"]), ConfigOption(key: "env.MADEIRA_IRCAP_MODULE", title: "", kind: .text, defaultValue: "", category: "x86 emulation (FEX)", note: "ml623: arm the targeted IR capture (PassManager.cpp) once the module that owns the instruction under investigation is mapped. Module + RVA come from the environment so chasing a different miscompile never needs a rebuild; the defaults ar...", choices: [], sources: ["FEX/Source/Windows/Common/InvalidationTracker.cpp"]), ConfigOption(key: "env.MADEIRA_IRCAP_RVA", title: "", kind: .text, defaultValue: "", category: "x86 emulation (FEX)", note: "ml623: arm the targeted IR capture (PassManager.cpp) once the module that owns the instruction under investigation is mapped. Module + RVA come from the environment so chasing a different miscompile never needs a rebuild; the defaults ar...", choices: [], sources: ["FEX/Source/Windows/Common/InvalidationTracker.cpp"]), + ConfigOption(key: "env.MADEIRA_JITCODE", title: "", kind: .text, defaultValue: "", category: "x86 emulation (FEX)", note: "", choices: [], sources: ["FEX/Source/Windows/ARM64EC/Module.cpp"]), + ConfigOption(key: "env.MADEIRA_JITMAP", title: "", kind: .text, defaultValue: "", category: "x86 emulation (FEX)", note: "", choices: [], sources: ["FEX/Source/Windows/ARM64EC/Module.cpp"]), ConfigOption(key: "env.MADEIRA_NO_DFE", title: "", kind: .text, defaultValue: "", category: "x86 emulation (FEX)", note: "iOS-Madeira ml597: TARGETED A/B for the ml594 post-login hang. The renderer thread was sampled 9x at 97-100% CPU inside DeadFlagCalculationEliminination while everything else idled and Steam presented no further frames. FEX_O0 is the wro...", choices: [], sources: ["FEX/FEXCore/Source/Interface/IR/PassManager.cpp"]), ConfigOption(key: "env.MADEIRA_SMC_HOT_PAGE", title: "", kind: .text, defaultValue: "", category: "x86 emulation (FEX)", note: "MADEIRA: hot SMC pages (InvalidationTracker::EnableHotSMCPages). MADEIRA_SMC_HOT_PAGE: unset = 64 write faults within a second, 0 = off (every write to a code page invalidates it), N = threshold.", choices: [], sources: ["FEX/Source/Windows/ARM64EC/Module.cpp", "FEX/Source/Windows/WOW64/Module.cpp"]), ConfigOption(key: "env.MADEIRA_STRICT_SPLITLOCK", title: "", kind: .text, defaultValue: "", category: "x86 emulation (FEX)", note: "MADEIRA: StrictInProcessSplitLocks defaults ON for 32-bit guests. * An x86 LOCK op on a word that crosses a 16-byte boundary faults on this host and FEX emulates it as two separate half-width CASes. Without the strict mode two threads do...", choices: [], sources: ["FEX/Source/Windows/WOW64/Module.cpp"]), diff --git a/app/Madeira/FPSOverlay.swift b/app/Madeira/FPSOverlay.swift index 69481f420e..44176a2d34 100644 --- a/app/Madeira/FPSOverlay.swift +++ b/app/Madeira/FPSOverlay.swift @@ -78,12 +78,13 @@ final class ProMotionIntent { // `minimum` must not exceed the panel's own maximum or CoreAnimation // clamps the whole range away (a 60Hz device asked for min 60 / // max 120 gets nothing useful). - let lo = Float(min(60, maxHz)) + let lo = ProMotionIntent.pinnedHz > 0 ? want : Float(min(60, maxHz)) // madeira-duo panel-hz: a fixed rate l.preferredFrameRateRange = CAFrameRateRange(minimum: lo, maximum: want, preferred: want) l.add(to: .main, forMode: .common) link = l activeMax = want displaySyncApplied = false; armedAt = 0; tickStart = 0 // ml2021: per arming + kickWanted = false fputs("[promote] display link armed preferred=\(Int(want))Hz panel_max=\(ProMotionIntent.panelMaxFPS)Hz\n", stderr) // ml2020: stderr written before Wine starts is not in the exported log; say it there too LogStore.shared.log("[promote] display link armed min=\(Int(lo))Hz preferred=\(Int(want))Hz panel_max=\(ProMotionIntent.panelMaxFPS)Hz") @@ -96,8 +97,20 @@ final class ProMotionIntent { } } + /// madeira-duo (6 Nov 2026): `panel-hz = N` in madeira.cfg pins the panel to N Hz + /// (minimum = preferred = maximum = N) for every FPS limit, overriding the intents + /// below. iPhone ProMotion rates include 120, 80, 60, 48, 40, 30 and 24 (Apple, + /// "Optimizing iPhone and iPad apps to support ProMotion displays"); iOS may still pick + /// another. A 40 FPS limit on a 40 Hz panel wakes the main thread a third as often as + /// at 120 Hz, but a frame that misses 25 ms then waits until 50 ms. Unset or 0: off. + static var pinnedHz: Int { + guard let text = MadeiraConfig.get("panel-hz"), let hz = Int(text), hz > 0 else { return 0 } + return min(hz, panelMaxFPS) + } + /// The intent that belongs to a given pacing mode (0 = none). See the type comment. static func maxHz(for mode: Int32) -> Int { + if pinnedHz > 0 { return pinnedHz } let floor = panelFloor ? min(60, panelMaxFPS) : 0 // ml2020: see panelFloor if mode == 3 { return holdMaximum ? min(60, panelMaxFPS) : floor } // 30 cap if mode == 1 { return holdMaximum ? panelMaxFPS : floor } // 60 cap @@ -107,7 +120,7 @@ final class ProMotionIntent { /// Arms or releases the link for `mode` and publishes the rates to DXMT. static func apply(mode: Int32) { let hz = maxHz(for: mode) - LogStore.shared.log("[promote] pacing mode \(mode): display intent \(hz) Hz (panel max \(panelMaxFPS), hold-maximum \(holdMaximum), floor \(panelFloor))") + LogStore.shared.log("[promote] pacing mode \(mode): display intent \(hz) Hz (panel max \(panelMaxFPS), hold-maximum \(holdMaximum), floor \(panelFloor), panel-hz \(pinnedHz))") shared.setActive(hz > 0, maxHz: hz) madeira_set_display_max_fps(Int32(panelMaxFPS), Int32(hz)) } @@ -127,6 +140,10 @@ final class ProMotionIntent { /// drawable waits fall with this on, that is what the display link alone does not do. private var kickLayer: CALayer? private var kickOn = false + /// madeira-duo: `kickEnabled` as read once per arming (with display sync, a second after the link starts). + /// Reading it on every tick cost two stat() calls on madeira.cfg plus string building each time: + /// 160 stats a second on the main thread at panel-hz 80, 44% of that thread's samples in a profile. + private var kickWanted = false static var kickEnabled: Bool { MadeiraConfig.flag("MADEIRA_PROMOTE_KICK", fallback: false) } /// ml2021: env.MADEIRA_DISPLAY_SYNC applied to the game's layer once the session's @@ -138,6 +155,7 @@ final class ProMotionIntent { private func applyDisplaySync(now: CFTimeInterval) { guard !displaySyncApplied, now - armedAt >= 1 else { return } displaySyncApplied = true + kickWanted = ProMotionIntent.kickEnabled let layer = MetalHostView.shared.metalLayer let sel = NSSelectorFromString("setDisplaySyncEnabled:") guard layer.responds(to: sel) else { return } @@ -164,7 +182,7 @@ final class ProMotionIntent { (sender.targetTimestamp - sender.timestamp) * 1000)) tickStart = now; tickCount = 1; tickMaxGap = 0 } - if ProMotionIntent.kickEnabled { kick() } + if kickWanted { kick() } } private func kick() { diff --git a/app/Madeira/GuestDisplay.swift b/app/Madeira/GuestDisplay.swift index 277db9002d..0d7434444e 100644 --- a/app/Madeira/GuestDisplay.swift +++ b/app/Madeira/GuestDisplay.swift @@ -17,7 +17,7 @@ import UIKit /// How the guest surface is mapped into the view's bounds. enum DisplayMode: String, CaseIterable { - case fit, fill, stretch, aspect + case fit, fill, stretch, aspect, blend /// Older settings stored "fitHeight" (Fill height); it behaved as Fit in /// landscape and is gone from the picker, so it decodes to Fit. @@ -27,6 +27,7 @@ enum DisplayMode: String, CaseIterable { case "fill": self = .fill case "stretch": self = .stretch case "aspect": self = .aspect + case "blend": self = .blend default: return nil } } @@ -37,6 +38,7 @@ enum DisplayMode: String, CaseIterable { case .fill: return "Fill" case .stretch: return "Stretch" case .aspect: return "Aspect" + case .blend: return "Blend" } } var symbol: String { @@ -45,6 +47,7 @@ enum DisplayMode: String, CaseIterable { case .fill: return "arrow.up.left.and.arrow.down.right" case .stretch: return "rectangle.expand.vertical" case .aspect: return "rectangle.ratio.16.to.9" + case .blend: return "rectangle.compress.vertical" } } } @@ -65,14 +68,24 @@ enum GameSurfaceLayout { /// game whose back buffer is 4:3 on a 16:9 monitor is stretched by the /// layer in every other mode; here it is scaled uniformly. Falls back to /// the guest shape until a drawable size is known (`aspect == .zero`). + /// - Blend: halfway between Fill and Stretch. The picture takes the + /// geometric mean of the guest's shape and `bounds`'s and covers + /// `bounds`, so half of the shape difference is cropped and half is + /// stretched (madeira-duo: PoE2 draws 16:10 at the narrowest, the + /// unfolded Duo is ~1.42:1; Stretch squashed it 11%, Fill cropped 5.5% + /// a side, Blend is ~5.5% squash and ~3% a side). static func rect(guest: CGSize, aspect: CGSize = .zero, bounds: CGRect, mode: DisplayMode) -> CGRect { guard guest.width > 0, guest.height > 0, bounds.width > 0, bounds.height > 0 else { return bounds } if mode == .stretch { return bounds } let useDrawable = mode == .aspect && aspect.width > 0 && aspect.height > 0 - let shape = useDrawable ? aspect : guest + var shape = useDrawable ? aspect : guest + if mode == .blend { + let guestAspect = guest.width / guest.height, boundsAspect = bounds.width / bounds.height + shape = CGSize(width: (guestAspect * boundsAspect).squareRoot(), height: 1) + } let sx = bounds.width / shape.width, sy = bounds.height / shape.height - let scale = mode == .fill ? max(sx, sy) : min(sx, sy) + let scale = mode == .fill || mode == .blend ? max(sx, sy) : min(sx, sy) let w = shape.width * scale, h = shape.height * scale return CGRect(x: bounds.minX + (bounds.width - w) / 2, y: bounds.minY + (bounds.height - h) / 2, diff --git a/app/Madeira/Library.swift b/app/Madeira/Library.swift index 651c0d2515..042834526c 100644 --- a/app/Madeira/Library.swift +++ b/app/Madeira/Library.swift @@ -4097,13 +4097,14 @@ struct LibraryDetail: View { } /// The pages the details page links to (iOS Settings style), each with its own Form. enum Page: Hashable { - case display, controls, launch, compatibility, steam, cloud, achievements, gog, itch, library, iniFiles, advanced + case display, controls, launch, compatibility, shaders, steam, cloud, achievements, gog, itch, library, iniFiles, advanced var title: String { switch self { case .display: return "Display" case .controls: return "Controls" case .launch: return "Launch" case .compatibility: return "Compatibility" + case .shaders: return "Shaders" case .steam: return "Steam" case .cloud: return "Steam Cloud" case .workshop: return "Steam Workshop" @@ -4121,6 +4122,7 @@ struct LibraryDetail: View { case .controls: return "gamecontroller" case .launch: return "terminal" case .compatibility: return "cpu" + case .shaders: return "hammer" case .steam: return "shippingbox" case .cloud: return "icloud" case .workshop: return "square.stack.3d.up" @@ -4143,7 +4145,7 @@ struct LibraryDetail: View { let steam: [Page] = entry.steamAppID == nil ? (entry.gogProductID != nil ? [.gog] : entry.itchGameID != nil ? [.itch] : []) : (SteamOwnedLibrary.cloudEnabled ? [.steam, .cloud, .achievements] : [.steam, .achievements]) + (SteamOwnedLibrary.workshopEnabled && Self.showsWorkshop(entry.steamAppID) ? [.workshop] : []) - let tuning: [Page] = launch ? [.display, .controls, .launch, .compatibility] : [.display, .controls, .compatibility] + let tuning: [Page] = launch ? [.display, .controls, .launch, .compatibility, .shaders] : [.display, .controls, .compatibility, .shaders] let more: [Page] = entry.desktop == true ? [.advanced] : [.library, .iniFiles, .advanced] return [tuning, steam, more].filter { !$0.isEmpty } } @@ -4175,6 +4177,7 @@ struct LibraryDetail: View { case .controls: controlsPage case .launch: launchPage case .compatibility: compatibilityPage + case .shaders: ShaderCacheSection() case .steam: steamPage case .cloud: if let appID = entry.steamAppID { SteamCloudSection(appID: appID) } case .workshop: @@ -4659,6 +4662,94 @@ struct BCDGameValues { /// syntax, applied at its next start. madeira-bcd: LibraryDetail binds it to the /// game's GameProfiles.swift file (Application Support/GameConfigs), which every /// launch exports as MADEIRA_CFG_GAME (BCDLaunch, MadeiraConfig.applyGame). +/// madeira-duo vk3: the shader caches in the prefix, how big each is, and a compile of the recorded +/// Vulkan pipelines before a game starts (madeira_shader_precompile_start, WineProcessBridge.m), with +/// its progress. The caches are shared by every game in the prefix. +struct ShaderCacheSection: View { + struct Folder: Identifiable { let name: String; let bytes: Int64; var id: String { name } } + @State private var sizes: [Folder] = [] + @State private var done: UInt32 = 0 + @State private var total: UInt32 = 0 + @State private var state: Int32 = 0 + @State private var seconds = 0.0 + @State private var message: String? + private let ticks = Timer.publish(every: 1, on: .main, in: .common).autoconnect() + + private static var documents: URL { FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! } + /// (name, folder under Documents). LOCALAPPDATA is drive_c/users/mobile/AppData/Local. + private static let folders: [(String, String)] = [ + ("Vulkan: Mesa shader cache", "wine/madeira-cache/kosmickrisp/mesa_shader_cache"), + ("Vulkan: Metal pipeline archives", "wine/madeira-cache/kosmickrisp/kosmickrisp-mtl4"), + ("Vulkan: recorded pipelines", "wine/madeira-cache/fossilize"), + ("D3D12: converted shaders", "shadercache"), + ("D3D12: shader cache", "wine/drive_c/users/mobile/AppData/Local/Madeira/ShaderCache"), + ("D3D12: pipeline archive", "wine/drive_c/users/mobile/AppData/Local/Madeira/PipelineArchive"), + ] + + private static func folderBytes(_ url: URL) -> Int64 { + guard let walker = FileManager.default.enumerator(at: url, includingPropertiesForKeys: [.totalFileAllocatedSizeKey, .isRegularFileKey]) else { return -1 } + var bytes: Int64 = 0 + for case let file as URL in walker { + guard let values = try? file.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .isRegularFileKey]), + values.isRegularFile == true else { continue } + bytes += Int64(values.totalFileAllocatedSize ?? 0) + } + return bytes + } + + private func measure() { + Task.detached(priority: .utility) { + let measured = Self.folders.map { Folder(name: $0.0, bytes: Self.folderBytes(Self.documents.appendingPathComponent($0.1))) } + await MainActor.run { sizes = measured } + } + } + + private func poll() { + var d: UInt32 = 0, t: UInt32 = 0, st: Int32 = 0, secs = 0.0 + madeira_shader_precompile_status(&d, &t, &st, &secs) + let finished = state == 1 && st != 1 + done = d; total = t; state = st; seconds = secs + if finished { measure() } + } + + private var progressText: String { + let rate = seconds > 0 ? Double(done) / seconds : 0 + var text = total > 0 ? "\(done) of \(total) pipelines" : "\(done) pipelines" + if rate > 0 { text += String(format: " · %.0f/s", rate) } + if rate > 0, total > done { text += String(format: " · about %.0f s left", Double(total - done) / rate) } + return text + } + + var body: some View { + Section { + ForEach(sizes) { entry in + LabeledContent(entry.name, value: entry.bytes < 0 ? "–" : ByteCountFormatter.string(fromByteCount: entry.bytes, countStyle: .file)) + } + Button("Compile shaders now", systemImage: "hammer") { + switch madeira_shader_precompile_start() { + case 0: message = nil; state = 1 + case -1: message = L("A shader compile is already running.") + default: message = L("Needs vulkan = kosmickrisp in madeira.cfg.") + } + } + .disabled(state == 1) + if state == 1 { + ProgressView(value: Double(done), total: Double(max(total, max(done, 1)))) + Text(progressText).font(.caption.monospacedDigit()) + } else if state == 2 { + Text(String(format: L("Last compile: %u pipelines in %.0f s."), done, seconds)).font(.caption) + } else if state == 3 { + Text("The last compile stopped with an error; the log has the [fossilize] lines.").font(.caption).foregroundStyle(.red) + } + if let message { Text(message).font(.caption).foregroundStyle(.secondary) } + } header: { Text("Shaders") } footer: { + Text("Compiles the Vulkan pipelines Madeira recorded while you played (vulkan = kosmickrisp, fossilize = on) on every core, before the game starts. A game started meanwhile waits for it. The same replay runs at each game start.") + } + .onAppear { measure(); poll() } + .onReceive(ticks) { _ in poll() } + } +} + struct LibraryGameConfigEditor: View { @Binding var text: String var body: some View { @@ -6105,7 +6196,7 @@ enum OverlayStyle { static let layouts: [(id: String, name: String)] = [("grid", "Grid"), ("row", "One row"), ("column", "Column")] static let backgrounds: [(id: String, name: String)] = [("glass", "Glass"), ("dark", "Dark"), ("clear", "None")] /// The figures the overlay can show, in the order of the menu's switches. - static let fields = ["FPS", "Frame time", "1% lows", "0.1% lows", "Frame graph", "CPU", "GPU", "RAM", "JIT memory", "Swap & donor", "Battery", "Thermal"] + static let fields = ["FPS", "Frame time", "1% lows", "0.1% lows", "Frame graph", "CPU", "GPU", "Shader misses", "RAM", "JIT memory", "Swap & donor", "Battery", "Thermal"] } /// Frame times from the present path (madeira_frame_times_us, Winios.m) and the @@ -6246,6 +6337,27 @@ struct LibraryMetrics: View { @State private var donatedMB = 0 @State private var donorPoolMB = 0 @State private var donorGuarded = 0 + /// madeira-duo overlay-shader: madeira_shader_overlay_stats (winemetal_unix.c). Totals since the + /// overlay started showing them (vk4: totals, not rates, so the figures don't drop back to zero + /// between bursts): shader stages madeira-d3d12's cache did not have (converted), and pipelines + /// Metal compiled because the pso-archive did not have them; right now, the pipelines the game + /// waits on (pso-async queue, and pso-create-block builds inside a create call) and the + /// create-time queue behind them; the flags it gave. + @State private var shaderPrimed = false + @State private var baseShaderMisses: UInt64 = 0 + @State private var basePipelineMisses: UInt64 = 0 + @State private var shaderTotal = 0 + @State private var pipelineTotal = 0 + @State private var psoQueue = 0 + @State private var psoBackground = 0 + @State private var shaderFlags = 0 + /// madeira-duo vk3/vk4: Vulkan builds KosmicKrisp reported (madeira_vulkan_compile_stats): compiles since + /// the overlay started showing them, builds running now, slow compiles since the game started. + @State private var baseVulkanCompiles: UInt64 = 0 + @State private var vulkanTotal = 0 + @State private var vulkanInFlight = 0 + @State private var vulkanSlow = 0 + @State private var vulkanSeen = false /// Half-second ticks; the figures change every `refresh` seconds (0.5, 1 or 2). private let ticks = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect() /// ml2021: one cell per figure. A fixed width per cell (the widest value it can show) @@ -6296,6 +6408,20 @@ struct LibraryMetrics: View { if donorPoolMB > 0 { result.append(Cell(id: "donor", label: "DONOR", value: "\(donatedMB)", width: 54)) } result.append(Cell(id: "swap", label: "SWAP", value: "\(swapFileMB)", width: 54)) } + if model.overlayFields.contains("Shader misses") { + if vulkanSeen { + // Vulkan (KosmicKrisp): compiles so far, builds running now, slow compiles this game. + result.append(Cell(id: "miss", label: "BUILT", value: "\(vulkanTotal)", width: 64)) + result.append(Cell(id: "psoq", label: "BUILD", value: "\(vulkanInFlight)", width: 50)) + result.append(Cell(id: "slow", label: "SLOW", value: "\(vulkanSlow)", width: 54)) + } else { + // D3D12: shaders converted and pipelines compiled so far, pipelines the game waits on now. + let known = shaderPrimed && shaderFlags & 1 != 0 + result.append(Cell(id: "miss", label: "SHADERS", value: known ? "\(shaderTotal)" : "–", width: 64)) + result.append(Cell(id: "pso", label: "PSO", value: known && shaderFlags & 8 != 0 ? "\(pipelineTotal)" : "–", width: 56)) + result.append(Cell(id: "psoq", label: "WAIT", value: shaderFlags & 1 == 0 ? "–" : shaderFlags & 4 == 0 ? "off" : "\(psoQueue)", width: 50)) + } + } if model.overlayFields.contains("Battery"), battery >= 0 { result.append(Cell(id: "bat", label: "BAT", value: "\(battery)%", width: 50)) } if model.overlayFields.contains("Thermal") { let (word, dot): (String, Color) = { @@ -6432,6 +6558,29 @@ struct LibraryMetrics: View { madeira_swap_overlay_stats(&file, &donated, &pool, &guarded) swapFileMB = Int(file); donatedMB = Int(donated); donorPoolMB = Int(pool); donorGuarded = Int(guarded) } + if model.overlayFields.contains("Shader misses") { + var shaders: UInt64 = 0, pipelines: UInt64 = 0, queue: Int64 = 0, background: Int64 = 0, flags: Int32 = 0 + _ = madeira_shader_overlay_stats_optional(&shaders, &pipelines, &queue, &background, &flags) + var vkBuilds: UInt64 = 0, vkCompiles: UInt64 = 0, vkSlow: UInt64 = 0, vkMs: UInt64 = 0 + var vkInFlight: Int64 = 0, vkLibraries: UInt64 = 0, vkPipelines: UInt64 = 0 + madeira_vulkan_compile_stats(&vkBuilds, &vkCompiles, &vkSlow, &vkMs, &vkInFlight, &vkLibraries, &vkPipelines) + // The counters run for the app (a new game's madeira-d3d12 block starts at + // zero again): totals count from the first sample, and a counter that went + // backwards (a new game process) counts from zero. + if vkBuilds > 0 { + if !vulkanSeen || vkCompiles < baseVulkanCompiles { baseVulkanCompiles = vulkanSeen ? 0 : vkCompiles } + vulkanSeen = true + vulkanTotal = Int(vkCompiles - baseVulkanCompiles) + vulkanInFlight = Int(vkInFlight); vulkanSlow = Int(vkSlow) + } + if !shaderPrimed { baseShaderMisses = shaders; basePipelineMisses = pipelines; shaderPrimed = true } + if shaders < baseShaderMisses { baseShaderMisses = 0 } + if pipelines < basePipelineMisses { basePipelineMisses = 0 } + shaderTotal = Int(shaders - baseShaderMisses); pipelineTotal = Int(pipelines - basePipelineMisses) + psoQueue = Int(queue); psoBackground = Int(background); shaderFlags = Int(flags) + } else if shaderPrimed { + shaderPrimed = false; shaderTotal = 0; pipelineTotal = 0 + } if model.overlayFields.contains("GPU") { let busy = madeira_gpu_meter_busy_seconds(), buffers = madeira_gpu_meter_cmdbufs() let used = max(0, busy - lastGPUBusy) @@ -6474,6 +6623,17 @@ struct LibraryMetrics: View { } result.append("Swap \(swapFileMB) MB") } + if model.overlayFields.contains("Shader misses"), vulkanSeen { + result.append("\(vulkanTotal) shaders compiled, \(vulkanInFlight) building, \(vulkanSlow) slow") + } else if model.overlayFields.contains("Shader misses") { + if !shaderPrimed || shaderFlags & 1 == 0 { result.append("Shader misses —") } + else if shaderFlags & 8 != 0 { + result.append("\(shaderTotal) shaders converted, \(pipelineTotal) pipelines compiled") + } else { result.append("\(shaderTotal) shaders converted") } + if shaderFlags & 1 == 0 { result.append("Pipeline queue —") } + else if shaderFlags & 4 == 0 { result.append("Pipeline queue off") } + else { result.append("Pipeline queue \(psoQueue) (\(psoBackground) queued at creation)") } + } if model.overlayFields.contains("Battery"), battery >= 0 { result.append("\(battery)%") } if model.overlayFields.contains("Thermal") { switch thermal { diff --git a/app/Madeira/Madeira-Bridging-Header.h b/app/Madeira/Madeira-Bridging-Header.h index 90d000dbb8..574cb2918a 100644 --- a/app/Madeira/Madeira-Bridging-Header.h +++ b/app/Madeira/Madeira-Bridging-Header.h @@ -59,6 +59,16 @@ void madeira_swap_overlay_stats(unsigned long long *file_mb, unsigned long long unsigned long long *donor_guarded); double madeira_gpu_meter_busy_seconds(void); uint64_t madeira_gpu_meter_cmdbufs(void); +/// madeira-duo vk3: Vulkan builds KosmicKrisp reported (Winios/WiniosGL.m), cumulative: all builds, +/// the ones that compiled (2 ms or more; the rest came from a cache), the slow ones (150 ms or more), +/// their total ms, builds running now, and the compiled ones split into libraries and pipelines. +void madeira_vulkan_compile_stats(uint64_t *builds, uint64_t *compiles, uint64_t *slow, uint64_t *compile_ms, + int64_t *in_flight, uint64_t *libraries, uint64_t *pipelines); +/// madeira-duo vk3: madeira_shader_overlay_stats (DXMT winemetal, D3D12 shader-cache and pso-archive misses, +/// pso-async queue), looked up at run time. Returns 0, all zero, when this build's DXMT lacks it. +/// flags: 1 madeira-d3d12's counters are there, 2 its shader cache is on, 4 pso-async is on, 8 the pso-archive is in use. +int madeira_shader_overlay_stats_optional(unsigned long long *shader_misses, unsigned long long *pipeline_misses, + long long *pso_queue, long long *pso_background, int *flags); // ml1098: ask the D3D12 runtime to capture the next N frames (winemetal_unix.c) void madeira_capture_request(int frames); // ml1133: ECO switch (ntdll unix sync.c). 1 = every guest thread drops to a diff --git a/app/Madeira/WineProcessBridge.h b/app/Madeira/WineProcessBridge.h index 70cabd2c42..df37630a05 100644 --- a/app/Madeira/WineProcessBridge.h +++ b/app/Madeira/WineProcessBridge.h @@ -59,6 +59,15 @@ int madeira_write_continue_flag(void); // Madeira Dock's component setup calls it before writing Steam's registry keys. void madeira_seed_prefix_if_needed(const char *prefix_path); +// madeira-duo vk3: compile shaders before a game starts (Library ▸ Shaders). Replays the recorded +// Vulkan pipelines (madeira-cache/fossilize) through KosmicKrisp on every core, filling its caches. +// 0 started, -1 a replay is already running, -2 vulkan isn't kosmickrisp in madeira.cfg. +// A game started meanwhile waits for it. +int madeira_shader_precompile_start(void); +// Progress of the running or last replay (pre-launch or at game start): pipelines done and in the +// recordings; state 0 idle, 1 running, 2 done, 3 failed; seconds running, or the last one took. +void madeira_shader_precompile_status(uint32_t *done, uint32_t *total, int *state, double *seconds); + #ifdef __cplusplus } #endif diff --git a/app/Madeira/WineProcessBridge.m b/app/Madeira/WineProcessBridge.m index d528ab5e69..a68f517619 100644 --- a/app/Madeira/WineProcessBridge.m +++ b/app/Madeira/WineProcessBridge.m @@ -1068,6 +1068,221 @@ static int madeira_link_vulkan_file(NSFileManager *fm, NSString *dir, NSString * return [fm createSymbolicLinkAtPath:dst withDestinationPath:src error:nil] ? 1 : 0; } +/* madeira-duo vk2: Fossilize (Valve's pipeline record/replay, the mechanism behind Steam's shader + * pre-caching), madeira.cfg + * fossilize = record | replay | on | off (default off) + * record: the session's Vulkan goes through the Khronos loader (gl/libvulkan.1.dylib) with the + * driver from gl/vulkan/icd.d and the capture layer VK_LAYER_fossilize (gl/vulkan/explicit_layer.d), + * which writes every pipeline the game creates to /madeira-cache/fossilize/capture.*.foz. + * KosmicKrisp only: MoltenVK is a portability driver the loader hides from Wine. + * replay: before the session starts, every .foz in that folder (and in its import/ subfolder, for + * databases recorded elsewhere) is replayed in-process through the session's driver + * (gl/libfossilize_replay.dylib), which fills the driver's own caches (KosmicKrisp: Mesa disk cache + * and Metal 4 archives). --replayer-cache keeps a list of what was already replayed, so later + * sessions only build new entries. Once per app process. + * on: both. fossilize-threads = N (default: every core) sets the replay worker count. */ +/* madeira-duo vk3: one replay at a time (a pre-launch compile from the Library or the replay at + * game start), with progress for the Library's Shaders page and the overlay. */ +static pthread_mutex_t fossilize_replay_lock = PTHREAD_MUTEX_INITIALIZER; +static _Atomic int fossilize_replay_state; /* 0 idle, 1 running, 2 done, 3 failed */ +static _Atomic double fossilize_replay_started; /* CLOCK_MONOTONIC seconds */ +static _Atomic double fossilize_replay_seconds; /* duration of the last finished replay */ +static _Atomic uint32_t fossilize_replay_last_done, fossilize_replay_last_total; +static void (*fossilize_replay_progress_fn)(uint32_t *, uint32_t *); +static BOOL fossilize_replayed; /* a replay finished in this app process */ + +static double madeira_monotonic_seconds(void) +{ + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + return now.tv_sec + now.tv_nsec / 1e9; +} + +/* Replay every .foz in `dir` and dir/import through `driver`. Called with fossilize_replay_lock held. */ +static int madeira_fossilize_replay_locked(NSFileManager *fm, NSString *gl, NSString *driver, NSString *dir, + const char *threads) +{ + NSMutableArray *databases = [NSMutableArray array]; + for (NSString *folder in @[dir, [dir stringByAppendingPathComponent:@"import"]]) + for (NSString *name in [[fm contentsOfDirectoryAtPath:folder error:nil] sortedArrayUsingSelector:@selector(compare:)]) + if ([name hasSuffix:@".foz"] && ![name hasPrefix:@"replayed.cache"]) + [databases addObject:[folder stringByAppendingPathComponent:name]]; + if (databases.count == 0) { + dprintf(STDERR_FILENO, "[fossilize] replay: no .foz in %s yet\n", dir.UTF8String); + return 1; + } + NSString *replayer = [gl stringByAppendingPathComponent:@"libfossilize_replay.dylib"]; + void *handle = dlopen(replayer.fileSystemRepresentation, RTLD_NOW | RTLD_LOCAL); + int (*replay_main)(int, char **) = handle ? (int (*)(int, char **))dlsym(handle, "fossilize_replay_main") : NULL; + if (!replay_main) { + dprintf(STDERR_FILENO, "[fossilize] replay: can't load %s: %s\n", replayer.UTF8String, dlerror()); + return -1; + } + fossilize_replay_progress_fn = (void (*)(uint32_t *, uint32_t *))dlsym(handle, "fossilize_replay_progress"); + + NSString *replayed_list = [dir stringByAppendingPathComponent:@"replayed.cache"]; + NSMutableArray *args = [NSMutableArray arrayWithObject:@"fossilize-replay"]; + [args addObjectsFromArray:databases]; + [args addObjectsFromArray:@[@"--num-threads", [NSString stringWithUTF8String:threads], + @"--replayer-cache", replayed_list]]; + char **argv = calloc(args.count + 1, sizeof(char *)); + for (NSUInteger i = 0; i < args.count; i++) argv[i] = strdup(args[i].UTF8String); + + setenv("FOSSILIZE_VULKAN_LIBRARY", driver.fileSystemRepresentation, 1); + dprintf(STDERR_FILENO, "[fossilize] replay: %lu database(s) through %s, %s thread(s)\n", + (unsigned long)databases.count, driver.lastPathComponent.UTF8String, threads); + double start = madeira_monotonic_seconds(); + fossilize_replay_started = start; + fossilize_replay_state = 1; + /* Sample the replayer's progress while it runs, so the totals are known even when nothing polls + * (the replay at game start) and the last figures survive the replay's end. */ + fossilize_replay_last_done = 0; + fossilize_replay_last_total = 0; + if (fossilize_replay_progress_fn) + dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{ + while (fossilize_replay_state == 1) { + uint32_t d = 0, t = 0; + fossilize_replay_progress_fn(&d, &t); + if (t) { fossilize_replay_last_done = d; fossilize_replay_last_total = t; } + usleep(200000); + } + }); + int code = replay_main((int)args.count, argv); + fossilize_replay_seconds = madeira_monotonic_seconds() - start; + unsetenv("FOSSILIZE_VULKAN_LIBRARY"); + dprintf(STDERR_FILENO, "[fossilize] replay: finished in %.1f s (exit %d), %u of %u pipelines\n", + fossilize_replay_seconds, code, fossilize_replay_last_done, fossilize_replay_last_total); + for (NSUInteger i = 0; i < args.count; i++) free(argv[i]); + free(argv); + fossilize_replay_state = code == 0 ? 2 : 3; + if (code == 0) fossilize_replayed = YES; + return code == 0 ? 0 : -1; +} + +/* Replay worker count: every core unless madeira.cfg `key` sets a number. madeira_cfg_get empties its + * buffer when the key is unset, so read into a scratch buffer (an empty --num-threads made Fossilize's + * stoul throw and abort the app, install33, 10 Nov 2026). */ +static void madeira_fossilize_threads(const char *key, char *out, size_t cap) +{ + snprintf(out, cap, "%d", (int)MAX(1, [NSProcessInfo processInfo].activeProcessorCount)); + char v[16]; + if (madeira_cfg_get(key, v, sizeof v) && atoi(v) > 0) snprintf(out, cap, "%d", atoi(v)); +} + +/* The replay at game start: waits for a pre-launch compile still running, and skips the replay when + * one already finished in this app process (the caches are warm; what the game records next is + * replayed at the next app start). */ +static void madeira_fossilize_replay(NSFileManager *fm, NSString *gl, NSString *driver, NSString *dir) +{ + if (fossilize_replay_state == 1) + dprintf(STDERR_FILENO, "[fossilize] replay: waiting for the shader compile that is running\n"); + pthread_mutex_lock(&fossilize_replay_lock); + if (!fossilize_replayed) { + /* The game waits for this replay, so it gets every core unless fossilize-threads says otherwise. */ + char threads[16]; + madeira_fossilize_threads("fossilize-threads", threads, sizeof threads); + madeira_fossilize_replay_locked(fm, gl, driver, dir, threads); + } else { + dprintf(STDERR_FILENO, "[fossilize] replay: already done in this app run (%.1f s); skipped\n", + fossilize_replay_seconds); + } + pthread_mutex_unlock(&fossilize_replay_lock); +} + +/* KosmicKrisp's cache locations; the same at game start and for a pre-launch compile. */ +static void madeira_kosmickrisp_cache_env(NSFileManager *fm, NSString *prefix) +{ + NSString *cache = [prefix stringByAppendingPathComponent:@"madeira-cache/kosmickrisp"]; + [fm createDirectoryAtPath:cache withIntermediateDirectories:YES attributes:nil error:nil]; + char v[1024]; + if (madeira_cfg_get("env.MESA_SHADER_CACHE_DIR", v, sizeof v) && v[0]) setenv("MESA_SHADER_CACHE_DIR", v, 0); + if (madeira_cfg_get("env.MESA_SHADER_CACHE_MAX_SIZE", v, sizeof v) && v[0]) setenv("MESA_SHADER_CACHE_MAX_SIZE", v, 0); + setenv("MESA_SHADER_CACHE_DIR", cache.fileSystemRepresentation, 0); + setenv("MESA_SHADER_CACHE_MAX_SIZE", "2G", 0); +} + + +int madeira_shader_precompile_start(void) +{ + if (fossilize_replay_state == 1) return -1; + NSString *bundle = [[NSBundle mainBundle] bundlePath]; + NSString *lib = madeira_vulkan_library(bundle); + if (!lib || ![lib.lastPathComponent containsString:@"kosmickrisp"]) return -2; + NSString *prefix = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] + stringByAppendingPathComponent:@"wine"]; + dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ + NSFileManager *fm = [NSFileManager defaultManager]; + pthread_mutex_lock(&fossilize_replay_lock); + madeira_kosmickrisp_cache_env(fm, prefix); + NSString *dir = [prefix stringByAppendingPathComponent:@"madeira-cache/fossilize"]; + [fm createDirectoryAtPath:[dir stringByAppendingPathComponent:@"import"] withIntermediateDirectories:YES attributes:nil error:nil]; + /* Every core: nothing else runs before the game starts. */ + char threads[16]; + madeira_fossilize_threads("fossilize-precompile-threads", threads, sizeof threads); + fossilize_replay_last_done = 0; + fossilize_replay_last_total = 0; + if (madeira_fossilize_replay_locked(fm, [bundle stringByAppendingPathComponent:@"gl"], lib, dir, threads) == 1) + fossilize_replay_state = 2; /* nothing recorded yet */ + pthread_mutex_unlock(&fossilize_replay_lock); + }); + return 0; +} + +void madeira_shader_precompile_status(uint32_t *done, uint32_t *total, int *state, double *seconds) +{ + *state = fossilize_replay_state; + if (*state == 1 && fossilize_replay_progress_fn) { + uint32_t d = 0, t = 0; + fossilize_replay_progress_fn(&d, &t); + if (t) { fossilize_replay_last_done = d; fossilize_replay_last_total = t; } + } + *done = fossilize_replay_last_done; + *total = fossilize_replay_last_total; + *seconds = *state == 1 ? madeira_monotonic_seconds() - fossilize_replay_started : fossilize_replay_seconds; +} + +static void madeira_setup_fossilize(NSFileManager *fm, NSString *prefix, NSString *bundle, NSString *lib) +{ + char mode[32] = ""; + if (!madeira_cfg_get("fossilize", mode, sizeof mode) || !mode[0] || !strcasecmp(mode, "off")) return; + BOOL record = !strcasecmp(mode, "record") || !strcasecmp(mode, "on"); + BOOL replay = !strcasecmp(mode, "replay") || !strcasecmp(mode, "on"); + if (!record && !replay) { + dprintf(STDERR_FILENO, "[fossilize] unknown madeira.cfg fossilize = %s (record, replay, on or off)\n", mode); + return; + } + if (![lib.lastPathComponent containsString:@"kosmickrisp"]) { + dprintf(STDERR_FILENO, "[fossilize] needs vulkan = kosmickrisp (this session: %s); off\n", lib.lastPathComponent.UTF8String); + return; + } + NSString *gl = [bundle stringByAppendingPathComponent:@"gl"]; + NSString *dir = [prefix stringByAppendingPathComponent:@"madeira-cache/fossilize"]; + [fm createDirectoryAtPath:[dir stringByAppendingPathComponent:@"import"] withIntermediateDirectories:YES attributes:nil error:nil]; + + if (replay) madeira_fossilize_replay(fm, gl, lib, dir); + + if (record) { + NSString *loader = [gl stringByAppendingPathComponent:@"libvulkan.1.dylib"]; + NSString *icd = [gl stringByAppendingPathComponent:@"vulkan/icd.d/kosmickrisp_icd.json"]; + NSString *layers = [gl stringByAppendingPathComponent:@"vulkan/explicit_layer.d"]; + NSString *layer_lib = [gl stringByAppendingPathComponent:@"libVkLayer_fossilize.dylib"]; + for (NSString *need in @[loader, icd, layer_lib]) + if (access(need.fileSystemRepresentation, R_OK) != 0) { + dprintf(STDERR_FILENO, "[fossilize] record: %s is missing; recording off\n", need.UTF8String); + return; + } + setenv("MADEIRA_VULKAN_LIBRARY", loader.fileSystemRepresentation, 1); + setenv("VK_DRIVER_FILES", icd.fileSystemRepresentation, 1); + setenv("VK_ADD_LAYER_PATH", layers.fileSystemRepresentation, 1); + const char *have = getenv("VK_INSTANCE_LAYERS"); + NSString *wanted = have && have[0] ? [NSString stringWithFormat:@"%s:VK_LAYER_fossilize", have] : @"VK_LAYER_fossilize"; + setenv("VK_INSTANCE_LAYERS", wanted.UTF8String, 1); + setenv("FOSSILIZE_DUMP_PATH", [dir stringByAppendingPathComponent:@"capture"].fileSystemRepresentation, 0); + dprintf(STDERR_FILENO, "[fossilize] record: loader %s, driver %s, layer VK_LAYER_fossilize, dump %s.*.foz\n", + loader.lastPathComponent.UTF8String, icd.lastPathComponent.UTF8String, getenv("FOSSILIZE_DUMP_PATH")); + } +} + static void madeira_setup_vulkan(NSFileManager *fm, NSString *prefix, NSString *bundle, BOOL use_arm64ec) { NSString *win = [prefix stringByAppendingPathComponent:@"drive_c/windows"]; @@ -1110,6 +1325,17 @@ static void madeira_setup_vulkan(NSFileManager *fm, NSString *prefix, NSString * } setenv("MADEIRA_VULKAN_LIBRARY", lib.UTF8String, 1); /* read by build/win32u-unix/vulkan_ios.c */ + /* madeira-duo vk2: KosmicKrisp's caches (Mesa disk cache, and its Metal 4 pipeline-archive + * chunks in /kosmickrisp-mtl4) live inside the prefix, so they survive in-place app + * upgrades like the d3d12 shader caches do. madeira.cfg env.MESA_SHADER_CACHE_DIR / + * env.MESA_SHADER_CACHE_MAX_SIZE win when set. */ + if ([lib.lastPathComponent containsString:@"kosmickrisp"]) { + madeira_kosmickrisp_cache_env(fm, prefix); + dprintf(STDERR_FILENO, "[vulkan] KosmicKrisp caches in %s (Mesa disk cache max %s)\n", + getenv("MESA_SHADER_CACHE_DIR"), getenv("MESA_SHADER_CACHE_MAX_SIZE")); + } + madeira_setup_fossilize(fm, prefix, bundle, lib); + for (NSString *dir in dirs) for (NSString *dll in vulkan_dlls) linked += madeira_link_vulkan_file(fm, [win stringByAppendingPathComponent:dir], dll, diff --git a/app/Madeira/Winios/WiniosGL.m b/app/Madeira/Winios/WiniosGL.m index 75e3330ad3..363c82eeb3 100644 --- a/app/Madeira/Winios/WiniosGL.m +++ b/app/Madeira/Winios/WiniosGL.m @@ -24,6 +24,7 @@ // deprecated but it is the only OpenGL iOS has. #pragma clang diagnostic ignored "-Wdeprecated-declarations" +#include #import #import #import @@ -284,8 +285,69 @@ static BOOL pipeline_ensure(MadeiraGLPresenter *p, MTLPixelFormat format) { extern uint64_t madeira_get_present_count(void); extern void madeira_frame_mark(const void *layer); // Winios.m: the overlay's frame times +// madeira-duo vk2: Vulkan presents. Vulkan drivers that know about Madeira (KosmicKrisp's +// kosmickrisp-ios-0009 patch looks this up with dlsym) report each present here, so the FPS +// overlay, [frame] lines and first-frame checks count Vulkan games like GL ones. +static _Atomic uint64_t vulkan_present_count; + +__attribute__((visibility("default"), used)) +void madeira_vulkan_present_mark(const void *layer) { + atomic_fetch_add_explicit(&vulkan_present_count, 1, memory_order_relaxed); + if (layer) madeira_frame_mark(layer); +} + +// madeira-duo vk3: Vulkan shader and pipeline builds. KosmicKrisp (kosmickrisp-ios-0013) reports each +// Metal library and pipeline build here, start and finish, so the overlay's Shader misses field and +// the Shaders page can show what is compiling. A build under 2 ms came from a cache (Metal's own, or +// the pipeline archives); anything longer was compiled. "Slow" = 150 ms or more. +static _Atomic int64_t vulkan_builds_in_flight; +static _Atomic uint64_t vulkan_builds, vulkan_compiles, vulkan_slow_compiles, vulkan_compile_ns; +static _Atomic uint64_t vulkan_kind_compiles[3]; + +__attribute__((visibility("default"), used)) +void madeira_vulkan_compile_mark(int kind, int begin, uint64_t ns) { + if (begin) { atomic_fetch_add_explicit(&vulkan_builds_in_flight, 1, memory_order_relaxed); return; } + atomic_fetch_sub_explicit(&vulkan_builds_in_flight, 1, memory_order_relaxed); + atomic_fetch_add_explicit(&vulkan_builds, 1, memory_order_relaxed); + if (ns < 2000000ull) return; + atomic_fetch_add_explicit(&vulkan_compiles, 1, memory_order_relaxed); + atomic_fetch_add_explicit(&vulkan_compile_ns, ns, memory_order_relaxed); + if (kind >= 0 && kind < 3) atomic_fetch_add_explicit(&vulkan_kind_compiles[kind], 1, memory_order_relaxed); + if (ns >= 150000000ull) atomic_fetch_add_explicit(&vulkan_slow_compiles, 1, memory_order_relaxed); +} + +void madeira_vulkan_compile_stats(uint64_t *builds, uint64_t *compiles, uint64_t *slow, uint64_t *compile_ms, + int64_t *in_flight, uint64_t *libraries, uint64_t *pipelines) { + *builds = atomic_load_explicit(&vulkan_builds, memory_order_relaxed); + *compiles = atomic_load_explicit(&vulkan_compiles, memory_order_relaxed); + *slow = atomic_load_explicit(&vulkan_slow_compiles, memory_order_relaxed); + *compile_ms = atomic_load_explicit(&vulkan_compile_ns, memory_order_relaxed) / 1000000ull; + *in_flight = MAX(0, atomic_load_explicit(&vulkan_builds_in_flight, memory_order_relaxed)); + *libraries = atomic_load_explicit(&vulkan_kind_compiles[0], memory_order_relaxed); + *pipelines = atomic_load_explicit(&vulkan_kind_compiles[1], memory_order_relaxed) + + atomic_load_explicit(&vulkan_kind_compiles[2], memory_order_relaxed); +} + +// The D3D12 overlay counters live in DXMT's winemetal (madeira_shader_overlay_stats, overlay-shader +// branch); looked up at run time so builds without them still link. 0 when absent. +int madeira_shader_overlay_stats_optional(unsigned long long *shader_misses, unsigned long long *pipeline_misses, + long long *pso_queue, long long *pso_background, int *flags) { + static void (*fn)(unsigned long long *, unsigned long long *, long long *, long long *, int *); + static _Atomic int resolved; + if (!atomic_load_explicit(&resolved, memory_order_acquire)) { + fn = (void (*)(unsigned long long *, unsigned long long *, long long *, long long *, int *)) + dlsym(RTLD_DEFAULT, "madeira_shader_overlay_stats"); + atomic_store_explicit(&resolved, 1, memory_order_release); + } + *shader_misses = 0; *pipeline_misses = 0; *pso_queue = 0; *pso_background = 0; *flags = 0; + if (!fn) return 0; + fn(shader_misses, pipeline_misses, pso_queue, pso_background, flags); + return 1; +} + uint64_t madeira_frame_count(void) { - return madeira_get_present_count() + atomic_load_explicit(&gl_present_count, memory_order_relaxed); + return madeira_get_present_count() + atomic_load_explicit(&gl_present_count, memory_order_relaxed) + + atomic_load_explicit(&vulkan_present_count, memory_order_relaxed); } // The presenter behind *state, created on first use for hwnd's layer. diff --git a/app/Madeira/gl/vulkan/explicit_layer.d/VkLayer_fossilize.json b/app/Madeira/gl/vulkan/explicit_layer.d/VkLayer_fossilize.json new file mode 100644 index 0000000000..5e4e8d8f87 --- /dev/null +++ b/app/Madeira/gl/vulkan/explicit_layer.d/VkLayer_fossilize.json @@ -0,0 +1,15 @@ +{ + "file_format_version": "1.0.0", + "layer": { + "name": "VK_LAYER_fossilize", + "type": "GLOBAL", + "library_path": "../../libVkLayer_fossilize.dylib", + "api_version": "1.4.303", + "implementation_version": "1", + "description": "Fossilize capture layer (Valve): records pipeline state to FOSSILIZE_DUMP_PATH", + "functions": { + "vkGetInstanceProcAddr": "VK_LAYER_fossilize_GetInstanceProcAddr", + "vkGetDeviceProcAddr": "VK_LAYER_fossilize_GetDeviceProcAddr" + } + } +} diff --git a/app/Madeira/gl/vulkan/icd.d/kosmickrisp_icd.json b/app/Madeira/gl/vulkan/icd.d/kosmickrisp_icd.json new file mode 100644 index 0000000000..9bfb2b441c --- /dev/null +++ b/app/Madeira/gl/vulkan/icd.d/kosmickrisp_icd.json @@ -0,0 +1,8 @@ +{ + "file_format_version": "1.0.1", + "ICD": { + "library_path": "../../libvulkan_kosmickrisp.dylib", + "api_version": "1.4.354", + "is_portability_driver": false + } +} diff --git a/build/dxc-arm64ec/.gitignore b/build/dxc-arm64ec/.gitignore new file mode 100644 index 0000000000..d04ef8fdf2 --- /dev/null +++ b/build/dxc-arm64ec/.gitignore @@ -0,0 +1,2 @@ +work/ +out/ diff --git a/build/dxc-arm64ec/build.sh b/build/dxc-arm64ec/build.sh new file mode 100755 index 0000000000..e66d0c8f0c --- /dev/null +++ b/build/dxc-arm64ec/build.sh @@ -0,0 +1,71 @@ +#!/bin/bash +# Native DXC for x64 games: dxcompiler.dll 1.8.2407 built as ARM64EC. +# +# Games that compile HLSL at run time ship Microsoft's x64 dxcompiler.dll and +# run the whole compiler under FEX; every allocation it makes through +# CoTaskMemAlloc is an x64 -> native crossing (Path of Exile 2, which ships +# 1.8.2407.7, made 0.5-1.2 million a second while it compiled). This builds the +# same DXC release as ARM64EC, so the compiler runs natively and the game calls +# it through the same two exports (DxcCreateInstance, DxcCreateInstance2). +# +# The output goes into the bundle's arm64ec-windows directory (linked into +# system32 like the other builtins). With env.MADEIRA_DXC_NATIVE = 1 the Wine +# loader takes dxcompiler.dll from system32 instead of the game's folder (wine +# fork, dlls/ntdll/loader.c madeira_dxc_native); without it nothing changes. +# By default the DLL loads the game's dxil.dll for validation and signing, as +# Microsoft's build does; with env.MADEIRA_DXC_DXIL = 0 it validates with its +# built-in validator and signs the container itself (patches/0003). +# +# Source: microsoft/DirectXShaderCompiler v1.8.2407 (University of +# Illinois/NCSA licence) with patches/*.patch: raedrizqie's MinGW patch set +# (upstream PR #8265, not merged) adapted to 1.8.2407, ARM64EC fixes, and +# hexops' container signing (MIT); see notices/README.txt. The version string +# is pinned to Microsoft's build ("dxcoob 1.8.2407.7 (416fab6b5)"), so shader +# caches keyed on it stay valid. +# +# Needs: git, ninja, a host C++ compiler (for llvm-tblgen/clang-tblgen), CMake +# 3.x (DXC's CMake files are rejected by CMake 4), python3 and llvm-mingw +# 20260421 (LLVM_MINGW, default: the toolchains/ copy build-ipa.sh uses). +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +REPO_ROOT="$(cd "$HERE/../.." && pwd)" +WORK="${WORK:-$HERE/work}" +CMAKE="${CMAKE:-cmake}" +JOBS="${JOBS:-$(getconf _NPROCESSORS_ONLN)}" +export LLVM_MINGW="${LLVM_MINGW:-$REPO_ROOT/toolchains/llvm-mingw-20260421-ucrt-macos-universal}" +TAG=v1.8.2407 +mkdir -p "$WORK" + +if [ ! -d "$WORK/src/.git" ]; then + git clone --depth 1 --branch "$TAG" --recurse-submodules --shallow-submodules \ + https://github.com/microsoft/DirectXShaderCompiler.git "$WORK/src" + git -C "$WORK/src" -c user.name=madeira -c user.email=madeira@localhost am "$HERE"/patches/*.patch +fi + +COMMON=(-G Ninja -C "$WORK/src/cmake/caches/PredefinedParams.cmake" -DCMAKE_BUILD_TYPE=Release + -DLLVM_ENABLE_ASSERTIONS=OFF -DHLSL_INCLUDE_TESTS=OFF -DLLVM_INCLUDE_TESTS=OFF + -DCLANG_INCLUDE_TESTS=OFF -DSPIRV_BUILD_TESTS=OFF -DSPIRV_WERROR=OFF) + +echo "=== host tablegen ===" +if [ ! -x "$WORK/build-host/bin/clang-tblgen" ]; then + "$CMAKE" -S "$WORK/src" -B "$WORK/build-host" "${COMMON[@]}" + ninja -C "$WORK/build-host" -j"$JOBS" llvm-tblgen clang-tblgen +fi + +echo "=== dxcompiler.dll (arm64ec) ===" +# madeira-duo vk2: SPIR-V code generation on (DXC's official -spirv backend), so games on a Vulkan +# renderer (Path of Exile 2 with renderer_type=Vulkan compiles every shader with -spirv) can use the +# native compiler too. DXC_SPIRV_CODEGEN=OFF builds the DXIL-only compiler as before. This doesn't +# change DXIL output. +"$CMAKE" -S "$WORK/src" -B "$WORK/build-arm64ec" "${COMMON[@]}" \ + -DCMAKE_TOOLCHAIN_FILE="$HERE/toolchain-arm64ec.cmake" \ + -DENABLE_SPIRV_CODEGEN="${DXC_SPIRV_CODEGEN:-ON}" -DHLSL_BUILD_DXILCONV=OFF -DLLVM_BUILD_STATIC=ON -DHLSL_ENABLE_FIXED_VER=ON \ + -DLLVM_TABLEGEN="$WORK/build-host/bin/llvm-tblgen" \ + -DCLANG_TABLEGEN="$WORK/build-host/bin/clang-tblgen" +ninja -C "$WORK/build-arm64ec" -j"$JOBS" dxcompiler +OUT="${OUT:-$HERE/out}" +mkdir -p "$OUT" +"$LLVM_MINGW/bin/llvm-strip" --strip-debug -o "$OUT/dxcompiler.dll" "$WORK/build-arm64ec/bin/dxcompiler.dll" +python3 "$HERE/mark-builtin.py" --prefer-native "$OUT/dxcompiler.dll" +echo " $(wc -c < "$OUT/dxcompiler.dll" | tr -d ' ') bytes, sha256 $( (shasum -a 256 "$OUT/dxcompiler.dll" 2>/dev/null || sha256sum "$OUT/dxcompiler.dll") | cut -c1-16)" +echo " copy it to app/Madeira/arm64ec-windows/dxcompiler.dll to bundle it" diff --git a/build/dxc-arm64ec/mark-builtin.py b/build/dxc-arm64ec/mark-builtin.py new file mode 100644 index 0000000000..6c91267371 --- /dev/null +++ b/build/dxc-arm64ec/mark-builtin.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +"""Mark a PE file as a Wine builtin, as winebuild --builtin does: the 32-byte +signature "Wine builtin DLL" right after the DOS header. Wine's loader only +takes a DLL from its builtin directories (and only honours a load-order "b") +when the signature is there. + +--prefer-native also sets Wine's IMAGE_DLLCHARACTERISTICS_PREFER_NATIVE (0x0010, +as winebuild --prefer-native): with the default load order a copy the program +ships wins, and the builtin is used only when the load order asks for it ("b"). +Without the flag a builtin replaces the program's own copy everywhere.""" +import struct +import sys + +SIGNATURE = b'Wine builtin DLL'.ljust(32, b'\0') + +PREFER_NATIVE = 0x0010 + +prefer_native = '--prefer-native' in sys.argv[1:] +path = [a for a in sys.argv[1:] if not a.startswith('--')][0] +with open(path, 'r+b') as f: + header = bytearray(f.read(0x40)) + if header[:2] != b'MZ': + sys.exit(f'{path}: not a PE file') + e_lfanew = struct.unpack_from(' + +------------------ + +Files: lib/Support/* docs/SystemLibrary.rst + +Written by Henry Spencer. Not derived from licensed software. + +Permission is granted to anyone to use this software for any +purpose on any computer system, and to redistribute it freely, +subject to the following restrictions: + +1. The author is not responsible for the consequences of use of + this software, no matter how awful, even if they arise + from defects in it. + +2. The origin of this software must not be misrepresented, either + by explicit claim or by omission. + +3. Altered versions must be plainly marked as such, and must not + be misrepresented as being the original software. + +------------------ + +Files: include/llvm/Support/ConvertUTF.h + +Copyright 2001-2004 Unicode, Inc. + +Disclaimer + +This source code is provided as is by Unicode, Inc. No claims are +made as to fitness for any particular purpose. No warranties of any +kind are expressed or implied. The recipient agrees to determine +applicability of information provided. If this file has been +purchased on magnetic or optical media from Unicode, Inc., the +sole remedy for any claim will be exchange of defective media +within 90 days of receipt. + +Limitations on Rights to Redistribute This Code + +Unicode, Inc. hereby grants the right to freely use the information +supplied in this file in the creation of products supporting the +Unicode Standard, and to make copies of this file in any form +for internal or external distribution as long as this notice +remains attached. + +------------------ + +Files: include/llvm/Support/MD5.h + +This software was written by Alexander Peslyak in 2001. No copyright is +claimed, and the software is hereby placed in the public domain. +In case this attempt to disclaim copyright and place the software in the +public domain is deemed null and void, then the software is +Copyright (c) 2001 Alexander Peslyak and it is hereby released to the +general public under the following terms: + +Redistribution and use in source and binary forms, with or without +modification, are permitted. + +There's ABSOLUTELY NO WARRANTY, express or implied. + +------------------ + +Files: lib/Support/regstrlcpy.c + +Copyright (c) 1998 Todd C. Miller + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + + + +------------------ +------------------ + +THE FOLLOWING LICENSES ARE FOR BUILD AND TEST DEPENDENCIES ONLY. + +------------------ +------------------ + +Files: utils/unittest/googletest/* + +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------ + +Files: utils/unittest/googlemock/* + +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------ + +Files: test/YamlParser/* + +Copyright (c) 2006 Kirill Simonov + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +------------------ + +Files: autoconf/config.guess + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + +Autoconf Exception + +As a special exception, the Free Software Foundation gives unlimited +permission to copy, distribute and modify the configure scripts that are the +output of Autoconf. You need not follow the terms of the GNU General Public +License when using or distributing such scripts, even though portions of the +text of Autoconf appear in them. The GNU General Public License (GPL) does +govern all other use of the material that constitutes the Autoconf program. + +Certain portions of the Autoconf source text are designed to be copied (in +certain cases, depending on the input) into the output of Autoconf. We call +these the "data" portions. The rest of the Autoconf source text consists of +comments plus executable code that decides which of the data portions to +output in any given case. We call these comments and executable code the "non- +data" portions. Autoconf never copies any of the non-data portions into its +output. + +This special exception to the GPL applies to versions of Autoconf released by +the Free Software Foundation. When you make and distribute a modified version +of Autoconf, you may extend this special exception to the GPL to apply to your +modified version as well, *unless* your modified version has the potential to +copy into its output some of the text that was the non-data portion of the +version that you started with. (In other words, unless your change moves or +copies text from the non-data portions to the data portions.) If your +modification has such potential, you must delete any notice of this special +exception to the GPL from your modified version. + + END OF TERMS AND CONDITIONS diff --git a/build/dxc-arm64ec/notices/README.txt b/build/dxc-arm64ec/notices/README.txt new file mode 100644 index 0000000000..7b32e37a3c --- /dev/null +++ b/build/dxc-arm64ec/notices/README.txt @@ -0,0 +1,16 @@ +dxcompiler.dll (Madeira native DXC, ARM64EC) + +- DirectX Shader Compiler 1.8.2407 (microsoft/DirectXShaderCompiler, tag + v1.8.2407, commit 416fab6b), University of Illinois/NCSA Open Source + License: DirectXShaderCompiler-LICENSE.TXT. Includes LLVM/Clang 3.7 under + the same licence. +- MinGW build changes based on raedrizqie's patch set + (microsoft/DirectXShaderCompiler pull request 8265), contributed under the + project's licence. +- tools/clang/tools/dxcompiler/MachSiegbertVogtDXCSA.{cpp,h} from + hexops/DirectXShaderCompiler (commit 4190bb0c9), Apache-2.0 or MIT at the + user's choice; MIT chosen: hexops-mach-LICENSE-MIT. +- Linked statically with llvm-mingw's libc++/libunwind (Apache-2.0 WITH + LLVM-exception) and mingw-w64 runtime libraries. + +Patches: build/dxc-arm64ec/patches/. Build: build/dxc-arm64ec/build.sh. diff --git a/build/dxc-arm64ec/notices/hexops-mach-LICENSE-MIT b/build/dxc-arm64ec/notices/hexops-mach-LICENSE-MIT new file mode 100644 index 0000000000..14cd797326 --- /dev/null +++ b/build/dxc-arm64ec/notices/hexops-mach-LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2021 Hexops Contributors (given via the Git commit history). + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/build/dxc-arm64ec/patches/0001-MinGW-and-ARM64EC-build-of-DXC-1.8.2407-for-Madeira.patch b/build/dxc-arm64ec/patches/0001-MinGW-and-ARM64EC-build-of-DXC-1.8.2407-for-Madeira.patch new file mode 100644 index 0000000000..4100dd82d0 --- /dev/null +++ b/build/dxc-arm64ec/patches/0001-MinGW-and-ARM64EC-build-of-DXC-1.8.2407-for-Madeira.patch @@ -0,0 +1,1120 @@ +From e54928d758f932e541add864bd232f975fb8dd19 Mon Sep 17 00:00:00 2001 +From: Shitiz Garg +Date: Wed, 4 Nov 2026 04:59:07 +1100 +Subject: [PATCH 1/3] MinGW and ARM64EC build of DXC 1.8.2407 for Madeira + +Based on raedrizqie's MinGW patch set (microsoft/DirectXShaderCompiler#8265, +unmerged), adapted to v1.8.2407, plus: +- CFG.h: rename the CALLBACK template parameter (windows.h macro) +- DxilContainerReflection.cpp: avoid UNREFERENCED_PARAMETER on a reference +- dxcvalidator.cpp: ETW header only with MSVC +- Host.cpp: no x86 cpuid asm on ARM64EC (clang defines __x86_64__ there) +- dxcapi.use.cpp: Windows DLL names (MinGW's lib prefix broke dxil.dll lookup) + +Co-Authored-By: Claude Opus 5.5 +--- + CMakeLists.txt | 4 +- + cmake/modules/HandleLLVMOptions.cmake | 10 + + include/dxc/Support/Global.h | 8 +- + include/dxc/WinAdapter.h | 292 +++++++++++++++++- + include/dxc/dxcapi.internal.h | 2 +- + include/dxc/dxcisense.h | 2 +- + include/llvm/ADT/StringRef.h | 21 +- + include/llvm/Object/COFF.h | 31 +- + include/llvm/Object/RelocVisitor.h | 10 +- + include/llvm/Support/COFF.h | 17 + + lib/DxcSupport/WinAdapter.cpp | 7 +- + lib/DxcSupport/dxcapi.use.cpp | 6 + + lib/HLSL/DxilContainerReflection.cpp | 2 +- + lib/IR/PassRegistry.cpp | 2 + + lib/Support/Host.cpp | 8 +- + projects/CMakeLists.txt | 4 +- + tools/clang/CMakeLists.txt | 3 + + tools/clang/include/clang/AST/Attr.h | 5 + + tools/clang/include/clang/Analysis/CFG.h | 4 +- + tools/clang/tools/dxclib/CMakeLists.txt | 2 +- + tools/clang/tools/dxclib/dxc.cpp | 12 +- + tools/clang/tools/dxcompiler/DXCompiler.cpp | 2 +- + tools/clang/tools/dxcompiler/DXCompiler.rc | 2 + + tools/clang/tools/dxcompiler/dxcapi.cpp | 6 +- + .../clang/tools/dxcompiler/dxcompilerobj.cpp | 2 +- + tools/clang/tools/dxcompiler/dxcpdbutils.cpp | 8 +- + tools/clang/tools/dxcompiler/dxcvalidator.cpp | 2 +- + 27 files changed, 399 insertions(+), 75 deletions(-) + +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 7b754049..4565d552 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -115,7 +115,9 @@ if(WIN32) + add_compile_options(/guard:cf) + add_link_options(/guard:cf) + else() +- add_compile_options(-fcf-protection) ++ if(LLVM_NATIVE_ARCH MATCHES "X86") ++ add_compile_options(-fcf-protection) ++ endif() + endif() + endif(WIN32) + +diff --git a/cmake/modules/HandleLLVMOptions.cmake b/cmake/modules/HandleLLVMOptions.cmake +index 7b8edecd..b92ea474 100644 +--- a/cmake/modules/HandleLLVMOptions.cmake ++++ b/cmake/modules/HandleLLVMOptions.cmake +@@ -223,6 +223,10 @@ endif( CMAKE_SIZEOF_VOID_P EQUAL 8 AND NOT WIN32 ) + + if (LLVM_BUILD_STATIC) + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static") ++ if(MINGW) ++ # We want to mimic MSVC standalone build here ++ set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -static") ++ endif() + endif() + + if( XCODE ) +@@ -409,12 +413,18 @@ elseif( LLVM_COMPILER_IS_GCC_COMPATIBLE ) + append("-Wno-unknown-pragmas" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) + + if (MINGW) ++ append("-Wno-cast-function-type-mismatch" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) + append("-Wno-implicit-fallthrough" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) + append("-Wno-missing-exception-spec" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) + append("-Wno-reorder-ctor" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) + append("-Wno-sign-compare" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) + append("-Wno-unused-const-variable" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) + append("-Wno-unused-function" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) ++ append("-Wno-unused-private-field" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) ++ ++ if (CMAKE_BUILD_TYPE STREQUAL "Debug") ++ append("-Wno-gnu-zero-variadic-macro-arguments" CMAKE_C_FLAGS CMAKE_CXX_FLAGS) ++ endif() + endif() + + add_flag_if_supported("-Wno-unused-but-set-variable" UNUSED_BUT_SET_VARIABLE) +diff --git a/include/dxc/Support/Global.h b/include/dxc/Support/Global.h +index 9d97467d..f6b08f02 100644 +--- a/include/dxc/Support/Global.h ++++ b/include/dxc/Support/Global.h +@@ -229,7 +229,7 @@ template T *VerifyNullAndThrow(T *p) { + } + #define VNT(__p) VerifyNullAndThrow(__p) + +-#ifdef _MSC_VER ++#ifdef _WIN32 + + extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA( + const char *msg); +@@ -268,7 +268,7 @@ inline void OutputDebugFormatA(const char *pszFormat, ...) { + + va_list argList; + va_start(argList, pszFormat); +- int count = vsnprintf_s(buffer, _countof(buffer), pszFormat, argList); ++ int count = vsnprintf_s(buffer, _countof(buffer), _countof(buffer), pszFormat, argList); + va_end(argList); + + OutputDebugStringA(buffer); +@@ -277,7 +277,7 @@ inline void OutputDebugFormatA(const char *pszFormat, ...) { + } + } + +-#endif // _MSC_VER ++#endif // _WIN32 + + #ifndef NDEBUG + +@@ -300,7 +300,7 @@ inline void OutputDebugFormatA(const char *pszFormat, ...) { + if (!(exp)) { \ + OutputDebugFormatA( \ + "Error: \t%s\nFile:\n%s(%d)\nFunc:\t%s.\n\t" fmt "\n", \ +- "!(" #exp ")", __FILE__, __LINE__, __FUNCTION__, __VA_ARGS__); \ ++ "!(" #exp ")", __FILE__, __LINE__, __FUNCTION__, ##__VA_ARGS__); \ + __debugbreak(); \ + } \ + } while (0) +diff --git a/include/dxc/WinAdapter.h b/include/dxc/WinAdapter.h +index b8c66468..f1d383f3 100644 +--- a/include/dxc/WinAdapter.h ++++ b/include/dxc/WinAdapter.h +@@ -15,7 +15,7 @@ + #ifndef LLVM_SUPPORT_WIN_ADAPTER_H + #define LLVM_SUPPORT_WIN_ADAPTER_H + +-#ifndef _WIN32 ++#ifndef _MSC_VER + + #ifdef __cplusplus + #include +@@ -33,6 +33,148 @@ + #include + #endif // __cplusplus + ++#ifdef __MINGW32__ ++ ++#undef _WIN32_WINNT ++#undef _WIN32_IE ++ ++// Require at least Windows 7 (Updated from XP) ++#define _WIN32_WINNT 0x0601 ++#define _WIN32_IE 0x0800 ++ ++#define WIN32_LEAN_AND_MEAN ++#define STRSAFE_NO_DEPRECATE ++ ++#include ++#include ++#include ++#include ++#include ++#include ++ ++#undef EN ++#undef IN ++#undef OUT ++ ++#ifdef MemoryFence ++#undef MemoryFence ++#endif ++ ++#define EventRegisterMicrosoft_Windows_DXCompiler_API() ++#define EventRegisterMicrosoft_Windows_DxcRuntime_API() ++#define EventUnregisterMicrosoft_Windows_DXCompiler_API() ++#define EventUnregisterMicrosoft_Windows_DxcRuntime_API() ++ ++#define DxcEtw_DXCompilerCompile_Start() ++#define DxcEtw_DXCompilerCompile_Stop(hr) ++#define DxcEtw_DXCompilerCreateInstance_Start() ++#define DxcEtw_DXCompilerCreateInstance_Stop(hr) ++#define DxcEtw_DXCompilerDisassemble_Start() ++#define DxcEtw_DXCompilerDisassemble_Stop(hr) ++#define DxcEtw_DXCompilerInitialization_Start() ++#define DxcEtw_DXCompilerInitialization_Stop(hr) ++#define DxcEtw_DXCompilerPreprocess_Start() ++#define DxcEtw_DXCompilerPreprocess_Stop(hr) ++#define DxcEtw_DXCompilerShutdown_Start() ++#define DxcEtw_DXCompilerShutdown_Stop(hr) ++#define DxcEtw_DxcValidation_Start() ++#define DxcEtw_DxcValidation_Stop(hr) ++#define DxcRuntimeEtw_DxcRuntimeInitialization_Start() ++#define DxcRuntimeEtw_DxcRuntimeInitialization_Stop(HR) ++#define DxcRuntimeEtw_DxcRuntimeShutdown_Start() ++#define DxcRuntimeEtw_DxcRuntimeShutdown_Stop(S_OK) ++ ++#define ATLASSERT assert ++#define ATLASSUME(expr) \ ++ do { \ ++ ATLASSERT(expr); \ ++ __analysis_assume(!!(expr)); \ ++ } while (0) ++#define ATLENSURE_THROW(expr, hr) \ ++ do { \ ++ int __atl_condVal = !!(expr); \ ++ ATLASSUME(__atl_condVal); \ ++ if (!(__atl_condVal)) \ ++ throw(hr); \ ++ } while (0) ++ ++// Disable all calling conventions ++#define __cdecl ++#define __stdcall ++#define __vectorcall ++#define __thiscall ++#define __fastcall ++#define __clrcall ++ ++// FIXME: missing from intsafe.h ++#define Int32ToUInt32 IntToUInt ++#define UInt32Add UIntAdd ++#define UInt32Mult UIntMult ++ ++// FIXME: missing from sal.h ++#define _Maybenull_ ++#define _Notnull_ ++ ++// FIXME: missing from d3d12shader.h ++#define D3D_SHADER_REQUIRES_EARLY_DEPTH_STENCIL 0x00000002 ++#define D3D12_SHVER_GET_TYPE(_Version) (((_Version) >> 16) & 0xffff) ++#define D3D12_SHVER_GET_MAJOR(_Version) (((_Version) >> 4) & 0xf) ++#define D3D12_SHVER_GET_MINOR(_Version) (((_Version) >> 0) & 0xf) ++ ++#ifdef __cplusplus ++ ++constexpr uint8_t nybble_from_hex(char c) { ++ return ((c >= '0' && c <= '9') ++ ? (c - '0') ++ : ((c >= 'a' && c <= 'f') ++ ? (c - 'a' + 10) ++ : ((c >= 'A' && c <= 'F') ? (c - 'A' + 10) ++ : /* Should be an error */ -1))); ++} ++ ++constexpr uint8_t byte_from_hex(char c1, char c2) { ++ return nybble_from_hex(c1) << 4 | nybble_from_hex(c2); ++} ++ ++constexpr uint8_t byte_from_hexstr(const char str[2]) { ++ return nybble_from_hex(str[0]) << 4 | nybble_from_hex(str[1]); ++} ++ ++constexpr GUID guid_from_string(const char str[37]) { ++ return GUID{static_cast(byte_from_hexstr(str)) << 24 | ++ static_cast(byte_from_hexstr(str + 2)) << 16 | ++ static_cast(byte_from_hexstr(str + 4)) << 8 | ++ byte_from_hexstr(str + 6), ++ static_cast( ++ static_cast(byte_from_hexstr(str + 9)) << 8 | ++ byte_from_hexstr(str + 11)), ++ static_cast( ++ static_cast(byte_from_hexstr(str + 14)) << 8 | ++ byte_from_hexstr(str + 16)), ++ {byte_from_hexstr(str + 19), byte_from_hexstr(str + 21), ++ byte_from_hexstr(str + 24), byte_from_hexstr(str + 26), ++ byte_from_hexstr(str + 28), byte_from_hexstr(str + 30), ++ byte_from_hexstr(str + 32), byte_from_hexstr(str + 34)}}; ++} ++ ++#define CROSS_PLATFORM_UUIDOF(name, spec) \ ++ struct __declspec(uuid(spec)) name; \ ++ extern "C++" { \ ++ template <> struct __mingw_uuidof_s { \ ++ static constexpr IID __uuid_inst = guid_from_string(spec); \ ++ }; \ ++ template <> constexpr const GUID &__mingw_uuidof() { \ ++ return __mingw_uuidof_s::__uuid_inst; \ ++ } \ ++ template <> constexpr const GUID &__mingw_uuidof() { \ ++ return __mingw_uuidof_s::__uuid_inst; \ ++ } \ ++ } ++ ++#endif // __cplusplus ++ ++#else // !__MINGW32__ ++ + #define COM_NO_WINDOWS_H // needed to inform d3d headers that this isn't windows + + //===----------------------------------------------------------------------===// +@@ -630,6 +772,12 @@ CROSS_PLATFORM_UUIDOF(ID3D12LibraryReflection, + CROSS_PLATFORM_UUIDOF(ID3D12ShaderReflection, + "5A58797D-A72C-478D-8BA2-EFC6B0EFE88E") + ++#endif // __cplusplus ++ ++#endif // !__MINGW32__ ++ ++#ifdef __cplusplus ++ + //===--------------------- COM Pointer Types ------------------------------===// + + class CAllocator { +@@ -897,6 +1045,7 @@ public: + + #define CComHeapPtr CHeapPtr + ++#ifndef __MINGW32__ + //===--------------------------- BSTR Allocation --------------------------===// + + void SysFreeString(BSTR bstrString); +@@ -982,6 +1131,145 @@ public: + + typedef CA2WEX<> CA2W; + ++#else // __MINGW32__ ++ ++inline UINT WINAPI _AtlGetConversionACP() { return CP_THREAD_ACP; } ++ ++template ++inline void AtlConvAllocMemory(_CharType **ppBuff, int nLength, ++ _CharType *pszFixedBuffer, ++ int nFixedBufferLength) { ++ ATLENSURE_THROW(ppBuff != NULL, E_INVALIDARG); ++ ATLENSURE_THROW(nLength >= 0, E_INVALIDARG); ++ ATLENSURE_THROW(pszFixedBuffer != NULL, E_INVALIDARG); ++ ++ if (*ppBuff != pszFixedBuffer) { ++ if (nLength > nFixedBufferLength) { ++#if __MSVCRT_VERSION__ >= 0x900 ++ _CharType *ppReallocBuf = static_cast<_CharType *>( ++ _recalloc(*ppBuff, nLength, sizeof(_CharType))); ++ if (ppReallocBuf == NULL) { ++ E_OUTOFMEMORY; ++ } ++ *ppBuff = ppReallocBuf; ++ } else { ++#endif ++ free(*ppBuff); ++ *ppBuff = pszFixedBuffer; ++ } ++ ++ } else { ++ if (nLength > nFixedBufferLength) { ++ *ppBuff = static_cast<_CharType *>(calloc(nLength, sizeof(_CharType))); ++ } else { ++ *ppBuff = pszFixedBuffer; ++ } ++ } ++ ++ if (*ppBuff == NULL) { ++ E_OUTOFMEMORY; ++ } ++} ++ ++template ++inline void AtlConvFreeMemory(_CharType *pBuff, _CharType *pszFixedBuffer, ++ int nFixedBufferLength) { ++ if (pBuff != pszFixedBuffer) { ++ free(pBuff); ++ } ++} ++ ++template class CW2AEX { ++public: ++ CW2AEX(LPCWSTR psz) : m_psz(m_szBuffer) { Init(psz, _AtlGetConversionACP()); } ++ CW2AEX(LPCWSTR psz, UINT nCodePage) : m_psz(m_szBuffer) { ++ Init(psz, nCodePage); ++ } ++ ~CW2AEX() { AtlConvFreeMemory(m_psz, m_szBuffer, t_nBufferLength); } ++ ++ operator LPSTR() const { return (m_psz); } ++ ++private: ++ void Init(LPCWSTR psz, UINT nConvertCodePage) { ++ if (psz == NULL) { ++ m_psz = NULL; ++ return; ++ } ++ int nLengthW = lstrlenW(psz) + 1; ++ int nLengthA = nLengthW * 4; ++ ++ AtlConvAllocMemory(&m_psz, nLengthA, m_szBuffer, t_nBufferLength); ++ ++ BOOL bFailed = ++ (0 == ::WideCharToMultiByte(nConvertCodePage, 0, psz, nLengthW, m_psz, ++ nLengthA, NULL, NULL)); ++ if (bFailed) { ++ if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { ++ nLengthA = ::WideCharToMultiByte(nConvertCodePage, 0, psz, nLengthW, ++ NULL, 0, NULL, NULL); ++ AtlConvAllocMemory(&m_psz, nLengthA, m_szBuffer, t_nBufferLength); ++ bFailed = ++ (0 == ::WideCharToMultiByte(nConvertCodePage, 0, psz, nLengthW, ++ m_psz, nLengthA, NULL, NULL)); ++ } ++ } ++ } ++ ++public: ++ LPSTR m_psz; ++ char m_szBuffer[t_nBufferLength]; ++ ++private: ++ CW2AEX(const CW2AEX &); ++ CW2AEX &operator=(const CW2AEX &); ++}; ++typedef CW2AEX<> CW2A; ++ ++template class CA2WEX { ++public: ++ CA2WEX(LPCSTR psz) : m_psz(m_szBuffer) { Init(psz, _AtlGetConversionACP()); } ++ CA2WEX(LPCSTR psz, UINT nCodePage) : m_psz(m_szBuffer) { ++ Init(psz, nCodePage); ++ } ++ ~CA2WEX() { AtlConvFreeMemory(m_psz, m_szBuffer, t_nBufferLength); } ++ ++ operator LPWSTR() const { return (m_psz); } ++ ++private: ++ void Init(LPCSTR psz, UINT nCodePage) { ++ if (psz == NULL) { ++ m_psz = NULL; ++ return; ++ } ++ int nLengthA = lstrlenA(psz) + 1; ++ int nLengthW = nLengthA; ++ ++ AtlConvAllocMemory(&m_psz, nLengthW, m_szBuffer, t_nBufferLength); ++ ++ BOOL bFailed = (0 == ::MultiByteToWideChar(nCodePage, 0, psz, nLengthA, ++ m_psz, nLengthW)); ++ if (bFailed) { ++ if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { ++ nLengthW = ::MultiByteToWideChar(nCodePage, 0, psz, nLengthA, NULL, 0); ++ AtlConvAllocMemory(&m_psz, nLengthW, m_szBuffer, t_nBufferLength); ++ bFailed = (0 == ::MultiByteToWideChar(nCodePage, 0, psz, nLengthA, ++ m_psz, nLengthW)); ++ } ++ } ++ } ++ ++public: ++ LPWSTR m_psz; ++ wchar_t m_szBuffer[t_nBufferLength]; ++ ++private: ++ CA2WEX(const CA2WEX &); ++ CA2WEX &operator=(const CA2WEX &); ++}; ++typedef CA2WEX<> CA2W; ++ ++#endif // __MINGW32__ ++ + //===--------- File IO Related Types ----------------===// + + class CHandle { +@@ -1034,6 +1322,6 @@ public: + + #endif // __cplusplus + +-#endif // _WIN32 ++#endif // _MSC_VER + + #endif // LLVM_SUPPORT_WIN_ADAPTER_H +diff --git a/include/dxc/dxcapi.internal.h b/include/dxc/dxcapi.internal.h +index 5c15c401..8f062bca 100644 +--- a/include/dxc/dxcapi.internal.h ++++ b/include/dxc/dxcapi.internal.h +@@ -12,7 +12,7 @@ + #ifndef __DXC_API_INTERNAL__ + #define __DXC_API_INTERNAL__ + +-#include "dxcapi.h" ++#include "dxc/dxcapi.h" + + /////////////////////////////////////////////////////////////////////////////// + // Forward declarations. +diff --git a/include/dxc/dxcisense.h b/include/dxc/dxcisense.h +index 661de168..266bed46 100644 +--- a/include/dxc/dxcisense.h ++++ b/include/dxc/dxcisense.h +@@ -12,7 +12,7 @@ + #ifndef __DXC_ISENSE__ + #define __DXC_ISENSE__ + +-#include "dxcapi.h" ++#include "dxc/dxcapi.h" + #ifndef _WIN32 + #include "WinAdapter.h" + #endif +diff --git a/include/llvm/ADT/StringRef.h b/include/llvm/ADT/StringRef.h +index 957707f4..5f0e722c 100644 +--- a/include/llvm/ADT/StringRef.h ++++ b/include/llvm/ADT/StringRef.h +@@ -12,6 +12,7 @@ + + #include + #include ++#include + #include + #include + #include +@@ -569,24 +570,4 @@ namespace llvm { + template <> struct isPodLike { static const bool value = true; }; + } + +-// HLSL Change Starts +-// StringRef provides an operator string; that trips up the std::pair noexcept specification, +-// which (a) enables the moves constructor (because conversion is allowed), but (b) +-// misclassifies the the construction as nothrow. +-namespace std { +- template<> +- struct is_nothrow_constructible +- : std::false_type { +- }; +- template<> +- struct is_nothrow_constructible +- : std::false_type { +- }; +- template<> +- struct is_nothrow_constructible +- : std::false_type { +- }; +-} +-// HLSL Change Ends +- + #endif +diff --git a/include/llvm/Object/COFF.h b/include/llvm/Object/COFF.h +index 025a9dbc..76479c0f 100644 +--- a/include/llvm/Object/COFF.h ++++ b/include/llvm/Object/COFF.h +@@ -20,6 +20,8 @@ + #include "llvm/Support/Endian.h" + #include "llvm/Support/ErrorOr.h" + ++using namespace llvm::COFF; ++ + namespace llvm { + template class ArrayRef; + +@@ -334,31 +336,31 @@ public: + } + + bool isExternal() const { +- return getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL; ++ return getStorageClass() == IMAGE_SYM_CLASS_EXTERNAL; + } + + bool isCommon() const { +- return isExternal() && getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED && ++ return isExternal() && getSectionNumber() == IMAGE_SYM_UNDEFINED && + getValue() != 0; + } + + bool isUndefined() const { +- return isExternal() && getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED && ++ return isExternal() && getSectionNumber() == IMAGE_SYM_UNDEFINED && + getValue() == 0; + } + + bool isWeakExternal() const { +- return getStorageClass() == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL; ++ return getStorageClass() == IMAGE_SYM_CLASS_WEAK_EXTERNAL; + } + + bool isFunctionDefinition() const { +- return isExternal() && getBaseType() == COFF::IMAGE_SYM_TYPE_NULL && +- getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION && ++ return isExternal() && getBaseType() == IMAGE_SYM_TYPE_NULL && ++ getComplexType() == IMAGE_SYM_DTYPE_FUNCTION && + !COFF::isReservedSectionNumber(getSectionNumber()); + } + + bool isFunctionLineInfo() const { +- return getStorageClass() == COFF::IMAGE_SYM_CLASS_FUNCTION; ++ return getStorageClass() == IMAGE_SYM_CLASS_FUNCTION; + } + + bool isAnyUndefined() const { +@@ -366,27 +368,26 @@ public: + } + + bool isFileRecord() const { +- return getStorageClass() == COFF::IMAGE_SYM_CLASS_FILE; ++ return getStorageClass() == IMAGE_SYM_CLASS_FILE; + } + + bool isSection() const { +- return getStorageClass() == COFF::IMAGE_SYM_CLASS_SECTION; ++ return getStorageClass() == IMAGE_SYM_CLASS_SECTION; + } + + bool isSectionDefinition() const { + // C++/CLI creates external ABS symbols for non-const appdomain globals. + // These are also followed by an auxiliary section definition. +- bool isAppdomainGlobal = +- getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL && +- getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE; +- bool isOrdinarySection = getStorageClass() == COFF::IMAGE_SYM_CLASS_STATIC; ++ bool isAppdomainGlobal = getStorageClass() == IMAGE_SYM_CLASS_EXTERNAL && ++ getSectionNumber() == IMAGE_SYM_ABSOLUTE; ++ bool isOrdinarySection = getStorageClass() == IMAGE_SYM_CLASS_STATIC; + if (!getNumberOfAuxSymbols()) + return false; + return isAppdomainGlobal || isOrdinarySection; + } + + bool isCLRToken() const { +- return getStorageClass() == COFF::IMAGE_SYM_CLASS_CLR_TOKEN; ++ return getStorageClass() == IMAGE_SYM_CLASS_CLR_TOKEN; + } + + private: +@@ -411,7 +412,7 @@ struct coff_section { + // Returns true if the actual number of relocations is stored in + // VirtualAddress field of the first relocation table entry. + bool hasExtendedRelocations() const { +- return (Characteristics & COFF::IMAGE_SCN_LNK_NRELOC_OVFL) && ++ return (Characteristics & IMAGE_SCN_LNK_NRELOC_OVFL) && + NumberOfRelocations == UINT16_MAX; + } + }; +diff --git a/include/llvm/Object/RelocVisitor.h b/include/llvm/Object/RelocVisitor.h +index d5e4258c..9bb52819 100644 +--- a/include/llvm/Object/RelocVisitor.h ++++ b/include/llvm/Object/RelocVisitor.h +@@ -26,6 +26,8 @@ + #include "llvm/Support/MachO.h" + #include "llvm/Support/raw_ostream.h" + ++using namespace llvm::COFF; ++ + namespace llvm { + namespace object { + +@@ -206,17 +208,17 @@ private: + switch (ObjToVisit.getArch()) { + case Triple::x86: + switch (RelocType) { +- case COFF::IMAGE_REL_I386_SECREL: ++ case IMAGE_REL_I386_SECREL: + return visitCOFF_I386_SECREL(R, Value); +- case COFF::IMAGE_REL_I386_DIR32: ++ case IMAGE_REL_I386_DIR32: + return visitCOFF_I386_DIR32(R, Value); + } + break; + case Triple::x86_64: + switch (RelocType) { +- case COFF::IMAGE_REL_AMD64_SECREL: ++ case IMAGE_REL_AMD64_SECREL: + return visitCOFF_AMD64_SECREL(R, Value); +- case COFF::IMAGE_REL_AMD64_ADDR64: ++ case IMAGE_REL_AMD64_ADDR64: + return visitCOFF_AMD64_ADDR64(R, Value); + } + break; +diff --git a/include/llvm/Support/COFF.h b/include/llvm/Support/COFF.h +index 3c5ee069..280a0e89 100644 +--- a/include/llvm/Support/COFF.h ++++ b/include/llvm/Support/COFF.h +@@ -80,6 +80,7 @@ namespace COFF { + uint32_t NumberOfSymbols; + }; + ++#ifndef __MINGW32__ + enum MachineTypes { + MT_Invalid = 0xffff, + +@@ -145,6 +146,7 @@ namespace COFF { + /// and should be 0. + IMAGE_FILE_BYTES_REVERSED_HI = 0x8000 + }; ++#endif // __MINGW32__ + + struct symbol { + char Name[NameSize]; +@@ -155,6 +157,12 @@ namespace COFF { + uint8_t NumberOfAuxSymbols; + }; + ++#ifdef __MINGW32__ ++ enum SymbolComplexType { ++ /// Type is formed as (base + (derived << SCT_COMPLEX_TYPE_SHIFT)) ++ SCT_COMPLEX_TYPE_SHIFT = 4 ++ }; ++#else + enum SymbolSectionNumber : int32_t { + IMAGE_SYM_DEBUG = -2, + IMAGE_SYM_ABSOLUTE = -1, +@@ -226,6 +234,7 @@ namespace COFF { + /// Type is formed as (base + (derived << SCT_COMPLEX_TYPE_SHIFT)) + SCT_COMPLEX_TYPE_SHIFT = 4 + }; ++#endif // __MINGW32__ + + enum AuxSymbolType { + IMAGE_AUX_SYMBOL_TYPE_TOKEN_DEF = 1 +@@ -244,6 +253,7 @@ namespace COFF { + uint32_t Characteristics; + }; + ++#ifndef __MINGW32__ + enum SectionCharacteristics : uint32_t { + SC_Invalid = 0xffffffff, + +@@ -283,6 +293,7 @@ namespace COFF { + IMAGE_SCN_MEM_READ = 0x40000000, + IMAGE_SCN_MEM_WRITE = 0x80000000 + }; ++#endif // __MINGW32__ + + struct relocation { + uint32_t VirtualAddress; +@@ -290,6 +301,7 @@ namespace COFF { + uint16_t Type; + }; + ++#ifndef __MINGW32__ + enum RelocationTypeI386 { + IMAGE_REL_I386_ABSOLUTE = 0x0000, + IMAGE_REL_I386_DIR16 = 0x0001, +@@ -351,6 +363,7 @@ namespace COFF { + IMAGE_COMDAT_SELECT_LARGEST, + IMAGE_COMDAT_SELECT_NEWEST + }; ++#endif // __MINGW32__ + + // Auxiliary Symbol Formats + struct AuxiliaryFunctionDefinition { +@@ -375,12 +388,14 @@ namespace COFF { + uint8_t unused[10]; + }; + ++#ifndef __MINGW32__ + /// These are not documented in the spec, but are located in WinNT.h. + enum WeakExternalCharacteristics { + IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY = 1, + IMAGE_WEAK_EXTERN_SEARCH_LIBRARY = 2, + IMAGE_WEAK_EXTERN_SEARCH_ALIAS = 3 + }; ++#endif // __MINGW32__ + + struct AuxiliarySectionDefinition { + uint32_t Length; +@@ -541,6 +556,7 @@ namespace COFF { + NUM_DATA_DIRECTORIES + }; + ++#ifndef __MINGW32__ + enum WindowsSubsystem { + IMAGE_SUBSYSTEM_UNKNOWN = 0, ///< An unknown subsystem. + IMAGE_SUBSYSTEM_NATIVE = 1, ///< Device drivers and native Windows processes +@@ -612,6 +628,7 @@ namespace COFF { + IMAGE_REL_BASED_MIPS_JMPADDR16 = 9, + IMAGE_REL_BASED_DIR64 = 10 + }; ++#endif // __MINGW32__ + + enum ImportType { + IMPORT_CODE = 0, +diff --git a/lib/DxcSupport/WinAdapter.cpp b/lib/DxcSupport/WinAdapter.cpp +index c3aaab88..df1f9f46 100644 +--- a/lib/DxcSupport/WinAdapter.cpp ++++ b/lib/DxcSupport/WinAdapter.cpp +@@ -10,7 +10,8 @@ + #include "assert.h" + #include "dxc/Support/WinFunctions.h" + #include "dxc/Support/WinIncludes.h" +-#ifndef _WIN32 ++ ++#ifndef _MSC_VER + + #include "dxc/Support/Unicode.h" + +@@ -22,6 +23,8 @@ void *CAllocator::Reallocate(void *p, size_t nBytes) throw() { + void *CAllocator::Allocate(size_t nBytes) throw() { return malloc(nBytes); } + void CAllocator::Free(void *p) throw() { free(p); } + ++#ifndef __MINGW32__ ++ + //===--------------------------- BSTR Allocation --------------------------===// + + void SysFreeString(BSTR bstrString) { +@@ -61,6 +64,8 @@ unsigned int SysStringLen(const BSTR bstrString) { + return blobIn[0] / sizeof(OLECHAR); + } + ++#endif // !__MINGW32__ ++ + //===--------------------------- CHandle -------------------------------===// + + CHandle::CHandle(HANDLE h) { m_h = h; } +diff --git a/lib/DxcSupport/dxcapi.use.cpp b/lib/DxcSupport/dxcapi.use.cpp +index 399259ef..868d1f42 100644 +--- a/lib/DxcSupport/dxcapi.use.cpp ++++ b/lib/DxcSupport/dxcapi.use.cpp +@@ -21,10 +21,16 @@ + + namespace dxc { + ++#ifdef _WIN32 ++// MinGW sets CMAKE_SHARED_LIBRARY_PREFIX to "lib"; the Windows names are fixed. ++const char *kDxCompilerLib = "dxcompiler.dll"; ++const char *kDxilLib = "dxil.dll"; ++#else + const char *kDxCompilerLib = + CMAKE_SHARED_LIBRARY_PREFIX "dxcompiler" CMAKE_SHARED_LIBRARY_SUFFIX; + const char *kDxilLib = + CMAKE_SHARED_LIBRARY_PREFIX "dxil" CMAKE_SHARED_LIBRARY_SUFFIX; ++#endif + + #ifdef _WIN32 + static void TrimEOL(char *pMsg) { +diff --git a/lib/HLSL/DxilContainerReflection.cpp b/lib/HLSL/DxilContainerReflection.cpp +index bebe018e..c85c7d45 100644 +--- a/lib/HLSL/DxilContainerReflection.cpp ++++ b/lib/HLSL/DxilContainerReflection.cpp +@@ -1509,7 +1509,7 @@ void CShaderReflectionConstantBuffer::Initialize( + } + + static unsigned CalcResTypeSize(DxilModule &M, DxilResource &R) { +- UNREFERENCED_PARAMETER(M); ++ (void)M; + Type *Ty = R.GetHLSLType()->getPointerElementType(); + if (R.IsStructuredBuffer()) { + Ty = dxilutil::StripArrayTypes(Ty); +diff --git a/lib/IR/PassRegistry.cpp b/lib/IR/PassRegistry.cpp +index b77d2bf3..6b57363a 100644 +--- a/lib/IR/PassRegistry.cpp ++++ b/lib/IR/PassRegistry.cpp +@@ -35,7 +35,9 @@ using namespace llvm; + // A simple global initialized at DllMain-time will do (still does more work + // than we should likely perform though). + static uint32_t g_PassRegistryTid; ++#ifdef _MSC_VER + extern "C" uint32_t __stdcall GetCurrentThreadId(void); ++#endif + static void CheckThreadId() { + if (g_PassRegistryTid == 0) + g_PassRegistryTid = GetCurrentThreadId(); +diff --git a/lib/Support/Host.cpp b/lib/Support/Host.cpp +index 071e12ac..931d0df6 100644 +--- a/lib/Support/Host.cpp ++++ b/lib/Support/Host.cpp +@@ -69,8 +69,8 @@ static ssize_t LLVM_ATTRIBUTE_UNUSED readCpuInfo(void *Buf, size_t Size) { + } + #endif + +-#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86)\ +- || defined(__x86_64__) || defined(_M_AMD64) || defined (_M_X64) ++#if !defined(__arm64ec__) && (defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86)\ ++ || defined(__x86_64__) || defined(_M_AMD64) || defined (_M_X64)) + + /// GetX86CpuIDAndInfo - Execute the specified cpuid and return the 4 values in the + /// specified arguments. If we can't run cpuid on the host, return true. +@@ -731,8 +731,8 @@ StringRef sys::getHostCPUName() { + } + #endif + +-#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86)\ +- || defined(__x86_64__) || defined(_M_AMD64) || defined (_M_X64) ++#if !defined(__arm64ec__) && (defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86)\ ++ || defined(__x86_64__) || defined(_M_AMD64) || defined (_M_X64)) + bool sys::getHostCPUFeatures(StringMap &Features) { + unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0; + unsigned MaxLevel; +diff --git a/projects/CMakeLists.txt b/projects/CMakeLists.txt +index d3093985..b879db20 100644 +--- a/projects/CMakeLists.txt ++++ b/projects/CMakeLists.txt +@@ -1,7 +1,7 @@ + set(DXC_PROJECTS_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}) + set(DXC_PROJECTS_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}) + +-if(WIN32 AND HLSL_BUILD_DXILCONV) ++if(MSVC AND HLSL_BUILD_DXILCONV) + add_subdirectory(include/Tracing) + add_subdirectory(dxilconv) +-endif (WIN32 AND HLSL_BUILD_DXILCONV) ++endif (MSVC AND HLSL_BUILD_DXILCONV) +diff --git a/tools/clang/CMakeLists.txt b/tools/clang/CMakeLists.txt +index 71190336..328ffad8 100644 +--- a/tools/clang/CMakeLists.txt ++++ b/tools/clang/CMakeLists.txt +@@ -431,6 +431,9 @@ install(DIRECTORY include/clang-c + ) + + add_definitions( -D_GNU_SOURCE ) ++if (MINGW) ++ add_definitions( -DMS_SUPPORT_VARIABLE_LANGOPTS ) ++endif() + + option(CLANG_ENABLE_ARCMT "Build ARCMT." ON) + if (CLANG_ENABLE_ARCMT) +diff --git a/tools/clang/include/clang/AST/Attr.h b/tools/clang/include/clang/AST/Attr.h +index 4e282d68..a4b3a7f4 100644 +--- a/tools/clang/include/clang/AST/Attr.h ++++ b/tools/clang/include/clang/AST/Attr.h +@@ -149,6 +149,11 @@ public: + } + }; + ++// MinGW defines interface as struct ++#ifdef interface ++#undef interface ++#endif ++ + #include "clang/AST/Attrs.inc" + + inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, +diff --git a/tools/clang/include/clang/Analysis/CFG.h b/tools/clang/include/clang/Analysis/CFG.h +index 68ed8d3e..2649ab15 100644 +--- a/tools/clang/include/clang/Analysis/CFG.h ++++ b/tools/clang/include/clang/Analysis/CFG.h +@@ -913,8 +913,8 @@ public: + // Member templates useful for various batch operations over CFGs. + //===--------------------------------------------------------------------===// + +- template +- void VisitBlockStmts(CALLBACK& O) const { ++ template ++ void VisitBlockStmts(CallbackT& O) const { + for (const_iterator I=begin(), E=end(); I != E; ++I) + for (CFGBlock::const_iterator BI=(*I)->begin(), BE=(*I)->end(); + BI != BE; ++BI) { +diff --git a/tools/clang/tools/dxclib/CMakeLists.txt b/tools/clang/tools/dxclib/CMakeLists.txt +index 74927fd4..a85549bb 100644 +--- a/tools/clang/tools/dxclib/CMakeLists.txt ++++ b/tools/clang/tools/dxclib/CMakeLists.txt +@@ -37,4 +37,4 @@ endif (MSVC) + target_compile_definitions(dxclib + PRIVATE VERSION_STRING_SUFFIX=" for ${CMAKE_SYSTEM_NAME}") + +-add_dependencies(dxclib TablegenHLSLOptions dxcompiler) ++add_dependencies(dxclib TablegenHLSLOptions) +diff --git a/tools/clang/tools/dxclib/dxc.cpp b/tools/clang/tools/dxclib/dxc.cpp +index cdcfe2b3..2d219c54 100644 +--- a/tools/clang/tools/dxclib/dxc.cpp ++++ b/tools/clang/tools/dxclib/dxc.cpp +@@ -61,14 +61,14 @@ + #include "llvm/Support/MemoryBuffer.h" + #include "llvm/Support/Path.h" + #include "llvm/Support/raw_ostream.h" +-#ifdef _WIN32 ++#ifdef _MSC_VER + #include + #include + #endif + #include + #include + +-#ifdef _WIN32 ++#ifdef _MSC_VER + #pragma comment(lib, "version.lib") + #endif + +@@ -137,12 +137,12 @@ private: + IDxcBlob **ppResult); + + // Dia is only supported on Windows. +-#ifdef _WIN32 ++#ifdef _MSC_VER + // TODO : Refactor two functions below. There are duplicate functions in + // DxcContext in dxa.cpp + HRESULT GetDxcDiaTable(IDxcLibrary *pLibrary, IDxcBlob *pTargetBlob, + IDiaTable **ppTable, LPCWSTR tableName); +-#endif // _WIN32 ++#endif // _MSC_VER + + HRESULT FindModuleBlob(hlsl::DxilFourCC fourCC, IDxcBlob *pSource, + IDxcLibrary *pLibrary, IDxcBlob **ppTargetBlob); +@@ -1142,7 +1142,7 @@ HRESULT DxcContext::FindModuleBlob(hlsl::DxilFourCC fourCC, IDxcBlob *pSource, + + // This function is currently only supported on Windows due to usage of + // IDiaTable. +-#ifdef _WIN32 ++#ifdef _MSC_VER + // TODO : There is an identical code in DxaContext in Dxa.cpp. Refactor this + // function. + HRESULT DxcContext::GetDxcDiaTable(IDxcLibrary *pLibrary, IDxcBlob *pTargetBlob, +@@ -1176,7 +1176,7 @@ HRESULT DxcContext::GetDxcDiaTable(IDxcLibrary *pLibrary, IDxcBlob *pTargetBlob, + *ppTable = pTable.Detach(); + return S_OK; + } +-#endif // _WIN32 ++#endif // _MSC_VER + + bool GetDLLFileVersionInfo(const char *dllPath, unsigned int *version) { + // This function is used to get version information from the DLL file. +diff --git a/tools/clang/tools/dxcompiler/DXCompiler.cpp b/tools/clang/tools/dxcompiler/DXCompiler.cpp +index c5484414..68c56414 100644 +--- a/tools/clang/tools/dxcompiler/DXCompiler.cpp ++++ b/tools/clang/tools/dxcompiler/DXCompiler.cpp +@@ -16,7 +16,7 @@ + #include "dxc/config.h" + #include "llvm/Support/FileSystem.h" + #include "llvm/Support/ManagedStatic.h" +-#ifdef LLVM_ON_WIN32 ++#ifdef _MSC_VER + #include "dxcetw.h" + #endif + #include "dxillib.h" +diff --git a/tools/clang/tools/dxcompiler/DXCompiler.rc b/tools/clang/tools/dxcompiler/DXCompiler.rc +index 4bec9e09..75b2d9e6 100644 +--- a/tools/clang/tools/dxcompiler/DXCompiler.rc ++++ b/tools/clang/tools/dxcompiler/DXCompiler.rc +@@ -11,4 +11,6 @@ + #define VER_ORIGINALFILENAME_STR "DXCompiler.dll" + + // #include ++#ifdef _MSC_VER + #include "dxcetw.rc" ++#endif +diff --git a/tools/clang/tools/dxcompiler/dxcapi.cpp b/tools/clang/tools/dxcompiler/dxcapi.cpp +index a6a877cb..1b8054ed 100644 +--- a/tools/clang/tools/dxcompiler/dxcapi.cpp ++++ b/tools/clang/tools/dxcompiler/dxcapi.cpp +@@ -11,7 +11,7 @@ + + #include "dxc/Support/WinIncludes.h" + +-#ifdef _WIN32 ++#ifdef _MSC_VER + #define DXC_API_IMPORT __declspec(dllexport) + #else + #define DXC_API_IMPORT __attribute__((visibility("default"))) +@@ -21,7 +21,7 @@ + #include "dxc/config.h" + #include "dxc/dxcisense.h" + #include "dxc/dxctools.h" +-#ifdef _WIN32 ++#ifdef _MSC_VER + #include "dxcetw.h" + #endif + #include "dxc/DxilContainer/DxcContainerBuilder.h" +@@ -110,7 +110,7 @@ static HRESULT ThreadMallocDxcCreateInstance(REFCLSID rclsid, REFIID riid, + hr = CreateDxcLinker(riid, ppv); + } + // Note: The following targets are not yet enabled for non-Windows platforms. +-#ifdef _WIN32 ++#ifdef _MSC_VER + else if (IsEqualCLSID(rclsid, CLSID_DxcDiaDataSource)) { + hr = CreateDxcDiaDataSource(riid, ppv); + } +diff --git a/tools/clang/tools/dxcompiler/dxcompilerobj.cpp b/tools/clang/tools/dxcompiler/dxcompilerobj.cpp +index 0ee0d007..231737d1 100644 +--- a/tools/clang/tools/dxcompiler/dxcompilerobj.cpp ++++ b/tools/clang/tools/dxcompiler/dxcompilerobj.cpp +@@ -50,7 +50,7 @@ + #include "dxc/Support/dxcapi.use.h" + #include "dxc/Support/microcom.h" + +-#ifdef _WIN32 ++#ifdef _MSC_VER + #include "dxcetw.h" + #endif + #include "dxcompileradapter.h" +diff --git a/tools/clang/tools/dxcompiler/dxcpdbutils.cpp b/tools/clang/tools/dxcompiler/dxcpdbutils.cpp +index 2fc224f3..e3ad375d 100644 +--- a/tools/clang/tools/dxcompiler/dxcpdbutils.cpp ++++ b/tools/clang/tools/dxcompiler/dxcpdbutils.cpp +@@ -47,7 +47,7 @@ + #include + #include + +-#ifdef _WIN32 ++#ifdef _MSC_VER + #include "dxc/dxcpix.h" + #include + #endif +@@ -273,7 +273,7 @@ public: + }; + + struct DxcPdbUtils : public IDxcPdbUtils2 +-#ifdef _WIN32 ++#ifdef _MSC_VER + // Skip Pix debug info on linux for dia dependence. + , + public IDxcPixDxilDebugInfoFactory +@@ -843,7 +843,7 @@ public: + + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, + void **ppvObject) override { +-#ifdef _WIN32 ++#ifdef _MSC_VER + HRESULT hr = + DoBasicQueryInterface( + this, iid, ppvObject); +@@ -1071,7 +1071,7 @@ public: + return CopyBlobWide(m_Name, ppResult); + } + +-#ifdef _WIN32 ++#ifdef _MSC_VER + virtual STDMETHODIMP + NewDxcPixDxilDebugInfo(IDxcPixDxilDebugInfo **ppDxilDebugInfo) override { + if (!m_pDebugProgramBlob) +diff --git a/tools/clang/tools/dxcompiler/dxcvalidator.cpp b/tools/clang/tools/dxcompiler/dxcvalidator.cpp +index c24d6da7..d62307b0 100644 +--- a/tools/clang/tools/dxcompiler/dxcvalidator.cpp ++++ b/tools/clang/tools/dxcompiler/dxcvalidator.cpp +@@ -26,7 +26,7 @@ + #include "llvm/Support/MSFileSystem.h" + #include "llvm/Support/MemoryBuffer.h" + +-#ifdef _WIN32 ++#ifdef _MSC_VER + #include "dxcetw.h" + #endif + +-- +2.56.0 + diff --git a/build/dxc-arm64ec/patches/0002-MinGW-HLSL-language-options-COM-allocator-release-ve.patch b/build/dxc-arm64ec/patches/0002-MinGW-HLSL-language-options-COM-allocator-release-ve.patch new file mode 100644 index 0000000000..a255017521 --- /dev/null +++ b/build/dxc-arm64ec/patches/0002-MinGW-HLSL-language-options-COM-allocator-release-ve.patch @@ -0,0 +1,121 @@ +From 3e002e4e8a640dc059f25a208df1e11591f3d6d4 Mon Sep 17 00:00:00 2001 +From: Shitiz Garg +Date: Wed, 4 Nov 2026 05:16:46 +1100 +Subject: [PATCH 2/3] MinGW: HLSL language options, COM allocator, release + version + +- Fixed (HLSL) LangOptions on MinGW like the MSVC release; with the variable + ones HLSL's built-in types were never declared (every shader failed) +- CAllocator uses CoTaskMem* on MinGW: CComHeapPtr memory reaches callers + that free it with CoTaskMemFree (as in hexops' Zig port) +- utils/version/version.inc set to Microsoft's 1.8.2407.7 (416fab6b5), so + with HLSL_ENABLE_FIXED_VER the DXIL matches the release byte for byte + (444 of 449 test shaders identical, signed hash included; the rest differ + only in value numbering/declaration order or /Zi paths) + +Co-Authored-By: Claude Opus 5.5 +--- + lib/DxcSupport/WinAdapter.cpp | 13 +++++++++++++ + tools/clang/CMakeLists.txt | 5 ++--- + tools/clang/lib/Basic/LangOptions.cpp | 2 +- + utils/version/version.inc | 9 ++++++--- + 4 files changed, 22 insertions(+), 7 deletions(-) + +diff --git a/lib/DxcSupport/WinAdapter.cpp b/lib/DxcSupport/WinAdapter.cpp +index df1f9f46..c9a9aaf8 100644 +--- a/lib/DxcSupport/WinAdapter.cpp ++++ b/lib/DxcSupport/WinAdapter.cpp +@@ -17,11 +17,24 @@ + + //===--------------------------- CAllocator -------------------------------===// + ++#ifdef __MINGW32__ ++// CComHeapPtr is CHeapPtr here, and its memory reaches callers ++// that free it with CoTaskMemFree (ATL's CComHeapPtr uses the COM heap), so on ++// Windows CAllocator is the COM allocator (as in hexops' Zig port). ++void *CAllocator::Reallocate(void *p, size_t nBytes) throw() { ++ return CoTaskMemRealloc(p, nBytes); ++} ++void *CAllocator::Allocate(size_t nBytes) throw() { ++ return CoTaskMemAlloc(nBytes); ++} ++void CAllocator::Free(void *p) throw() { CoTaskMemFree(p); } ++#else + void *CAllocator::Reallocate(void *p, size_t nBytes) throw() { + return realloc(p, nBytes); + } + void *CAllocator::Allocate(size_t nBytes) throw() { return malloc(nBytes); } + void CAllocator::Free(void *p) throw() { free(p); } ++#endif + + #ifndef __MINGW32__ + +diff --git a/tools/clang/CMakeLists.txt b/tools/clang/CMakeLists.txt +index 328ffad8..9702cf82 100644 +--- a/tools/clang/CMakeLists.txt ++++ b/tools/clang/CMakeLists.txt +@@ -431,9 +431,8 @@ install(DIRECTORY include/clang-c + ) + + add_definitions( -D_GNU_SOURCE ) +-if (MINGW) +- add_definitions( -DMS_SUPPORT_VARIABLE_LANGOPTS ) +-endif() ++# Madeira: MinGW builds use the fixed (HLSL) language options, like the MSVC ++# release; with the variable ones HLSL's built-in types are never declared. + + option(CLANG_ENABLE_ARCMT "Build ARCMT." ON) + if (CLANG_ENABLE_ARCMT) +diff --git a/tools/clang/lib/Basic/LangOptions.cpp b/tools/clang/lib/Basic/LangOptions.cpp +index 87d20740..0b466583 100644 +--- a/tools/clang/lib/Basic/LangOptions.cpp ++++ b/tools/clang/lib/Basic/LangOptions.cpp +@@ -16,7 +16,7 @@ + /////////////////////////////////////////////////////////////////////////////// + using namespace clang; + +-#ifdef LLVM_ON_UNIX ++#if defined(LLVM_ON_UNIX) || defined(__MINGW32__) // Madeira: clang needs the definitions on MinGW too + #ifndef MS_SUPPORT_VARIABLE_LANGOPTS + #define LANGOPT(Name, Bits, Default, Description) const unsigned LangOptionsBase::Name; + #define LANGOPT_BOOL(Name, Default, Description) const bool LangOptionsBase::Name; +diff --git a/utils/version/version.inc b/utils/version/version.inc +index 4e5d9f73..1ce97be5 100644 +--- a/utils/version/version.inc ++++ b/utils/version/version.inc +@@ -1,5 +1,8 @@ + #pragma once + ++// Madeira: the version of Microsoft's release build 1.8.2407.7 (the copy games ++// ship), so the DXIL this build emits matches theirs byte for byte. ++ + #ifdef RC_COMPANY_NAME + #undef RC_COMPANY_NAME + #endif +@@ -23,12 +26,12 @@ + #ifdef RC_VERSION_FIELD_4 + #undef RC_VERSION_FIELD_4 + #endif +-#define RC_VERSION_FIELD_4 0 ++#define RC_VERSION_FIELD_4 7 + + #ifdef RC_FILE_VERSION + #undef RC_FILE_VERSION + #endif +-#define RC_FILE_VERSION "1.8.2407.0" ++#define RC_FILE_VERSION "1.8.2407.7" + + #ifdef RC_FILE_DESCRIPTION + #undef RC_FILE_DESCRIPTION +@@ -49,7 +52,7 @@ + #ifdef RC_PRODUCT_VERSION + #undef RC_PRODUCT_VERSION + #endif +-#define RC_PRODUCT_VERSION "1.8.2407.0" ++#define RC_PRODUCT_VERSION "1.8.2407.7 (416fab6b5)" + + #ifdef HLSL_TOOL_NAME + #undef HLSL_TOOL_NAME +-- +2.56.0 + diff --git a/build/dxc-arm64ec/patches/0003-Opt-in-MADEIRA_DXC_DXIL-0-no-dxil.dll-built-in-valid.patch b/build/dxc-arm64ec/patches/0003-Opt-in-MADEIRA_DXC_DXIL-0-no-dxil.dll-built-in-valid.patch new file mode 100644 index 0000000000..70c1b8bc34 --- /dev/null +++ b/build/dxc-arm64ec/patches/0003-Opt-in-MADEIRA_DXC_DXIL-0-no-dxil.dll-built-in-valid.patch @@ -0,0 +1,409 @@ +From a0608d9a3e274e945a0e050aa1916d0a06073c0f Mon Sep 17 00:00:00 2001 +From: Shitiz Garg +Date: Wed, 4 Nov 2026 05:37:18 +1100 +Subject: [PATCH 3/3] Opt-in MADEIRA_DXC_DXIL=0: no dxil.dll, built-in + validator, open signing + +Under Madeira a game's dxil.dll is x64 code that runs emulated, once per +compiled shader. With the environment variable MADEIRA_DXC_DXIL=0 the +built-in validator (the same 1.8.2407 source dxil.dll is built from) +validates, and the container hash dxil.dll would write is computed by +hexops' MachSiegbertVogtDXCSA (MIT/Apache, from hexops/DirectXShaderCompiler +4190bb0c9), after a successful validation. The "not signed" warning is +not emitted in that mode. Unset, nothing changes. + +Co-Authored-By: Claude Opus 5.5 +--- + tools/clang/tools/dxcompiler/CMakeLists.txt | 2 + + .../dxcompiler/MachSiegbertVogtDXCSA.cpp | 234 ++++++++++++++++++ + .../tools/dxcompiler/MachSiegbertVogtDXCSA.h | 20 ++ + tools/clang/tools/dxcompiler/dxcutil.cpp | 5 +- + tools/clang/tools/dxcompiler/dxillib.cpp | 30 ++- + tools/clang/tools/dxcompiler/dxillib.h | 8 + + 6 files changed, 297 insertions(+), 2 deletions(-) + create mode 100644 tools/clang/tools/dxcompiler/MachSiegbertVogtDXCSA.cpp + create mode 100644 tools/clang/tools/dxcompiler/MachSiegbertVogtDXCSA.h + +diff --git a/tools/clang/tools/dxcompiler/CMakeLists.txt b/tools/clang/tools/dxcompiler/CMakeLists.txt +index d7aec327..d1ebe805 100644 +--- a/tools/clang/tools/dxcompiler/CMakeLists.txt ++++ b/tools/clang/tools/dxcompiler/CMakeLists.txt +@@ -58,6 +58,7 @@ set(SOURCES + DXCompiler.def + dxcfilesystem.cpp + dxillib.cpp ++ MachSiegbertVogtDXCSA.cpp + dxcutil.cpp + dxcdisassembler.cpp + dxcpdbutils.cpp +@@ -76,6 +77,7 @@ set(SOURCES + dxcdisassembler.cpp + dxcpdbutils.cpp + dxillib.cpp ++ MachSiegbertVogtDXCSA.cpp + dxcvalidator.cpp + dxclinker.cpp + dxcshadersourceinfo.cpp +diff --git a/tools/clang/tools/dxcompiler/MachSiegbertVogtDXCSA.cpp b/tools/clang/tools/dxcompiler/MachSiegbertVogtDXCSA.cpp +new file mode 100644 +index 00000000..a6d6a539 +--- /dev/null ++++ b/tools/clang/tools/dxcompiler/MachSiegbertVogtDXCSA.cpp +@@ -0,0 +1,234 @@ ++// Licensed under the Mach engine license (Apache or MIT at your choosing.) For details ++// and a copy of this license, see https://github.com/hexops/mach/blob/main/LICENSE ++// This copyright header, and a copy of the above open source licenses, must be provided ++// with any redistributions of this software. ++ ++#include ++#include "MachSiegbertVogtDXCSA.h" ++ ++// Note: If this algorithm looks familiar to you, it is - but not exactly. Fun! ++ ++static uint8_t PADDING[64] = ++{ ++ 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ++ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ++ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ++ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ++ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ++ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ++ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ++ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ++}; ++ ++#define F(x, y, z) (((x) & (y)) | ((~x) & (z))) ++#define G(x, y, z) (((x) & (z)) | ((y) & (~z))) ++#define H(x, y, z) ((x) ^ (y) ^ (z)) ++#define I(x, y, z) ((y) ^ ((x) | (~z))) ++#define ROTL(x, n) (((x) << (n)) | ((x) >> (32-(n)))) ++ ++#define FF(a, b, c, d, x, s, ac) { (a) += F((b), (c), (d)) + (x) + (uint32_t)(ac); (a) = ROTL((a), (s)); (a) += (b); } ++#define GG(a, b, c, d, x, s, ac) { (a) += G((b), (c), (d)) + (x) + (uint32_t)(ac); (a) = ROTL((a), (s)); (a) += (b); } ++#define HH(a, b, c, d, x, s, ac) { (a) += H((b), (c), (d)) + (x) + (uint32_t)(ac); (a) = ROTL((a), (s)); (a) += (b); } ++#define II(a, b, c, d, x, s, ac) { (a) += I((b), (c), (d)) + (x) + (uint32_t)(ac); (a) = ROTL((a), (s)); (a) += (b); } ++ ++// Round 1 ++#define S11 7 ++#define S12 12 ++#define S13 17 ++#define S14 22 ++ ++// Round 2 ++#define S21 5 ++#define S22 9 ++#define S23 14 ++#define S24 20 ++ ++// Round 3 ++#define S31 4 ++#define S32 11 ++#define S33 16 ++#define S34 23 ++#define S41 6 ++ ++// Round 4 ++#define S42 10 ++#define S43 15 ++#define S44 21 ++ ++// Message digest computation ++typedef struct Context { ++ uint32_t i[2]; // bits handled mod 2^64 ++ uint32_t buf[4]; // scratch buffer ++ uint8_t in[64]; // input buffer ++ uint8_t digest[16]; // digest after final() ++} Context; ++ ++static void transform(uint32_t* buf, uint32_t* in) { ++ uint32_t a = buf[0], b = buf[1], c = buf[2], d = buf[3]; ++ ++ // round 1 ++ FF(a, b, c, d, in[ 0], S11, (uint32_t) 3614090360u); ++ FF(d, a, b, c, in[ 1], S12, (uint32_t) 3905402710u); ++ FF(c, d, a, b, in[ 2], S13, (uint32_t) 606105819u); ++ FF(b, c, d, a, in[ 3], S14, (uint32_t) 3250441966u); ++ FF(a, b, c, d, in[ 4], S11, (uint32_t) 4118548399u); ++ FF(d, a, b, c, in[ 5], S12, (uint32_t) 1200080426u); ++ FF(c, d, a, b, in[ 6], S13, (uint32_t) 2821735955u); ++ FF(b, c, d, a, in[ 7], S14, (uint32_t) 4249261313u); ++ FF(a, b, c, d, in[ 8], S11, (uint32_t) 1770035416u); ++ FF(d, a, b, c, in[ 9], S12, (uint32_t) 2336552879u); ++ FF(c, d, a, b, in[10], S13, (uint32_t) 4294925233u); ++ FF(b, c, d, a, in[11], S14, (uint32_t) 2304563134u); ++ FF(a, b, c, d, in[12], S11, (uint32_t) 1804603682u); ++ FF(d, a, b, c, in[13], S12, (uint32_t) 4254626195u); ++ FF(c, d, a, b, in[14], S13, (uint32_t) 2792965006u); ++ FF(b, c, d, a, in[15], S14, (uint32_t) 1236535329u); ++ ++ // round 2 ++ GG(a, b, c, d, in[ 1], S21, (uint32_t) 4129170786u); ++ GG(d, a, b, c, in[ 6], S22, (uint32_t) 3225465664u); ++ GG(c, d, a, b, in[11], S23, (uint32_t) 643717713u); ++ GG(b, c, d, a, in[ 0], S24, (uint32_t) 3921069994u); ++ GG(a, b, c, d, in[ 5], S21, (uint32_t) 3593408605u); ++ GG(d, a, b, c, in[10], S22, (uint32_t) 38016083u); ++ GG(c, d, a, b, in[15], S23, (uint32_t) 3634488961u); ++ GG(b, c, d, a, in[ 4], S24, (uint32_t) 3889429448u); ++ GG(a, b, c, d, in[ 9], S21, (uint32_t) 568446438u); ++ GG(d, a, b, c, in[14], S22, (uint32_t) 3275163606u); ++ GG(c, d, a, b, in[ 3], S23, (uint32_t) 4107603335u); ++ GG(b, c, d, a, in[ 8], S24, (uint32_t) 1163531501u); ++ GG(a, b, c, d, in[13], S21, (uint32_t) 2850285829u); ++ GG(d, a, b, c, in[ 2], S22, (uint32_t) 4243563512u); ++ GG(c, d, a, b, in[ 7], S23, (uint32_t) 1735328473u); ++ GG(b, c, d, a, in[12], S24, (uint32_t) 2368359562u); ++ ++ // round 3 ++ HH(a, b, c, d, in[ 5], S31, (uint32_t) 4294588738u); ++ HH(d, a, b, c, in[ 8], S32, (uint32_t) 2272392833u); ++ HH(c, d, a, b, in[11], S33, (uint32_t) 1839030562u); ++ HH(b, c, d, a, in[14], S34, (uint32_t) 4259657740u); ++ HH(a, b, c, d, in[ 1], S31, (uint32_t) 2763975236u); ++ HH(d, a, b, c, in[ 4], S32, (uint32_t) 1272893353u); ++ HH(c, d, a, b, in[ 7], S33, (uint32_t) 4139469664u); ++ HH(b, c, d, a, in[10], S34, (uint32_t) 3200236656u); ++ HH(a, b, c, d, in[13], S31, (uint32_t) 681279174u); ++ HH(d, a, b, c, in[ 0], S32, (uint32_t) 3936430074u); ++ HH(c, d, a, b, in[ 3], S33, (uint32_t) 3572445317u); ++ HH(b, c, d, a, in[ 6], S34, (uint32_t) 76029189u); ++ HH(a, b, c, d, in[ 9], S31, (uint32_t) 3654602809u); ++ HH(d, a, b, c, in[12], S32, (uint32_t) 3873151461u); ++ HH(c, d, a, b, in[15], S33, (uint32_t) 530742520u); ++ HH(b, c, d, a, in[ 2], S34, (uint32_t) 3299628645u); ++ ++ // round 4 ++ II(a, b, c, d, in[ 0], S41, (uint32_t) 4096336452u); ++ II(d, a, b, c, in[ 7], S42, (uint32_t) 1126891415u); ++ II(c, d, a, b, in[14], S43, (uint32_t) 2878612391u); ++ II(b, c, d, a, in[ 5], S44, (uint32_t) 4237533241u); ++ II(a, b, c, d, in[12], S41, (uint32_t) 1700485571u); ++ II(d, a, b, c, in[ 3], S42, (uint32_t) 2399980690u); ++ II(c, d, a, b, in[10], S43, (uint32_t) 4293915773u); ++ II(b, c, d, a, in[ 1], S44, (uint32_t) 2240044497u); ++ II(a, b, c, d, in[ 8], S41, (uint32_t) 1873313359u); ++ II(d, a, b, c, in[15], S42, (uint32_t) 4264355552u); ++ II(c, d, a, b, in[ 6], S43, (uint32_t) 2734768916u); ++ II(b, c, d, a, in[13], S44, (uint32_t) 1309151649u); ++ II(a, b, c, d, in[ 4], S41, (uint32_t) 4149444226u); ++ II(d, a, b, c, in[11], S42, (uint32_t) 3174756917u); ++ II(c, d, a, b, in[ 2], S43, (uint32_t) 718787259u); ++ II(b, c, d, a, in[ 9], S44, (uint32_t) 3951481745u); ++ ++ buf[0] += a; ++ buf[1] += b; ++ buf[2] += c; ++ buf[3] += d; ++} ++ ++static void update(Context* ctx, uint8_t* in_buf, uint32_t in_len) { ++ uint32_t in[16]; ++ int32_t mdi = 0; ++ uint32_t i = 0; ++ uint32_t ii = 0; ++ ++ mdi = (int32_t)((ctx->i[0] >> 3) & 0x3F); // number of bytes mod 64 ++ ++ // update # of bits ++ if ((ctx->i[0] + ((uint32_t)in_len << 3)) < ctx->i[0]) ctx->i[1]++; ++ ++ ctx->i[0] += ((uint32_t)in_len << 3); ++ ctx->i[1] += ((uint32_t)in_len >> 29); ++ ++ while (in_len--) { ++ ctx->in[mdi++] = *in_buf++; // add new char, increment mdi ++ if (mdi == 0x40) { ++ for (i = 0, ii = 0; i < 16; i++, ii += 4) { ++ in[i] = (((uint32_t)ctx->in[ii + 3]) << 24); ++ in[i] |= (((uint32_t)ctx->in[ii + 2]) << 16); ++ in[i] |= (((uint32_t)ctx->in[ii + 1]) << 8); ++ in[i] |= ((uint32_t)ctx->in[ii]); ++ } ++ transform(ctx->buf, in); ++ mdi = 0; ++ } ++ } ++} ++ ++static const uint32_t secret_hash_offset = 0x14; ++ ++void machSiegbertVogtDXCSA(uint8_t* data, uint32_t data_size, uint32_t secret_out[4]) ++{ ++ // Initialize ctx ++ uint64_t rng = 0; ++ Context ctx; ++ ctx.i[0] = ctx.i[1] = (uint32_t)0; ++ ctx.buf[0] = (uint32_t)0x67452301 + (rng * 11); ++ ctx.buf[1] = (uint32_t)0xefcdab89 + (rng * 71); ++ ctx.buf[2] = (uint32_t)0x98badcfe + (rng * 37); ++ ctx.buf[3] = (uint32_t)0x10325476 + (rng * 97); ++ ++ // Note: first 4 bytes of bin are "DXBC" (IL) header/file-magic, then 16-byte signing hash, ++ // then remainder of the file contents. ++ data_size -= secret_hash_offset; ++ data += secret_hash_offset; ++ ++ uint32_t num_bits = data_size * 8; ++ ++ uint32_t full_chunks_size = data_size & 0xffffffc0; ++ update(&ctx, data, full_chunks_size); ++ ++ uint32_t last_chunk_size = data_size - full_chunks_size; ++ uint32_t padding_size = 64 - last_chunk_size; ++ uint8_t* last_chunk_data = data + full_chunks_size; ++ ++ if (last_chunk_size >= 56) { ++ update(&ctx, last_chunk_data, last_chunk_size); ++ ++ // Pad to 56 mod 64 ++ update(&ctx, PADDING, padding_size); ++ ++ uint32_t in[16]; ++ memset(in, 0, sizeof(in)); ++ in[0] = num_bits; ++ in[15] = (num_bits >> 2) | 1; ++ ++ transform(ctx.buf, in); ++ } else { ++ update(&ctx, (uint8_t*) &num_bits, 4); ++ ++ if (last_chunk_size) update(&ctx, last_chunk_data, last_chunk_size); ++ ++ // Adjust for the space used for num_bits ++ last_chunk_size += sizeof(uint32_t); ++ padding_size -= sizeof(uint32_t); ++ ++ // Pad to 56 mod 64 ++ memcpy(&ctx.in[last_chunk_size], PADDING, padding_size); ++ ++ ((uint32_t*)ctx.in)[15] = (num_bits >> 2) | 1; ++ ++ uint32_t in[16]; ++ memcpy(in, ctx.in, 64); ++ transform(ctx.buf, in); ++ } ++ memcpy(secret_out, ctx.buf, 4 * sizeof(uint32_t)); ++} +\ No newline at end of file +diff --git a/tools/clang/tools/dxcompiler/MachSiegbertVogtDXCSA.h b/tools/clang/tools/dxcompiler/MachSiegbertVogtDXCSA.h +new file mode 100644 +index 00000000..ee591010 +--- /dev/null ++++ b/tools/clang/tools/dxcompiler/MachSiegbertVogtDXCSA.h +@@ -0,0 +1,20 @@ ++// Licensed under the Mach engine license (Apache or MIT at your choosing.) For details ++// and a copy of this license, see https://github.com/hexops/mach/blob/main/LICENSE ++// This copyright header, and a copy of the above open source licenses, must be provided ++// with any redistributions of this software. ++ ++#pragma once ++#ifndef MACH_SIEGBERT_VOGT_DXCSA_H ++#define MACH_SIEGBERT_VOGT_DXCSA_H ++ ++#include ++ ++// Performs Mach Siegbert Vogt DX Code Signing Algorithm on a DXIL binary file / container blob. ++// ++// This is an open source alternative to dxil.dll's proprietary code signing. ++// ++// Writes the code signing secret to ++// the `secret_out` out parameter. ++void machSiegbertVogtDXCSA(uint8_t* p_data, uint32_t dw_size, uint32_t secret_out[4]); ++ ++#endif // MACH_SIEGBERT_VOGT_DXCSA_H +diff --git a/tools/clang/tools/dxcompiler/dxcutil.cpp b/tools/clang/tools/dxcompiler/dxcutil.cpp +index b49e01af..23d8fbad 100644 +--- a/tools/clang/tools/dxcompiler/dxcutil.cpp ++++ b/tools/clang/tools/dxcompiler/dxcutil.cpp +@@ -174,7 +174,7 @@ HRESULT ValidateAndAssembleToContainer(AssembleInputs &inputs) { + pValidator.QueryInterface(&pValidator2); + } + +- if (bInternalValidator && ++ if (bInternalValidator && !MadeiraNativeDxil() && + inputs.SelectValidator != hlsl::options::ValidatorSelection::Internal) { + if (inputs.pDiag) { + unsigned diagID = inputs.pDiag->getCustomDiagID( +@@ -269,6 +269,9 @@ HRESULT ValidateAndAssembleToContainer(AssembleInputs &inputs) { + std::swap(inputs.pOutputContainerBlob, pValidatedBlob); + } + pValidator.Release(); ++ // Madeira: sign as dxil.dll does after a successful validation. ++ if (bInternalValidator && MadeiraNativeDxil() && SUCCEEDED(valHR)) ++ MadeiraSignContainer(inputs.pOutputContainerBlob); + + return valHR; + } +diff --git a/tools/clang/tools/dxcompiler/dxillib.cpp b/tools/clang/tools/dxcompiler/dxillib.cpp +index 72abc869..27381c10 100644 +--- a/tools/clang/tools/dxcompiler/dxillib.cpp ++++ b/tools/clang/tools/dxcompiler/dxillib.cpp +@@ -13,6 +13,10 @@ + #include "dxc/Support/Global.h" // For DXASSERT + #include "dxc/Support/dxcapi.use.h" + #include "llvm/Support/Mutex.h" ++#include "dxc/DxilContainer/DxilContainer.h" ++#include "MachSiegbertVogtDXCSA.h" ++#include ++#include + + using namespace dxc; + +@@ -23,10 +27,34 @@ static llvm::sys::Mutex *cs = nullptr; + + // Check if we can successfully get IDxcValidator from dxil.dll + // This function is to prevent multiple attempts to load dxil.dll ++bool MadeiraNativeDxil() { ++ static const bool native = [] { ++ const char *value = getenv("MADEIRA_DXC_DXIL"); ++ return value != nullptr && strcmp(value, "0") == 0; ++ }(); ++ return native; ++} ++ ++void MadeiraSignContainer(IDxcBlob *pContainer) { ++ if (pContainer == nullptr || pContainer->GetBufferSize() < sizeof(hlsl::DxilContainerHeader)) ++ return; ++ hlsl::DxilContainerHeader *pHeader = ++ reinterpret_cast(pContainer->GetBufferPointer()); ++ if (pHeader->HeaderFourCC != hlsl::DFCC_Container) ++ return; ++ uint32_t hash[4] = {}; ++ machSiegbertVogtDXCSA(reinterpret_cast(pHeader), ++ (uint32_t)pContainer->GetBufferSize(), hash); ++ memcpy(&pHeader->Hash, hash, sizeof(hash)); ++} ++ + HRESULT DxilLibInitialize() { + cs = new llvm::sys::Mutex; + cs->lock(); +- g_DllLibResult = g_DllSupport.InitializeForDll(kDxilLib, "DxcCreateInstance"); ++ if (MadeiraNativeDxil()) ++ g_DllLibResult = E_FAIL; // never load dxil.dll; DxilLibIsEnabled stays false ++ else ++ g_DllLibResult = g_DllSupport.InitializeForDll(kDxilLib, "DxcCreateInstance"); + cs->unlock(); + return S_OK; + } +diff --git a/tools/clang/tools/dxcompiler/dxillib.h b/tools/clang/tools/dxcompiler/dxillib.h +index 879d0234..0adc2123 100644 +--- a/tools/clang/tools/dxcompiler/dxillib.h ++++ b/tools/clang/tools/dxcompiler/dxillib.h +@@ -16,6 +16,14 @@ + #include "dxc/Support/WinIncludes.h" + #include "dxc/WinAdapter.h" + ++// Madeira: environment MADEIRA_DXC_DXIL=0 leaves dxil.dll alone. The built-in ++// validator (the same 1.8.2407 code dxil.dll is built from) validates, and ++// MadeiraSignContainer writes the container hash dxil.dll would have written. ++// Under Madeira a game's dxil.dll is x64 code that runs emulated. ++struct IDxcBlob; ++bool MadeiraNativeDxil(); ++void MadeiraSignContainer(IDxcBlob *pContainer); ++ + // Initialize Dxil library. + HRESULT DxilLibInitialize(); + +-- +2.56.0 + diff --git a/build/dxc-arm64ec/patches/0004-Opt-in-MADEIRA_DXC_ARGS_LOG-_ADD-_DROP-log-and-rewri.patch b/build/dxc-arm64ec/patches/0004-Opt-in-MADEIRA_DXC_ARGS_LOG-_ADD-_DROP-log-and-rewri.patch new file mode 100644 index 0000000000..85ae8b09e3 --- /dev/null +++ b/build/dxc-arm64ec/patches/0004-Opt-in-MADEIRA_DXC_ARGS_LOG-_ADD-_DROP-log-and-rewri.patch @@ -0,0 +1,155 @@ +From f68320c50494a3e315a257965a8b164b438f77a5 Mon Sep 17 00:00:00 2001 +From: Shitiz Garg +Date: Sun, 8 Nov 2026 00:22:55 +1100 +Subject: [PATCH] Opt-in MADEIRA_DXC_ARGS_LOG / _ADD / _DROP: log and rewrite + the game's compile arguments + +--- + .../clang/tools/dxcompiler/dxcompilerobj.cpp | 117 ++++++++++++++++++ + 1 file changed, 117 insertions(+) + +diff --git a/tools/clang/tools/dxcompiler/dxcompilerobj.cpp b/tools/clang/tools/dxcompiler/dxcompilerobj.cpp +index 231737d1..3a5d6ca7 100644 +--- a/tools/clang/tools/dxcompiler/dxcompilerobj.cpp ++++ b/tools/clang/tools/dxcompiler/dxcompilerobj.cpp +@@ -40,6 +40,10 @@ + #include "dxc/Support/dxcfilesystem.h" + #include "dxc/dxcapi.internal.h" + #include "dxcutil.h" ++#include ++#include ++#include ++#include + + #include "dxc/Support/DxcLangExtensionsHelper.h" + #include "dxc/Support/FileIOHelper.h" +@@ -462,6 +466,113 @@ static HRESULT ErrorWithString(const std::string &error, REFIID riid, + return S_OK; + } + ++// Madeira (madeira-duo dxc-args): opt-in, all off by default. ++// MADEIRA_DXC_ARGS_LOG=1 log each distinct argument set the game passes ++// (flags only: -D values, -E/-Fo/-Fd/file names ++// are summarised), with a running count. ++// MADEIRA_DXC_ARGS_DROP=a;b drop these arguments (exact match; a value-taking ++// option drops its value too, e.g. "-O1" or "-Zi"). ++// MADEIRA_DXC_ARGS_ADD=a;b append these arguments (e.g. "-O3"). ++// Lines go to Wine's debug output (__wine_dbg_output), one record < 1000 bytes. ++namespace madeira_dxc_args { ++static std::mutex g_lock; ++static std::map *g_seen; ++static unsigned g_total; ++static int g_log = -1; ++static std::vector *g_add, *g_drop; ++static void out(const char *line) { ++ typedef int(__cdecl * fn_t)(const char *); ++ static fn_t fn; ++ static int looked; ++ if (!looked) { ++ HMODULE nt = GetModuleHandleA("ntdll.dll"); ++ fn = nt ? (fn_t)(void *)GetProcAddress(nt, "__wine_dbg_output") : nullptr; ++ looked = 1; ++ } ++ if (fn) fn(line); ++} ++static std::vector *split(const char *v) { ++ auto *r = new std::vector(); ++ if (!v) return r; ++ std::string cur; ++ for (const char *c = v;; c++) { ++ if (*c == ';' || !*c) { ++ if (!cur.empty()) r->push_back(std::wstring(cur.begin(), cur.end())); ++ cur.clear(); ++ if (!*c) break; ++ } else cur += *c; ++ } ++ return r; ++} ++static void init() { ++ std::lock_guard g(g_lock); ++ if (g_log >= 0) return; ++ const char *l = getenv("MADEIRA_DXC_ARGS_LOG"); ++ g_add = split(getenv("MADEIRA_DXC_ARGS_ADD")); ++ g_drop = split(getenv("MADEIRA_DXC_ARGS_DROP")); ++ g_seen = new std::map(); ++ if (g_log || !g_add->empty() || !g_drop->empty() || (l && l[0] == '1')) { ++ char b[600]; ++ snprintf(b, sizeof b, "[dxc-args] madeira: log %d, %u argument(s) added, %u dropped (MADEIRA_DXC_ARGS_LOG/ADD/DROP)\n", ++ (l && l[0] == '1') ? 1 : 0, (unsigned)g_add->size(), (unsigned)g_drop->size()); ++ out(b); ++ } ++ g_log = (l && l[0] == '1') ? 1 : 0; // last: other threads read the lists only after this ++} ++static std::string narrow(LPCWSTR w) { ++ std::string r; ++ for (; w && *w; w++) r += (*w < 128) ? (char)*w : '?'; ++ return r; ++} ++// Options whose next argument is a per-shader value. ++static bool value_opt(const std::string &a) { ++ static const char *const v[] = {"-E", "-T", "-Fo", "-Fd", "-Fc", "-Fe", "-Fh", "-Fre", "-Frs", "-Fsh", "-Vn", "-I", "-D", ++ "-setprivate", "-setrootsignature", "-extractrootsignature", nullptr}; ++ for (int i = 0; v[i]; i++) if (a == v[i]) return true; ++ return false; ++} ++static bool value_opt_w(LPCWSTR w) { return value_opt(narrow(w)); } ++static void log_args(LPCWSTR *args, UINT32 n) { ++ std::string key; ++ unsigned defines = 0; ++ for (UINT32 i = 0; i < n; i++) { ++ std::string a = narrow(args[i]); ++ if (a.empty() || (a[0] != '-' && a[0] != '/')) continue; // a file name ++ if (a.compare(1, 1, "D") == 0) { defines++; if (a.size() == 2) i++; continue; } ++ if (a == "-T" && i + 1 < n) { key += "-T " + narrow(args[i + 1]).substr(0, 2) + "_x "; i++; continue; } // stage, not the model ++ if (value_opt(a)) { i++; continue; } ++ if (a.compare(0, 2, "-E") == 0 || a.compare(0, 2, "-T") == 0) continue; // -Emain / -Tvs_6_0 joined ++ key += a; key += ' '; ++ } ++ char b[990]; ++ std::lock_guard g(g_lock); ++ g_total++; ++ unsigned &c = (*g_seen)[key]; ++ c++; ++ if (c == 1 && g_seen->size() <= 64) { ++ snprintf(b, sizeof b, "[dxc-args] new set #%u (compile %u, %u -D): %.880s\n", (unsigned)g_seen->size(), g_total, defines, key.c_str()); ++ out(b); ++ } ++ if (!(g_total % 2000)) { ++ snprintf(b, sizeof b, "[dxc-args] %u compiles, %u distinct sets\n", g_total, (unsigned)g_seen->size()); ++ out(b); ++ } ++} ++// The argument list the compile uses: the game's, minus DROP, plus ADD. ++static void rewrite(LPCWSTR *&args, UINT32 &n, std::vector &store) { ++ if (g_drop->empty() && g_add->empty()) return; ++ for (UINT32 i = 0; i < n; i++) { ++ bool drop = false; ++ for (auto &d : *g_drop) if (args[i] && d == args[i]) drop = true; ++ if (drop) { if (value_opt_w(args[i]) && i + 1 < n) i++; continue; } ++ store.push_back(args[i]); ++ } ++ for (auto &a : *g_add) store.push_back(a.c_str()); ++ args = store.data(); ++ n = (UINT32)store.size(); ++} ++} // namespace madeira_dxc_args ++ + class DxcCompiler : public IDxcCompiler3, + public IDxcLangExtensions3, + public IDxcContainerEvent, +@@ -539,6 +650,12 @@ public: + + *ppResult = nullptr; + ++ // Madeira dxc-args: log and/or rewrite the game's arguments (opt-in). ++ std::vector madeiraArgs; ++ madeira_dxc_args::init(); ++ if (madeira_dxc_args::g_log) madeira_dxc_args::log_args(pArguments, argCount); ++ madeira_dxc_args::rewrite(pArguments, argCount, madeiraArgs); ++ + HRESULT hr = S_OK; + CComPtr utf8Source; + CComPtr pOutputStream; +-- +2.56.0 + diff --git a/build/dxc-arm64ec/patches/0005-mem2reg-find-the-first-reference-in-a-block-from-the.patch b/build/dxc-arm64ec/patches/0005-mem2reg-find-the-first-reference-in-a-block-from-the.patch new file mode 100644 index 0000000000..7ace254fb4 --- /dev/null +++ b/build/dxc-arm64ec/patches/0005-mem2reg-find-the-first-reference-in-a-block-from-the.patch @@ -0,0 +1,131 @@ +From e130005f4e09b3f1d6a320f4ce1cc15ce2ed1844 Mon Sep 17 00:00:00 2001 +From: Shitiz Garg +Date: Sat, 14 Nov 2026 23:45:05 +1100 +Subject: [PATCH 5/6] mem2reg: find the first reference in a block from the + alloca's own uses + +ComputeLiveInBlocks walked each defining-and-using block from its start +for every alloca until it met a load or store of that alloca. Shaders that +inline into a few huge blocks with many allocas make that quadratic: on +Path of Exile 2's shaders it was 19% of all compile time (PromoteMem2Reg::run +on a 100 Hz CPU profile on the iPhone). + +Take the earliest of the alloca's own loads and stores in each block instead, +ordered by LargeBlockInfo's per-block numbering, which is computed once per +block and shared by every alloca. The answer is the same, so the output +doesn't change. MADEIRA_DXC_MEM2REG_SCAN=1 goes back to the walk. + +Signed-off-by: Shitiz Garg +Co-Authored-By: Claude Opus 5.5 +--- + .../Utils/PromoteMemoryToRegister.cpp | 59 ++++++++++++++++++- + 1 file changed, 56 insertions(+), 3 deletions(-) + +diff --git a/lib/Transforms/Utils/PromoteMemoryToRegister.cpp b/lib/Transforms/Utils/PromoteMemoryToRegister.cpp +index b452d238..962c2edb 100644 +--- a/lib/Transforms/Utils/PromoteMemoryToRegister.cpp ++++ b/lib/Transforms/Utils/PromoteMemoryToRegister.cpp +@@ -39,6 +39,7 @@ + #include "llvm/IR/Module.h" + #include "llvm/Transforms/Utils/Local.h" + #include ++#include + using namespace llvm; + + #define DEBUG_TYPE "mem2reg" +@@ -298,7 +299,8 @@ private: + void ComputeLiveInBlocks(AllocaInst *AI, AllocaInfo &Info, + const SmallPtrSetImpl &DefBlocks, + SmallPtrSetImpl &LiveInBlocks, +- BasicBlock *LifetimeStartBB); ++ BasicBlock *LifetimeStartBB, ++ LargeBlockInfo &LBI); + void RenamePass(BasicBlock *BB, BasicBlock *Pred, + RenamePassData::ValVector &IncVals, + std::vector &Worklist); +@@ -640,7 +642,7 @@ void PromoteMem2Reg::run() { + // Determine which blocks the value is live in. These are blocks which lead + // to uses. + SmallPtrSet LiveInBlocks; +- ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks, LifetimeStartBB); ++ ComputeLiveInBlocks(AI, Info, DefBlocks, LiveInBlocks, LifetimeStartBB, LBI); + + // If there is a lifetime start block, add it to the def blocks now. + // This ensures that the block that holds the lifetime.start call is treated +@@ -852,7 +854,8 @@ void PromoteMem2Reg::ComputeLiveInBlocks( + AllocaInst *AI, AllocaInfo &Info, + const SmallPtrSetImpl &DefBlocks, + SmallPtrSetImpl &LiveInBlocks, +- BasicBlock *LifetimeStartBB) { ++ BasicBlock *LifetimeStartBB, ++ LargeBlockInfo &LBI) { + + // To determine liveness, we must iterate through the predecessors of blocks + // where the def is live. Blocks are added to the worklist if we need to +@@ -863,6 +866,8 @@ void PromoteMem2Reg::ComputeLiveInBlocks( + // If any of the using blocks is also a definition block, check to see if the + // definition occurs before or after the use. If it happens before the use, + // the value isn't really live-in. ++ SmallDenseMap, 16> FirstReference; ++ bool FirstReferenceDone = false; + for (unsigned i = 0, e = LiveInBlockWorklist.size(); i != e; ++i) { + BasicBlock *BB = LiveInBlockWorklist[i]; + if (!DefBlocks.count(BB)) +@@ -882,6 +887,54 @@ void PromoteMem2Reg::ComputeLiveInBlocks( + + // Okay, this is a block that both uses and defines the value. If the first + // reference to the alloca is a def (store), then we know it isn't live-in. ++ // ++ // Madeira: the walk below goes from the start of the block for every ++ // alloca, which is quadratic on shaders that inline into a few huge blocks ++ // with many allocas (19% of all compile time on Path of Exile 2's shaders). ++ // Instead, take the earliest of this alloca's own loads and stores in the ++ // block by LargeBlockInfo's per-block numbering (one scan per block, shared ++ // by every alloca). Same answer, so the output doesn't change. ++ // MADEIRA_DXC_MEM2REG_SCAN=1 goes back to the walk. ++ static const bool UseWalk = [] { ++ const char *Value = getenv("MADEIRA_DXC_MEM2REG_SCAN"); ++ return Value && Value[0] && !(Value[0] == '0' && !Value[1]); ++ }(); ++ if (!UseWalk) { ++ // One pass over the alloca's users, the first time a block needs it: ++ // the earliest reference in each defining block, and whether it is a ++ // store. ++ if (!FirstReferenceDone) { ++ FirstReferenceDone = true; ++ for (User *U : AI->users()) { ++ Instruction *UserInst = dyn_cast(U); ++ if (!UserInst) ++ continue; ++ bool IsStore = ++ isa(UserInst) && UserInst->getOperand(1) == AI; ++ bool IsLoad = ++ isa(UserInst) && UserInst->getOperand(0) == AI; ++ if (!IsStore && !IsLoad) ++ continue; ++ BasicBlock *UserBlock = UserInst->getParent(); ++ if (!DefBlocks.count(UserBlock)) ++ continue; ++ unsigned Index = LBI.getInstructionIndex(UserInst); ++ auto Inserted = FirstReference.insert( ++ std::make_pair(UserBlock, std::make_pair(Index, IsStore))); ++ if (!Inserted.second && Index < Inserted.first->second.first) ++ Inserted.first->second = std::make_pair(Index, IsStore); ++ } ++ } ++ auto Found = FirstReference.find(BB); ++ if (Found != FirstReference.end() && Found->second.second) { ++ // The first reference is a store: not live-in here. ++ LiveInBlockWorklist[i] = LiveInBlockWorklist.back(); ++ LiveInBlockWorklist.pop_back(); ++ --i, --e; ++ } ++ continue; ++ } ++ + for (BasicBlock::iterator I = BB->begin();; ++I) { + if (StoreInst *SI = dyn_cast(I)) { + if (SI->getOperand(1) != AI) +-- +2.56.0 + diff --git a/build/dxc-arm64ec/patches/0006-MADEIRA_DXC_ARGS_LOG-dxc-time-compile-timing-every-1.patch b/build/dxc-arm64ec/patches/0006-MADEIRA_DXC_ARGS_LOG-dxc-time-compile-timing-every-1.patch new file mode 100644 index 0000000000..34ac07a173 --- /dev/null +++ b/build/dxc-arm64ec/patches/0006-MADEIRA_DXC_ARGS_LOG-dxc-time-compile-timing-every-1.patch @@ -0,0 +1,99 @@ +From 7b31eb1d5b0872bdbc74515f6162c58cf8cfd307 Mon Sep 17 00:00:00 2001 +From: Shitiz Garg +Date: Sat, 14 Nov 2026 23:45:05 +1100 +Subject: [PATCH 6/6] MADEIRA_DXC_ARGS_LOG: [dxc-time] compile timing every 100 + compiles + +With the args log on, each Compile is timed and a [dxc-time] line every +100 compiles gives the count, total and average time, the last 100's +average, the slowest compile and which mem2reg path is in use, so a +session's compile cost can be compared across builds and settings. + +Signed-off-by: Shitiz Garg +Co-Authored-By: Claude Opus 5.5 +--- + .../clang/tools/dxcompiler/dxcompilerobj.cpp | 40 +++++++++++++++++++ + 1 file changed, 40 insertions(+) + +diff --git a/tools/clang/tools/dxcompiler/dxcompilerobj.cpp b/tools/clang/tools/dxcompiler/dxcompilerobj.cpp +index 3a5d6ca7..dd6fb909 100644 +--- a/tools/clang/tools/dxcompiler/dxcompilerobj.cpp ++++ b/tools/clang/tools/dxcompiler/dxcompilerobj.cpp +@@ -41,6 +41,7 @@ + #include "dxc/dxcapi.internal.h" + #include "dxcutil.h" + #include ++#include + #include + #include + #include +@@ -481,6 +482,9 @@ static unsigned g_total; + static int g_log = -1; + static std::vector *g_add, *g_drop; + static void out(const char *line) { ++#ifndef _WIN32 ++ fputs(line, stderr); // host builds (tests): no Wine debug channel ++#else + typedef int(__cdecl * fn_t)(const char *); + static fn_t fn; + static int looked; +@@ -490,6 +494,7 @@ static void out(const char *line) { + looked = 1; + } + if (fn) fn(line); ++#endif + } + static std::vector *split(const char *v) { + auto *r = new std::vector(); +@@ -558,6 +563,40 @@ static void log_args(LPCWSTR *args, UINT32 n) { + out(b); + } + } ++// Compile timing (with MADEIRA_DXC_ARGS_LOG=1): a [dxc-time] line every 100 ++// compiles with the running total, so a session's compile cost can be compared ++// across builds and settings (MADEIRA_DXC_MEM2REG_SCAN). ++static unsigned g_timed; ++static double g_total_ms, g_window_ms, g_max_ms; ++static void record_time(double ms) { ++ char b[400]; ++ std::lock_guard g(g_lock); ++ g_timed++; ++ g_total_ms += ms; ++ g_window_ms += ms; ++ if (ms > g_max_ms) g_max_ms = ms; ++ if (g_timed == 1 || !(g_timed % 100)) { ++ const char *walk = getenv("MADEIRA_DXC_MEM2REG_SCAN"); ++ snprintf(b, sizeof b, ++ "[dxc-time] %u compiles, %.0f ms in all (avg %.1f ms), last %u avg %.1f ms, max %.0f ms; mem2reg %s\n", ++ g_timed, g_total_ms, g_total_ms / g_timed, g_timed == 1 ? 1u : 100u, ++ g_window_ms / (g_timed == 1 ? 1 : 100), g_max_ms, ++ walk && walk[0] && !(walk[0] == '0' && !walk[1]) ? "walk (MADEIRA_DXC_MEM2REG_SCAN)" : "first-reference map"); ++ out(b); ++ g_window_ms = 0; ++ } ++} ++struct CompileTimer { ++ bool on; ++ std::chrono::steady_clock::time_point start; ++ explicit CompileTimer(bool enabled) : on(enabled) { ++ if (on) start = std::chrono::steady_clock::now(); ++ } ++ ~CompileTimer() { ++ if (on) ++ record_time(std::chrono::duration(std::chrono::steady_clock::now() - start).count()); ++ } ++}; + // The argument list the compile uses: the game's, minus DROP, plus ADD. + static void rewrite(LPCWSTR *&args, UINT32 &n, std::vector &store) { + if (g_drop->empty() && g_add->empty()) return; +@@ -655,6 +694,7 @@ public: + madeira_dxc_args::init(); + if (madeira_dxc_args::g_log) madeira_dxc_args::log_args(pArguments, argCount); + madeira_dxc_args::rewrite(pArguments, argCount, madeiraArgs); ++ madeira_dxc_args::CompileTimer madeiraTimer(madeira_dxc_args::g_log == 1); + + HRESULT hr = S_OK; + CComPtr utf8Source; +-- +2.56.0 + diff --git a/build/dxc-arm64ec/toolchain-arm64ec.cmake b/build/dxc-arm64ec/toolchain-arm64ec.cmake new file mode 100644 index 0000000000..ddb61751e9 --- /dev/null +++ b/build/dxc-arm64ec/toolchain-arm64ec.cmake @@ -0,0 +1,16 @@ +# llvm-mingw ARM64EC cross toolchain for DXC. +set(CMAKE_SYSTEM_NAME Windows) +set(CMAKE_SYSTEM_PROCESSOR ARM64) +if(NOT DEFINED ENV{LLVM_MINGW}) + message(FATAL_ERROR "set LLVM_MINGW to the llvm-mingw 20260421 directory (build.sh does)") +endif() +set(LLVM_MINGW "$ENV{LLVM_MINGW}") +set(CMAKE_C_COMPILER ${LLVM_MINGW}/bin/arm64ec-w64-mingw32-clang) +set(CMAKE_CXX_COMPILER ${LLVM_MINGW}/bin/arm64ec-w64-mingw32-clang++) +set(CMAKE_RC_COMPILER ${LLVM_MINGW}/bin/arm64ec-w64-mingw32-windres) +set(CMAKE_AR ${LLVM_MINGW}/bin/llvm-ar) +set(CMAKE_RANLIB ${LLVM_MINGW}/bin/llvm-ranlib) +set(CMAKE_FIND_ROOT_PATH ${LLVM_MINGW}/arm64ec-w64-mingw32) +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) diff --git a/build/fossilize-ios/build.sh b/build/fossilize-ios/build.sh new file mode 100755 index 0000000000..0da89310bc --- /dev/null +++ b/build/fossilize-ios/build.sh @@ -0,0 +1,37 @@ +#!/bin/bash +# Fossilize (Valve, MIT) for iOS, staged in app/Madeira/gl/: +# libVkLayer_fossilize.dylib the capture layer (VK_LAYER_fossilize), loaded through the Khronos +# loader (build/vulkan-loader-ios) when madeira.cfg fossilize = record|on; +# manifest gl/vulkan/explicit_layer.d/VkLayer_fossilize.json +# libfossilize_replay.dylib the replayer as a library (fossilize_replay_main), run in-process +# before the game starts when fossilize = replay|on (iOS apps can't +# spawn fossilize-replay processes) +# Source: ValveSoftware/Fossilize at REV with patches/*.patch (FOSSILIZE_VULKAN_LIBRARY, the +# library entry point). Needs: git, cmake, ninja, Xcode (iphoneos SDK). +set -euo pipefail +HERE="$(cd "$(dirname "$0")" && pwd)" +REPO_ROOT="$(cd "$HERE/../.." && pwd)" +WORK="${WORK:-$HERE/work}" +REV=556da9ff7d7616704dda515756219ab1dab693ec +GL="$REPO_ROOT/app/Madeira/gl" +mkdir -p "$WORK" +if [ ! -d "$WORK/src/.git" ]; then + git clone https://github.com/ValveSoftware/Fossilize.git "$WORK/src" + git -C "$WORK/src" checkout -q "$REV" + git -C "$WORK/src" submodule update --init --depth 1 + git -C "$WORK/src" -c user.name=madeira -c user.email=madeira@localhost am "$HERE"/patches/*.patch +fi +cmake -S "$WORK/src" -B "$WORK/build-ios" -G Ninja \ + -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_OSX_ARCHITECTURES=arm64 -DCMAKE_OSX_DEPLOYMENT_TARGET=26.0 \ + -DCMAKE_BUILD_TYPE=Release -DCMAKE_POSITION_INDEPENDENT_CODE=ON \ + -DFOSSILIZE_REPLAY_LIBRARY=ON -DFOSSILIZE_REPLAYER_SPIRV_VAL=OFF -DFOSSILIZE_TESTS=OFF +ninja -C "$WORK/build-ios" VkLayer_fossilize fossilize-replay-lib +mkdir -p "$GL/vulkan/explicit_layer.d" +for lib in layer/libVkLayer_fossilize.dylib cli/libfossilize_replay.dylib; do + name="$(basename "$lib")" + cp "$WORK/build-ios/$lib" "$GL/$name" + install_name_tool -id "@rpath/$name" "$GL/$name" + strip -x "$GL/$name" + echo " $GL/$name: $(wc -c < "$GL/$name" | tr -d ' ') bytes, sha256 $(shasum -a 256 "$GL/$name" | cut -c1-16)" +done +git -C "$WORK/src" rev-parse --short HEAD > "$GL/libfossilize.version" diff --git a/build/fossilize-ios/patches/0001-replay-library-and-custom-vulkan-library.patch b/build/fossilize-ios/patches/0001-replay-library-and-custom-vulkan-library.patch new file mode 100644 index 0000000000..90dc1b6028 --- /dev/null +++ b/build/fossilize-ios/patches/0001-replay-library-and-custom-vulkan-library.patch @@ -0,0 +1,104 @@ +From 68769ce8e4bc04ea4424b3f703e2069abeb6b33b Mon Sep 17 00:00:00 2001 +From: Shitiz Garg +Date: Mon, 9 Nov 2026 21:30:22 +1100 +Subject: [PATCH] cli: replay through FOSSILIZE_VULKAN_LIBRARY; replayer as a + library + +FOSSILIZE_VULKAN_LIBRARY names the Vulkan library to load instead of the +system loader (embedders that carry the loader or an ICD in their bundle). +FOSSILIZE_REPLAY_LIBRARY builds libfossilize_replay exporting +fossilize_replay_main for hosts that can't spawn processes (iOS). + +Signed-off-by: Shitiz Garg +--- + cli/CMakeLists.txt | 10 ++++++++++ + cli/device.cpp | 25 +++++++++++++++++++++++++ + cli/fossilize_replay.cpp | 7 +++++++ + 3 files changed, 42 insertions(+) + +diff --git a/cli/CMakeLists.txt b/cli/CMakeLists.txt +index d106024..839dc7a 100644 +--- a/cli/CMakeLists.txt ++++ b/cli/CMakeLists.txt +@@ -37,6 +37,16 @@ function(add_fossilize_cli NAME) + endfunction() + + add_fossilize_cli(fossilize-replay fossilize_replay.cpp) ++ ++option(FOSSILIZE_REPLAY_LIBRARY "Also build the replayer as a shared library exporting fossilize_replay_main." OFF) ++if (FOSSILIZE_REPLAY_LIBRARY) ++ add_library(fossilize-replay-lib SHARED fossilize_replay.cpp) ++ set_target_properties(fossilize-replay-lib PROPERTIES OUTPUT_NAME fossilize_replay) ++ target_compile_options(fossilize-replay-lib PRIVATE ${FOSSILIZE_CXX_FLAGS}) ++ target_compile_definitions(fossilize-replay-lib PRIVATE FOSSILIZE_REPLAY_LIBRARY=1 NO_ROBUST_REPLAYER=1) ++ target_link_libraries(fossilize-replay-lib PRIVATE fossilize cli-utils) ++ install(TARGETS fossilize-replay-lib DESTINATION ${CMAKE_INSTALL_LIBDIR}) ++endif() + if (WIN32) + target_sources(fossilize-replay PRIVATE fossilize_replay_windows.hpp) + else() +diff --git a/cli/device.cpp b/cli/device.cpp +index 05e6e73..bc9f307 100644 +--- a/cli/device.cpp ++++ b/cli/device.cpp +@@ -25,6 +25,10 @@ + #include + #include + #include ++#include ++#ifndef _WIN32 ++#include ++#endif + + using namespace std; + +@@ -273,6 +277,27 @@ bool VulkanDevice::init_device(const Options &opts) + return true; + } + ++#ifndef _WIN32 ++ // FOSSILIZE_VULKAN_LIBRARY names a Vulkan library (a loader or an ICD that exports ++ // vkGetInstanceProcAddr) to replay through instead of the system loader. Embedders ++ // whose loader isn't on the default search path (iOS apps carry it in the bundle) ++ // use this to target a specific driver. ++ const char *custom_library = getenv("FOSSILIZE_VULKAN_LIBRARY"); ++ if (custom_library && *custom_library) ++ { ++ void *handle = dlopen(custom_library, RTLD_NOW | RTLD_LOCAL); ++ auto get_instance_proc_addr = handle ? ++ reinterpret_cast(dlsym(handle, "vkGetInstanceProcAddr")) : nullptr; ++ if (!get_instance_proc_addr) ++ { ++ LOGE("FOSSILIZE_VULKAN_LIBRARY=%s: %s.\n", custom_library, ++ handle ? "no vkGetInstanceProcAddr" : dlerror()); ++ return false; ++ } ++ volkInitializeCustom(get_instance_proc_addr); ++ } ++ else ++#endif + if (volkInitialize() != VK_SUCCESS) + { + LOGE("volkInitialize failed.\n"); +diff --git a/cli/fossilize_replay.cpp b/cli/fossilize_replay.cpp +index 07c3ffd..bbf76f0 100644 +--- a/cli/fossilize_replay.cpp ++++ b/cli/fossilize_replay.cpp +@@ -4565,7 +4565,14 @@ static int run_normal_process(ThreadedReplayer &replayer, const vector databases; + const char *whitelist_path = nullptr; +-- +2.56.0 + diff --git a/build/fossilize-ios/patches/0002-external-replayer-optional-off-on-ios.patch b/build/fossilize-ios/patches/0002-external-replayer-optional-off-on-ios.patch new file mode 100644 index 0000000000..508ddd6b7b --- /dev/null +++ b/build/fossilize-ios/patches/0002-external-replayer-optional-off-on-ios.patch @@ -0,0 +1,50 @@ +From 060c15f6929c6c26df4e7f16bc925313af64ee6e Mon Sep 17 00:00:00 2001 +From: Shitiz Garg +Date: Mon, 9 Nov 2026 21:52:43 +1100 +Subject: [PATCH] Make the external replayer optional; off on Android and iOS + +The external replayer spawns fossilize-replay child processes and includes +Linux-only headers (sys/prctl.h). Hosts that can't spawn processes replay +in-process. FOSSILIZE_EXTERNAL_REPLAYER (default off on Android and iOS) +replaces the Android-only exclusion. + +Signed-off-by: Shitiz Garg +--- + CMakeLists.txt | 15 +++++++++++++-- + 1 file changed, 13 insertions(+), 2 deletions(-) + +diff --git a/CMakeLists.txt b/CMakeLists.txt +index 473c6b0..3d4ff9c 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -75,14 +75,25 @@ if (WIN32 AND CMAKE_COMPILER_IS_GNUCXX) + target_compile_definitions(fossilize PUBLIC __USE_MINGW_ANSI_STDIO=1) + endif() + +-if (NOT ANDROID) ++# The external replayer spawns fossilize-replay child processes (Linux: prctl, fork). Hosts that ++# can't spawn processes (Android, iOS) replay in-process instead and leave it out. ++if (ANDROID OR IOS) ++ set(FOSSILIZE_EXTERNAL_REPLAYER_DEFAULT OFF) ++else() ++ set(FOSSILIZE_EXTERNAL_REPLAYER_DEFAULT ON) ++endif() ++option(FOSSILIZE_EXTERNAL_REPLAYER "Build the process-spawning external replayer." ${FOSSILIZE_EXTERNAL_REPLAYER_DEFAULT}) ++ ++if (FOSSILIZE_EXTERNAL_REPLAYER) + target_sources(fossilize PRIVATE fossilize_external_replayer.cpp fossilize_external_replayer.hpp) + endif() + + if (WIN32) + target_sources(fossilize PRIVATE fossilize_external_replayer_windows.hpp) +-else() ++elseif (FOSSILIZE_EXTERNAL_REPLAYER) + target_sources(fossilize PRIVATE fossilize_external_replayer_linux.hpp) ++endif() ++if (NOT WIN32) + if (APPLE) + target_sources(fossilize PRIVATE platform/gcc_clang_spinlock.hpp) + else() +-- +2.56.0 + diff --git a/build/fossilize-ios/patches/0003-replay-progress-for-the-library.patch b/build/fossilize-ios/patches/0003-replay-progress-for-the-library.patch new file mode 100644 index 0000000000..6a07dc7a79 --- /dev/null +++ b/build/fossilize-ios/patches/0003-replay-progress-for-the-library.patch @@ -0,0 +1,75 @@ +From a48b4951ac112332dcb908a32d9486e95e3888f6 Mon Sep 17 00:00:00 2001 +From: Shitiz Garg +Date: Tue, 10 Nov 2026 01:04:35 +1100 +Subject: [PATCH] cli: fossilize_replay_progress for the replay library + +Signed-off-by: Shitiz Garg +Co-Authored-By: Claude Opus 5.5 +--- + cli/fossilize_replay.cpp | 36 ++++++++++++++++++++++++++++++++++++ + 1 file changed, 36 insertions(+) + +diff --git a/cli/fossilize_replay.cpp b/cli/fossilize_replay.cpp +index bbf76f0..92e68c1 100644 +--- a/cli/fossilize_replay.cpp ++++ b/cli/fossilize_replay.cpp +@@ -3598,6 +3598,35 @@ struct ThreadedReplayer : StateCreatorInterface + DatabaseInterface *global_database = nullptr; + }; + ++#ifdef FOSSILIZE_REPLAY_LIBRARY ++// Progress for an embedding app (Madeira): pipelines in the databases being ++// replayed, and pipelines played back so far. Both 0 when no replay is running. ++static std::atomic library_progress_total; ++static std::atomic library_progress_replayer; ++ ++extern "C" __attribute__((visibility("default"))) void fossilize_replay_progress(uint32_t *done, uint32_t *total) ++{ ++ ThreadedReplayer *replayer = library_progress_replayer.load(std::memory_order_acquire); ++ *total = replayer ? library_progress_total.load(std::memory_order_relaxed) : 0; ++ *done = replayer ? replayer->graphics_pipeline_count.load(std::memory_order_relaxed) + ++ replayer->compute_pipeline_count.load(std::memory_order_relaxed) : 0; ++} ++ ++struct LibraryProgressScope ++{ ++ explicit LibraryProgressScope(ThreadedReplayer *replayer) ++ { ++ library_progress_total.store(0, std::memory_order_relaxed); ++ library_progress_replayer.store(replayer, std::memory_order_release); ++ } ++ ~LibraryProgressScope() ++ { ++ library_progress_replayer.store(nullptr, std::memory_order_release); ++ library_progress_total.store(0, std::memory_order_relaxed); ++ } ++}; ++#endif ++ + static void on_validation_error(void *userdata) + { + auto *replayer = static_cast(userdata); +@@ -4134,6 +4163,9 @@ static int run_normal_process(ThreadedReplayer &replayer, const vectorerase(begin(*hashes) + (end_index - start_index), end(*hashes)); ++#ifdef FOSSILIZE_REPLAY_LIBRARY ++ if (tag == RESOURCE_GRAPHICS_PIPELINE || tag == RESOURCE_COMPUTE_PIPELINE) ++ library_progress_total.fetch_add(uint32_t(hashes->size()), std::memory_order_relaxed); ++#endif + + if (replayer.replayer_cache_db) + populate_blob_hash_set(replayer.cached_blobs[tag], tag, *replayer.replayer_cache_db); +-- +2.56.0 + diff --git a/build/madeira-d3d12/build-libxess.sh b/build/madeira-d3d12/build-libxess.sh new file mode 100755 index 0000000000..fc3de0e1bc --- /dev/null +++ b/build/madeira-d3d12/build-libxess.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# libxess.dll, the builtin that answers XeSS 2.x with MetalFX temporal upscaling +# through madeira_d3d12 (madeira-d3d12/src/libxess/libxess.c). ARM64EC, marked as a +# Wine builtin as winebuild --builtin does. Install it as arm64ec-windows/libxess.dll; +# wine loads it from system32 instead of the game's own copy with +# env.MADEIRA_XESS_METALFX = 1. +# Usage: build-libxess.sh [out-dir] (LLVM_MINGW = llvm-mingw root; default as build-pe.sh) +set -eu +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +MINGW="${LLVM_MINGW:-$REPO_ROOT/toolchains/llvm-mingw-20260421-ucrt-macos-universal}/bin" +OUT="${1:-$REPO_ROOT/build/madeira-d3d12/out}" +mkdir -p "$OUT" +"$MINGW/arm64ec-w64-mingw32-clang" -shared -O2 -o "$OUT/libxess.dll" "$REPO_ROOT/madeira-d3d12/src/libxess/libxess.c" +python3 "$REPO_ROOT/build/dxc-arm64ec/mark-builtin.py" "$OUT/libxess.dll" diff --git a/build/madeira-d3d12/build-pe.sh b/build/madeira-d3d12/build-pe.sh index 56f8b40e56..51d70ed8da 100755 --- a/build/madeira-d3d12/build-pe.sh +++ b/build/madeira-d3d12/build-pe.sh @@ -102,8 +102,26 @@ for cpp in "$SRC/mad_bcn.cpp" "$REPO_ROOT/dxmt/src/dxmt/dxmt_bcn.cpp"; do "$MINGW/arm64ec-w64-mingw32-clang++" -c -O2 -std=c++17 -fno-exceptions -fno-rtti \ -I"$REPO_ROOT/dxmt/src/dxmt" -o "$OUT/$(basename "$cpp" .cpp).o" "$cpp" done +# list-journal: the *.x64.c / *.x64.S objects are x64 code linked into the +# ARM64EC image (lld puts them in the x64 code range). x64 code runs at the PE +# address while ARM64EC code runs from Madeira's pool copy with its own .data, +# so an x64 object must not reference any symbol outside itself +# (madeira_list_journal.h); the build stops if one does. +X64_OBJS=() +for s in "$SRC"/*.x64.S "$SRC"/*.x64.c; do + [ -e "$s" ] || continue + "$MINGW/x86_64-w64-mingw32-clang" -c -O2 -Wall -fno-auto-import -fno-builtin \ + -I"$SRC" -I"$REPO_ROOT/madeira-d3d12/src" -o "$OUT/$(basename "$s").o" "$s" + X64_OBJS+=("$OUT/$(basename "$s").o") + if [ -n "$("$MINGW/llvm-nm" -u "$OUT/$(basename "$s").o")" ]; then + echo "x64 object $(basename "$s") references outside symbols:" >&2 + "$MINGW/llvm-nm" -u "$OUT/$(basename "$s").o" >&2 + exit 1 + fi +done "$MINGW/arm64ec-w64-mingw32-clang" -shared -O2 -Wall ${EXTRA[@]+"${EXTRA[@]}"} \ - -o "$OUT/madeira_d3d12.dll" "$SRC/madeira_d3d12.c" "$OUT/mad_bcn.o" "$OUT/dxmt_bcn.o" "$SRC/d3d12.def" \ + -o "$OUT/madeira_d3d12.dll" "$SRC/madeira_d3d12.c" "$OUT/mad_bcn.o" "$OUT/dxmt_bcn.o" \ + ${X64_OBJS[@]+"${X64_OBJS[@]}"} "$SRC/d3d12.def" \ -I"$SRC" -I"$REPO_ROOT/madeira-d3d12/src" -I"$REPO_ROOT/dxmt/src/winemetal" \ -L"$REPO_ROOT/dxmt/build-arm64ec/src/winemetal" -lwinemetal \ -luuid -lole32 diff --git a/build/mesa-ios/build-kosmickrisp.sh b/build/mesa-ios/build-kosmickrisp.sh index 424b31b4a3..14771e3d61 100644 --- a/build/mesa-ios/build-kosmickrisp.sh +++ b/build/mesa-ios/build-kosmickrisp.sh @@ -90,7 +90,7 @@ if [ ! -f "$B/build.ninja" ]; then -Dopengl=false -Dgles1=disabled -Dgles2=disabled \ -Dglx=disabled -Degl=disabled -Dgbm=disabled \ -Dllvm=disabled -Dmesa-clc=system -Dprecomp-compiler=system \ - -Dshader-cache=disabled -Dxmlconfig=disabled \ + -Dshader-cache=enabled -Dxmlconfig=disabled \ -Dzstd=disabled -Dlibunwind=disabled -Dvalgrind=disabled -Dlmsensors=disabled \ -Dexpat=disabled -Dbuild-tests=false -Dvideo-codecs= \ -Dvulkan-icd-dir=share/vulkan/icd.d diff --git a/build/mesa-ios/patches/kosmickrisp-ios-0007-shader-cache.patch b/build/mesa-ios/patches/kosmickrisp-ios-0007-shader-cache.patch new file mode 100644 index 0000000000..8b111bc23e --- /dev/null +++ b/build/mesa-ios/patches/kosmickrisp-ios-0007-shader-cache.patch @@ -0,0 +1,99 @@ +From cdc6fe09287ff31e54ccbcf4777fdd5a5cb1246e Mon Sep 17 00:00:00 2001 +From: Shitiz Garg +Date: Mon, 9 Nov 2026 21:23:41 +1100 +Subject: [PATCH] kosmickrisp: on-disk shader cache and an implicit pipeline + cache + +KosmicKrisp never created a disk cache, and with no implicit pipeline cache +the runtime consulted no cache at all for applications that pass no +VkPipelineCache. Create the disk cache keyed on the driver build and device +name, and create device->mem_cache the way RADV does. + +Signed-off-by: Shitiz Garg +--- + src/kosmickrisp/vulkan/kk_device.c | 16 ++++++++++++++++ + src/kosmickrisp/vulkan/kk_physical_device.c | 20 ++++++++++++++++++++ + 2 files changed, 36 insertions(+) + +diff --git a/src/kosmickrisp/vulkan/kk_device.c b/src/kosmickrisp/vulkan/kk_device.c +index 216faed..644a872 100644 +--- a/src/kosmickrisp/vulkan/kk_device.c ++++ b/src/kosmickrisp/vulkan/kk_device.c +@@ -298,6 +298,17 @@ kk_CreateDevice(VkPhysicalDevice physicalDevice, + if (result != VK_SUCCESS) + goto fail_alloc; + ++ /* Implicit pipeline cache. Applications that pass no VkPipelineCache (many ++ * do, relying on the driver's own cache) otherwise get no caching at all, ++ * not even the on-disk cache: the runtime only consults the disk cache ++ * through a vk_pipeline_cache. */ ++ struct vk_pipeline_cache_create_info mem_cache_info = {.weak_ref = true}; ++ dev->vk.mem_cache = vk_pipeline_cache_create(&dev->vk, &mem_cache_info, NULL); ++ if (dev->vk.mem_cache == NULL) { ++ result = VK_ERROR_OUT_OF_HOST_MEMORY; ++ goto fail_init; ++ } ++ + dev->vk.shader_ops = &kk_device_shader_ops; + dev->mtl_handle = pdev->mtl_dev_handle; + dev->vk.command_buffer_ops = &kk_cmd_buffer_ops; +@@ -363,6 +374,8 @@ fail_vab_memory: + fail_compiler: + kk_release_compiler(dev); + fail_init: ++ if (dev->vk.mem_cache) ++ vk_pipeline_cache_destroy(dev->vk.mem_cache, NULL); + vk_device_finish(&dev->vk); + fail_alloc: + vk_free(&dev->vk.alloc, dev); +@@ -404,6 +417,9 @@ kk_DestroyDevice(VkDevice _device, const VkAllocationCallbacks *pAllocator) + + kk_release_compiler(dev); + ++ if (dev->vk.mem_cache) ++ vk_pipeline_cache_destroy(dev->vk.mem_cache, NULL); ++ + vk_device_finish(&dev->vk); + + vk_free(&dev->vk.alloc, dev); +diff --git a/src/kosmickrisp/vulkan/kk_physical_device.c b/src/kosmickrisp/vulkan/kk_physical_device.c +index 227273d..556196c 100644 +--- a/src/kosmickrisp/vulkan/kk_physical_device.c ++++ b/src/kosmickrisp/vulkan/kk_physical_device.c +@@ -17,6 +17,7 @@ + #include "kosmickrisp/bridge/mtl_bridge.h" + + #include "util/disk_cache.h" ++#include "util/hex.h" + #include "util/mesa-blake3.h" + #include "git_sha1.h" + +@@ -911,6 +912,25 @@ kk_physical_device_init_pipeline_cache(struct kk_physical_device *pdev) + STATIC_ASSERT(BLAKE3_KEY_LEN >= VK_UUID_SIZE); + memcpy(pdev->vk.properties.pipelineCacheUUID, blake3, VK_UUID_SIZE); + memcpy(pdev->vk.properties.shaderBinaryUUID, blake3, VK_UUID_SIZE); ++ ++#ifdef ENABLE_SHADER_CACHE ++ /* On-disk shader cache. Without it, the runtime's pipeline cache keeps ++ * compiled shaders only for the life of the process, so every launch ++ * repeats SPIR-V -> NIR -> MSL for every pipeline the application creates. ++ * The key covers the driver build and the device name, so a driver update ++ * or a different GPU starts a fresh cache. */ ++ _mesa_blake3_init(&blake3_ctx); ++ _mesa_blake3_update(&blake3_ctx, instance->driver_build_sha, ++ sizeof(instance->driver_build_sha)); ++ _mesa_blake3_update(&blake3_ctx, pdev->vk.properties.deviceName, ++ strlen(pdev->vk.properties.deviceName)); ++ unsigned char cache_key[BLAKE3_KEY_LEN]; ++ _mesa_blake3_final(&blake3_ctx, cache_key); ++ ++ char timestamp[BLAKE3_KEY_LEN * 2 + 1]; ++ mesa_bytes_to_hex(timestamp, cache_key, BLAKE3_KEY_LEN); ++ pdev->vk.disk_cache = disk_cache_create("kosmickrisp", timestamp, 0); ++#endif + } + + static void +-- +2.56.0 + diff --git a/build/mesa-ios/patches/kosmickrisp-ios-0008-mtl4-archives-compile-timing.patch b/build/mesa-ios/patches/kosmickrisp-ios-0008-mtl4-archives-compile-timing.patch new file mode 100644 index 0000000000..f0de0d913f --- /dev/null +++ b/build/mesa-ios/patches/kosmickrisp-ios-0008-mtl4-archives-compile-timing.patch @@ -0,0 +1,540 @@ +From 7bb0c615e15b25d34563f9f13467128758476768 Mon Sep 17 00:00:00 2001 +From: Shitiz Garg +Date: Mon, 9 Nov 2026 21:25:16 +1100 +Subject: [PATCH] kosmickrisp: Metal 4 pipeline archives and compile timing + +Pipelines built through the MTL4Compiler are collected by a +MTL4PipelineDataSetSerializer and written as archive chunks every 60 s +while new pipelines are built, and when the compiler is released. Chunks +from earlier sessions are loaded at start-up and passed as lookupArchives, +so repeat builds are found instead of compiled. Library and pipeline +builds are timed: [kk-slow] for builds of 150 ms or more, [kk-compile] +totals every 30 s. MADEIRA_KK_ARCHIVE=0 / MADEIRA_KK_COMPILE_STATS=0 opt out. + +Signed-off-by: Shitiz Garg +--- + src/kosmickrisp/bridge/mtl_compiler.h | 4 + + src/kosmickrisp/bridge/mtl_compiler.m | 422 +++++++++++++++++++- + src/kosmickrisp/bridge/stubs/mtl_compiler.c | 5 + + src/kosmickrisp/vulkan/kk_device.c | 3 + + 4 files changed, 432 insertions(+), 2 deletions(-) + +diff --git a/src/kosmickrisp/bridge/mtl_compiler.h b/src/kosmickrisp/bridge/mtl_compiler.h +index b433ac9..b0fa59f 100644 +--- a/src/kosmickrisp/bridge/mtl_compiler.h ++++ b/src/kosmickrisp/bridge/mtl_compiler.h +@@ -18,6 +18,10 @@ enum mtl_pixel_format; + /* Compiler */ + mtl_compiler *mtl_new_compiler(mtl_device *device); + ++/* Madeira: writes pending pipeline-archive data now and logs the compile ++ * statistics. Called when the last device using the compiler goes away. */ ++void mtl_compiler_flush_archive(mtl_compiler *compiler); ++ + /* Library */ + mtl_library * + mtl_new_library(mtl_compiler *compiler, const char *src, +diff --git a/src/kosmickrisp/bridge/mtl_compiler.m b/src/kosmickrisp/bridge/mtl_compiler.m +index 92c532e..74e1bde 100644 +--- a/src/kosmickrisp/bridge/mtl_compiler.m ++++ b/src/kosmickrisp/bridge/mtl_compiler.m +@@ -12,6 +12,402 @@ + #include + #include + #include ++#include ++#include ++#include ++ ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++#include ++ ++/* ++ * Madeira: Metal 4 pipeline archives and compile timing. ++ * ++ * Archives. Every pipeline the compiler builds is also collected by a ++ * MTL4PipelineDataSetSerializer (binaries). The collected set is written out ++ * as one archive chunk at most every MADEIRA_KK_ARCHIVE_FLUSH_S seconds ++ * (default 60) while new pipelines are being built, and when the compiler is ++ * released. At start-up every chunk in the archive directory is loaded, ++ * newest first, up to MADEIRA_KK_ARCHIVE_MB (default 1024) in total, and ++ * passed to every pipeline build as lookupArchives, so a pipeline built in an ++ * earlier session is found instead of compiled again. Chunks Metal can't read ++ * (for example after an OS update) are deleted. The directory is ++ * MADEIRA_KK_ARCHIVE_DIR, else $MESA_SHADER_CACHE_DIR/kosmickrisp-mtl4, else ++ * $HOME/.cache/kosmickrisp-mtl4. MADEIRA_KK_ARCHIVE=0 turns all of it off. ++ * ++ * Timing. Library compiles, render and compute pipeline builds are timed. ++ * Any one that takes 150 ms or more is logged as [kk-slow]; every 30 s a ++ * [kk-compile] line gives cumulative counts, totals, maxima and a duration ++ * histogram per kind (the < 2 ms bucket is, in practice, archive or Metal ++ * cache hits). MADEIRA_KK_COMPILE_STATS=0 turns the lines off. ++ */ ++ ++#define KK_SLOW_NS (150ull * 1000000ull) ++#define KK_REPORT_NS (30ull * 1000000000ull) ++ ++struct kk_compile_stat { ++ const char *name; ++ _Atomic uint64_t count; ++ _Atomic uint64_t total_ns; ++ _Atomic uint64_t max_ns; ++ _Atomic uint64_t under_2ms; ++ _Atomic uint64_t under_20ms; ++ _Atomic uint64_t under_150ms; ++ _Atomic uint64_t slow; ++}; ++ ++static struct kk_compile_stat kk_stat_library = {.name = "library"}; ++static struct kk_compile_stat kk_stat_render = {.name = "render"}; ++static struct kk_compile_stat kk_stat_compute = {.name = "compute"}; ++static _Atomic uint64_t kk_last_report_ns; ++static int kk_stats_enabled = -1; ++ ++static struct { ++ pthread_once_t once; ++ bool enabled; ++ char directory[1024]; ++ uint64_t cap_bytes; ++ uint64_t flush_interval_ns; ++ NSMutableArray *archives; ++ id serializer; ++ MTL4CompilerTaskOptions *task_options; ++ pthread_rwlock_t lock; ++ _Atomic uint64_t built_since_flush; ++ _Atomic uint64_t last_flush_ns; ++ _Atomic uint64_t chunks_written; ++ _Atomic uint64_t flush_running; ++ uint32_t chunks_loaded; ++ uint32_t chunks_rejected; ++ uint64_t bytes_loaded; ++} kk_archive = {.once = PTHREAD_ONCE_INIT}; ++ ++static uint64_t ++kk_now_ns(void) ++{ ++ struct timespec ts; ++ clock_gettime(CLOCK_MONOTONIC, &ts); ++ return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec; ++} ++ ++static uint64_t ++kk_env_u64(const char *name, uint64_t fallback) ++{ ++ const char *value = getenv(name); ++ if (value == NULL || value[0] == '\0') ++ return fallback; ++ return strtoull(value, NULL, 10); ++} ++ ++static void ++kk_compile_report(bool force) ++{ ++ if (kk_stats_enabled < 0) ++ kk_stats_enabled = kk_env_u64("MADEIRA_KK_COMPILE_STATS", 1) != 0; ++ if (!kk_stats_enabled) ++ return; ++ ++ uint64_t now = kk_now_ns(); ++ uint64_t last = atomic_load(&kk_last_report_ns); ++ if (!force && now - last < KK_REPORT_NS) ++ return; ++ if (!force && !atomic_compare_exchange_strong(&kk_last_report_ns, &last, now)) ++ return; ++ ++ struct kk_compile_stat *stats[3] = {&kk_stat_library, &kk_stat_render, &kk_stat_compute}; ++ char line[1024]; ++ int used = snprintf(line, sizeof(line), "[kk-compile]"); ++ for (int i = 0; i < 3; ++i) { ++ struct kk_compile_stat *stat = stats[i]; ++ uint64_t count = atomic_load(&stat->count); ++ uint64_t total = atomic_load(&stat->total_ns); ++ used += snprintf(line + used, sizeof(line) - used, ++ " %s n=%llu total=%.0fms avg=%.2fms max=%.1fms <2ms=%llu <20ms=%llu <150ms=%llu slow=%llu |", ++ stat->name, (unsigned long long)count, total / 1e6, ++ count ? total / 1e6 / count : 0.0, ++ atomic_load(&stat->max_ns) / 1e6, ++ (unsigned long long)atomic_load(&stat->under_2ms), ++ (unsigned long long)atomic_load(&stat->under_20ms), ++ (unsigned long long)atomic_load(&stat->under_150ms), ++ (unsigned long long)atomic_load(&stat->slow)); ++ if (used >= (int)sizeof(line)) ++ break; ++ } ++ fprintf(stderr, "%s archive chunks loaded=%u (%llu KB) rejected=%u written=%llu%s\n", line, ++ kk_archive.chunks_loaded, (unsigned long long)(kk_archive.bytes_loaded / 1024), ++ kk_archive.chunks_rejected, ++ (unsigned long long)atomic_load(&kk_archive.chunks_written), ++ kk_archive.enabled ? "" : " (archives off)"); ++} ++ ++static void ++kk_compile_record(struct kk_compile_stat *stat, uint64_t start_ns) ++{ ++ uint64_t elapsed = kk_now_ns() - start_ns; ++ atomic_fetch_add(&stat->count, 1); ++ atomic_fetch_add(&stat->total_ns, elapsed); ++ uint64_t max = atomic_load(&stat->max_ns); ++ while (elapsed > max && !atomic_compare_exchange_weak(&stat->max_ns, &max, elapsed)) ++ ; ++ if (elapsed < 2000000ull) ++ atomic_fetch_add(&stat->under_2ms, 1); ++ else if (elapsed < 20000000ull) ++ atomic_fetch_add(&stat->under_20ms, 1); ++ else if (elapsed < KK_SLOW_NS) ++ atomic_fetch_add(&stat->under_150ms, 1); ++ else { ++ atomic_fetch_add(&stat->slow, 1); ++ if (kk_stats_enabled != 0) ++ fprintf(stderr, "[kk-slow] %s %.1f ms (thread %p)\n", stat->name, elapsed / 1e6, ++ (void *)pthread_self()); ++ } ++ kk_compile_report(false); ++} ++ ++static void ++kk_archive_default_directory(char *out, size_t size) ++{ ++ const char *explicit_dir = getenv("MADEIRA_KK_ARCHIVE_DIR"); ++ if (explicit_dir && explicit_dir[0]) { ++ snprintf(out, size, "%s", explicit_dir); ++ return; ++ } ++ const char *mesa_dir = getenv("MESA_SHADER_CACHE_DIR"); ++ if (mesa_dir && mesa_dir[0]) { ++ snprintf(out, size, "%s/kosmickrisp-mtl4", mesa_dir); ++ return; ++ } ++ const char *home = getenv("HOME"); ++ snprintf(out, size, "%s/.cache/kosmickrisp-mtl4", home ? home : "."); ++} ++ ++static void ++kk_mkdir_parents(const char *path) ++{ ++ char buffer[1024]; ++ snprintf(buffer, sizeof(buffer), "%s", path); ++ for (char *cursor = buffer + 1; *cursor; ++cursor) { ++ if (*cursor == '/') { ++ *cursor = '\0'; ++ mkdir(buffer, 0755); ++ *cursor = '/'; ++ } ++ } ++ mkdir(buffer, 0755); ++} ++ ++struct kk_chunk_entry { ++ char name[256]; ++ time_t modified; ++ off_t size; ++}; ++ ++static int ++kk_chunk_newest_first(const void *a, const void *b) ++{ ++ const struct kk_chunk_entry *left = a, *right = b; ++ if (left->modified != right->modified) ++ return left->modified < right->modified ? 1 : -1; ++ return strcmp(right->name, left->name); ++} ++ ++/* Lists *.mtl4a in the archive directory, newest first. Caller frees. */ ++static struct kk_chunk_entry * ++kk_list_chunks(uint32_t *count_out) ++{ ++ *count_out = 0; ++ DIR *directory = opendir(kk_archive.directory); ++ if (directory == NULL) ++ return NULL; ++ uint32_t capacity = 64, count = 0; ++ struct kk_chunk_entry *entries = malloc(capacity * sizeof(*entries)); ++ struct dirent *entry; ++ while (entries && (entry = readdir(directory)) != NULL) { ++ size_t length = strlen(entry->d_name); ++ if (length < 7 || strcmp(entry->d_name + length - 6, ".mtl4a") != 0) ++ continue; ++ char path[1400]; ++ snprintf(path, sizeof(path), "%s/%s", kk_archive.directory, entry->d_name); ++ struct stat info; ++ if (stat(path, &info) != 0) ++ continue; ++ if (count == capacity) { ++ capacity *= 2; ++ struct kk_chunk_entry *grown = realloc(entries, capacity * sizeof(*entries)); ++ if (grown == NULL) ++ break; ++ entries = grown; ++ } ++ snprintf(entries[count].name, sizeof(entries[count].name), "%s", entry->d_name); ++ entries[count].modified = info.st_mtime; ++ entries[count].size = info.st_size; ++ count++; ++ } ++ closedir(directory); ++ if (entries) ++ qsort(entries, count, sizeof(*entries), kk_chunk_newest_first); ++ *count_out = count; ++ return entries; ++} ++ ++/* Deletes the oldest chunks beyond the size cap. */ ++static void ++kk_prune_chunks(void) ++{ ++ uint32_t count; ++ struct kk_chunk_entry *entries = kk_list_chunks(&count); ++ uint64_t kept = 0; ++ for (uint32_t i = 0; i < count; ++i) { ++ kept += (uint64_t)entries[i].size; ++ if (kept > kk_archive.cap_bytes && i > 0) { ++ char path[1400]; ++ snprintf(path, sizeof(path), "%s/%s", kk_archive.directory, entries[i].name); ++ unlink(path); ++ fprintf(stderr, "[kk-archive] pruned %s (cap %llu MB)\n", entries[i].name, ++ (unsigned long long)(kk_archive.cap_bytes >> 20)); ++ } ++ } ++ free(entries); ++} ++ ++static id kk_archive_device; ++ ++static void ++kk_archive_init_once(void) ++{ ++ id device = kk_archive_device; ++ kk_archive.enabled = kk_env_u64("MADEIRA_KK_ARCHIVE", 1) != 0; ++ kk_archive.cap_bytes = kk_env_u64("MADEIRA_KK_ARCHIVE_MB", 1024) << 20; ++ kk_archive.flush_interval_ns = kk_env_u64("MADEIRA_KK_ARCHIVE_FLUSH_S", 60) * 1000000000ull; ++ pthread_rwlock_init(&kk_archive.lock, NULL); ++ atomic_store(&kk_archive.last_flush_ns, kk_now_ns()); ++ if (!kk_archive.enabled) { ++ fprintf(stderr, "[kk-archive] off (MADEIRA_KK_ARCHIVE=0)\n"); ++ return; ++ } ++ ++ kk_archive_default_directory(kk_archive.directory, sizeof(kk_archive.directory)); ++ kk_mkdir_parents(kk_archive.directory); ++ ++ @autoreleasepool { ++ kk_archive.archives = [[NSMutableArray alloc] init]; ++ uint32_t count; ++ struct kk_chunk_entry *entries = kk_list_chunks(&count); ++ for (uint32_t i = 0; i < count; ++i) { ++ char path[1400]; ++ snprintf(path, sizeof(path), "%s/%s", kk_archive.directory, entries[i].name); ++ if (kk_archive.bytes_loaded + (uint64_t)entries[i].size > kk_archive.cap_bytes) ++ break; ++ NSURL *url = [NSURL fileURLWithPath:[NSString stringWithUTF8String:path]]; ++ NSError *error = nil; ++ id archive = [device newArchiveWithURL:url error:&error]; ++ if (archive == nil) { ++ fprintf(stderr, "[kk-archive] %s unreadable, deleted: %s\n", entries[i].name, ++ error ? [error.localizedDescription UTF8String] : "no error"); ++ unlink(path); ++ kk_archive.chunks_rejected++; ++ continue; ++ } ++ [kk_archive.archives addObject:archive]; ++ [archive release]; ++ kk_archive.chunks_loaded++; ++ kk_archive.bytes_loaded += (uint64_t)entries[i].size; ++ } ++ free(entries); ++ ++ MTL4PipelineDataSetSerializerDescriptor *serializer_descriptor = ++ [[MTL4PipelineDataSetSerializerDescriptor new] autorelease]; ++ serializer_descriptor.configuration = MTL4PipelineDataSetSerializerConfigurationCaptureBinaries; ++ kk_archive.serializer = [device newPipelineDataSetSerializerWithDescriptor:serializer_descriptor]; ++ if (kk_archive.serializer == nil) ++ fprintf(stderr, "[kk-archive] no pipeline data set serializer: new chunks won't be written\n"); ++ ++ if (kk_archive.archives.count > 0) { ++ kk_archive.task_options = [[MTL4CompilerTaskOptions alloc] init]; ++ kk_archive.task_options.lookupArchives = kk_archive.archives; ++ } ++ } ++ fprintf(stderr, "[kk-archive] dir %s: %u chunk(s) loaded (%llu KB), %u rejected, cap %llu MB, flush every %llu s\n", ++ kk_archive.directory, kk_archive.chunks_loaded, ++ (unsigned long long)(kk_archive.bytes_loaded / 1024), kk_archive.chunks_rejected, ++ (unsigned long long)(kk_archive.cap_bytes >> 20), ++ (unsigned long long)(kk_archive.flush_interval_ns / 1000000000ull)); ++} ++ ++static void ++kk_archive_write_chunk(void) ++{ ++ if (!kk_archive.enabled || kk_archive.serializer == nil) ++ return; ++ uint64_t built = atomic_exchange(&kk_archive.built_since_flush, 0); ++ if (built == 0) ++ return; ++ ++ char path[1400]; ++ snprintf(path, sizeof(path), "%s/chunk-%lld-%d-%llu.mtl4a", kk_archive.directory, ++ (long long)time(NULL), (int)getpid(), ++ (unsigned long long)atomic_load(&kk_archive.chunks_written)); ++ uint64_t start = kk_now_ns(); ++ bool written = false; ++ pthread_rwlock_wrlock(&kk_archive.lock); ++ @autoreleasepool { ++ NSURL *url = [NSURL fileURLWithPath:[NSString stringWithUTF8String:path]]; ++ NSError *error = nil; ++ written = [kk_archive.serializer serializeAsArchiveAndFlushToURL:url error:&error]; ++ if (!written) ++ fprintf(stderr, "[kk-archive] writing %s failed: %s\n", path, ++ error ? [error.localizedDescription UTF8String] : "no error"); ++ } ++ pthread_rwlock_unlock(&kk_archive.lock); ++ if (written) { ++ struct stat info; ++ off_t size = stat(path, &info) == 0 ? info.st_size : 0; ++ atomic_fetch_add(&kk_archive.chunks_written, 1); ++ fprintf(stderr, "[kk-archive] wrote %s: %lld KB, %llu pipeline build(s) since the last chunk, %.0f ms\n", ++ path, (long long)(size / 1024), (unsigned long long)built, ++ (kk_now_ns() - start) / 1e6); ++ kk_prune_chunks(); ++ } ++ atomic_store(&kk_archive.last_flush_ns, kk_now_ns()); ++} ++ ++/* After a pipeline build: write a chunk in the background when it's due. */ ++static void ++kk_archive_after_build(void) ++{ ++ if (!kk_archive.enabled) ++ return; ++ atomic_fetch_add(&kk_archive.built_since_flush, 1); ++ uint64_t now = kk_now_ns(); ++ if (now - atomic_load(&kk_archive.last_flush_ns) < kk_archive.flush_interval_ns) ++ return; ++ uint64_t idle = 0; ++ if (!atomic_compare_exchange_strong(&kk_archive.flush_running, &idle, 1)) ++ return; ++ atomic_store(&kk_archive.last_flush_ns, now); ++ dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{ ++ kk_archive_write_chunk(); ++ atomic_store(&kk_archive.flush_running, 0); ++ }); ++} ++ ++void ++mtl_compiler_flush_archive(mtl_compiler *compiler) ++{ ++ (void)compiler; ++ kk_compile_report(true); ++ if (kk_archive.archives == nil && !kk_archive.enabled) ++ return; ++ while (atomic_load(&kk_archive.flush_running)) ++ usleep(1000); ++ kk_archive_write_chunk(); ++} + + /* Compiler */ + mtl_compiler * +@@ -22,6 +418,12 @@ mtl_new_compiler(mtl_device *device) + + MTL4CompilerDescriptor *desc = [[MTL4CompilerDescriptor new] autorelease]; + ++ /* Madeira: archives (see the top of this file). */ ++ kk_archive_device = dev; ++ pthread_once(&kk_archive.once, kk_archive_init_once); ++ if (kk_archive.serializer != nil) ++ desc.pipelineDataSetSerializer = kk_archive.serializer; ++ + NSError *error; + id compiler = [dev newCompilerWithDescriptor:desc error:&error]; + +@@ -56,7 +458,9 @@ mtl_new_library(mtl_compiler *compiler, const char *src, + desc.options = opts; + + NSError *error; ++ uint64_t start = kk_now_ns(); + id lib = [comp newLibraryWithDescriptor:desc error:&error]; ++ kk_compile_record(&kk_stat_library, start); + + if (lib == nil) { + fprintf(stderr, "Failed to create MTLLibrary: %s\n", [error.localizedDescription UTF8String]); +@@ -94,8 +498,15 @@ mtl_new_compute_pipeline_state(mtl_compiler *compiler, + desc.maxTotalThreadsPerThreadgroup = max_total_threads_per_threadgroup; + + NSError *error; +- id pipeline = [comp newComputePipelineStateWithDescriptor:desc compilerTaskOptions:nil ++ uint64_t start = kk_now_ns(); ++ pthread_rwlock_rdlock(&kk_archive.lock); ++ id pipeline = [comp newComputePipelineStateWithDescriptor:desc ++ compilerTaskOptions:kk_archive.task_options + error:&error]; ++ pthread_rwlock_unlock(&kk_archive.lock); ++ kk_compile_record(&kk_stat_compute, start); ++ if (pipeline != nil) ++ kk_archive_after_build(); + + if (pipeline == nil) { + fprintf(stderr, "Failed to create MTLComputePipelineState: %s\n", [error.localizedDescription UTF8String]); +@@ -214,8 +625,15 @@ mtl_new_render_pipeline(mtl_compiler *compiler, mtl_render_pass_descriptor *desc + MTL4RenderPipelineDescriptor *desc = (MTL4RenderPipelineDescriptor *)descriptor; + + NSError *error = nil; +- id pipeline = [comp newRenderPipelineStateWithDescriptor:desc compilerTaskOptions:nil ++ uint64_t start = kk_now_ns(); ++ pthread_rwlock_rdlock(&kk_archive.lock); ++ id pipeline = [comp newRenderPipelineStateWithDescriptor:desc ++ compilerTaskOptions:kk_archive.task_options + error:&error]; ++ pthread_rwlock_unlock(&kk_archive.lock); ++ kk_compile_record(&kk_stat_render, start); ++ if (pipeline != nil) ++ kk_archive_after_build(); + + if (pipeline == nil) { + fprintf(stderr, "Failed to create MTLRenderPipelineState: %s\n", [error.localizedDescription UTF8String]); +diff --git a/src/kosmickrisp/bridge/stubs/mtl_compiler.c b/src/kosmickrisp/bridge/stubs/mtl_compiler.c +index c8b1a1b..86e6ffa 100644 +--- a/src/kosmickrisp/bridge/stubs/mtl_compiler.c ++++ b/src/kosmickrisp/bridge/stubs/mtl_compiler.c +@@ -15,6 +15,11 @@ mtl_new_compiler(mtl_device *device) + return NULL; + } + ++void ++mtl_compiler_flush_archive(mtl_compiler *compiler) ++{ ++} ++ + /* Library */ + mtl_library * + mtl_new_library(mtl_compiler *compiler, const char *src, +diff --git a/src/kosmickrisp/vulkan/kk_device.c b/src/kosmickrisp/vulkan/kk_device.c +index 644a872..959e6a0 100644 +--- a/src/kosmickrisp/vulkan/kk_device.c ++++ b/src/kosmickrisp/vulkan/kk_device.c +@@ -81,6 +81,7 @@ kk_release_compiler(struct kk_device *dev) + { + /* KK_WORKAROUND_11 */ + if (dev->disabled_workarounds & BITFIELD64_BIT(11)) { ++ mtl_compiler_flush_archive(dev->mtl_compiler_handle); + mtl_release(dev->mtl_compiler_handle); + return; + } +@@ -95,6 +96,8 @@ kk_release_compiler(struct kk_device *dev) + + if (compiler->refcount == 0) { + _mesa_hash_table_remove(&compilers_ht, ent); ++ /* Madeira: write the pipeline-archive chunk for this session. */ ++ mtl_compiler_flush_archive(compiler->handle); + mtl_release(compiler->handle); + ralloc_free(compiler); + } +-- +2.56.0 + diff --git a/build/mesa-ios/patches/kosmickrisp-ios-0009-frame-stats-present-hook.patch b/build/mesa-ios/patches/kosmickrisp-ios-0009-frame-stats-present-hook.patch new file mode 100644 index 0000000000..7bdf90ffcd --- /dev/null +++ b/build/mesa-ios/patches/kosmickrisp-ios-0009-frame-stats-present-hook.patch @@ -0,0 +1,246 @@ +From ba372134901040a9bb3c81400329158d939c46ee Mon Sep 17 00:00:00 2001 +From: Shitiz Garg +Date: Mon, 9 Nov 2026 21:25:54 +1100 +Subject: [PATCH] kosmickrisp: frame, submit and GPU statistics; Madeira + present hook + +[kk-frame] every 30 s: presents, present intervals (avg, max, >33/50/100 ms), +CPU time in queue submits and Metal's per-commit GPU time per frame. Each +present is also passed to madeira_vulkan_present_mark when the host process +exports it, so Madeira's FPS overlay counts Vulkan frames. +MADEIRA_KK_FRAME_STATS=0 turns the line off. + +Signed-off-by: Shitiz Garg +--- + src/kosmickrisp/bridge/mtl_command_queue.h | 1 + + src/kosmickrisp/bridge/mtl_command_queue.m | 12 ++ + .../bridge/stubs/mtl_command_queue.c | 6 + + src/kosmickrisp/vulkan/kk_queue.c | 137 ++++++++++++++++++ + 4 files changed, 156 insertions(+) + +diff --git a/src/kosmickrisp/bridge/mtl_command_queue.h b/src/kosmickrisp/bridge/mtl_command_queue.h +index 56c24f2..d9b03ab 100644 +--- a/src/kosmickrisp/bridge/mtl_command_queue.h ++++ b/src/kosmickrisp/bridge/mtl_command_queue.h +@@ -40,6 +40,7 @@ void mtl_command_queue_signal_drawable(mtl_command_queue *queue, + void *drawable); + + void mtl_drawable_present(void *drawable); ++void *mtl_drawable_layer(void *drawable); + + /* Madeira: Metal 4 drawable synchronisation. waitForDrawable must precede the + * commit of any command buffer that writes the drawable, and the layer's +diff --git a/src/kosmickrisp/bridge/mtl_command_queue.m b/src/kosmickrisp/bridge/mtl_command_queue.m +index ae5d52b..5c43bb4 100644 +--- a/src/kosmickrisp/bridge/mtl_command_queue.m ++++ b/src/kosmickrisp/bridge/mtl_command_queue.m +@@ -133,6 +133,18 @@ mtl_drawable_present(void *drawable) + } + } + ++/* Madeira: the CAMetalLayer a drawable belongs to (not retained), or NULL. */ ++void * ++mtl_drawable_layer(void *drawable) ++{ ++ @autoreleasepool { ++ id d = (id)drawable; ++ if (![d respondsToSelector:@selector(layer)]) ++ return NULL; ++ return (void *)[d performSelector:@selector(layer)]; ++ } ++} ++ + void + mtl_command_queue_wait_for_drawable(mtl_command_queue *queue, void *drawable) + { +diff --git a/src/kosmickrisp/bridge/stubs/mtl_command_queue.c b/src/kosmickrisp/bridge/stubs/mtl_command_queue.c +index d1962cc..491f205 100644 +--- a/src/kosmickrisp/bridge/stubs/mtl_command_queue.c ++++ b/src/kosmickrisp/bridge/stubs/mtl_command_queue.c +@@ -66,6 +66,12 @@ mtl_drawable_present(void *drawable) + { + } + ++void * ++mtl_drawable_layer(void *drawable) ++{ ++ return NULL; ++} ++ + void + mtl_command_queue_wait_for_drawable(mtl_command_queue *queue, void *drawable) + { +diff --git a/src/kosmickrisp/vulkan/kk_queue.c b/src/kosmickrisp/vulkan/kk_queue.c +index a5b8313..b8cd744 100644 +--- a/src/kosmickrisp/vulkan/kk_queue.c ++++ b/src/kosmickrisp/vulkan/kk_queue.c +@@ -22,6 +22,118 @@ + + #include + ++#include ++#include ++#include ++#include ++ ++/* ++ * Madeira: frame and GPU statistics. Every 30 s a [kk-frame] line gives the ++ * presents in the window, the CPU interval between presents (average, max and ++ * how many took over 33, 50 and 100 ms), the CPU time spent in queue submits, ++ * and the GPU time Metal reports per commit (GPUEndTime - GPUStartTime) summed ++ * per frame. Presents are also handed to Madeira's frame counter ++ * (madeira_vulkan_present_mark, looked up at run time; absent outside Madeira) ++ * so its FPS overlay and [frame] lines count Vulkan frames. ++ * MADEIRA_KK_FRAME_STATS=0 turns the line off. ++ */ ++#define KK_FRAME_REPORT_NS (30ull * 1000000000ull) ++ ++static struct { ++ _Atomic uint64_t gpu_ns; ++ _Atomic uint64_t gpu_commits; ++ _Atomic uint64_t gpu_max_ns; ++ uint64_t window_start_ns; ++ uint64_t last_present_ns; ++ uint64_t presents; ++ uint64_t interval_total_ns; ++ uint64_t interval_max_ns; ++ uint64_t over_33ms; ++ uint64_t over_50ms; ++ uint64_t over_100ms; ++ uint64_t submit_ns; ++ uint64_t submits; ++ int enabled; ++ void (*present_mark)(const void *layer); ++ bool present_mark_resolved; ++} kk_frames = {.enabled = -1}; ++ ++static uint64_t ++kk_frame_now_ns(void) ++{ ++ struct timespec ts; ++ clock_gettime(CLOCK_MONOTONIC, &ts); ++ return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec; ++} ++ ++static void ++kk_frame_report(uint64_t now) ++{ ++ uint64_t window = now - kk_frames.window_start_ns; ++ uint64_t gpu_ns = atomic_exchange(&kk_frames.gpu_ns, 0); ++ uint64_t commits = atomic_exchange(&kk_frames.gpu_commits, 0); ++ uint64_t gpu_max = atomic_exchange(&kk_frames.gpu_max_ns, 0); ++ uint64_t presents = kk_frames.presents; ++ fprintf(stderr, ++ "[kk-frame] %.1f s: presents=%llu fps=%.1f interval avg=%.1fms max=%.1fms >33ms=%llu >50ms=%llu " ++ ">100ms=%llu | submit cpu %.2f ms/frame (%llu submits) | gpu %.2f ms/frame busy=%.0f%% " ++ "commits=%llu max=%.1fms\n", ++ window / 1e9, (unsigned long long)presents, window ? presents * 1e9 / window : 0.0, ++ presents ? kk_frames.interval_total_ns / 1e6 / presents : 0.0, ++ kk_frames.interval_max_ns / 1e6, (unsigned long long)kk_frames.over_33ms, ++ (unsigned long long)kk_frames.over_50ms, (unsigned long long)kk_frames.over_100ms, ++ presents ? kk_frames.submit_ns / 1e6 / presents : 0.0, ++ (unsigned long long)kk_frames.submits, presents ? gpu_ns / 1e6 / presents : 0.0, ++ window ? 100.0 * gpu_ns / window : 0.0, (unsigned long long)commits, gpu_max / 1e6); ++ kk_frames.window_start_ns = now; ++ kk_frames.presents = 0; ++ kk_frames.interval_total_ns = 0; ++ kk_frames.interval_max_ns = 0; ++ kk_frames.over_33ms = 0; ++ kk_frames.over_50ms = 0; ++ kk_frames.over_100ms = 0; ++ kk_frames.submit_ns = 0; ++ kk_frames.submits = 0; ++} ++ ++/* Called from the submitting thread for each present. */ ++static void ++kk_frame_present(void *drawable) ++{ ++ if (!kk_frames.present_mark_resolved) { ++ kk_frames.present_mark = ++ (void (*)(const void *))dlsym(RTLD_DEFAULT, "madeira_vulkan_present_mark"); ++ kk_frames.present_mark_resolved = true; ++ } ++ if (kk_frames.present_mark) ++ kk_frames.present_mark(mtl_drawable_layer(drawable)); ++ ++ if (kk_frames.enabled < 0) ++ kk_frames.enabled = debug_get_bool_option("MADEIRA_KK_FRAME_STATS", true); ++ if (!kk_frames.enabled) ++ return; ++ ++ uint64_t now = kk_frame_now_ns(); ++ if (kk_frames.window_start_ns == 0) ++ kk_frames.window_start_ns = now; ++ if (kk_frames.last_present_ns != 0) { ++ uint64_t interval = now - kk_frames.last_present_ns; ++ kk_frames.interval_total_ns += interval; ++ if (interval > kk_frames.interval_max_ns) ++ kk_frames.interval_max_ns = interval; ++ if (interval > 33000000ull) ++ kk_frames.over_33ms++; ++ if (interval > 50000000ull) ++ kk_frames.over_50ms++; ++ if (interval > 100000000ull) ++ kk_frames.over_100ms++; ++ } ++ kk_frames.last_present_ns = now; ++ kk_frames.presents++; ++ if (now - kk_frames.window_start_ns >= KK_FRAME_REPORT_NS) ++ kk_frame_report(now); ++} ++ + /* Madeira: Metal 4 does not synchronise or page in CAMetalLayer drawables on + * its own. Before a command buffer that writes a drawable is committed, the + * queue must wait for the display to release it, and the layer's residency +@@ -54,6 +166,16 @@ kk_queue_prepare_drawable(struct kk_queue *queue, void *drawable) + static void + commit_callback(struct mtl_feedback_data *data) + { ++ /* Madeira: GPU time per commit for [kk-frame]. */ ++ if (data->gpu_end > data->gpu_start && data->gpu_start > 0.0) { ++ uint64_t gpu = (uint64_t)((data->gpu_end - data->gpu_start) * 1e9); ++ atomic_fetch_add(&kk_frames.gpu_ns, gpu); ++ atomic_fetch_add(&kk_frames.gpu_commits, 1); ++ uint64_t max = atomic_load(&kk_frames.gpu_max_ns); ++ while (gpu > max && ++ !atomic_compare_exchange_weak(&kk_frames.gpu_max_ns, &max, gpu)) ++ ; ++ } + if (data->error != MTL_COMMAND_QUEUE_ERROR_NONE) { + struct kk_device *dev = (struct kk_device *)data->user_data; + vk_device_set_lost( +@@ -78,8 +200,22 @@ rerecord_cmd_buffer(struct kk_cmd_buffer *cmd) + kk_device_make_resources_resident(dev); + } + ++static VkResult ++kk_queue_submit_impl(struct vk_queue *vk_queue, struct vk_queue_submit *submit); ++ ++/* Madeira: CPU time in queue submits, for [kk-frame]. */ + static VkResult + kk_queue_submit(struct vk_queue *vk_queue, struct vk_queue_submit *submit) ++{ ++ uint64_t start = kk_frame_now_ns(); ++ VkResult result = kk_queue_submit_impl(vk_queue, submit); ++ kk_frames.submit_ns += kk_frame_now_ns() - start; ++ kk_frames.submits++; ++ return result; ++} ++ ++static VkResult ++kk_queue_submit_impl(struct vk_queue *vk_queue, struct vk_queue_submit *submit) + { + struct kk_queue *queue = container_of(vk_queue, struct kk_queue, vk); + struct kk_device *dev = kk_queue_device(queue); +@@ -142,6 +278,7 @@ kk_queue_submit(struct vk_queue *vk_queue, struct vk_queue_submit *submit) + mtl_command_queue_signal_drawable(queue->mtl_handle, + cmd_buffer->drawable); + mtl_drawable_present(cmd_buffer->drawable); ++ kk_frame_present(cmd_buffer->drawable); + /* Madeira: drop the reference kk_encode_drawable_present took. A + * CAMetalLayer reuses a drawable only after every reference to it + * is gone; with this one leaked, the layer ran out of drawables +-- +2.56.0 + diff --git a/build/mesa-ios/patches/kosmickrisp-ios-0010-device-features-diagnostics.patch b/build/mesa-ios/patches/kosmickrisp-ios-0010-device-features-diagnostics.patch new file mode 100644 index 0000000000..9879e156ed --- /dev/null +++ b/build/mesa-ios/patches/kosmickrisp-ios-0010-device-features-diagnostics.patch @@ -0,0 +1,193 @@ +From 59076c1af3dc9eaa63a372f1eae3299e90b89769 Mon Sep 17 00:00:00 2001 +From: Shitiz Garg +Date: Mon, 9 Nov 2026 23:40:21 +1100 +Subject: [PATCH] kosmickrisp: name unsupported features at device creation; + opt-in relaxation + +Signed-off-by: Shitiz Garg +Co-Authored-By: Claude Opus 5.5 +--- + src/kosmickrisp/vulkan/kk_device.c | 149 ++++++++++++++++++++++++++++- + 1 file changed, 148 insertions(+), 1 deletion(-) + +diff --git a/src/kosmickrisp/vulkan/kk_device.c b/src/kosmickrisp/vulkan/kk_device.c +index 959e6a0..3899837 100644 +--- a/src/kosmickrisp/vulkan/kk_device.c ++++ b/src/kosmickrisp/vulkan/kk_device.c +@@ -23,7 +23,10 @@ + + #include "vulkan/wsi/wsi_common.h" + #include "vk_pipeline_cache.h" ++#include "vk_enum_to_str.h" + ++#include ++#include + #include + + struct kk_mtl_compiler { +@@ -265,6 +268,134 @@ kk_get_timestamp(struct vk_device *device, uint64_t *timestamp) + return VK_SUCCESS; + } + ++ ++/* Madeira: device-creation diagnostics and an opt-in feature relaxation. ++ * ++ * When an application enables a feature KosmicKrisp lacks, vk_device_init ++ * fails with VK_ERROR_FEATURE_NOT_PRESENT and the reason only reaches a debug ++ * messenger, so a game that silently falls back to another renderer leaves no ++ * trace. Every enabled core feature that isn't supported is logged here as ++ * [kk-features]. With MADEIRA_KK_RELAX_FEATURES=1 those core 1.0 features are ++ * dropped from the request instead (each one logged), so device creation can ++ * go ahead for applications that enable features they never use. ++ */ ++#define KK_CORE_FEATURES(X) \ ++ X(robustBufferAccess) \ ++ X(fullDrawIndexUint32) \ ++ X(imageCubeArray) \ ++ X(independentBlend) \ ++ X(geometryShader) \ ++ X(tessellationShader) \ ++ X(sampleRateShading) \ ++ X(dualSrcBlend) \ ++ X(logicOp) \ ++ X(multiDrawIndirect) \ ++ X(drawIndirectFirstInstance) \ ++ X(depthClamp) \ ++ X(depthBiasClamp) \ ++ X(fillModeNonSolid) \ ++ X(depthBounds) \ ++ X(wideLines) \ ++ X(largePoints) \ ++ X(alphaToOne) \ ++ X(multiViewport) \ ++ X(samplerAnisotropy) \ ++ X(textureCompressionETC2) \ ++ X(textureCompressionASTC_LDR) \ ++ X(textureCompressionBC) \ ++ X(occlusionQueryPrecise) \ ++ X(pipelineStatisticsQuery) \ ++ X(vertexPipelineStoresAndAtomics) \ ++ X(fragmentStoresAndAtomics) \ ++ X(shaderTessellationAndGeometryPointSize) \ ++ X(shaderImageGatherExtended) \ ++ X(shaderStorageImageExtendedFormats) \ ++ X(shaderStorageImageMultisample) \ ++ X(shaderStorageImageReadWithoutFormat) \ ++ X(shaderStorageImageWriteWithoutFormat) \ ++ X(shaderUniformBufferArrayDynamicIndexing) \ ++ X(shaderSampledImageArrayDynamicIndexing) \ ++ X(shaderStorageBufferArrayDynamicIndexing) \ ++ X(shaderStorageImageArrayDynamicIndexing) \ ++ X(shaderClipDistance) \ ++ X(shaderCullDistance) \ ++ X(shaderFloat64) \ ++ X(shaderInt64) \ ++ X(shaderInt16) \ ++ X(shaderResourceResidency) \ ++ X(shaderResourceMinLod) \ ++ X(sparseBinding) \ ++ X(sparseResidencyBuffer) \ ++ X(sparseResidencyImage2D) \ ++ X(sparseResidencyImage3D) \ ++ X(sparseResidency2Samples) \ ++ X(sparseResidency4Samples) \ ++ X(sparseResidency8Samples) \ ++ X(sparseResidency16Samples) \ ++ X(sparseResidencyAliased) \ ++ X(variableMultisampleRate) \ ++ X(inheritedQueries) ++ ++static uint32_t ++kk_relax_core_features(VkPhysicalDeviceFeatures *enabled, ++ const VkPhysicalDeviceFeatures *supported, bool relax, ++ const char *where) ++{ ++ uint32_t missing = 0; ++#define KK_CHECK_FEATURE(name) \ ++ if (enabled->name && !supported->name) { \ ++ missing++; \ ++ fprintf(stderr, "[kk-features] %s.%s requested but not supported%s\n", \ ++ where, #name, relax ? ": dropped (MADEIRA_KK_RELAX_FEATURES)" : ""); \ ++ if (relax) \ ++ enabled->name = VK_FALSE; \ ++ } ++ KK_CORE_FEATURES(KK_CHECK_FEATURE) ++#undef KK_CHECK_FEATURE ++ return missing; ++} ++ ++static const VkDeviceCreateInfo * ++kk_relax_device_features(VkPhysicalDevice physicalDevice, ++ const VkDeviceCreateInfo *info, ++ VkDeviceCreateInfo *relaxed_info, ++ VkPhysicalDeviceFeatures *relaxed_features, ++ VkPhysicalDeviceFeatures2 *relaxed_features2) ++{ ++ const char *env = getenv("MADEIRA_KK_RELAX_FEATURES"); ++ bool relax = env && env[0] == '1'; ++ VkPhysicalDeviceFeatures supported; ++ vk_common_GetPhysicalDeviceFeatures(physicalDevice, &supported); ++ ++ *relaxed_info = *info; ++ if (info->pEnabledFeatures) { ++ *relaxed_features = *info->pEnabledFeatures; ++ kk_relax_core_features(relaxed_features, &supported, relax, ++ "pEnabledFeatures"); ++ relaxed_info->pEnabledFeatures = relaxed_features; ++ } ++ ++ for (const VkBaseInStructure *ext = info->pNext; ext; ext = ext->pNext) { ++ if (ext->sType != VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2) ++ continue; ++ VkPhysicalDeviceFeatures2 *features2 = (VkPhysicalDeviceFeatures2 *)ext; ++ if ((const void *)ext == info->pNext) { ++ /* The usual layout: substitute a copy at the head of the chain. */ ++ *relaxed_features2 = *features2; ++ kk_relax_core_features(&relaxed_features2->features, &supported, ++ relax, "VkPhysicalDeviceFeatures2"); ++ relaxed_info->pNext = relaxed_features2; ++ } else { ++ /* Deeper in the chain: the copy can't be spliced in without cloning ++ * the structures before it, so report, and relax in place. */ ++ kk_relax_core_features(&features2->features, &supported, relax, ++ "VkPhysicalDeviceFeatures2 (in place)"); ++ } ++ break; ++ } ++ return relaxed_info; ++} ++ + VKAPI_ATTR VkResult VKAPI_CALL + kk_CreateDevice(VkPhysicalDevice physicalDevice, + const VkDeviceCreateInfo *pCreateInfo, +@@ -296,10 +427,26 @@ kk_CreateDevice(VkPhysicalDevice physicalDevice, + vk_device_dispatch_table_from_entrypoints(&dispatch_table, + &wsi_device_entrypoints, false); + ++ VkDeviceCreateInfo relaxed_info; ++ VkPhysicalDeviceFeatures relaxed_features; ++ VkPhysicalDeviceFeatures2 relaxed_features2; ++ pCreateInfo = kk_relax_device_features(physicalDevice, pCreateInfo, ++ &relaxed_info, &relaxed_features, ++ &relaxed_features2); ++ ++ /* Madeira: let vk_errorf reach stderr during device creation, so a ++ * failure names the feature or extension (Vulkan 1.1+ and extension ++ * feature structures included). */ ++ bool saved_debug_logging = pdev->vk.instance->enable_debug_logging; ++ pdev->vk.instance->enable_debug_logging = true; + result = vk_device_init(&dev->vk, &pdev->vk, &dispatch_table, pCreateInfo, + pAllocator); +- if (result != VK_SUCCESS) ++ pdev->vk.instance->enable_debug_logging = saved_debug_logging; ++ if (result != VK_SUCCESS) { ++ fprintf(stderr, "[kk-features] vkCreateDevice failed: %s\n", ++ vk_Result_to_str(result)); + goto fail_alloc; ++ } + + /* Implicit pipeline cache. Applications that pass no VkPipelineCache (many + * do, relying on the driver's own cache) otherwise get no caching at all, +-- +2.56.0 + diff --git a/build/mesa-ios/patches/kosmickrisp-ios-0011-split-timestamp-counter-heaps.patch b/build/mesa-ios/patches/kosmickrisp-ios-0011-split-timestamp-counter-heaps.patch new file mode 100644 index 0000000000..d8d2f66ca5 --- /dev/null +++ b/build/mesa-ios/patches/kosmickrisp-ios-0011-split-timestamp-counter-heaps.patch @@ -0,0 +1,211 @@ +From 6ea8e3a1fd9951c06e1405dbbf0f6501f5853825 Mon Sep 17 00:00:00 2001 +From: Shitiz Garg +Date: Mon, 9 Nov 2026 23:56:47 +1100 +Subject: [PATCH] kosmickrisp: split large timestamp query pools across counter + heaps + +Metal caps the entries in one MTL4CounterHeap (AGX: "Invalid heap size +requested"). PoE2 creates a timestamp pool larger than that, so +vkCreateQueryPool failed with VK_ERROR_OUT_OF_DEVICE_MEMORY and the game +fell back to DirectX 11. Find the largest size Metal accepts by halving, +remember it for the process, and spread the pool over as many heaps as +it needs. + +Signed-off-by: Shitiz Garg +Co-Authored-By: Claude Opus 5.5 +--- + src/kosmickrisp/vulkan/kk_query_pool.c | 102 +++++++++++++++++++++---- + src/kosmickrisp/vulkan/kk_query_pool.h | 12 ++- + 2 files changed, 96 insertions(+), 18 deletions(-) + +diff --git a/src/kosmickrisp/vulkan/kk_query_pool.c b/src/kosmickrisp/vulkan/kk_query_pool.c +index 3e7dd25..7e6890f 100644 +--- a/src/kosmickrisp/vulkan/kk_query_pool.c ++++ b/src/kosmickrisp/vulkan/kk_query_pool.c +@@ -18,6 +18,9 @@ + #include "kk_query_table.h" + + #include "kosmickrisp/bridge/mtl_bridge.h" ++#include "vk_alloc.h" ++ ++#include + + struct kk_query_report { + uint64_t value; +@@ -116,6 +119,73 @@ host_zero_queries(struct kk_device *dev, struct kk_query_pool *pool, + } + } + ++ ++/* Madeira: Metal caps the entries in one counter heap (AGX answers "Invalid ++ * heap size requested"), and PoE2 asks for a timestamp pool larger than that, ++ * so vkCreateQueryPool failed with VK_ERROR_OUT_OF_DEVICE_MEMORY and the game ++ * fell back to DirectX 11. Split large pools across several heaps. The largest ++ * size that worked is remembered for the process, so later pools don't retry ++ * sizes Metal has already refused. */ ++static uint32_t kk_ts_heap_max_entries; ++ ++static inline mtl_counter_heap * ++kk_ts_heap(struct kk_query_pool *pool, uint32_t query) ++{ ++ return pool->ts.heaps[query / pool->ts.heap_entries]; ++} ++ ++static VkResult ++kk_ts_create_heaps(struct kk_device *dev, struct kk_query_pool *pool, ++ const VkAllocationCallbacks *pAllocator) ++{ ++ uint32_t count = MAX2(pool->vk.query_count, 1); ++ uint32_t known_max = __atomic_load_n(&kk_ts_heap_max_entries, __ATOMIC_RELAXED); ++ uint32_t entries = known_max ? MIN2(count, known_max) : count; ++ ++ /* Find a heap size Metal accepts: halve until one works. */ ++ mtl_counter_heap *first = NULL; ++ while (entries > 0) { ++ first = mtl_new_timestamp_counter_heap(dev->mtl_handle, entries); ++ if (first) ++ break; ++ entries /= 2; ++ } ++ if (!first) { ++ fprintf(stderr, "[kk-query] timestamp pool of %u: no counter heap size works\n", ++ pool->vk.query_count); ++ return VK_ERROR_OUT_OF_DEVICE_MEMORY; ++ } ++ if (entries < count && entries > known_max) ++ __atomic_store_n(&kk_ts_heap_max_entries, entries, __ATOMIC_RELAXED); ++ ++ uint32_t heap_count = DIV_ROUND_UP(count, entries); ++ pool->ts.heaps = vk_zalloc2(&dev->vk.alloc, pAllocator, ++ heap_count * sizeof(*pool->ts.heaps), 8, ++ VK_SYSTEM_ALLOCATION_SCOPE_OBJECT); ++ if (!pool->ts.heaps) { ++ mtl_release(first); ++ return VK_ERROR_OUT_OF_HOST_MEMORY; ++ } ++ pool->ts.heap_entries = entries; ++ pool->ts.heap_count = heap_count; ++ pool->ts.heaps[0] = first; ++ for (uint32_t i = 1; i < heap_count; ++i) { ++ uint32_t this_entries = MIN2(entries, count - i * entries); ++ pool->ts.heaps[i] = mtl_new_timestamp_counter_heap(dev->mtl_handle, ++ this_entries); ++ if (!pool->ts.heaps[i]) { ++ fprintf(stderr, "[kk-query] timestamp pool of %u: counter heap %u of %u " ++ "(%u entries) failed\n", pool->vk.query_count, i + 1, ++ heap_count, this_entries); ++ return VK_ERROR_OUT_OF_DEVICE_MEMORY; ++ } ++ } ++ if (heap_count > 1) ++ fprintf(stderr, "[kk-query] timestamp pool of %u split into %u counter " ++ "heaps of %u\n", pool->vk.query_count, heap_count, entries); ++ return VK_SUCCESS; ++} ++ + VKAPI_ATTR VkResult VKAPI_CALL + kk_CreateQueryPool(VkDevice device, const VkQueryPoolCreateInfo *pCreateInfo, + const VkAllocationCallbacks *pAllocator, +@@ -178,15 +248,14 @@ kk_CreateQueryPool(VkDevice device, const VkQueryPoolCreateInfo *pCreateInfo, + remap_index[pool->oq.queries++] = index; + } + } else if (kk_pool_is_ts(pool)) { +- /* Timestamps are sampled into a Metal counter heap (one entry per query) ++ /* Timestamps are sampled into Metal counter heaps (one entry per query) + * and resolved into `bo` after the GPU writes them. */ +- pool->ts.heap = +- mtl_new_timestamp_counter_heap(dev->mtl_handle, pool->vk.query_count); +- if (pool->ts.heap == NULL) { ++ pool->ts.stage_map = UTIL_DYNARRAY_INIT; ++ result = kk_ts_create_heaps(dev, pool, pAllocator); ++ if (result != VK_SUCCESS) { + kk_DestroyQueryPool(device, kk_query_pool_to_handle(pool), pAllocator); +- return vk_error(dev, VK_ERROR_OUT_OF_DEVICE_MEMORY); ++ return vk_error(dev, result); + } +- pool->ts.stage_map = UTIL_DYNARRAY_INIT; + + /* set up default mapping for unique queries */ + for (unsigned i = 0; i < pool->vk.query_count; ++i) { +@@ -218,8 +287,11 @@ kk_DestroyQueryPool(VkDevice device, VkQueryPool queryPool, + kk_query_table_remove(dev, &dev->occlusion_queries, remap_index[i]); + } + } else if (kk_pool_is_ts(pool)) { +- if (pool->ts.heap) +- mtl_release(pool->ts.heap); ++ for (uint32_t i = 0; i < pool->ts.heap_count; ++i) { ++ if (pool->ts.heaps[i]) ++ mtl_release(pool->ts.heaps[i]); ++ } ++ vk_free2(&dev->vk.alloc, pAllocator, pool->ts.heaps); + util_dynarray_fini(&pool->ts.stage_map); + } + +@@ -340,7 +412,9 @@ kk_CmdWriteTimestamp2(VkCommandBuffer commandBuffer, + VK_FROM_HANDLE(kk_cmd_buffer, cmd, commandBuffer); + VK_FROM_HANDLE(kk_query_pool, pool, queryPool); + struct kk_device *dev = kk_cmd_buffer_device(cmd); +- assert(kk_pool_is_ts(pool) && pool->ts.heap); ++ assert(kk_pool_is_ts(pool) && pool->ts.heaps); ++ uint32_t heap_index = query % pool->ts.heap_entries; ++ mtl_counter_heap *heap = kk_ts_heap(pool, query); + + uint32_t count = kk_mv_query_count(cmd); + enum mtl_render_stages mtl_stage = +@@ -350,8 +424,8 @@ kk_CmdWriteTimestamp2(VkCommandBuffer commandBuffer, + * BO (overwriting the unavailable sentinel) so both the host and GPU result + * paths can read it. Flushed on the GPU timeline at cs_end. */ + struct kk_ts_resolve resolve = { +- .heap = pool->ts.heap, +- .index = query, ++ .heap = heap, ++ .index = heap_index, + .dst_addr = kk_query_report_addr(dev, pool, query), + }; + +@@ -379,8 +453,8 @@ kk_CmdWriteTimestamp2(VkCommandBuffer commandBuffer, + .index = query}; + util_dynarray_append(&pool->ts.stage_map, entry); + +- mtl_render_write_timestamp(cmd->gfx.encoder, mtl_stage, pool->ts.heap, +- query); ++ mtl_render_write_timestamp(cmd->gfx.encoder, mtl_stage, heap, ++ heap_index); + util_dynarray_append(&cmd->gfx.ts_resolves, resolve); + } else { + bool top = true; +@@ -401,7 +475,7 @@ kk_CmdWriteTimestamp2(VkCommandBuffer commandBuffer, + addr += sizeof(uint32_t); + } + +- mtl_compute_write_timestamp(es->encoder, pool->ts.heap, query); ++ mtl_compute_write_timestamp(es->encoder, heap, heap_index); + util_dynarray_append(&es->ts_resolves, resolve); + } + } +diff --git a/src/kosmickrisp/vulkan/kk_query_pool.h b/src/kosmickrisp/vulkan/kk_query_pool.h +index 2fe4c76..67b6177 100644 +--- a/src/kosmickrisp/vulkan/kk_query_pool.h ++++ b/src/kosmickrisp/vulkan/kk_query_pool.h +@@ -20,10 +20,14 @@ struct kk_ts_stage_entry { + }; + + struct kk_ts_state { +- /* Metal 4 counter heap backing VK_QUERY_TYPE_TIMESTAMP pools. Timestamps are +- * sampled into this heap and later resolved into `bo` (see kk_query_pool.c). +- * NULL for non-timestamp pools. */ +- mtl_counter_heap *heap; ++ /* Metal 4 counter heaps backing VK_QUERY_TYPE_TIMESTAMP pools. Timestamps are ++ * sampled into these heaps and later resolved into `bo` (see kk_query_pool.c). ++ * Metal caps the size of one counter heap, so a large pool is split into ++ * `heap_count` heaps of `heap_entries` entries: query q lives in ++ * heaps[q / heap_entries] at q % heap_entries. NULL for non-timestamp pools. */ ++ mtl_counter_heap **heaps; ++ uint32_t heap_count; ++ uint32_t heap_entries; + struct util_dynarray stage_map; + }; + +-- +2.56.0 + diff --git a/build/mesa-ios/patches/kosmickrisp-ios-0012-heapless-timestamp-pools.patch b/build/mesa-ios/patches/kosmickrisp-ios-0012-heapless-timestamp-pools.patch new file mode 100644 index 0000000000..af03159051 --- /dev/null +++ b/build/mesa-ios/patches/kosmickrisp-ios-0012-heapless-timestamp-pools.patch @@ -0,0 +1,85 @@ +From 63b7b94c6f33dd26726af0792de771364f9f13a8 Mon Sep 17 00:00:00 2001 +From: Shitiz Garg +Date: Tue, 10 Nov 2026 00:17:17 +1100 +Subject: [PATCH] kosmickrisp: timestamp pools without a counter heap when + Metal refuses one + +On the iPhone (A20, iOS 26) Metal refuses every timestamp counter heap, +even one of 2 entries (AGX: "Invalid heap size requested"), so splitting +the pool doesn't help and vkCreateQueryPool still failed. Create the pool +without a heap instead: vkCmdWriteTimestamp2 marks the query available and +its value reads as the 0 the reset left. Logged once as [kk-query]. + +Signed-off-by: Shitiz Garg +Co-Authored-By: Claude Opus 5.5 +--- + src/kosmickrisp/vulkan/kk_query_pool.c | 36 ++++++++++++++++++++++---- + 1 file changed, 31 insertions(+), 5 deletions(-) + +diff --git a/src/kosmickrisp/vulkan/kk_query_pool.c b/src/kosmickrisp/vulkan/kk_query_pool.c +index 7e6890f..d0dd8b3 100644 +--- a/src/kosmickrisp/vulkan/kk_query_pool.c ++++ b/src/kosmickrisp/vulkan/kk_query_pool.c +@@ -140,6 +140,8 @@ kk_ts_create_heaps(struct kk_device *dev, struct kk_query_pool *pool, + { + uint32_t count = MAX2(pool->vk.query_count, 1); + uint32_t known_max = __atomic_load_n(&kk_ts_heap_max_entries, __ATOMIC_RELAXED); ++ if (known_max == UINT32_MAX) ++ return VK_SUCCESS; /* heaps refused before: no heap (see below) */ + uint32_t entries = known_max ? MIN2(count, known_max) : count; + + /* Find a heap size Metal accepts: halve until one works. */ +@@ -151,9 +153,19 @@ kk_ts_create_heaps(struct kk_device *dev, struct kk_query_pool *pool, + entries /= 2; + } + if (!first) { +- fprintf(stderr, "[kk-query] timestamp pool of %u: no counter heap size works\n", +- pool->vk.query_count); +- return VK_ERROR_OUT_OF_DEVICE_MEMORY; ++ /* On the iPhone (A20, iOS 26) Metal refuses every timestamp counter ++ * heap, even of 2 entries ("Invalid heap size requested"). Failing the ++ * pool makes PoE2 abandon Vulkan, so create it without a heap: writes ++ * mark the query available and the value reads as 0. */ ++ static bool warned; ++ if (!warned) { ++ warned = true; ++ fprintf(stderr, "[kk-query] Metal refuses timestamp counter heaps here " ++ "(pool of %u): timestamp queries will read 0\n", ++ pool->vk.query_count); ++ } ++ __atomic_store_n(&kk_ts_heap_max_entries, UINT32_MAX, __ATOMIC_RELAXED); ++ return VK_SUCCESS; + } + if (entries < count && entries > known_max) + __atomic_store_n(&kk_ts_heap_max_entries, entries, __ATOMIC_RELAXED); +@@ -412,11 +424,25 @@ kk_CmdWriteTimestamp2(VkCommandBuffer commandBuffer, + VK_FROM_HANDLE(kk_cmd_buffer, cmd, commandBuffer); + VK_FROM_HANDLE(kk_query_pool, pool, queryPool); + struct kk_device *dev = kk_cmd_buffer_device(cmd); +- assert(kk_pool_is_ts(pool) && pool->ts.heaps); ++ assert(kk_pool_is_ts(pool)); ++ uint32_t count = kk_mv_query_count(cmd); ++ ++ if (!pool->ts.heaps) { ++ /* No Metal counter heap on this device (see kk_ts_create_heaps): make ++ * the query available with the value the reset left, 0, so the ++ * application never waits on it. */ ++ bool top = !(cmd->gfx.encoder && ++ (stage & VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT)); ++ uint64_t addr = kk_query_available_addr(pool, query); ++ for (uint32_t i = 0; i < count; i++) { ++ libkk_write_u32(cmd, kk_grid_1d(1), top, addr, true); ++ addr += sizeof(uint32_t); ++ } ++ return; ++ } + uint32_t heap_index = query % pool->ts.heap_entries; + mtl_counter_heap *heap = kk_ts_heap(pool, query); + +- uint32_t count = kk_mv_query_count(cmd); + enum mtl_render_stages mtl_stage = + kk_pipeline_stages_to_mtl_render_stage(stage); + +-- +2.56.0 + diff --git a/build/mesa-ios/patches/kosmickrisp-ios-0013-compile-marks-for-the-app.patch b/build/mesa-ios/patches/kosmickrisp-ios-0013-compile-marks-for-the-app.patch new file mode 100644 index 0000000000..08233ff4c7 --- /dev/null +++ b/build/mesa-ios/patches/kosmickrisp-ios-0013-compile-marks-for-the-app.patch @@ -0,0 +1,113 @@ +From 382e00241a98afde248ea02e9ea67bdaa33bf06e Mon Sep 17 00:00:00 2001 +From: Shitiz Garg +Date: Tue, 10 Nov 2026 01:07:23 +1100 +Subject: [PATCH] kosmickrisp: report builds to the embedding app + (madeira_vulkan_compile_mark) + +Signed-off-by: Shitiz Garg +Co-Authored-By: Claude Opus 5.5 +--- + src/kosmickrisp/bridge/mtl_compiler.m | 41 +++++++++++++++++++++++---- + 1 file changed, 35 insertions(+), 6 deletions(-) + +diff --git a/src/kosmickrisp/bridge/mtl_compiler.m b/src/kosmickrisp/bridge/mtl_compiler.m +index 74e1bde..7617cec 100644 +--- a/src/kosmickrisp/bridge/mtl_compiler.m ++++ b/src/kosmickrisp/bridge/mtl_compiler.m +@@ -15,6 +15,7 @@ + #include + #include + #include ++#include + + #include + #include +@@ -54,6 +55,7 @@ + + struct kk_compile_stat { + const char *name; ++ int kind; /* madeira_vulkan_compile_mark: 0 library, 1 render, 2 compute */ + _Atomic uint64_t count; + _Atomic uint64_t total_ns; + _Atomic uint64_t max_ns; +@@ -63,9 +65,9 @@ struct kk_compile_stat { + _Atomic uint64_t slow; + }; + +-static struct kk_compile_stat kk_stat_library = {.name = "library"}; +-static struct kk_compile_stat kk_stat_render = {.name = "render"}; +-static struct kk_compile_stat kk_stat_compute = {.name = "compute"}; ++static struct kk_compile_stat kk_stat_library = {.name = "library", .kind = 0}; ++static struct kk_compile_stat kk_stat_render = {.name = "render", .kind = 1}; ++static struct kk_compile_stat kk_stat_compute = {.name = "compute", .kind = 2}; + static _Atomic uint64_t kk_last_report_ns; + static int kk_stats_enabled = -1; + +@@ -146,10 +148,37 @@ kk_compile_report(bool force) + kk_archive.enabled ? "" : " (archives off)"); + } + ++ ++/* Madeira: every build is also reported to the app (madeira_vulkan_compile_mark in ++ * WiniosGL.m, found with dlsym like madeira_vulkan_present_mark), which keeps the ++ * counters its performance overlay and Shaders page show: builds in flight, and ++ * each finished build's kind and duration. Absent outside Madeira. */ ++static void (*kk_compile_mark)(int kind, int begin, uint64_t ns); ++static _Atomic int kk_compile_mark_resolved; ++ ++static void ++kk_compile_notify(int kind, int begin, uint64_t ns) ++{ ++ if (!atomic_load_explicit(&kk_compile_mark_resolved, memory_order_acquire)) { ++ kk_compile_mark = (void (*)(int, int, uint64_t))dlsym(RTLD_DEFAULT, "madeira_vulkan_compile_mark"); ++ atomic_store_explicit(&kk_compile_mark_resolved, 1, memory_order_release); ++ } ++ if (kk_compile_mark) ++ kk_compile_mark(kind, begin, ns); ++} ++ ++static uint64_t ++kk_compile_begin(struct kk_compile_stat *stat) ++{ ++ kk_compile_notify(stat->kind, 1, 0); ++ return kk_now_ns(); ++} ++ + static void + kk_compile_record(struct kk_compile_stat *stat, uint64_t start_ns) + { + uint64_t elapsed = kk_now_ns() - start_ns; ++ kk_compile_notify(stat->kind, 0, elapsed); + atomic_fetch_add(&stat->count, 1); + atomic_fetch_add(&stat->total_ns, elapsed); + uint64_t max = atomic_load(&stat->max_ns); +@@ -458,7 +487,7 @@ mtl_new_library(mtl_compiler *compiler, const char *src, + desc.options = opts; + + NSError *error; +- uint64_t start = kk_now_ns(); ++ uint64_t start = kk_compile_begin(&kk_stat_library); + id lib = [comp newLibraryWithDescriptor:desc error:&error]; + kk_compile_record(&kk_stat_library, start); + +@@ -498,7 +527,7 @@ mtl_new_compute_pipeline_state(mtl_compiler *compiler, + desc.maxTotalThreadsPerThreadgroup = max_total_threads_per_threadgroup; + + NSError *error; +- uint64_t start = kk_now_ns(); ++ uint64_t start = kk_compile_begin(&kk_stat_compute); + pthread_rwlock_rdlock(&kk_archive.lock); + id pipeline = [comp newComputePipelineStateWithDescriptor:desc + compilerTaskOptions:kk_archive.task_options +@@ -625,7 +654,7 @@ mtl_new_render_pipeline(mtl_compiler *compiler, mtl_render_pass_descriptor *desc + MTL4RenderPipelineDescriptor *desc = (MTL4RenderPipelineDescriptor *)descriptor; + + NSError *error = nil; +- uint64_t start = kk_now_ns(); ++ uint64_t start = kk_compile_begin(&kk_stat_render); + pthread_rwlock_rdlock(&kk_archive.lock); + id pipeline = [comp newRenderPipelineStateWithDescriptor:desc + compilerTaskOptions:kk_archive.task_options +-- +2.56.0 + diff --git a/build/mesa-ios/patches/kosmickrisp-ios-0014-compile-speed-levers.patch b/build/mesa-ios/patches/kosmickrisp-ios-0014-compile-speed-levers.patch new file mode 100644 index 0000000000..e7baed94fd --- /dev/null +++ b/build/mesa-ios/patches/kosmickrisp-ios-0014-compile-speed-levers.patch @@ -0,0 +1,302 @@ +From e63a94bf6e1ae387a6bea74421c745968acab4dc Mon Sep 17 00:00:00 2001 +From: Shitiz Garg +Date: Tue, 10 Nov 2026 01:55:28 +1100 +Subject: [PATCH] kosmickrisp: compile-speed levers (QoS, parallel library + pairs, size optimisation) and diagnostics + +- MADEIRA_KK_COMPILE_QOS (default 1): raise a compiling thread below + user-initiated to user-interactive for the compile. +- MADEIRA_KK_PARALLEL_LIBS (default 1): a render pipeline's vertex and + fragment libraries compile at the same time (mtl_new_library_pair). +- MADEIRA_KK_OPT_SIZE (default 0): MTLLibraryOptimizationLevelSize. +- [kk-slow] logs the thread's QoS and the MSL size; [kk-frame] counts + feedback-handler calls and those without GPU times. + +Signed-off-by: Shitiz Garg +Co-Authored-By: Claude Opus 5.5 +--- + src/kosmickrisp/bridge/mtl_compiler.h | 7 ++ + src/kosmickrisp/bridge/mtl_compiler.m | 83 ++++++++++++++++++++- + src/kosmickrisp/bridge/stubs/mtl_compiler.c | 10 +++ + src/kosmickrisp/vulkan/kk_queue.c | 11 ++- + src/kosmickrisp/vulkan/kk_shader.c | 18 +++-- + 5 files changed, 117 insertions(+), 12 deletions(-) + +diff --git a/src/kosmickrisp/bridge/mtl_compiler.h b/src/kosmickrisp/bridge/mtl_compiler.h +index b0fa59f..7ae4825 100644 +--- a/src/kosmickrisp/bridge/mtl_compiler.h ++++ b/src/kosmickrisp/bridge/mtl_compiler.h +@@ -27,6 +27,13 @@ mtl_library * + mtl_new_library(mtl_compiler *compiler, const char *src, + enum mtl_math_mode math_mode, + enum mtl_math_floating_point_functions math_fp_fns); ++/* Madeira: both libraries of a render pipeline, compiled at the same time ++ * (MADEIRA_KK_PARALLEL_LIBS=0: one after the other). *out_b is NULL when a ++ * fails in the sequential mode. */ ++void mtl_new_library_pair(mtl_compiler *compiler, const char *src_a, const char *src_b, ++ enum mtl_math_mode math_mode, ++ enum mtl_math_floating_point_functions math_fp_fns, ++ mtl_library **out_a, mtl_library **out_b); + mtl_function_descriptor * + mtl_new_library_function_descriptor(mtl_library *library, + const char *entry_point); +diff --git a/src/kosmickrisp/bridge/mtl_compiler.m b/src/kosmickrisp/bridge/mtl_compiler.m +index 7617cec..1b90f9e 100644 +--- a/src/kosmickrisp/bridge/mtl_compiler.m ++++ b/src/kosmickrisp/bridge/mtl_compiler.m +@@ -65,6 +65,7 @@ struct kk_compile_stat { + _Atomic uint64_t slow; + }; + ++static _Thread_local size_t kk_compile_msl_bytes; /* MSL size of the library being built */ + static struct kk_compile_stat kk_stat_library = {.name = "library", .kind = 0}; + static struct kk_compile_stat kk_stat_render = {.name = "render", .kind = 1}; + static struct kk_compile_stat kk_stat_compute = {.name = "compute", .kind = 2}; +@@ -193,8 +194,8 @@ kk_compile_record(struct kk_compile_stat *stat, uint64_t start_ns) + else { + atomic_fetch_add(&stat->slow, 1); + if (kk_stats_enabled != 0) +- fprintf(stderr, "[kk-slow] %s %.1f ms (thread %p)\n", stat->name, elapsed / 1e6, +- (void *)pthread_self()); ++ fprintf(stderr, "[kk-slow] %s %.1f ms (thread %p, qos %d, msl %zu B)\n", stat->name, ++ elapsed / 1e6, (void *)pthread_self(), (int)qos_class_self(), kk_compile_msl_bytes); + } + kk_compile_report(false); + } +@@ -465,6 +466,46 @@ mtl_new_compiler(mtl_device *device) + } + + /* Library */ ++/* Madeira: compile-speed levers that keep KosmicKrisp's design (one library ++ * per stage, pipeline state baked in), each with a switch: ++ * - MADEIRA_KK_COMPILE_QOS (default 1): a thread compiling below user-initiated ++ * QoS is raised to user-interactive for the compile and set back after, so ++ * Metal's compiler service (which takes the requester's QoS) runs it on the ++ * performance cores. PoE2 creates pipelines on one loading thread whose QoS ++ * comes from MADEIRA_THREAD_QOS. ++ * - MADEIRA_KK_OPT_SIZE (default 0): MTLLibraryOptimizationLevelSize, which ++ * Apple documents as smaller binaries that "may also reduce compile time"; ++ * possibly slower shaders, so measure. ++ * - MADEIRA_KK_PARALLEL_LIBS (default 1): mtl_new_library_pair compiles a ++ * pipeline's vertex and fragment libraries at the same time. ++ * Slow builds now log the MSL size. */ ++static int ++kk_env_flag(const char *name, int fallback) ++{ ++ const char *v = getenv(name); ++ return v && v[0] ? v[0] != '0' : fallback; ++} ++ ++static qos_class_t ++kk_compile_qos_raise(void) ++{ ++ static int enabled = -1; ++ if (enabled < 0) ++ enabled = kk_env_flag("MADEIRA_KK_COMPILE_QOS", 1); ++ qos_class_t previous = qos_class_self(); ++ if (enabled && previous != QOS_CLASS_UNSPECIFIED && previous < QOS_CLASS_USER_INITIATED && ++ pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0) == 0) ++ return previous; ++ return QOS_CLASS_UNSPECIFIED; ++} ++ ++static void ++kk_compile_qos_restore(qos_class_t previous) ++{ ++ if (previous != QOS_CLASS_UNSPECIFIED) ++ pthread_set_qos_class_self_np(previous, 0); ++} ++ + mtl_library * + mtl_new_library(mtl_compiler *compiler, const char *src, + enum mtl_math_mode math_mode, +@@ -481,15 +522,24 @@ mtl_new_library(mtl_compiler *compiler, const char *src, + opts.languageVersion = MTLLanguageVersion3_2; + opts.mathMode = (MTLMathMode)math_mode; + opts.mathFloatingPointFunctions = (MTLMathFloatingPointFunctions)math_fp_fns; ++ static int opt_size = -1; ++ if (opt_size < 0) ++ opt_size = kk_env_flag("MADEIRA_KK_OPT_SIZE", 0); ++ if (opt_size) ++ opts.optimizationLevel = MTLLibraryOptimizationLevelSize; + + MTL4LibraryDescriptor *desc = [[MTL4LibraryDescriptor new] autorelease]; + desc.source = ns_src; + desc.options = opts; + + NSError *error; ++ qos_class_t qos = kk_compile_qos_raise(); ++ kk_compile_msl_bytes = strlen(src); + uint64_t start = kk_compile_begin(&kk_stat_library); + id lib = [comp newLibraryWithDescriptor:desc error:&error]; + kk_compile_record(&kk_stat_library, start); ++ kk_compile_msl_bytes = 0; ++ kk_compile_qos_restore(qos); + + if (lib == nil) { + fprintf(stderr, "Failed to create MTLLibrary: %s\n", [error.localizedDescription UTF8String]); +@@ -499,6 +549,31 @@ mtl_new_library(mtl_compiler *compiler, const char *src, + } + } + ++void ++mtl_new_library_pair(mtl_compiler *compiler, const char *src_a, const char *src_b, ++ enum mtl_math_mode math_mode, ++ enum mtl_math_floating_point_functions math_fp_fns, ++ mtl_library **out_a, mtl_library **out_b) ++{ ++ static int parallel = -1; ++ if (parallel < 0) ++ parallel = kk_env_flag("MADEIRA_KK_PARALLEL_LIBS", 1); ++ if (!parallel) { ++ *out_a = mtl_new_library(compiler, src_a, math_mode, math_fp_fns); ++ *out_b = *out_a ? mtl_new_library(compiler, src_b, math_mode, math_fp_fns) : NULL; ++ return; ++ } ++ __block mtl_library *b = NULL; ++ dispatch_group_t group = dispatch_group_create(); ++ dispatch_group_async(group, dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), ^{ ++ b = mtl_new_library(compiler, src_b, math_mode, math_fp_fns); ++ }); ++ *out_a = mtl_new_library(compiler, src_a, math_mode, math_fp_fns); ++ dispatch_group_wait(group, DISPATCH_TIME_FOREVER); ++ dispatch_release(group); ++ *out_b = b; ++} ++ + mtl_function_descriptor * + mtl_new_library_function_descriptor(mtl_library *library, const char *entry_point) + { +@@ -527,6 +602,7 @@ mtl_new_compute_pipeline_state(mtl_compiler *compiler, + desc.maxTotalThreadsPerThreadgroup = max_total_threads_per_threadgroup; + + NSError *error; ++ qos_class_t qos = kk_compile_qos_raise(); + uint64_t start = kk_compile_begin(&kk_stat_compute); + pthread_rwlock_rdlock(&kk_archive.lock); + id pipeline = [comp newComputePipelineStateWithDescriptor:desc +@@ -534,6 +610,7 @@ mtl_new_compute_pipeline_state(mtl_compiler *compiler, + error:&error]; + pthread_rwlock_unlock(&kk_archive.lock); + kk_compile_record(&kk_stat_compute, start); ++ kk_compile_qos_restore(qos); + if (pipeline != nil) + kk_archive_after_build(); + +@@ -654,6 +731,7 @@ mtl_new_render_pipeline(mtl_compiler *compiler, mtl_render_pass_descriptor *desc + MTL4RenderPipelineDescriptor *desc = (MTL4RenderPipelineDescriptor *)descriptor; + + NSError *error = nil; ++ qos_class_t qos = kk_compile_qos_raise(); + uint64_t start = kk_compile_begin(&kk_stat_render); + pthread_rwlock_rdlock(&kk_archive.lock); + id pipeline = [comp newRenderPipelineStateWithDescriptor:desc +@@ -661,6 +739,7 @@ mtl_new_render_pipeline(mtl_compiler *compiler, mtl_render_pass_descriptor *desc + error:&error]; + pthread_rwlock_unlock(&kk_archive.lock); + kk_compile_record(&kk_stat_render, start); ++ kk_compile_qos_restore(qos); + if (pipeline != nil) + kk_archive_after_build(); + +diff --git a/src/kosmickrisp/bridge/stubs/mtl_compiler.c b/src/kosmickrisp/bridge/stubs/mtl_compiler.c +index 86e6ffa..ad8c047 100644 +--- a/src/kosmickrisp/bridge/stubs/mtl_compiler.c ++++ b/src/kosmickrisp/bridge/stubs/mtl_compiler.c +@@ -29,6 +29,16 @@ mtl_new_library(mtl_compiler *compiler, const char *src, + return NULL; + } + ++void ++mtl_new_library_pair(mtl_compiler *compiler, const char *src_a, const char *src_b, ++ enum mtl_math_mode math_mode, ++ enum mtl_math_floating_point_functions math_fp_fns, ++ mtl_library **out_a, mtl_library **out_b) ++{ ++ *out_a = NULL; ++ *out_b = NULL; ++} ++ + mtl_function_descriptor * + mtl_new_library_function_descriptor(mtl_library *library, + const char *entry_point) +diff --git a/src/kosmickrisp/vulkan/kk_queue.c b/src/kosmickrisp/vulkan/kk_queue.c +index b8cd744..a6b9e52 100644 +--- a/src/kosmickrisp/vulkan/kk_queue.c ++++ b/src/kosmickrisp/vulkan/kk_queue.c +@@ -43,6 +43,8 @@ static struct { + _Atomic uint64_t gpu_ns; + _Atomic uint64_t gpu_commits; + _Atomic uint64_t gpu_max_ns; ++ _Atomic uint64_t feedbacks; /* Madeira: feedback handler calls */ ++ _Atomic uint64_t feedbacks_untimed; /* ... with no usable GPU start/end */ + uint64_t window_start_ns; + uint64_t last_present_ns; + uint64_t presents; +@@ -77,14 +79,16 @@ kk_frame_report(uint64_t now) + fprintf(stderr, + "[kk-frame] %.1f s: presents=%llu fps=%.1f interval avg=%.1fms max=%.1fms >33ms=%llu >50ms=%llu " + ">100ms=%llu | submit cpu %.2f ms/frame (%llu submits) | gpu %.2f ms/frame busy=%.0f%% " +- "commits=%llu max=%.1fms\n", ++ "commits=%llu max=%.1fms | feedback %llu (%llu untimed)\n", + window / 1e9, (unsigned long long)presents, window ? presents * 1e9 / window : 0.0, + presents ? kk_frames.interval_total_ns / 1e6 / presents : 0.0, + kk_frames.interval_max_ns / 1e6, (unsigned long long)kk_frames.over_33ms, + (unsigned long long)kk_frames.over_50ms, (unsigned long long)kk_frames.over_100ms, + presents ? kk_frames.submit_ns / 1e6 / presents : 0.0, + (unsigned long long)kk_frames.submits, presents ? gpu_ns / 1e6 / presents : 0.0, +- window ? 100.0 * gpu_ns / window : 0.0, (unsigned long long)commits, gpu_max / 1e6); ++ window ? 100.0 * gpu_ns / window : 0.0, (unsigned long long)commits, gpu_max / 1e6, ++ (unsigned long long)atomic_exchange(&kk_frames.feedbacks, 0), ++ (unsigned long long)atomic_exchange(&kk_frames.feedbacks_untimed, 0)); + kk_frames.window_start_ns = now; + kk_frames.presents = 0; + kk_frames.interval_total_ns = 0; +@@ -167,6 +171,9 @@ static void + commit_callback(struct mtl_feedback_data *data) + { + /* Madeira: GPU time per commit for [kk-frame]. */ ++ atomic_fetch_add(&kk_frames.feedbacks, 1); ++ if (!(data->gpu_end > data->gpu_start && data->gpu_start > 0.0)) ++ atomic_fetch_add(&kk_frames.feedbacks_untimed, 1); + if (data->gpu_end > data->gpu_start && data->gpu_start > 0.0) { + uint64_t gpu = (uint64_t)((data->gpu_end - data->gpu_start) * 1e9); + atomic_fetch_add(&kk_frames.gpu_ns, gpu); +diff --git a/src/kosmickrisp/vulkan/kk_shader.c b/src/kosmickrisp/vulkan/kk_shader.c +index c3583d7..9c207b2 100644 +--- a/src/kosmickrisp/vulkan/kk_shader.c ++++ b/src/kosmickrisp/vulkan/kk_shader.c +@@ -1224,20 +1224,22 @@ kk_compile_graphics_pipeline(struct kk_device *device, struct kk_shader *vs) + } + + const struct msl_compile_data *vs_data = &vs->msl_data[vs_stage]; +- mtl_library *vertex_library = mtl_new_library( +- device->mtl_compiler_handle, vs_data->code, MTL_MATH_MODE_FAST, +- MTL_MATH_FLOATING_POINT_FUNCTIONS_FAST); +- if (vertex_library == NULL) ++ const struct msl_compile_data *fs_data = &vs->msl_data[MESA_SHADER_FRAGMENT]; ++ /* Madeira: the two libraries compile at the same time (mtl_compiler.m). */ ++ mtl_library *vertex_library = NULL, *fragment_library = NULL; ++ mtl_new_library_pair(device->mtl_compiler_handle, vs_data->code, fs_data->code, ++ MTL_MATH_MODE_FAST, MTL_MATH_FLOATING_POINT_FUNCTIONS_FAST, ++ &vertex_library, &fragment_library); ++ if (vertex_library == NULL) { ++ if (fragment_library) ++ mtl_release(fragment_library); + return VK_ERROR_INVALID_SHADER_NV; ++ } + + mtl_function_descriptor *vertex_function = + mtl_new_library_function_descriptor(vertex_library, + vs_data->entrypoint_name); + +- const struct msl_compile_data *fs_data = &vs->msl_data[MESA_SHADER_FRAGMENT]; +- mtl_library *fragment_library = mtl_new_library( +- device->mtl_compiler_handle, fs_data->code, MTL_MATH_MODE_FAST, +- MTL_MATH_FLOATING_POINT_FUNCTIONS_FAST); + if (fragment_library == NULL) { + result = VK_ERROR_INVALID_SHADER_NV; + goto destroy_vertex; +-- +2.56.0 + diff --git a/build/mesa-ios/patches/kosmickrisp-ios-0015-giant-msl-hash-and-dump.patch b/build/mesa-ios/patches/kosmickrisp-ios-0015-giant-msl-hash-and-dump.patch new file mode 100644 index 0000000000..7a763e0891 --- /dev/null +++ b/build/mesa-ios/patches/kosmickrisp-ios-0015-giant-msl-hash-and-dump.patch @@ -0,0 +1,138 @@ +From d461eea048d9c990cc3a13021f7206ffba2b2f01 Mon Sep 17 00:00:00 2001 +From: Shitiz Garg +Date: Wed, 11 Nov 2026 02:45:42 +1100 +Subject: [PATCH] kosmickrisp: hash slow libraries, dump giant MSL; raise + compile QoS from user-initiated too + +PoE2's slowest libraries come from 0.5-1.5 MB of generated MSL (4-24 s +each on the Duo). [kk-slow] now logs a hash of the source, so a later +session can tell a recompile from a new shader, and sources of at least +MADEIRA_KK_DUMP_MSL_KB (default 250) are written once to +$MESA_SHADER_CACHE_DIR/msl-dump/.metal (at most 64). The compile +QoS raise now also lifts user-initiated threads, where PoE2's loader runs. + +Signed-off-by: Shitiz Garg +Co-Authored-By: Claude Opus 5.5 +--- + src/kosmickrisp/bridge/mtl_compiler.m | 66 +++++++++++++++++++++++++-- + 1 file changed, 61 insertions(+), 5 deletions(-) + +diff --git a/src/kosmickrisp/bridge/mtl_compiler.m b/src/kosmickrisp/bridge/mtl_compiler.m +index 1b90f9e..f020e33 100644 +--- a/src/kosmickrisp/bridge/mtl_compiler.m ++++ b/src/kosmickrisp/bridge/mtl_compiler.m +@@ -19,6 +19,7 @@ + + #include + #include ++#include + #include + #include + #include +@@ -150,6 +151,57 @@ kk_compile_report(bool force) + } + + ++/* Madeira: big generated shaders. PoE2's slowest libraries come from 0.5-1.5 MB ++ * of MSL (4-24 s each on the Duo, 10 Nov 2026). Every library of 150 ms or more ++ * logs a hash of its source, so a shader compiled again in a later session (a ++ * Metal library-cache miss) can be told from a new one, and sources of at least ++ * MADEIRA_KK_DUMP_MSL_KB (default 250; 0 = off) are written once to ++ * $MESA_SHADER_CACHE_DIR/msl-dump/.metal (at most 64 files). */ ++static _Thread_local uint64_t kk_compile_msl_hash; ++ ++static uint64_t ++kk_msl_hash(const char *src, size_t len) ++{ ++ uint64_t h = 1469598103934665603ull; ++ for (size_t i = 0; i < len; ++i) { ++ h ^= (unsigned char)src[i]; ++ h *= 1099511628211ull; ++ } ++ return h; ++} ++ ++static void ++kk_msl_dump(const char *src, size_t len, uint64_t hash) ++{ ++ static int limit_kb = -1; ++ static _Atomic int dumped; ++ if (limit_kb < 0) { ++ const char *v = getenv("MADEIRA_KK_DUMP_MSL_KB"); ++ limit_kb = v && v[0] ? atoi(v) : 250; ++ } ++ if (limit_kb <= 0 || len < (size_t)limit_kb * 1024 || atomic_load(&dumped) >= 64) ++ return; ++ const char *base = getenv("MESA_SHADER_CACHE_DIR"); ++ if (!base || !base[0]) ++ return; ++ char dir[1024], path[1100]; ++ snprintf(dir, sizeof dir, "%s/msl-dump", base); ++ mkdir(dir, 0755); ++ snprintf(path, sizeof path, "%s/%016llx.metal", dir, (unsigned long long)hash); ++ int fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0644); ++ if (fd < 0) ++ return; ++ size_t off = 0; ++ while (off < len) { ++ ssize_t w = write(fd, src + off, len - off); ++ if (w <= 0) ++ break; ++ off += (size_t)w; ++ } ++ close(fd); ++ atomic_fetch_add(&dumped, 1); ++} ++ + /* Madeira: every build is also reported to the app (madeira_vulkan_compile_mark in + * WiniosGL.m, found with dlsym like madeira_vulkan_present_mark), which keeps the + * counters its performance overlay and Shaders page show: builds in flight, and +@@ -194,8 +246,9 @@ kk_compile_record(struct kk_compile_stat *stat, uint64_t start_ns) + else { + atomic_fetch_add(&stat->slow, 1); + if (kk_stats_enabled != 0) +- fprintf(stderr, "[kk-slow] %s %.1f ms (thread %p, qos %d, msl %zu B)\n", stat->name, +- elapsed / 1e6, (void *)pthread_self(), (int)qos_class_self(), kk_compile_msl_bytes); ++ fprintf(stderr, "[kk-slow] %s %.1f ms (thread %p, qos %d, msl %zu B, hash %016llx)\n", ++ stat->name, elapsed / 1e6, (void *)pthread_self(), (int)qos_class_self(), ++ kk_compile_msl_bytes, (unsigned long long)kk_compile_msl_hash); + } + kk_compile_report(false); + } +@@ -468,8 +521,8 @@ mtl_new_compiler(mtl_device *device) + /* Library */ + /* Madeira: compile-speed levers that keep KosmicKrisp's design (one library + * per stage, pipeline state baked in), each with a switch: +- * - MADEIRA_KK_COMPILE_QOS (default 1): a thread compiling below user-initiated +- * QoS is raised to user-interactive for the compile and set back after, so ++ * - MADEIRA_KK_COMPILE_QOS (default 1): a thread compiling below user-interactive ++ * QoS (PoE2's loader runs at user-initiated) is raised to user-interactive for the compile and set back after, so + * Metal's compiler service (which takes the requester's QoS) runs it on the + * performance cores. PoE2 creates pipelines on one loading thread whose QoS + * comes from MADEIRA_THREAD_QOS. +@@ -493,7 +546,7 @@ kk_compile_qos_raise(void) + if (enabled < 0) + enabled = kk_env_flag("MADEIRA_KK_COMPILE_QOS", 1); + qos_class_t previous = qos_class_self(); +- if (enabled && previous != QOS_CLASS_UNSPECIFIED && previous < QOS_CLASS_USER_INITIATED && ++ if (enabled && previous != QOS_CLASS_UNSPECIFIED && previous < QOS_CLASS_USER_INTERACTIVE && + pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0) == 0) + return previous; + return QOS_CLASS_UNSPECIFIED; +@@ -535,10 +588,13 @@ mtl_new_library(mtl_compiler *compiler, const char *src, + NSError *error; + qos_class_t qos = kk_compile_qos_raise(); + kk_compile_msl_bytes = strlen(src); ++ kk_compile_msl_hash = kk_msl_hash(src, kk_compile_msl_bytes); + uint64_t start = kk_compile_begin(&kk_stat_library); + id lib = [comp newLibraryWithDescriptor:desc error:&error]; + kk_compile_record(&kk_stat_library, start); ++ kk_msl_dump(src, kk_compile_msl_bytes, kk_compile_msl_hash); + kk_compile_msl_bytes = 0; ++ kk_compile_msl_hash = 0; + kk_compile_qos_restore(qos); + + if (lib == nil) { +-- +2.56.0 + diff --git a/build/ntdll-unix/audio_null_ios.c b/build/ntdll-unix/audio_null_ios.c index 35c02fc375..d1a84d9e25 100644 --- a/build/ntdll-unix/audio_null_ios.c +++ b/build/ntdll-unix/audio_null_ios.c @@ -1948,6 +1948,29 @@ static NTSTATUS ios_get_loopback_capture_device(void *args) { return STATUS_SUCCESS; } +/* madeira-duo MADEIRA_AUDIO_MIX_RATE: the sample rate the shared-mode mix format + * reports (8000..96000 Hz; unset, 0 or out of range: 48000, as before). A sound engine + * that mixes at the device's rate then mixes that much less audio per second; one + * whose game fixed the rate converts at its output instead and gains nothing. FMOD + * documents 24 kHz as its own default on mobile "to reduce CPU cost" + * (System::setSoftwareFormat), and Path of Exile 2's FMOD mixer thread is 9.5% of + * the process's CPU in a map. The RemoteIO endpoint is created at the rate of its + * first client (ios_dev_create_locked), so iOS converts to the hardware rate; the + * ml1066 create_stream line gives the rate each client then opened. */ +static UINT32 ios_audio_mix_rate(void) { + static UINT32 rate; + if (!rate) { + const char *e = getenv( "MADEIRA_AUDIO_MIX_RATE" ); + long v = e ? atol( e ) : 0; + UINT32 r = (v >= 8000 && v <= 96000) ? (UINT32)v : IOS_AUDIO_SAMPLE_RATE; + if (r != IOS_AUDIO_SAMPLE_RATE) + fprintf(stderr, "[ios_audio] MADEIRA_AUDIO_MIX_RATE=%u: the mix format reports %u Hz (default %u)\n", + (unsigned)r, (unsigned)r, (unsigned)IOS_AUDIO_SAMPLE_RATE); + rate = r; + } + return rate; +} + static NTSTATUS ios_get_mix_format(void *args) { struct get_mix_format_params *p = args; LOG_FN_CALL(16, "get_mix_format"); @@ -1957,10 +1980,10 @@ static NTSTATUS ios_get_mix_format(void *args) { struct WAVEFORMATEX_stub *f = p->fmt; f->wFormatTag = 0xFFFE; /* WAVE_FORMAT_EXTENSIBLE */ f->nChannels = IOS_AUDIO_CHANNELS; - f->nSamplesPerSec = IOS_AUDIO_SAMPLE_RATE; + f->nSamplesPerSec = ios_audio_mix_rate(); /* madeira-duo MADEIRA_AUDIO_MIX_RATE; 48000 unless set */ f->wBitsPerSample = IOS_AUDIO_BITS; f->nBlockAlign = IOS_AUDIO_FRAME_BYTES; - f->nAvgBytesPerSec = IOS_AUDIO_SAMPLE_RATE * IOS_AUDIO_FRAME_BYTES; + f->nAvgBytesPerSec = f->nSamplesPerSec * IOS_AUDIO_FRAME_BYTES; f->cbSize = 22; /* extensible body */ /* Extensible body: Samples (2), ChannelMask (4), SubFormat (16). * KSDATAFORMAT_SUBTYPE_PCM = {00000001-0000-0010-8000-00AA00389B71} */ diff --git a/build/ntdll-unix/server_ios.c b/build/ntdll-unix/server_ios.c index dd92c34b4c..17097679fe 100644 --- a/build/ntdll-unix/server_ios.c +++ b/build/ntdll-unix/server_ios.c @@ -3007,11 +3007,23 @@ static void ios_xprobe_main( void ) { thread_act_array_t th = NULL; mach_msg_type_number_t nth = 0, k; uint64_t now; double dt_ms, sum_thr_ms = 0; int nrows = 0, i, j; + char ttl[1000], ttwall[16]; int ttn = 0, tt; /* madeira-duo thread table */ #define XP_MS(ticks) ((double)(ticks) * tb.numer / tb.denom / 1e6) usleep( 250000 ); now = mach_absolute_time(); dt_ms = XP_MS( now - t_prev ); gen++; + /* madeira-duo thread table, about every 30 s: one [xp-thr] entry for every thread with at + * least half a second of CPU so far -- Windows thread id, Mach thread id (the m of + * [xp-t]), name, scheduled / base priority, policy, and its CPU so far on P and E cores in + * ms. It names the threads [xp-t] and [srv-req] show by id only. */ + tt = (gen % 120) == 8; ttwall[0] = 0; + if (tt) + { + struct timeval ttv; struct tm ttm; + gettimeofday( &ttv, NULL ); localtime_r( &ttv.tv_sec, &ttm ); + snprintf( ttwall, sizeof(ttwall), "%02d:%02d:%02d.%03d", ttm.tm_hour, ttm.tm_min, ttm.tm_sec, (int)(ttv.tv_usec / 1000) ); + } if (used > 1400) { memset( ios_xp_tab, 0, sizeof(ios_xp_tab) ); used = 0; wine_log_write( "[xp] ml1128 thread table reset (gen %u)", gen ); } /* per-thread counters */ @@ -3031,6 +3043,23 @@ static void ios_xprobe_main( void ) struct ios_xp_tcd cur[2]; int nl = tc.len > 2 ? 2 : tc.len; memset( cur, 0, sizeof(cur) ); for (lv = 0; lv < nl; lv++) cur[lv] = tc.c[lv]; + if (tt) /* madeira-duo thread table */ + { + double tp = XP_MS( cur[0].ut + cur[0].st ), te = XP_MS( cur[1].ut + cur[1].st ); + thread_extended_info_data_t txi; mach_msg_type_number_t txc = THREAD_EXTENDED_INFO_COUNT; + if (tp + te >= 500.0 && thread_info( th[k], THREAD_EXTENDED_INFO, (thread_info_t)&txi, &txc ) == KERN_SUCCESS) + { + pthread_t tpt = pthread_from_mach_thread_np( th[k] ); + uint64_t tteb = tpt ? ios_ts_teb( tpt ) : 0; uint32_t tw = 0; + if (tteb) ios_ts_read( tteb + 0x48, &tw, 4 ); + txi.pth_name[sizeof(txi.pth_name) - 1] = 0; + if (ttn > (int)sizeof(ttl) - 160) { wine_log_write( "%s", ttl ); ttn = 0; } + if (!ttn) ttn = snprintf( ttl, sizeof(ttl), "[xp-thr] %s", ttwall ); + ttn += snprintf( ttl + ttn, sizeof(ttl) - ttn, " | %04x m%llu \"%s\" pri %d/%d pol %d P %.0f E %.0f", tw, + (unsigned long long)idi.thread_id, txi.pth_name, (int)txi.pth_curpri, (int)txi.pth_priority, + (int)txi.pth_policy, tp, te ); + } + } for (h = (int)(idi.thread_id * 2654435761u) & 2047, j = 0; j < 2048; j++, h = (h + 1) & 2047) if (!ios_xp_tab[h].tid || ios_xp_tab[h].tid == idi.thread_id) { pv = &ios_xp_tab[h]; break; } if (pv && pv->tid == idi.thread_id && pv->gen == gen - 1 && nrows < 1024) @@ -3079,6 +3108,7 @@ static void ios_xprobe_main( void ) } vm_deallocate( mach_task_self(), (vm_address_t)th, nth * sizeof(*th) ); } + if (ttn) wine_log_write( "%s", ttl ); /* madeira-duo thread table */ if (!(gen % 40)) ios_xp_fallback_pick(); /* ml1131c: every ~10 s */ /* process counters + PE counters */ @@ -3114,7 +3144,7 @@ static void ios_xprobe_main( void ) n = snprintf( line, sizeof(line), "[xp] %s +%.2f dt=%.0f cpu=%.0f (thr %.0f) P=%.0f E=%.0f run=%.0f pgw=%.1f GHz P=%.2f E=%.2f Minst=%.0f IPC=%.2f mJ=%.0f pin=%llu rdKB=%llu fpMB=%llu", wall, XP_MS( now - t_start ) / 1000.0, dt_ms, cpu, sum_thr_ms, pms, ems, - XP_MS( ru.ri_runnable_time - pru.ri_runnable_time ), page_wait_ms, + (double)(ru.ri_runnable_time - pru.ri_runnable_time) / 1e6, page_wait_ms, pms > 0 ? pcy / (pms * 1e6) : 0, ems > 0 ? (cy - pcy) / (ems * 1e6) : 0, ins / 1e6, cy > 0 ? ins / cy : 0, (double)(ru.ri_energy_nj - pru.ri_energy_nj) / 1e6, (unsigned long long)(ru.ri_pageins - pru.ri_pageins), (unsigned long long)((ru.ri_diskio_bytesread - pru.ri_diskio_bytesread) >> 10), @@ -3154,6 +3184,33 @@ static void ios_xprobe_main( void ) wine_log_write( "%s", line ); } if (!(gen & 3)) ios_xp_api_report( wall, XP_MS( now - t_start ) / 1000.0 ); /* ml1131: ~1 s */ + if (!(gen & 3)) + { /* madeira-duo [xp-vm], ~1 s: where the page-ins come from. The system's counters since the + * last line (decompressions = pages brought back from the memory compressor, pageins = + * pages read from files) and this process's resident memory by kind. */ + static vm_statistics64_data_t pvm; static int have_vm; static mach_port_t hport; + vm_statistics64_data_t vm; mach_msg_type_number_t vc = HOST_VM_INFO64_COUNT; + task_vm_info_data_t ti; mach_msg_type_number_t tic = TASK_VM_INFO_COUNT; + if (!hport) hport = mach_host_self(); + memset( &ti, 0, sizeof(ti) ); + task_info( mach_task_self(), TASK_VM_INFO, (task_info_t)&ti, &tic ); + if (host_statistics64( hport, HOST_VM_INFO64, (host_info64_t)&vm, &vc ) == KERN_SUCCESS) + { + unsigned long long pg = (unsigned long long)getpagesize(); + if (have_vm) + wine_log_write( "[xp-vm] %s system: decompressions %llu compressions %llu pageins %llu faults %llu cow %llu zero-fill %llu, " + "free %llu MB, compressor %llu MB | process: internal %llu MB, compressed %llu MB, external %llu MB, " + "footprint %llu MB", + wall, (unsigned long long)(vm.decompressions - pvm.decompressions), + (unsigned long long)(vm.compressions - pvm.compressions), (unsigned long long)(vm.pageins - pvm.pageins), + (unsigned long long)(vm.faults - pvm.faults), (unsigned long long)(vm.cow_faults - pvm.cow_faults), + (unsigned long long)(vm.zero_fill_count - pvm.zero_fill_count), + ((unsigned long long)vm.free_count * pg) >> 20, ((unsigned long long)vm.compressor_page_count * pg) >> 20, + (unsigned long long)(ti.internal >> 20), (unsigned long long)(ti.compressed >> 20), + (unsigned long long)(ti.external >> 20), (unsigned long long)(ti.phys_footprint >> 20) ); + pvm = vm; have_vm = 1; + } + } if (ios_power_probe_on) /* madeira-bcd power probe: every 5 s; ri_penergy_nj is the uint64 after ri_energy_nj in v6 */ ios_power_probe_tick( wall, ios_bg_now_ns(), dt_ms, (double)(ru.ri_energy_nj - pru.ri_energy_nj) / 1e6, (double)((&ru.ri_energy_nj)[1] - (&pru.ri_energy_nj)[1]) / 1e6, @@ -3649,6 +3706,286 @@ static void ios_stuck_store_check( void ) vm_deallocate( mach_task_self(), (vm_address_t)tl, tc * sizeof(*tl) ); } +/* madeira-duo [prof]: a CPU-time-weighted sampling profiler for every thread of + * the task, for finding where a game's CPU really goes (MADEIRA_PROF=1). + * + * Why not [cpu-split]: that one counts a sample whenever run_state says RUNNING, + * which includes threads that are only runnable (a thread in swtch_pri yielding + * the core looks as busy as one computing), and it keeps only the top 64 JIT + * buckets per burst, about a quarter of the samples. Here every pass reads each + * thread's CPU time first (THREAD_EXTENDED_INFO, no suspend) and samples only the + * threads whose CPU time moved; the sample's weight is the CPU time used since the + * thread's previous sample. Threads that stay idle are looked at every 50th pass. + * MADEIRA_PROF_HZ sets the pass rate (default 100, 20-1000); every busy thread costs + * a suspend, a state read and a resume per pass, so keep it low on a hot phone. + * + * Output, next to the stderr log (fcntl F_GETPATH on fd 2): + * madeira-prof-