From 1c4c8ae9dcd3b0116523e3637bb1b53addcec87b Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:34:15 +0300 Subject: [PATCH 001/134] [GPU] Recognize the Demon's Souls pattern copy shader as a bounded copy --- .../Gpu/Pipelines/BoundedFillDetector.cs | 17 ++++++++++++++++- .../Gpu/Pipelines/ShaderProgramCache.cs | 2 +- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/BoundedFillDetector.cs b/src/SharpEmu.Libs/Gpu/Pipelines/BoundedFillDetector.cs index 56811bda7..a1065d14a 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/BoundedFillDetector.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/BoundedFillDetector.cs @@ -44,8 +44,23 @@ public static class BoundedFillDetector "BufferLoadFormatX", "BufferStoreFormatX", "SEndpgm", ]; - public static BoundedCopy? DetectCopy(Gen5ShaderProgram program) + private const ulong DemonsSoulsPatternCopyShader = 0xEB7456322124ECC7UL; + private const uint PatternCopyGroupRegister = 12; + private const uint PatternCopyParameters = 8; + + public static BoundedCopy? DetectCopy(Gen5ShaderProgram program, ulong hash = 0) { + if (hash == DemonsSoulsPatternCopyShader) + { + static FillWord UserWord(uint register) => new(FillWordSource.UserData, register, 0, 0); + return new BoundedCopy( + PatternCopyGroupRegister, + new FillWord(FillWordSource.BufferResource, PatternCopyParameters, 0, 0), + new FillWord(FillWordSource.BufferResource, PatternCopyParameters, 0, sizeof(uint)), + [.. Enumerable.Range(0, 4).Select(word => UserWord((uint)word))], + [.. Enumerable.Range(4, 4).Select(word => UserWord((uint)word))]); + } + var instructions = ShaderOpcodePattern.Match(program.Instructions, ModuloCopyOpcodes, ignoreMarkers: true); if (instructions is null) { diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index 35195d889..09c433d29 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -1274,7 +1274,7 @@ private ProgramSourceEntry CreateEntry(ShaderSource source, StageCompileOptions HasShaderCalls = program.Instructions.Any(instruction => instruction.Opcode == "SSwappcB64"), ConstantFill = source.Stage == ShaderStage.Compute ? ConstantFillDetector.Detect(program) : null, BoundedFill = source.Stage == ShaderStage.Compute ? BoundedFillDetector.Detect(program) : null, - BoundedCopy = source.Stage == ShaderStage.Compute ? BoundedFillDetector.DetectCopy(program) : null, + BoundedCopy = source.Stage == ShaderStage.Compute ? BoundedFillDetector.DetectCopy(program, source.Hash) : null, StoresUniformValues = source.Stage == ShaderStage.Compute && GuardedStoreDetector.StoresOnlyUniformValues(program), EmbeddedFetch = fetch, VertexInputs = vertexInputs, From d3842f11efe0239a7f9aa304ca56724e388143e8 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:34:15 +0300 Subject: [PATCH 002/134] [GPU] Raise the host word copy limit to 16 MiB --- src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs index 323deccb4..e312e296a 100644 --- a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs +++ b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs @@ -766,7 +766,7 @@ private bool TryWriteFillToBacking(ulong guestAddress, ulong size, uint value) } } - public const ulong MaxHostCopyWords = 64 * 1024; + public const ulong MaxHostCopyWords = 4 * 1024 * 1024; public bool TryCopyWordsOnHost(ulong destination, ulong source, ulong sourceWords, ulong words) { From c3950131b876a48d8caf55470b78dd58d6815709 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:34:15 +0300 Subject: [PATCH 003/134] [Diagnostics] Name the writing program in target writer traces --- src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs index e312e296a..c2367f29e 100644 --- a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs +++ b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs @@ -416,6 +416,11 @@ public void PrepareBufferAllocations(ReadOnlySpan ranges) buffer.NoteGpuWrite(buffer.Offset(guestAddress), size); if (Diagnostics.DccWriterTrace.Enabled) { + if (traceShaderHash != 0) + { + Diagnostics.DccWriterTrace.CurrentProgram = traceShaderHash; + } + Diagnostics.DccWriterTrace.Record(RequireImageCache(), guestAddress, size); Diagnostics.DccWriterTrace.RecordWrite(guestAddress, size); } From 90d306cb116171cabecb59c87437d4bd0d65a25a Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:34:16 +0300 Subject: [PATCH 004/134] [GPU] Check image bytes exactly before a kernel store lands over GPU bytes --- src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs index c2367f29e..3305b641f 100644 --- a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs +++ b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs @@ -2629,7 +2629,7 @@ public bool TryWriteOverGpuBytes(ulong guestAddress, ReadOnlySpan data) } CompleteGuestPublications?.Invoke(guestAddress, size, PublicationAccess.Write); - if (RequireImageCache().MayHaveImageBytes(guestAddress, size)) + if (RequireImageCache().MayHaveImageBytes(guestAddress, size) && RequireImageCache().QueryRegion(guestAddress, size).ImageBytes) { return false; } From 052a5dc958cb55ceb5e5b7c2ed89070350e803c0 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:34:16 +0300 Subject: [PATCH 005/134] [GPU] Separate the kernel write stream check from posting --- .../VideoOut/KernelWritePolicy.cs | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/SharpEmu.Libs/VideoOut/KernelWritePolicy.cs b/src/SharpEmu.Libs/VideoOut/KernelWritePolicy.cs index 2768e1521..6f1c34d06 100644 --- a/src/SharpEmu.Libs/VideoOut/KernelWritePolicy.cs +++ b/src/SharpEmu.Libs/VideoOut/KernelWritePolicy.cs @@ -32,17 +32,19 @@ internal interface IKernelWriteStream // as well, so they need no download. internal static class KernelWritePolicy { + public static KernelWriteRefusal Check(IKernelWriteStream stream, ulong address, ulong size) => + !stream.OnStreamThread ? KernelWriteRefusal.Thread + : stream.InCrossQueueOrderWindow ? KernelWriteRefusal.CrossQueue + : stream.HasPendingPublication(address, size) ? KernelWriteRefusal.Publication + : stream.HasPendingRange(address, size) ? KernelWriteRefusal.PendingRange + : stream.HasPendingGpuWrite(address, size) ? KernelWriteRefusal.PendingWrite + : stream.HasImageBytes(address, size) ? KernelWriteRefusal.Image + : stream.HasSurfaceMetadata(address, size) ? KernelWriteRefusal.Metadata + : KernelWriteRefusal.None; + public static KernelWriteRefusal TryPost(IKernelWriteStream stream, ulong address, ReadOnlySpan words) { - var size = (ulong)words.Length * sizeof(uint); - var refusal = !stream.OnStreamThread ? KernelWriteRefusal.Thread - : stream.InCrossQueueOrderWindow ? KernelWriteRefusal.CrossQueue - : stream.HasPendingPublication(address, size) ? KernelWriteRefusal.Publication - : stream.HasPendingRange(address, size) ? KernelWriteRefusal.PendingRange - : stream.HasPendingGpuWrite(address, size) ? KernelWriteRefusal.PendingWrite - : stream.HasImageBytes(address, size) ? KernelWriteRefusal.Image - : stream.HasSurfaceMetadata(address, size) ? KernelWriteRefusal.Metadata - : KernelWriteRefusal.None; + var refusal = Check(stream, address, (ulong)words.Length * sizeof(uint)); if (refusal == KernelWriteRefusal.None) { stream.PostWrite(address, MemoryMarshal.AsBytes(words)); From b13a98086d08949b8d9103a509e0f7689529f145 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:34:17 +0300 Subject: [PATCH 006/134] [GPU] Post owned store data without copying it again --- .../VideoOut/VulkanVideoPresenter.CommandThread.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs index 1418af885..70bb2a4c0 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs @@ -235,9 +235,11 @@ public T Run(Func function, [CallerMemberName] string caller = "") internal const int ProducerRunWait = 4; private volatile int _producerState; - public void PostWrite(ulong address, ReadOnlySpan data, bool kernel = false) + public void PostWrite(ulong address, ReadOnlySpan data, bool kernel = false) => PostOwnedWrite(address, data.ToArray(), kernel); + + public void PostOwnedWrite(ulong address, byte[] data, bool kernel) { - var item = new Item { Kind = Kind.Write, Address = address, Data = data.ToArray(), Kernel = kernel }; + var item = new Item { Kind = Kind.Write, Address = address, Data = data, Kernel = kernel }; lock (_writeLock) { _pendingWrites.Enqueue(item); From 681e89d1004e8462a57f3ac26fd675da03fe3428 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:34:17 +0300 Subject: [PATCH 007/134] [GPU] Read the command queue depth from the environment --- .../VideoOut/VulkanVideoPresenter.CommandThread.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs index 70bb2a4c0..23d846589 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs @@ -22,7 +22,8 @@ private sealed class CommandThread : AgcExports.IDeferredWorkSink // The thread runs this far ahead of the render thread at most. Operand reads only drain the // queue when a queued write targets them, so the depth mostly costs memory; too shallow and the // two threads take turns waiting on each other (128 did, with draws resolving on the pool). - private const int MaxOutstanding = 1024; + private static readonly int MaxOutstanding = + int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_COMMAND_QUEUE_DEPTH"), out var depth) && depth >= 128 ? depth : 1024; private const int ShadowSweepCount = 64; private const int StorePageShift = 12; From a7ef0c0a6b42db3f617b0bb87068e6783d1ea8ed Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:34:17 +0300 Subject: [PATCH 008/134] [GPU] Index queued stores by page for overlay reads --- .../VulkanVideoPresenter.CommandThread.cs | 75 +++++++++++++++---- 1 file changed, 62 insertions(+), 13 deletions(-) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs index 23d846589..d2f9e944e 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs @@ -117,6 +117,8 @@ private sealed class Unit private readonly object _writeLock = new(); private readonly Queue _pendingWrites = new(); private readonly ConcurrentDictionary _pendingStorePages = new(); + private readonly Dictionary> _storesByPage = new(); + private readonly Stack> _spareStoreQueues = new(); private volatile int _pendingWriteCount; // The destinations of queued fills and copies; a read on this thread that overlaps one waits @@ -173,11 +175,39 @@ public bool HasPendingStores(ulong address, ulong size) return false; } - private void NotePendingStorePages(ulong address, int length, int delta) + private void NotePendingStorePages(Item item, int delta) { - var last = (address + (ulong)length - 1) >> StorePageShift; + var address = item.Address; + var last = (address + (ulong)item.Data!.Length - 1) >> StorePageShift; for (var page = address >> StorePageShift; page <= last; page++) { + if (delta > 0) + { + if (!_storesByPage.TryGetValue(page, out var queued)) + { + queued = _spareStoreQueues.Count != 0 ? _spareStoreQueues.Pop() : new Queue(); + _storesByPage.Add(page, queued); + } + + queued.Enqueue(item); + } + else if (_storesByPage.TryGetValue(page, out var queued)) + { + if (!ReferenceEquals(queued.Dequeue(), item)) + { + throw SubmissionScheduler.Fatal("The command stream store index ran out of order."); + } + + if (queued.Count == 0) + { + _storesByPage.Remove(page); + if (_spareStoreQueues.Count < 4096) + { + _spareStoreQueues.Push(queued); + } + } + } + if (_pendingStorePages.AddOrUpdate(page, delta, (_, count) => count + delta) == 0) { _pendingStorePages.TryRemove(new KeyValuePair(page, 0)); @@ -244,7 +274,7 @@ public void PostOwnedWrite(ulong address, byte[] data, bool kernel) lock (_writeLock) { _pendingWrites.Enqueue(item); - NotePendingStorePages(address, item.Data.Length, 1); + NotePendingStorePages(item, 1); _pendingWriteCount = _pendingWrites.Count; } @@ -488,22 +518,41 @@ public bool ReadOverlayBefore(ulong address, Span destination, long sequen private void ApplyPendingStoresLocked(ulong address, Span destination, long afterSequence, long beforeSequence = long.MaxValue) { var end = address + (ulong)destination.Length; - foreach (var write in _pendingWrites) + var page = address >> StorePageShift; + if (page == (end - 1) >> StorePageShift) { - var writeEnd = write.Address + (ulong)write.Data!.Length; - if (write.Sequence <= afterSequence || write.Address >= end || writeEnd <= address || - (beforeSequence != long.MaxValue && (write.Sequence == 0 || write.Sequence >= beforeSequence))) + if (_storesByPage.TryGetValue(page, out var queued)) { - continue; + foreach (var write in queued) + { + ApplyPendingStore(write, address, end, destination, afterSequence, beforeSequence); + } } - var start = Math.Max(address, write.Address); - var stop = Math.Min(end, writeEnd); - write.Data.AsSpan((int)(start - write.Address), (int)(stop - start)) - .CopyTo(destination[(int)(start - address)..]); + return; + } + + foreach (var write in _pendingWrites) + { + ApplyPendingStore(write, address, end, destination, afterSequence, beforeSequence); } } + private static void ApplyPendingStore(Item write, ulong address, ulong end, Span destination, long afterSequence, long beforeSequence) + { + var writeEnd = write.Address + (ulong)write.Data!.Length; + if (write.Sequence <= afterSequence || write.Address >= end || writeEnd <= address || + (beforeSequence != long.MaxValue && (write.Sequence == 0 || write.Sequence >= beforeSequence))) + { + return; + } + + var start = Math.Max(address, write.Address); + var stop = Math.Min(end, writeEnd); + write.Data.AsSpan((int)(start - write.Address), (int)(stop - start)) + .CopyTo(destination[(int)(start - address)..]); + } + private void Enqueue(Item item) { ThrowIfFailed(); @@ -1035,7 +1084,7 @@ private void ApplyWrite(Item item) } _pendingWrites.Dequeue(); - NotePendingStorePages(item.Address, item.Data!.Length, -1); + NotePendingStorePages(item, -1); _pendingWriteCount = _pendingWrites.Count; if (!written) { From e14d25cb2a6a11c904f1d49d0c71a9f5843b19bb Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:34:28 +0300 Subject: [PATCH 009/134] [Diagnostics] Count posted word copies and their refusals --- .../Gpu/Pipelines/IShaderPipelineHost.cs | 1 + .../ShaderPipelineCache.KernelEvaluation.cs | 38 ++++++++++++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs b/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs index 41d40c36f..5aab95a4d 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs @@ -38,6 +38,7 @@ internal enum KernelWriteRefusal PendingWrite, Image, Metadata, + Input, Count, } diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.KernelEvaluation.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.KernelEvaluation.cs index 5a337b1be..f9066f886 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.KernelEvaluation.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.KernelEvaluation.cs @@ -37,6 +37,10 @@ internal sealed partial class ShaderPipelineCache internal static readonly ThreadCounter KernelWritesToCpu = new(); internal static readonly ThreadCounter KernelWritesOverGpu = new(); internal static readonly ThreadCounter KernelWriteBytesOverGpu = new(); + private static readonly ThreadCounter _wordCopiesPosted = new(); + private static readonly ThreadCounter _wordCopyBytesPosted = new(); + private static readonly ThreadCounter[] _wordCopyRefusals = NewCounters((int)KernelWriteRefusal.Count); + private static readonly ThreadCounter[] _wordCopyInputs = NewCounters(6); private static readonly ThreadCounter[] _kernelMemoLookups = NewCounters(4); private static long _kernelMemoBytes; private static readonly ConditionalWeakTable _kernelDemands = new(); @@ -67,7 +71,39 @@ public static string TakeCpuKernelReport() FormattableString.Invariant($" ineligible={_kernelsIneligible.Take()} lane_ops={_kernelLaneOperations.Take()} ") + FormattableString.Invariant($"probe_runs={_kernelProbeRuns.Take()} eval_ms={milliseconds:F2}") + FormattableString.Invariant($" demand=read:{_kernelPredictionsRead.Take()},muted:{_kernelProgramsMuted.Take()},") + - FormattableString.Invariant($"unmuted:{_kernelProgramsUnmuted.Take()},muted_skips:{_kernelMutedSkips.Take()},rechecks:{_kernelMutedRechecks.Take()}"); + FormattableString.Invariant($"unmuted:{_kernelProgramsUnmuted.Take()},muted_skips:{_kernelMutedSkips.Take()},rechecks:{_kernelMutedRechecks.Take()}") + + FormattableString.Invariant($" word_copies=posted:{_wordCopiesPosted.Take()},bytes:{_wordCopyBytesPosted.Take()},refused:") + TakeRefusals(_wordCopyRefusals) + + FormattableString.Invariant($" input=publication:{_wordCopyInputs[0].Take()},unmapped:{_wordCopyInputs[1].Take()},range:{_wordCopyInputs[2].Take()},") + + FormattableString.Invariant($"pending:{_wordCopyInputs[3].Take()},gpu_dirty:{_wordCopyInputs[4].Take()},other:{_wordCopyInputs[5].Take()}"); + } + + internal static void NoteWordCopyInput(int reason) => _wordCopyInputs[reason].Increment(); + + internal static void NoteWordCopy(KernelWriteRefusal refusal, ulong bytes) + { + if (refusal != KernelWriteRefusal.None) + { + _wordCopyRefusals[(int)refusal].Increment(); + return; + } + + _wordCopiesPosted.Increment(); + _wordCopyBytesPosted.Add((long)bytes); + } + + private static string TakeRefusals(ThreadCounter[] counters) + { + var reasons = new List(); + for (var index = 1; index < counters.Length; index++) + { + var count = counters[index].Take(); + if (count != 0) + { + reasons.Add(FormattableString.Invariant($"{(KernelWriteRefusal)index}:{count}")); + } + } + + return reasons.Count == 0 ? "none" : string.Join(",", reasons); } private static string TakeConsumeRefusals() From 61e9ec8f31f7fe9437848b716105051903757172 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:34:28 +0300 Subject: [PATCH 010/134] [GPU] Post a bounded word copy as a store at its stream position --- .../Gpu/Rendering/IRenderHost.cs | 2 + .../VulkanVideoPresenter.KernelWrites.cs | 62 +++++++++++++++++++ .../VulkanVideoPresenter.Rendering.cs | 3 + 3 files changed, 67 insertions(+) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs b/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs index 715fe3a99..3a593d7a8 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs @@ -270,5 +270,7 @@ void NoteKnownGpuContents(ulong address, ReadOnlySpan words) bool TryCopyWordsOnHost(ulong destination, ulong source, ulong sourceWords, ulong words); + bool TryPostWordCopy(ulong destination, ulong source, ulong sourceWords, ulong words) => false; + Exception Fatal(string message); } diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.KernelWrites.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.KernelWrites.cs index 7d1e62f1e..3602b4ca4 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.KernelWrites.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.KernelWrites.cs @@ -27,6 +27,68 @@ private sealed partial class Presenter : IKernelWriteStream void IKernelWriteStream.PostWrite(ulong address, ReadOnlySpan data) => _commandThread!.PostWrite(address, data, kernel: true); + public bool TryPostWordCopy(ulong destination, ulong source, ulong sourceWords, ulong words) + { + var refusal = PostWordCopy(destination, source, sourceWords, words); + ShaderPipelineCache.NoteWordCopy(refusal, words * sizeof(uint)); + return refusal == KernelWriteRefusal.None; + } + + private KernelWriteRefusal PostWordCopy(ulong destination, ulong source, ulong sourceWords, ulong words) + { + if (destination == 0 || source == 0 || sourceWords == 0 || words == 0 || ((destination | source) & 3) != 0 || + words > Gpu.Buffers.GuestBufferCache.MaxHostCopyWords || sourceWords > Gpu.Buffers.GuestBufferCache.MaxHostCopyWords) + { + return KernelWriteRefusal.Unsupported; + } + + var size = words * sizeof(uint); + var sourceSize = Math.Min(sourceWords, words) * sizeof(uint); + if (size > ulong.MaxValue - destination || sourceSize > ulong.MaxValue - source || + (source < destination + size && destination < source + sourceSize)) + { + return KernelWriteRefusal.Unsupported; + } + + var refusal = KernelWritePolicy.Check(this, destination, size); + if (refusal == KernelWriteRefusal.Image && !_imageCache.QueryRegion(destination, size).ImageBytes) + { + refusal = _imageCache.MayOverlapMetadata(destination, size) ? KernelWriteRefusal.Metadata : KernelWriteRefusal.None; + } + + if (refusal != KernelWriteRefusal.None) + { + return refusal; + } + + var data = GC.AllocateUninitializedArray((int)size); + if (!TryPeekResidentGuestBytes(source, data.AsSpan(0, (int)sourceSize))) + { + if (RenderPhaseProfile.Enabled) + { + ShaderPipelineCache.NoteWordCopyInput( + HasPendingMemoryPublication(source, sourceSize) ? 0 + : !_guestMemory.CanRead(source, sourceSize) ? 1 + : _commandThread!.HasPendingRange(source, sourceSize) ? 2 + : IsPendingOnCommandThread(source, sourceSize) ? 3 + : _bufferCache.HasGpuDirtyBytes(source, sourceSize) ? 4 + : 5); + } + + return KernelWriteRefusal.Input; + } + + for (var filled = (int)sourceSize; filled < data.Length;) + { + var count = Math.Min(filled, data.Length - filled); + data.AsSpan(0, count).CopyTo(data.AsSpan(filled)); + filled += count; + } + + _commandThread!.PostOwnedWrite(destination, data, kernel: true); + return KernelWriteRefusal.None; + } + // On the render thread at the store's stream position: a store into GPU-dirty pages lands on both copies. internal bool TryApplyKernelWriteOverGpuBytes(ulong address, byte[] data) { diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs index ee0c54d1d..f6fbd599c 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs @@ -1864,5 +1864,8 @@ public bool TryCopyWordsOnHost(ulong destination, ulong source, ulong sourceWord return _bufferCache.TryCopyWordsOnHost(destination, source, sourceWords, words); } + + public bool TryPostWordCopy(ulong destination, ulong source, ulong sourceWords, ulong words) => + !_worker && _presenter.TryPostWordCopy(destination, source, sourceWords, words); } } From 5d4937c46a8312dc407c0eb66ebf994a8df2cdcf Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:34:29 +0300 Subject: [PATCH 011/134] [GPU] Consume bounded copy dispatches on the stream thread --- .../Gpu/Rendering/RenderExecutor.Compute.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Compute.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Compute.cs index f13ba3327..1ffa134c7 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Compute.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Compute.cs @@ -123,6 +123,17 @@ public void Dispatch(ulong submitId, RegisterBanks banks, uint groupsX, uint gro record.BoundedFill = DecodeBoundedFill(input, groupsX, groupsY, groupsZ, dispatchInitiator); record.BoundedCopy = DecodeBoundedCopy(input, groupsX, groupsY, groupsZ, dispatchInitiator); record.ImageClear = TryDecodeImageClear(input, groupsX, groupsY, groupsZ, dispatchInitiator); + if (record.BoundedCopy is { } wordCopy && PostedWordCopyEnabled && + _host.TryPostWordCopy(wordCopy.Destination, wordCopy.Source, wordCopy.Modulus, wordCopy.Words)) + { + record.MetadataClear = null; + record.ConstantFill = null; + record.BoundedFill = null; + record.BoundedCopy = null; + record.ImageClear = null; + Record(record); + return; + } } if (useThreadDimensions) @@ -570,6 +581,8 @@ private MetadataBufferProbe[] DecodeMetadataClear(ComputeInputInfo input) private static readonly bool BoundedCopyEnabled = Environment.GetEnvironmentVariable("SHARPEMU_HOST_BOUNDED_COPY") != "0"; + private static readonly bool PostedWordCopyEnabled = Environment.GetEnvironmentVariable("SHARPEMU_POSTED_WORD_COPY") != "0"; + private static bool IsPlainWordBuffer(BufferDescriptorWords descriptor) => descriptor.Stride == sizeof(uint) && !descriptor.SwizzleEnabled && !descriptor.AddThreadId && descriptor.OutOfBounds == 0 && descriptor.Type == 0 && (descriptor.Address & 3) == 0 && descriptor.Format is Format32UInt or Format32SInt or Format32Float; From 12e2f9b31632cb3c08f7ef9e7b0e74b5c7161f4a Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:34:29 +0300 Subject: [PATCH 012/134] [GPU] Report the kind of a pending write between two stream positions --- .../Gpu/Rendering/PendingGpuWrites.cs | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/PendingGpuWrites.cs b/src/SharpEmu.Libs/Gpu/Rendering/PendingGpuWrites.cs index 7d88e29af..da20bc7d6 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/PendingGpuWrites.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/PendingGpuWrites.cs @@ -450,6 +450,29 @@ public bool HasPendingBetween(ulong address, ulong size, long afterSequence, lon } } + public PendingWriteKind? KindBetween(ulong address, ulong size, long afterSequence, long beforeSequence) + { + _gate.EnterReadLock(); + try + { + foreach (var entry in _entries.Values) + { + if (Volatile.Read(ref entry.Sequence) > afterSequence && Volatile.Read(ref entry.Oldest) < beforeSequence && + entry.Address < address + size && address < entry.Address + entry.Size && + entry.HasBetween(afterSequence, beforeSequence)) + { + return entry.Kind; + } + } + + return null; + } + finally + { + _gate.ExitReadLock(); + } + } + public bool TryGetPending(ulong address, ulong size, out long sequence) { sequence = 0; From e2337a5b99db9afb599900432a1924945e45d593 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:34:29 +0300 Subject: [PATCH 013/134] [Diagnostics] Name the pending write kind that sends a draw to the stream thread --- .../VulkanVideoPresenter.CommandStream.cs | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandStream.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandStream.cs index 5633558e9..9faba4241 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandStream.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandStream.cs @@ -334,7 +334,7 @@ private bool ReadOnResolveWorker(ulong address, Span destination) if (IsPendingForWorker(address, size)) { - throw new SerialResolveRequiredException("pending write read"); + throw new SerialResolveRequiredException(PendingReadReason(address, size, worker.Sequence)); } if (!_commandThread!.ReadOverlayBefore(address, destination, worker.Sequence)) @@ -371,6 +371,24 @@ private bool TryReadShadowForWorker(ulong address, Span destination) return true; } + private static readonly string[] PendingReadReasons = + [.. Enum.GetNames().Select(static name => "pending write read " + name.ToLowerInvariant())]; + + private string PendingReadReason(ulong address, ulong size, long sequence) + { + if (!RenderPhaseProfile.Enabled) + { + return "pending write read"; + } + + if (_translation.PendingWrites is { } pending && pending.KindBetween(address, size, pending.Released, sequence) is { } kind) + { + return PendingReadReasons[(int)kind]; + } + + return "pending write read shadow"; + } + private bool IsGpuOwnedForWorkerRead(ulong address, ulong size) => _bufferCache.HasGpuDirtyBytes(address, size); private bool IsGpuOwnedForWorkerCleanRead(ulong address, ulong size) => From 7cf0ac5687a735c5c841de123e89a2924c941a0e Mon Sep 17 00:00:00 2001 From: Usif <19160089+Im-Usif@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:58:12 +0300 Subject: [PATCH 014/134] [GPU/HLE] Wolverine: shader calls, bindless heap, translator and pipeline prewarm fixes (#1144) --- docs/sharpemu-gui-undocumented-env-vars.md | 4 +- src/SharpEmu.CLI/Program.cs | 3 + .../DirectExecutionBackend.Exceptions.cs | 10 +- .../Native/DirectExecutionBackend.Imports.cs | 21 +- .../Memory/PhysicalVirtualMemory.cs | 90 +- src/SharpEmu.Core/Runtime/SharpEmuRuntime.cs | 38 + src/SharpEmu.GnmMode/Gpu/GnmCommandPackets.cs | 2 + .../Shaders/GcnImageDescriptor.cs | 1 + src/SharpEmu.HLE/GpuMemory/AvlSpanSet.cs | 107 +- src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs | 113 ++ .../GpuMemory/GuestGpuMemoryHook.cs | 9 + .../GpuMemory/GuestPageTracker.cs | 14 +- .../GpuMemory/GuestWriteReservations.cs | 640 ++++++++++++ src/SharpEmu.HLE/GpuMemory/PageGuard.cs | 2 + src/SharpEmu.HLE/GpuMemory/SpanSet.cs | 62 +- src/SharpEmu.HLE/HostCallTrims.cs | 28 + .../Agc/AgcExports.CommandPackets.cs | 32 +- .../Agc/AgcExports.DrawPackets.cs | 74 +- .../Agc/AgcExports.SubmittedGeometry.cs | 70 ++ src/SharpEmu.Libs/Agc/AgcExports.cs | 109 ++ src/SharpEmu.Libs/Agc/AgcPacketWrites.cs | 27 + src/SharpEmu.Libs/Ampr/AmprExports.Amm.cs | 451 ++++++++ src/SharpEmu.Libs/Ampr/AmprExports.Queues.cs | 148 +++ src/SharpEmu.Libs/Ampr/AmprExports.cs | 173 +++- src/SharpEmu.Libs/Gpu/Buffers/GpuBuffer.cs | 6 + .../Gpu/Buffers/GpuDeviceInfo.cs | 9 + .../Buffers/GuestBufferCache.ObtainMemo.cs | 140 +++ .../Gpu/Buffers/GuestBufferCache.cs | 172 ++- .../Gpu/Buffers/GuestBufferUploader.cs | 159 ++- .../Gpu/GpuCommands/CommandStreamQueue.cs | 97 +- .../Gpu/GpuCommands/CommandSubmission.cs | 6 + .../Gpu/GpuCommands/EndOfPipeLandings.cs | 148 +++ .../GpuCommandInterpreter.Draws.cs | 125 ++- .../GpuCommandInterpreter.Labels.cs | 9 + .../GpuCommandInterpreter.Memory.cs | 9 + .../GpuCommandInterpreter.Waits.cs | 80 ++ .../Gpu/GpuCommands/GpuCommandInterpreter.cs | 36 + .../Gpu/GpuCommands/ICommandStreamHost.cs | 26 +- .../GpuCommands/Registers/RegisterBanks.cs | 4 + src/SharpEmu.Libs/Gpu/IGuestGpuBackend.cs | 3 + src/SharpEmu.Libs/Gpu/Images/CachedImage.cs | 74 +- .../Gpu/Images/GuestImageCache.Collection.cs | 22 +- .../Gpu/Images/GuestImageCache.Lookup.cs | 2 +- .../Gpu/Images/GuestImageCache.Overlap.cs | 60 ++ .../Gpu/Images/GuestImageCache.Tracking.cs | 53 +- .../Gpu/Images/GuestImageCache.Transfers.cs | 15 +- .../Gpu/Images/GuestImageCache.cs | 23 +- .../Gpu/Images/HostLayoutTargets.cs | 17 + .../Images/ImageRequestBuilders.Texture.cs | 13 +- .../Gpu/Images/ViewFormatRules.cs | 21 +- .../Pipelines/ComputeStageInputResolver.cs | 4 +- .../Gpu/Pipelines/DescriptorHeap.cs | 49 +- .../Gpu/Pipelines/IShaderPipelineHost.cs | 52 + .../Gpu/Pipelines/LinkedShaderPrewarm.cs | 148 +++ .../Gpu/Pipelines/MeshDrawPlanner.cs | 30 +- .../Pipelines/ShaderCallLibrary.TableScan.cs | 310 ++++++ .../Gpu/Pipelines/ShaderCallLibrary.cs | 491 +++++++-- .../Gpu/Pipelines/ShaderCallLibraryMemo.cs | 355 +++++++ .../Gpu/Pipelines/ShaderCallUnionStore.cs | 14 + .../Gpu/Pipelines/ShaderCalleeTiers.cs | 60 +- .../Gpu/Pipelines/ShaderDescriptorLimits.cs | 28 + .../Gpu/Pipelines/ShaderFunctionReader.cs | 5 +- .../Gpu/Pipelines/ShaderPermutationDump.cs | 2 +- .../Gpu/Pipelines/ShaderPipelineCache.cs | 196 +++- .../Gpu/Pipelines/ShaderPrewarmList.Vertex.cs | 444 ++++++++ .../Gpu/Pipelines/ShaderPrewarmList.cs | 877 +++++++++++++--- .../ShaderProgramCache.CallDispatch.cs | 24 + .../Gpu/Pipelines/ShaderProgramCache.cs | 945 +++++++++++++---- .../Gpu/Pipelines/SliceDescriptorHeap.cs | 163 +++ .../Gpu/Pipelines/StageStaticKey.cs | 13 + .../Gpu/Pipelines/TranslationDiskCache.cs | 444 ++++++++ .../Gpu/Rendering/DispatchChain.cs | 9 + .../Gpu/Rendering/DispatchThreadsPipeline.cs | 233 +++++ .../Gpu/Rendering/IRenderHost.cs | 43 + .../Gpu/Rendering/IShaderPipelineProvider.cs | 25 + .../Gpu/Rendering/IndirectMeshDraw.cs | 9 + .../Gpu/Rendering/MeshIndirectPipeline.cs | 32 +- .../Gpu/Rendering/MeshTaskLaunch.cs | 26 + .../Rendering/RenderExecutor.Adaptations.cs | 11 +- .../Gpu/Rendering/RenderExecutor.Compute.cs | 131 ++- .../Rendering/RenderExecutor.DynamicState.cs | 2 + .../Rendering/RenderExecutor.PendingWrites.cs | 9 + .../Gpu/Rendering/RenderExecutor.cs | 57 +- .../Gpu/Rendering/RenderRecorder.Compute.cs | 39 +- .../Rendering/RenderRecorder.Tessellation.cs | 7 +- .../Gpu/Rendering/RenderRecorder.cs | 61 +- .../Gpu/Rendering/ResolvedCommands.cs | 3 + .../Gpu/Rendering/ShaderStageResources.cs | 26 +- .../Scheduling/PendingGuestPublications.cs | 87 +- .../Gpu/Scheduling/SubmissionScheduler.cs | 4 + .../Gpu/Scheduling/SubmitBundle.cs | 7 + .../Gpu/Vulkan/DeviceFaultReport.cs | 186 ++++ .../Gpu/Vulkan/VulkanGuestGpuBackend.cs | 3 + .../Kernel/KernelAprCompatExports.cs | 48 +- .../Kernel/KernelMemoryCompatExports.cs | 12 +- .../Kernel/KernelModuleRegistry.cs | 37 + .../Kernel/KernelPthreadState.cs | 2 + .../Kernel/KernelRuntimeCompatExports.cs | 2 + .../Network/HttpExports.Requests.cs | 197 ++++ src/SharpEmu.Libs/Network/HttpExports.cs | 1 + .../Np/NpEntitlementAccessExports.cs | 91 ++ src/SharpEmu.Libs/Pad/PadExports.cs | 27 + src/SharpEmu.Libs/PlayGo/PlayGoExports.cs | 46 + src/SharpEmu.Libs/SaveData/SaveDataExports.cs | 47 + .../VideoOut/DriverShaderCacheFolder.cs | 51 + .../VideoOut/HostVideoOptions.cs | 2 + .../VideoOut/LinkedCompileAdmission.cs | 61 ++ .../VideoOut/PipelineBinaryStorePolicy.cs | 27 + .../VideoOut/PipelineBuildGate.cs | 69 ++ src/SharpEmu.Libs/VideoOut/PrewarmPool.cs | 155 +++ .../VideoOut/ShaderPrewarmQueue.cs | 182 ++++ src/SharpEmu.Libs/VideoOut/VideoOutExports.cs | 18 + .../VulkanVideoPresenter.BindingShadow.cs | 48 +- .../VulkanVideoPresenter.BindlessHeap.cs | 430 +++++++- .../VulkanVideoPresenter.CallRecordSpans.cs | 377 +++++++ .../VulkanVideoPresenter.CallRecords.cs | 57 +- .../VulkanVideoPresenter.CommandStream.cs | 8 + .../VulkanVideoPresenter.DeferredSignals.cs | 11 +- .../VulkanVideoPresenter.Descriptors.cs | 300 ++++-- .../VulkanVideoPresenter.Device.Setup.cs | 220 +++- .../VulkanVideoPresenter.Device.Teardown.cs | 7 + .../VulkanVideoPresenter.DispatchThreads.cs | 163 +++ .../VulkanVideoPresenter.GraphicsPrewarm.cs | 343 ++++++ .../VulkanVideoPresenter.LodStatistics.cs | 6 + .../VulkanVideoPresenter.MeshIndirect.cs | 147 ++- .../VulkanVideoPresenter.PipelineBinaries.cs | 543 ++++++++++ .../VulkanVideoPresenter.PipelineLibraries.cs | 924 +++++++++++++++++ .../VulkanVideoPresenter.Pipelines.cs | 561 ++++++++-- .../VulkanVideoPresenter.RecordingHost.cs | 1 + .../VulkanVideoPresenter.RenderLoop.cs | 3 +- .../VulkanVideoPresenter.Rendering.cs | 100 +- .../VulkanVideoPresenter.Scheduler.cs | 7 +- .../VulkanVideoPresenter.ShaderPrewarm.cs | 495 +++++++-- .../VideoOut/VulkanVideoPresenter.Slices.cs | 26 + .../VideoOut/VulkanVideoPresenter.cs | 37 + src/SharpEmu.Logging/HostSystemInfo.cs | 19 + .../Gen5SpirvTranslator.Alu.cs | 474 +++++++-- .../Gen5SpirvTranslator.DeferredGuards.cs | 73 ++ .../Gen5SpirvTranslator.DeviceLoadFunction.cs | 125 +++ .../Gen5SpirvTranslator.HalfWave64Lowering.cs | 8 +- .../Gen5SpirvTranslator.Mesh.cs | 46 +- ...en5SpirvTranslator.NativeWave32Lowering.cs | 8 +- ...en5SpirvTranslator.NativeWave64Lowering.cs | 10 +- .../Gen5SpirvTranslator.RayIntersect.cs | 31 +- .../Gen5SpirvTranslator.Resources.cs | 276 ++++- .../Gen5SpirvTranslator.SharedCalls.cs | 3 + .../Gen5SpirvTranslator.Tessellation.cs | 5 +- .../Gen5SpirvTranslator.WaveReductions.cs | 361 +++++++ .../Gen5SpirvTranslator.cs | 744 +++++++++++-- .../SpirvDispatchThreads.cs | 106 ++ .../SpirvMeshIndirect.cs | 16 +- .../SpirvMeshTask.cs | 157 +++ .../SpirvModuleBuilder.Simplify.cs | 387 ++++++- .../SpirvModuleBuilder.cs | 45 +- .../Gen5ShaderCallLinker.cs | 41 +- .../Gen5ShaderTranslator.cs | 17 +- .../Gen5TessellationData.cs | 2 +- .../Resources/BindingLayout.cs | 55 +- .../Resources/BindlessHeap.cs | 57 +- .../Resources/CallRecordPlanner.cs | 26 +- .../Resources/CompiledBranchTransaction.cs | 407 ++++++++ .../Resources/CompiledDeviceAddressRanges.cs | 980 ++++++++++++++++++ .../Resources/CompiledResourceTransaction.cs | 6 +- .../Resources/DeviceAddressRangePlanner.cs | 68 +- .../Resources/DeviceCountProofWorker.cs | 30 + .../Resources/DeviceRecordCountPlan.cs | 222 ++++ .../Resources/DispatchBufferFootprint.Word.cs | 72 ++ .../Resources/DispatchBufferFootprint.cs | 389 +++++++ .../Resources/MaterializationProgram.cs | 7 +- .../Resources/ResourceBranchBlock.cs | 31 +- .../Resources/ResourceBranchWriteGuard.cs | 73 ++ .../Resources/ResourceMaterializationCache.cs | 13 + .../ResourceMaterializationProfile.cs | 2 +- ...esourceMaterializer.SpecializationGuard.cs | 16 +- .../Resources/ResourceMaterializer.cs | 125 ++- .../Resources/ResourceRuntimeInputs.cs | 18 +- .../Resources/ResourceSnapshot.cs | 3 + .../Resources/ResourceSpecialization.cs | 11 +- .../Resources/ResourceTableReadPlanner.cs | 70 +- .../Resources/ResourceTracker.DirectImages.cs | 27 +- .../Resources/ResourceTracker.cs | 290 +++++- .../Resources/RuntimeEvaluationScratch.cs | 12 + .../Resources/RuntimeImageSwizzle.cs | 150 +++ .../Resources/RuntimeValueEvaluator.cs | 85 +- .../Resources/RuntimeValueValidator.cs | 27 +- .../Resources/ScalarDataReadPolicy.cs | 13 + .../Resources/ScalarGraphDiskCache.cs | 102 +- .../Resources/ScalarValueGraph.Builder.cs | 12 +- .../Resources/ShaderResourceInfo.cs | 12 +- .../ShaderResourcePlan.CompiledRanges.cs | 22 + .../Resources/ShaderResourcePlan.cs | 62 +- .../Resources/StableImageDescriptorLimits.cs | 40 + .../ShaderCompileRequest.cs | 52 +- .../Agc/AgcDrawIndex2Tests.cs | 83 +- .../Agc/AgcPacketWritesTests.cs | 374 +++++++ .../Agc/Gen5ShaderAtomicDecodeTests.cs | 15 + .../Agc/Gen5StorageImageSwizzleCacheTests.cs | 22 +- .../Ampr/AmprCommandQueueTests.cs | 168 +++ .../Buffers/GuestBufferAsyncReadbackTests.cs | 30 +- .../GuestBufferBdaRegistrationTests.cs | 62 ++ .../Gpu/Buffers/GuestBufferCacheTests.cs | 37 + .../GuestBufferManagedCopyReadbackTests.cs | 148 +++ .../GuestBufferManagedWriteAdmissionTests.cs | 144 +++ .../Gpu/Buffers/GuestBufferObtainMemoTests.cs | 271 +++++ .../Buffers/GuestBufferUnmappedPageTests.cs | 84 ++ .../Gpu/Buffers/UploadPieceTests.cs | 53 + .../GpuCommands/CommandStreamQueueTests.cs | 61 ++ .../GpuCommands/CommandStreamTestSupport.cs | 17 + .../Gpu/GpuCommands/EndOfPipeSoftWaitTests.cs | 427 ++++++++ .../GpuCommandInterpreterDrawTests.cs | 155 ++- .../Registers/ContextIdentityTests.cs | 49 + .../Gpu/Images/CachedImageTests.cs | 32 + .../Gpu/Images/GuestImageCacheTests.Depth.cs | 26 + .../Images/GuestImageCacheTests.HeapHold.cs | 55 + .../Images/GuestImageCacheTests.ImageTypes.cs | 71 +- .../Gpu/Images/ImageTestHarness.cs | 4 +- .../Gpu/Images/ReadbackLandingTests.cs | 70 ++ .../Gpu/Images/ViewFormatRulesTests.cs | 1 + .../Gpu/Pipelines/CallTableScanTests.cs | 429 ++++++++ .../Pipelines/ComputeRejectionPolicyTests.cs | 36 + .../Gpu/Pipelines/ImageBindingTestProgram.cs | 37 + .../Gpu/Pipelines/LinkedShaderPrewarmTests.cs | 96 ++ .../Gpu/Pipelines/MeshDrawPlannerTests.cs | 42 + .../Gpu/Pipelines/PendingPassSkipTests.cs | 311 ++++++ .../Gpu/Pipelines/PipelineTestSupport.cs | 37 +- .../Gpu/Pipelines/PixelPrewarmTests.cs | 147 +++ .../ProgramInputDependenciesTests.cs | 139 +++ .../Pipelines/ShaderCallLibraryMemoTests.cs | 335 ++++++ .../Gpu/Pipelines/ShaderCallLibraryTests.cs | 247 +++++ .../ShaderCallSiteCacheRegressionTests.cs | 155 +++ .../Pipelines/ShaderCallUnionStoreTests.cs | 62 ++ .../Gpu/Pipelines/ShaderCalleeTiersTests.cs | 65 ++ .../Pipelines/ShaderDescriptorLimitsTests.cs | 44 + .../Pipelines/ShaderFunctionReaderTests.cs | 18 + .../Gpu/Pipelines/ShaderPipelineCacheTests.cs | 20 + .../Gpu/Pipelines/ShaderPlanningDumpTests.cs | 4 +- .../Pipelines/ShaderPrewarmExtensionTests.cs | 273 +++++ .../ShaderPrewarmLinkedReplayTests.cs | 254 +++++ .../Gpu/Pipelines/ShaderPrewarmListTests.cs | 289 +++++- .../Gpu/Pipelines/ShaderProgramCacheTests.cs | 49 + .../Pipelines/TranslationDiskCacheTests.cs | 186 ++++ .../Gpu/Pipelines/VertexPrewarmTests.cs | 392 +++++++ .../Gpu/Rendering/DispatchChainTests.cs | 55 +- .../Rendering/EmbeddedVertexOffsetTests.cs | 77 ++ .../Gpu/Rendering/LinkedModuleWaitTests.cs | 51 + .../RenderExecutorAdaptationTests.cs | 52 +- .../Rendering/RenderExecutorComputeTests.cs | 155 ++- .../Gpu/Rendering/RenderExecutorDrawTests.cs | 82 +- .../RenderExecutorPendingWritesTests.cs | 2 +- .../Gpu/Rendering/RenderExecutorStateTests.cs | 2 +- .../Rendering/RenderExecutorTestSupport.cs | 10 + .../Rendering/ResolvedCommandReplayTests.cs | 2 +- .../PendingGuestPublicationTests.cs | 20 + .../Scheduling/PresenterSubmissionTests.cs | 67 ++ .../Gpu/Scheduling/PublicationGapTests.cs | 99 ++ .../Vulkan/BiasedStorageBufferDeviceTests.cs | 5 +- .../Vulkan/BufferAtomicRangeDeviceTests.cs | 50 + .../Gpu/Vulkan/BufferFormatWrapDeviceTests.cs | 53 + .../Vulkan/CompactDeviceRangeDeviceTests.cs | 146 +++ .../Vulkan/CpuKernelEvaluationDeviceTests.cs | 5 +- .../Vulkan/DeferredExecGuardDeviceTests.cs | 203 ++++ .../Gpu/Vulkan/DeviceAddressShaderTests.cs | 119 +++ .../Vulkan/DeviceFormatStoreDeviceTests.cs | 88 ++ .../Vulkan/FlattenedReadReuseDeviceTests.cs | 4 +- .../Vulkan/Float16ArithmeticDeviceTests.cs | 4 + .../Vulkan/FloatMinMaxLoweringDeviceTests.cs | 151 +++ .../Vulkan/FloatNanSemanticsDeviceTests.cs | 56 + .../Gpu/Vulkan/FmaMixDeviceTests.cs | 51 + .../Gpu/Vulkan/GcnComputeDeviceTests.cs | 3 +- .../Gpu/Vulkan/HeadlessVulkan.cs | 99 ++ .../Vulkan/LargeStorageBindingDeviceTests.cs | 73 ++ .../Gpu/Vulkan/LayoutComputeRunner.cs | 16 + .../Gpu/Vulkan/LayoutImageShaderTests.cs | 60 +- .../NativeFloat16ConversionDeviceTests.cs | 525 ++++++++++ .../Vulkan/ReadFirstLaneWave32DeviceTests.cs | 67 ++ .../Gpu/Vulkan/RobustBufferLoadDeviceTests.cs | 120 +++ .../Vulkan/RuntimeBufferStrideDeviceTests.cs | 52 + .../Vulkan/RuntimeImageSwizzleDeviceTests.cs | 204 ++++ .../Gpu/Vulkan/SharedDeviceLoadDeviceTests.cs | 230 ++++ .../Gpu/Vulkan/TessellationWaveDeviceTests.cs | 3 +- .../Gpu/Vulkan/Wave64HalfMaskDeviceTests.cs | 2 +- .../Gpu/Vulkan/WaveReductionDeviceTests.cs | 316 ++++++ .../Kernel/KernelBackedMemoryTests.cs | 23 + .../Kernel/KernelRuntimeCompatExportsTests.cs | 41 + .../Memory/GpuMemory/AvlSpanSetTests.cs | 43 + .../GuestGpuManagedWriteLeaseTests.cs | 235 +++++ .../Memory/GpuMemory/GuestPageTrackerTests.cs | 25 + .../GpuMemory/GuestWriteReservationsTests.cs | 430 ++++++++ .../GpuMemory/SpanSnapshotLastHitTests.cs | 120 +++ .../GpuMemory/SpanSnapshotOverlapTests.cs | 29 + .../PhysicalVirtualMemoryBackedTests.cs | 72 +- .../Network/HttpExportsTests.cs | 67 ++ .../Np/NpEntitlementAccessExportsTests.cs | 39 + .../Pad/PadExportsTests.cs | 25 + .../PlayGo/PlayGoExportsTests.cs | 36 + .../SaveData/SaveDataExportsTests.cs | 30 + .../VideoOut/BindlessHeapRunTests.cs | 263 +++++ .../VideoOut/CallRecordPreparationTests.cs | 130 +++ .../VideoOut/CallRecordSpanTests.cs | 171 +++ .../VideoOut/DeferredSignalHarness.cs | 8 + .../DeferredSignalPublicationTests.cs | 99 +- .../VideoOut/DriverShaderCacheFolderTests.cs | 25 + .../VideoOut/ForwardedWaitTransferTests.cs | 69 ++ .../VideoOut/LinkedCompileAdmissionTests.cs | 69 ++ .../PipelineBinaryStorePolicyTests.cs | 34 + .../VideoOut/PipelineBuildGateTests.cs | 79 ++ .../VideoOut/PresenterImageBindingTests.cs | 110 ++ .../VideoOut/PresenterUnderTest.cs | 4 +- .../VideoOut/PrewarmPoolTests.cs | 176 ++++ .../RenderHostDeviceTests.BufferLifetime.cs | 150 +++ ...nderHostDeviceTests.DeviceAddressRanges.cs | 54 + .../RenderHostDeviceTests.DispatchThreads.cs | 94 ++ .../RenderHostDeviceTests.GraphicsPrewarm.cs | 135 +++ .../RenderHostDeviceTests.IndirectLifetime.cs | 136 +++ .../RenderHostDeviceTests.MeshDraw.cs | 48 +- .../RenderHostDeviceTests.MeshIndirect.cs | 125 ++- .../RenderHostDeviceTests.NullImageMemo.cs | 164 +++ .../RenderHostDeviceTests.Tessellation.cs | 80 +- .../VideoOut/RenderHostDeviceTests.cs | 258 ++++- .../VideoOut/ShaderPrewarmPresenterTests.cs | 83 ++ .../VideoOut/ShaderPrewarmQueueTests.cs | 228 ++++ .../VideoOut/SliceRecordingTests.cs | 1 + .../VulkanGraphicsSubgroupPolicyTests.cs | 17 + .../VideoOut/VulkanPipelineBinaryTests.cs | 310 ++++++ .../VideoOut/VulkanPipelineLibraryTests.cs | 39 + .../Gen5ArrayReadDimensionTests.cs | 117 +++ .../Gen5BufferAtomic64Tests.cs | 102 ++ .../Gen5DataShareRead64Tests.cs | 27 + .../Gen5DeviceBufferFormatStoreTests.cs | 33 + .../Gen5Float16ArithmeticTests.cs | 45 +- .../Gen5ImageTests.cs | 69 +- .../Gen5MeshShaderTests.cs | 278 ++++- .../Gen5NonTessellationSpirvStabilityTests.cs | 30 +- .../Gen5ShaderCallLinkerTests.cs | 58 +- .../Gen5ShaderClockTests.cs | 116 +++ .../Gen5VertexSystemRegisterTests.cs | 8 +- .../Resources/BindingLayoutTests.cs | 57 + .../Resources/BindlessHeapTests.cs | 343 ++++++ .../Resources/BranchSelectionSeedTests.cs | 70 ++ .../CompiledBranchTransactionTests.cs | 231 +++++ .../Resources/CompiledCallRecordRangeTests.cs | 470 +++++++++ .../CompiledDeviceAddressRangeTests.Large.cs | 103 ++ .../CompiledDeviceAddressRangeTests.cs | 507 +++++++++ .../CompiledResourceTransactionTests.cs | 6 +- .../Resources/DeviceRecordCountTests.cs | 309 ++++++ .../Resources/DirectImageTableTests.cs | 5 +- .../Resources/FastMaterializationCheck.cs | 5 + .../Resources/FlattenedReadReuseTests.cs | 6 +- .../Resources/ResourceBranchTests.cs | 159 ++- .../Resources/ResourceMaterializerTests.cs | 4 +- .../Resources/ResourceTestProgram.cs | 19 +- .../Resources/ResourceTrackerTests.cs | 195 +++- .../Resources/RuntimeImageSwizzleTests.cs | 129 +++ .../Resources/ScalarBufferBoundsTests.cs | 90 ++ .../Resources/ScalarDataReadPolicyTests.cs | 119 +++ .../Resources/ScalarGraphDiskCacheTests.cs | 52 + .../Resources/ScalarValueGraphTests.cs | 5 +- .../Resources/SpecializationGuardTests.cs | 4 +- .../Resources/SpirvBindingDeclarationTests.cs | 8 +- .../Resources/StableImageBindingTests.cs | 159 +++ .../SpirvEmitterContractTests.cs | 325 ++++++ .../SpirvExtInstOperandTests.cs | 91 ++ .../SpirvExtInstUseTests.cs | 136 +++ .../SpirvOptimizationTests.cs | 200 ++++ 364 files changed, 38509 insertions(+), 1711 deletions(-) create mode 100644 src/SharpEmu.HLE/GpuMemory/GuestWriteReservations.cs create mode 100644 src/SharpEmu.HLE/HostCallTrims.cs create mode 100644 src/SharpEmu.Libs/Agc/AgcPacketWrites.cs create mode 100644 src/SharpEmu.Libs/Ampr/AmprExports.Amm.cs create mode 100644 src/SharpEmu.Libs/Ampr/AmprExports.Queues.cs create mode 100644 src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.ObtainMemo.cs create mode 100644 src/SharpEmu.Libs/Gpu/GpuCommands/EndOfPipeLandings.cs create mode 100644 src/SharpEmu.Libs/Gpu/Images/HostLayoutTargets.cs create mode 100644 src/SharpEmu.Libs/Gpu/Pipelines/LinkedShaderPrewarm.cs create mode 100644 src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibrary.TableScan.cs create mode 100644 src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibraryMemo.cs create mode 100644 src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.Vertex.cs create mode 100644 src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.CallDispatch.cs create mode 100644 src/SharpEmu.Libs/Gpu/Pipelines/SliceDescriptorHeap.cs create mode 100644 src/SharpEmu.Libs/Gpu/Pipelines/TranslationDiskCache.cs create mode 100644 src/SharpEmu.Libs/Gpu/Rendering/DispatchThreadsPipeline.cs create mode 100644 src/SharpEmu.Libs/Gpu/Rendering/MeshTaskLaunch.cs create mode 100644 src/SharpEmu.Libs/Gpu/Vulkan/DeviceFaultReport.cs create mode 100644 src/SharpEmu.Libs/Network/HttpExports.Requests.cs create mode 100644 src/SharpEmu.Libs/VideoOut/DriverShaderCacheFolder.cs create mode 100644 src/SharpEmu.Libs/VideoOut/LinkedCompileAdmission.cs create mode 100644 src/SharpEmu.Libs/VideoOut/PipelineBinaryStorePolicy.cs create mode 100644 src/SharpEmu.Libs/VideoOut/PipelineBuildGate.cs create mode 100644 src/SharpEmu.Libs/VideoOut/PrewarmPool.cs create mode 100644 src/SharpEmu.Libs/VideoOut/ShaderPrewarmQueue.cs create mode 100644 src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CallRecordSpans.cs create mode 100644 src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.DispatchThreads.cs create mode 100644 src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.GraphicsPrewarm.cs create mode 100644 src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.PipelineBinaries.cs create mode 100644 src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.PipelineLibraries.cs create mode 100644 src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.DeferredGuards.cs create mode 100644 src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.DeviceLoadFunction.cs create mode 100644 src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.WaveReductions.cs create mode 100644 src/SharpEmu.ShaderCompiler.Vulkan/SpirvDispatchThreads.cs create mode 100644 src/SharpEmu.ShaderCompiler.Vulkan/SpirvMeshTask.cs create mode 100644 src/SharpEmu.ShaderCompiler/Resources/CompiledBranchTransaction.cs create mode 100644 src/SharpEmu.ShaderCompiler/Resources/CompiledDeviceAddressRanges.cs create mode 100644 src/SharpEmu.ShaderCompiler/Resources/DeviceCountProofWorker.cs create mode 100644 src/SharpEmu.ShaderCompiler/Resources/DeviceRecordCountPlan.cs create mode 100644 src/SharpEmu.ShaderCompiler/Resources/DispatchBufferFootprint.Word.cs create mode 100644 src/SharpEmu.ShaderCompiler/Resources/DispatchBufferFootprint.cs create mode 100644 src/SharpEmu.ShaderCompiler/Resources/ResourceBranchWriteGuard.cs create mode 100644 src/SharpEmu.ShaderCompiler/Resources/RuntimeImageSwizzle.cs create mode 100644 src/SharpEmu.ShaderCompiler/Resources/ScalarDataReadPolicy.cs create mode 100644 src/SharpEmu.ShaderCompiler/Resources/ShaderResourcePlan.CompiledRanges.cs create mode 100644 src/SharpEmu.ShaderCompiler/Resources/StableImageDescriptorLimits.cs create mode 100644 tests/SharpEmu.Libs.Tests/Agc/AgcPacketWritesTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Ampr/AmprCommandQueueTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferBdaRegistrationTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferManagedCopyReadbackTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferManagedWriteAdmissionTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferObtainMemoTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferUnmappedPageTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Buffers/UploadPieceTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/EndOfPipeSoftWaitTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/Registers/ContextIdentityTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.HeapHold.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Images/ReadbackLandingTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/CallTableScanTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ImageBindingTestProgram.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/LinkedShaderPrewarmTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PendingPassSkipTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PixelPrewarmTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ProgramInputDependenciesTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCallLibraryMemoTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCallSiteCacheRegressionTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCallUnionStoreTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPrewarmExtensionTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPrewarmLinkedReplayTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/TranslationDiskCacheTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/VertexPrewarmTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Rendering/LinkedModuleWaitTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Scheduling/PublicationGapTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Vulkan/BufferFormatWrapDeviceTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Vulkan/CompactDeviceRangeDeviceTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Vulkan/DeferredExecGuardDeviceTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Vulkan/DeviceFormatStoreDeviceTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Vulkan/FloatMinMaxLoweringDeviceTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Vulkan/LargeStorageBindingDeviceTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Vulkan/NativeFloat16ConversionDeviceTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Vulkan/ReadFirstLaneWave32DeviceTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Vulkan/RobustBufferLoadDeviceTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Vulkan/RuntimeBufferStrideDeviceTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Vulkan/RuntimeImageSwizzleDeviceTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Vulkan/SharedDeviceLoadDeviceTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Vulkan/WaveReductionDeviceTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Memory/GpuMemory/GuestGpuManagedWriteLeaseTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Memory/GpuMemory/GuestWriteReservationsTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Memory/GpuMemory/SpanSnapshotLastHitTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Memory/GpuMemory/SpanSnapshotOverlapTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Network/HttpExportsTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/BindlessHeapRunTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/CallRecordPreparationTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/CallRecordSpanTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/DriverShaderCacheFolderTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/ForwardedWaitTransferTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/LinkedCompileAdmissionTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/PipelineBinaryStorePolicyTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/PipelineBuildGateTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/PrewarmPoolTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.BufferLifetime.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.DeviceAddressRanges.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.DispatchThreads.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.GraphicsPrewarm.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.IndirectLifetime.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.NullImageMemo.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/ShaderPrewarmQueueTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/VulkanPipelineBinaryTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/VulkanPipelineLibraryTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Gen5ArrayReadDimensionTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Gen5BufferAtomic64Tests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Gen5DeviceBufferFormatStoreTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Gen5ShaderClockTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Resources/BindlessHeapTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Resources/BranchSelectionSeedTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledBranchTransactionTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledCallRecordRangeTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledDeviceAddressRangeTests.Large.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledDeviceAddressRangeTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Resources/DeviceRecordCountTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Resources/RuntimeImageSwizzleTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Resources/ScalarBufferBoundsTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Resources/ScalarDataReadPolicyTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Resources/StableImageBindingTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/SpirvEmitterContractTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/SpirvExtInstOperandTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/SpirvExtInstUseTests.cs diff --git a/docs/sharpemu-gui-undocumented-env-vars.md b/docs/sharpemu-gui-undocumented-env-vars.md index 44e1a1567..1a5c2d423 100644 --- a/docs/sharpemu-gui-undocumented-env-vars.md +++ b/docs/sharpemu-gui-undocumented-env-vars.md @@ -102,7 +102,7 @@ result filters, mutex warning sampling, and diagnostic selection. | Group | Variables | | --- | --- | | Behavior switches | 17 | -| GPU and Vulkan | 61 | +| GPU and Vulkan | 63 | | GnmMode | 4 (plus 2 shared switches listed below; trophy key also exposed in GUI) | | Audio and video | 6 | | Input | 5 | @@ -224,11 +224,13 @@ These variables change the GPU path or the Vulkan presenter. | `SHARPEMU_FORCE_TITLE_SOLID_FRAGMENT` | `1` | The Vulkan presenter reads the value into a field. No code uses the field, so the variable has no effect at this time. | `VulkanVideoPresenter.Draws.Recording.cs` | | `SHARPEMU_FORCE_TITLE_VERTEX_OUTPUTS_ONE` | `1` | Vertex export targets 32 to 35 write the vector (1, 1, 1, 1). This applies only to the vertex shader at guest address 0x0000000500780000. Default is off. | `Gen5SpirvTranslator.cs` | | `SHARPEMU_GPU_WAIT_SPIN_US` | number (microseconds) | Sets how long a wait for GPU work polls before it blocks. A short poll saves the wake-up delay when the GPU finishes soon. `0` blocks at once. The default is 150. | `GpuWaitSpin.cs` | +| `SHARPEMU_GRAPHICS_PIPELINE_LIBRARY` | `0` | `0` builds every graphics pipeline whole, with one descriptor set. By default, on a device that links `VK_EXT_graphics_pipeline_library` parts fast, the vertex input, vertex stage, pixel stage and color outputs compile once as separate parts and each pipeline links them: the vertex set is pushed, the bindless heap is set 1 and the pixel set comes from a descriptor pool. Render workers take pixel sets from their own pools, which return when the slice's submission completes. Enabling the extension changes the device, so the driver may compile every pipeline again after a change. | `VulkanVideoPresenter.PipelineLibraries.cs`, `VulkanVideoPresenter.Device.Setup.cs` | | `SHARPEMU_GRAPHICS_SUBGROUPS` | `0` or `1` | Set `1` to use native Vulkan subgroup operations in graphics shaders. Set `0` to use the fallback path. When unset, the presenter uses them only if the subgroup size is 32 and the vertex and fragment stages support subgroups. | `VulkanVideoPresenter.cs`, `VulkanVideoPresenter.Device.Setup.cs` | | `SHARPEMU_IMAGE_LOOKUP_MEMO` | `0` | `0` turns off the image lookup memo. The default keeps the result of each image lookup that found an image with the same backing, and gives it again for the same request until an image is registered or removed. | `GuestImageCache.Lookup.cs` | | `SHARPEMU_OCCLUSION_GPU_DUMPS` | `0` | `0` turns off GPU copies of pending occlusion results. By default, later GPU buffer reads receive these results without waiting for CPU publication. Guest memory publication remains ordered in both modes. | `VulkanVideoPresenter.Occlusion.cs`, `VulkanOcclusionQueries.GpuResults.cs` | | `SHARPEMU_MARK_PIXEL_PCS` | list of `pc:register` pairs | Makes the SPIR-V pixel shader write the float value 1.0 to a shader register when execution reaches the given instruction PC. Use decimal numbers, a register below 256, and a comma between pairs. It has an effect only for the shader address in `SHARPEMU_CAPTURE_PIXEL_VGPR_ADDRESS`. | `Gen5SpirvTranslator.cs` | | `SHARPEMU_MAX_GUEST_WORK_PER_RENDER` | number | Sets the maximum number of guest command stream slices that the Vulkan presenter runs in one render pass. The default is 1024. The value must be more than 0. | `VulkanVideoPresenter.cs`, `VulkanVideoPresenter.CommandStream.cs` | +| `SHARPEMU_READBACK_LINEAR_IMAGES` | `0` | `0` turns off the readback of linear images. By default, a linear storage image or color target that the GPU writes is copied back to guest memory when its work completes, so a CPU thread that waits for a GPU-filled image, such as an occlusion buffer whose sentinel it wrote, continues. An image is read back in the frame the GPU first writes it, and in the frame the CPU stores into it and the next one; an image only the GPU writes is not read back again every frame. A GnmMode target that is tiled in guest memory but laid out linear on the host is never read back, because its host bytes do not follow the guest's layout. The log names the first 16 images read back (`linear image readback`). | `VulkanVideoPresenter.Scheduler.cs`, `GuestImageCache.Tracking.cs`, `HostLayoutTargets.cs` | | `SHARPEMU_RENDERDOC_CAPTURE_TIMEOUT_SECONDS` | number (seconds) | Set the maximum time for a RenderDoc frame capture. The emulator discards a capture that does not end in this time. The range is 1 to 120. The default is 15. | `RenderDocCapture.cs` | | `SHARPEMU_RENDERDOC_DLL` | path | Set the path of the RenderDoc library file. The emulator tries this path first. When unset or when the load fails, it searches the default library name and the known install paths. | `RenderDocCapture.cs` | | `SHARPEMU_RENDERDOC_WAIT` | number (seconds) or `enter` | Set to make the emulator wait before it starts Vulkan, so that you can attach RenderDoc. `enter` waits until you press Enter. A number waits that many seconds, from 1 to 300. Other text waits 15 seconds. | `VulkanVideoPresenter.Device.Setup.cs` | diff --git a/src/SharpEmu.CLI/Program.cs b/src/SharpEmu.CLI/Program.cs index d0ed9a5ad..0bd544a8e 100644 --- a/src/SharpEmu.CLI/Program.cs +++ b/src/SharpEmu.CLI/Program.cs @@ -43,6 +43,9 @@ private static readonly (string Name, string Value)[] ServerGarbageCollector = ("DOTNET_gcServer", "1"), ("DOTNET_GCHeapCount", "4"), ("DOTNET_GCNoAffinitize", "1"), + // Guest memory keeps the machine's memory load above the GC's high-memory thresholds, where it runs a blocking + // compacting generation-2 collection of most of a second every few seconds. The value is hexadecimal (99 percent). + ("DOTNET_GCHighMemPercent", "63"), ]; private const int ATTACH_PARENT_PROCESS = -1; private const int STD_INPUT_HANDLE = -10; diff --git a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Exceptions.cs b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Exceptions.cs index a48c01356..ad645e163 100644 --- a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Exceptions.cs +++ b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Exceptions.cs @@ -677,15 +677,17 @@ private unsafe static bool TryResolveGpuFault(EXCEPTION_RECORD* exceptionRecord) && GuestGpuMemoryHook.TryResolveFault(kind, exceptionRecord->ExceptionInformation[1]); } + private static readonly bool GuestAllocatorHoleRecoveryDisabled = string.Equals( + Environment.GetEnvironmentVariable("SHARPEMU_DISABLE_GUEST_ALLOCATOR_HOLE_RECOVERY"), + "1", + StringComparison.Ordinal); + private unsafe static bool TryRecoverGuestAllocatorHole( EXCEPTION_RECORD* exceptionRecord, void* contextRecord, ulong rip) { - if (string.Equals( - Environment.GetEnvironmentVariable("SHARPEMU_DISABLE_GUEST_ALLOCATOR_HOLE_RECOVERY"), - "1", - StringComparison.Ordinal) || + if (GuestAllocatorHoleRecoveryDisabled || exceptionRecord->NumberParameters < 2 || exceptionRecord->ExceptionInformation[0] != 0 || exceptionRecord->ExceptionInformation[1] != 8 || diff --git a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Imports.cs b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Imports.cs index e10953c8c..de4abc582 100644 --- a/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Imports.cs +++ b/src/SharpEmu.Core/Cpu/Native/DirectExecutionBackend.Imports.cs @@ -372,18 +372,21 @@ private unsafe ulong DispatchImportCore(int importIndex, nint argPackPtr) Console.Error.WriteLine($"[LOADER][TRACE] Raw sentinel recoveries: {num2} (last import index={importIndex})"); _lastReportedRawSentinelRecoveries = num2; } - if (importStubEntry.IsLeaf && + // After a host shutdown request every import takes the full path below, whose shutdown check ends the guest + // thread's slice before a service being torn down can fail it. + var leafDispatch = !_forcedGuestExit; + if (leafDispatch && importStubEntry.IsLeaf && TryDispatchHotMemoryLeaf(cpuContext, importStubEntry, argPackPtr, out var hotMemoryResult)) { return hotMemoryResult; } - if (importStubEntry.IsTrivialLeaf && !_disableTrivialLeafDispatch) + if (leafDispatch && importStubEntry.IsTrivialLeaf && !_disableTrivialLeafDispatch) { return DispatchTrivialLeaf(cpuContext, in importStubEntry, argPackPtr, num); } - if (importStubEntry.IsLeaf && + if (leafDispatch && importStubEntry.IsLeaf && TryDispatchLeafImport(cpuContext, importStubEntry, argPackPtr, num, out var leafResult)) { return leafResult; @@ -523,7 +526,9 @@ private unsafe ulong DispatchImportCore(int importIndex, nint argPackPtr) // Once the host is shutting down, a guest thread still running reaches no more HLE: the // services behind the imports are being torn down, and a title that sees them fail (a null // command buffer from the GPU library, say) crashes the process on its way out. - if (_forcedGuestExit && !ActiveForcedGuestExit && TryEndGuestSliceForShutdown(argPackPtr)) + // The thread's own exit flag: ActiveForcedGuestExit also reads the backend-wide _forcedGuestExit, so testing it + // here would never let the slice end. + if (_forcedGuestExit && !(HasActiveExecutionThread && _activeForcedGuestExit) && TryEndGuestSliceForShutdown(argPackPtr)) { cpuContext[CpuRegister.Rax] = 1uL; return 1uL; @@ -1866,6 +1871,11 @@ private bool ShouldLogImportResult(string nid, OrbisGen2Result result, out int m var expectedPlayGoChunkEnumerationEnd = string.Equals(nid, "uWIYLFkkwqk", StringComparison.Ordinal) && resultValue == unchecked((int)0x80B2000C); + // sceSaveDataConvert reports a save directory that is missing or already in the current format; titles + // then mount it as usual. + var expectedSaveDataNoConversion = + string.Equals(nid, "2mfSRGdshtk", StringComparison.Ordinal) && + (resultValue == unchecked((int)0x809F0008) || resultValue == unchecked((int)0x809F001E)); if (!expectedFileProbeMiss && !expectedTimedWaitTimeout && !expectedEqueueTimeout && @@ -1878,7 +1888,8 @@ private bool ShouldLogImportResult(string nid, OrbisGen2Result result, out int m !expectedNetAcceptWouldBlock && !expectedUserServiceNoEvent && !expectedPrivacyInvalidParameter && - !expectedPlayGoChunkEnumerationEnd) + !expectedPlayGoChunkEnumerationEnd && + !expectedSaveDataNoConversion) { return ShouldSampleImportResult(nid, resultValue, out mutexOccurrence); } diff --git a/src/SharpEmu.Core/Memory/PhysicalVirtualMemory.cs b/src/SharpEmu.Core/Memory/PhysicalVirtualMemory.cs index 017ecde50..54f440985 100644 --- a/src/SharpEmu.Core/Memory/PhysicalVirtualMemory.cs +++ b/src/SharpEmu.Core/Memory/PhysicalVirtualMemory.cs @@ -2228,24 +2228,20 @@ public bool TryWrite(ulong virtualAddress, ReadOnlySpan source) // there). Pre-visit the span so tracked pages are unprotected and // their owners dirtied before the copy; guest addresses are // host-identical, matching the tracker's fault addresses. - GuestImageWriteTracker.NotifyManagedWrite(virtualAddress, (ulong)source.Length); if (!source.IsEmpty && _backedSpace is { } backed && !_disposed) { - GuestGpuMemoryHook.PrepareEmulatorWrite(virtualAddress, (ulong)source.Length); + using var singleViewWrite = GuestGpuMemoryHook.BeginCpuWrite(virtualAddress, (ulong)source.Length, emulatorWrite: true); if (backed.TryWriteSingleView(virtualAddress, source)) { - GuestGpuMemoryHook.NoteEmulatorWrite(virtualAddress, (ulong)source.Length); NotifyGuestWriteWatch(virtualAddress, source); return true; } } - GuestGpuMemoryHook.MarkCpuWrite(virtualAddress, (ulong)source.Length); + using var write = GuestGpuMemoryHook.BeginCpuWrite(virtualAddress, (ulong)source.Length); var written = TryWriteCore(virtualAddress, source); - // Backed writes go through an alias no page watch covers: an upload between the mark above - // and the write took the old bytes and left the pages clean, and no fault reports the new ones. - GuestGpuMemoryHook.MarkCpuWriteLanded(virtualAddress, (ulong)source.Length); + // The lease publishes landed bytes before admitting another overlapping GPU claim. return written; } @@ -2344,30 +2340,79 @@ public bool TryCopy(ulong destinationAddress, ulong sourceAddress, ulong length) return false; } - // Match TryWrite's managed-write notification before touching an - // identity-mapped guest page protected by the image tracker. - GuestImageWriteTracker.NotifyManagedWrite(destinationAddress, length); if (_backedSpace is { } backed && !_disposed) { - GuestGpuMemoryHook.PrepareEmulatorWrite(destinationAddress, length); + using var singleViewWrite = GuestGpuMemoryHook.BeginCpuWrite(destinationAddress, length, emulatorWrite: true); if (backed.TryCopySingleView(destinationAddress, sourceAddress, length)) { - GuestGpuMemoryHook.NoteEmulatorWrite(destinationAddress, length); NotifyBackedWriteWatch(destinationAddress, length); return true; } } - GuestGpuMemoryHook.MarkCpuWrite(destinationAddress, length); - var copied = TryCopyCore(destinationAddress, sourceAddress, length); + bool copied, needsStaging; + using (GuestGpuMemoryHook.BeginCpuWrite(destinationAddress, length)) + { + copied = TryCopyCore(destinationAddress, sourceAddress, length, out needsStaging); + } - // As in TryWrite: an upload after the mark may have taken the bytes from before the copy. - GuestGpuMemoryHook.MarkCpuWriteLanded(destinationAddress, length); - return copied; + // Staging re-enters TryWrite, whose premark may wait on the GPU. Each piece obtains + // its own reservation; no outer reservation may span that nested premark. + return needsStaging ? CopyThroughStaging(destinationAddress, sourceAddress, length) : copied; } - private bool TryCopyCore(ulong destinationAddress, ulong sourceAddress, ulong length) + // HostCallTrims.MixedCopyDirect, under the read lock: a copy between the backing and private memory in one call, + // when the private side resolves, is committed and needs no protection change, as the TryRead or TryWrite of each + // staging piece would find it. The backing's read or write checks its whole span before it copies a byte, and the + // write notification is the one TryWrite makes. False leaves both sides untouched, and the caller stages the copy. + private bool TryCopyMixedDirect(ulong destinationAddress, ulong sourceAddress, ulong length, + MemoryRegion? sourceRegion, MemoryRegion? destinationRegion, bool sourceBacked) { + var privateAddress = sourceBacked ? destinationAddress : sourceAddress; + var privateRegion = sourceBacked ? destinationRegion : sourceRegion; + // Armed watches depend on the ordinary staging pieces' call boundaries and lengths. + if (GuestWriteWatch.Armed || length > int.MaxValue || privateRegion is null || privateRegion.IsReservedOnly || + !TryResolveRegionOffset(privateAddress, length, privateRegion, out var offset)) + { + return false; + } + + var pointer = privateRegion.VirtualAddress + offset; + if (sourceBacked) + { + if (!CanWriteWithoutProtectionChange(pointer, length, privateRegion)) + { + return false; + } + + var target = new Span((void*)pointer, (int)length); + if (!_backedSpace!.TryReadBacking(sourceAddress, target)) + { + return false; + } + + NotifyGuestWriteWatch(destinationAddress, target); + return true; + } + + if (!CanReadWithoutProtectionChange(pointer, length, privateRegion)) + { + return false; + } + + var source = new ReadOnlySpan((void*)pointer, (int)length); + if (!_backedSpace!.TryWriteBacking(destinationAddress, source)) + { + return false; + } + + NotifyGuestWriteWatch(destinationAddress, source); + return true; + } + + private bool TryCopyCore(ulong destinationAddress, ulong sourceAddress, ulong length, out bool needsStaging) + { + needsStaging = false; _gate.EnterReadLock(); try { @@ -2389,6 +2434,12 @@ private bool TryCopyCore(ulong destinationAddress, ulong sourceAddress, ulong le // The staged path re-enters TryRead/TryWrite, which may need the write lock. if (sourceBacked || destinationBacked) { + if (global::SharpEmu.HLE.HostCallTrims.MixedCopyDirect && + TryCopyMixedDirect(destinationAddress, sourceAddress, length, sourceRegion, destinationRegion, sourceBacked)) + { + return true; + } + goto staged; } @@ -2426,7 +2477,8 @@ private bool TryCopyCore(ulong destinationAddress, ulong sourceAddress, ulong le } staged: - return CopyThroughStaging(destinationAddress, sourceAddress, length); + needsStaging = true; + return false; } private bool TryReadExclusive(ulong virtualAddress, Span destination) diff --git a/src/SharpEmu.Core/Runtime/SharpEmuRuntime.cs b/src/SharpEmu.Core/Runtime/SharpEmuRuntime.cs index 8b562d19f..5c0fc6129 100644 --- a/src/SharpEmu.Core/Runtime/SharpEmuRuntime.cs +++ b/src/SharpEmu.Core/Runtime/SharpEmuRuntime.cs @@ -200,6 +200,7 @@ public OrbisGen2Result Run(string ebootPath) KernelMemoryCompatExports.ConfigureApplicationInfo(image.TitleId); SaveDataExports.ConfigureApplicationInfo(image.TitleId); SystemServiceExports.ConfigureApplicationInfo(image.TitleId, _systemLanguage); + VideoOutExports.StartPresenter(); _ = RegisterLoadedModule(normalizedEbootPath, image, isMain: true, isSystemModule: false); KernelRuntimeCompatExports.ConfigureProcessProcParamAddress(image.ProcParamAddress); Console.Error.WriteLine($"[RUNTIME] Entry: 0x{image.EntryPoint:X16}"); @@ -1338,11 +1339,38 @@ private int RegisterLoadedModule(string modulePath, SelfImage image, bool isMain isMain, isSystemModule); KernelModuleRegistry.RegisterModuleSymbols(handle, image.RuntimeSymbols); + KernelModuleRegistry.RegisterModuleSegments(handle, ComputeImageSegments(image)); Console.Error.WriteLine( $"[RUNTIME] Registered module handle={handle} name={Path.GetFileName(modulePath)} base=0x{baseAddress:X16} size=0x{size:X16}"); return handle; } + // The loaded segments in whole 16 KiB pages, each with the kernel protection of its ELF flags (CPU read 0x1, + // write 0x2, execute 0x4). + private static KernelModuleRegistry.ModuleSegment[] ComputeImageSegments(SelfImage image) + { + const ulong PageMask = 0x3FFF; + var imageBase = image.EntryPoint >= image.ElfHeader.EntryPoint + ? image.EntryPoint - image.ElfHeader.EntryPoint + : 0UL; + var segments = new List(); + foreach (var header in image.ProgramHeaders) + { + if (header.HeaderType != ProgramHeaderType.Load || header.MemorySize == 0) + { + continue; + } + + var start = unchecked(imageBase + header.VirtualAddress); + var protection = ((header.Flags & ProgramHeaderFlags.Read) != 0 ? 0x1 : 0) | + ((header.Flags & ProgramHeaderFlags.Write) != 0 ? 0x2 : 0) | + ((header.Flags & ProgramHeaderFlags.Execute) != 0 ? 0x4 : 0); + segments.Add(new(start & ~PageMask, unchecked(start + header.MemorySize + PageMask) & ~PageMask, protection)); + } + + return [.. segments]; + } + private static bool TryComputeImageRange(SelfImage image, out ulong baseAddress, out ulong size) { baseAddress = 0; @@ -1518,6 +1546,16 @@ public void Dispose() return; } + if (HostSessionControl.IsShutdownRequested) + { + // A host shutdown tears the presentation down on its own thread, which still returns pages to their guest + // protection and downloads GPU results into guest memory; the process exits after it. Releasing the page + // guard or unmapping the guest space here would race that teardown. + Console.Error.WriteLine( + "[RUNTIME] Host shutdown: the presentation tears down guest GPU memory; keeping the guest address space mapped."); + return; + } + if (_gpuMemory != null) { if (GuestGpuMemoryHook.TryTakeShutdownSummary(out var gpuSummary)) diff --git a/src/SharpEmu.GnmMode/Gpu/GnmCommandPackets.cs b/src/SharpEmu.GnmMode/Gpu/GnmCommandPackets.cs index 81ff7e076..4bc4731e3 100644 --- a/src/SharpEmu.GnmMode/Gpu/GnmCommandPackets.cs +++ b/src/SharpEmu.GnmMode/Gpu/GnmCommandPackets.cs @@ -614,6 +614,8 @@ private static void TranslateColorTarget(GpuCommandInterpreter interpreter, Targ Attrib3 = (1u << 24) | ((uint)hostTile << 14), }; interpreter.TypedRegisters.MarkWritten(1u << (int)RegisterStamp.ColorTargets); + if (!linear && hostTile == GuestTileMode.Linear) + HostLayoutTargets.Mark(target.BaseAddress); GcnImageDescriptor.ObserveColorTarget(guestAddress, in target, pitch, height, tileIndex); } diff --git a/src/SharpEmu.GnmMode/Shaders/GcnImageDescriptor.cs b/src/SharpEmu.GnmMode/Shaders/GcnImageDescriptor.cs index cd94fee07..55e3d5306 100644 --- a/src/SharpEmu.GnmMode/Shaders/GcnImageDescriptor.cs +++ b/src/SharpEmu.GnmMode/Shaders/GcnImageDescriptor.cs @@ -67,6 +67,7 @@ private static bool IsDepthTarget(ReadOnlySpan words) internal static void ResetLayouts() { ColorTargets.Clear(); + HostLayoutTargets.Reset(); LinearPitches.Clear(); DepthTargets.Clear(); ReportedDepthCopies.Clear(); diff --git a/src/SharpEmu.HLE/GpuMemory/AvlSpanSet.cs b/src/SharpEmu.HLE/GpuMemory/AvlSpanSet.cs index e6aeb47e1..7e1d35187 100644 --- a/src/SharpEmu.HLE/GpuMemory/AvlSpanSet.cs +++ b/src/SharpEmu.HLE/GpuMemory/AvlSpanSet.cs @@ -16,13 +16,28 @@ private sealed class Node(ulong start, ulong end) public int Count = 1; } + // A new snapshot copies the last one's spans outside the extent of every span removed or inserted since, and walks the + // tree only inside it. SHARPEMU_SPAN_SNAPSHOT_SPLICE=0 walks the whole tree. + private static readonly bool SpliceSnapshots = Environment.GetEnvironmentVariable("SHARPEMU_SPAN_SNAPSHOT_SPLICE") != "0"; + private Node? _root; private SpanSnapshot? _snapshot = SpanSnapshot.Empty; + private SpanSnapshot _built = SpanSnapshot.Empty; + private ulong _changedStart = ulong.MaxValue; + private ulong _changedEnd; + internal int SplicedSnapshots { get; private set; } public bool IsEmpty => _root is null; public void Clear() { _root = null; - _snapshot = SpanSnapshot.Empty; + Built(SpanSnapshot.Empty); + } + + private void NoteChange(ulong start, ulong end) + { + _snapshot = null; + _changedStart = Math.Min(_changedStart, start); + _changedEnd = Math.Max(_changedEnd, end); } public void Add(ulong address, ulong size) @@ -37,13 +52,13 @@ public void Add(ulong address, ulong size) start = previous.Start; _root = Delete(_root, start); } - _snapshot = null; for (var next = FindAtOrAbove(start); next is not null && next.Start <= end; next = FindAtOrAbove(start)) { end = Math.Max(end, next.End); _root = Delete(_root, next.Start); } _root = Insert(_root, start, end); + NoteChange(start, end); } public void Remove(ulong address, ulong size) @@ -53,11 +68,11 @@ public void Remove(ulong address, ulong size) var current = FindAtOrBelow(address); if (current is null || current.End <= address) current = FindAtOrAbove(address); if (current is null || current.Start >= end) return; - _snapshot = null; while (current is not null && current.Start < end) { var spanStart = current.Start; var spanEnd = current.End; + NoteChange(spanStart, spanEnd); _root = Delete(_root, spanStart); if (spanStart < address) _root = Insert(_root, spanStart, address); if (spanEnd > end) @@ -93,12 +108,90 @@ public bool Overlaps(ulong address, ulong size) public SpanSnapshot Snapshot() { if (_snapshot is { } snapshot) return snapshot; - if (_root is null) return _snapshot = SpanSnapshot.Empty; + if (_root is null) return Built(SpanSnapshot.Empty); var starts = new ulong[_root.Count]; var ends = new ulong[starts.Length]; - var index = 0; - Collect(_root, starts, ends, ref index); - return _snapshot = new SpanSnapshot(starts, ends); + if (SpliceSnapshots && TrySplice(starts, ends)) + { + SplicedSnapshots++; + } + else + { + var index = 0; + Collect(_root, starts, ends, ref index); + } + + return Built(new SpanSnapshot(starts, ends)); + } + + private SpanSnapshot Built(SpanSnapshot snapshot) + { + _changedStart = ulong.MaxValue; + _changedEnd = 0; + return _snapshot = _built = snapshot; + } + + // The spans that end before the changed extent or start after it are the last snapshot's; the tree gives the ones + // between. False when the counts disagree, and the caller walks the whole tree. + private bool TrySplice(ulong[] starts, ulong[] ends) + { + var builtStarts = _built.Starts; + var builtEnds = _built.Ends; + var before = FirstAtOrAbove(builtEnds, _changedStart); + var after = FirstAbove(builtStarts, _changedEnd); + var tail = builtStarts.Length - after; + var middle = starts.Length - before - tail; + if (middle < 0) return false; + builtStarts[..before].CopyTo(starts); + builtEnds[..before].CopyTo(ends); + var index = before; + if (!CollectWithin(_root, _changedStart, _changedEnd, starts, ends, ref index, before + middle) || + index != before + middle) + { + return false; + } + + builtStarts[after..].CopyTo(starts.AsSpan(index)); + builtEnds[after..].CopyTo(ends.AsSpan(index)); + return true; + } + + private static int FirstAtOrAbove(ReadOnlySpan values, ulong bound) + { + int low = 0, high = values.Length; + while (low < high) + { + var middle = (low + high) >>> 1; + if (values[middle] < bound) low = middle + 1; + else high = middle; + } + return low; + } + + private static int FirstAbove(ReadOnlySpan values, ulong bound) + { + int low = 0, high = values.Length; + while (low < high) + { + var middle = (low + high) >>> 1; + if (values[middle] <= bound) low = middle + 1; + else high = middle; + } + return low; + } + + // In order, the spans that touch [low, high]; false when they would pass the limit. + private static bool CollectWithin(Node? node, ulong low, ulong high, ulong[] starts, ulong[] ends, ref int index, int limit) + { + if (node is null) return true; + if (node.Start >= low && !CollectWithin(node.Left, low, high, starts, ends, ref index, limit)) return false; + if (node.End >= low && node.Start <= high) + { + if (index == limit) return false; + starts[index] = node.Start; + ends[index++] = node.End; + } + return node.End > high || CollectWithin(node.Right, low, high, starts, ends, ref index, limit); } public List GetOverlappingRanges(ulong address, ulong size) diff --git a/src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs b/src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs index 77ff0771b..95e328179 100644 --- a/src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs +++ b/src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs @@ -154,6 +154,119 @@ AddressSpace is not IGuestBackedSpace backing || private const ulong GuestWriteGranule = 0x4000; + // Both hooks execute outside admission/tracker/image locks. The reserved hook is for + // deterministic tests only: it must never request work from the GPU queue. + internal Action? BeforeManagedWriteReservationForTest; + internal Action? ManagedWriteReservedForTest; + + internal readonly ref struct ManagedWriteLease(GuestGpuMemory memory, ulong address, ulong size, + GuestWriteReservations.CpuAttempt? attempt, bool emulatorWrite) + { + public void Dispose() + { + if (memory is null || attempt?.Released == true) return; + try + { + // Include partial or failed copies: any page may have received new bytes. + memory.MarkManagedWriteParts(address, size, landed: true, emulatorWrite); + } + finally + { + attempt?.Dispose(); + } + } + } + + // emulatorWrite: the write goes through one backing view, so the stores take PrepareEmulatorWrite before it and + // NoteEmulatorWrite after it; otherwise MarkCpuWrite before and MarkCpuWriteLanded after. + internal ManagedWriteLease BeginManagedWrite(ulong address, ulong size, bool emulatorWrite = false) + { + var valid = address != 0 && size != 0 && new GuestSpan(address, size).IsValid; + for (var retry = 0; ; retry++) + { + GuestWriteReservations.CpuAttempt? attempt = valid ? _pages.ManagedWrites.BeginCpuAttempt(address, size) : null; + try + { + // Recovery can relay to the GPU; no reservation is held yet. + GuestImageWriteTracker.NotifyManagedWrite(address, size); + MarkManagedWriteParts(address, size, landed: false, emulatorWrite); + BeforeManagedWriteReservationForTest?.Invoke(retry); + if (attempt is { } activeAttempt && !activeAttempt.TryReserve()) + { + activeAttempt.Dispose(); + continue; + } + if (attempt is not null) ManagedWriteReservedForTest?.Invoke(); + return new ManagedWriteLease(this, address, size, attempt, emulatorWrite); + } + catch + { + attempt?.Dispose(); + throw; + } + } + } + + private void MarkManagedWriteParts(ulong address, ulong size, bool landed, bool emulatorWrite) + { + if (size == 0 || !new GuestSpan(address, size).IsValid) return; + var snapshot = Volatile.Read(ref _spanSnapshot) ?? throw new ObjectDisposedException(nameof(GuestGpuMemory)); + var lazy = Volatile.Read(ref _lazySnapshot); + if (snapshot.Contains(address, size) || lazy.Contains(address, size)) + { + MarkManagedWritePart(address, size, landed, emulatorWrite); + return; + } + + MarkPartialManagedWrite(snapshot, lazy, address, size, landed, emulatorWrite); + } + + private void MarkManagedWritePart(ulong address, ulong size, bool landed, bool emulatorWrite) + { + if (emulatorWrite) + { + if (landed) NoteEmulatorWrite(address, size); + else PrepareEmulatorWrite(address, size); + } + else if (landed) + { + MarkCpuWriteLanded(address, size); + } + else + { + _ = MarkCpuWrite(address, size); + } + } + + // Keep the callback closure off the common full-span path. Every intersection with a registered span or a lazily backed + // range matters; a part both cover is marked twice, which repeats the same conservative mark. + private void MarkPartialManagedWrite(SpanSnapshot snapshot, SpanSnapshot lazy, ulong address, ulong size, bool landed, + bool emulatorWrite) + { + // HostCallTrims.MarkClosureFree: the same overlap walk, its state passed in by value instead of a closure allocated + // for each call. + if (HostCallTrims.MarkClosureFree) + { + var state = (Memory: this, Landed: landed, Emulator: emulatorWrite); + snapshot.ForEachOverlap(address, size, state, + static (part, partAddress, partSize) => part.Memory.MarkManagedWritePart(partAddress, partSize, part.Landed, part.Emulator)); + lazy.ForEachOverlap(address, size, state, + static (part, partAddress, partSize) => part.Memory.MarkManagedWritePart(partAddress, partSize, part.Landed, part.Emulator)); + return; + } + + MarkPartialManagedWriteWithClosure(snapshot, lazy, address, size, landed, emulatorWrite); + } + + // A separate method: a lambda capturing a parameter allocates its closure on entry to the method that holds it. + private void MarkPartialManagedWriteWithClosure(SpanSnapshot snapshot, SpanSnapshot lazy, ulong address, ulong size, + bool landed, bool emulatorWrite) + { + void Visit(ulong partAddress, ulong partSize) => MarkManagedWritePart(partAddress, partSize, landed, emulatorWrite); + snapshot.ForEachOverlap(address, size, Visit); + lazy.ForEachOverlap(address, size, Visit); + } + public bool MarkCpuWrite(ulong address, ulong size) { diff --git a/src/SharpEmu.HLE/GpuMemory/GuestGpuMemoryHook.cs b/src/SharpEmu.HLE/GpuMemory/GuestGpuMemoryHook.cs index b0fd6f689..c6995fde0 100644 --- a/src/SharpEmu.HLE/GpuMemory/GuestGpuMemoryHook.cs +++ b/src/SharpEmu.HLE/GpuMemory/GuestGpuMemoryHook.cs @@ -180,6 +180,15 @@ public static bool TryResolveFault(FaultKind kind, ulong address) return false; } + // Capture the attached manager once, and hold its reservation through the landed notification. + internal static GuestGpuMemory.ManagedWriteLease BeginCpuWrite(ulong address, ulong size, bool emulatorWrite = false) + { + if (size == 0) return default; + if (_current is { } current) return current.BeginManagedWrite(address, size, emulatorWrite); + GuestImageWriteTracker.NotifyManagedWrite(address, size); + return default; + } + // Notify the stores before a managed write changes guest memory. public static void MarkCpuWrite(ulong address, ulong size) { diff --git a/src/SharpEmu.HLE/GpuMemory/GuestPageTracker.cs b/src/SharpEmu.HLE/GpuMemory/GuestPageTracker.cs index 6e992c71e..c17da4eb4 100644 --- a/src/SharpEmu.HLE/GpuMemory/GuestPageTracker.cs +++ b/src/SharpEmu.HLE/GpuMemory/GuestPageTracker.cs @@ -138,7 +138,9 @@ public bool MayHaveCpuDirtyPages(ulong vaddr, ulong size) while (remaining != 0) { var bytes = Math.Min(BlockBytes - offset, remaining); - if (Volatile.Read(ref _regions[index]) is not { } region || region.IsModified(WriteOrigin.Cpu, offset, bytes)) + // A clear summary bit means the block has no CPU-dirty page; IsKnownCpuClean trusts the same bit. + if (Volatile.Read(ref _regions[index]) is not { } region || + (_cpuDirtySummary.IsDirty(index) && region.IsModified(WriteOrigin.Cpu, offset, bytes))) { return true; } @@ -903,13 +905,19 @@ private static PageMask SpanPages(GuestSpan[] spans, ref int nextSpan, ulong blo return pages; } + // 64 blocks per step: a block is known clean when its region is present and its summary bit is clear. The present bit + // is set after the region is stored, so a clear one is at worst a region not seen yet. private bool IsKnownCpuClean(ulong vaddr, ulong size) { ValidateRange(vaddr, size); + var first = vaddr / BlockBytes; var last = (vaddr + size - 1) / BlockBytes; - for (var index = vaddr / BlockBytes; index <= last; index++) + for (var word = first / 64; word <= last / 64; word++) { - if (Volatile.Read(ref _regions[index]) == null || _cpuDirtySummary.IsDirty(index)) + var possiblyDirty = ~(ulong)Volatile.Read(ref _presentRegions[word]) | _cpuDirtySummary.Word((int)word); + var low = word == first / 64 ? (int)(first % 64) : 0; + var high = word == last / 64 ? (int)(last % 64) : 63; + if ((possiblyDirty & (ulong.MaxValue >> (63 - high)) & (ulong.MaxValue << low)) != 0) { return false; } diff --git a/src/SharpEmu.HLE/GpuMemory/GuestWriteReservations.cs b/src/SharpEmu.HLE/GpuMemory/GuestWriteReservations.cs new file mode 100644 index 000000000..086ef3c5f --- /dev/null +++ b/src/SharpEmu.HLE/GpuMemory/GuestWriteReservations.cs @@ -0,0 +1,640 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.InteropServices; + +namespace SharpEmu.HLE.GpuMemory; + +// Premark may relay to the GPU. Only the subsequent copy and landed notification reserve pages. +// Admission and validation share this gate; no store, copy or relay executes while it is held. +// +// A managed write inside one 2 MiB region takes no lock while no GPU claim covers the region, as almost every guest +// store does. Its reservation is an entry in the region's slot of a small table, published before it reads the slot's +// claim count; a GPU claim counts itself into the slots of its regions before it reads their entries, so either the +// write sees the claim or the claim sees the write. A write that meets a claim or a locked reservation in its region, +// spans regions or finds its slot full takes the locked path, under the same rules. A claim that began in the region +// while the write premarked is looked up in the history of recent claims, so only a claim over the write's own pages +// invalidates it, as on the locked path. +// +// Most guest stores go to memory that no GPU claim has ever covered, such as command buffers. A claim marks the 64 KiB +// chunks of its range for good. A write inside one region whose chunks are unmarked reserves its pages in its thread's +// own record instead of the shared slot table and then reads the marks again; a mark that appeared while the write +// premarked sends it on to the slot table, where the claim history decides whether it premarks again. The claim that +// marks a chunk first makes every thread either see the mark or show its record (Interlocked.MemoryBarrierProcessWide) +// and waits out every recorded write in the chunk. Writes on unmarked chunks do not exclude each other; each landed +// notification marks its pages again. +internal sealed class GuestWriteReservations +{ + private readonly object _gate = new(); + private readonly List _cpu = []; + private readonly List _gpu = []; + private long _nextClaim; + private long _nextCpuAttempt; + + private const int RegionShift = 21; + private const int SlotBits = 10; + private const int SlotCount = 1 << SlotBits; + private const int Ways = 4; + private const int HistorySize = 64; + // An entry being filled in: its range is not readable yet, so it counts as overlapping everything. + private const long Filling = -1; + private readonly Slot[] _slots = new Slot[SlotCount]; + private readonly long[] _entryTokens = new long[SlotCount * Ways]; + private readonly ulong[] _entryStarts = new ulong[SlotCount * Ways]; + private readonly ulong[] _entryEnds = new ulong[SlotCount * Ways]; + private readonly ClaimRecord[] _history = new ClaimRecord[HistorySize]; + private long _claimSequence; + + // One bit per 64 KiB chunk of the guest GPU address space that a GPU claim has covered. + private const int ChunkShift = 16; + private readonly long[] _claimedChunks = new long[(int)(TrackerLayout.SpaceBytes >> ChunkShift >> 6)]; + + // Each thread's reservation on unmarked chunks, shared by every owner: a thread reserves one write at a time. + private const int RecordCount = 1024; + private static readonly ThreadRecord[] s_records = new ThreadRecord[RecordCount]; + private static int s_recordsTaken; + + [ThreadStatic] private static FastAttempt? t_fast; + [ThreadStatic] private static uint t_tokens; + [ThreadStatic] private static List? t_lockedReserved; + + // Tests may only signal asynchronous continuations from these hooks, which run under the gate. + internal Action? GpuClaimWaitingForTest; + internal Action? CpuAttemptWaitingForTest; + private readonly record struct Claim(long Id, ulong Start, ulong End, int Thread); + private readonly record struct ClaimRecord(long Sequence, ulong Start, ulong End); + + private record struct CpuReservation(long Id, ulong Start, ulong End, int Thread) + { + internal bool Invalidated; + internal bool Reserved; + } + + // A region's GPU claims (begun and not released), its locked reservations and the count of claims begun in it. + [StructLayout(LayoutKind.Explicit, Size = 64)] + private struct Slot + { + [FieldOffset(0)] public int Claims; + [FieldOffset(4)] public int LockedReserved; + [FieldOffset(8)] public long Epoch; + } + + // Padded so that two threads' records never share a cache line. + [StructLayout(LayoutKind.Explicit, Size = 128)] + private struct ThreadRecord + { + [FieldOffset(64)] public long Token; + [FieldOffset(72)] public ulong Start; + [FieldOffset(80)] public ulong End; + [FieldOffset(88)] public GuestWriteReservations? Owner; + } + + // The thread's lock-free attempt. A thread holds at most one; a nested attempt takes the locked path. + private sealed class FastAttempt + { + public GuestWriteReservations? Owner; + public GuestWriteReservations? LockedNext; + public long Token; + public ulong Start; + public ulong End; + public int Slot; + public int Entry = -1; + // The thread's record, or -1 when every record is taken. + public readonly int Record = TakeRecord(); + public long Epoch; + public long Sequence; + public bool Active; + public bool Reserved; + public bool Invalidated; + public bool InRecord; + } + + private static int TakeRecord() + { + var index = Interlocked.Increment(ref s_recordsTaken) - 1; + return index < RecordCount ? index : -1; + } + + // A copied or stale token names only its original admission; a later write never reuses that id. Locked attempts + // have positive ids, lock-free ones the negated token of their thread. + internal readonly struct CpuAttempt(GuestWriteReservations owner, long id) : IDisposable + { + internal bool Released => owner is null || owner.IsReleased(id); + internal bool TryReserve() => owner is not null ? owner.TryReserve(id) + : throw new InvalidOperationException("The CPU write attempt is not available on this thread."); + public void Dispose() => owner?.Release(id); + } + + internal readonly struct GpuClaim(GuestWriteReservations owner, long id) : IDisposable + { + public void Dispose() => owner?.ReleaseGpu(id); + } + + internal CpuAttempt BeginCpuAttempt(ulong address, ulong size) + { + var (start, end) = Pages(address, size); + RejectFastReservedReentry(); + var fast = t_fast; + if (fast?.LockedNext == this) + { + fast.LockedNext = null; + } + else if (start >> RegionShift == (end - 1) >> RegionShift && fast is not { Active: true } && + t_lockedReserved is not { Count: > 0 }) + { + fast ??= t_fast = new FastAttempt(); + var slot = SlotOf(start >> RegionShift); + // Sequence, then the marks, then epoch, then the counts: a claim marks its chunks and counts itself into the + // slot before it advances the epoch and takes its sequence number. + var sequence = Volatile.Read(ref _claimSequence); + var inRecord = fast.Record >= 0 && ChunksUnmarked(start, end); + // An epoch no slot reaches: a write that leaves its record looks up every claim since the sequence. + var epoch = inRecord ? -1 : Volatile.Read(ref _slots[slot].Epoch); + if (inRecord || + (Volatile.Read(ref _slots[slot].Claims) == 0 && Volatile.Read(ref _slots[slot].LockedReserved) == 0)) + { + fast.Owner = this; + fast.Token = ((long)Environment.CurrentManagedThreadId << 32) | ++t_tokens; + fast.Start = start; + fast.End = end; + fast.Slot = slot; + fast.Entry = -1; + fast.Epoch = epoch; + fast.Sequence = sequence; + fast.Active = true; + fast.Reserved = false; + fast.Invalidated = false; + fast.InRecord = inRecord; + return new CpuAttempt(this, -fast.Token); + } + } + + return BeginLockedCpuAttempt(start, end); + } + + private CpuAttempt BeginLockedCpuAttempt(ulong start, ulong end) + { + var thread = Environment.CurrentManagedThreadId; + lock (_gate) + { + RejectReservedReentry(thread); + while (ReservedOverlap(start, end) || GpuOverlap(start, end, thread) || FastEntryOverlaps(start, end)) + { + CpuAttemptWaitingForTest?.Invoke(); + WaitForRelease(start, end, thread, cpu: true); + } + var id = checked(++_nextCpuAttempt); + _cpu.Add(new CpuReservation(id, start, end, thread)); + return new CpuAttempt(this, id); + } + } + + private bool TryReserve(long id) + { + if (id < 0) + { + return TryReserveFast(-id); + } + + lock (_gate) + { + for (var index = _cpu.Count - 1; index >= 0; index--) + { + var attempt = _cpu[index]; + if (attempt.Id != id) continue; + if (attempt.Reserved || attempt.Thread != Environment.CurrentManagedThreadId) + break; + if (attempt.Invalidated || ReservedOverlap(attempt.Start, attempt.End) || + GpuOverlap(attempt.Start, attempt.End, attempt.Thread)) + return false; + // Counted into the slots before the entries are read: a lock-free write that publishes later sees the count. + AddLockedReserved(attempt.Start, attempt.End, 1); + if (FastEntryOverlaps(attempt.Start, attempt.End)) + { + AddLockedReserved(attempt.Start, attempt.End, -1); + return false; + } + attempt.Reserved = true; + _cpu[index] = attempt; + (t_lockedReserved ??= []).Add(this); + return true; + } + throw new InvalidOperationException("The CPU write attempt is not available on this thread."); + } + } + + private bool TryReserveFast(long token) + { + var fast = t_fast; + if (fast is null || !fast.Active || fast.Owner != this || fast.Token != token || fast.Reserved) + throw new InvalidOperationException("The CPU write attempt is not available on this thread."); + if (fast.Invalidated) + return false; + + if (fast.InRecord) + { + ref var record = ref s_records[fast.Record]; + record.Owner = this; + record.Start = fast.Start; + record.End = fast.End; + Volatile.Write(ref record.Token, token); + // No fence: the claim that marks a chunk first makes this store visible before it reads the records. + if (ChunksUnmarked(fast.Start, fast.End)) + { + fast.Reserved = true; + return true; + } + + // A claim marked a chunk while the write premarked. + Volatile.Write(ref record.Token, 0); + fast.InRecord = false; + } + + var slot = fast.Slot; + var entry = -1; + for (var way = 0; way < Ways; way++) + { + var index = slot * Ways + way; + if (Volatile.Read(ref _entryTokens[index]) != 0 || + Interlocked.CompareExchange(ref _entryTokens[index], Filling, 0) != 0) + continue; + _entryStarts[index] = fast.Start; + _entryEnds[index] = fast.End; + // Published with a full fence, so the counts read below are not read before the entry is visible. + Interlocked.Exchange(ref _entryTokens[index], token); + entry = index; + break; + } + + if (entry < 0) + { + fast.LockedNext = this; + return false; + } + + if (Volatile.Read(ref _slots[slot].Claims) != 0 || Volatile.Read(ref _slots[slot].LockedReserved) != 0 || + OtherEntryOverlaps(slot, entry, fast.Start, fast.End)) + { + ClearEntry(entry); + fast.LockedNext = this; + return false; + } + + if (Volatile.Read(ref _slots[slot].Epoch) != fast.Epoch && ClaimBeganSince(fast.Sequence, fast.Start, fast.End)) + { + ClearEntry(entry); + fast.Invalidated = true; + return false; + } + + fast.Entry = entry; + fast.Reserved = true; + return true; + } + + // Enter before tracker/image/backing locks; retain the claim through its publication. + internal GpuClaim BeginGpuClaim(ulong address, ulong size) + { + if (size == 0) return default; + var (start, end) = Pages(address, size); + var thread = Environment.CurrentManagedThreadId; + RejectFastReservedReentry(); + lock (_gate) + { + RejectReservedReentry(thread); + // Marked before the sequence: a write that read the sequence before this claim took its number and then found + // the chunks unmarked looks the claim up in the history. + MarkChunks(start, end); + // Counted into the slots before the entries are read: a lock-free write that publishes later sees the count. + var walk = new SlotWalk(start, end); + while (walk.Next(out var slot)) + { + Interlocked.Increment(ref _slots[slot].Claims); + Interlocked.Increment(ref _slots[slot].Epoch); + } + var sequence = Interlocked.Increment(ref _claimSequence); + _history[sequence % HistorySize] = new ClaimRecord(sequence, start, end); + try + { + while (ReservedOverlap(start, end) || FastEntryOverlaps(start, end)) + { + GpuClaimWaitingForTest?.Invoke(); + WaitForRelease(start, end, thread, cpu: false); + } + } + catch + { + walk = new SlotWalk(start, end); + while (walk.Next(out var slot)) + { + Interlocked.Decrement(ref _slots[slot].Claims); + } + throw; + } + var id = unchecked(++_nextClaim); + if (id == 0) id = unchecked(++_nextClaim); + _gpu.Add(new Claim(id, start, end, thread)); + for (var index = 0; index < _cpu.Count; index++) + { + var attempt = _cpu[index]; + if (!Overlaps(start, end, attempt.Start, attempt.End)) continue; + attempt.Invalidated = true; + _cpu[index] = attempt; + } + return new GpuClaim(this, id); + } + } + + // Waits under the gate for a release. Locked reservations and claims pulse the gate when they are released, and the + // timeout bounds the wait should a pulse still be missed. A lock-free write holds its entry for one copy and releases it + // without the gate, so a wait on lock-free entries alone spins outside the gate until they clear. + private void WaitForRelease(ulong start, ulong end, int thread, bool cpu) + { + if (ReservedOverlap(start, end) || (cpu && GpuOverlap(start, end, thread))) + { + Monitor.Wait(_gate, 10); + return; + } + + Monitor.Exit(_gate); + try + { + var spin = new SpinWait(); + while (FastEntryOverlaps(start, end)) + { + spin.SpinOnce(sleep1Threshold: -1); + } + } + finally + { + Monitor.Enter(_gate); + } + } + + private void RejectFastReservedReentry() + { + if (t_fast is { Active: true, Reserved: true } fast && fast.Owner == this) + throw new InvalidOperationException("A reserved CPU writer cannot enter another premark or GPU claim."); + } + + private void RejectReservedReentry(int thread) + { + foreach (var attempt in _cpu) + if (attempt.Reserved && attempt.Thread == thread) + throw new InvalidOperationException("A reserved CPU writer cannot enter another premark or GPU claim."); + } + + private bool ReservedOverlap(ulong start, ulong end) + { + foreach (var attempt in _cpu) + if (attempt.Reserved && Overlaps(start, end, attempt.Start, attempt.End)) return true; + return false; + } + + // A GPU owner may perform a managed store inside its own claim, but not another thread's claim. + private bool GpuOverlap(ulong start, ulong end, int exceptThread) + { + foreach (var claim in _gpu) + if (claim.Thread != exceptThread && Overlaps(start, end, claim.Start, claim.End)) return true; + return false; + } + + // A lock-free reservation over the range. An entry replaced while it is read may give a mixed range; its new writer + // publishes after the caller's count and so finds that count itself. + private bool FastEntryOverlaps(ulong start, ulong end) + { + var walk = new SlotWalk(start, end); + while (walk.Next(out var slot)) + { + if (OtherEntryOverlaps(slot, -1, start, end)) return true; + } + return false; + } + + private bool OtherEntryOverlaps(int slot, int exceptEntry, ulong start, ulong end) + { + for (var way = 0; way < Ways; way++) + { + var index = slot * Ways + way; + if (index == exceptEntry) continue; + var token = Volatile.Read(ref _entryTokens[index]); + if (token == 0) continue; + if (token == Filling) return true; + if (Overlaps(start, end, Volatile.Read(ref _entryStarts[index]), Volatile.Read(ref _entryEnds[index]))) return true; + } + return false; + } + + // Marks the chunks of a claim's range. The claim that marks a chunk first waits until every thread either sees the + // mark or shows its record, and then until every recorded write in its chunks has released, over its own pages or + // not: a later claim over another page of a marked chunk reads no records. No write that begins afterwards reserves a + // marked chunk in its record. + private void MarkChunks(ulong start, ulong end) + { + var first = start >> ChunkShift; + var last = (end - 1) >> ChunkShift; + var marked = false; + for (var word = first >> 6; word <= last >> 6; word++) + { + var mask = ChunkMask(word, first, last); + if ((Volatile.Read(ref _claimedChunks[word]) & mask) == mask) continue; + Interlocked.Or(ref _claimedChunks[word], mask); + marked = true; + } + + if (!marked) return; + Interlocked.MemoryBarrierProcessWide(); + var spin = new SpinWait(); + while (RecordOverlaps(first << ChunkShift, (last + 1) << ChunkShift)) + { + GpuClaimWaitingForTest?.Invoke(); + spin.SpinOnce(sleep1Threshold: -1); + } + } + + private bool ChunksUnmarked(ulong start, ulong end) + { + var first = start >> ChunkShift; + var last = (end - 1) >> ChunkShift; + for (var word = first >> 6; word <= last >> 6; word++) + { + if ((Volatile.Read(ref _claimedChunks[word]) & ChunkMask(word, first, last)) != 0) return false; + } + return true; + } + + private static long ChunkMask(ulong word, ulong first, ulong last) + { + var low = word == first >> 6 ? (int)(first & 63) : 0; + var high = word == last >> 6 ? (int)(last & 63) : 63; + var bits = high - low + 1; + return bits == 64 ? -1L : (long)(((1UL << bits) - 1) << low); + } + + // A recorded write of this owner over the range. A record whose token changes while it is read is skipped: the write + // it named has released, and a write that shows its record only now reads the marks afterwards. + private bool RecordOverlaps(ulong start, ulong end) + { + var count = Math.Min(Volatile.Read(ref s_recordsTaken), RecordCount); + for (var index = 0; index < count; index++) + { + ref var record = ref s_records[index]; + var token = Volatile.Read(ref record.Token); + if (token == 0 || record.Owner != this || + !Overlaps(start, end, Volatile.Read(ref record.Start), Volatile.Read(ref record.End))) continue; + if (Volatile.Read(ref record.Token) == token) return true; + } + return false; + } + + // Whether a claim over the range began after the attempt read the sequence. When the history does not reach back to + // the attempt, the answer is yes. + private bool ClaimBeganSince(long sequence, ulong start, ulong end) + { + lock (_gate) + { + var current = _claimSequence; + if (current - sequence > HistorySize) return true; + for (var next = sequence + 1; next <= current; next++) + { + var record = _history[next % HistorySize]; + if (record.Sequence != next || Overlaps(start, end, record.Start, record.End)) return true; + } + return false; + } + } + + private void AddLockedReserved(ulong start, ulong end, int delta) + { + var walk = new SlotWalk(start, end); + while (walk.Next(out var slot)) + { + Interlocked.Add(ref _slots[slot].LockedReserved, delta); + } + } + + // Cleared after the copy's stores; a waiter on lock-free entries spins until it reads the entry free. + private void ClearEntry(int entry) => Volatile.Write(ref _entryTokens[entry], 0); + + private bool IsReleased(long id) + { + if (id < 0) + { + var fast = t_fast; + return fast is null || !fast.Active || fast.Owner != this || fast.Token != -id; + } + + lock (_gate) + { + foreach (var attempt in _cpu) + if (attempt.Id == id) return false; + return true; + } + } + + private void Release(long id) + { + if (id < 0) + { + var fast = t_fast; + if (fast is not { Active: true } || fast.Owner != this || fast.Token != -id) return; + fast.Active = false; + if (fast.Reserved) + { + fast.Reserved = false; + if (fast.InRecord) Volatile.Write(ref s_records[fast.Record].Token, 0); + else ClearEntry(fast.Entry); + } + fast.Entry = -1; + fast.InRecord = false; + return; + } + + lock (_gate) + { + for (var index = _cpu.Count - 1; index >= 0; index--) + { + var attempt = _cpu[index]; + if (attempt.Id != id) continue; + _cpu.RemoveAt(index); + if (attempt.Reserved) + { + AddLockedReserved(attempt.Start, attempt.End, -1); + t_lockedReserved?.Remove(this); + } + Monitor.PulseAll(_gate); + return; + } + } + } + + private void ReleaseGpu(long id) + { + lock (_gate) + { + for (var index = _gpu.Count - 1; index >= 0; index--) + { + var claim = _gpu[index]; + if (claim.Id != id) continue; + _gpu.RemoveAt(index); + var walk = new SlotWalk(claim.Start, claim.End); + while (walk.Next(out var slot)) + { + Interlocked.Decrement(ref _slots[slot].Claims); + } + Monitor.PulseAll(_gate); + return; + } + } + } + + private static int SlotOf(ulong region) => (int)((region * 0x9E3779B97F4A7C15UL) >> (64 - SlotBits)); + + // The slots of a page range's regions, one per region (two regions may share a slot); a range over more regions than + // there are slots visits every slot once. + private struct SlotWalk + { + private ulong _region; + private readonly ulong _last; + private readonly bool _every; + private int _index; + + public SlotWalk(ulong start, ulong end) + { + _region = start >> RegionShift; + _last = (end - 1) >> RegionShift; + _every = _last - _region >= SlotCount; + _index = 0; + } + + public bool Next(out int slot) + { + if (_every) + { + slot = _index; + return _index++ < SlotCount; + } + + if (_region > _last) + { + slot = 0; + return false; + } + + slot = SlotOf(_region++); + return true; + } + } + + private static bool Overlaps(ulong aStart, ulong aEnd, ulong bStart, ulong bEnd) => + aStart < bEnd && bStart < aEnd; + + private static (ulong Start, ulong End) Pages(ulong address, ulong size) + { + if (address == 0 || size == 0 || address >= TrackerLayout.SpaceBytes || + size > TrackerLayout.SpaceBytes - address) + throw new ArgumentOutOfRangeException(nameof(address), "The reservation must fit the guest GPU address space."); + return (address & ~(TrackerLayout.PageBytes - 1), + (address + size + TrackerLayout.PageBytes - 1) & ~(TrackerLayout.PageBytes - 1)); + } +} diff --git a/src/SharpEmu.HLE/GpuMemory/PageGuard.cs b/src/SharpEmu.HLE/GpuMemory/PageGuard.cs index 774d7998d..5bb13f822 100644 --- a/src/SharpEmu.HLE/GpuMemory/PageGuard.cs +++ b/src/SharpEmu.HLE/GpuMemory/PageGuard.cs @@ -141,6 +141,8 @@ public PageGuard(IGuestAddressSpace addressSpace) public CpuStackRanges Stacks { get; } = new(); + internal GuestWriteReservations ManagedWrites { get; } = new(); + public void Dispose() { foreach (var block in _blocks) diff --git a/src/SharpEmu.HLE/GpuMemory/SpanSet.cs b/src/SharpEmu.HLE/GpuMemory/SpanSet.cs index 2d3ec57c1..8e57bb937 100644 --- a/src/SharpEmu.HLE/GpuMemory/SpanSet.cs +++ b/src/SharpEmu.HLE/GpuMemory/SpanSet.cs @@ -7,7 +7,39 @@ public sealed class SpanSnapshot(ulong[] starts, ulong[] ends) { public static readonly SpanSnapshot Empty = new([], []); - public bool Contains(ulong address, ulong size) + internal ReadOnlySpan Starts => starts; + internal ReadOnlySpan Ends => ends; + // Contains remembers, per thread, the span of its last complete hit in a snapshot; SHARPEMU_SPAN_CONTAINS_CACHE=0 + // searches every query. + private static readonly bool CacheLastHit = Environment.GetEnvironmentVariable("SHARPEMU_SPAN_CONTAINS_CACHE") != "0"; + + [ThreadStatic] private static SpanSnapshot? _lastSnapshot; + [ThreadStatic] private static int _lastIndex; + + public bool Contains(ulong address, ulong size) => CacheLastHit + ? ContainsWithLastHit(address, size) + : ContainsUncached(address, size); + + internal bool ContainsWithLastHit(ulong address, ulong size) + { + // Snapshot identity includes mapping changes. Only a complete positive range can hit; a zero-sized or + // overflowing request gives the answer ContainsUncached gives. + if (ReferenceEquals(_lastSnapshot, this) && size != 0 && + address >= starts[_lastIndex] && address < ends[_lastIndex] && size <= ends[_lastIndex] - address) + return true; + + var index = Array.BinarySearch(starts, address); + if (index < 0) index = ~index - 1; + var contained = index >= 0 && ends[index] >= address + size; + if (contained && size != 0 && address < ends[index] && size <= ends[index] - address) + { + _lastIndex = index; + _lastSnapshot = this; + } + return contained; + } + + private bool ContainsUncached(ulong address, ulong size) { var index = Array.BinarySearch(starts, address); if (index < 0) @@ -18,6 +50,34 @@ public bool Contains(ulong address, ulong size) return index >= 0 && ends[index] >= address + size; } + // Immutable snapshot: callbacks may recover GPU data without holding the mapping lock. + internal void ForEachOverlap(ulong address, ulong size, Action visit) + { + var end = address + size; + var index = Array.BinarySearch(starts, address); + if (index < 0) index = Math.Max(0, ~index - 1); + for (; index < starts.Length && starts[index] < end; index++) + { + var first = Math.Max(address, starts[index]); + var last = Math.Min(end, ends[index]); + if (first < last) visit(first, last - first); + } + } + + // The walk above with its state passed to a static callback; the same overlaps, in the same order. + internal void ForEachOverlap(ulong address, ulong size, TState state, Action visit) + { + var end = address + size; + var index = Array.BinarySearch(starts, address); + if (index < 0) index = Math.Max(0, ~index - 1); + for (; index < starts.Length && starts[index] < end; index++) + { + var first = Math.Max(address, starts[index]); + var last = Math.Min(end, ends[index]); + if (first < last) visit(state, first, last - first); + } + } + public bool TryGetContaining(ulong address, out ulong start, out ulong end) { var index = Array.BinarySearch(starts, address); diff --git a/src/SharpEmu.HLE/HostCallTrims.cs b/src/SharpEmu.HLE/HostCallTrims.cs new file mode 100644 index 000000000..6fb0ea2a7 --- /dev/null +++ b/src/SharpEmu.HLE/HostCallTrims.cs @@ -0,0 +1,28 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.HLE; + +// Exact trims on the guest threads' host calls, each read at startup and on unless its variable is 0. +// - SHARPEMU_MARK_CLOSURE_FREE: a managed write that is not inside one GPU span walks its overlaps with its state passed +// by value, without allocating a closure for each mark. +// - SHARPEMU_MIXED_COPY_DIRECT: a guest copy between the backing and private memory that needs no commit or protection +// change copies in one call under the read lock instead of through 64 KiB staging pieces. +public static class HostCallTrims +{ + private static readonly bool MarkClosureFreeConfigured = + Environment.GetEnvironmentVariable("SHARPEMU_MARK_CLOSURE_FREE") != "0"; + + private static readonly bool MixedCopyConfigured = + Environment.GetEnvironmentVariable("SHARPEMU_MIXED_COPY_DIRECT") != "0"; + + // Tests: override the switches on this thread. + [ThreadStatic] + internal static bool? MarkClosureFreeOverrideForTests; + [ThreadStatic] + internal static bool? MixedCopyOverrideForTests; + + public static bool MarkClosureFree => MarkClosureFreeOverrideForTests ?? MarkClosureFreeConfigured; + + public static bool MixedCopyDirect => MixedCopyOverrideForTests ?? MixedCopyConfigured; +} diff --git a/src/SharpEmu.Libs/Agc/AgcExports.CommandPackets.cs b/src/SharpEmu.Libs/Agc/AgcExports.CommandPackets.cs index 2d439e832..8fca58dd3 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.CommandPackets.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.CommandPackets.cs @@ -341,12 +341,26 @@ public static int CbReleaseMem(CpuContext ctx) var cachePolicy = (uint)(ctx[CpuRegister.R8] & 0xFF); var destinationAddress = ctx[CpuRegister.R9]; var stackAddress = ctx[CpuRegister.Rsp]; - if (!TryReadUInt64(ctx, stackAddress + 8, out var dataSelectionRaw) || - !TryReadUInt64(ctx, stackAddress + 16, out var data) || - !TryReadUInt64(ctx, stackAddress + 24, out var gdsOffsetRaw) || - !TryReadUInt64(ctx, stackAddress + 32, out var gdsSizeRaw) || - !TryReadUInt64(ctx, stackAddress + 40, out var interruptRaw) || - !TryReadUInt64(ctx, stackAddress + 48, out var interruptContextIdRaw)) + ulong dataSelectionRaw, data, gdsOffsetRaw, gdsSizeRaw, interruptRaw, interruptContextIdRaw; + // AgcPacketWrites: the six stack words (Rsp + 8 to Rsp + 48) in one read of the same bytes; when it fails, the + // six reads below. + Span stackWords = stackalloc byte[6 * sizeof(ulong)]; + if (AgcPacketWrites.Active && stackAddress <= ulong.MaxValue - 7 * sizeof(ulong) && + ctx.Memory.TryRead(stackAddress + 8, stackWords)) + { + dataSelectionRaw = System.Buffers.Binary.BinaryPrimitives.ReadUInt64LittleEndian(stackWords); + data = System.Buffers.Binary.BinaryPrimitives.ReadUInt64LittleEndian(stackWords[8..]); + gdsOffsetRaw = System.Buffers.Binary.BinaryPrimitives.ReadUInt64LittleEndian(stackWords[16..]); + gdsSizeRaw = System.Buffers.Binary.BinaryPrimitives.ReadUInt64LittleEndian(stackWords[24..]); + interruptRaw = System.Buffers.Binary.BinaryPrimitives.ReadUInt64LittleEndian(stackWords[32..]); + interruptContextIdRaw = System.Buffers.Binary.BinaryPrimitives.ReadUInt64LittleEndian(stackWords[40..]); + } + else if (!TryReadUInt64(ctx, stackAddress + 8, out dataSelectionRaw) || + !TryReadUInt64(ctx, stackAddress + 16, out data) || + !TryReadUInt64(ctx, stackAddress + 24, out gdsOffsetRaw) || + !TryReadUInt64(ctx, stackAddress + 32, out gdsSizeRaw) || + !TryReadUInt64(ctx, stackAddress + 40, out interruptRaw) || + !TryReadUInt64(ctx, stackAddress + 48, out interruptContextIdRaw)) { return ReturnPointer(ctx, 0); } @@ -807,8 +821,12 @@ public static int DcbPushMarker(CpuContext ctx) { var commandBufferAddress = ctx[CpuRegister.Rdi]; var markerAddress = ctx[CpuRegister.Rsi]; + var atOnce = AgcPacketWrites.Active; + byte[] marker; if (commandBufferAddress == 0 || - !TryReadGuestCString(ctx, markerAddress, 4095, out var marker)) + !(atOnce + ? TryReadGuestCStringInChunks(ctx, markerAddress, 4095, out marker) + : TryReadGuestCString(ctx, markerAddress, 4095, out marker))) { return ReturnPointer(ctx, 0); } diff --git a/src/SharpEmu.Libs/Agc/AgcExports.DrawPackets.cs b/src/SharpEmu.Libs/Agc/AgcExports.DrawPackets.cs index 06a019f34..83f34a456 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.DrawPackets.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.DrawPackets.cs @@ -172,14 +172,8 @@ public static int DcbDrawIndirect(CpuContext ctx) } var modifierBits = (uint)drawModifier; - var shaderStage = modifierBits >> 29; - var scalarRegisterBase = shaderStage is 3 or 5 ? 0x10Cu : 0x8Cu; - var firstVertexRegister = (modifierBits & 1u) != 0 - ? scalarRegisterBase + ((modifierBits >> 9) & 0x1Fu) - : 0x280u; - var firstInstanceRegister = (modifierBits & 4u) != 0 - ? scalarRegisterBase + ((modifierBits >> 19) & 0x1Fu) - : 0x280u; + var firstVertexRegister = DrawModifierRegister(modifierBits, DrawModifierStartVertex, 9); + var firstInstanceRegister = DrawModifierRegister(modifierBits, DrawModifierStartInstance, 19); var drawInitiator = (drawModifier & (1UL << 32)) != 0 ? 2u : ((modifierBits >> 3) & 0x20u) | 2u; @@ -247,17 +241,9 @@ public static int DcbDrawIndexIndirect(CpuContext ctx) var dataOffset = (uint)ctx[CpuRegister.Rsi]; var modifier = ctx[CpuRegister.Rdx]; var modifierBits = (uint)modifier; - var shaderStage = modifierBits >> 29; - var scalarRegisterBase = shaderStage is 3 or 5 ? 0x10Cu : 0x8Cu; - ulong registerLocations = (modifierBits & 1u) != 0 - ? scalarRegisterBase + ((modifierBits >> 9) & 0x1Fu) : 0x280u; - var firstInstanceRegister = (modifierBits & 4u) != 0 - ? scalarRegisterBase + ((modifierBits >> 19) & 0x1Fu) : 0x280u; - registerLocations |= (ulong)firstInstanceRegister << 32; - if ((modifierBits & 2u) != 0) - { - registerLocations |= ((ulong)(scalarRegisterBase + ((modifierBits >> 14) & 0x1Fu)) << 16) | (1UL << 59); - } + // Only the multi draws have the CP write the draw index; a single draw's comes from the bound user data. + var registerLocations = DrawModifierRegister(modifierBits, DrawModifierStartVertex, 9) | + ((ulong)DrawModifierRegister(modifierBits, DrawModifierStartInstance, 19) << 32); // The API modifier selects register locations; it is not a packet initiator. var drawInitiator = (modifier & (1UL << 32)) != 0 @@ -283,7 +269,37 @@ public static int DcbDrawIndexIndirect(CpuContext ctx) ExportName = "sceAgcDcbDrawIndexIndirectMulti", Target = Generation.Gen5, LibraryName = "libSceAgc")] - public static int DcbDrawIndexIndirectMulti(CpuContext ctx) + public static int DcbDrawIndexIndirectMulti(CpuContext ctx) => + EmitDrawIndirectMulti(ctx, ItDrawIndexIndirectMulti, "agc.dcb_draw_index_indirect_multi"); + + [SysAbiExport( + Nid = "kUlvghKs-mA", + ExportName = "sceAgcDcbDrawIndirectMulti", + Target = Generation.Gen5, + LibraryName = "libSceAgc")] + public static int DcbDrawIndirectMulti(CpuContext ctx) => + EmitDrawIndirectMulti(ctx, ItDrawIndirectMulti, "agc.dcb_draw_indirect_multi"); + + private const uint DrawModifierStartVertex = 1u << 0; + private const uint DrawModifierStartInstance = 1u << 2; + private const uint DrawModifierDrawIndex = 1u << 3; + private const uint DrawModifierUserVgprs = 1u << 4; + + // The shader register of a user-data slot the modifier enables, as sce::Agc::get{VertexOffset,InstanceOffset, + // DrawIndex}UserDataSlot read it: five bits at slotShift, no slot when the modifier passes the values in VGPRs. + // Bits 29-31 name the frontmost stage; the hull stages' user data starts at 0x10C, the others' at 0x8C. + private static uint DrawModifierRegister(uint modifierBits, uint enable, int slotShift) + { + if ((modifierBits & (enable | DrawModifierUserVgprs)) != enable) + return 0x280u; + + var userData0 = (modifierBits >> 29) is 3 or 5 ? 0x10Cu : 0x8Cu; + return userData0 + ((modifierBits >> slotShift) & 0x1Fu); + } + + // Both multi draws take the same arguments and write the same ten-dword packet; the register the modifier names + // holds the base vertex of an indexed draw and the start vertex of the other. + private static int EmitDrawIndirectMulti(CpuContext ctx, uint opcode, string trace) { var commandBufferAddress = ctx[CpuRegister.Rdi]; var dataOffset = (uint)ctx[CpuRegister.Rsi]; @@ -296,21 +312,17 @@ public static int DcbDrawIndexIndirectMulti(CpuContext ctx) return ReturnPointer(ctx, 0); var modifierBits = (uint)modifier; - var shaderStage = modifierBits >> 29; - var scalarRegisterBase = shaderStage is 3 or 5 ? 0x10Cu : 0x8Cu; - ulong registerLocations = (modifierBits & 1u) != 0 - ? scalarRegisterBase + ((modifierBits >> 9) & 0x1Fu) : 0x280u; - var firstInstanceRegister = (modifierBits & 4u) != 0 - ? scalarRegisterBase + ((modifierBits >> 19) & 0x1Fu) : 0x280u; - registerLocations |= (ulong)firstInstanceRegister << 32; - if ((modifierBits & 2u) != 0) - registerLocations |= ((ulong)(scalarRegisterBase + ((modifierBits >> 14) & 0x1Fu)) << 16) | (1UL << 59); + var registerLocations = DrawModifierRegister(modifierBits, DrawModifierStartVertex, 9) | + ((ulong)DrawModifierRegister(modifierBits, DrawModifierStartInstance, 19) << 32); + var drawIndexRegister = DrawModifierRegister(modifierBits, DrawModifierDrawIndex, 24); + if (drawIndexRegister != 0x280u) + registerLocations |= ((ulong)drawIndexRegister << 16) | (1UL << 59); var drawInitiator = (modifier & (1UL << 32)) != 0 ? 2u : ((modifierBits >> 3) & 0x20u) | 2u; if (commandBufferAddress == 0 || !TryAllocateCommandDwords(ctx, commandBufferAddress, 10, out var commandAddress) || - !TryWriteUInt32(ctx, commandAddress, Pm4(10, ItDrawIndexIndirectMulti, 0)) || + !TryWriteUInt32(ctx, commandAddress, Pm4(10, opcode, 0)) || !TryWriteUInt32(ctx, commandAddress + 4, dataOffset) || !ctx.TryWriteUInt64(commandAddress + 8, registerLocations) || !TryWriteUInt32(ctx, commandAddress + 16, countFromMemory << 30) || @@ -323,7 +335,7 @@ public static int DcbDrawIndexIndirectMulti(CpuContext ctx) } TraceAgc( - $"agc.dcb_draw_index_indirect_multi buf=0x{commandBufferAddress:X16} " + + $"{trace} buf=0x{commandBufferAddress:X16} " + $"cmd=0x{commandAddress:X16} offset=0x{dataOffset:X8} draws={drawCount} " + $"stride={stride} modifier=0x{modifier:X8}"); return ReturnPointer(ctx, commandAddress); diff --git a/src/SharpEmu.Libs/Agc/AgcExports.SubmittedGeometry.cs b/src/SharpEmu.Libs/Agc/AgcExports.SubmittedGeometry.cs index 455ba14f8..6e39b1533 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.SubmittedGeometry.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.SubmittedGeometry.cs @@ -179,6 +179,15 @@ private static bool TryReadPacketUInt64(CpuContext ctx, ulong address, out ulong return indexSnapshots is { Count: > 0 } ? indexSnapshots : null; } + // AgcPacketWrites: the walk below with TryReadUInt32 serving the buffer's words from a copy loaded page by page as + // the walk reads them (a chained buffer gets its own copy at its depth). The walk writes no guest memory, so the + // copy holds what the word reads would return on this thread. A buffer that is too large or was walked already is + // walked with direct word reads. + [ThreadStatic] + private static byte[]?[]? _scanBuffers; + [ThreadStatic] + private static ulong[]?[]? _scanLoadedPages; + private static void CaptureSubmittedIndexPacketsCore( CpuContext ctx, ulong commandAddress, @@ -190,6 +199,67 @@ private static void CaptureSubmittedIndexPacketsCore( ref long retainedIndexBytes, ref long retainedVertexBytes, int depth) + { + byte[]? buffer = null; + ulong[]? loaded = null; + var bytes = (int)Math.Min(dwordCount, AgcPacketWrites.MaximumScanDwords) * sizeof(uint); + if (AgcPacketWrites.Active && commandAddress != 0 && dwordCount != 0 && dwordCount <= AgcPacketWrites.MaximumScanDwords && + depth <= 8 && commandAddress <= ulong.MaxValue - (ulong)bytes && !visited.Contains((commandAddress, dwordCount))) + { + var buffers = _scanBuffers ??= new byte[]?[9]; + var loadedPages = _scanLoadedPages ??= new ulong[]?[9]; + buffer = buffers[depth]; + if (buffer is null || buffer.Length < bytes) + { + buffer = new byte[Math.Max(bytes, ScanPageBytes)]; + buffers[depth] = buffer; + } + + // Pages the window overlaps, from the page holding its start: at most bytes / 4 KiB + 1. + var words = (bytes / ScanPageBytes + 2 + 63) / 64; + loaded = loadedPages[depth]; + if (loaded is null || loaded.Length < words) + { + loaded = new ulong[words]; + loadedPages[depth] = loaded; + } + else + { + Array.Clear(loaded, 0, words); + } + } + + if (buffer is null) + { + CaptureSubmittedIndexPacketsWalk(ctx, commandAddress, dwordCount, visited, indexSnapshots, vertexSnapshots, + captureState, ref retainedIndexBytes, ref retainedVertexBytes, depth); + return; + } + + var (outerWindow, outerStart, outerLength, outerLoaded) = (_scanWindow, _scanWindowStart, _scanWindowLength, _scanLoaded); + (_scanWindow, _scanWindowStart, _scanWindowLength, _scanLoaded) = (buffer, commandAddress, bytes, loaded); + try + { + CaptureSubmittedIndexPacketsWalk(ctx, commandAddress, dwordCount, visited, indexSnapshots, vertexSnapshots, + captureState, ref retainedIndexBytes, ref retainedVertexBytes, depth); + } + finally + { + (_scanWindow, _scanWindowStart, _scanWindowLength, _scanLoaded) = (outerWindow, outerStart, outerLength, outerLoaded); + } + } + + private static void CaptureSubmittedIndexPacketsWalk( + CpuContext ctx, + ulong commandAddress, + uint dwordCount, + HashSet<(ulong Address, uint Dwords)> visited, + Dictionary? indexSnapshots, + Dictionary? vertexSnapshots, + SubmittedDcbState captureState, + ref long retainedIndexBytes, + ref long retainedVertexBytes, + int depth) { if (commandAddress == 0 || dwordCount == 0 || depth > 8 || !visited.Add((commandAddress, dwordCount))) diff --git a/src/SharpEmu.Libs/Agc/AgcExports.cs b/src/SharpEmu.Libs/Agc/AgcExports.cs index c155b3a08..afc2d9535 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.cs @@ -33,6 +33,7 @@ public static partial class AgcExports private const uint ItDrawIndexMultiAuto = 0x30; private const uint ItDrawIndexOffset2 = 0x35; private const uint ItDrawIndexIndirectMulti = 0x38; + private const uint ItDrawIndirectMulti = 0x2C; private const uint DrawIndexedIndirectArgsSize = 20; private const uint DrawIndexedIndirectMaxScan = 1024; private const uint ItWriteData = 0x37; @@ -644,8 +645,55 @@ private static bool TryReadUInt16(CpuContext ctx, ulong address, out ushort valu return true; } + // AgcPacketWrites: the submitted command buffer the capture scan walks on this thread. TryReadUInt32 serves its + // words from a copy that is loaded one 4 KiB page at a time, when a word there is first read, so the walk touches + // the pages its word reads would. A page that cannot be loaded leaves its words to the ordinary read. + private const int ScanPageBytes = 4096; + [ThreadStatic] + private static byte[]? _scanWindow; + [ThreadStatic] + private static ulong _scanWindowStart; + [ThreadStatic] + private static int _scanWindowLength; + // One bit per 4 KiB page the window overlaps, from the page that holds its start: set once the page is in the copy. + [ThreadStatic] + private static ulong[]? _scanLoaded; + + private static bool TryLoadScanPages(CpuContext ctx, byte[] window, ulong address, int length) + { + var loaded = _scanLoaded!; + var firstPage = _scanWindowStart / ScanPageBytes; + var windowEnd = _scanWindowStart + (ulong)_scanWindowLength; + for (var page = address / ScanPageBytes; page <= (address + (ulong)length - 1) / ScanPageBytes; page++) + { + var index = (int)(page - firstPage); + if ((loaded[index >> 6] & (1UL << (index & 63))) != 0) + { + continue; + } + + var begin = Math.Max(_scanWindowStart, page * ScanPageBytes); + var end = Math.Min(windowEnd, (page + 1) * ScanPageBytes); + if (!ctx.Memory.TryRead(begin, window.AsSpan((int)(begin - _scanWindowStart), (int)(end - begin)))) + { + return false; + } + + loaded[index >> 6] |= 1UL << (index & 63); + } + + return true; + } + private static bool TryReadUInt32(CpuContext ctx, ulong address, out uint value) { + if (_scanWindow is { } window && address >= _scanWindowStart && address - _scanWindowStart < (ulong)_scanWindowLength && + _scanWindowLength - (int)(address - _scanWindowStart) >= sizeof(uint) && TryLoadScanPages(ctx, window, address, sizeof(uint))) + { + value = BinaryPrimitives.ReadUInt32LittleEndian(window.AsSpan((int)(address - _scanWindowStart))); + return true; + } + Span buffer = stackalloc byte[sizeof(uint)]; if (!ctx.Memory.TryRead(address, buffer)) { @@ -737,6 +785,67 @@ private static bool TryReadGuestCString( return false; } + // AgcPacketWrites: TryReadGuestCString with the bytes read up to 64 at a time, each chunk within one 4 KiB page, so + // it touches the pages the byte reads touch (those up to the terminator). From a chunk that cannot be read, it goes + // on byte by byte as there, so a name that ends just before unreadable memory gives the same result. + private static bool TryReadGuestCStringInChunks( + CpuContext ctx, + ulong address, + int maximumLength, + out byte[] bytes) + { + if (address == 0) + { + bytes = []; + return true; + } + + var values = new List(Math.Min(maximumLength, 128)); + Span chunk = stackalloc byte[64]; + var index = 0; + while (index < maximumLength) + { + var at = address + (ulong)index; + var toPageEnd = ScanPageBytes - (int)(at % ScanPageBytes); + var piece = chunk[..Math.Min(Math.Min(chunk.Length, maximumLength - index), toPageEnd)]; + if (address > ulong.MaxValue - (ulong)maximumLength || !ctx.Memory.TryRead(at, piece)) + { + break; + } + + var end = piece.IndexOf((byte)0); + if (end >= 0) + { + values.AddRange(piece[..end]); + bytes = [.. values]; + return true; + } + + values.AddRange(piece); + index += piece.Length; + } + + for (; index < maximumLength; index++) + { + if (!TryReadByte(ctx, address + (ulong)index, out var value)) + { + bytes = []; + return false; + } + + if (value == 0) + { + bytes = [.. values]; + return true; + } + + values.Add(value); + } + + bytes = []; + return false; + } + private static bool ShouldTraceHotPath(ref long counter) { var count = Interlocked.Increment(ref counter); diff --git a/src/SharpEmu.Libs/Agc/AgcPacketWrites.cs b/src/SharpEmu.Libs/Agc/AgcPacketWrites.cs new file mode 100644 index 000000000..6752cc98b --- /dev/null +++ b/src/SharpEmu.Libs/Agc/AgcPacketWrites.cs @@ -0,0 +1,27 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Libs.Agc; + +// Fewer guest memory reads in the AGC emitters (SHARPEMU_AGC_PACKET_WRITES=0 turns them off): +// - Marker names are read in chunks within a page. +// - A release reads its six stack words in one read. +// - The submitted command scan uses a copy loaded a page at a time. +// Register ranges always use the ordinary marker allocation/write, packet allocation/header and payload-copy sequence. +// Push markers retain ordinary allocation/header/name-word writes after name resolution. There is no combined packet +// write, cursor rollback or speculative write followed by replay in either emitter. +// The retained read optimizations have separate input-stability and read-effect contracts. +internal static class AgcPacketWrites +{ + internal static readonly bool Configured = + Environment.GetEnvironmentVariable("SHARPEMU_AGC_PACKET_WRITES") != "0"; + + // Tests: overrides the switch on this thread. + [ThreadStatic] + internal static bool? OverrideForTests; + + internal static bool Active => OverrideForTests ?? Configured; + + // The largest submitted command buffer the scan reads at once. + internal const uint MaximumScanDwords = 1u << 18; +} diff --git a/src/SharpEmu.Libs/Ampr/AmprExports.Amm.cs b/src/SharpEmu.Libs/Ampr/AmprExports.Amm.cs new file mode 100644 index 000000000..bda20831a --- /dev/null +++ b/src/SharpEmu.Libs/Ampr/AmprExports.Amm.cs @@ -0,0 +1,451 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using SharpEmu.Libs.Kernel; +using System.Buffers.Binary; + +namespace SharpEmu.Libs.Ampr; + +// AMM, the AMPR memory manager. A title gives AMM direct memory and maps it into the AMM area with +// command buffers. The commands run when their buffer is submitted, in buffer order with the buffer's +// other commands. Auto memory is handed out by page, so one map can take several physical runs. +public static partial class AmprExports +{ + // The AMM area lies inside the guest user range that the GPU trackers cover. A title sizes its own + // allocator from the range it is given. + private const ulong AmmAreaStart = 0x80_0000_0000UL; + private const ulong AmmAreaEnd = 0xFC_0000_0000UL; + private const ulong AmmPageSize = 0x4000; + private const ulong AmmGiveGranularity = 0x20_0000; + private const ulong AmmRecordSize = 0x20; + private const uint AmmMapRecordType = 1; + private const uint AmmUnmapRecordType = 2; + private const int AmmUsageDirect = 0; + private const int AmmUsageAuto = 1; + private const ulong AmmMapFixed = 0x10; + private const int KernelEperm = unchecked((int)0x80020001); + private const int KernelEfault = unchecked((int)0x8002000E); + private const int KernelEbusy = unchecked((int)0x80020010); + private const int KernelEinval = unchecked((int)0x80020016); + private const int KernelEagain = unchecked((int)0x80020023); + private static readonly object _ammGate = new(); + // Free auto pages and the mapped runs, both sorted by start. + private static readonly List<(ulong Offset, ulong Length)> _ammFreePages = []; + private static readonly List<(ulong Address, ulong Length, ulong Offset)> _ammMappings = []; + private static bool _ammAreaReserved; + private static ulong _ammAddressSlot; + + private sealed class AmmCommand + { + public ulong RecordOffset; + public bool Unmap; + public ulong Address; + public ulong Size; + public int Protection; + } + + [SysAbiExport( + Nid = "wkQR9+xTFKY", + ExportName = "sceAmprAmmGetVirtualAddressRanges", + Target = Generation.Gen5, + LibraryName = "libSceAmpr")] + public static int AmmGetVirtualAddressRanges(CpuContext ctx) + { + // The multimap range sits at the end of the area and is empty, as it is by default. + var ranges = ctx[CpuRegister.Rdi]; + if (ranges != 0) + { + _ = ctx.TryWriteUInt64(ranges, AmmAreaStart) && + ctx.TryWriteUInt64(ranges + 0x08, AmmAreaEnd) && + ctx.TryWriteUInt64(ranges + 0x10, AmmAreaEnd) && + ctx.TryWriteUInt64(ranges + 0x18, AmmAreaEnd); + } + + _ = TryReserveAmmArea(ctx); + return SetAmmResult(ctx, 0); + } + + [SysAbiExport( + Nid = "Q07J7XpvhrU", + ExportName = "sceAmprAmmGiveDirectMemory", + Target = Generation.Gen5, + LibraryName = "libSceAmpr")] + public static int AmmGiveDirectMemory(CpuContext ctx) + { + var searchStart = ctx[CpuRegister.Rdi]; + var searchEnd = ctx[CpuRegister.Rsi]; + var size = ctx[CpuRegister.Rdx]; + var alignment = ctx[CpuRegister.Rcx]; + var usage = unchecked((int)ctx[CpuRegister.R8]); + var offsetOut = ctx[CpuRegister.R9]; + if (size == 0 || size % AmmGiveGranularity != 0 || alignment % AmmGiveGranularity != 0 || + usage is not (AmmUsageDirect or AmmUsageAuto)) + { + return SetAmmResult(ctx, KernelEinval); + } + + if (offsetOut == 0) + { + return SetAmmResult(ctx, KernelEfault); + } + + if (!TryReserveAmmArea(ctx)) + { + return SetAmmResult(ctx, KernelEbusy); + } + + // The pages come out of the title's direct memory. + var result = KernelMemoryCompatExports.InvokeKernelMemoryOperation( + ctx, + KernelMemoryCompatExports.KernelAllocateDirectMemory, + searchStart, + searchEnd, + size, + alignment == 0 ? AmmGiveGranularity : alignment, + 0, + offsetOut); + if (result != 0) + { + return SetAmmResult(ctx, result == (int)OrbisGen2Result.ORBIS_GEN2_ERROR_TRY_AGAIN ? KernelEagain : result); + } + + if (!ctx.TryReadUInt64(offsetOut, out var offset)) + { + return SetAmmResult(ctx, KernelEfault); + } + + if (usage == AmmUsageAuto) + { + lock (_ammGate) + { + ReleaseAmmPagesLocked(offset, size); + } + } + + TraceAmpr(ctx, "amm_give", offset, size, (ulong)usage); + return SetAmmResult(ctx, 0); + } + + [SysAbiExport( + Nid = "JEVYGhDc97M", + ExportName = "sceAmprAmmCommandBufferMap", + Target = Generation.Gen5, + LibraryName = "libSceAmpr")] + public static int AmmCommandBufferMap(CpuContext ctx) => + AppendAmmCommand(ctx, unmap: false, ctx[CpuRegister.Rsi], ctx[CpuRegister.Rdx], unchecked((int)ctx[CpuRegister.R8])); + + [SysAbiExport( + Nid = "M-VFI2DJWQA", + ExportName = "sceAmprAmmCommandBufferUnmap", + Target = Generation.Gen5, + LibraryName = "libSceAmpr")] + public static int AmmCommandBufferUnmap(CpuContext ctx) => + AppendAmmCommand(ctx, unmap: true, ctx[CpuRegister.Rsi], ctx[CpuRegister.Rdx], 0); + + [SysAbiExport( + Nid = "lwS-7y3jcBI", + ExportName = "sceAmprAmmSubmitCommandBuffer", + Target = Generation.Gen5, + LibraryName = "libSceAmpr")] + public static int AmmSubmitCommandBuffer(CpuContext ctx) + { + // The entry takes the buffer the commands were written to, the bytes written and the priority. + var commandBuffer = ctx[CpuRegister.Rdi]; + var priority = unchecked((uint)ctx[CpuRegister.Rdx]); + if (commandBuffer == 0 || priority > 2) + { + return SetAmmResult(ctx, KernelEinval); + } + + var result = SubmitCommandBuffer( + ctx, + commandBuffer, + AmprEngine.Amm, + priority, + (_, executionResult, errorOffset) => ReportAmmFailure(commandBuffer, executionResult, errorOffset), + out var submission); + if (result != (int)OrbisGen2Result.ORBIS_GEN2_OK) + { + return SetAmmResult(ctx, result); + } + + if (submission!.CompletedInline) + { + ReportAmmFailure(commandBuffer, submission.ExecutionResult, submission.ErrorOffset); + } + + return SetAmmResult(ctx, 0); + } + + // On hardware a failed command ends the application; here it is reported and the buffer stops. + private static void ReportAmmFailure(ulong commandBuffer, int executionResult, uint errorOffset) + { + if (executionResult != (int)OrbisGen2Result.ORBIS_GEN2_OK) + { + Console.Error.WriteLine( + $"[LOADER][ERROR] ampr.amm command failed: buffer=0x{commandBuffer:X16} offset=0x{errorOffset:X} result=0x{executionResult:X8}"); + } + } + + private static int AppendAmmCommand(CpuContext ctx, bool unmap, ulong address, ulong size, int protection) + { + var commandBuffer = ctx[CpuRegister.Rdi]; + if (commandBuffer == 0 || size == 0 || address % AmmPageSize != 0 || size % AmmPageSize != 0 || + address < AmmAreaStart || address >= AmmAreaEnd || size > AmmAreaEnd - address) + { + return SetAmmResult(ctx, KernelEinval); + } + + if (!TryGetCommandBufferState(ctx, commandBuffer, out var buffer, out _, out var state) || state is null) + { + return SetAmmResult(ctx, KernelEfault); + } + + if (buffer == 0) + { + return SetAmmResult(ctx, KernelEperm); + } + + Span record = stackalloc byte[(int)AmmRecordSize]; + record.Clear(); + BinaryPrimitives.WriteUInt32LittleEndian(record, unmap ? AmmUnmapRecordType : AmmMapRecordType); + BinaryPrimitives.WriteUInt32LittleEndian(record[0x04..], unchecked((uint)protection)); + BinaryPrimitives.WriteUInt64LittleEndian(record[0x08..], address); + BinaryPrimitives.WriteUInt64LittleEndian(record[0x10..], size); + ulong recordOffset; + lock (state) + { + recordOffset = state.WriteOffset; + } + + if (!AppendCommandBufferRecord(ctx, commandBuffer, record)) + { + return SetAmmResult(ctx, KernelEbusy); + } + + lock (state) + { + state.AmmCommands.Add(new AmmCommand + { + RecordOffset = recordOffset, + Unmap = unmap, + Address = address, + Size = size, + Protection = protection, + }); + } + + TraceAmpr(ctx, unmap ? "amm_unmap" : "amm_map", commandBuffer, address, size); + return SetAmmResult(ctx, 0); + } + + private static int ExecuteAmmCommand(CpuContext ctx, AmmCommand command) + { + lock (_ammGate) + { + if (!TryReserveAmmArea(ctx)) + { + return KernelEbusy; + } + + // A map over mapped pages replaces them, so both commands first return the range to the area. + var result = ReleaseAmmRangeLocked(ctx, command.Address, command.Size); + if (result != 0 || command.Unmap) + { + return result; + } + + if (!TryTakeAmmPagesLocked(command.Size, out var runs)) + { + return KernelEagain; + } + + var address = command.Address; + for (var i = 0; i < runs.Count; i++) + { + var (offset, length) = runs[i]; + result = ctx.TryWriteUInt64(_ammAddressSlot, address) + ? KernelMemoryCompatExports.InvokeKernelMemoryOperation( + ctx, + KernelMemoryCompatExports.KernelMapDirectMemory, + _ammAddressSlot, + length, + unchecked((ulong)(uint)command.Protection), + AmmMapFixed, + offset, + 0) + : KernelEfault; + if (result != 0) + { + for (var j = i; j < runs.Count; j++) + { + ReleaseAmmPagesLocked(runs[j].Offset, runs[j].Length); + } + + _ = ReleaseAmmRangeLocked(ctx, command.Address, address - command.Address); + return result; + } + + InsertAmmMappingLocked(address, length, offset); + address += length; + } + + return 0; + } + } + + // The range becomes reserved AMM area again and its pages go back to the pool. + private static int ReleaseAmmRangeLocked(CpuContext ctx, ulong address, ulong size) + { + if (size == 0) + { + return 0; + } + + var end = address + size; + var first = _ammMappings.FindIndex(mapping => mapping.Address + mapping.Length > address); + if (first < 0 || _ammMappings[first].Address >= end) + { + return 0; + } + + var result = ctx.TryWriteUInt64(_ammAddressSlot, address) + ? KernelMemoryCompatExports.ReserveBackingRange(ctx, _ammAddressSlot, size, AmmMapFixed, 0) + : KernelEfault; + if (result != 0) + { + return result; + } + + while (first < _ammMappings.Count && _ammMappings[first].Address < end) + { + var (mappedAddress, length, offset) = _ammMappings[first]; + _ammMappings.RemoveAt(first); + var mappedEnd = mappedAddress + length; + var cutStart = Math.Max(mappedAddress, address); + var cutEnd = Math.Min(mappedEnd, end); + ReleaseAmmPagesLocked(offset + (cutStart - mappedAddress), cutEnd - cutStart); + if (mappedAddress < cutStart) + { + _ammMappings.Insert(first++, (mappedAddress, cutStart - mappedAddress, offset)); + } + + if (cutEnd < mappedEnd) + { + _ammMappings.Insert(first++, (cutEnd, mappedEnd - cutEnd, offset + (cutEnd - mappedAddress))); + } + } + + return 0; + } + + private static void InsertAmmMappingLocked(ulong address, ulong length, ulong offset) + { + var index = _ammMappings.FindIndex(mapping => mapping.Address > address); + _ammMappings.Insert(index < 0 ? _ammMappings.Count : index, (address, length, offset)); + } + + private static bool TryTakeAmmPagesLocked(ulong size, out List<(ulong Offset, ulong Length)> runs) + { + runs = []; + var remaining = size; + for (var i = 0; i < _ammFreePages.Count && remaining != 0; i++) + { + runs.Add((_ammFreePages[i].Offset, Math.Min(_ammFreePages[i].Length, remaining))); + remaining -= runs[^1].Length; + } + + if (remaining != 0) + { + runs.Clear(); + return false; + } + + foreach (var (_, length) in runs) + { + var (freeOffset, freeLength) = _ammFreePages[0]; + if (length == freeLength) + { + _ammFreePages.RemoveAt(0); + } + else + { + _ammFreePages[0] = (freeOffset + length, freeLength - length); + } + } + + return true; + } + + private static void ReleaseAmmPagesLocked(ulong offset, ulong length) + { + if (length == 0) + { + return; + } + + var index = _ammFreePages.FindIndex(run => run.Offset > offset); + if (index < 0) + { + index = _ammFreePages.Count; + } + + _ammFreePages.Insert(index, (offset, length)); + if (index + 1 < _ammFreePages.Count && offset + length == _ammFreePages[index + 1].Offset) + { + _ammFreePages[index] = (offset, length + _ammFreePages[index + 1].Length); + _ammFreePages.RemoveAt(index + 1); + } + + if (index > 0 && _ammFreePages[index - 1].Offset + _ammFreePages[index - 1].Length == offset) + { + _ammFreePages[index - 1] = (_ammFreePages[index - 1].Offset, _ammFreePages[index - 1].Length + _ammFreePages[index].Length); + _ammFreePages.RemoveAt(index); + } + } + + // The area is reserved at the first AMM call, before the title maps anything into it. + // The AMM area is GPU memory a title maps piece by piece: a streamed texture's descriptor covers its whole mip + // chain while only the resident levels are mapped, and its minimum LOD keeps sampling on those. The pages of the + // area that are not mapped read as zeros, as in a PRT aperture. + internal static bool ContainsAmmRange(ulong address, ulong size) => + Volatile.Read(ref _ammAreaReserved) && size != 0 && address >= AmmAreaStart && address < AmmAreaEnd && + size <= AmmAreaEnd - address; + + private static bool TryReserveAmmArea(CpuContext ctx) + { + lock (_ammGate) + { + if (_ammAreaReserved) + { + return true; + } + + if (_ammAddressSlot == 0 && + !KernelMemoryCompatExports.TryAllocateHleData(ctx, sizeof(ulong), sizeof(ulong), out _ammAddressSlot)) + { + return false; + } + + var result = ctx.TryWriteUInt64(_ammAddressSlot, AmmAreaStart) + ? KernelMemoryCompatExports.ReserveBackingRange(ctx, _ammAddressSlot, AmmAreaEnd - AmmAreaStart, AmmMapFixed, 0) + : KernelEfault; + if (result != 0) + { + Console.Error.WriteLine( + $"[LOADER][ERROR] ampr.amm area reservation failed: 0x{AmmAreaStart:X16}+0x{AmmAreaEnd - AmmAreaStart:X} result=0x{result:X8}"); + return false; + } + + _ammAreaReserved = true; + return true; + } + } + + private static int SetAmmResult(CpuContext ctx, int result) + { + ctx[CpuRegister.Rax] = unchecked((ulong)(long)result); + return result; + } +} diff --git a/src/SharpEmu.Libs/Ampr/AmprExports.Queues.cs b/src/SharpEmu.Libs/Ampr/AmprExports.Queues.cs new file mode 100644 index 000000000..b22b233d3 --- /dev/null +++ b/src/SharpEmu.Libs/Ampr/AmprExports.Queues.cs @@ -0,0 +1,148 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using System.Collections.Concurrent; +using System.Threading; + +namespace SharpEmu.Libs.Ampr; + +public static partial class AmprExports +{ + internal enum AmprEngine + { + Apr, + Amm, + } + + private static readonly ConcurrentDictionary<(AmprEngine Engine, uint Priority), CommandQueue> _commandQueues = new(); + + // Submits a buffer to the queue of its engine and priority. The submission completes when the buffer has run. + // onQueuedCompletion runs only for a buffer that finished on the queue's thread, with that thread's context. + internal static int SubmitCommandBuffer( + CpuContext ctx, + ulong commandBuffer, + AmprEngine engine, + uint priority, + Action? onQueuedCompletion, + out AmprSubmission? submission) + { + submission = null; + var status = TryCaptureCommands(ctx, commandBuffer, out var captured); + if (status != (int)OrbisGen2Result.ORBIS_GEN2_OK) + { + return status; + } + + var queue = _commandQueues.GetOrAdd( + (engine, priority), + static key => new CommandQueue($"SharpEmu-AMPR {key.Engine} {key.Priority}")); + submission = queue.Submit(ctx, captured!, onQueuedCompletion); + return (int)OrbisGen2Result.ORBIS_GEN2_OK; + } + + internal sealed class AmprSubmission + { + private readonly ManualResetEventSlim _completed = new(); + + public int ExecutionResult { get; private set; } + + public uint ErrorOffset { get; private set; } + + // The buffer ran on the thread that submitted it, before the submission returned. + public bool CompletedInline { get; private set; } + + public bool IsCompleted => _completed.IsSet; + + public void Wait() => _completed.Wait(); + + public bool Wait(TimeSpan timeout) => _completed.Wait(timeout); + + internal void Complete(int executionResult, uint errorOffset, bool inline) + { + ExecutionResult = executionResult; + ErrorOffset = errorOffset; + CompletedInline = inline; + _completed.Set(); + } + } + + // The AMPR engine runs the buffers of one queue in order, and a buffer that waits for an address holds the queue, + // not the thread that submitted it: titles submit reads that wait for work they submit later. A buffer runs on the + // submitting thread while the queue is idle and every wait it reaches is already met. From the first wait that is + // not, the rest of it and every later buffer of the queue run in order on the queue's own thread. + private sealed class CommandQueue(string name) + { + private readonly object _gate = new(); + private readonly Queue _pending = new(); + private Thread? _worker; + + public AmprSubmission Submit(CpuContext ctx, CapturedCommands captured, Action? onQueuedCompletion) + { + var submission = new AmprSubmission(); + lock (_gate) + { + var next = 0; + if (_pending.Count == 0 && + RunCommands(ctx, captured, ref next, stopAtUnmetWait: true, out var executionResult, out var errorOffset)) + { + submission.Complete(executionResult, errorOffset, inline: true); + return submission; + } + + // The submitting thread goes on using its context, so the queue's thread gets its own. + var context = new CpuContext(ctx.Memory, ctx.TargetGeneration) + { + FsBase = ctx.FsBase, + GsBase = ctx.GsBase, + }; + _pending.Enqueue(new QueuedRun(context, captured, next, onQueuedCompletion, submission)); + if (_worker is null) + { + _worker = new Thread(Drain) { IsBackground = true, Name = name }; + _worker.Start(); + } + else + { + Monitor.Pulse(_gate); + } + } + + return submission; + } + + private void Drain() + { + while (true) + { + QueuedRun run; + lock (_gate) + { + while (_pending.Count == 0) + { + Monitor.Wait(_gate); + } + + run = _pending.Peek(); + } + + // The run stays queued until it ends, so a buffer submitted meanwhile queues behind it. + var next = run.Next; + RunCommands(run.Context, run.Commands, ref next, stopAtUnmetWait: false, out var executionResult, out var errorOffset); + run.OnQueuedCompletion?.Invoke(run.Context, executionResult, errorOffset); + run.Submission.Complete(executionResult, errorOffset, inline: false); + lock (_gate) + { + _pending.Dequeue(); + } + } + } + } + + private sealed record QueuedRun( + CpuContext Context, + CapturedCommands Commands, + int Next, + Action? OnQueuedCompletion, + AmprSubmission Submission); +} diff --git a/src/SharpEmu.Libs/Ampr/AmprExports.cs b/src/SharpEmu.Libs/Ampr/AmprExports.cs index 419b0f69f..777a09758 100644 --- a/src/SharpEmu.Libs/Ampr/AmprExports.cs +++ b/src/SharpEmu.Libs/Ampr/AmprExports.cs @@ -13,7 +13,7 @@ namespace SharpEmu.Libs.Ampr; -public static class AmprExports +public static partial class AmprExports { private const int CommandBufferHeaderSize = 0x18; private const ulong CommandBufferTypeOffset = 0x00; @@ -37,6 +37,7 @@ public static class AmprExports private const ulong AprMaxAppAddress = 0x0000f00000000000; private const ulong KernelEventQueueRecordSize = 0x20; private const ulong WriteAddressRecordSize = 0x20; + private const ulong MarkerRecordSize = 0x40; private const ulong WaitAddressRecordSizeWithoutReference = 0x08; private const ulong WaitAddressRecordSizeWith32BitReference = 0x0C; private const ulong WaitAddressRecordSizeWith64BitReference = 0x10; @@ -61,6 +62,7 @@ private sealed class CommandBufferState public readonly List KernelEventCommands = []; public readonly List WriteAddressCommands = []; public readonly List WaitAddressCommands = []; + public readonly List AmmCommands = []; public bool GatherScatterValid; public uint GatherScatterFileId; public ulong GatherScatterDestination; @@ -688,6 +690,55 @@ public static int CommandBufferGetCurrentOffset(CpuContext ctx) return (int)OrbisGen2Result.ORBIS_GEN2_OK; } + [SysAbiExport( + Nid = "RPCAhx-aabE", + ExportName = "sceAmprCommandBufferGetBufferBaseAddress", + Target = Generation.Gen5, + LibraryName = "libSceAmpr")] + public static int CommandBufferGetBufferBaseAddress(CpuContext ctx) + { + var commandBuffer = ctx[CpuRegister.Rdi]; + if (commandBuffer == 0) + { + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT; + } + + if (!TryGetCommandBufferState(ctx, commandBuffer, out var buffer, out _, out _)) + { + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT; + } + + TraceAmpr(ctx, "get_buffer_base", commandBuffer, buffer, 0); + ctx[CpuRegister.Rax] = buffer; + return (int)OrbisGen2Result.ORBIS_GEN2_OK; + } + + // A marker only feeds the trace: it takes the place of one no-op record and does nothing when it runs. + [SysAbiExport( + Nid = "4quckD2y7Pg", + ExportName = "sceAmprCommandBufferSetMarker", + Target = Generation.Gen5, + LibraryName = "libSceAmpr")] + public static int CommandBufferSetMarker(CpuContext ctx) + { + var commandBuffer = ctx[CpuRegister.Rdi]; + if (commandBuffer == 0) + { + return SetAmprResult(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT); + } + + Span record = stackalloc byte[(int)MarkerRecordSize]; + record.Clear(); + if (!AppendCommandBufferRecord(ctx, commandBuffer, record)) + { + return SetAmprResult(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_BUSY); + } + + TraceAmpr(ctx, "set_marker", commandBuffer, ctx[CpuRegister.Rsi], 0); + ctx[CpuRegister.Rax] = 0; + return (int)OrbisGen2Result.ORBIS_GEN2_OK; + } + [SysAbiExport( Nid = "gzndltBEzWc", ExportName = "sceAmprCommandBufferGetNumCommands", @@ -882,7 +933,34 @@ public static int CompleteCommandBuffer( { executionResult = (int)OrbisGen2Result.ORBIS_GEN2_OK; errorOffset = 0; + var status = TryCaptureCommands(ctx, commandBuffer, out var captured); + if (status != (int)OrbisGen2Result.ORBIS_GEN2_OK) + { + return status; + } + + var next = 0; + RunCommands(ctx, captured!, ref next, stopAtUnmetWait: false, out executionResult, out errorOffset); + return (int)OrbisGen2Result.ORBIS_GEN2_OK; + } + + // The commands of a buffer as they were when it was submitted, in record order. + private sealed class CapturedCommands + { + public required ulong CommandBuffer { get; init; } + public required ulong Buffer { get; init; } + public required ulong WriteOffset { get; init; } + public required ReadFileCommand[] ReadCommands { get; init; } + public required KernelEventCommand[] KernelEventCommands { get; init; } + public required WriteAddressCommand[] WriteAddressCommands { get; init; } + public required WaitAddressCommand[] WaitAddressCommands { get; init; } + public required AmmCommand[] AmmCommands { get; init; } + public required (ulong Offset, int Kind, int Index)[] Order { get; init; } + } + private static int TryCaptureCommands(CpuContext ctx, ulong commandBuffer, out CapturedCommands? captured) + { + captured = null; if (commandBuffer == 0) { return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT; @@ -898,6 +976,7 @@ public static int CompleteCommandBuffer( KernelEventCommand[] kernelEventCommands; WriteAddressCommand[] writeAddressCommands; WaitAddressCommand[] waitAddressCommands; + AmmCommand[] ammCommands; lock (state) { writeOffset = state.WriteOffset; @@ -905,10 +984,12 @@ public static int CompleteCommandBuffer( kernelEventCommands = state.KernelEventCommands.ToArray(); writeAddressCommands = state.WriteAddressCommands.ToArray(); waitAddressCommands = state.WaitAddressCommands.ToArray(); + ammCommands = state.AmmCommands.ToArray(); } var commands = new List<(ulong Offset, int Kind, int Index)>( - readCommands.Length + kernelEventCommands.Length + writeAddressCommands.Length + waitAddressCommands.Length); + readCommands.Length + kernelEventCommands.Length + writeAddressCommands.Length + waitAddressCommands.Length + + ammCommands.Length); for (var i = 0; i < readCommands.Length; i++) { commands.Add((readCommands[i].RecordOffset, 0, i)); @@ -925,27 +1006,59 @@ public static int CompleteCommandBuffer( { commands.Add((waitAddressCommands[i].RecordOffset, 3, i)); } + for (var i = 0; i < ammCommands.Length; i++) + { + commands.Add((ammCommands[i].RecordOffset, 4, i)); + } commands.Sort(static (left, right) => left.Offset.CompareTo(right.Offset)); + captured = new CapturedCommands + { + CommandBuffer = commandBuffer, + Buffer = buffer, + WriteOffset = writeOffset, + ReadCommands = readCommands, + KernelEventCommands = kernelEventCommands, + WriteAddressCommands = writeAddressCommands, + WaitAddressCommands = waitAddressCommands, + AmmCommands = ammCommands, + Order = commands.ToArray(), + }; + return (int)OrbisGen2Result.ORBIS_GEN2_OK; + } - foreach (var commandEntry in commands) + // Runs the captured commands from next on. A failed command stops the buffer, and executionResult and + // errorOffset report it. With stopAtUnmetWait, a wait whose condition does not hold yet stops the run there + // and returns false, so the rest can run where waiting holds up no guest thread. + private static bool RunCommands( + CpuContext ctx, + CapturedCommands captured, + ref int next, + bool stopAtUnmetWait, + out int executionResult, + out uint errorOffset) + { + executionResult = (int)OrbisGen2Result.ORBIS_GEN2_OK; + errorOffset = 0; + for (; next < captured.Order.Length; next++) { + var commandEntry = captured.Order[next]; switch (commandEntry.Kind) { case 0: { - var readCommand = readCommands[commandEntry.Index]; - var readResult = CompleteReadFileRecord(ctx, commandBuffer, readCommand); + var readCommand = captured.ReadCommands[commandEntry.Index]; + var readResult = CompleteReadFileRecord(ctx, captured.CommandBuffer, readCommand); if (readResult != (int)OrbisGen2Result.ORBIS_GEN2_OK) { executionResult = readResult; errorOffset = checked((uint)commandEntry.Offset); - return (int)OrbisGen2Result.ORBIS_GEN2_OK; + return true; } break; } case 1: - var eventCommand = kernelEventCommands[commandEntry.Index]; + var eventCommand = captured.KernelEventCommands[commandEntry.Index]; if (!KernelEventQueueCompatExports.TriggerAmprEvent( eventCommand.Equeue, unchecked((uint)eventCommand.Id), @@ -953,35 +1066,62 @@ public static int CompleteCommandBuffer( { executionResult = (int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND; errorOffset = checked((uint)commandEntry.Offset); - return (int)OrbisGen2Result.ORBIS_GEN2_OK; + return true; } break; case 2: - var writeCommand = writeAddressCommands[commandEntry.Index]; + var writeCommand = captured.WriteAddressCommands[commandEntry.Index]; if (!ctx.TryWriteUInt64(writeCommand.Address, writeCommand.Value)) { executionResult = (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT; errorOffset = checked((uint)commandEntry.Offset); - return (int)OrbisGen2Result.ORBIS_GEN2_OK; + return true; } break; case 3: - var waitCommand = waitAddressCommands[commandEntry.Index]; + var waitCommand = captured.WaitAddressCommands[commandEntry.Index]; + if (stopAtUnmetWait && !IsWaitMet(ctx, waitCommand)) + { + return false; + } + var waitResult = WaitForAddress(ctx, waitCommand); if (waitResult != (int)OrbisGen2Result.ORBIS_GEN2_OK) { executionResult = waitResult; errorOffset = checked((uint)commandEntry.Offset); - return (int)OrbisGen2Result.ORBIS_GEN2_OK; + return true; + } + break; + + case 4: + var ammResult = ExecuteAmmCommand(ctx, captured.AmmCommands[commandEntry.Index]); + if (ammResult != (int)OrbisGen2Result.ORBIS_GEN2_OK) + { + executionResult = ammResult; + errorOffset = checked((uint)commandEntry.Offset); + return true; } break; } } - TraceAmpr(ctx, "complete", commandBuffer, buffer, writeOffset); - return (int)OrbisGen2Result.ORBIS_GEN2_OK; + TraceAmpr(ctx, "complete", captured.CommandBuffer, captured.Buffer, captured.WriteOffset); + return true; + } + + // An address that cannot be read counts as met, so the wait reports the fault where it runs. + private static bool IsWaitMet(CpuContext ctx, WaitAddressCommand command) + { + if (command.Flush != 0) + { + Thread.MemoryBarrier(); + } + + return !ctx.TryReadUInt64(command.Address, out var value) || + IsWaitConditionSatisfied(value, command.Reference, command.Compare); } private static int _unknownReadFileIdWarnings; @@ -1084,6 +1224,7 @@ private static void UpdateCommandBufferState( state.KernelEventCommands.Clear(); state.WriteAddressCommands.Clear(); state.WaitAddressCommands.Clear(); + state.AmmCommands.Clear(); state.GatherScatterValid = false; state.GatherScatterFileId = 0; state.GatherScatterDestination = 0; @@ -1151,6 +1292,7 @@ private static bool TryGetCommandBufferState( state.KernelEventCommands.Clear(); state.WriteAddressCommands.Clear(); state.WaitAddressCommands.Clear(); + state.AmmCommands.Clear(); state.GatherScatterValid = false; state.GatherScatterFileId = 0; state.GatherScatterDestination = 0; @@ -1173,7 +1315,8 @@ private static bool HasQueuedCommands(CommandBufferState state) return state.ReadFileCommands.Count != 0 || state.KernelEventCommands.Count != 0 || state.WriteAddressCommands.Count != 0 || - state.WaitAddressCommands.Count != 0; + state.WaitAddressCommands.Count != 0 || + state.AmmCommands.Count != 0; } } diff --git a/src/SharpEmu.Libs/Gpu/Buffers/GpuBuffer.cs b/src/SharpEmu.Libs/Gpu/Buffers/GpuBuffer.cs index be68c3f2d..a7ec08182 100644 --- a/src/SharpEmu.Libs/Gpu/Buffers/GpuBuffer.cs +++ b/src/SharpEmu.Libs/Gpu/Buffers/GpuBuffer.cs @@ -159,6 +159,8 @@ public GpuBuffer(GpuDeviceInfo device, SubmissionScheduler scheduler, GpuBufferU { throw SubmissionScheduler.Fatal("The buffer device address is unavailable."); } + if (DeviceFaultReport.Requested) + DeviceFaultReport.Track(_deviceAddress, Size, usage.ToString(), cpuAddress); } // A dedicated allocation arrives zeroed; keep that for a block another buffer used. @@ -200,6 +202,9 @@ public Span MappedRange(ulong offset, int length) public ulong DeviceAddress => _deviceAddress != 0 ? _deviceAddress : throw SubmissionScheduler.Fatal("The buffer has no device address."); + // Created with ShaderDeviceAddressBit (rings are not). + public bool HasDeviceAddress => _deviceAddress != 0; + public int StreamScore { get; private set; } protected GpuDeviceInfo Device => _device; @@ -567,6 +572,7 @@ public void Dispose() } } + DeviceFaultReport.Untrack(_deviceAddress); _device.Vk.DestroyBuffer(_device.Device, _handle, null); if (_slab is { } slab) { diff --git a/src/SharpEmu.Libs/Gpu/Buffers/GpuDeviceInfo.cs b/src/SharpEmu.Libs/Gpu/Buffers/GpuDeviceInfo.cs index b62a0b4b2..d49b2cef0 100644 --- a/src/SharpEmu.Libs/Gpu/Buffers/GpuDeviceInfo.cs +++ b/src/SharpEmu.Libs/Gpu/Buffers/GpuDeviceInfo.cs @@ -175,9 +175,18 @@ public bool TryGetImageFormatProperties(Format format, ImageType type, ImageTili return entry.Result == Result.Success; } + // Tests: memory types whose allocations fail as when their heap is exhausted. + internal Func? SimulateExhaustedMemoryType { get; set; } + // Every device-memory allocation goes through here so the live count stays exact. public Result AllocateMemory(in MemoryAllocateInfo info, out DeviceMemory memory) { + if (SimulateExhaustedMemoryType is { } exhausted && exhausted(info.MemoryTypeIndex)) + { + memory = default; + return Result.ErrorOutOfDeviceMemory; + } + fixed (MemoryAllocateInfo* pointer = &info) { var result = Vk.AllocateMemory(Device, pointer, null, out memory); diff --git a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.ObtainMemo.cs b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.ObtainMemo.cs new file mode 100644 index 000000000..9075ed41d --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.ObtainMemo.cs @@ -0,0 +1,140 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE.Diagnostics; + +namespace SharpEmu.Libs.Gpu.Buffers; + +// Read obtains remember the persistent buffer that held each range. A later read of the same range takes it while the +// buffer is still registered and still holds the whole range, and no page of the range is CPU-dirty: registered buffers +// never overlap, so the full path would find that buffer and upload nothing. The memo keeps two ways per set; a range +// takes its own way, else an empty one, else the one used less recently. A served read still runs every per-use effect +// of a clean read: the buffer's lifetime touch, a texel read's image bytes and the overlay of pending dumps. +// SHARPEMU_OBTAIN_MEMO=0 turns the memo off; =verify takes the full path for every read the memo would serve and counts +// the reads where it found another buffer or offset. +public sealed unsafe partial class GuestBufferCache +{ + internal enum ObtainMemoMode + { + Off, + On, + Verify, + } + + internal static readonly ObtainMemoMode ConfiguredObtainMemo = Environment.GetEnvironmentVariable("SHARPEMU_OBTAIN_MEMO") switch + { + "0" => ObtainMemoMode.Off, + "verify" => ObtainMemoMode.Verify, + _ => ObtainMemoMode.On, + }; + + private const int ObtainMemoSets = 4096; + + private readonly record struct ObtainMemo(ulong Address, ulong Size, ResourceSlotIdentifier Identifier, ulong Offset, GpuBuffer? Buffer) + { + public bool Holds(ulong address, ulong size) => Buffer is not null && Address == address && Size == size; + } + + private readonly ObtainMemo[] _obtainMemos = new ObtainMemo[ObtainMemoSets * 2]; + private readonly long[] _obtainMemoUses = new long[ObtainMemoSets * 2]; + private long _obtainMemoClock; + + private static readonly ThreadCounter _obtainMemoServed = new(); + private static readonly ThreadCounter _obtainMemoFull = new(); + private static readonly ThreadCounter _obtainMemoVerified = new(); + private static readonly ThreadCounter _obtainMemoMismatches = new(); + private static int _obtainMemoMismatchReports; + + // Tests choose the mode per cache. + internal ObtainMemoMode ObtainMemoUse { get; set; } = ConfiguredObtainMemo; + + // Reads this cache served from the memo, reads it compared in verify mode, and the comparisons that differed. + internal long ObtainMemoHits { get; private set; } + + internal long ObtainMemoVerifications { get; private set; } + + internal long ObtainMemoMismatches { get; private set; } + + // Reads served, reads that took the full path with the memo on, and the verify comparisons. + public static string TakeObtainMemoReport() => FormattableString.Invariant( + $"obtain_memo=served:{_obtainMemoServed.Take()},full:{_obtainMemoFull.Take()},verified:{_obtainMemoVerified.Take()},mismatches:{_obtainMemoMismatches.Take()}"); + + // The first of the two ways of the range's set. + internal static int ObtainMemoSet(ulong address, ulong size) => + (int)(((address >> 4) ^ (address >> 17) ^ (size * 0x9E3779B1UL)) & (ObtainMemoSets - 1)) * 2; + + // Serves a clean read of a remembered range; true when served. In verify mode it serves none and returns the answer it + // would have served, for the full path to compare (RememberObtain). + private bool TryServeObtainMemo(int set, ulong address, ulong size, bool isTexelBuffer, out (GpuBuffer? Buffer, ulong Offset) kept) + { + kept = default; + var way = _obtainMemos[set].Holds(address, size) ? set : _obtainMemos[set + 1].Holds(address, size) ? set + 1 : -1; + if (way < 0) + { + _obtainMemoFull.Increment(); + return false; + } + + var memo = _obtainMemos[way]; + var buffer = memo.Buffer!; + if (!ReferenceEquals(_registry.TryGetRegisteredBuffer(memo.Identifier), buffer) || !buffer.IsInBounds(address, size) || + _tracker.MayHaveCpuDirtyPages(address, size)) + { + _obtainMemoFull.Increment(); + return false; + } + + _obtainMemoUses[way] = ++_obtainMemoClock; + if (ObtainMemoUse == ObtainMemoMode.Verify) + { + kept = (buffer, memo.Offset); + _obtainMemoFull.Increment(); + return false; + } + + ObtainMemoHits++; + _obtainMemoServed.Increment(); + TouchBuffer(memo.Identifier); + // A clean texel read still takes the bytes of an image over its range, as SynchronizeBuffer does for it. + if (isTexelBuffer) + { + _ = SynchronizeTexelFromImage(buffer, address, size); + } + + OverlayGuestPublications?.Invoke(buffer, memo.Offset, address, size); + kept = (buffer, memo.Offset); + return true; + } + + // After the full path of a read that bound a persistent buffer: remembers it, and compares it with the answer the memo + // would have served (verify mode). + private void RememberObtain(int set, ulong address, ulong size, ResourceSlotIdentifier identifier, GpuBuffer buffer, + (GpuBuffer? Buffer, ulong Offset) kept) + { + var offset = buffer.Offset(address); + if (kept.Buffer is not null) + { + ObtainMemoVerifications++; + _obtainMemoVerified.Increment(); + if (!ReferenceEquals(kept.Buffer, buffer) || kept.Offset != offset) + { + ObtainMemoMismatches++; + _obtainMemoMismatches.Increment(); + if (Interlocked.Increment(ref _obtainMemoMismatchReports) <= 16) + { + Console.Error.WriteLine( + $"[GPU][WARN] The obtain memo's buffer differs from the full path: address=0x{address:X16} size=0x{size:X} " + + $"memo_offset=0x{kept.Offset:X} offset=0x{offset:X} same_buffer={ReferenceEquals(kept.Buffer, buffer)}"); + } + } + } + + var way = _obtainMemos[set].Holds(address, size) ? set + : _obtainMemos[set + 1].Holds(address, size) ? set + 1 + : _obtainMemos[set].Buffer is null ? set + : _obtainMemos[set + 1].Buffer is null ? set + 1 + : _obtainMemoUses[set] <= _obtainMemoUses[set + 1] ? set : set + 1; + _obtainMemos[way] = new ObtainMemo(address, size, identifier, offset, buffer); + _obtainMemoUses[way] = ++_obtainMemoClock; + } +} diff --git a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs index 3305b641f..cabbc5af0 100644 --- a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs +++ b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs @@ -71,12 +71,9 @@ public void Dispose() cache._gpuModifiedGate.ExitWriteLock(); } } - private const int ObtainMemoSlots = 4096; - private readonly ObtainMemo[] _obtainMemos = new ObtainMemo[ObtainMemoSlots]; - - private readonly record struct ObtainMemo(ulong Address, ulong Size, ResourceSlotIdentifier Identifier, ulong Offset, GpuBuffer? Buffer); private long _gpuModifiedVersion; private readonly GuestPageTracker _tracker; + private readonly GuestWriteReservations _managedWrites; private readonly GpuRingBuffer _staging; private readonly ParallelGuestCopy _sweepCopy; private readonly GpuRingBuffer _stream; @@ -107,10 +104,11 @@ public GuestBufferCache( _gds = new GpuBuffer(device, scheduler, GpuBufferUsage.Stream, 0, GpuBuffer.AllFlags, GdsBufferSize); _bdaPageTable = new GpuBuffer(device, scheduler, GpuBufferUsage.DeviceLocal, 0, GpuBuffer.AllFlags, BdaPageTableSize); _tracker = new GuestPageTracker(pages); + _managedWrites = pages.ManagedWrites; _staging = new GpuRingBuffer(device, scheduler, GpuBufferUsage.Upload, 512 * MiB); - _uploader = new GuestBufferUploader(device, scheduler, guest, _staging); - // Up to three helper threads copy a large sweep's guest bytes with the render thread. + // Up to three helper threads copy a large sweep's guest bytes with the render thread, and a large upload's. _sweepCopy = new ParallelGuestCopy(guest, Math.Clamp(Environment.ProcessorCount - 1, 0, 3)); + _uploader = new GuestBufferUploader(device, scheduler, guest, _staging, _sweepCopy); _stream = new GpuRingBuffer(device, scheduler, GpuMemoryPlacement.StreamRing, 64 * MiB, GpuBuffer.AddressedFlags); _download = new GpuRingBuffer(device, scheduler, GpuBufferUsage.Download, 64 * MiB); _deviceRing = new GpuRingBuffer(device, scheduler, GpuBufferUsage.DeviceLocal, 128 * MiB); @@ -341,19 +339,17 @@ public void PrepareBufferAllocations(ReadOnlySpan ranges) throw SubmissionScheduler.Fatal("A buffer request requires a command buffer that is recording."); } - var memoSlot = -1; - if (!isWritten) + // Admission precedes all tracker/image/backing locks and lasts through GPU ownership publication. + using var managedWriteClaim = isWritten ? _managedWrites.BeginGpuClaim(guestAddress, size) : default; + + var memoSet = -1; + (GpuBuffer? Buffer, ulong Offset) remembered = default; + if (!isWritten && ObtainMemoUse != ObtainMemoMode.Off) { - memoSlot = (int)(((guestAddress >> 4) ^ (guestAddress >> 17) ^ (size * 0x9E3779B1UL)) & (ObtainMemoSlots - 1)); - ref var memo = ref _obtainMemos[memoSlot]; - if (memo.Buffer is { } kept && memo.Address == guestAddress && memo.Size == size && - ReferenceEquals(_registry.TryGetRegisteredBuffer(memo.Identifier), kept) && kept.IsInBounds(guestAddress, size) && - !_tracker.MayHaveCpuDirtyPages(guestAddress, size) && - (!isTexelBuffer || !RequireImageCache().MayHaveImageBytes(guestAddress, size))) + memoSet = ObtainMemoSet(guestAddress, size); + if (TryServeObtainMemo(memoSet, guestAddress, size, isTexelBuffer, out remembered)) { - TouchBuffer(memo.Identifier); - OverlayGuestPublications?.Invoke(kept, memo.Offset, guestAddress, size); - return (kept, memo.Offset); + return (remembered.Buffer!, remembered.Offset); } } @@ -439,9 +435,9 @@ public void PrepareBufferAllocations(ReadOnlySpan ranges) } else OverlayGuestPublications?.Invoke(buffer, buffer.Offset(guestAddress), guestAddress, size); - if (memoSlot >= 0) + if (memoSet >= 0) { - _obtainMemos[memoSlot] = new ObtainMemo(guestAddress, size, bufferIdentifier, buffer.Offset(guestAddress), buffer); + RememberObtain(memoSet, guestAddress, size, bufferIdentifier, buffer, remembered); } return (buffer, buffer.Offset(guestAddress)); @@ -557,6 +553,11 @@ private bool StreamUseExceeded(ulong guestAddress, ulong size) return (owner, owner.Offset(guestAddress)); } + // A GPU-side write into guest memory waits out overlapping reserved managed CPU writes (GuestWriteReservations); entered + // before the tracker, image and backing locks and held through the write's publication. + private GuestWriteReservations.GpuClaim ReserveGpuWrite(ulong address, ulong size) => + IsValidRange(address, size) ? _managedWrites.BeginGpuClaim(address, size) : default; + public void WriteHostMemory(ulong guestAddress, ReadOnlySpan data) { CompleteGuestPublications?.Invoke(guestAddress, (ulong)data.Length, PublicationAccess.Write); @@ -565,6 +566,7 @@ public void WriteHostMemory(ulong guestAddress, ReadOnlySpan data) throw SubmissionScheduler.Fatal("The host DMA write range is invalid."); } + using var managedWriteClaim = ReserveGpuWrite(guestAddress, (ulong)data.Length); if (!_backing.TryWriteBacking(guestAddress, data)) { throw SubmissionScheduler.Fatal($"Could not write the required direct backing: addr=0x{guestAddress:X16} size=0x{data.Length:X16}"); @@ -618,6 +620,7 @@ private void FillBuffer(ulong guestAddress, ulong size, uint value, bool isGds, throw SubmissionScheduler.Fatal("The fill memory address is invalid."); } + using var managedWriteClaim = ReserveGpuWrite(guestAddress, size); var images = RequireImageCache(); if (ImageClearTrace.Enabled) images.TraceGuestWrite("command-fill", guestAddress, size, value); images.TraceMetadataFill(guestAddress, size, value); @@ -720,6 +723,7 @@ public void FillDccMetadata(ulong guestAddress, ulong size, uint value) return; } + using var managedWriteClaim = ReserveGpuWrite(guestAddress, size); // Images over the range read it again; only GPU-owned image bytes need the general fill. // The buffer copy is filled on the GPU rather than uploaded from the written bytes. var images = RequireImageCache(); @@ -794,6 +798,7 @@ public bool TryCopyWordsOnHost(ulong destination, ulong source, ulong sourceWord return false; } + using var managedWriteClaim = ReserveGpuWrite(destination, size); var images = RequireImageCache(); var sourceRegion = images.QueryRegion(source, sourceSize); var destinationRegion = images.QueryRegion(destination, size); @@ -858,6 +863,7 @@ public void CopyBuffer(ulong dstVaddr, ulong srcVaddr, ulong size, bool dstGds, $"The buffer copy range is invalid: src=0x{srcVaddr:X16} dst=0x{dstVaddr:X16} size=0x{size:X16} src_gds={(srcGds ? 1 : 0)} dst_gds={(dstGds ? 1 : 0)}"); } + using var managedWriteClaim = dstMemory ? ReserveGpuWrite(dstVaddr, size) : default; var images = RequireImageCache(); if (ImageClearTrace.Enabled && dstMemory) images.TraceGuestWrite("command-copy", dstVaddr, size, srcGds ? 0 : srcVaddr); var srcRegion = srcMemory ? images.QueryRegion(srcVaddr, size) : default; @@ -1055,7 +1061,9 @@ public void PrepareBda(IReadOnlyList spans, ulong mapping) } var epoch = _tracker.CpuDirtyEpoch; - if (mapping != _bdaSweepMapping || (epoch != _bdaSweepEpoch && (!ObservationGated || _observation != _bdaSweepObservation))) + var registrations = _registrationGeneration; + if (mapping != _bdaSweepMapping || registrations != _bdaSweepRegistrations || + (epoch != _bdaSweepEpoch && (!ObservationGated || _observation != _bdaSweepObservation))) { if (!_bdaSweepPlanBuilt || mapping != _bdaSweepPlanMapping) { @@ -1103,6 +1111,7 @@ public void PrepareBda(IReadOnlyList spans, ulong mapping) _bdaSweepEpoch = epoch; _bdaSweepMapping = mapping; + _bdaSweepRegistrations = registrations; _bdaSweepObservation = _observation; Interlocked.Increment(ref BdaSweeps); } @@ -1250,6 +1259,10 @@ private void RecordSweepBarrier(CommandBuffer native, PipelineStageFlags sourceS } private long _bdaSweepEpoch = -1; + + // Every registration advances it: a new owner needs its first upload even when no CPU write moved the epoch. + private long _registrationGeneration; + private long _bdaSweepRegistrations = -1; private long _bdaSweepObservation = -1; private long _observation; public static long BdaSweeps; @@ -1760,6 +1773,11 @@ private bool ReadMemoryOrAwaitShutdown(ulong guestAddress, ulong size, bool isWr private readonly record struct HotWindow(ulong Address, ulong Size, long LastHit, int Strikes = 0, long MutedUntil = 0); + // Eager readbacks are off unless SHARPEMU_EAGER_READBACKS=1: the CPU consumes few of them, while each still ends + // rendering early to flush its batch and downloads its whole window. + internal bool EagerReadbacksEnabled { get; set; } = + string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_EAGER_READBACKS"), "1", StringComparison.Ordinal); + internal long EagerReadbacksStarted { get; private set; } internal long EagerReadbacksUsed { get; private set; } @@ -1808,7 +1826,7 @@ private void NoteEagerOutcome(ulong key, bool wasted) private void NoteHotWindowWrite(ulong guestAddress, ulong size) { - if (_hotWindows.Count == 0 || size == 0) + if (!EagerReadbacksEnabled || _hotWindows.Count == 0 || size == 0) { return; } @@ -2412,6 +2430,7 @@ private void UpdateRegistration(ResourceSlotIdentifier bufferIdentifier, bool in { _bufferPages.Set(buffer.CpuAddress, buffer.Size, covered: true); _registry.RegisterBuffer(bufferIdentifier, _retirementPolicy.CurrentTick); + _registrationGeneration++; var addresses = new ulong[sizePages]; for (ulong page = 0; page < sizePages; page++) { @@ -2424,6 +2443,7 @@ private void UpdateRegistration(ResourceSlotIdentifier bufferIdentifier, bool in { _bufferPages.Set(buffer.CpuAddress, buffer.Size, covered: false); _registry.BeginRetirement(bufferIdentifier); + _unregistrations++; _bdaPageTable.Fill(first * sizeof(ulong), sizePages * sizeof(ulong), 0); } } @@ -2451,12 +2471,45 @@ private void DeleteBuffer(ResourceSlotIdentifier bufferIdentifier) CompleteRetirementAfterSubmittedWork(bufferIdentifier); } + private long _unregistrations; + private int _preparationsOpen; + private readonly List _retireAfterPreparation = []; + + // Changes whenever an owner is unregistered. A binding made before a change may name a retired owner. + internal long OwnerGeneration => _unregistrations; + + // A draw or dispatch being prepared can still name an owner unregistered during its own preparation, and a wait + // inside the preparation can complete the tick a retirement was queued on. Such retirements are queued when the + // preparation closes, behind everything it recorded. + internal void BeginPreparation() => _preparationsOpen++; + + internal void EndPreparation() + { + if (--_preparationsOpen != 0 || _retireAfterPreparation.Count == 0) + { + return; + } + + var retired = _retireAfterPreparation.ToArray(); + _retireAfterPreparation.Clear(); + foreach (var bufferIdentifier in retired) + { + CompleteRetirementAfterSubmittedWork(bufferIdentifier); + } + } + // Unregistering clears the buffer's page-table entries only for work recorded from now // on. Work already recorded or in flight can still reach it through its device address // (an async readback waits only for its last recorded writer), so it is destroyed once // that work completes. private void CompleteRetirementAfterSubmittedWork(ResourceSlotIdentifier bufferIdentifier) { + if (_preparationsOpen != 0) + { + _retireAfterPreparation.Add(bufferIdentifier); + return; + } + if (_scheduler.Active) { _scheduler.QueueCompletionAction(() => _registry.CompleteRetirement(bufferIdentifier)); @@ -2629,6 +2682,7 @@ public bool TryWriteOverGpuBytes(ulong guestAddress, ReadOnlySpan data) } CompleteGuestPublications?.Invoke(guestAddress, size, PublicationAccess.Write); + using var managedWriteClaim = ReserveGpuWrite(guestAddress, size); if (RequireImageCache().MayHaveImageBytes(guestAddress, size) && RequireImageCache().QueryRegion(guestAddress, size).ImageBytes) { return false; @@ -3058,7 +3112,7 @@ public UploadCollector() if (_defer) _cache.DeferSweepUpload(_buffer, _guestAddress, _size, Copies, TotalSize); else - Source = _cache._uploader.PrepareSource(_buffer.CpuAddress, CollectionsMarshal.AsSpan(Copies), TotalSize, _guestAddress, _size); + Source = _cache.StageCollectedUpload(this, _buffer, _guestAddress, _size); }; } @@ -3091,6 +3145,80 @@ public void End() [ThreadStatic] private static UploadCollector? _uploadCollector; + // An upload larger than the staging ring goes through the ring in pieces of half its size instead of through a new + // buffer of the whole size, whose first writes fault in every page. Each piece is recorded before the next one is + // staged, so staging a later piece may submit the earlier ones and wait for them. The last piece stays with the + // collector for the caller to record. + private GpuBuffer? StageCollectedUpload(UploadCollector collector, GpuBuffer buffer, ulong guestAddress, ulong size) + { + var copies = collector.Copies; + var pieceBytes = _staging.Size / 2; + if (collector.TotalSize <= _staging.Size || pieceBytes == 0) + { + return _uploader.PrepareSource(buffer.CpuAddress, CollectionsMarshal.AsSpan(copies), collector.TotalSize, guestAddress, size); + } + + var pieces = SplitUploadPieces(CollectionsMarshal.AsSpan(copies), pieceBytes); + for (var index = 0; index < pieces.Count - 1; index++) + { + var regions = CollectionsMarshal.AsSpan(pieces[index]); + var bytes = UploadPieceBytes(regions); + if (_uploader.PrepareSource(buffer.CpuAddress, regions, bytes, guestAddress, size) is { } source) + { + RecordUpload(buffer, source, regions, guestAddress, size, bytes); + BufferUploadProfile.NoteUpload(regions.Length, bytes, size); + } + } + + copies.Clear(); + copies.AddRange(pieces[^1]); + collector.TotalSize = UploadPieceBytes(CollectionsMarshal.AsSpan(copies)); + return _uploader.PrepareSource(buffer.CpuAddress, CollectionsMarshal.AsSpan(copies), collector.TotalSize, guestAddress, size); + } + + // Splits staged copies into pieces of at most pieceBytes staged bytes each; a copy that crosses a piece boundary is + // split there. Source offsets restart at zero in every piece. + internal static List> SplitUploadPieces(ReadOnlySpan copies, ulong pieceBytes) + { + var pieces = new List>(); + var piece = new List(); + ulong staged = 0; + foreach (var copy in copies) + { + for (ulong done = 0; done < copy.Size;) + { + var take = Math.Min(copy.Size - done, pieceBytes - staged); + piece.Add(new BufferCopy(staged, copy.DstOffset + done, take)); + staged += take; + done += take; + if (staged == pieceBytes) + { + pieces.Add(piece); + piece = new List(); + staged = 0; + } + } + } + + if (piece.Count != 0) + { + pieces.Add(piece); + } + + return pieces; + } + + private static ulong UploadPieceBytes(ReadOnlySpan regions) + { + ulong bytes = 0; + foreach (var region in regions) + { + bytes += region.Size; + } + + return bytes; + } + private bool SynchronizeBufferCore(UploadCollector collector, GpuBuffer buffer, ulong guestAddress, ulong size, bool isWritten, bool isTexelBuffer, bool preserveCpuWriteHotPages, long startedAt) { diff --git a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferUploader.cs b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferUploader.cs index 0a8c1dedd..5467bf52a 100644 --- a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferUploader.cs +++ b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferUploader.cs @@ -1,6 +1,8 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; using SharpEmu.HLE; using SharpEmu.Libs.Gpu.Scheduling; using SharpEmu.Libs.VideoOut; @@ -10,10 +12,18 @@ namespace SharpEmu.Libs.Gpu.Buffers; // The cache owns the staging ring; temporary sources retire after their submission. internal sealed class GuestBufferUploader( - GpuDeviceInfo device, SubmissionScheduler scheduler, ICpuMemory guest, GpuRingBuffer staging) + GpuDeviceInfo device, SubmissionScheduler scheduler, ICpuMemory guest, GpuRingBuffer staging, + ParallelGuestCopy? parallelCopy = null) { private const ulong TemporaryPieceBytes = 1UL << 30; + // An upload of GuestBufferCache.ParallelSweepCopyBytes or more copies its guest bytes in pieces with the parallel + // copy's helper threads, as a large sweep does: a loading screen can upload pools of gigabytes, and a serial copy + // holds the render thread for each of them. SHARPEMU_PARALLEL_UPLOAD_COPY=0 keeps the serial copy. + private static readonly bool ParallelUploadCopy = Environment.GetEnvironmentVariable("SHARPEMU_PARALLEL_UPLOAD_COPY") != "0"; + private const ulong ParallelPieceBytes = 64 * 1024; + private ParallelGuestCopy.Piece[] _pieces = []; + public GpuBuffer? PrepareSource(ulong bufferAddress, Span regions, ulong totalSize, ulong requestedAddress, ulong requestedSize) { @@ -25,10 +35,15 @@ internal sealed class GuestBufferUploader( if (staging.TryMap(totalSize, out var baseOffset, 4)) { + var copied = TryCopyInParallel(staging, baseOffset, bufferAddress, regions, totalSize); foreach (ref var copy in regions) { - ReadGuestBytes(bufferAddress + copy.DstOffset, - staging.Mapped.Slice((int)(baseOffset + copy.SrcOffset), (int)copy.Size), requestedAddress, requestedSize); + if (!copied) + { + ReadGuestBytes(bufferAddress + copy.DstOffset, + staging.Mapped.Slice((int)(baseOffset + copy.SrcOffset), (int)copy.Size), requestedAddress, requestedSize); + } + copy.SrcOffset += baseOffset; } @@ -37,14 +52,17 @@ internal sealed class GuestBufferUploader( } var temporary = new GpuBuffer(device, scheduler, GpuBufferUsage.Upload, 0, BufferUsageFlags.TransferSrcBit, totalSize); - foreach (ref readonly var copy in regions) + if (!TryCopyInParallel(temporary, 0, bufferAddress, regions, totalSize)) { - for (var done = 0UL; done < copy.Size;) + foreach (ref readonly var copy in regions) { - var piece = (int)Math.Min(copy.Size - done, TemporaryPieceBytes); - ReadGuestBytes(bufferAddress + copy.DstOffset + done, - temporary.MappedRange(copy.SrcOffset + done, piece), requestedAddress, requestedSize); - done += (ulong)piece; + for (var done = 0UL; done < copy.Size;) + { + var piece = (int)Math.Min(copy.Size - done, TemporaryPieceBytes); + ReadGuestBytes(bufferAddress + copy.DstOffset + done, + temporary.MappedRange(copy.SrcOffset + done, piece), requestedAddress, requestedSize); + done += (ulong)piece; + } } } @@ -53,21 +71,128 @@ internal sealed class GuestBufferUploader( return temporary; } + // Copies each region to target at targetOffset plus its source offset with the parallel copy. False when there is + // no parallel copy, the upload is small, or a read failed; the caller then copies serially, which stages pages + // without a guest mapping as zero and reports a mapped page that cannot be read. + private unsafe bool TryCopyInParallel(GpuBuffer target, ulong targetOffset, ulong bufferAddress, Span regions, + ulong totalSize) + { + if (parallelCopy is null || !ParallelUploadCopy || totalSize < GuestBufferCache.ParallelSweepCopyBytes) + { + return false; + } + + var count = 0; + foreach (ref readonly var copy in regions) + { + count += checked((int)((copy.Size + ParallelPieceBytes - 1) / ParallelPieceBytes)); + } + + if (_pieces.Length < count) + { + _pieces = new ParallelGuestCopy.Piece[Math.Max(count, _pieces.Length * 2)]; + } + + count = 0; + foreach (ref readonly var copy in regions) + { + for (var done = 0UL; done < copy.Size; done += ParallelPieceBytes) + { + var length = (int)Math.Min(ParallelPieceBytes, copy.Size - done); + var destination = target.MappedRange(targetOffset + copy.SrcOffset + done, length); + _pieces[count++] = new ParallelGuestCopy.Piece(bufferAddress + copy.DstOffset + done, + (nint)Unsafe.AsPointer(ref MemoryMarshal.GetReference(destination)), length); + } + } + + return parallelCopy.Run(_pieces, count, parallel: true); + } + + private const ulong GuestPageBytes = 0x1000; + private const int MaxUnmappedReports = 8; + private static int _unmappedReports; + private void ReadGuestBytes(ulong address, Span destination, ulong requestedAddress, ulong requestedSize) { - if (!guest.TryRead(address, destination)) + if (guest.TryRead(address, destination)) + { + return; + } + + // A buffer can cover pages the guest no longer maps: they hold nothing a GPU access may read, so they stage + // as zero. A mapped page that cannot be read still stops the game below. + if (TryReadMappedPages(guest, address, destination, out var unmappedBytes)) { - Console.Error.WriteLine($"[GPU][READ_FAILURE] addr=0x{address:X16} size=0x{destination.Length:X}"); - Console.Error.WriteLine($"[GPU][READ_FAILURE] binding=0x{requestedAddress:X16} size=0x{requestedSize:X}"); - try + ReportUnmappedPages(address, destination.Length, unmappedBytes, requestedAddress, requestedSize); + return; + } + + Console.Error.WriteLine($"[GPU][READ_FAILURE] addr=0x{address:X16} size=0x{destination.Length:X}"); + Console.Error.WriteLine($"[GPU][READ_FAILURE] binding=0x{requestedAddress:X16} size=0x{requestedSize:X}"); + try + { + Console.Error.WriteLine(guest.DescribeReadRange(address, (ulong)destination.Length)); + } + catch (Exception error) + { + Console.Error.WriteLine($"[GPU][READ_FAILURE] mapping query failed: {error.GetType().Name}"); + } + throw SubmissionScheduler.Fatal($"Could not read guest memory: addr=0x{address:X16} size=0x{destination.Length:X}"); + } + + // Reads the range page by page: a page without a guest mapping reads as zero, a mapped page must read. False when a + // mapped page could not be read. + internal static bool TryReadMappedPages(ICpuMemory memory, ulong address, Span destination, out ulong unmappedBytes) + { + unmappedBytes = 0; + var offset = 0; + while (offset < destination.Length) + { + var pageAddress = address + (ulong)offset; + var length = (int)Math.Min((ulong)(destination.Length - offset), GuestPageBytes - (pageAddress & (GuestPageBytes - 1))); + var piece = destination.Slice(offset, length); + if (memory.CanRead(pageAddress, (ulong)length)) { - Console.Error.WriteLine(guest.DescribeReadRange(address, (ulong)destination.Length)); + if (!memory.TryRead(pageAddress, piece)) + { + return false; + } } - catch (Exception error) + else { - Console.Error.WriteLine($"[GPU][READ_FAILURE] mapping query failed: {error.GetType().Name}"); + piece.Clear(); + unmappedBytes += (ulong)length; } - throw SubmissionScheduler.Fatal($"Could not read guest memory: addr=0x{address:X16} size=0x{destination.Length:X}"); + + offset += length; + } + + return true; + } + + private void ReportUnmappedPages(ulong address, int length, ulong unmappedBytes, ulong requestedAddress, ulong requestedSize) + { + var report = Interlocked.Increment(ref _unmappedReports); + if (report > MaxUnmappedReports) + { + return; + } + + Console.Error.WriteLine( + $"[GPU][WARN] A buffer upload covers guest pages without a mapping; they read as zero: addr=0x{address:X16} " + + $"size=0x{length:X} unmapped=0x{unmappedBytes:X} binding=0x{requestedAddress:X16} binding_size=0x{requestedSize:X}"); + try + { + Console.Error.WriteLine(guest.DescribeReadRange(address, (ulong)length)); + } + catch (Exception error) + { + Console.Error.WriteLine($"[GPU][WARN] mapping query failed: {error.GetType().Name}"); + } + + if (report == 1) + { + Console.Error.WriteLine($"[GPU][WARN] first unmapped upload requested from:{Environment.NewLine}{Environment.StackTrace}"); } } } diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs index 82d4cdc4d..74707a5f9 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandStreamQueue.cs @@ -56,6 +56,25 @@ private sealed record ControlBarrier(ulong CutoffOrdinal, Action Work, Action Ca private readonly int _boundariesInFlight; + // SHARPEMU_END_OF_PIPE_SOFT_WAITS: every queue's releases; null when off. Tests set it before the first interpreter. + private EndOfPipeLandings? _landings = EndOfPipeLandings.Configured ? new EndOfPipeLandings() : null; + + internal EndOfPipeLandings? Landings + { + get => _landings; + set + { + lock (_gate) + { + _landings = value; + foreach (var interpreter in _interpreters) + { + if (interpreter is not null) interpreter.Landings = value; + } + } + } + } + public CommandStreamQueue(ICommandStreamHost host) : this(host, DefaultBoundariesInFlight) { } @@ -131,7 +150,10 @@ public GpuCommandInterpreter GetInterpreter(int queueId) lock (_gate) { - return _interpreters[queueId] ??= new GpuCommandInterpreter(_host, queueId, queueId == 0 ? 0 : GpuCommandInterpreter.ComputeQueueBase + queueId - 1); + return _interpreters[queueId] ??= new GpuCommandInterpreter(_host, queueId, queueId == 0 ? 0 : GpuCommandInterpreter.ComputeQueueBase + queueId - 1) + { + Landings = _landings, + }; } } @@ -372,13 +394,15 @@ public void NotifyCompletedGpuTick(ulong completedTick) } } - private ulong _publicationGeneration; + // Retry notifications also cover a head temporarily removed by ProcessOne. A notification + // between its predicate read and requeue must leave that head eligible for another read. + private ulong _retryGeneration; public void NotifyPublicationCompleted() { lock (_gate) { - _publicationGeneration++; + _retryGeneration++; var retried = false; foreach (var queue in _queues) if (queue.First is { Value.Blocked: true } head) @@ -395,6 +419,7 @@ public void RetryBlocked() { lock (_gate) { + _retryGeneration++; foreach (var queue in _queues) { if (queue.First is { } head) @@ -413,10 +438,12 @@ public SliceResult ProcessOne() { CommandSubmission? submission = null; ControlBarrier? control = null; - ulong publicationGeneration; + ulong retryGeneration; + var mayDeferForLanding = false; + ulong completedGpuTick = 0; lock (_gate) { - publicationGeneration = _publicationGeneration; + retryGeneration = _retryGeneration; if (_processing) { throw _host.Fatal("The command stream queue is already processing a slice."); @@ -439,6 +466,11 @@ public SliceResult ProcessOne() queue.RemoveFirst(); _submissionCount--; _nextQueue = (selected + 1) % QueueCount; + if (_landings is not null) + { + mayDeferForLanding = HasOtherRunnableLocked(selected); + completedGpuTick = _lastCompletedGpuTick; + } } _processing = true; @@ -481,7 +513,7 @@ submission.Kind is not (CommandSubmissionKind.FlipPreparation or CommandSubmissi bool complete; try { - complete = RunSlice(submission!); + complete = RunSlice(submission!, mayDeferForLanding, completedGpuTick); } catch (Exception exception) { @@ -504,7 +536,12 @@ submission.Kind is not (CommandSubmissionKind.FlipPreparation or CommandSubmissi SliceResult result; if (!complete) { - submission!.Blocked = publicationGeneration == _publicationGeneration; + // A soft wait for a release keeps the head runnable behind the other queues (SelectQueueLocked). + long deferredSince = 0; + var deferral = _landings is null ? null : _interpreters[submission!.QueueId]?.TakeLandingDeferral(out deferredSince); + submission!.Deferral = deferral; + submission.DeferredSinceTicks = deferral is null ? 0 : deferredSince; + submission.Blocked = deferral is null && retryGeneration == _retryGeneration; submission.BlockedSinceTicks = System.Diagnostics.Stopwatch.GetTimestamp(); submission.BlockedPacketAddress = submission.Commands.CurrentPacketAddress; _queues[submission.QueueId].AddFirst(submission); @@ -536,7 +573,7 @@ submission.Kind is not (CommandSubmissionKind.FlipPreparation or CommandSubmissi } } - private bool RunSlice(CommandSubmission submission) + private bool RunSlice(CommandSubmission submission, bool mayDeferForLanding = false, ulong completedGpuTick = 0) { if (submission.Kind == CommandSubmissionKind.FlipPreparation) { @@ -573,6 +610,8 @@ private bool RunSlice(CommandSubmission submission) } SlicesRun++; + processor.MayDeferForLanding = mayDeferForLanding; + processor.CompletedGpuTick = completedGpuTick; _host.BeginSubmission(submission.QueueId, submission.SubmissionId, submission.GeometrySnapshots); processor.ConstantEngineComplete = true; var complete = processor.Process(submission.Commands, submission.Address, submission.DwordCount, @@ -788,15 +827,55 @@ private int SelectQueueLocked() for (var offset = 0; offset < QueueCount; offset++) { var queueId = (_nextQueue + offset) % QueueCount; - if (_queues[queueId].First is { } head && !head.Value.Blocked) + if (_queues[queueId].First is { } head && !head.Value.Blocked && DeferralReadyLocked(head.Value)) { return queueId; } } + // SHARPEMU_END_OF_PIPE_SOFT_WAITS: a head waiting softly for a release runs once no other head can. + if (_landings is not null) + { + for (var offset = 0; offset < QueueCount; offset++) + { + var queueId = (_nextQueue + offset) % QueueCount; + if (_queues[queueId].First is { } head && !head.Value.Blocked) + { + return queueId; + } + } + } + return -1; } + // A head without a soft wait, or whose release completed on the GPU, whose deadline passed, or any head once the queue + // stops. + private bool DeferralReadyLocked(CommandSubmission submission) => + submission.Deferral is not { } landing || _landings is not { } landings || landing.IsComplete(_lastCompletedGpuTick) || + _stopping || !_accepting || + System.Diagnostics.Stopwatch.GetTimestamp() - submission.DeferredSinceTicks >= landings.CapTicks; + + // Another queue's head may run now without a soft wait of its own: a slice of the selected queue may then wait softly. + private bool HasOtherRunnableLocked(int selected) + { + if (_controlBarriers.Count != 0 || _stopping || !_accepting) + { + return false; + } + + for (var queueId = 0; queueId < QueueCount; queueId++) + { + if (queueId != selected && _queues[queueId].First is { } head && !head.Value.Blocked && + DeferralReadyLocked(head.Value)) + { + return true; + } + } + + return false; + } + private bool HasRunnableWorkLocked() => IsControlBarrierReadyLocked() || SelectQueueLocked() >= 0; private bool IsControlBarrierReadyLocked() diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandSubmission.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandSubmission.cs index 683c8c028..15f1f873d 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/CommandSubmission.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/CommandSubmission.cs @@ -160,6 +160,12 @@ internal void ReleaseCommandBytes() public bool Blocked { get; internal set; } + // SHARPEMU_END_OF_PIPE_SOFT_WAITS: the slice stopped at a wait whose release has not completed on the GPU; the head + // stays runnable behind every other head until the release completes or the cap passes. + internal EndOfPipeLanding? Deferral { get; set; } + + internal long DeferredSinceTicks { get; set; } + // Host timestamp of the slice that left this submission blocked; diagnostics only. public long BlockedSinceTicks { get; internal set; } diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/EndOfPipeLandings.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/EndOfPipeLandings.cs new file mode 100644 index 000000000..fafca3450 --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/EndOfPipeLandings.cs @@ -0,0 +1,148 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Diagnostics; + +namespace SharpEmu.Libs.Gpu.GpuCommands; + +// One ordinary end-of-pipe label write (Write32 or Write64 of a fixed value). The command stream thread writes the label +// into guest memory when it interprets the release, before the render thread records the work in front of it; the render +// thread names the scheduler tick of the recording that holds the release. This is a scheduling hint only: it never +// satisfies a wait and never shows that guest bytes are current. +public sealed class EndOfPipeLanding +{ + private long _tick; + private int _consumed; + + internal EndOfPipeLanding(int queue, ulong destination, int width, ulong value, long sequence) + { + Queue = queue; + Destination = destination; + Width = width; + Value = value; + Sequence = sequence; + } + + internal int Queue { get; } + + internal ulong Destination { get; } + + // 4 or 8 bytes. + internal int Width { get; } + + internal ulong Value { get; } + + internal long Sequence { get; } + + // 0 until the render thread recorded the release. + internal ulong Tick => (ulong)Volatile.Read(ref _tick); + + // A soft wait used this release once; it is never armed again. + internal bool Consumed => Volatile.Read(ref _consumed) != 0; + + // Render thread: the release is in the recording that Submit gives this tick (SubmissionScheduler reserves timeline + // ticks only there, in order, so the current recording's tick is CurrentTick; QueueCompletionAction relies on the same). + internal void Recorded(ulong tick) => Volatile.Write(ref _tick, (long)tick); + + internal void Consume() => Volatile.Write(ref _consumed, 1); + + // Why the soft wait that used this release passed (tests and traces); null while unused or still waiting. + internal EndOfPipeLandings.Release? ReleasedBy { get; set; } + + // Recorded, and the scheduler timeline reached its tick. Unrecorded, or a recording that never submitted, is not. + internal bool IsComplete(ulong completedTick) + { + var tick = Tick; + return tick != 0 && completedTick >= tick; + } +} + +// Another queue's wait on an ordinary end-of-pipe label is satisfied as soon as the command stream thread interpreted the +// release, long before the work in front of the release completes on the GPU; on the console it would not be. While that +// work has not completed and another queue's head may run, the satisfied wait suspends like an unmet one, so the render +// thread translates that queue's work instead of waiting for GPU results the resumed queue reads. The wait then passes +// unchanged: once the release completes on the GPU, once no other head may run, at shutdown, or at CapTicks after the first +// suspension. Only the order of the queues' slices changes, to one the command stream could already choose; the label, the +// wait's comparison and every packet stay as they are. SHARPEMU_END_OF_PIPE_SOFT_WAITS=0 turns these soft waits off. +internal sealed class EndOfPipeLandings +{ + internal static readonly bool Configured = + Environment.GetEnvironmentVariable("SHARPEMU_END_OF_PIPE_SOFT_WAITS") != "0"; + + internal static readonly long DefaultCapTicks = Stopwatch.Frequency / 125; + + private const int MaxTracked = 4096; + + // One monotonic deadline per soft wait, from its first suspension; never re-armed (8 ms, the busy batch age). + internal long CapTicks { get; init; } = DefaultCapTicks; + + // Command stream thread only: the newest admitted release of each label address. + private readonly Dictionary _latest = new(); + private long _sequence; + + // Command stream thread: an ordinary label write of this queue is in guest memory now. Other kinds take no record (an + // earlier record of the address is dropped, so a later wait cannot match it). + internal EndOfPipeLanding? Publish(int queue, in EndOfPipeWrite write) + { + var width = write.Kind switch + { + EndOfPipeWriteKind.Write32 => 4, + EndOfPipeWriteKind.Write64 => 8, + _ => 0, + }; + if (width == 0 || write.Destination == 0) + { + _latest.Remove(write.Destination); + return null; + } + + if (_latest.Count >= MaxTracked && !_latest.ContainsKey(write.Destination)) + { + _latest.Clear(); + } + + var value = width == 4 ? (uint)write.Value : write.Value; + var landing = new EndOfPipeLanding(queue, write.Destination, width, value, ++_sequence); + _latest[write.Destination] = landing; + return landing; + } + + // Command stream thread: this queue's wait read observed at address (not a deferred label, not its own write) and found + // the condition met. Returns the release to wait for softly, or null. Admitted: an equality compare of the record's + // width under a full mask, whose reference and observed value both equal the value another queue's newest release of + // that address wrote, while that release is unconsumed and has not completed on the GPU. + internal EndOfPipeLanding? Admit(int queue, ulong address, int width, uint compareFunction, ulong reference, ulong mask, + ulong observed, ulong completedTick) + { + if (!_latest.TryGetValue(address, out var landing)) + { + return null; + } + + if (landing.Consumed || landing.IsComplete(completedTick)) + { + _latest.Remove(address); + return null; + } + + var fullMask = width == 4 ? 0xFFFF_FFFFUL : ulong.MaxValue; + if (landing.Queue == queue || landing.Width != width || compareFunction != 3 || (mask & fullMask) != fullMask || + reference != landing.Value || observed != landing.Value) + { + return null; + } + + return landing; + } + + // Command stream thread: another write to this address (a deferred label) replaces its hint. + internal void Forget(ulong destination) => _latest.Remove(destination); + + internal enum Release + { + Complete, + Idle, + Cap, + Off, + } +} diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Draws.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Draws.cs index 6e4be62b8..4998a62d9 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Draws.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Draws.cs @@ -5,6 +5,17 @@ namespace SharpEmu.Libs.Gpu.GpuCommands; +// The shader registers an indirect draw packet names for the CP to fill from the arguments as the draw executes: +// the base vertex (the start vertex of a non-indexed draw) in DW2[15:0], the start instance in DW3[15:0] and, when +// DW3 bit 27 is set, the draw's index in DW2[31:16]. Location 0 and ShaderRegisterNop name no register. +internal readonly record struct DrawRegisterLocations(uint BaseVertex, uint StartInstance, uint DrawIndex) +{ + public static DrawRegisterLocations FromPacket(uint vertexWord, uint instanceWord) => + new(vertexWord & 0xFFFFu, instanceWord & 0xFFFFu, (instanceWord & (1u << 27)) != 0 ? vertexWord >> 16 : 0); + + public static bool Names(uint location) => location != 0 && location != RegisterBankLayout.ShaderRegisterNop; +} + public sealed partial class GpuCommandInterpreter { private const uint DrawIndirectArgumentsSize = 16; @@ -26,7 +37,8 @@ public sealed partial class GpuCommandInterpreter _ => throw _host.Fatal($"The index type is unknown: type={IndexTypeAndSize}."), }; - internal void DrawIndexed(ulong packetAddress, uint opcode, uint indexCount, ulong indexAddress, uint instanceCount = 0, int baseVertex = 0, uint firstInstance = 0, DrawOffsetSource offsetSource = DrawOffsetSource.Packet, int startInstanceUserData = -1) + internal void DrawIndexed(ulong packetAddress, uint opcode, uint indexCount, ulong indexAddress, uint instanceCount = 0, int baseVertex = 0, uint firstInstance = 0, DrawOffsetSource offsetSource = DrawOffsetSource.Packet, + bool baseVertexInRegister = false, bool firstInstanceInRegister = false, int startInstanceUserData = -1) { if (instanceCount == 0) { @@ -40,7 +52,8 @@ internal void DrawIndexed(ulong packetAddress, uint opcode, uint indexCount, ulo } if (Rendering.ScissorTrace.Instance is { Active: true } trace) trace.DrawIssued(TypedRegisters, SubmitId, QueueId, packetAddress); - _host.DrawIndexed(SubmitId, new DrawIndexedArguments(packetAddress, opcode, indexCount, indexAddress, IndexTypeAndSize, instanceCount, baseVertex, firstInstance, offsetSource, StartInstanceUserData: startInstanceUserData)); + _host.DrawIndexed(SubmitId, new DrawIndexedArguments(packetAddress, opcode, indexCount, indexAddress, IndexTypeAndSize, instanceCount, baseVertex, firstInstance, offsetSource, + StartInstanceUserData: startInstanceUserData, BaseVertexInRegister: baseVertexInRegister, FirstInstanceInRegister: firstInstanceInRegister)); } internal void DrawIndexedOffset(ulong packetAddress, uint indexOffset, uint indexCount) @@ -49,7 +62,8 @@ internal void DrawIndexedOffset(ulong packetAddress, uint indexOffset, uint inde DrawIndexed(packetAddress, PacketOpcode.DrawIndexOffset2, indexCount, IndexBaseAddress + (indexOffset * IndexElementSize)); } - internal void DrawAuto(ulong packetAddress, uint opcode, uint vertexCount, uint instanceCount = 0, uint firstVertex = 0, uint firstInstance = 0, DrawOffsetSource offsetSource = DrawOffsetSource.Packet, int startInstanceUserData = -1) + internal void DrawAuto(ulong packetAddress, uint opcode, uint vertexCount, uint instanceCount = 0, uint firstVertex = 0, uint firstInstance = 0, DrawOffsetSource offsetSource = DrawOffsetSource.Packet, + bool firstVertexInRegister = false, bool firstInstanceInRegister = false, int startInstanceUserData = -1) { if (instanceCount == 0) { @@ -58,11 +72,13 @@ internal void DrawAuto(ulong packetAddress, uint opcode, uint vertexCount, uint if (Rendering.ScissorTrace.Instance is { Active: true } trace) trace.DrawIssued(TypedRegisters, SubmitId, QueueId, packetAddress); - _host.DrawAuto(SubmitId, new DrawAutoArguments(packetAddress, opcode, vertexCount, instanceCount, firstVertex, firstInstance, offsetSource, startInstanceUserData)); + _host.DrawAuto(SubmitId, new DrawAutoArguments(packetAddress, opcode, vertexCount, instanceCount, firstVertex, firstInstance, offsetSource, startInstanceUserData, + FirstVertexInRegister: firstVertexInRegister, FirstInstanceInRegister: firstInstanceInRegister)); } // Indirect arguments are read from guest memory now, as the packet executes. - internal void DrawIndirect(ulong packetAddress, uint opcode, uint dataOffset, uint drawInitiator, bool indexed, int startInstanceUserData) + internal void DrawIndirect(ulong packetAddress, uint opcode, uint dataOffset, uint drawInitiator, bool indexed, + DrawRegisterLocations locations = default) { if ((drawInitiator & ~0x20u) != 2u) { @@ -74,10 +90,11 @@ internal void DrawIndirect(ulong packetAddress, uint opcode, uint dataOffset, ui throw _host.Fatal($"The indirect draw arguments base is zero: address=0x{packetAddress:X16}."); } - DrawIndirectArguments(packetAddress, opcode, DrawIndirectArgumentsBase + dataOffset, indexed, startInstanceUserData); + DrawIndirectArguments(packetAddress, opcode, DrawIndirectArgumentsBase + dataOffset, indexed, locations, 0); } - internal void DrawIndirectMulti(ulong packetAddress, uint opcode, uint dataOffset, uint maxCountOrCount, ulong countAddress, uint strideInBytes, uint drawInitiator, bool indexed, int startInstanceUserData) + internal void DrawIndirectMulti(ulong packetAddress, uint opcode, uint dataOffset, uint maxCountOrCount, ulong countAddress, uint strideInBytes, uint drawInitiator, bool indexed, + DrawRegisterLocations locations = default) { if ((drawInitiator & ~0x20u) != 2u) { @@ -108,35 +125,50 @@ internal void DrawIndirectMulti(ulong packetAddress, uint opcode, uint dataOffse for (var draw = 0u; draw < drawCount; draw++) { - DrawIndirectArguments(packetAddress, opcode, DrawIndirectArgumentsBase + dataOffset + ((ulong)draw * strideInBytes), indexed, startInstanceUserData); + DrawIndirectArguments(packetAddress, opcode, DrawIndirectArgumentsBase + dataOffset + ((ulong)draw * strideInBytes), indexed, locations, draw); } } - private void DrawIndirectArguments(ulong packetAddress, uint opcode, ulong argumentsAddress, bool indexed, int startInstanceUserData) + // A value the CP writes to a register reaches the shader there, which adds it to its vertex or instance id; the + // draw then counts those from 0. A start instance in the vertex program's live user data stays in the arguments + // instead: the draw passes it as its first instance and the program stores its base instance in that user data + // (StartInstanceUserData), so the host can leave the arguments on the GPU. A named base vertex, or a start instance + // in another register, takes its value here, so the draw reads its arguments now. + private void DrawIndirectArguments(ulong packetAddress, uint opcode, ulong argumentsAddress, bool indexed, DrawRegisterLocations locations, uint drawIndex) { - if (!indexed && _host.ResolvesIndirectDrawOnGpu) - { - _deferredInstanceCountAddress = argumentsAddress + 4; - if (Rendering.ScissorTrace.Instance is { Active: true } gpuTrace) - gpuTrace.DrawIssued(TypedRegisters, SubmitId, QueueId, packetAddress); - _host.DrawAuto(SubmitId, new DrawAutoArguments(packetAddress, opcode, uint.MaxValue, 1, 0, 0, - DrawOffsetSource.IndirectArguments, startInstanceUserData, argumentsAddress)); - return; - } - + var startInstanceUserData = StartInstanceUserData(locations.StartInstance); + var vertexInRegister = DrawRegisterLocations.Names(locations.BaseVertex); + var instanceInRegister = DrawRegisterLocations.Names(locations.StartInstance) && startInstanceUserData < 0; + var registersNeedArguments = vertexInRegister || instanceInRegister; if (!indexed) { + if (!registersNeedArguments && _host.ResolvesIndirectDrawOnGpu) + { + WriteDrawRegister(locations.DrawIndex, drawIndex); + // The host reads the four arguments on the GPU, or itself when the draw needs the counts. + _deferredInstanceCountAddress = argumentsAddress + 4; + if (Rendering.ScissorTrace.Instance is { Active: true } gpuTrace) + gpuTrace.DrawIssued(TypedRegisters, SubmitId, QueueId, packetAddress); + _host.DrawAuto(SubmitId, new DrawAutoArguments(packetAddress, opcode, uint.MaxValue, 1, 0, 0, + DrawOffsetSource.IndirectArguments, startInstanceUserData, argumentsAddress)); + return; + } + var vertexCount = ReadDword(argumentsAddress); var instanceCount = ReadDword(argumentsAddress + 4); var startVertex = ReadDword(argumentsAddress + 8); var startInstance = ReadDword(argumentsAddress + 12); InstanceCount = instanceCount; - DrawAuto(packetAddress, opcode, vertexCount, instanceCount, startVertex, startInstance, DrawOffsetSource.IndirectArguments, startInstanceUserData); + WriteDrawRegisters(locations, startVertex, startInstance, drawIndex, instanceInRegister); + DrawAuto(packetAddress, opcode, vertexCount, instanceCount, vertexInRegister ? 0 : startVertex, + instanceInRegister ? 0 : startInstance, DrawOffsetSource.IndirectArguments, vertexInRegister, instanceInRegister, + startInstanceUserData); return; } - if (_host.ResolvesIndirectDrawOnGpu && IndexTypeAndSize is 0 or 1 && TryGetGpuIndexRange(out var gpuIndexCount)) + if (!registersNeedArguments && _host.ResolvesIndirectDrawOnGpu && IndexTypeAndSize is 0 or 1 && TryGetGpuIndexRange(out var gpuIndexCount)) { + WriteDrawRegister(locations.DrawIndex, drawIndex); // The host reads the five arguments on the GPU. It draws from the whole index // range; the arguments pick the indices. The host falls back to reading them // itself when the draw needs the counts. @@ -145,7 +177,8 @@ private void DrawIndirectArguments(ulong packetAddress, uint opcode, ulong argum trace.DrawIssued(TypedRegisters, SubmitId, QueueId, packetAddress); _host.DrawIndexed(SubmitId, new DrawIndexedArguments( packetAddress, opcode, gpuIndexCount, IndexBaseAddress, IndexTypeAndSize, 1, 0, 0, - DrawOffsetSource.IndirectArguments, argumentsAddress, UnboundedIndexBuffer: IndexBufferSize == 0, StartInstanceUserData: startInstanceUserData)); + DrawOffsetSource.IndirectArguments, argumentsAddress, UnboundedIndexBuffer: IndexBufferSize == 0, + StartInstanceUserData: startInstanceUserData)); return; } @@ -162,15 +195,48 @@ private void DrawIndirectArguments(ulong packetAddress, uint opcode, ulong argum LearnIndexExtent(startIndex, indexCountPerInstance); } - DrawIndexed(packetAddress, opcode, indexCount, indexAddress, indexedInstanceCount, unchecked((int)baseVertex), indexedStartInstance, DrawOffsetSource.IndirectArguments, startInstanceUserData); + WriteDrawRegisters(locations, baseVertex, indexedStartInstance, drawIndex, instanceInRegister); + DrawIndexed(packetAddress, opcode, indexCount, indexAddress, indexedInstanceCount, + vertexInRegister ? 0 : unchecked((int)baseVertex), + instanceInRegister ? 0 : indexedStartInstance, DrawOffsetSource.IndirectArguments, vertexInRegister, instanceInRegister, + startInstanceUserData); } + private void WriteDrawRegisters(DrawRegisterLocations locations, uint baseVertex, uint startInstance, uint drawIndex, bool instanceInRegister) + { + WriteDrawRegister(locations.BaseVertex, baseVertex); + if (instanceInRegister) + { + WriteDrawRegister(locations.StartInstance, startInstance); + } + + WriteDrawRegister(locations.DrawIndex, drawIndex); + } + + // The vertex program's user data index of a start instance register, or -1 when the register is not one of the + // user data registers the program loads. private int StartInstanceUserData(uint location) { var index = location - ShaderRegisterOffset.SpiShaderUserDataGs0; return index < TypedRegisters.Shader.Vertex.GeometryResource2.UserScalarCount ? (int)index : -1; } + private void WriteDrawRegister(uint offset, uint value) + { + if (!DrawRegisterLocations.Names(offset)) + { + return; + } + + if (offset >= RegisterBankLayout.ShaderRegisterCount) + { + throw _host.Fatal($"The draw register is outside the bank: offset=0x{offset:X8}."); + } + + Registers.Shader[offset] = value; + RegisterWriteTable.WriteShaderEntry(TypedRegisters, offset, value, 0); + } + // An index buffer without a size (INDEX_BUFFER_SIZE never set) has no bound the GPU // path could bind. The extent the draws from an index base have used so far, rounded // up to the end of its 16 KiB page, stands in for it; every 1024th such draw reads its @@ -244,11 +310,12 @@ internal void DispatchIndirect(uint dataOffset, uint dispatchInitiator) private const uint DispatchInitiatorUseThreadDimensions = 1u << 5; // Group counts written by an earlier shader are only in GPU memory; reading them - // here waits for the GPU. When the host dispatches indirectly they stay there. - // Thread-unit dispatches still need the counts to convert them to groups. + // here waits for the GPU. When the host dispatches indirectly they stay there, and + // thread counts too when the host converts them to groups on the GPU. private void DispatchIndirectAt(ulong argumentsAddress, uint dispatchInitiator) { - if (_host.ResolvesIndirectDispatchOnGpu && (dispatchInitiator & DispatchInitiatorUseThreadDimensions) == 0) + if (_host.ResolvesIndirectDispatchOnGpu && + ((dispatchInitiator & DispatchInitiatorUseThreadDimensions) == 0 || _host.ResolvesIndirectThreadDispatchOnGpu)) { DispatchDirect(0, 0, 0, dispatchInitiator, argumentsAddress); return; @@ -301,7 +368,8 @@ internal uint DrawIndirectPacket(in PacketContext packet, ReadOnlySpan pay throw _host.Fatal($"The indirect draw header is not supported: header=0x{packet.Header:X8} address=0x{packet.PacketAddress:X16}."); } - DrawIndirect(packet.PacketAddress, packet.Opcode, payload[0], payload[3], indexed, StartInstanceUserData(payload[2] & 0xFFFFu)); + DrawIndirect(packet.PacketAddress, packet.Opcode, payload[0], payload[3], indexed, + DrawRegisterLocations.FromPacket(payload[1], payload[2])); return 4; } @@ -315,7 +383,8 @@ internal uint DrawIndirectMultiPacket(in PacketContext packet, ReadOnlySpan> 30) & 0x1u; var countAddress = countIndirect != 0 ? Address(payload[5], payload[6]) : 0; - DrawIndirectMulti(packet.PacketAddress, packet.Opcode, payload[0], payload[4], countAddress, payload[7], payload[8], indexed, StartInstanceUserData(payload[2] & 0xFFFFu)); + DrawIndirectMulti(packet.PacketAddress, packet.Opcode, payload[0], payload[4], countAddress, payload[7], payload[8], indexed, + DrawRegisterLocations.FromPacket(payload[1], payload[2])); return 9; } diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Labels.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Labels.cs index f57365de4..d342062e1 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Labels.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Labels.cs @@ -254,11 +254,20 @@ private void PublishLabel(in EndOfPipeWrite write, bool is64Bit) if (_host.TryDeferEndOfPipe(QueueId, in completion)) { _lastWriteLength = 0; + // SHARPEMU_END_OF_PIPE_SOFT_WAITS: a deferred label replaces any earlier hint for its address. + Landings?.Forget(write.Destination); return; } if (completion.WaitForGpu) _host.SynchronizeGpu(); if (is64Bit) WriteQword(write.Destination, write.Value); else WriteDword(write.Destination, (uint)write.Value); + // SHARPEMU_END_OF_PIPE_SOFT_WAITS: the label is visible now; the host names the tick its release completes at. + if (Landings is { } landings && landings.Publish(QueueId, in write) is { } landing) + { + _host.RecordEndOfPipe(write with { Landing = landing }); + return; + } + _host.RecordEndOfPipe(in write); } diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Memory.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Memory.cs index 1fec55975..78240e4f6 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Memory.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Memory.cs @@ -109,6 +109,15 @@ internal void TransferData( throw _host.Fatal($"The DMA destination selector is not supported: selector=0x{destinationSelect:X2} destination=0x{destination:X16}."); } + // A forwarded wait can pass before its foreign label publishes. The buffer cache may + // implement this transfer with CPU reads/writes, even when its ranges do not overlap + // the label. Keep the packet pending until that queue-order dependency completes. + if (_host.MustHoldForCrossQueueOrder(QueueId)) + { + Suspend(); + return; + } + if (sourceSelect == 2) { _host.FillBuffer(destination, byteCount, (uint)sourceOrImmediate, destinationIsGds); diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Waits.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Waits.cs index 56420dba7..97e2b6166 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Waits.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Waits.cs @@ -30,6 +30,19 @@ internal void WaitOnMemory(uint compareFunction, ulong address, ulong reference, return; } + // SHARPEMU_END_OF_PIPE_SOFT_WAITS: this packet's wait already passed on an earlier try. Only its advisory delay + // resumes: the label is not read or compared again, so a later change of the label cannot undo the pass. + if (_softWait is { } soft) + { + if (soft.Is(_execution, _packetAddress)) + { + ResumeSoftWait(soft); + return; + } + + EndSoftWait(); + } + // A deferred label is visible here at once; guest CPU threads see it after the dump before it. if (!_host.TryReadDeferredLabel(QueueId, address, is64Bit ? 8UL : 4UL, out var deferred, out var value)) { @@ -60,14 +73,81 @@ internal void WaitOnMemory(uint compareFunction, ulong address, ulong reference, if (!satisfied && TryReadOwnWrite(address, is64Bit, out var ownValue)) { _ = WaitOperation.TryCompare(ownValue, reference, mask, compareFunction, out satisfied); + if (satisfied) + { + return; + } } if (!satisfied) { Suspend(); + return; + } + + // Met by the label bytes in guest memory, not a deferred label or this queue's own write. + if (!deferred && Landings is { } landings && _execution is { } execution && + landings.Admit(QueueId, address, is64Bit ? 8 : 4, compareFunction, reference, mask, value, CompletedGpuTick) is { } landing) + { + ResumeSoftWait(new SoftWait(execution, execution.Depth, _packetAddress, landing, System.Diagnostics.Stopwatch.GetTimestamp())); } } + // SHARPEMU_END_OF_PIPE_SOFT_WAITS: the wait of this packet passed, on a label another queue's release wrote, but the + // work in front of that release has not completed on the GPU. While another queue's head may run, the packet suspends + // as an unmet wait does and runs again later, resuming only this delay; the wait then passes once that work completed, + // once no other head may run, or at the deadline counted from the first suspension. A release + // is used by one soft wait once. + private void ResumeSoftWait(SoftWait soft) + { + var elapsed = System.Diagnostics.Stopwatch.GetTimestamp() - soft.Since; + var landings = Landings; + EndOfPipeLandings.Release? release = + landings is null ? EndOfPipeLandings.Release.Off + : soft.Landing.IsComplete(CompletedGpuTick) ? EndOfPipeLandings.Release.Complete + : elapsed >= landings.CapTicks ? EndOfPipeLandings.Release.Cap + : !MayDeferForLanding ? EndOfPipeLandings.Release.Idle + : null; + if (release is { } reason) + { + soft.Landing.ReleasedBy = reason; + soft.Landing.Consume(); + _softWait = null; + return; + } + + _softWait = soft; + _suspendedForLanding = true; + Suspend(); + } + + // Ends a soft wait that no longer belongs to the packet running now (its submission was dropped or the queue reset). + private void EndSoftWait() + { + if (_softWait is not { } soft) + { + return; + } + + soft.Landing.Consume(); + _softWait = null; + _suspendedForLanding = false; + } + + // The packet a soft wait suspended: its submission's cursor stack, the depth and the packet address. Only the retry of + // that packet resumes it; any other packet ends it. + private sealed class SoftWait(PacketCursorStack execution, int depth, ulong packetAddress, EndOfPipeLanding landing, long since) + { + internal PacketCursorStack Execution { get; } = execution; + + internal EndOfPipeLanding Landing { get; } = landing; + + internal long Since { get; } = since; + + internal bool Is(PacketCursorStack? current, ulong currentPacket) => + ReferenceEquals(Execution, current) && current!.Depth == depth && currentPacket == packetAddress; + } + // The wait bit is PredicationZPassWaitOp: 0 (kWaitForQueryResults) stalls the command // processor until the results arrive, 1 (kDoNotPredicateIfQueryResultsNotReady) never // stalls and leaves the tagged packets unpredicated while the results are outstanding. diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs index 2802f55e2..2946b69f3 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs @@ -48,6 +48,11 @@ public sealed partial class GpuCommandInterpreter private ulong _lastWriteValue; private int _lastWriteLength; private ulong _lastWritePacket; + // SHARPEMU_END_OF_PIPE_SOFT_WAITS: the packet whose passed wait waits softly for a release, whether the last slice + // stopped for it, and the address of the packet whose handler runs now. + private SoftWait? _softWait; + private bool _suspendedForLanding; + private ulong _packetAddress; public GpuCommandInterpreter(ICommandStreamHost host, int queueId, int interruptEventId) { @@ -72,6 +77,28 @@ internal void SetPacketHandlers(PacketHandler?[] handlers) public bool IsComputeQueue => InterruptEventId >= ComputeQueueBase; + // SHARPEMU_END_OF_PIPE_SOFT_WAITS: the releases of every queue, set by the command stream queue; null when off. + internal EndOfPipeLandings? Landings { get; set; } + + // Set by the command stream queue for each slice: another queue's head may run now, and the newest completed GPU tick. + internal bool MayDeferForLanding { get; set; } + + internal ulong CompletedGpuTick { get; set; } + + // The release the last slice stopped for, or null, and when its soft wait began; the queue keeps such a head runnable, + // behind the other queues, until the same deadline. + internal EndOfPipeLanding? TakeLandingDeferral(out long since) + { + since = _softWait?.Since ?? 0; + if (!_suspendedForLanding || _softWait is null) + { + return null; + } + + _suspendedForLanding = false; + return _softWait.Landing; + } + public CommandRegisterBanks Registers { get; } = new(); // The typed banks the render executor reads; the dictionaries feed the translation they replace. @@ -165,6 +192,8 @@ public void Reset() { var before = TypedRegisters.Context; _lastWriteLength = 0; + // A register reset leaves labels in memory as they are; only this queue's own soft wait ends. + EndSoftWait(); Registers.Reset(); TypedRegisters.Reset(); IndexTypeAndSize = 0; @@ -212,6 +241,12 @@ public SubmissionProgress Process(PacketCursorStack execution, ulong address, ui execution.Suspended = false; execution.MadeProgress = false; + _suspendedForLanding = false; + // A soft wait of a submission that will not run again (dropped, cancelled or discarded) ends here. + if (_softWait is { } soft && !ReferenceEquals(soft.Execution, execution)) + { + EndSoftWait(); + } // Forwarding is local to this slice, never a cached signal from an older submission. _lastWriteLength = 0; _pendingCommands = _host.CommandSignal; @@ -416,6 +451,7 @@ 0 or PacketCustomCode.PushMarker or PacketCustomCode.PopMarker or } var packet = new PacketContext(header & ~1u, packetAddress, offset, remaining, total); + _packetAddress = packetAddress; uint consumed; var handlerStarted = SharpEmu.Libs.Diagnostics.PacketHandlerTally.Enabled ? Stopwatch.GetTimestamp() : 0; var waitedBefore = SharpEmu.Libs.Diagnostics.PacketHandlerTally.WaitedTicks; diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs index 825e61110..eb131aa38 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs @@ -31,7 +31,11 @@ public readonly record struct DrawIndexedArguments( // The guest set no index buffer size: IndexCount is only the range seen so far and // must not clamp the count read from the arguments. bool UnboundedIndexBuffer = false, - int StartInstanceUserData = -1); + int StartInstanceUserData = -1, + // The indirect packet named a shader register for the base vertex or the start instance: the + // value is in that register, and BaseVertex or FirstInstance is 0. + bool BaseVertexInRegister = false, + bool FirstInstanceInRegister = false); // Arguments of a non-indexed draw as the packet stream describes them. public readonly record struct DrawAutoArguments( @@ -43,7 +47,13 @@ public readonly record struct DrawAutoArguments( uint FirstInstance, DrawOffsetSource OffsetSource, int StartInstanceUserData = -1, - ulong IndirectArgumentsAddress = 0); + // Nonzero when the counts are still in guest memory at this address, laid out as + // (vertexCount, instanceCount, firstVertex, firstInstance). + ulong IndirectArgumentsAddress = 0, + // The indirect packet named a shader register for the start vertex or the start instance: the + // value is in that register, and FirstVertex or FirstInstance is 0. + bool FirstVertexInRegister = false, + bool FirstInstanceInRegister = false); public enum EndOfPipeWriteKind { @@ -80,7 +90,9 @@ public readonly record struct EndOfPipeWrite( int FlipMode = 0, long FlipArgument = 0, ulong FlipRequestId = 0, - bool WaitForGpu = false); + bool WaitForGpu = false, + // SHARPEMU_END_OF_PIPE_SOFT_WAITS: the host names the GPU tick that completes this write. + EndOfPipeLanding? Landing = null); // Everything a packet handler needs from the renderer, the caches, the scheduler and video out. public interface ICommandStreamHost @@ -219,8 +231,12 @@ ulong PrepareFlip(int queueId, int handle, int index, int flipMode, long flipArg // GPU, so the interpreter need not wait for the GPU to read them back first. bool ResolvesIndirectDispatchOnGpu => false; - // True when an indexed indirect draw may be handed over with its arguments still in - // guest memory (DrawIndexedArguments.IndirectArgumentsAddress). + // True when an indirect dispatch whose arguments count threads (DISPATCH_INITIATOR.USE_THREAD_DIMENSIONS) also keeps + // its counts on the GPU (IRenderHost.PrepareThreadDispatch). + bool ResolvesIndirectThreadDispatchOnGpu => false; + + // True when an indirect draw may be handed over with its arguments still in guest + // memory (the IndirectArgumentsAddress of DrawIndexedArguments and DrawAutoArguments). bool ResolvesIndirectDrawOnGpu => false; // Called when a queue reset packet clears the processor. diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/RegisterBanks.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/RegisterBanks.cs index 3576c7344..fdc4bbec3 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/RegisterBanks.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/Registers/RegisterBanks.cs @@ -102,6 +102,9 @@ public RegisterBanks Clone() private bool _computeShared; private bool _userConfigShared; + // Only Snapshot publishes the read-only banks used by deferred draws. + internal bool IsSnapshot { get; private set; } + // A read-only copy that shares every part with the live banks until they next write it: a // deferred draw takes one per draw, and between draws only a few parts change. public RegisterBanks Snapshot() => Snapshot(null); @@ -127,6 +130,7 @@ public RegisterBanks Snapshot(RegisterBanks? shell) snapshot.OwnContext(Context); } + snapshot.IsSnapshot = true; snapshot.CompositeDepthSizeXy = CompositeDepthSizeXy; snapshot.UserDataMarker = UserDataMarker; snapshot.IndexTypeAndSize = IndexTypeAndSize; diff --git a/src/SharpEmu.Libs/Gpu/IGuestGpuBackend.cs b/src/SharpEmu.Libs/Gpu/IGuestGpuBackend.cs index c08d2281c..9b19fa958 100644 --- a/src/SharpEmu.Libs/Gpu/IGuestGpuBackend.cs +++ b/src/SharpEmu.Libs/Gpu/IGuestGpuBackend.cs @@ -30,6 +30,9 @@ internal interface IGuestGpuBackend // Compiles one permutation of a program over its resource plan and binding layout. bool TryCompileProgram(ShaderCompileRequest request, out IGuestCompiledShader? shader, out string error); + // The shader of a translation the translation disk cache kept (TranslationDiskCache); null when the backend keeps none. + IGuestCompiledShader? CreateCachedShader(byte[] payload, uint? inputLocationMask) => null; + // The vertex stage a tessellated pipeline requires and the control stage that feeds the guest's hull factors to the tessellator. (IGuestCompiledShader Vertex, IGuestCompiledShader Control) CompileTessellationBridge( SharpEmu.ShaderCompiler.Resources.BindingLayout layout, Gen5TessellationDomain domain) => diff --git a/src/SharpEmu.Libs/Gpu/Images/CachedImage.cs b/src/SharpEmu.Libs/Gpu/Images/CachedImage.cs index a3575406e..6bf5792cc 100644 --- a/src/SharpEmu.Libs/Gpu/Images/CachedImage.cs +++ b/src/SharpEmu.Libs/Gpu/Images/CachedImage.cs @@ -106,6 +106,9 @@ public sealed unsafe partial class CachedImage : IDisposable // Set while descriptor set 1 holds a view of this image: told when its layout, contents or registration change. public Action? HeapChanged; + // Set when the image is deleted while descriptor set 1 still holds its view; frees the slot after the current tick. + // The heap runs it once it has rewritten the last element that names the image. + public Action? DeferredErase; public bool Registered; public uint QueryEpoch; public ulong WatchBegin; @@ -116,6 +119,11 @@ public sealed unsafe partial class CachedImage : IDisposable public bool Parked; public ulong ParkedTick; + // The image of the other dimensional type (1D or 2D) over the same single-row memory. Both are kept while they hold the + // same contents; a GPU write to either leaves the other stale, and the cache replaces the stale one on its next lookup. + public CachedImage? DimensionTwin; + public bool DimensionTwinStale; + public CachedImage(GpuDeviceInfo device, SubmissionScheduler scheduler, IGuestBackedSpace guestBacking, in ImageDescription description, ImageBackingPool? pool = null, Action? reportAllocationFailure = null) { @@ -187,20 +195,30 @@ public CachedImage(GpuDeviceInfo device, SubmissionScheduler scheduler, IGuestBa }; var allocated = Result.ErrorOutOfDeviceMemory; var allocationAttempted = false; - for (uint index = 0; index < device.MemoryTypeCount; index++) + // Device-local memory first. When it is exhausted, any other type the image allows: system memory the device reads + // over the bus is slow but keeps the run going, as GpuBuffer.RankMemoryTypes does for buffers. + for (var deviceLocalPass = 1; deviceLocalPass >= 0 && allocated != Result.Success; deviceLocalPass--) { - if ((requirements.MemoryTypeBits & (1u << (int)index)) == 0 || - (device.GetMemoryTypeFlags(index) & MemoryPropertyFlags.DeviceLocalBit) == 0) + for (uint index = 0; index < device.MemoryTypeCount; index++) { - continue; - } + var deviceLocal = (device.GetMemoryTypeFlags(index) & MemoryPropertyFlags.DeviceLocalBit) != 0; + if ((requirements.MemoryTypeBits & (1u << (int)index)) == 0 || deviceLocal != (deviceLocalPass == 1)) + { + continue; + } - allocateInfo.MemoryTypeIndex = index; - allocationAttempted = true; - allocated = device.AllocateMemory(allocateInfo, out Backing.Memory); - if (allocated == Result.Success) - { - break; + allocateInfo.MemoryTypeIndex = index; + allocationAttempted = true; + allocated = device.AllocateMemory(allocateInfo, out Backing.Memory); + if (allocated == Result.Success) + { + if (!deviceLocal) + { + ReportSystemMemoryImage(create, requirements.Size, index); + } + + break; + } } } @@ -214,7 +232,7 @@ public CachedImage(GpuDeviceInfo device, SubmissionScheduler scheduler, IGuestBa Backing.Handle = default; Backing.Memory = default; reportAllocationFailure?.Invoke(); - throw CreateFailure(create, !allocationAttempted ? "select_device_local_memory_type" : + throw CreateFailure(create, !allocationAttempted ? "select_memory_type" : allocated != Result.Success ? "vkAllocateMemory" : "vkBindImageMemory", bindingResult, requirements.Size, requirements.MemoryTypeBits); } @@ -222,6 +240,19 @@ public CachedImage(GpuDeviceInfo device, SubmissionScheduler scheduler, IGuestBa Backing.AllocationSize = requirements.Size; } + private static int _systemMemoryImageReports; + + private static void ReportSystemMemoryImage(in ImageCreateInfo create, ulong size, uint memoryType) + { + if (Interlocked.Increment(ref _systemMemoryImageReports) <= 16) + { + Console.Error.WriteLine( + $"[GPU][WARN] Device-local memory is exhausted; the image is in system memory: extent={create.Extent.Width}x" + + $"{create.Extent.Height}x{create.Extent.Depth} format={create.Format} layers={create.ArrayLayers} " + + $"levels={create.MipLevels} bytes={size} memory_type={memoryType}"); + } + } + private static Exception CreateFailure(in ImageCreateInfo create, string operation, Result result, ulong allocationSize = 0, uint memoryTypeBits = 0) => SubmissionScheduler.Fatal( @@ -470,6 +501,11 @@ public void MarkGpuModified() { RawWriteAfterGpuWrite = false; _gpuModified = true; + if (DimensionTwin is { } twin) + { + twin.DimensionTwinStale = true; + } + _bufferHoldsGpuContents = false; GpuWriteSequence = Interlocked.Increment(ref _gpuWriteCounter); _guestPieceHashes = null; @@ -478,6 +514,20 @@ public void MarkGpuModified() public void ClearGpuModified() => _gpuModified = false; + private ulong _readbackUntilFrame; + + internal bool HasReadbackWindow { get; private set; } + + internal ulong ReadbackUntilFrame + { + get => _readbackUntilFrame; + set + { + _readbackUntilFrame = value; + HasReadbackWindow = true; + } + } + public bool IsBufferModified => _bufferModified; // The guest buffer cache holds this image's current GPU contents. diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Collection.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Collection.cs index 14029c678..aa104221f 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Collection.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Collection.cs @@ -130,15 +130,33 @@ public void FlushScheduledReadbacks() foreach (var imageIdentifier in _scheduledReadbacks) { var owner = _slots.TryGet(imageIdentifier); - if (owner != null && owner.Registered && owner.IsGpuModified) + if (owner != null && owner.Registered && owner.IsGpuModified && !HostLayoutTargets.Holds(owner.Description.Data.Address) && + TryDownloadToGuest(imageIdentifier)) { - _ = TryDownloadToGuest(imageIdentifier); + ReportLinearReadback(owner); } } _scheduledReadbacks.Clear(); } + private const int MaxReportedLinearReadbacks = 16; + private static readonly System.Collections.Concurrent.ConcurrentDictionary ReportedLinearReadbacks = new(); + + private static void ReportLinearReadback(CachedImage image) + { + var description = image.Description; + if (ReportedLinearReadbacks.Count >= MaxReportedLinearReadbacks || !ReportedLinearReadbacks.TryAdd(description.Data.Address, 0)) + { + return; + } + + Console.Error.WriteLine( + $"[GPU][INFO] linear image readback address=0x{description.Data.Address:X16} bytes=0x{description.Data.Size:X} " + + $"extent={description.Extent.Width}x{description.Extent.Height}x{description.Extent.Depth} layers={description.Resources.Layers} " + + $"levels={description.Resources.Levels} format={description.PixelFormat} guest_format={description.GuestFormat} render_target={image.Uses.RenderTarget}"); + } + private long _pendingDestroyBytes; private long _destroyedImageReclaims; diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Lookup.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Lookup.cs index c01b63579..0e803a1a0 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Lookup.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Lookup.cs @@ -221,7 +221,7 @@ private bool TryReuseLookup(ref ImageRequest request, bool exactFormat, out Reso ref var memo = ref lookups[LookupSlot(request, exactFormat)]; if (memo.ExactFormat != exactFormat || !SameRequest(memo.Request, request) || !LookupUnchangedSince(memo.Generation, memo.Begin, memo.End) || - _slots.TryGet(memo.Result) is not { Registered: true, Parked: false } image) + _slots.TryGet(memo.Result) is not { Registered: true, Parked: false, DimensionTwinStale: false } image) { _lookupMisses++; _totalLookupMisses.Increment(); diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Overlap.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Overlap.cs index 63e95ab9c..9e9bd15bd 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Overlap.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Overlap.cs @@ -571,6 +571,66 @@ private OverlapResolution ResolveOverlap(in ImageDescription requested, ImageRol return new OverlapResolution(mergedImageIdentifier); } + // Releases the images that a GPU write to their dimension twin left stale; true when one was released. + private bool ReleaseStaleDimensionTwins(in ImageQueryResults candidates) + { + var released = false; + foreach (var candidate in candidates) + { + if (_slots.TryGet(candidate) is { Registered: true, DimensionTwinStale: true }) + { + ReleaseImage(candidate); + released = true; + } + } + + return released; + } + + // The image's registered twin when it gives the requested view. + private ResourceSlotIdentifier FindDimensionTwin(in ImageQueryResults candidates, CachedImage image, in ImageViewDescription view) + { + if (image.DimensionTwin is not { Registered: true, DimensionTwinStale: false } twin || !twin.SupportsViewType(view)) + { + return ResourceSlotIdentifier.Invalid; + } + + foreach (var candidate in candidates) + { + if (ReferenceEquals(_slots.TryGet(candidate), twin)) + { + return candidate; + } + } + + return ResourceSlotIdentifier.Invalid; + } + + // An image of the other dimensional type beside the partner, filled from guest memory like any new image. + private ResourceSlotIdentifier InsertDimensionTwin(in ImageDescription description, CachedImage partner) + { + if (partner.DimensionTwin is { } previous) + { + previous.DimensionTwin = null; + } + + var twinIdentifier = InsertImage(description); + var twin = _slots[twinIdentifier]; + twin.Uses = partner.Uses; + if (_bufferCache.HasGpuDirtyBytes(twin.Description.Data.Address, twin.Description.Data.Size)) + { + twin.MarkBufferModified(); + } + else + { + PopulateFromGuest(twinIdentifier, ImageRequest.Refresh(description, UploadRole(twin)), "dimension-twin"); + } + + twin.DimensionTwin = partner; + partner.DimensionTwin = twin; + return twinIdentifier; + } + // Replaces the source with a larger image that starts with the source contents. private ResourceSlotIdentifier GrowImage(in ImageDescription description, ResourceSlotIdentifier sourceImageIdentifier) { diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Tracking.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Tracking.cs index bf8f2b00e..d57c9040f 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Tracking.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Tracking.cs @@ -71,7 +71,8 @@ private void RemoveFromIndex(ResourceSlotIdentifier imageIdentifier) image.HeapChanged?.Invoke(image); } - // Removes the image and its stencil associations; the slot is freed after the current tick. + // Removes the image and its stencil associations; the slot is freed after the current tick, or for an image the bindless + // heap names, after the tick in which the heap lets go of it. private void DeleteImage(ResourceSlotIdentifier imageIdentifier) { using var profileScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ImageDelete); @@ -87,6 +88,12 @@ private void DeleteImage(ResourceSlotIdentifier imageIdentifier) _parked.Remove(imageIdentifier); } + if (image.DimensionTwin is { } twin) + { + twin.DimensionTwin = null; + image.DimensionTwin = null; + } + if (!image.DepthOwner.IsValid) { var associations = new List(); @@ -127,9 +134,23 @@ private void DeleteImage(ResourceSlotIdentifier imageIdentifier) } RemoveFromIndex(imageIdentifier); + // Descriptor set 1 still names a view of this image until the heap rewrites the element. A wait before that + // can complete this tick and run its erase, and a draw recorded after it would read a destroyed view. + var bytes = (long)image.Backing.AllocationSize; + if (image.HeapChanged is not null) + { + image.DeferredErase = () => EraseAfterCurrentTick(imageIdentifier, bytes, callerHoldsLock: false); + return; + } + + EraseAfterCurrentTick(imageIdentifier, bytes, callerHoldsLock: true); + } + + // Frees the slot once the current tick completes, or at once when no tick is recording. + private void EraseAfterCurrentTick(ResourceSlotIdentifier imageIdentifier, long bytes, bool callerHoldsLock) + { if (_scheduler.Active) { - var bytes = (long)image.Backing.AllocationSize; Interlocked.Add(ref _pendingDestroyBytes, bytes); _scheduler.QueueCompletionAction(() => { @@ -137,8 +158,13 @@ private void DeleteImage(ResourceSlotIdentifier imageIdentifier) Interlocked.Add(ref _pendingDestroyBytes, -bytes); }); } + else if (callerHoldsLock) + { + _slots.Erase(imageIdentifier); + } else { + using var held = _lock.Hold(); _slots.Erase(imageIdentifier); } } @@ -396,9 +422,30 @@ private void UnwatchImageTail(ResourceSlotIdentifier imageIdentifier) } } + private const ulong CpuReadbackFrames = 1; + + private void ScheduleReadbackAfterCpuWrite(ResourceSlotIdentifier imageIdentifier, CachedImage image, bool cpuWritten) + { + if (!_readbackLinearImages || image.Description.IsTiled) + { + return; + } + + if (cpuWritten || !image.HasReadbackWindow) + { + image.ReadbackUntilFrame = _collectionTick + CpuReadbackFrames; + } + + if (_collectionTick <= image.ReadbackUntilFrame) + { + ScheduleReadback(imageIdentifier, image); + } + } + private void ScheduleReadback(ResourceSlotIdentifier imageIdentifier, CachedImage image) { - if (_readbackLinearImages && !image.Description.IsTiled && !ImageDescription.IsEmptyRange(image.Description.Data)) + if (_readbackLinearImages && !image.Description.IsTiled && !ImageDescription.IsEmptyRange(image.Description.Data) && + !HostLayoutTargets.Holds(image.Description.Data.Address)) { if (!image.IsGpuModified) { diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Transfers.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Transfers.cs index 94afb3528..629bdf7f7 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Transfers.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Transfers.cs @@ -537,7 +537,7 @@ private void PopulateFromGuest(ResourceSlotIdentifier imageIdentifier, in ImageR } // A maybe-dirty image resolves through its edge hash first; a dirty one is populated again. - private void RefreshFromGuest(ResourceSlotIdentifier imageIdentifier, in ImageRequest request) + private bool RefreshFromGuest(ResourceSlotIdentifier imageIdentifier, in ImageRequest request) { using var profileScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ImageRefresh); WatchImage(imageIdentifier); @@ -548,13 +548,14 @@ private void RefreshFromGuest(ResourceSlotIdentifier imageIdentifier, in ImageRe if (image.NeedsMaybeCpuHash) { image.SetMaybeCpuHash(hash); - return; + return false; } _ = image.ResolveMaybeCpuHash(hash); } - var cpuDirty = image.IsBufferModified || image.IsDefinitelyCpuDirty; + var cpuWritten = image.IsDefinitelyCpuDirty; + var cpuDirty = image.IsBufferModified || cpuWritten; if (image.Description.Metadata.Compression != DisplayCompression.Uncompressed) { if (cpuDirty) @@ -562,15 +563,16 @@ private void RefreshFromGuest(ResourceSlotIdentifier imageIdentifier, in ImageRe throw SubmissionScheduler.Fatal($"A compressed guest image cannot be refreshed from guest memory: address=0x{image.Description.Data.Address:X16} bufferModified={image.IsBufferModified} cpuDirty={image.IsDefinitelyCpuDirty}."); } - return; + return false; } if (!cpuDirty) { - return; + return false; } PopulateFromGuest(imageIdentifier, request, "refresh"); + return cpuWritten; } private void DownloadDepthToBuffer(CachedImage image, GpuBuffer destination, ulong destinationOffset) @@ -707,8 +709,9 @@ public bool TrySynchronizeBufferFromImage(GpuBuffer buffer, ulong address, ulong using var profileScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ImageDownload); using var held = _lock.Hold(); + // Only an image that starts at the address qualifies, and it owns the address's page: the query reads that page. var matches = new List(); - foreach (var imageIdentifier in FindImagesInRange(address, size, pageOverlap: false)) + foreach (var imageIdentifier in FindImagesInRange(address, 1, pageOverlap: false)) { var owner = _slots.TryGet(imageIdentifier); if (owner == null || owner.Description.Data.Address != address) diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.cs index d2ef62d27..d2955903c 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.cs @@ -238,6 +238,11 @@ private ResourceSlotIdentifier LookUpImage(ref ImageRequest request, bool exactF if (ImageClearTrace.Enabled) ImageTraceRange.NoteImageLookup(request.Description.Data.Address, request.Description.Data.Size); PrintResourceHistory(request); var candidates = FindImagesInRange(request.Description.Data.Address, request.Description.Data.Size, pageOverlap: false); + if (ReleaseStaleDimensionTwins(candidates)) + { + candidates = FindImagesInRange(request.Description.Data.Address, request.Description.Data.Size, pageOverlap: false); + } + if (ImageClearTrace.Enabled && request.TraceTextureMetadataAddress != 0) { ImageClearTrace.Write($"texture-owner-search image=0x{request.Description.Data.Address:X16} candidates={candidates.Count}"); @@ -302,7 +307,14 @@ private ResourceSlotIdentifier LookUpImage(ref ImageRequest request, bool exactF var replacement = resolved.Description; replacement.Type = request.View.Type is ImageViewType.Type1D or ImageViewType.Type1DArray ? GuestImageType.Color1D : GuestImageType.Color2D; - result = GrowImage(replacement, result); + // A texture read both as 1D and as 2D keeps an image of each type while both hold the guest's contents. + // Replacing one with the other on every lookup recreated the image endlessly when both types were read. + result = request.Role == ImageRole.Texture && !resolved.IsGpuModified && !resolved.IsBufferModified && + !resolved.DimensionTwinStale + ? FindDimensionTwin(candidates, resolved, request.View) is { IsValid: true } twin + ? twin + : InsertDimensionTwin(replacement, resolved) + : GrowImage(replacement, result); } else if (request.View.Type == ImageViewType.Type3D && resolved.Backing.ImageType != ImageType.Type3D) { @@ -451,9 +463,10 @@ private void AcquireTextureCore(ResourceSlotIdentifier imageIdentifier, CachedIm image.MarkGpuModified(); } + var cpuWritten = false; if (hasData) { - RefreshFromGuest(imageIdentifier, request); + cpuWritten = RefreshFromGuest(imageIdentifier, request); MergeMipTailBlock(image); } @@ -472,7 +485,7 @@ private void AcquireTextureCore(ResourceSlotIdentifier imageIdentifier, CachedIm TakeGpuOwnership(image); } - ScheduleReadback(imageIdentifier, image); + ScheduleReadbackAfterCpuWrite(imageIdentifier, image, cpuWritten); break; default: throw SubmissionScheduler.Fatal($"The texture role is invalid: role={request.Role}."); @@ -512,7 +525,7 @@ private void AcquireColorTargetCore(ResourceSlotIdentifier imageIdentifier, Cach image.MarkGpuModified(); image.Uses.RenderTarget = true; TraceVolumeState("color-acquire", image, request); - RefreshFromGuest(imageIdentifier, request); + var cpuWritten = RefreshFromGuest(imageIdentifier, request); TraceMetadataBinding(request); if (request.Description.Metadata.Kind == MetadataKind.Dcc && request.Description.Metadata.Range.Size == 0) { @@ -544,7 +557,7 @@ private void AcquireColorTargetCore(ResourceSlotIdentifier imageIdentifier, Cach } TakeGpuOwnership(image); - ScheduleReadback(imageIdentifier, image); + ScheduleReadbackAfterCpuWrite(imageIdentifier, image, cpuWritten); } public ImageView AcquireDepthTargetView(ResourceSlotIdentifier imageIdentifier, in ImageRequest request) diff --git a/src/SharpEmu.Libs/Gpu/Images/HostLayoutTargets.cs b/src/SharpEmu.Libs/Gpu/Images/HostLayoutTargets.cs new file mode 100644 index 000000000..ff6cdab60 --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/Images/HostLayoutTargets.cs @@ -0,0 +1,17 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections.Concurrent; + +namespace SharpEmu.Libs.Gpu.Images; + +internal static class HostLayoutTargets +{ + private static readonly ConcurrentDictionary Addresses = new(); + + public static void Mark(ulong address) => Addresses.TryAdd(address, 0); + + public static bool Holds(ulong address) => !Addresses.IsEmpty && Addresses.ContainsKey(address); + + public static void Reset() => Addresses.Clear(); +} diff --git a/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.Texture.cs b/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.Texture.cs index 14a04a8fd..5179c3de7 100644 --- a/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.Texture.cs +++ b/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.Texture.cs @@ -12,15 +12,22 @@ namespace SharpEmu.Libs.Gpu.Images; // A descriptor the texture builder rejected inside ImageRequestBuilders.RejectInvalidDescriptors. public sealed class TextureDescriptorRejectedException(string message) : Exception(message); -// A texture request built from the descriptor words and the shape the shader was compiled with. -public readonly record struct TextureRequestResolution(ImageRequest Request, bool ExactFormat, Format ViewFormat, uint Swizzle); +// A texture request built from the descriptor words and the shape the shader was compiled with. Fields, not properties: +// a request is about 560 bytes, and passing a property to an `in` parameter copies it. +public struct TextureRequestResolution(ImageRequest request, bool exactFormat, Format viewFormat, uint swizzle) +{ + public ImageRequest Request = request; + public bool ExactFormat = exactFormat; + public Format ViewFormat = viewFormat; + public uint Swizzle = swizzle; +} public static partial class ImageRequestBuilders { [ThreadStatic] private static int _rejectInvalidDescriptors; // Inside this scope a descriptor the builder cannot turn into a texture request throws TextureDescriptorRejectedException - // instead of stopping the GPU: a call record holds whatever the game last wrote there. + // instead of stopping the GPU: a bindless heap record holds whatever the game last wrote there. public static RejectionScope RejectInvalidDescriptors() { _rejectInvalidDescriptors++; diff --git a/src/SharpEmu.Libs/Gpu/Images/ViewFormatRules.cs b/src/SharpEmu.Libs/Gpu/Images/ViewFormatRules.cs index adc30b645..8f95cc51c 100644 --- a/src/SharpEmu.Libs/Gpu/Images/ViewFormatRules.cs +++ b/src/SharpEmu.Libs/Gpu/Images/ViewFormatRules.cs @@ -280,9 +280,24 @@ public static uint SelectSampledColorView(Format imageFormat, Format viewFormat, ? swizzle : throw UnsupportedColorView("sampled", imageFormat, viewFormat, swizzle); - public static bool IsSupportedSampledDepthView(Format imageFormat, Format viewFormat, uint swizzle) => - IsSupportedSampledDepthFormat(imageFormat, viewFormat) && - (swizzle == PackDestinationSelect(4, 4, 4, 4) || swizzle == PackDestinationSelect(4, 0, 0, 0) || swizzle == PackDestinationSelect(4, 0, 0, 1)); + public static bool IsSupportedSampledDepthView(Format imageFormat, Format viewFormat, uint swizzle) + { + if (!IsSupportedSampledDepthFormat(imageFormat, viewFormat) || (swizzle & ~0xfffu) != 0) + { + return false; + } + + // A depth view has one channel: the swizzle may repeat it and fill the other channels with 0 or 1. + for (uint channel = 0; channel < 4; channel++) + { + if (DestinationSelect(swizzle, channel) is not (0 or 1 or 4)) + { + return false; + } + } + + return true; + } public static uint SelectSampledDepthView(Format imageFormat, Format viewFormat, uint swizzle) => IsSupportedSampledDepthView(imageFormat, viewFormat, swizzle) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ComputeStageInputResolver.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ComputeStageInputResolver.cs index e866a6681..4401d6240 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ComputeStageInputResolver.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ComputeStageInputResolver.cs @@ -20,7 +20,8 @@ public static ComputeInputInfo Resolve( bool needsLocalDataShareBarriers, uint dispatchX, uint dispatchY, - uint dispatchZ) + uint dispatchZ, + bool gpuThreadCounts = false) { var threadDimensions = (dispatchInitiator & UseThreadDimensionsBit) != 0; return new ComputeInputInfo @@ -29,6 +30,7 @@ public static ComputeInputInfo Resolve( ThreadsY = compute.ThreadsY & 0xFFFFu, ThreadsZ = compute.ThreadsZ & 0xFFFFu, DispatchThreadDimensions = threadDimensions, + IndirectThreadCounts = threadDimensions && gpuThreadCounts, DispatchThreadsX = threadDimensions ? dispatchX : 0, DispatchThreadsY = threadDimensions ? dispatchY : 0, DispatchThreadsZ = threadDimensions ? dispatchZ : 0, diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/DescriptorHeap.cs b/src/SharpEmu.Libs/Gpu/Pipelines/DescriptorHeap.cs index 4531bb774..f053d4136 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/DescriptorHeap.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/DescriptorHeap.cs @@ -56,7 +56,7 @@ private sealed class SetBatchState private readonly GpuDeviceInfo _device; private readonly SubmissionScheduler _scheduler; - private static readonly DescriptorSetDemand PoolCapacity = new(8192, 8192, 1024, 1024); + internal static readonly DescriptorSetDemand PoolCapacity = new(8192, 8192, 1024, 1024); private readonly Queue<(DescriptorPool Pool, ulong Tick)> _pendingPools = new(); private readonly Dictionary _sets = new(); @@ -133,6 +133,18 @@ public DescriptorSet Commit(DescriptorSetLayout layout, in DescriptorSetDemand d // Halves the batch until the pool has room for it; false when one set does not fit. private bool Allocate(DescriptorSetLayout layout, in DescriptorSetDemand demand, SetBatchState batch) + { + if (!TryAllocateBatch(_device, _currentPool, layout, in demand, batch.Sets, ref batch.Allocation, ref _remainingSets, ref _remaining)) + { + return false; + } + + batch.Size = batch.Allocation; + return true; + } + + internal static bool TryAllocateBatch(GpuDeviceInfo device, DescriptorPool pool, DescriptorSetLayout layout, in DescriptorSetDemand demand, + DescriptorSet[] sets, ref uint allocation, ref uint remainingSets, ref DescriptorSetDemand remaining) { var layouts = stackalloc DescriptorSetLayout[(int)SetBatch]; for (var index = 0; index < SetBatch; index++) @@ -142,35 +154,34 @@ private bool Allocate(DescriptorSetLayout layout, in DescriptorSetDemand demand, for (;;) { - if (batch.Allocation > _remainingSets || !demand.Scale(batch.Allocation).Fits(in _remaining)) + if (allocation > remainingSets || !demand.Scale(allocation).Fits(in remaining)) { - if (batch.Allocation == 1) + if (allocation == 1) { return false; } - batch.Allocation /= 2; + allocation /= 2; continue; } var allocate = new DescriptorSetAllocateInfo { SType = StructureType.DescriptorSetAllocateInfo, - DescriptorPool = _currentPool, - DescriptorSetCount = batch.Allocation, + DescriptorPool = pool, + DescriptorSetCount = allocation, PSetLayouts = layouts, }; Result result; - fixed (DescriptorSet* sets = batch.Sets) + fixed (DescriptorSet* allocated = sets) { - result = _device.Vk.AllocateDescriptorSets(_device.Device, &allocate, sets); + result = device.Vk.AllocateDescriptorSets(device.Device, &allocate, allocated); } if (result == Result.Success) { - batch.Size = batch.Allocation; - _remaining = _remaining.Subtract(demand.Scale(batch.Allocation)); - _remainingSets -= batch.Allocation; + remaining = remaining.Subtract(demand.Scale(allocation)); + remainingSets -= allocation; return true; } @@ -179,16 +190,24 @@ private bool Allocate(DescriptorSetLayout layout, in DescriptorSetDemand demand, throw SubmissionScheduler.Fatal($"vkAllocateDescriptorSets failed: result={result}."); } - if (batch.Allocation == 1) + if (allocation == 1) { return false; } - batch.Allocation /= 2; + allocation /= 2; } } private DescriptorPool CreatePool() + { + var pool = CreatePool(_device); + _remaining = PoolCapacity; + _remainingSets = SetsPerPool; + return pool; + } + + internal static DescriptorPool CreatePool(GpuDeviceInfo device) { fixed (DescriptorPoolSize* poolSizes = PoolSizes) { @@ -199,14 +218,12 @@ private DescriptorPool CreatePool() PoolSizeCount = (uint)PoolSizes.Length, PPoolSizes = poolSizes, }; - var result = _device.Vk.CreateDescriptorPool(_device.Device, &create, null, out var pool); + var result = device.Vk.CreateDescriptorPool(device.Device, &create, null, out var pool); if (result != Result.Success) { throw SubmissionScheduler.Fatal($"vkCreateDescriptorPool failed: result={result}."); } - _remaining = PoolCapacity; - _remainingSets = SetsPerPool; return pool; } } diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs b/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs index 5aab95a4d..52b064eb9 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/IShaderPipelineHost.cs @@ -69,6 +69,10 @@ internal interface IShaderPipelineHost { uint MaxPushDescriptors { get; } + StableImageDescriptorLimits ComputeImageDescriptorLimits => default; + + StableImageDescriptorLimits GraphicsImageDescriptorLimits => default; + bool ComputeWave64Supported { get; } // True when a 64-invocation wave64 compute workgroup runs as one 64-lane host subgroup. @@ -78,6 +82,9 @@ internal interface IShaderPipelineHost bool MipStatisticsSubgroupReduction => false; + // The host subgroup of a pixel shader is one guest wave32 and has arithmetic operations. + bool PixelSubgroupArithmetic => false; + // Whether the host reads a linked program's call records at run time, through descriptor set 1. bool RuntimeCallRecordsSupported => false; @@ -95,10 +102,24 @@ internal interface IShaderPipelineHost // emitted as real 64-bit atomics instead of a non-atomic 32-bit pair. bool SharedInt64AtomicsEnabled { get; } + // The device supports shaderBufferInt64Atomics, so a 64-bit buffer atomic (BUFFER_ATOMIC_*_X2) is + // one 64-bit atomic instead of a pair of 32-bit ones, which is not atomic as a pair. + bool BufferInt64AtomicsEnabled => false; + // The device supports shaderImageInt64Atomics, so an atomic on a 64-bit image texel // (a 32_32 UINT image) can be compiled; without it such a program is rejected. bool ImageInt64AtomicsEnabled => false; + + // The device supports shaderDeviceClock, so a program can read a running clock. + bool ShaderDeviceClockEnabled => false; bool ShaderSignedZeroInfNanPreserveFloat32Supported => false; + + // The device was created with robustBufferAccess2: a storage buffer access past its descriptor's range reads zero and + // writes nothing. + bool RobustBufferAccess2Enabled => false; + + // The device was created with shaderFloat16 and converts f16 exactly under float controls (NativeFloat16Conversions). + bool NativeFloat16Conversions => false; bool ExecGuardElisionEnabled => true; ShaderPrewarmList? ShaderPrewarm => null; bool PerVertexPixelInputsSupported => true; @@ -115,6 +136,11 @@ internal interface IShaderPipelineHost // The device can blend with a second fragment output (dualSrcBlend). bool SupportsDualSourceBlend => false; + // The device has the bindless heap set (descriptor indexing with update-after-bind and partially bound arrays, and + // null descriptors): an image or sampler read from one heap V# at an index the host cannot evaluate becomes a heap + // record instead of rejecting the program. + bool SupportsBindlessHeap => false; + // The sample counts a pipeline without attachments can rasterize at. SampleCountFlags NoAttachmentSampleCounts { get; } @@ -151,6 +177,32 @@ uint[] NormalizeImageDescriptor(IShaderFrontend frontend, ReadOnlySpan wor PipelineHandle CreateGraphicsPipeline(GraphicsPipelineDescription description); + // Creates the graphics pipeline without blocking the command stream on the host shader compiler: false means the + // compile is still running and the caller should ask again with the same description, true hands over the finished + // pipeline. A backend that compiles cheaply keeps the blocking behaviour. + bool TryCreateGraphicsPipeline(GraphicsPipelineDescription description, out PipelineHandle handle) + { + handle = CreateGraphicsPipeline(description); + return true; + } + + // Blocks until the compile TryCreateGraphicsPipeline left running for this description is done. The caller holds no + // pipeline cache lock, so programs of later draws resolve meanwhile. + void WaitForGraphicsPipeline(GraphicsPipelineDescription description) + { + } + + // A pixel program was created; the host can start compiling what depends on the program alone. + void PixelProgramCreated(ShaderProgramInfo program, ulong module) + { + } + + // A vertex or mesh program was recorded for the prewarm under prewarmIdentity (ShaderPrewarmList.Identity); the host + // records the states it compiles the program's pre-rasterization libraries with. + void VertexProgramRecorded(ulong module, ulong prewarmIdentity) + { + } + PipelineHandle CreateComputePipeline(ComputePipelineDescription description); Task? GetComputePipelineCompletion(ShaderProgram program) => null; diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/LinkedShaderPrewarm.cs b/src/SharpEmu.Libs/Gpu/Pipelines/LinkedShaderPrewarm.cs new file mode 100644 index 000000000..dbf820d0e --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/Pipelines/LinkedShaderPrewarm.cs @@ -0,0 +1,148 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.ShaderCompiler; + +namespace SharpEmu.Libs.Gpu.Pipelines; + +// The exact library used by one linked program, independent of live tables and the next session's latest union. +// Code is stored once per target address; sites retain target order, arguments and return registers. +internal sealed record LinkedShaderPrewarm(bool RuntimeRecords, bool CallMarks, bool BindlessHeap, + LinkedPrewarmFunction[] Functions, LinkedPrewarmSite[] Sites) +{ + public static LinkedShaderPrewarm Capture(ShaderCallLibrary library, bool runtimeRecords, bool callMarks, bool bindlessHeap) + { + var functions = library.Calls.SelectMany(site => site.Targets).Select(target => target.Address).Distinct().Order() + .Select(address => new LinkedPrewarmFunction(address, library.CodeRuns[address] + .Select(run => new CodeRange(run.Address, run.Bytes.ToArray())).ToArray())).ToArray(); + var sites = library.Calls.Select(site => new LinkedPrewarmSite( + site.Pc, site.AddressRegister, site.ArgumentRegister, site.ReturnRegister, site.ReturnAddress, + site.Targets.Select(target => new LinkedPrewarmTarget(target.Address, target.Argument)).ToArray())).ToArray(); + return new(runtimeRecords, callMarks, bindlessHeap, functions, sites); + } + + public Gen5ShaderProgram Link(Gen5ShaderProgram caller) + { + var functions = new Dictionary(); + foreach (var function in Functions) + { + var memory = new ReplayCpuMemory(function.Ranges); + var decoded = ShaderFunctionReader.Read(function.Address, (ulong address, out uint word) => + { + Span bytes = stackalloc byte[sizeof(uint)]; + var read = memory.TryRead(address, bytes); + word = read ? BinaryPrimitives.ReadUInt32LittleEndian(bytes) : 0; + return read; + }); + if (!decoded.Complete) + throw new InvalidOperationException($"The prewarm callee cannot be decoded: address=0x{function.Address:X16} {decoded.Error}"); + functions.Add(function.Address, decoded.Program); + } + + var sites = Sites.Select(site => new ShaderCallSite(site.Pc, site.AddressRegister, site.ArgumentRegister, + site.ReturnRegister, site.ReturnAddress, site.Targets.Select(target => new ShaderCallTarget( + target.Address, target.Argument, functions[target.Address])).ToArray())).ToArray(); + // The captured library already excludes any callees runtime linking refused. Replay must not drop more. + return Gen5ShaderCallLinker.Link(caller, sites, RuntimeRecords); + } + + public void Write(BinaryWriter writer) + { + writer.Write(RuntimeRecords); + writer.Write(CallMarks); + writer.Write(BindlessHeap); + writer.Write(Functions.Length); + foreach (var function in Functions) + { + writer.Write(function.Address); + writer.Write(function.Ranges.Length); + foreach (var range in function.Ranges) + { + writer.Write(range.Address); + writer.Write(range.Bytes.Length); + writer.Write(range.Bytes); + } + } + writer.Write(Sites.Length); + foreach (var site in Sites) + { + writer.Write(site.Pc); + writer.Write(site.AddressRegister); + writer.Write(site.ArgumentRegister); + writer.Write(site.ReturnRegister); + writer.Write(site.ReturnAddress); + writer.Write(site.Targets.Length); + foreach (var target in site.Targets) + { + writer.Write(target.Address); + writer.Write(target.Argument); + } + } + } + + public static LinkedShaderPrewarm Read(BinaryReader reader) + { + var runtimeRecords = reader.ReadBoolean(); + var callMarks = reader.ReadBoolean(); + var bindlessHeap = reader.ReadBoolean(); + if (callMarks && !runtimeRecords) throw new ArgumentException("Prewarm call marks require runtime records."); + var functions = new LinkedPrewarmFunction[Count(reader, 12)]; + var addresses = new HashSet(); + for (var index = 0; index < functions.Length; index++) + { + var address = reader.ReadUInt64(); + if (!addresses.Add(address)) throw new ArgumentException("Duplicate prewarm callee address."); + var ranges = new CodeRange[Count(reader, 16)]; + if (ranges.Length == 0) throw new ArgumentException("The prewarm callee has no code."); + ulong end = 0; + for (var run = 0; run < ranges.Length; run++) + { + var start = reader.ReadUInt64(); + var length = Count(reader, 1); + if (length == 0 || (length & 3) != 0 || (start & 3) != 0 || + start < address || (run != 0 && start < end) || start > ulong.MaxValue - (ulong)length) + throw new ArgumentException("Invalid prewarm callee code range."); + var bytes = reader.ReadBytes(length); + if (bytes.Length != length) throw new EndOfStreamException(); + ranges[run] = new CodeRange(start, bytes); + end = start + (ulong)length; + } + functions[index] = new LinkedPrewarmFunction(address, ranges); + } + var sites = new LinkedPrewarmSite[Count(reader, 28)]; + var pcs = new HashSet(); + for (var index = 0; index < sites.Length; index++) + { + var pc = reader.ReadUInt32(); + if (!pcs.Add(pc)) throw new ArgumentException("Duplicate prewarm call site."); + var addressRegister = reader.ReadUInt32(); + var argumentRegister = reader.ReadUInt32(); + var returnRegister = reader.ReadUInt32(); + var returnAddress = reader.ReadUInt64(); + var targets = new LinkedPrewarmTarget[Count(reader, 16)]; + for (var target = 0; target < targets.Length; target++) + { + var address = reader.ReadUInt64(); + var argument = reader.ReadUInt64(); + if (!addresses.Contains(address)) throw new ArgumentException("The prewarm call target has no code."); + targets[target] = new LinkedPrewarmTarget(address, argument); + } + sites[index] = new LinkedPrewarmSite(pc, addressRegister, argumentRegister, returnRegister, returnAddress, targets); + } + return new(runtimeRecords, callMarks, bindlessHeap, functions, sites); + } + + private static int Count(BinaryReader reader, int minimumBytes) + { + var count = reader.ReadInt32(); + if (count < 0 || count > (reader.BaseStream.Length - reader.BaseStream.Position) / minimumBytes) + throw new ArgumentException("The prewarm linked record count is out of range."); + return count; + } +} + +internal sealed record LinkedPrewarmFunction(ulong Address, CodeRange[] Ranges); +internal sealed record LinkedPrewarmTarget(ulong Address, ulong Argument); +internal sealed record LinkedPrewarmSite(uint Pc, uint AddressRegister, uint ArgumentRegister, uint ReturnRegister, + ulong ReturnAddress, LinkedPrewarmTarget[] Targets); diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/MeshDrawPlanner.cs b/src/SharpEmu.Libs/Gpu/Pipelines/MeshDrawPlanner.cs index 4147e16f8..155cd69b5 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/MeshDrawPlanner.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/MeshDrawPlanner.cs @@ -14,6 +14,9 @@ internal readonly record struct MeshDrawPlan internal static class MeshDrawPlanner { + // A primitive shader subgroup exports at most 256 primitives. + private const uint MaximumSubgroupPrimitives = 256; + internal static MeshDrawPlan? Create(VertexStageRegisters vertex, ShaderInterfaceRegisters shaderInterface, ContextRegisters context, UserConfigRegisters userConfig, MeshShaderLimits limits, uint subgroupSize) @@ -47,8 +50,25 @@ internal static class MeshDrawPlanner var outputPrimitiveCapacity = fusedGeometry ? checked((uint)group.PrimitiveGroupSize * (verticesPerPrimitive - 2)) : (uint)group.PrimitiveGroupSize; - var threadsPerGroup = checked(((outputVertexCapacity + waveSize - 1) / waveSize) * waveSize); - var deviceInvocationCount = waveSize == 64 && subgroupSize == 32 ? threadsPerGroup / 2 : threadsPerGroup; + var threadsPerGroup = WholeWaves(outputVertexCapacity, waveSize); + // GE_NGG_SUBGRP_CNTL.PRIM_AMP_FACTOR bounds the primitives one input primitive produces. A mesh-style primitive + // shader (one input point per subgroup) exports its own triangles, more than a strip of VGT_GS_MAX_VERT_OUT + // vertices holds, and each lane exports one of them, so the subgroup needs a lane per primitive too. The plan + // only grows, and only while the device can run it. + var amplification = shaderInterface.PrimitiveShaderSubgroupControl & 0x1FFu; + if (fusedGeometry && amplification != 0) + { + var amplified = Math.Min(MaximumSubgroupPrimitives, checked((uint)group.PrimitiveGroupSize * amplification)); + var amplifiedThreads = WholeWaves(Math.Max(outputVertexCapacity, amplified), waveSize); + var amplifiedInvocations = DeviceInvocations(amplifiedThreads, waveSize, subgroupSize); + if (amplified > outputPrimitiveCapacity && amplified <= limits.OutputPrimitiveCapacity && + amplifiedInvocations <= limits.MaxInvocations && amplifiedInvocations <= limits.MaxWorkGroupSizeX) + { + outputPrimitiveCapacity = amplified; + threadsPerGroup = amplifiedThreads; + } + } + var deviceInvocationCount = DeviceInvocations(threadsPerGroup, waveSize, subgroupSize); var localDataShareDwords = (uint)vertex.GeometryResource2.LocalDataShareSize * 128; var sharedBytes = checked((localDataShareDwords + outputVertexCapacity + 5) * sizeof(uint)); if (inputPrimitiveCountPerWorkgroup == 0 || deviceInvocationCount > limits.MaxInvocations || deviceInvocationCount > limits.MaxWorkGroupSizeX || @@ -87,4 +107,10 @@ subgroupSize is not (32 or 64) || subgroupSize > waveSize || }, }; } + + private static uint WholeWaves(uint threads, uint waveSize) => checked((threads + waveSize - 1) / waveSize * waveSize); + + // A wave64 subgroup runs as two 32-lane halves on a 32-lane device. + private static uint DeviceInvocations(uint threads, uint waveSize, uint subgroupSize) => + waveSize == 64 && subgroupSize == 32 ? threads / 2 : threads; } diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibrary.TableScan.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibrary.TableScan.cs new file mode 100644 index 000000000..553fe63f2 --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibrary.TableScan.cs @@ -0,0 +1,310 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.Libs.Gpu.Pipelines; + +// The read of a run-time-record caller's tables in one pass per table. A ray tracer's hit table reserves far more +// records than a frame fills (megabytes of records, a few thousand of them live), and every pass reads it. The +// per-record read keeps a set of records per site and a ShaderCallTarget per record, then derives the library's records +// and each site's distinct callees from those (WithRuntimeArguments). This read skips zero targets four records at a +// time and keeps only what the library holds: each site's distinct callees by address in first occurrence, and the +// distinct records of all sites in first occurrence, site by site. The library it returns equals the per-record read's +// (records, sites, code hashes and runs, current code hashes in the same order, current sites); each function is read +// and validated once per address and read, as the per-record read does, and every failure throws the same exception. +// On by default; SHARPEMU_CALL_TABLE_SCAN=0, or any value but 1, turns it off. +internal sealed partial record ShaderCallLibrary +{ + internal enum TableScanMode { Off, On } + + internal static readonly TableScanMode ConfiguredTableScan = + Environment.GetEnvironmentVariable("SHARPEMU_CALL_TABLE_SCAN") switch + { + null or "" or "1" => TableScanMode.On, + _ => TableScanMode.Off, + }; + + // Tests: this thread's mode, whatever the configuration. + [ThreadStatic] internal static TableScanMode? TableScanOverride; + + internal static TableScanMode TableScan => TableScanOverride ?? ConfiguredTableScan; + + // The host reads the tables and the functions they name as it reads any shader code and resource table, so bytes + // the GPU wrote are brought back and an image the GPU wrote over memory the game has since reused does not refuse + // the game's own bytes. + // With memo (call-library reuse), a run-time-record library whose topology a previous read derived reuses it + // (ShaderCallLibraryMemo.Runtime); the tables and functions are read as without it. + // With runtimeArguments and the table scan on, the tables are read in one pass each (see above). + public static ShaderCallLibrary Read(Gen5ShaderProgram caller, MemoryAccessTable memory, + ResourceSnapshot snapshot, GuestWordReader read, ShaderFunctionCache? functionCache = null, bool runtimeArguments = false, + uint userDataBase = 0, ResidentGuestBytesReader? readBytes = null, ShaderCallLibraryMemo? memo = null) + { + var mode = runtimeArguments && BitConverter.IsLittleEndian ? TableScan : TableScanMode.Off; + if (mode == TableScanMode.Off) + return ReadOriginal(caller, memory, snapshot, read, functionCache, runtimeArguments, userDataBase, readBytes, memo); + return ReadScanned(caller, memory, snapshot, read, functionCache, userDataBase, readBytes, memo); + } + + // ReadOriginal with runtimeArguments, in one pass per table. The checks, their order and their exceptions are the + // original's; the records, sites, code hashes and runs and current sites it derives are the ones the original's + // collections yield. + private static ShaderCallLibrary ReadScanned(Gen5ShaderProgram caller, MemoryAccessTable memory, ResourceSnapshot snapshot, + GuestWordReader read, ShaderFunctionCache? functionCache, uint userDataBase, ResidentGuestBytesReader? readBytes, + ShaderCallLibraryMemo? memo) + { + var scan = _tableScan ??= new TableScanState(); + scan.Begin(caller.Address, functionCache, read); + try + { + var calls = new List(); + foreach (var callSite in CallSites(caller, userDataBase, (uint)snapshot.UserData.Length)) + { + if (callSite.Refusal is { } refusal) throw new InvalidOperationException(refusal); + var call = caller.Instructions[callSite.Index]; + if (callSite.UserData is { } userData) + { + // A function pointer the dispatch passes in user data: one target, read as the original's Target reads it. + var userTarget = UserDataPair(snapshot, userDataBase, userData.Target); + var userArgument = UserDataPair(snapshot, userDataBase, userData.Argument); + var userArgumentRegister = call.Sources[0].Value + 2; + var userReturn = unchecked(caller.Address + call.ProgramOffset + (ulong)call.Words.Count * sizeof(uint)); + var userTargets = new List(1); + if (userTarget != 0) + { + scan.BeginSite(call.Pc, userTargets, 0); + scan.VisitUserTarget(userTarget, userArgument); + } + + calls.Add(new(call.Pc, call.Sources[0].Value, userArgumentRegister, call.Destinations[0].Value, userReturn, userTargets)); + continue; + } + + var load = callSite.Load!; + var loadControl = (Gen5ScalarMemoryControl)load.Control!; + var argumentRegister = callSite.ArgumentRegister; + var access = memory.Find(load.Pc); + if (access is null || access.Resource >= snapshot.Buffers.Length) + throw new InvalidOperationException("The shader call table has no materialized buffer."); + var descriptor = snapshot.Buffers[access.Resource]; + var address = descriptor[0] | ((ulong)(descriptor[1] & 0xFFFF) << 32); + var stride = (descriptor[1] >> 16) & 0x3FFF; + var size = (ulong)descriptor[2] * Math.Max(stride, 1u); + var returnAddress = unchecked(caller.Address + call.ProgramOffset + (ulong)call.Words.Count * sizeof(uint)); + if (size == 0) + { + calls.Add(new(call.Pc, call.Sources[0].Value, argumentRegister, call.Destinations[0].Value, returnAddress, [])); + continue; + } + + if (size > MaxRuntimeTableBytes || (size & 15) != 0 || (descriptor[1] & 0x80000000) != 0) + throw new InvalidOperationException( + $"The shader call table extent or layout is not supported: address=0x{address:X} stride={stride} records={descriptor[2]} " + + $"swizzle={descriptor[1] >> 31} dynamic={loadControl.DynamicOffsetRegister.HasValue} offset={loadControl.ImmediateOffsetBytes}."); + ReadOnlySpan table = ReadTable(address, (int)size, read, readBytes); + if ((ulong)table.Length != size) + throw new InvalidOperationException( + $"The shader call table is not CPU-readable at this submission: address=0x{address:X} bytes={size} readable={table.Length}."); + var targets = new List(); + var firstRecord = checked((int)loadControl.ImmediateOffsetBytes); + if (firstRecord < 0 || (firstRecord & 15) != 0 || firstRecord > table.Length - 16) + throw new InvalidOperationException("The shader call record is outside the table or is not aligned."); + var recordEnd = loadControl.DynamicOffsetRegister.HasValue ? table.Length : firstRecord + 16; + scan.BeginSite(call.Pc, targets, address); + ScanRecords(scan, MemoryMarshal.Cast(table[firstRecord..recordEnd]), firstRecord / 16); + calls.Add(new(call.Pc, call.Sources[0].Value, argumentRegister, call.Destinations[0].Value, returnAddress, targets)); + } + + var records = scan.TakeRecords(); + return (memo?.Runtime(caller, calls, scan.CodeHashes, scan.CodeRuns, records) ?? + WithRuntimeArguments(caller, calls, scan.CodeHashes, scan.CodeRuns, records)) with + { + CurrentSites = scan.CurrentSites, + }; + } + finally + { + scan.End(); + } + } + + // Each record of a table whose target is nonzero, in order (words: the records' target and argument words, little + // endian; first: the first record's index in the table). A zero target names no call; four records whose targets are + // all zero are skipped together. + private static void ScanRecords(TableScanState scan, ReadOnlySpan words, int first) + { + var index = 0; + if (Vector256.IsHardwareAccelerated && words.Length >= 8) + { + ref var start = ref MemoryMarshal.GetReference(words); + var targets = Vector256.Create(ulong.MaxValue, 0UL, ulong.MaxValue, 0UL); + for (; index <= words.Length - 8; index += 8) + { + var low = Vector256.LoadUnsafe(ref start, (nuint)index); + var high = Vector256.LoadUnsafe(ref start, (nuint)(index + 4)); + if (((low | high) & targets) == Vector256.Zero) continue; + for (var word = index; word < index + 8; word += 2) + { + if (words[word] != 0) scan.Visit(words[word], words[word + 1], first + (word >> 1)); + } + } + } + + for (; index < words.Length; index += 2) + { + if (words[index] != 0) scan.Visit(words[index], words[index + 1], first + (index >> 1)); + } + } + + [ThreadStatic] private static TableScanState? _tableScan; + + // One thread's state of a scanned read. The collections a library holds are made for each read; the rest is kept. + private sealed class TableScanState + { + // A callee the tables named in this read: its target as a library's site holds it (argument 0), null until its + // function is read; whether a table record could not read it (the original's unreadable set: its later table + // records are left out, also when a user-data site reads it after all); and the last site that named it. + private sealed class Callee + { + public ShaderCallTarget? Target; + public bool Unreadable; + public int Site; + } + + private readonly Dictionary _callees = new(); + private readonly HashSet<(ulong Target, ulong Argument)> _seen = new(); + private (ulong Target, ulong Argument)[] _records = new (ulong, ulong)[256]; + private int _recordCount; + private int _site; + private uint _sitePc; + private ulong _table; + private ulong _caller; + private List? _siteTargets; + private ShaderFunctionCache? _functionCache; + private GuestWordReader? _read; + + public Dictionary CodeHashes = []; + public Dictionary CodeRuns = []; + public Dictionary> CurrentSites = []; + + public void Begin(ulong caller, ShaderFunctionCache? functionCache, GuestWordReader read) + { + _caller = caller; + _functionCache = functionCache; + _read = read; + CodeHashes = []; + CodeRuns = []; + CurrentSites = []; + _site = 0; + _recordCount = 0; + } + + public void End() + { + _callees.Clear(); + _seen.Clear(); + _recordCount = 0; + _siteTargets = null; + _functionCache = null; + _read = null; + } + + public void BeginSite(uint pc, List targets, ulong table) + { + _site++; + _sitePc = pc; + _siteTargets = targets; + _table = table; + } + + // A table record with a nonzero target, as the original's loop takes it: a target whose function cannot be read + // leaves the record out, and every later table record naming it in this read. + public void Visit(ulong target, ulong argument, int record) + { + if (!_callees.TryGetValue(target, out var callee)) + { + callee = new Callee(); + _callees.Add(target, callee); + var result = ReadFunction(target); + if (!result.Complete) + { + callee.Unreadable = true; + if (Interlocked.Increment(ref _unreadableTargetReports) <= 8) + { + Console.Error.WriteLine( + $"[GPU][WARN][LINKED_PROGRAM] A call table record names a function that cannot be read; its calls return at once: " + + $"caller=0x{_caller:X} table=0x{_table:X} record={record} target=0x{target:X} error={result.Error}."); + } + + return; + } + + Resolve(callee, target, result); + } + else if (callee.Unreadable) + { + return; + } + + Name(callee, target); + AddRecord(target, argument); + } + + // A user-data site's target, as the original's Target reads it: a function a table record could not read is read + // again, and a failure throws. + public void VisitUserTarget(ulong target, ulong argument) + { + if (!_callees.TryGetValue(target, out var callee) || callee.Target is null) + { + var result = ReadFunction(target); + if (!result.Complete) throw new ShaderFunctionReadException(target, result); + if (callee is null) + { + callee = new Callee(); + _callees.Add(target, callee); + } + + Resolve(callee, target, result); + } + + Name(callee, target); + AddRecord(target, argument); + } + + public (ulong Target, ulong Argument)[] TakeRecords() => _records.AsSpan(0, _recordCount).ToArray(); + + private ShaderFunctionReadResult ReadFunction(ulong address) => + _functionCache?.Read(address, _read!) ?? ShaderFunctionReader.Read(address, _read!); + + private void Resolve(Callee callee, ulong address, ShaderFunctionReadResult result) + { + callee.Target = new ShaderCallTarget(address, 0, result.Program); + CodeHashes.Add(address, CodeDigest(result)); + CodeRuns.Add(address, result.Runs); + } + + // The site holds each callee once, in first occurrence, and the callee's current sites name the site. + private void Name(Callee callee, ulong address) + { + if (callee.Site == _site) return; + callee.Site = _site; + _siteTargets!.Add(callee.Target!); + if (!CurrentSites.TryGetValue(address, out var namedAt)) + { + CurrentSites.Add(address, namedAt = []); + } + + namedAt.Add(_sitePc); + } + + private void AddRecord(ulong target, ulong argument) + { + if (!_seen.Add((target, argument))) return; + if (_recordCount == _records.Length) Array.Resize(ref _records, _records.Length * 2); + _records[_recordCount++] = (target, argument); + } + } +} diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibrary.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibrary.cs index 9770d7ba9..86dea22d3 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibrary.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibrary.cs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: GPL-2.0-or-later using System.Buffers.Binary; +using System.Runtime.CompilerServices; using System.Security.Cryptography; using SharpEmu.ShaderCompiler; using SharpEmu.ShaderCompiler.Ir; @@ -16,15 +17,24 @@ internal sealed record UnitedCallee(ShaderCallTarget Target, byte[] Code, (ulong // Identity names the tables and code exactly. LayoutIdentity names them up to the values of the records' arguments: it // keeps which records share an argument and which have none. A game rebuilds its tables with the argument data // elsewhere as often as every frame; such a table links to the same program, whose plan and module read Arguments (the -// distinct nonzero record arguments, Gen5ShaderCallLinker.CallEntryArguments) from each dispatch. -internal sealed record ShaderCallLibrary(string Identity, IReadOnlyList Calls, string LayoutIdentity, +// distinct nonzero record arguments, Gen5ShaderCallLinker.CallEntryArguments) from each dispatch. A library read with +// runtimeArguments holds its records as dispatch data (Records): its Identity is its LayoutIdentity. +internal sealed partial record ShaderCallLibrary(string Identity, IReadOnlyList Calls, string LayoutIdentity, ulong[] Arguments) { private const ulong MaxTableBytes = 65536; // With runtimeArguments a site links each callee once, so a table's size sets only how many records the host reads and - // resolves at each dispatch. - private const ulong MaxRuntimeTableBytes = 1 << 20; + // resolves at each dispatch. A ray tracer's hit table can reserve hundreds of thousands of records: up to 16 MiB. + private const ulong MaxRuntimeTableBytes = 16 << 20; + + private static int _unreadableTargetReports; + + // Each callee's code hash, computed once for the decoded function the function cache returns while its code is unchanged. + private static readonly ConditionalWeakTable CodeDigests = new(); + + private static byte[] CodeDigest(ShaderFunctionReadResult function) => + CodeDigests.GetValue(function, static result => SHA256.HashData(result.Bytes)); // Read with runtimeArguments, a site's Calls hold each callee once (in the order of their code, so the program does not // depend on the tables' order), LayoutIdentity names only the sites and the callees' code, and Records holds every @@ -37,7 +47,7 @@ internal sealed record ShaderCallLibrary(string Identity, IReadOnlyList CodeHashes { get; init; } = []; - // The words each callee's decode read, by address, when read with runtimeArguments. + // The words each callee's decode read, by address; also retained for exact prewarm replay of static links. public Dictionary CodeRuns { get; init; } = []; // The hash of the code at each address the tables name, as this dispatch read it; CodeHashes holds the code the library @@ -47,68 +57,96 @@ internal sealed record ShaderCallLibrary(string Identity, IReadOnlyList> CurrentSites { get; init; } = []; - // The host reads the tables and the functions they name as it reads any shader code and resource table, so bytes - // the GPU wrote are brought back and an image the GPU wrote over memory the game has since reused does not refuse - // the game's own bytes. - public static ShaderCallLibrary Read(Gen5ShaderProgram caller, MemoryAccessTable memory, - ResourceSnapshot snapshot, GuestWordReader read, ShaderFunctionCache? functionCache = null, bool runtimeArguments = false) + // With call-library reuse on, the token of this library's topology: every field but Records, CurrentCodeHashes and + // CurrentSites, which are this dispatch's own (ShaderCallLibraryMemo). Null otherwise. + internal object? Topology { get; init; } + + // Read without the one-pass table scan (ShaderCallLibrary.TableScan.cs), which is also the scan's reference. + private static ShaderCallLibrary ReadOriginal(Gen5ShaderProgram caller, MemoryAccessTable memory, + ResourceSnapshot snapshot, GuestWordReader read, ShaderFunctionCache? functionCache, bool runtimeArguments, + uint userDataBase, ResidentGuestBytesReader? readBytes, ShaderCallLibraryMemo? memo) { - using var identity = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); - using var layout = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + // A runtime-argument library names its sites from the callees' code hashes (WithRuntimeSites), so its read hashes + // neither the tables nor the code. + using var identity = runtimeArguments ? null : IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using var layout = runtimeArguments ? null : IncrementalHash.CreateHash(HashAlgorithmName.SHA256); var calls = new List(); var functions = new Dictionary(); var codeHashes = new Dictionary(); var codeRuns = new Dictionary(); var currentSites = new Dictionary>(); - foreach (var (call, index) in caller.Instructions.Select((instruction, index) => (instruction, index))) + + var unreadable = new HashSet(); + + // A target a site names: its function, read once per library, joins both identities. + ShaderCallTarget Target(uint site, ulong address, ulong argument) => + TryTarget(site, address, argument, out var target, out var failure) + ? target + : throw new ShaderFunctionReadException(address, failure!); + + bool TryTarget(uint site, ulong address, ulong argument, out ShaderCallTarget target, out ShaderFunctionReadResult? failure) { - if (call.Opcode != "SSwappcB64") continue; - if (call.Sources.Count != 1 || call.Destinations.Count != 1 || - call.Sources[0].Kind != Gen5OperandKind.ScalarRegister || call.Destinations[0].Kind != Gen5OperandKind.ScalarRegister) - throw new InvalidOperationException("The shader call does not use a supported table record."); - Gen5ShaderInstruction load; - Gen5ScalarMemoryControl loadControl; - uint argumentRegister = 0; - if (TryFindDirectRecordLoads(caller, index, out var targetLoad, out var directArgumentRegister)) + target = null!; + failure = null; + if (!functions.TryGetValue(address, out var function)) { - load = targetLoad; - loadControl = (Gen5ScalarMemoryControl)targetLoad.Control!; - argumentRegister = directArgumentRegister; - } - else - { - if (index < 6) throw new InvalidOperationException("The shader call does not use a supported table record."); - var loadIndex = index - 6; - while (loadIndex >= 0 && caller.Instructions[loadIndex] is { Opcode: "VMovB32", Destinations.Count: 1 } vectorMove && - vectorMove.Destinations[0].Kind == Gen5OperandKind.VectorRegister) loadIndex--; - if (loadIndex < 0) throw new InvalidOperationException("The shader call table load is missing."); - load = caller.Instructions[loadIndex]; - if (load.Opcode != "SBufferLoadDwordx4" || load.Control is not Gen5ScalarMemoryControl recordControl || - load.Destinations.Count != 4 || caller.Instructions[index - 5].Opcode != "SWaitcnt") - throw new InvalidOperationException("The shader call table load is not supported."); - loadControl = recordControl; - if (loadControl.DynamicOffsetRegister is { } selector) + var result = functionCache?.Read(address, read) ?? ShaderFunctionReader.Read(address, read); + if (!result.Complete) + { + failure = result; + return false; + } + + function = result.Program; + identity?.AppendData(result.Bytes); + layout?.AppendData(result.Bytes); + functions.Add(address, function); + if (runtimeArguments) { - var scale = caller.Instructions.Take(loadIndex).Reverse().FirstOrDefault(instruction => - instruction.Opcode.StartsWith("SCbranch", StringComparison.Ordinal) || instruction.Opcode is "SBranch" or "SSwappcB64" || - instruction.Destinations.Any(destination => destination.Kind == Gen5OperandKind.ScalarRegister && - selector >= destination.Value && selector - destination.Value < instruction.DestinationWidth)); - if (scale is null || scale.Opcode != "SLshlB32" || scale.Destinations.Count != 1 || scale.Destinations[0] != Gen5Operand.Scalar(selector) || - scale.Sources.Count != 2 || scale.Sources[1] != new Gen5Operand(Gen5OperandKind.EncodedConstant, 132)) - throw new InvalidOperationException("The shader call table does not use 16-byte records."); + codeHashes.Add(address, CodeDigest(result)); } - for (var component = 0; component < 4; component++) + codeRuns.Add(address, result.Runs); + } + + if (runtimeArguments) + { + if (!currentSites.TryGetValue(address, out var namedAt)) { - var move = caller.Instructions[index - 4 + component]; - if (move.Opcode != "SMovB32" || move.Sources.Count != 1 || move.Destinations.Count != 1 || - move.Sources[0] != load.Destinations[component] || move.Destinations[0].Kind != Gen5OperandKind.ScalarRegister) - throw new InvalidOperationException("The shader call record has an unsupported register transfer."); - if (component == 2) argumentRegister = move.Destinations[0].Value; - var expected = component < 2 ? call.Sources[0].Value + (uint)component : argumentRegister + (uint)component - 2; - if (move.Destinations[0].Value != expected) - throw new InvalidOperationException("The shader call record does not use register pairs."); + currentSites.Add(address, namedAt = []); } + + namedAt.Add(site); + } + + layout?.AppendData(BitConverter.GetBytes(address)); + target = new(address, argument, function); + return true; + } + + foreach (var callSite in CallSites(caller, userDataBase, (uint)snapshot.UserData.Length)) + { + if (callSite.Refusal is { } refusal) throw new InvalidOperationException(refusal); + var call = caller.Instructions[callSite.Index]; + if (callSite.UserData is { } userData) + { + // A function pointer the dispatch passes in user data: one target, which the linked program still checks + // against the call registers when the call runs. Its argument is a record argument like a table's. + var userTarget = UserDataPair(snapshot, userDataBase, userData.Target); + var userArgument = UserDataPair(snapshot, userDataBase, userData.Argument); + var userArgumentRegister = call.Sources[0].Value + 2; + var userReturn = unchecked(caller.Address + call.ProgramOffset + (ulong)call.Words.Count * sizeof(uint)); + identity?.AppendData(BitConverter.GetBytes(userTarget)); + identity?.AppendData(BitConverter.GetBytes(userArgument)); + layout?.AppendData(BitConverter.GetBytes(call.Pc)); + layout?.AppendData(BitConverter.GetBytes(userArgumentRegister)); + List userTargets = userTarget == 0 ? [] : [Target(call.Pc, userTarget, userArgument)]; + layout?.AppendData(BitConverter.GetBytes(userTargets.Count)); + calls.Add(new(call.Pc, call.Sources[0].Value, userArgumentRegister, call.Destinations[0].Value, userReturn, userTargets)); + continue; } + var load = callSite.Load!; + var loadControl = (Gen5ScalarMemoryControl)load.Control!; + var argumentRegister = callSite.ArgumentRegister; var access = memory.Find(load.Pc); if (access is null || access.Resource >= snapshot.Buffers.Length) throw new InvalidOperationException("The shader call table has no materialized buffer."); @@ -117,8 +155,8 @@ public static ShaderCallLibrary Read(Gen5ShaderProgram caller, MemoryAccessTable var stride = (descriptor[1] >> 16) & 0x3FFF; var size = (ulong)descriptor[2] * Math.Max(stride, 1u); var returnAddress = unchecked(caller.Address + call.ProgramOffset + (ulong)call.Words.Count * sizeof(uint)); - layout.AppendData(BitConverter.GetBytes(call.Pc)); - layout.AppendData(BitConverter.GetBytes(argumentRegister)); + layout?.AppendData(BitConverter.GetBytes(call.Pc)); + layout?.AppendData(BitConverter.GetBytes(argumentRegister)); if (size == 0) { // A buffer without records reads zero for every load: a null target, so the call has no target. @@ -129,11 +167,11 @@ public static ShaderCallLibrary Read(Gen5ShaderProgram caller, MemoryAccessTable throw new InvalidOperationException( $"The shader call table extent or layout is not supported: address=0x{address:X} stride={stride} records={descriptor[2]} " + $"swizzle={descriptor[1] >> 31} dynamic={loadControl.DynamicOffsetRegister.HasValue} offset={loadControl.ImmediateOffsetBytes}."); - var table = ShaderCallDump.ReadPrefix(address, (int)size, read); + ReadOnlySpan table = ReadTable(address, (int)size, read, readBytes); if ((ulong)table.Length != size) throw new InvalidOperationException( $"The shader call table is not CPU-readable at this submission: address=0x{address:X} bytes={size} readable={table.Length}."); - identity.AppendData(table); + identity?.AppendData(table); var targets = new List(); var records = new HashSet<(ulong, ulong)>(); var firstRecord = checked((int)loadControl.ImmediateOffsetBytes); @@ -142,68 +180,127 @@ public static ShaderCallLibrary Read(Gen5ShaderProgram caller, MemoryAccessTable var recordEnd = loadControl.DynamicOffsetRegister.HasValue ? table.Length : firstRecord + 16; for (var offset = firstRecord; offset < recordEnd; offset += 16) { - var target = BinaryPrimitives.ReadUInt64LittleEndian(table.AsSpan(offset)); - var argument = BinaryPrimitives.ReadUInt64LittleEndian(table.AsSpan(offset + 8)); - if (target == 0 || !records.Add((target, argument))) continue; - if (!functions.TryGetValue(target, out var function)) + var target = BinaryPrimitives.ReadUInt64LittleEndian(table[offset..]); + var argument = BinaryPrimitives.ReadUInt64LittleEndian(table[(offset + 8)..]); + if (target == 0 || !records.Add((target, argument)) || unreadable.Contains(target)) continue; + if (!runtimeArguments) { - var result = functionCache?.Read(target, read) ?? ShaderFunctionReader.Read(target, read); - if (!result.Complete) throw new ShaderFunctionReadException(target, result); - function = result.Program; - identity.AppendData(result.Bytes); - layout.AppendData(result.Bytes); - functions.Add(target, function); - if (runtimeArguments) - { - codeHashes.Add(target, SHA256.HashData(result.Bytes)); - codeRuns.Add(target, result.Runs); - } + targets.Add(Target(call.Pc, target, argument)); + continue; } - targets.Add(new(target, argument, function)); - if (runtimeArguments) + + // A table can hold records past the ones the game wrote for this dispatch, naming functions it has since + // unloaded, and the GPU never calls those. A record whose function cannot be read is left out: its call + // returns at once, as one to a callee the program does not hold does. + if (TryTarget(call.Pc, target, argument, out var linked, out var failure)) { - if (!currentSites.TryGetValue(target, out var namedAt)) - { - currentSites.Add(target, namedAt = []); - } + targets.Add(linked); + continue; + } - namedAt.Add(call.Pc); + unreadable.Add(target); + if (Interlocked.Increment(ref _unreadableTargetReports) <= 8) + { + Console.Error.WriteLine( + $"[GPU][WARN][LINKED_PROGRAM] A call table record names a function that cannot be read; its calls return at once: " + + $"caller=0x{caller.Address:X} table=0x{address:X} record={offset / 16} target=0x{target:X} error={failure!.Error}."); } - layout.AppendData(BitConverter.GetBytes(target)); } - layout.AppendData(BitConverter.GetBytes(targets.Count)); + layout?.AppendData(BitConverter.GetBytes(targets.Count)); calls.Add(new(call.Pc, call.Sources[0].Value, argumentRegister, call.Destinations[0].Value, returnAddress, targets)); } - identity.AppendData(BitConverter.GetBytes(caller.Address)); + identity?.AppendData(BitConverter.GetBytes(caller.Address)); if (runtimeArguments) - return WithRuntimeArguments(caller, Convert.ToHexString(identity.GetHashAndReset()), calls, codeHashes, codeRuns) with + return (memo?.Runtime(caller, calls, codeHashes, codeRuns) ?? WithRuntimeArguments(caller, calls, codeHashes, codeRuns)) with { CurrentSites = currentSites, }; - layout.AppendData(BitConverter.GetBytes(caller.Address)); + var identityHash = identity!; + var layoutHash = layout!; + layoutHash.AppendData(BitConverter.GetBytes(caller.Address)); ulong[] recordArguments = [.. calls.SelectMany(site => site.Targets).Select(target => target.Argument)]; ulong[] arguments = [.. recordArguments.Where(argument => argument != 0).Distinct()]; var slotOf = arguments.Select((argument, slot) => (argument, slot)).ToDictionary(entry => entry.argument, entry => entry.slot); foreach (var argument in recordArguments) - layout.AppendData(BitConverter.GetBytes(argument == 0 ? -1 : slotOf[argument])); - return new(Convert.ToHexString(identity.GetHashAndReset()), calls, Convert.ToHexString(layout.GetHashAndReset()), arguments); + layoutHash.AppendData(BitConverter.GetBytes(argument == 0 ? -1 : slotOf[argument])); + return new(Convert.ToHexString(identityHash.GetHashAndReset()), calls, Convert.ToHexString(layoutHash.GetHashAndReset()), arguments) + { CodeRuns = codeRuns }; } - private static ShaderCallLibrary WithRuntimeArguments(Gen5ShaderProgram caller, string identity, List calls, - Dictionary codeHashes, Dictionary codeRuns) + // A code hash as text. With call-library reuse on, one string per code array: the arrays are never written. + internal static string CodeKey(byte[] code) => ShaderCallLibraryMemo.Enabled + ? CodeKeys.GetValue(code, static bytes => Convert.ToHexString(bytes)) + : Convert.ToHexString(code); + + private static readonly ConditionalWeakTable CodeKeys = new(); + + // The table bytes of the call site being read; valid until the next table read on this thread. + [ThreadStatic] + private static byte[]? _tableScratch; + + // A table is copied at once when the host can read it without first bringing back bytes the GPU wrote; otherwise it is + // read a word at a time, as the host reads any shader resource. Either way into one buffer per thread: a ray tracer's + // table is megabytes, read at each of its dispatches, and a new array each time is a large-object allocation. + private static ReadOnlySpan ReadTable(ulong address, int size, GuestWordReader read, ResidentGuestBytesReader? readBytes) + { + var scratch = _tableScratch; + if (scratch is null || scratch.Length < size) + { + _tableScratch = scratch = new byte[(size + 0xFFFF) & ~0xFFFF]; + } + + var bytes = scratch.AsSpan(0, size); + if (readBytes is not null && readBytes(address, bytes, false)) + { + return bytes; + } + + // As ShaderCallDump.ReadPrefix: whole words up to the first unreadable one. + var offset = 0; + while (offset + sizeof(uint) <= (size & ~3) && address <= ulong.MaxValue - (ulong)offset - 3 && + read(address + (ulong)offset, out var word)) + { + BinaryPrimitives.WriteUInt32LittleEndian(bytes[offset..], word); + offset += sizeof(uint); + } + + return bytes[..offset]; + } + + internal static ShaderCallLibrary WithRuntimeArguments(Gen5ShaderProgram caller, List calls, + Dictionary codeHashes, Dictionary codeRuns) => + WithRuntimeArguments(caller, calls, codeHashes, codeRuns, RuntimeRecords(calls)); + + // The records of a read's sites as a run-time library holds them: every site's distinct target and argument pairs, in + // first occurrence, site by site. + internal static (ulong Target, ulong Argument)[] RuntimeRecords(List calls) { - var sites = new List(calls.Count); var records = new HashSet<(ulong Target, ulong Argument)>(); foreach (var site in calls) { foreach (var target in site.Targets) records.Add((target.Address, target.Argument)); + } + + return [.. records]; + } + + // records: RuntimeRecords of the read's sites. A one-pass read (ReadScanned) collects them itself, and its sites hold + // each callee once. + internal static ShaderCallLibrary WithRuntimeArguments(Gen5ShaderProgram caller, List calls, + Dictionary codeHashes, Dictionary codeRuns, + (ulong Target, ulong Argument)[] records) + { + var sites = new List(calls.Count); + foreach (var site in calls) + { sites.Add(site with { Targets = [.. site.Targets.DistinctBy(static target => target.Address).Select(static target => target with { Argument = 0 })], }); } - return WithRuntimeSites(caller.Address, identity, sites, [.. records], codeHashes, codeRuns) with { CurrentCodeHashes = codeHashes }; + var library = WithRuntimeSites(caller.Address, "", sites, records, codeHashes, codeRuns); + return library with { Identity = library.LayoutIdentity, CurrentCodeHashes = codeHashes }; } // The library of sites whose callees are each named once, in the order of their code, and whose identity names only the @@ -245,7 +342,7 @@ private static ShaderCallLibrary WithRuntimeSites(ulong callerAddress, string id Records = records, CodeHashes = codeHashes, CodeRuns = codeRuns, - Bodies = sites.SelectMany(static site => site.Targets).Select(target => Convert.ToHexString(codeHashes[target.Address])) + Bodies = sites.SelectMany(static site => site.Targets).Select(target => CodeKey(codeHashes[target.Address])) .Distinct().Count(), }; } @@ -279,6 +376,32 @@ public ShaderCallLibrary WithSiteCallees(ulong callerAddress, IReadOnlyDictionar }; } + // This runtime-argument library without the callee at an address, at every site: a call to it returns at once. + public ShaderCallLibrary WithoutCallee(ulong callerAddress, ulong address) => + WithSiteCallees(callerAddress, SiteCallees().ToDictionary(static site => site.Key, + site => site.Value.Where(callee => callee.Target.Address != address).ToDictionary(static callee => callee.Target.Address))); + + // Links the sites with run-time arguments. A callee the linker cannot copy (one that calls another function, say) is left + // out at every site and the others still link: its records return at once, as the records of any callee a program lacks + // do. The library becomes the one the program holds. + public static Gen5ShaderProgram LinkLeavingOutUnlinkable(Gen5ShaderProgram caller, ref ShaderCallLibrary library, + Action leftOut) + { + while (true) + { + try + { + return Gen5ShaderCallLinker.Link(caller, library.Calls, runtimeArguments: true); + } + catch (ShaderCallLinkException failure) when (library.Calls.Any(site => + site.Targets.Any(target => target.Address == failure.Target.Address))) + { + leftOut(failure); + library = library.WithoutCallee(caller.Address, failure.Target.Address); + } + } + } + // This runtime-argument library without a callee at any site: its program returns from every call at once, as from a // record of a callee it does not hold, and compiles in seconds where the callees' code can take the driver minutes. public ShaderCallLibrary WithoutCallees(ulong callerAddress) => @@ -292,21 +415,28 @@ public Dictionary SiteCallees() => Calls.ToDictionary(stat // address, which this updates): a callee that leaves the tables keeps its copy, so tables that drop and regain it link // to the same program. An address whose code changed takes the new code, and a site that would pass maxCallees starts // over from its current callees. - public ShaderCallLibrary Unite(ulong callerAddress, Dictionary> union, int maxCallees) + public ShaderCallLibrary Unite(ulong callerAddress, Dictionary> union, int maxCallees) => + Unite(callerAddress, union, maxCallees, out _); + + // changed: whether the union changed. A call that changed nothing returns the same library again for the same union + // (ShaderCallLibraryMemo keeps that result). + public ShaderCallLibrary Unite(ulong callerAddress, Dictionary> union, int maxCallees, + out bool changed) { + changed = false; // Callees whose code is the same share one decoded program, so the module can share their function: the translator // compares instructions whose controls hold register lists by reference (SameBody). var programs = new Dictionary(); foreach (var known in union.Values.SelectMany(static callees => callees.Values)) { - programs.TryAdd(Convert.ToHexString(known.Code), known.Target.Program); + programs.TryAdd(CodeKey(known.Code), known.Target.Program); } UnitedCallee Current(ShaderCallTarget target) { var code = CodeHashes[target.Address]; - var program = programs.TryGetValue(Convert.ToHexString(code), out var shared) ? shared : target.Program; - programs.TryAdd(Convert.ToHexString(code), program); + var program = programs.TryGetValue(CodeKey(code), out var shared) ? shared : target.Program; + programs.TryAdd(CodeKey(code), program); return new UnitedCallee(target with { Program = program }, code, CodeRuns[target.Address]); } @@ -325,6 +455,7 @@ UnitedCallee Current(ShaderCallTarget target) if (named.TryGetValue(address, out var target) && !known.Code.AsSpan().SequenceEqual(CodeHashes[address])) { callees[address] = Current(target); + changed = true; } } } @@ -363,9 +494,13 @@ UnitedCallee Current(ShaderCallTarget target) { foreach (var (from, to) in moved) { - if (callees.Remove(from) && !callees.ContainsKey(to)) + if (callees.Remove(from)) { - callees[to] = Current(named[to]); + changed = true; + if (!callees.ContainsKey(to)) + { + callees[to] = Current(named[to]); + } } } } @@ -376,11 +511,13 @@ UnitedCallee Current(ShaderCallTarget target) { callees = []; union.Add(site.Pc, callees); + changed = true; } if (site.Targets.Count(target => !callees.ContainsKey(target.Address)) + callees.Count > maxCallees) { callees.Clear(); + changed = true; } foreach (var target in site.Targets) @@ -388,6 +525,7 @@ UnitedCallee Current(ShaderCallTarget target) if (!callees.ContainsKey(target.Address)) { callees[target.Address] = Current(target); + changed = true; } } } @@ -395,6 +533,163 @@ UnitedCallee Current(ShaderCallTarget target) return WithSiteCallees(callerAddress, union); } + // A caller may also copy its target and argument pairs from user data: each of the four call registers (the + // target pair, then the argument pair) still holds a user-data register, reached through S_MOV_B32 and + // S_MOV_B64 copies (a caller may save a pair at entry and reuse it after the call registers were overwritten). + // A call site as the caller's code decides it: the user-data registers that hold its target and argument pairs, or the + // instruction that loads its record, or why it is refused. Each read takes the values from its own dispatch. + private sealed record CallSitePlan(int Index, string? Refusal = null, (uint Target, uint Argument)? UserData = null, + Gen5ShaderInstruction? Load = null, uint ArgumentRegister = 0); + + private sealed record CallSitePlans(uint UserDataBase, uint UserDataCount, CallSitePlan[] Sites); + + private sealed class CallSitePlanSlot + { + public volatile CallSitePlans? Plans; + } + + // By instruction list, which a copy of the program at another address shares. + private static readonly ConditionalWeakTable, CallSitePlanSlot> SitePlans = new(); + + private static CallSitePlan[] CallSites(Gen5ShaderProgram caller, uint userDataBase, uint userDataCount) + { + var slot = SitePlans.GetValue(caller.Instructions, static _ => new CallSitePlanSlot()); + if (slot.Plans is { } plans && plans.UserDataBase == userDataBase && plans.UserDataCount == userDataCount) + { + return plans.Sites; + } + + var planned = new CallSitePlans(userDataBase, userDataCount, PlanSites(caller, userDataBase, userDataCount)); + slot.Plans = planned; + return planned.Sites; + } + + private static CallSitePlan[] PlanSites(Gen5ShaderProgram caller, uint userDataBase, uint userDataCount) + { + var sites = new List(); + for (var index = 0; index < caller.Instructions.Count; index++) + { + if (caller.Instructions[index].Opcode == "SSwappcB64") + { + sites.Add(PlanSite(caller, index, userDataBase, userDataCount)); + } + } + + return [.. sites]; + } + + private static CallSitePlan PlanSite(Gen5ShaderProgram caller, int index, uint userDataBase, uint userDataCount) + { + try + { + return PlanSiteOrThrow(caller, index, userDataBase, userDataCount); + } + catch (InvalidOperationException refusal) + { + return new CallSitePlan(index, refusal.Message); + } + } + + private static CallSitePlan PlanSiteOrThrow(Gen5ShaderProgram caller, int index, uint userDataBase, uint userDataCount) + { + var call = caller.Instructions[index]; + if (call.Sources.Count != 1 || call.Destinations.Count != 1 || + call.Sources[0].Kind != Gen5OperandKind.ScalarRegister || call.Destinations[0].Kind != Gen5OperandKind.ScalarRegister) + throw new InvalidOperationException("The shader call does not use a supported table record."); + if (TryFindUserDataCall(caller, index, userDataBase, userDataCount, out var userData)) + return new CallSitePlan(index, UserData: userData); + Gen5ShaderInstruction load; + Gen5ScalarMemoryControl loadControl; + uint argumentRegister = 0; + if (TryFindDirectRecordLoads(caller, index, out var targetLoad, out var directArgumentRegister)) + { + load = targetLoad; + loadControl = (Gen5ScalarMemoryControl)targetLoad.Control!; + argumentRegister = directArgumentRegister; + } + else + { + if (index < 6) throw new InvalidOperationException("The shader call does not use a supported table record."); + var loadIndex = index - 6; + while (loadIndex >= 0 && caller.Instructions[loadIndex] is { Opcode: "VMovB32", Destinations.Count: 1 } vectorMove && + vectorMove.Destinations[0].Kind == Gen5OperandKind.VectorRegister) loadIndex--; + if (loadIndex < 0) throw new InvalidOperationException("The shader call table load is missing."); + load = caller.Instructions[loadIndex]; + if (load.Opcode != "SBufferLoadDwordx4" || load.Control is not Gen5ScalarMemoryControl recordControl || + load.Destinations.Count != 4 || caller.Instructions[index - 5].Opcode != "SWaitcnt") + throw new InvalidOperationException("The shader call table load is not supported."); + loadControl = recordControl; + if (loadControl.DynamicOffsetRegister is { } selector) + { + var scale = caller.Instructions.Take(loadIndex).Reverse().FirstOrDefault(instruction => + instruction.Opcode.StartsWith("SCbranch", StringComparison.Ordinal) || instruction.Opcode is "SBranch" or "SSwappcB64" || + instruction.Destinations.Any(destination => destination.Kind == Gen5OperandKind.ScalarRegister && + selector >= destination.Value && selector - destination.Value < instruction.DestinationWidth)); + if (scale is null || scale.Opcode != "SLshlB32" || scale.Destinations.Count != 1 || scale.Destinations[0] != Gen5Operand.Scalar(selector) || + scale.Sources.Count != 2 || scale.Sources[1] != new Gen5Operand(Gen5OperandKind.EncodedConstant, 132)) + throw new InvalidOperationException("The shader call table does not use 16-byte records."); + } + for (var component = 0; component < 4; component++) + { + var move = caller.Instructions[index - 4 + component]; + if (move.Opcode != "SMovB32" || move.Sources.Count != 1 || move.Destinations.Count != 1 || + move.Sources[0] != load.Destinations[component] || move.Destinations[0].Kind != Gen5OperandKind.ScalarRegister) + throw new InvalidOperationException("The shader call record has an unsupported register transfer."); + if (component == 2) argumentRegister = move.Destinations[0].Value; + var expected = component < 2 ? call.Sources[0].Value + (uint)component : argumentRegister + (uint)component - 2; + if (move.Destinations[0].Value != expected) + throw new InvalidOperationException("The shader call record does not use register pairs."); + } + } + return new CallSitePlan(index, Load: load, ArgumentRegister: argumentRegister); + } + + private static ulong UserDataPair(ResourceSnapshot snapshot, uint userDataBase, uint first) => + snapshot.UserData[first - userDataBase] | (ulong)snapshot.UserData[first - userDataBase + 1] << 32; + + private static bool TryFindUserDataCall(Gen5ShaderProgram caller, int index, uint userDataBase, uint userDataCount, + out (uint Target, uint Argument) userData) + { + userData = default; + var callRegister = caller.Instructions[index].Sources[0].Value; + var sources = new uint[4]; + for (var slot = 0; slot < sources.Length; slot++) + if (!TryTraceUserDataRegister(caller, index, callRegister + (uint)slot, userDataBase, userDataCount, out sources[slot])) + return false; + if (sources[1] != sources[0] + 1 || sources[3] != sources[2] + 1) return false; + userData = (sources[0], sources[2]); + return true; + } + + // Follows one scalar register back from an instruction through register copies to the user-data register it + // holds. Any other writer ends the trace; a vector instruction's scalar result counts as a lane-mask pair. + private static bool TryTraceUserDataRegister(Gen5ShaderProgram caller, int before, uint register, uint userDataBase, + uint userDataCount, out uint userDataRegister) + { + userDataRegister = 0; + for (var cursor = before - 1; cursor >= 0; cursor--) + { + var instruction = caller.Instructions[cursor]; + var vector = instruction.Encoding is Gen5ShaderEncoding.Vopc or Gen5ShaderEncoding.Vop3 or Gen5ShaderEncoding.Vop1 or + Gen5ShaderEncoding.Vop2; + foreach (var destination in instruction.Destinations) + { + var width = vector ? 2u : Math.Max(instruction.DestinationWidth, 1u); + if (destination.Kind != Gen5OperandKind.ScalarRegister || register < destination.Value || + register - destination.Value >= width) continue; + if (instruction.Opcode is not ("SMovB32" or "SMovB64") || instruction.Sources.Count != 1 || + instruction.Sources[0].Kind != Gen5OperandKind.ScalarRegister) return false; + register = instruction.Sources[0].Value + (register - destination.Value); + goto Traced; + } + continue; + Traced:; + } + if (register < userDataBase || register - userDataBase >= userDataCount) return false; + userDataRegister = register; + return true; + } + // A caller may also load one 16-byte record straight into the call registers: the target pair with an // S_BUFFER_LOAD_DWORDX2 and the argument pair with another one 8 bytes further on, often with a null // check of the target that branches past the call. Only waits, scalar compares and such a branch may stand diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibraryMemo.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibraryMemo.cs new file mode 100644 index 000000000..936d20ea9 --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallLibraryMemo.cs @@ -0,0 +1,355 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.Libs.Gpu.Pipelines; + +// Reuse of call-library work across dispatches, on by default: a ray-traced pass derives its call library again at +// every dispatch, hundreds of times per frame. SHARPEMU_CALL_LIBRARY_REUSE=0, or any value but 1, turns it off. Unite +// still tracks the union's changes while reuse is off, so a result kept earlier is never reused over a union the path +// without reuse changed meanwhile. +// +// A run-time-record caller's library is derived again at every dispatch. Its records (which change as often as every +// frame) are this dispatch's own, but its topology (the sites, the callees each site names and their code, and what is +// derived from them: the callee order and slots, the layout identity, the union and the chosen callees) changes rarely: +// - Topology: the per-record scan of the tables stays fresh (dedup, first occurrence, unreadable targets, current sites, +// code hashes from the function cache's validated lookups). A run-time library whose sites and distinct callees (by +// address, in first occurrence, each with the decoded program of the function cache's result) equal a previous read's +// reuses that read's sorted sites, slots, identity and bodies, with this dispatch's records and current code hashes. +// - Unite and WithSiteCallees depend on their input library only through its topology and carry its records, current +// code hashes and current sites through; their results are kept by topology (and the union's version, or the chosen +// callees map) and reused with the current dispatch's fields. A Unite that changed the union is not kept. +// The tables and functions are read at every dispatch as without reuse (ShaderCallLibrary.Read). Whole libraries are +// not cached by their exact input: the input words change at every dispatch. +internal sealed class ShaderCallLibraryMemo +{ + internal enum Mode { Off, On } + + internal static readonly Mode Configured = Environment.GetEnvironmentVariable("SHARPEMU_CALL_LIBRARY_REUSE") switch + { + null or "" or "1" => Mode.On, + _ => Mode.Off, + }; + + // Whether reuse is on. Code-hash text follows it (ShaderCallLibrary.CodeKey). + internal static bool Enabled => Configured != Mode.Off; + + // Tests make a memo that always or never reuses (active true or false), whatever the configuration (the variable is + // read once per process). Null follows the configuration. + private readonly bool? _active; + + internal ShaderCallLibraryMemo(bool? active = null) + { + _active = active; + } + + private bool IsActive => _active ?? Enabled; + + private const int MaxTopologies = 4096; + + private enum Counter + { + TopologyHit, TopologyMiss, UniteHit, UniteMiss, UniteChanged, UniteUntokened, SitesHit, SitesMiss, SitesUntokened, + Off, Count, + } + + private readonly long[] _counters = new long[(int)Counter.Count]; + + private void Count(Counter counter) => _counters[(int)counter]++; + + // Tests: a counter's total since the memo was made, by name. + internal long Counted(string counter) => _counters[(int)Enum.Parse(counter)]; + + // ---- Read ------------------------------------------------------------------------------------------------------------ + + // The library of the caller's call sites, as ShaderCallLibrary.Read returns it. + internal ShaderCallLibrary Read(Gen5ShaderProgram caller, MemoryAccessTable memory, ResourceSnapshot snapshot, GuestWordReader read, + ShaderFunctionCache? functionCache, bool runtimeArguments, uint userDataBase, ResidentGuestBytesReader? readBytes) + { + var active = IsActive; + if (!active) Count(Counter.Off); + return ShaderCallLibrary.Read(caller, memory, snapshot, read, functionCache, runtimeArguments, userDataBase, readBytes, + active ? this : null); + } + + // ---- Topology -------------------------------------------------------------------------------------------------------- + + // A run-time library's topology: the caller, and per site its registers, its return address and the set of distinct + // callees its records name (by address), each with the program the function cache's result decoded. The static library + // sorts each site's callees by code and address, so the order the records name them in is not part of it. + private sealed class Topology(ulong[] words, object[] programs, ShaderCallLibrary library) + { + public readonly ulong[] Words = words; + public readonly object[] Programs = programs; + public readonly ShaderCallLibrary Library = library; + } + + private readonly Dictionary<(object Instructions, ulong Hash), List> _topologies = new(); + private int _topologyCount; + private readonly List _topologyWords = new(256); + private readonly List _topologyPrograms = new(128); + private readonly Dictionary _callees = new(); + private readonly List _sorted = new(); + + // ShaderCallLibrary.WithRuntimeArguments for a read's sites and callees, reusing a previous read's topology. Called by + // ShaderCallLibrary.Read; the caller attaches the read's current sites. records: the read's records when it collected + // them itself (a one-pass read, whose sites hold each callee once); null collects them from the sites. + internal ShaderCallLibrary Runtime(Gen5ShaderProgram caller, List calls, Dictionary codeHashes, + Dictionary codeRuns, (ulong Target, ulong Argument)[]? records = null) + { + var words = _topologyWords; + var programs = _topologyPrograms; + words.Clear(); + programs.Clear(); + words.Add(caller.Address); + foreach (var site in calls) + { + words.Add(site.Pc); + words.Add(site.AddressRegister | (ulong)site.ArgumentRegister << 32); + words.Add(site.ReturnRegister); + words.Add(site.ReturnAddress); + _callees.Clear(); + foreach (var target in site.Targets) + { + _callees.TryAdd(target.Address, target.Program); + } + + words.Add((ulong)_callees.Count); + _sorted.Clear(); + _sorted.AddRange(_callees.Keys); + _sorted.Sort(); + foreach (var address in _sorted) + { + words.Add(address); + programs.Add(_callees[address]); + } + } + + var hash = Hash(CollectionsMarshal.AsSpan(words)); + foreach (var program in CollectionsMarshal.AsSpan(programs)) hash = (hash ^ (ulong)RuntimeHelpers.GetHashCode(program)) * 0x100000001B3UL; + var key = ((object)caller.Instructions, hash); + if (_topologies.TryGetValue(key, out var candidates)) + { + foreach (var topology in candidates) + { + if (!topology.Words.AsSpan().SequenceEqual(CollectionsMarshal.AsSpan(words)) || + !SameReferences(topology.Programs, CollectionsMarshal.AsSpan(programs))) + { + continue; + } + + Count(Counter.TopologyHit); + // The records, as WithRuntimeArguments collects them: every site's distinct target and argument pairs, in + // first occurrence. + var current = records ?? ShaderCallLibrary.RuntimeRecords(calls); + return topology.Library with { Records = current, CurrentCodeHashes = codeHashes }; + } + } + + Count(Counter.TopologyMiss); + if (_topologyCount >= MaxTopologies) + { + _topologies.Clear(); + _topologyCount = 0; + } + + var library = ShaderCallLibrary.WithRuntimeArguments(caller, calls, codeHashes, codeRuns, + records ?? ShaderCallLibrary.RuntimeRecords(calls)) with { Topology = new object() }; + if (!_topologies.TryGetValue(key, out candidates)) _topologies[key] = candidates = new List(1); + candidates.Add(new Topology(words.ToArray(), programs.ToArray(), library)); + _topologyCount++; + return library; + } + + private static bool SameReferences(object[] left, ReadOnlySpan right) + { + if (left.Length != right.Length) return false; + for (var index = 0; index < left.Length; index++) + if (!ReferenceEquals(left[index], right[index])) return false; + return true; + } + + // ---- Unite and site callees, by topology ------------------------------------------------------------------------------ + + private sealed class UniteResult(object union, long version, ulong callerAddress, int maxCallees, ShaderCallLibrary output) + { + public readonly object Union = union; + public readonly long Version = version; + public readonly ulong CallerAddress = callerAddress; + public readonly int MaxCallees = maxCallees; + public readonly ShaderCallLibrary Output = output; + } + + private sealed class SitesResult(object callees, ulong callerAddress, ShaderCallLibrary output) + { + public readonly object Callees = callees; + public readonly ulong CallerAddress = callerAddress; + public readonly ShaderCallLibrary Output = output; + } + + private readonly ConditionalWeakTable _unites = new(); + private readonly ConditionalWeakTable> _unionVersions = new(); + private readonly ConditionalWeakTable _sites = new(); + + // A kept result with this dispatch's own fields. + private static ShaderCallLibrary WithCurrent(ShaderCallLibrary kept, ShaderCallLibrary current) => kept with + { + Records = current.Records, + CurrentCodeHashes = current.CurrentCodeHashes, + CurrentSites = current.CurrentSites, + }; + + // ShaderCallLibrary.Unite (which updates union): a call that changed nothing is kept by the input's topology and the + // union's version, and reused while both hold. + internal ShaderCallLibrary Unite(ShaderCallLibrary library, ulong callerAddress, Dictionary> union, + int maxCallees) => Unite(library, callerAddress, union, maxCallees, out _); + + // changed: whether this call changed the union (its version moved). + internal ShaderCallLibrary Unite(ShaderCallLibrary library, ulong callerAddress, Dictionary> union, + int maxCallees, out bool changed) + { + changed = false; + var version = _unionVersions.GetValue(union, static _ => new StrongBox()); + if (library.Topology is not { } topology || !IsActive) + { + Count(Counter.UniteUntokened); + var original = library.Unite(callerAddress, union, maxCallees, out var originalChanged); + if (originalChanged) + { + version.Value++; + changed = true; + } + + return original; + } + + if (_unites.TryGetValue(topology, out var kept) && ReferenceEquals(kept.Union, union) && kept.Version == version.Value && + kept.CallerAddress == callerAddress && kept.MaxCallees == maxCallees) + { + Count(Counter.UniteHit); + return WithCurrent(kept.Output, library); + } + + Count(Counter.UniteMiss); + var output = library.Unite(callerAddress, union, maxCallees, out var unionChanged); + if (unionChanged) + { + Count(Counter.UniteChanged); + version.Value++; + changed = true; + return output; + } + + output = output with { Topology = new object() }; + _unites.AddOrUpdate(topology, new UniteResult(union, version.Value, callerAddress, maxCallees, output)); + return output; + } + + // ShaderCallLibrary.WithSiteCallees, kept by the input's topology and the callees map (a chosen map is never changed). + internal ShaderCallLibrary WithSiteCallees(ShaderCallLibrary library, ulong callerAddress, + IReadOnlyDictionary> callees) + { + if (library.Topology is not { } topology || !IsActive) + { + Count(Counter.SitesUntokened); + return library.WithSiteCallees(callerAddress, callees); + } + + if (_sites.TryGetValue(topology, out var kept) && ReferenceEquals(kept.Callees, callees) && kept.CallerAddress == callerAddress) + { + Count(Counter.SitesHit); + return WithCurrent(kept.Output, library); + } + + Count(Counter.SitesMiss); + var output = library.WithSiteCallees(callerAddress, callees) with { Topology = new object() }; + _sites.AddOrUpdate(topology, new SitesResult(callees, callerAddress, output)); + return output; + } + + // ---- Common ---------------------------------------------------------------------------------------------------------- + + private static ulong Hash(ReadOnlySpan words) + { + var hash = 0xCBF29CE484222325UL ^ (ulong)words.Length; + foreach (var word in words) + { + hash = (hash ^ word) * 0x100000001B3UL; + hash ^= hash >> 29; + } + + return hash; + } + + // The first difference between two libraries, or null when they are the same: identities, sites with their registers + // and targets (address, argument, the same decoded program), records in order, arguments, bodies, callee code and runs + // (by address), and the current code hashes (in order) and sites of the dispatch. + internal static string? Difference(ShaderCallLibrary left, ShaderCallLibrary right) + { + if (left.Identity != right.Identity) return "identity"; + if (left.LayoutIdentity != right.LayoutIdentity) return "layout identity"; + if (!left.Arguments.AsSpan().SequenceEqual(right.Arguments)) return "arguments"; + if (!left.Records.AsSpan().SequenceEqual(right.Records)) return "records"; + if (left.Bodies != right.Bodies) return "bodies"; + if (left.Calls.Count != right.Calls.Count) return "site count"; + for (var index = 0; index < left.Calls.Count; index++) + { + var (a, b) = (left.Calls[index], right.Calls[index]); + if (a.Pc != b.Pc || a.AddressRegister != b.AddressRegister || a.ArgumentRegister != b.ArgumentRegister || + a.ReturnRegister != b.ReturnRegister || a.ReturnAddress != b.ReturnAddress || a.Targets.Count != b.Targets.Count) + return $"site {index}"; + for (var target = 0; target < a.Targets.Count; target++) + { + var (x, y) = (a.Targets[target], b.Targets[target]); + if (x.Address != y.Address || x.Argument != y.Argument || !ReferenceEquals(x.Program, y.Program)) + return $"site {index} target {target}"; + } + } + + if (!SameBytesByKey(left.CodeHashes, right.CodeHashes)) return "code hashes"; + if (!SameBytes(left.CurrentCodeHashes, right.CurrentCodeHashes)) return "current code hashes"; + if (left.CodeRuns.Count != right.CodeRuns.Count) return "code runs"; + foreach (var (address, runs) in left.CodeRuns) + { + if (!right.CodeRuns.TryGetValue(address, out var other) || runs.Length != other.Length) return "code runs"; + for (var run = 0; run < runs.Length; run++) + if (runs[run].Address != other[run].Address || !runs[run].Bytes.AsSpan().SequenceEqual(other[run].Bytes)) return "code runs"; + } + + if (left.CurrentSites.Count != right.CurrentSites.Count) return "current sites"; + foreach (var (address, sites) in left.CurrentSites) + if (!right.CurrentSites.TryGetValue(address, out var other) || !sites.SetEquals(other)) return "current sites"; + return null; + } + + // Same keys with equal bytes, in any order: the static code hashes are looked up by address, never enumerated for a + // decision, and a reused topology holds them in the order of the read that derived it. + private static bool SameBytesByKey(Dictionary left, Dictionary right) + { + if (left.Count != right.Count) return false; + foreach (var (address, bytes) in left) + { + if (!right.TryGetValue(address, out var other) || !bytes.AsSpan().SequenceEqual(other)) return false; + } + + return true; + } + + // Same keys with equal bytes, in the same order. + private static bool SameBytes(Dictionary left, Dictionary right) + { + if (left.Count != right.Count) return false; + using var first = left.GetEnumerator(); + using var second = right.GetEnumerator(); + while (first.MoveNext() && second.MoveNext()) + { + if (first.Current.Key != second.Current.Key || !first.Current.Value.AsSpan().SequenceEqual(second.Current.Value)) return false; + } + + return true; + } +} diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallUnionStore.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallUnionStore.cs index bf21e4312..16e185f6b 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallUnionStore.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCallUnionStore.cs @@ -43,6 +43,20 @@ public Dictionary> Load(ShaderStage stage, return callees; } + // Whether the callees kept for the caller are the ones the recorded library links, site by site, so a session's first + // link of the caller asks for that library's program. + public bool KeepsCalleesOf(ShaderStage stage, ulong hash, LinkedShaderPrewarm linked) + { + EnsureLoaded(); + if (!_callers.TryGetValue((stage, hash), out var sites)) + { + return false; + } + + var kept = sites.SelectMany(static site => site.Value.Select(callee => (site.Key, callee.Target.Address))).ToHashSet(); + return kept.SetEquals(linked.Sites.SelectMany(static site => site.Targets.Select(target => (site.Pc, target.Address)))); + } + public void Save(ShaderStage stage, ulong hash, Dictionary sites) { if (path is null) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCalleeTiers.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCalleeTiers.cs index 54b3b0777..e401c435a 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCalleeTiers.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCalleeTiers.cs @@ -20,7 +20,7 @@ internal sealed class ShaderCalleeTiers // A choice waits this many snapshots after the last callee became called, and at most MaxSettle after the first one that // the chosen program lacks. - private const long Settle = 8; + internal const long Settle = 8; private const long MaxSettle = 64; private readonly HashSet _called; @@ -29,12 +29,18 @@ internal sealed class ShaderCalleeTiers private long _lastCalled = -1; private long _firstUnchosen = -1; + // The union changes the program cache reports (NoteUnionChanged: each Unite that changed the union or failed), and the + // union revision and choice that HasUnchosenCalledSite last found fully chosen. The scan runs again only after either moves. + private long _unionRevision = 1; + private long _scannedRevision; + private object? _scannedChosen; + // The callees an earlier session kept for the caller count as called, and its first program holds exactly those, whose // pipeline the linked cache holds. The union also names the other addresses the game loaded the same code at in this // session, and a first program that held them too would be another compile of minutes. public ShaderCalleeTiers(IReadOnlyDictionary> kept) { - _called = [.. kept.Values.SelectMany(static callees => callees.Values).Select(static callee => Convert.ToHexString(callee.Code))]; + _called = [.. kept.Values.SelectMany(static callees => callees.Values).Select(static callee => ShaderCallLibrary.CodeKey(callee.Code))]; if (kept.Count != 0) { _chosen = kept.ToDictionary(static site => site.Key, static site => site.Value); @@ -43,6 +49,9 @@ public ShaderCalleeTiers(IReadOnlyDictionary _called.Count; + // The program cache's Unite changed this caller's union (or failed while changing it): no earlier scan of it stands. + internal void NoteUnionChanged() => _unionRevision++; + // The generation of the program linked from the chosen callees, once the caller has linked it. public long? LinkedGeneration { get; set; } @@ -53,7 +62,7 @@ public int Observe(ShaderCallLibrary library, ulong callerHash, IShaderPipelineH var added = 0; foreach (var (address, code) in library.CurrentCodeHashes) { - var key = Convert.ToHexString(code); + var key = ShaderCallLibrary.CodeKey(code); if (_called.Contains(key)) { continue; @@ -98,6 +107,28 @@ public void NoteUnservedCopy(long snapshots) public IReadOnlyDictionary> Choose(Dictionary> union, long fallbackGeneration, long snapshots) { + // A body already called at one site can appear at another without a new body or address. Marks are per body, and a + // globally served address is not an unserved copy, so neither observation would move the choice, and the program + // would keep no target at the new site. Batch this new site coverage like a call. Such a site can appear only after a + // union change the program cache reported or a new choice (a body that becomes called moves the choice in Observe). + if (_chosen is not null && _firstUnchosen < 0) + { + if (_scannedRevision != _unionRevision || !ReferenceEquals(_scannedChosen, _chosen)) + { + if (HasUnchosenCalledSite(union)) + { + _firstUnchosen = snapshots; + _lastCalled = snapshots; + } + else + { + // Only the scan's cost depends on these, never Choose's result. + _scannedRevision = _unionRevision; + _scannedChosen = _chosen; + } + } + } + if (_chosen is not null && (LinkedGeneration is not { } generation || fallbackGeneration < generation || _firstUnchosen < 0 || snapshots - _lastCalled < Settle && snapshots - _firstUnchosen < MaxSettle)) { @@ -112,7 +143,7 @@ public IReadOnlyDictionary> Choose(Diction var linked = new Dictionary(); foreach (var (address, callee) in callees) { - if (_called.Contains(Convert.ToHexString(callee.Code))) + if (_called.Contains(ShaderCallLibrary.CodeKey(callee.Code))) { linked.Add(address, callee); } @@ -130,6 +161,27 @@ public IReadOnlyDictionary> Choose(Diction return _chosen; } + // Compare code at the same site, not its address: moving an existing site's body can keep its slot through + // CurrentTargets, while additional address copies are reported there (NoteUnservedCopy). + private bool HasUnchosenCalledSite(Dictionary> union) + { + if (_chosen is not { } chosen) return false; + foreach (var (pc, callees) in union) + { + foreach (var callee in callees.Values) + { + if (!_called.Contains(ShaderCallLibrary.CodeKey(callee.Code))) continue; + if (!chosen.TryGetValue(pc, out var linked) || + !linked.Values.Any(known => known.Code.AsSpan().SequenceEqual(callee.Code))) + { + return true; + } + } + } + + return false; + } + private static bool SameChoice(Dictionary> left, Dictionary> right) { if (left.Count != right.Count) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderDescriptorLimits.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderDescriptorLimits.cs index 4b89a0046..da9f6b108 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderDescriptorLimits.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderDescriptorLimits.cs @@ -1,12 +1,40 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using SharpEmu.ShaderCompiler.Resources; using Silk.NET.Vulkan; namespace SharpEmu.Libs.Gpu.Pipelines; internal static class ShaderDescriptorLimits { + // Compute owns its set. A larger layout can use an allocated set instead of push descriptors, + // but must fit one pool as well as the per-stage and per-set device limits. + public static StableImageDescriptorLimits ComputeImageLimits(PhysicalDeviceLimits limits) + { + var pool = DescriptorHeap.PoolCapacity; + return new( + Math.Min(Math.Min(limits.MaxPerStageDescriptorSampledImages, limits.MaxDescriptorSetSampledImages), pool.SampledImages), + Math.Min(Math.Min(limits.MaxPerStageDescriptorStorageImages, limits.MaxDescriptorSetStorageImages), pool.StorageImages), + Math.Min(Math.Min(limits.MaxPerStageDescriptorSamplers, limits.MaxDescriptorSetSamplers), pool.Samplers), + Math.Min(Math.Min(limits.MaxPerStageDescriptorStorageBuffers, limits.MaxDescriptorSetStorageBuffers), pool.StorageBuffers), + limits.MaxPerStageResources); + } + + // A graphics stage shares its set and pool with the pipeline's other stage when the pipeline is built whole, so each + // stage takes at most half the per-set and pool budget (and its per-stage limits): any two stages then fit together. + public static StableImageDescriptorLimits GraphicsImageLimits(PhysicalDeviceLimits limits) + { + var pool = DescriptorHeap.PoolCapacity; + return new( + Math.Min(limits.MaxPerStageDescriptorSampledImages, Math.Min(limits.MaxDescriptorSetSampledImages, pool.SampledImages) / 2), + Math.Min(limits.MaxPerStageDescriptorStorageImages, Math.Min(limits.MaxDescriptorSetStorageImages, pool.StorageImages) / 2), + Math.Min(limits.MaxPerStageDescriptorSamplers, Math.Min(limits.MaxDescriptorSetSamplers, pool.Samplers) / 2), + Math.Min(limits.MaxPerStageDescriptorStorageBuffers, + Math.Min(limits.MaxDescriptorSetStorageBuffers, pool.StorageBuffers) / 2), + limits.MaxPerStageResources); + } + public static void Validate(IReadOnlyList bindings, PhysicalDeviceLimits limits) { ValidateScope(bindings, 0, limits, false); diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderFunctionReader.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderFunctionReader.cs index 5802808fa..a09b16deb 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderFunctionReader.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderFunctionReader.cs @@ -90,6 +90,9 @@ public byte[] CapturedBytes() // Decoded shader functions by address. A call table names the same functions on every dispatch, so a function is decoded // again only when a word its decode read has changed: each lookup compares those words with the guest's current ones. +// A decode that failed on the words it read fails again until one of them changes, so it is kept the same way (a table +// may hold a stale record naming other data); a failed read of guest memory is not kept, as the memory may be readable +// on the next lookup. internal sealed class ShaderFunctionCache(ResidentGuestBytesReader? residentReader) { private const int Capacity = 4096; @@ -101,7 +104,7 @@ public ShaderFunctionReadResult Read(ulong address, GuestWordReader read) if (_functions.TryGetValue(address, out var cached) && Unchanged(cached, read)) return cached; var result = ShaderFunctionReader.Read(address, read); - if (!result.Complete) + if (!result.Complete && result.Error.Contains("read-failed", StringComparison.Ordinal)) { _functions.Remove(address); return result; diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPermutationDump.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPermutationDump.cs index a74faff8b..d622b63ee 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPermutationDump.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPermutationDump.cs @@ -41,7 +41,7 @@ private static Action CreateEnabledFailureCapture(ShaderSo { ProgramId = candidate.Handle.Id, SpecializationMatches = candidate.Specialization.Equals(specialization), - PushDataMatches = candidate.Bindings.PushDataStartDword == PushData.StartFor(pushDataCursor, candidate.Bindings.ShaderDataDwordCount), + PushDataMatches = candidate.Bindings.PushDataStartDword == candidate.Bindings.PushStartFor(pushDataCursor), candidate.Bindings.PushDataStartDword, candidate.Bindings.ShaderDataDwordCount, }).ToArray(); diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index 0d1fd674c..3da151f0c 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -30,6 +30,9 @@ internal sealed partial class ShaderPipelineCache : IShaderPipelineProvider private readonly ShaderHeaderRegistry _registry; private readonly ShaderProgramCache _programs; private readonly System.Collections.Concurrent.ConcurrentDictionary _graphicsPipelines = new(); + // The pipelines the host is still compiling (IShaderPipelineHost.TryCreateGraphicsPipeline), each with the key and the + // description that started its compile; under _pipelineGate. + private readonly Dictionary _pendingGraphicsPipelines = new(); private readonly System.Collections.Concurrent.ConcurrentDictionary _computePipelines = new(); private readonly Dictionary _rayTracingComputePrograms = new(); private readonly object _pipelineGate = new(); @@ -162,7 +165,8 @@ internal ulong IdentityOf(ShaderHeaderEntry header, ulong codeAddress, string la public static string TakeFastPathReport() => FormattableString.Invariant($"[PERF][FAST_PATHS] zero_group_skips={Interlocked.Exchange(ref Rendering.RenderExecutor.ZeroGroupSkips, 0)} shader_hash_memo={_identityMemoHits.Take()} ") + - FormattableString.Invariant($"stream_cleaned={Interlocked.Exchange(ref Buffers.GuestBufferCache.StreamCleaned, 0)} stream_uses={Interlocked.Exchange(ref Buffers.GuestBufferCache.StreamUses, 0)}"); + FormattableString.Invariant($"stream_cleaned={Interlocked.Exchange(ref Buffers.GuestBufferCache.StreamCleaned, 0)} stream_uses={Interlocked.Exchange(ref Buffers.GuestBufferCache.StreamUses, 0)} ") + + Buffers.GuestBufferCache.TakeObtainMemoReport(); private uint[]? InputSemantics(ShaderHeaderEntry header) { @@ -201,12 +205,22 @@ public GraphicsPrograms GetMeshGraphicsPrograms( UserConfigRegisters userConfig, ReadOnlySpan targetExportMapping, bool pixelActive, - bool depthBound) + bool depthBound) => + GetMeshGraphicsPrograms(banks, userConfig, targetExportMapping, pixelActive, depthBound, taskLaunch: false); + + // taskLaunch: an automatic indirect draw launched by the task stage (MeshTaskLaunch). + public GraphicsPrograms GetMeshGraphicsPrograms( + RegisterBanks banks, + UserConfigRegisters userConfig, + ReadOnlySpan targetExportMapping, + bool pixelActive, + bool depthBound, + bool taskLaunch) { var vertex = banks.Shader.Vertex; var context = banks.Context; var shaderInterface = context.ShaderInterface; - var mesh = PrepareMeshInput(vertex, shaderInterface, context, userConfig); + var mesh = PrepareMeshInput(vertex, shaderInterface, context, userConfig, taskLaunch); if (MeshDrawTrace.Active) { var group = userConfig.GeometryEngineControl; @@ -521,7 +535,10 @@ mesh is null DropUnwrittenColorTargets = dropUnwritten, PositionStream = mesh is null ? FindPositionStream(vertexInfo) : null, }; - if (keptGraphics is not null) + // A program with shader calls reads its call tables at every draw: its call records, targets and ready fallback can + // change while its registers and resources stay the same. + if (keptGraphics is not null && pair.Vertex.Entry is not { HasShaderCalls: true } && + (pixelSource is null || pair.Pixel.Entry is not { HasShaderCalls: true })) { KeepGraphicsPrograms(keptGraphics, programs, programsStamp, vertexUserDataStamp, pixelUserDataStamp, interfaceStamp, blendDependent ? banks.Stamp(RegisterStamp.PipelineState) : 0, pixelActive ? PixelOutputBlend(context) : 0, targetExportMapping, pixelActive, @@ -531,9 +548,12 @@ mesh is null return programs; } + // The task stage's payload (SpirvMeshTask): three words, rounded up. + private const uint MeshTaskPayloadBytes = 16; + private MeshDrawConfiguration? PrepareMeshInput(VertexStageRegisters vertex, ShaderInterfaceRegisters shaderInterface, ContextRegisters context, - UserConfigRegisters userConfig) + UserConfigRegisters userConfig, bool taskLaunch = false) { var planned = MeshDrawPlanner.Create(vertex, shaderInterface, context, userConfig, _host.MeshLimits, _host.MeshSubgroupSize); @@ -547,6 +567,10 @@ mesh is null IeeeMode = vertex.GeometryResource1.IeeeMode, ScratchDwords = Math.Max(registered.ScratchDwords, registered.ContinuationScratchDwords), ClipSpace = ResolveClipSpace(context), + // The task payload shares the mesh workgroup's payload-and-shared memory with the planned shared memory. + TaskLaunched = taskLaunch && + (configuration.Geometry.LocalDataShareDwords + configuration.Geometry.OutputVertexCapacity + 5) * 4 + MeshTaskPayloadBytes <= + _host.MeshLimits.MaxSharedMemoryBytes, }, }; } @@ -1037,8 +1061,15 @@ private static int BoundColorSlots(ContextRegisters context, Span slots) public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitiator, uint dimensionX, uint dimensionY, uint dimensionZ) => GetComputeProgram(banks, dispatchInitiator, dimensionX, dimensionY, dimensionZ, indirect: false); - public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitiator, uint dimensionX, uint dimensionY, uint dimensionZ, bool indirect) + public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitiator, uint dimensionX, uint dimensionY, uint dimensionZ, bool indirect) => + GetComputeProgram(banks, dispatchInitiator, dimensionX, dimensionY, dimensionZ, indirect, gpuThreadCounts: false); + + // gpuThreadCounts: the thread counts are in GPU memory (zero here); the program reads its thread limits from shader data + // the GPU writes (ComputeInputInfo.IndirectThreadCounts). + public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitiator, uint dimensionX, uint dimensionY, uint dimensionZ, bool indirect, + bool gpuThreadCounts) { + indirect |= gpuThreadCounts; var compute = banks.Shader.Compute; var registrations = ShaderHeaderRegistry.Registrations; var all = _keptComputes ??= new Dictionary>(); @@ -1051,7 +1082,8 @@ public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitia KeptComputeProgram? kept = null; foreach (var candidate in keptList) { - if (candidate.Registrations == registrations && candidate.DispatchInitiator == dispatchInitiator && SameComputeShape(candidate.Registers, compute)) + if (candidate.Registrations == registrations && candidate.DispatchInitiator == dispatchInitiator && + candidate.GpuThreadCounts == gpuThreadCounts && SameComputeShape(candidate.Registers, compute)) { kept = candidate; break; @@ -1077,7 +1109,8 @@ public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitia } _computeResolved.Increment(); - var program = ResolveComputeProgram(compute, dispatchInitiator, dimensionX, dimensionY, dimensionZ, out var source, out var systemRegisters, out var decoded); + var program = ResolveComputeProgram(compute, dispatchInitiator, dimensionX, dimensionY, dimensionZ, gpuThreadCounts, out var source, + out var systemRegisters, out var decoded); if (program.ImageCopy is not null) return program; if (kept is null) @@ -1087,7 +1120,7 @@ public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitia keptList.RemoveAt(0); } - kept = new KeptComputeProgram { Registrations = registrations, DispatchInitiator = dispatchInitiator }; + kept = new KeptComputeProgram { Registrations = registrations, DispatchInitiator = dispatchInitiator, GpuThreadCounts = gpuThreadCounts }; keptList.Add(kept); } @@ -1101,7 +1134,8 @@ public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitia private static void KeepComputeProgram(KeptComputeProgram kept, ComputeProgram program, ComputeStageRegisters compute, uint dimensionX, uint dimensionY, uint dimensionZ) { - kept.Program = program.Available && !program.Consumed ? program : null; + // A program with shader calls reads its call tables at every dispatch (its entry rebinds instead). + kept.Program = program.Available && !program.Consumed && kept.Entry is not { HasShaderCalls: true } ? program : null; if (kept.Registers is { } registers && SameComputeShape(registers, compute)) { registers.UserScalars.CopyFrom(compute.UserScalars, compute.UserScalarCount); @@ -1122,9 +1156,14 @@ private ComputeProgram RebindComputeProgram(KeptComputeProgram kept, ProgramSour var userData = UserData(compute.UserScalars, compute.UserScalarCount, probeWrittenRegisters: false, compute.Address, "compute").ToArray(); var source = kept.Source! with { UserData = userData }; kept.Source = source; - var input = ComputeStageInputResolver.Resolve(compute, source.Registered, dispatchInitiator, !_host.ComputeWave64Supported, dimensionX, dimensionY, dimensionZ); - var pushDataCursor = 0u; - var options = new StageCompileOptions { ComputeInfo = input, ComputeSystemRegisters = kept.SystemRegisters }; + var input = ComputeStageInputResolver.Resolve(compute, source.Registered, dispatchInitiator, !_host.ComputeWave64Supported, dimensionX, dimensionY, dimensionZ, + kept.GpuThreadCounts); + var pushDataCursor = ComputePushDataCursor(input); + var options = new StageCompileOptions + { + ComputeInfo = input, ComputeSystemRegisters = kept.SystemRegisters, + ComputeDispatch = CountedDispatch(input, kept.SystemRegisters, dimensionX, dimensionY, dimensionZ, kept.GpuThreadCounts), + }; if (!_programs.TryGetProgramForEntry(entry, source, options, _strictShaders, ref pushDataCursor, out var handle, out var stage, out var rejection)) { ReportShaderSkip(source, rejection); @@ -1160,13 +1199,14 @@ public ComputeProgram GetComputeProgram( uint dimensionY, uint dimensionZ) { - var program = ResolveComputeProgram(compute, dispatchInitiator, dimensionX, dimensionY, dimensionZ, out var source, out var systemRegisters, out var decoded); + var program = ResolveComputeProgram(compute, dispatchInitiator, dimensionX, dimensionY, dimensionZ, gpuThreadCounts: false, out var source, + out var systemRegisters, out var decoded); var kernel = decoded is not null && program.Available && !program.Consumed ? KernelFor(decoded) : null; return WithPrediction(program, kernel, source, systemRegisters, compute, dimensionX, dimensionY, dimensionZ, indirect: false); } private ComputeProgram ResolveComputeProgram(ComputeStageRegisters compute, uint dispatchInitiator, uint dimensionX, uint dimensionY, uint dimensionZ, - out ShaderSource? resolvedSource, out Gen5ComputeSystemRegisters resolvedSystemRegisters, out Gen5ShaderProgram? decoded) + bool gpuThreadCounts, out ShaderSource? resolvedSource, out Gen5ComputeSystemRegisters resolvedSystemRegisters, out Gen5ShaderProgram? decoded) { using var profileScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramPreparation); var userData = UserData(compute.UserScalars, compute.UserScalarCount, probeWrittenRegisters: false, compute.Address, "compute").ToArray(); @@ -1193,7 +1233,9 @@ private ComputeProgram ResolveComputeProgram(ComputeStageRegisters compute, uint if (usesRayTracing) return new ComputeProgram { Available = false }; } } - var input = ComputeStageInputResolver.Resolve(compute, source.Registered, dispatchInitiator, !_host.ComputeWave64Supported, dimensionX, dimensionY, dimensionZ); + var input = ComputeStageInputResolver.Resolve(compute, source.Registered, dispatchInitiator, !_host.ComputeWave64Supported, dimensionX, dimensionY, dimensionZ, + gpuThreadCounts); + var dispatch = CountedDispatch(input, systemRegisters, dimensionX, dimensionY, dimensionZ, gpuThreadCounts); if (source.Registered.Frontend is { } frontend && frontend.TryResolveImageCopy(_context, source.Registered, source.UserData, input, systemRegisters, dimensionX, dimensionY, dimensionZ, out var copySource, out var copyDestination)) @@ -1201,19 +1243,20 @@ private ComputeProgram ResolveComputeProgram(ComputeStageRegisters compute, uint return new ComputeProgram { Input = input, - ImageCopy = new(copySource, copyDestination, () => CompileComputeProgram(source, input, systemRegisters)), + ImageCopy = new(copySource, copyDestination, () => CompileComputeProgram(source, input, systemRegisters, dispatch)), }; } - return CompileComputeProgram(source, input, systemRegisters); + return CompileComputeProgram(source, input, systemRegisters, dispatch); } - private ComputeProgram CompileComputeProgram(ShaderSource source, ComputeInputInfo input, Gen5ComputeSystemRegisters systemRegisters) + private ComputeProgram CompileComputeProgram(ShaderSource source, ComputeInputInfo input, Gen5ComputeSystemRegisters systemRegisters, + DispatchBufferFootprint.Dispatch? dispatch) { using var profileScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramPreparation); - var pushDataCursor = 0u; + var pushDataCursor = ComputePushDataCursor(input); if (!TryPrepareProgram( source, - new StageCompileOptions { ComputeInfo = input, ComputeSystemRegisters = systemRegisters }, + new StageCompileOptions { ComputeInfo = input, ComputeSystemRegisters = systemRegisters, ComputeDispatch = dispatch }, ref pushDataCursor, out var handle, out var stage)) @@ -1225,6 +1268,18 @@ private ComputeProgram CompileComputeProgram(ShaderSource source, ComputeInputIn return new ComputeProgram { Program = handle, Input = input }; } + // Thread limits the GPU writes need shader data in a buffer: a cursor at the end of the push range keeps it out. + private static uint ComputePushDataCursor(ComputeInputInfo input) => input.IndirectThreadCounts ? PushData.DwordCount : 0u; + + // The dispatch whose GPU-loaded record counts a footprint proof bounds (DeviceRecordCountPlan); none when the thread + // counts are in GPU memory or the initiator counts threads. + private static DispatchBufferFootprint.Dispatch? CountedDispatch(ComputeInputInfo input, Gen5ComputeSystemRegisters systemRegisters, + uint dimensionX, uint dimensionY, uint dimensionZ, bool gpuThreadCounts) => + DeviceRecordCountPlan.Enabled && !gpuThreadCounts && !input.DispatchThreadDimensions + ? new(dimensionX, dimensionY, dimensionZ, Math.Max(input.ThreadsX, 1), Math.Max(input.ThreadsY, 1), Math.Max(input.ThreadsZ, 1), + input.WaveSize, input.ThreadIdCount, systemRegisters) + : null; + private bool TryPrepareProgram(ShaderSource source, StageCompileOptions options, ref uint pushDataCursor, out ShaderProgram program, out ShaderStageResources stage) { @@ -1300,6 +1355,41 @@ public PipelineHandle CreateGraphicsPipeline( ShaderProgram vertexProgram, ShaderProgram pixelProgram) { + // A draw waits for a compile the host runs off this thread, outside the cache's lock: programs and pipelines of + // other draws resolve meanwhile. + PipelineHandle handle; + while (!TryCreateGraphicsPipeline(colors, in depth, vertexInput, pixelInput, context, in rendering, topology, + primitiveRestartEnabled, disableBlending, vertexProgram, pixelProgram, out handle, out var compiling)) + { + if (compiling is null) + { + Thread.Sleep(1); + continue; + } + + _host.WaitForGraphicsPipeline(compiling); + } + + return handle; + } + + // compiling: the description of the compile the host still runs when this returns false. + private bool TryCreateGraphicsPipeline( + ReadOnlySpan colors, + in DepthAttachmentState depth, + VertexInputInfo vertexInput, + PixelInputInfo? pixelInput, + ContextRegisters context, + in RenderingState rendering, + PrimitiveTopology topology, + bool primitiveRestartEnabled, + bool disableBlending, + ShaderProgram vertexProgram, + ShaderProgram pixelProgram, + out PipelineHandle handle, + out GraphicsPipelineDescription? compiling) + { + compiling = null; using var profileScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.PipelineCreation); // The lookup fills objects this thread reuses for every draw; only a new pipeline gets its own. var lookup = _graphicsLookup ??= new GraphicsPipelineKey @@ -1316,24 +1406,38 @@ public PipelineHandle CreateGraphicsPipeline( lookup.VertexProgramId = vertexProgram.Id; lookup.PixelProgramId = pixelInput is not null ? pixelProgram.Id : 0; lookup.Tessellation = vertexInput.Tessellation; - if (_graphicsPipelines.TryGetValue(lookup, out var known)) + if (_graphicsPipelines.TryGetValue(lookup, out handle)) { - return known; + return true; } - var description = BuildGraphicsDescription( - colors, in depth, vertexInput, pixelInput, context, in rendering, topology, primitiveRestartEnabled, disableBlending, - vertexProgram, pixelProgram, _host.NoAttachmentSampleCounts); - var key = KeyOf(description); profileScope.SwitchPhase(RenderPhaseProfile.Phase.PipelineSharedGateWait); lock (_pipelineGate) { profileScope.SwitchPhase(RenderPhaseProfile.Phase.PipelineCreation); - if (_graphicsPipelines.TryGetValue(key, out var cached)) + if (_graphicsPipelines.TryGetValue(lookup, out handle)) { - return cached; + return true; } + // A pipeline the host is still compiling is asked for with the description that started its compile. + if (_pendingGraphicsPipelines.TryGetValue(lookup, out var pending)) + { + if (!_host.TryCreateGraphicsPipeline(pending.Description, out handle)) + { + compiling = pending.Description; + return false; + } + + _pendingGraphicsPipelines.Remove(pending.Key); + AddGraphicsPipeline(pending.Key, pending.Description, handle); + return true; + } + + var description = BuildGraphicsDescription( + colors, in depth, vertexInput, pixelInput, context, in rendering, topology, primitiveRestartEnabled, disableBlending, + vertexProgram, pixelProgram, _host.NoAttachmentSampleCounts); + var key = KeyOf(description); if (RenderTrace.Enabled && RenderTrace.Pipeline()) { RenderTrace.Write( @@ -1342,21 +1446,29 @@ public PipelineHandle CreateGraphicsPipeline( } - var created = _host.CreateGraphicsPipeline(description); - lock (_pipelineGate) + if (!_host.TryCreateGraphicsPipeline(description, out handle)) { - _graphicsPipelines.TryAdd(key, created); + _pendingGraphicsPipelines.Add(key, (key, description)); + compiling = description; + return false; } - if (_host.ShaderPrewarm is { } prewarm && description.Tessellation is null && - description.VertexStage.Stage == ShaderStageKind.Vertex) - { - prewarm.RecordGraphics(description); - } + AddGraphicsPipeline(key, description, handle); + return true; + } + } - ShaderCacheCounters.CountGraphicsPipeline(); - return created; + // Caller holds _pipelineGate. + private void AddGraphicsPipeline(GraphicsPipelineKey key, GraphicsPipelineDescription description, PipelineHandle handle) + { + _graphicsPipelines.TryAdd(key, handle); + if (_host.ShaderPrewarm is { } prewarm && description.Tessellation is null && + description.VertexStage.Stage == ShaderStageKind.Vertex) + { + prewarm.RecordGraphics(description); } + + ShaderCacheCounters.CountGraphicsPipeline(); } [ThreadStatic] @@ -1659,6 +1771,11 @@ public bool TryCreateComputePipeline(ComputeInputInfo input, ShaderProgram progr return _host.GetComputePipelineCompletion(program); } } + + public bool IsSlowLinkedCompile(ulong hash) => _host.ShaderPrewarm?.IsSlowLinkedCompile(hash) ?? false; + + public void RecordLinkedCompile(ulong hash, bool slow, long milliseconds) => + _host.ShaderPrewarm?.RecordLinkedCompile(hash, slow, milliseconds); } internal sealed class KeptGraphicsPrograms @@ -1689,6 +1806,7 @@ internal sealed class KeptComputeProgram public long Rebinds; public long Registrations; public uint DispatchInitiator; + public bool GpuThreadCounts; public uint DimensionX; public uint DimensionY; public uint DimensionZ; diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.Vertex.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.Vertex.cs new file mode 100644 index 000000000..59df3ee13 --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.Vertex.cs @@ -0,0 +1,444 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Diagnostics; +using System.IO.Hashing; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.Libs.Gpu.Pipelines; + +// A vertex or mesh program a session translated, with what its translation read besides the code: the fields its +// static key (StageStaticKey) holds, without vertex buffer addresses and record counts. A later build's prewarm translates +// it again and compiles its pre-rasterization library for each state recorded with it, so the program's first draw links a +// stored library instead of compiling one while the command stream waits. +internal sealed class VertexPrewarmRecord +{ + public bool Mesh { get; init; } + public ulong ContinuationAddressOffset { get; init; } + public required ulong Hash { get; init; } + public required uint CodeSize { get; init; } + public required ulong Address { get; init; } + public required uint UserDataBase { get; init; } + public required uint UserDataCount { get; init; } + public required uint PushDataCursor { get; init; } + public VertexInputInfo? VertexInfo { get; init; } + public MeshDrawConfiguration? MeshInfo { get; init; } + public required int RequiredVertexOutputCount { get; init; } + public uint? MeshOutputLocationMask { get; init; } + public required ResourceSpecialization Specialization { get; init; } + public bool DeviceRecordCounts { get; init; } + + public (ulong Hash, uint CodeSize, ulong Address, ulong ContinuationAddressOffset) CodeKey => + (Hash, CodeSize, Address, ContinuationAddressOffset); +} + +// What a pre-rasterization library takes from the draw besides its program and layout, as Vulkan enum values. The part +// is built without attachment formats (CreatePreRasterizationLibrary), so this is all a prewarm needs to build it again. +internal readonly record struct PreRasterizationState( + int PolygonMode, + int CullMode, + int FrontFace, + bool DepthClampEnable, + bool RasterizerDiscardEnable, + bool DepthClipEnable, + bool NegativeOneToOne); + +// One unit of the graphics prewarm; its identity keys the prewarm's progress, and its first use orders it. +internal abstract record GraphicsPrewarmItem(ulong Identity) +{ + public float FirstUse { get; init; } +} + +internal sealed record PixelPrewarmItem(PixelPrewarmRecord Record, ShaderCodeCapture Code, ulong Identity) + : GraphicsPrewarmItem(Identity); + +internal sealed record PreRasterizationPrewarmItem( + VertexPrewarmRecord Program, ShaderCodeCapture Code, PreRasterizationState State, ulong Identity) + : GraphicsPrewarmItem(Identity); + +internal sealed partial class ShaderPrewarmList +{ + // Vertex prewarm records, in the side file: a vertex or mesh program, and one state its pre-rasterization library + // was compiled with. + private const byte VertexKind = 5; + private const byte PreRasterizationKind = 6; + private const int PreRasterizationPayloadBytes = sizeof(ulong) + 3 * sizeof(int) + 4; + + private readonly HashSet _vertices = []; + private readonly Dictionary _loadedVertices = new(); + private readonly HashSet _preRasterizations = []; + private readonly List<(ulong Program, PreRasterizationState State, ulong Identity)> _loadedPreRasterizations = []; + // The loaded pixel and pre-rasterization records in load order: record kind, index in its list, and the seconds into its + // session at which that session first met it. + private readonly List<(byte Kind, int Index, float FirstUse)> _graphicsOrder = []; + + // A pixel or pre-rasterization record ends with the seconds into its session at which the session first met it (a + // float after the record's own bytes, which alone give its identity). The graphics prewarm runs items in that order + // across sessions, so the records a later session adds go where that session needed them instead of after every + // record of the earlier sessions. + private const int FirstUseBytes = sizeof(float); + private readonly long _opened = Stopwatch.GetTimestamp(); + + // The session's clock, seconds since the list opened (tests replace it). + internal Func? SessionClock { get; set; } + + private float SessionSeconds() => SessionClock?.Invoke() ?? (float)Stopwatch.GetElapsedTime(_opened).TotalSeconds; + + private byte[] WithFirstUse(byte[] record) + { + var payload = new byte[record.Length + FirstUseBytes]; + record.CopyTo(payload, 0); + BitConverter.TryWriteBytes(payload.AsSpan(record.Length), SessionSeconds()); + return payload; + } + + private static (byte[] Record, float FirstUse) SplitFirstUse(byte[] payload) => payload.Length < FirstUseBytes + ? (payload, 0f) + : (payload[..^FirstUseBytes], BitConverter.ToSingle(payload, payload.Length - FirstUseBytes)); + + internal static readonly uint VertexSchemaFingerprint = SchemaFingerprintOf( + typeof(VertexPrewarmRecord), typeof(VertexInputInfo), typeof(VertexAttributeResource), typeof(BufferDescriptorWords), + typeof(ClipSpaceTransform), typeof(MeshDrawConfiguration), typeof(GuestGeometryConfiguration), typeof(MeshExecutionLimits), + typeof(ResourceSpecialization), typeof(BufferSpecialization), typeof(ImageSpecialization), + typeof(BufferCandidateTableSpecialization)); + + public int LoadedPreRasterizationCount => _loadedPreRasterizations.Count; + + // Without the code address, as a pixel record's. + public static ulong Identity(VertexPrewarmRecord record) => XxHash3.HashToUInt64(SerializeVertex(record, address: 0)); + + // The recorded pixel programs and pre-rasterization states by the time into their sessions at which they were first + // met, records of equal times in load order. A state whose program or code is missing is left out. + public IReadOnlyList LoadedGraphicsPrewarm() + { + var items = new List(_graphicsOrder.Count); + foreach (var (kind, index, firstUse) in _graphicsOrder.OrderBy(static item => item.FirstUse)) + { + if (kind == PixelKind) + { + var pixel = _loadedPixels[index]; + if (_loadedCodes.TryGetValue(pixel.CodeKey, out var pixelCode)) + { + items.Add(new PixelPrewarmItem(pixel, pixelCode, Identity(pixel)) { FirstUse = firstUse }); + } + + continue; + } + + var (program, state, identity) = _loadedPreRasterizations[index]; + if (_loadedVertices.TryGetValue(program, out var vertex) && _loadedCodes.TryGetValue(vertex.CodeKey, out var code)) + { + items.Add(new PreRasterizationPrewarmItem(vertex, code, state, identity) { FirstUse = firstUse }); + } + } + + return items; + } + + // Returns the record's identity, under which RecordPreRasterization records the program's states. + public ulong RecordVertex(ShaderCodeCapture code, VertexPrewarmRecord record) + { + var payload = SerializeVertex(record, record.Address); + var identity = Identity(record); + lock (_gate) + { + if (!_failed && _vertices.Add(identity)) + { + if (_extensionCodes.Add(code.Key)) + { + Append(_extension, CodeKind, SerializeCode(code)); + } + + Append(_extension, VertexKind, payload); + } + } + + return identity; + } + + // program: the identity of the recorded vertex or mesh program (Identity(VertexPrewarmRecord)). + public void RecordPreRasterization(ulong program, PreRasterizationState state) + { + var payload = SerializePreRasterization(program, state); + lock (_gate) + { + if (_failed || !_preRasterizations.Add(XxHash3.HashToUInt64(payload))) + { + return; + } + + Append(_extension, PreRasterizationKind, WithFirstUse(payload)); + } + } + + // TryLoadRecord's vertex kinds; false for any other kind. A record of another schema is skipped, not refused. + private bool TryLoadGraphicsRecord(byte kind, byte[] payload) + { + switch (kind) + { + case VertexKind: + if (TryDeserializeVertex(payload) is { } vertex && _vertices.Add(Identity(vertex))) + { + _loadedVertices[Identity(vertex)] = vertex; + } + + return true; + + case PreRasterizationKind: + { + var (state, firstUse) = SplitFirstUse(payload); + if (state.Length == PreRasterizationPayloadBytes && _preRasterizations.Add(XxHash3.HashToUInt64(state))) + { + _loadedPreRasterizations.Add((BitConverter.ToUInt64(state, 0), DeserializePreRasterization(state), + XxHash3.HashToUInt64(state))); + _graphicsOrder.Add((PreRasterizationKind, _loadedPreRasterizations.Count - 1, firstUse)); + } + + return true; + } + + default: + return false; + } + } + + // address: the record's code address, or 0 for its identity. + private static byte[] SerializeVertex(VertexPrewarmRecord record, ulong address) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + writer.Write(VertexSchemaFingerprint); + writer.Write(record.Mesh); + writer.Write(record.Hash); + writer.Write(record.CodeSize); + writer.Write(address); + writer.Write(record.ContinuationAddressOffset); + writer.Write(record.UserDataBase); + writer.Write(record.UserDataCount); + writer.Write(record.PushDataCursor); + writer.Write(record.RequiredVertexOutputCount); + writer.Write(record.MeshOutputLocationMask.HasValue); + writer.Write(record.MeshOutputLocationMask.GetValueOrDefault()); + if (record.Mesh) + { + var mesh = record.MeshInfo ?? throw new ArgumentException("A mesh prewarm record has no mesh configuration."); + var geometry = mesh.Geometry; + writer.Write(geometry.ThreadsPerGroup); + writer.Write(geometry.InputTriangleStrip); + writer.Write(geometry.InputPointList); + writer.Write(geometry.InputLineList); + writer.Write(geometry.InputPrimitiveCountPerWorkgroup); + writer.Write(geometry.InputVertexCountPerWorkgroup); + writer.Write(geometry.OutputVertexCapacity); + writer.Write(geometry.OutputPrimitiveCapacity); + writer.Write(geometry.ProvokingVertex); + writer.Write(geometry.WaveSize); + writer.Write(geometry.IeeeMode); + writer.Write(geometry.ScratchDwords); + writer.Write(geometry.LocalDataShareDwords); + writer.Write(geometry.PositionExportControl); + WriteClipSpace(writer, geometry.ClipSpace); + writer.Write(geometry.TaskLaunched); + writer.Write(mesh.Execution.DeviceSubgroupLaneCount); + writer.Write(mesh.Execution.MaxGroupCountX); + writer.Write(mesh.Execution.MaxGroupCountY); + writer.Write(mesh.Execution.MaxGroupTotalCount); + } + else + { + var info = record.VertexInfo ?? throw new ArgumentException("A vertex prewarm record has no vertex input info."); + writer.Write(info.FetchEmbedded); + writer.Write(info.FetchAttributeRegister); + writer.Write(info.FetchBufferRegister); + writer.Write(info.IeeeMode); + writer.Write(info.ScratchDwords); + writer.Write(info.PositionExportControl); + WriteClipSpace(writer, info.ClipSpace); + writer.Write(info.Attributes.Length); + foreach (var attribute in info.Attributes) + { + // The translation reads the descriptor's format, selectors and stride, not its base or record count. + writer.Write(attribute.Descriptor.Word1 & 0xFFFF_0000u); + writer.Write(attribute.Descriptor.Word3); + writer.Write(attribute.RegisterStart); + writer.Write(attribute.RegisterCount); + writer.Write(attribute.AttributeId); + writer.Write(attribute.FetchIndex); + writer.Write(attribute.BufferIndex); + writer.Write(attribute.OffsetBytes); + } + } + + WriteSpecialization(writer, record.Specialization); + writer.Write(record.DeviceRecordCounts); + // The user data register of the draw's start instance, last and only when the program reads one, so a record + // without one keeps its bytes and identity. + if (!record.Mesh && record.VertexInfo is { StartInstanceUserData: not -1 } startInstanceInfo) + { + writer.Write(startInstanceInfo.StartInstanceUserData); + } + + writer.Flush(); + return stream.ToArray(); + } + + // Null for a record of another vertex schema or a damaged one. + private static VertexPrewarmRecord? TryDeserializeVertex(byte[] payload) + { + try + { + using var reader = new BinaryReader(new MemoryStream(payload)); + if (reader.ReadUInt32() != VertexSchemaFingerprint) + { + return null; + } + + var mesh = reader.ReadBoolean(); + var hash = reader.ReadUInt64(); + var codeSize = reader.ReadUInt32(); + var address = reader.ReadUInt64(); + var continuationAddressOffset = reader.ReadUInt64(); + var userDataBase = reader.ReadUInt32(); + var userDataCount = reader.ReadUInt32(); + var pushDataCursor = reader.ReadUInt32(); + var requiredOutputCount = reader.ReadInt32(); + var hasOutputMask = reader.ReadBoolean(); + var outputMask = reader.ReadUInt32(); + VertexInputInfo? vertexInfo = null; + MeshDrawConfiguration? meshInfo = null; + // Member initializers run in order, so the reads below follow the written layout. + if (mesh) + { + var geometry = new GuestGeometryConfiguration + { + ThreadsPerGroup = reader.ReadUInt32(), + InputTriangleStrip = reader.ReadBoolean(), + InputPointList = reader.ReadBoolean(), + InputLineList = reader.ReadBoolean(), + InputPrimitiveCountPerWorkgroup = reader.ReadUInt32(), + InputVertexCountPerWorkgroup = reader.ReadUInt32(), + OutputVertexCapacity = reader.ReadUInt32(), + OutputPrimitiveCapacity = reader.ReadUInt32(), + ProvokingVertex = reader.ReadUInt32(), + WaveSize = reader.ReadUInt32(), + IeeeMode = reader.ReadBoolean(), + ScratchDwords = reader.ReadUInt32(), + LocalDataShareDwords = reader.ReadUInt32(), + PositionExportControl = reader.ReadUInt32(), + ClipSpace = ReadClipSpace(reader), + TaskLaunched = reader.ReadBoolean(), + }; + meshInfo = new MeshDrawConfiguration + { + Geometry = geometry, + Execution = new MeshExecutionLimits + { + DeviceSubgroupLaneCount = reader.ReadUInt32(), + MaxGroupCountX = reader.ReadUInt32(), + MaxGroupCountY = reader.ReadUInt32(), + MaxGroupTotalCount = reader.ReadUInt32(), + }, + }; + } + else + { + var fetchEmbedded = reader.ReadBoolean(); + var fetchAttributeRegister = reader.ReadInt32(); + var fetchBufferRegister = reader.ReadInt32(); + var ieeeMode = reader.ReadBoolean(); + var scratchDwords = reader.ReadUInt32(); + var positionExportControl = reader.ReadUInt32(); + var clipSpace = ReadClipSpace(reader); + var attributes = new VertexAttributeResource[CheckedCount(reader.ReadInt32(), payload.Length)]; + for (var index = 0; index < attributes.Length; index++) + { + var word1 = reader.ReadUInt32(); + var word3 = reader.ReadUInt32(); + attributes[index] = new VertexAttributeResource(new BufferDescriptorWords(0, word1, 0, word3), + reader.ReadInt32(), reader.ReadInt32(), reader.ReadInt32(), reader.ReadUInt32(), reader.ReadInt32(), + reader.ReadUInt32()); + } + + vertexInfo = new VertexInputInfo + { + Attributes = attributes, + FetchEmbedded = fetchEmbedded, + FetchAttributeRegister = fetchAttributeRegister, + FetchBufferRegister = fetchBufferRegister, + IeeeMode = ieeeMode, + ScratchDwords = scratchDwords, + PositionExportControl = positionExportControl, + ClipSpace = clipSpace, + }; + } + + var specialization = ReadSpecialization(reader, payload.Length); + var deviceRecordCounts = reader.ReadBoolean(); + if (vertexInfo is not null && reader.BaseStream.Length - reader.BaseStream.Position == sizeof(int)) + { + vertexInfo.StartInstanceUserData = reader.ReadInt32(); + } + + if (reader.BaseStream.Position != reader.BaseStream.Length) + { + return null; + } + + return new VertexPrewarmRecord + { + Mesh = mesh, + Hash = hash, + CodeSize = codeSize, + Address = address, + ContinuationAddressOffset = continuationAddressOffset, + UserDataBase = userDataBase, + UserDataCount = userDataCount, + PushDataCursor = pushDataCursor, + VertexInfo = vertexInfo, + MeshInfo = meshInfo, + RequiredVertexOutputCount = requiredOutputCount, + MeshOutputLocationMask = hasOutputMask ? outputMask : null, + Specialization = specialization, + DeviceRecordCounts = deviceRecordCounts, + }; + } + catch (Exception exception) when (exception is EndOfStreamException or ArgumentException or IOException) + { + return null; + } + } + + private static void WriteClipSpace(BinaryWriter writer, ClipSpaceTransform clipSpace) + { + writer.Write(clipSpace.Enabled); + writer.Write(clipSpace.ScaleX); + writer.Write(clipSpace.ScaleY); + writer.Write(clipSpace.OffsetX); + writer.Write(clipSpace.OffsetY); + writer.Write(clipSpace.HalfExtentX); + writer.Write(clipSpace.HalfExtentY); + } + + private static ClipSpaceTransform ReadClipSpace(BinaryReader reader) => new( + reader.ReadBoolean(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), + reader.ReadSingle(), reader.ReadSingle()); + + private static byte[] SerializePreRasterization(ulong program, PreRasterizationState state) + { + var payload = new byte[PreRasterizationPayloadBytes]; + BitConverter.TryWriteBytes(payload, program); + BitConverter.TryWriteBytes(payload.AsSpan(8), state.PolygonMode); + BitConverter.TryWriteBytes(payload.AsSpan(12), state.CullMode); + BitConverter.TryWriteBytes(payload.AsSpan(16), state.FrontFace); + payload[20] = state.DepthClampEnable ? (byte)1 : (byte)0; + payload[21] = state.RasterizerDiscardEnable ? (byte)1 : (byte)0; + payload[22] = state.DepthClipEnable ? (byte)1 : (byte)0; + payload[23] = state.NegativeOneToOne ? (byte)1 : (byte)0; + return payload; + } + + private static PreRasterizationState DeserializePreRasterization(byte[] payload) => new( + BitConverter.ToInt32(payload, 8), BitConverter.ToInt32(payload, 12), BitConverter.ToInt32(payload, 16), + payload[20] != 0, payload[21] != 0, payload[22] != 0, payload[23] != 0); +} diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.cs index cade0f3fa..72389bb8e 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.cs @@ -1,6 +1,7 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using System.Collections.Concurrent; using System.Globalization; using System.IO.Hashing; using System.Security.Cryptography; @@ -141,6 +142,31 @@ internal sealed class ComputePrewarmRecord public required ComputeInputInfo Info { get; init; } public Gen5ComputeSystemRegisters? SystemRegisters { get; init; } public required ResourceSpecialization Specialization { get; init; } + public LinkedShaderPrewarm? Linked { get; init; } + public bool DeviceRecordCounts { get; init; } + + public (ulong Hash, uint CodeSize, ulong Address, ulong ContinuationAddressOffset) CodeKey => + (Hash, CodeSize, Address, ContinuationAddressOffset); +} + +// A pixel program a session translated, with what its translation read besides the code. A later build's prewarm +// translates it again and compiles its pixel library, so the program's first draw links a stored library instead of +// compiling one while the command stream waits. +internal sealed class PixelPrewarmRecord +{ + public ulong ContinuationAddressOffset { get; init; } + public required ulong Hash { get; init; } + public required uint CodeSize { get; init; } + public required ulong Address { get; init; } + public required uint UserDataBase { get; init; } + public required uint UserDataCount { get; init; } + public required uint PushDataCursor { get; init; } + public required PixelInputInfo Info { get; init; } + public required Gen5PixelOutputBinding[] Outputs { get; init; } + public required uint InputEnable { get; init; } + public required uint InputAddress { get; init; } + public required ResourceSpecialization Specialization { get; init; } + public bool DeviceRecordCounts { get; init; } public (ulong Hash, uint CodeSize, ulong Address, ulong ContinuationAddressOffset) CodeKey => (Hash, CodeSize, Address, ContinuationAddressOffset); @@ -171,7 +197,10 @@ internal sealed class GraphicsPrewarmRecord internal sealed record PrewarmStage(ulong Identity, StagePrewarmRecord Record, ShaderCodeCapture Code); -internal sealed record GraphicsPrewarmItem(ulong Identity, GraphicsPrewarmRecord Record, PrewarmStage Vertex, PrewarmStage? Pixel); +// A whole graphics pipeline a session created, with the stage programs it links; the prewarm builds it again on a +// device that creates whole pipelines (the graphics prewarm otherwise builds pipeline library parts). +internal sealed record PipelinePrewarmItem(GraphicsPrewarmRecord Record, PrewarmStage Vertex, PrewarmStage? Pixel, ulong Identity) + : GraphicsPrewarmItem(Identity); internal sealed class PrewarmRecordFile : IDisposable { @@ -293,53 +322,107 @@ private void Load(Func loadRecord) } } -internal sealed class ShaderPrewarmList : IDisposable +internal sealed partial class ShaderPrewarmList : IDisposable { public const string FileName = "shader-prewarm.bin"; - public const string GraphicsFileName = "shader-prewarm-graphics.bin"; public const string StampFileName = "shader-prewarm.stamp"; public const string ProgressFileName = "shader-prewarm.progress"; + // Records a build before them cannot read go to a side file such a build never opens: a build stops reading the main + // list at the first record kind it does not know and cuts the file there, losing every record written after it. + public const string ExtensionFileName = "shader-prewarm-ext.bin"; + // The side file's prewarms keep their own progress: the compute prewarm clears its progress when it cannot trust it. + public const string ExtensionProgressFileName = "shader-prewarm-ext.progress"; + // Whole graphics pipelines (RecordGraphics) and the stage programs they link (RecordStage), in a file of their own. + public const string GraphicsFileName = "shader-prewarm-graphics.bin"; private const uint Magic = 0x57504553; - private const uint GraphicsMagic = 0x47504553; - private const uint FormatVersion = 4; - private const uint GraphicsFormatVersion = 1; + private const uint FormatVersion = 6; private const byte CodeKind = 1; private const byte ComputeKind = 2; + // Pixel prewarm records, in the side file (a main list written before the side file existed can hold some; they + // still load). + private const byte PixelKind = 3; + // What a session learned about a linked program's module compile (side file). + private const byte LinkedCompileKind = 4; + // When a session first used a compute record (its identity, then the seconds into the session), in the side file, + // since the main list's records carry no time. A session writes one for each record it uses unless a session used + // that record sooner, and the prewarm runs records by their earliest use, so a record goes where a session needed + // it rather than where the session that recorded it first met it. Records no session timed, and linked records, + // whose permutations the prewarm takes newest first in list order (ShaderPrewarmQueue), keep list order after the + // timed ones. + private const byte ComputeFirstUseKind = 7; + // How long a prewarm compile of a compute record took (its identity, then the seconds), in the side file, kept when + // it took a second or more and longer than any compile recorded before. The prewarm runs each record by the time it + // must start to be ready at its earliest use, first use minus compile time, so a long compile starts that much + // sooner. + private const byte ComputeCostKind = 8; + private const float MinimumComputeCostSeconds = 1; + // Kinds 7 and 8: a record identity, then seconds. + private const int ComputeSecondsPayloadBytes = sizeof(ulong) + sizeof(float); + // Kinds 5 and 6 (vertex prewarm records): ShaderPrewarmList.Vertex.cs. + private const int LinkedCompilePayloadBytes = sizeof(ulong) + 1 + sizeof(long); + private const uint ExtensionMagic = 0x58504553; + // 2: graphics programs bind their images one per slot when the layout fits, so graphics records of version 1 would + // translate differently. 3: pixel and pre-rasterization records end with the seconds into their session at which it + // first met them. A side file of another version starts empty. + private const uint ExtensionFormatVersion = 3; + private const int ExtensionHeaderBytes = 2 * sizeof(uint); + private const int RecordHeaderBytes = sizeof(uint) + sizeof(ulong); + // The pipeline file's kinds besides CodeKind, a numbering of its own. 2: stage records hold their resource + // specialization in the layout of the compute records (WriteSpecialization) and whether they read device record counts. + private const uint GraphicsMagic = 0x47504553; + private const uint GraphicsFormatVersion = 2; private const byte StageKind = 3; private const byte GraphicsKind = 4; private readonly object _gate = new(); - private PrewarmRecordFile? _computeFile; + private readonly FileStream _file; + private readonly FileStream _extension; private PrewarmRecordFile? _graphicsFile; private readonly string _stampPath; private readonly string _progressPath; + private readonly string _extensionProgressPath; private readonly object _progressGate = new(); private readonly HashSet<(ulong Hash, uint CodeSize, ulong Address, ulong ContinuationAddressOffset)> _codes = []; + private readonly HashSet<(ulong Hash, uint CodeSize, ulong Address, ulong ContinuationAddressOffset)> _extensionCodes = []; + // The last recorded outcome of each linked program's module compile (true: it compiled for minutes). + private readonly ConcurrentDictionary _linkedCompiles = new(); private readonly HashSet _computes = []; + private readonly Dictionary _computeFirstUses = new(); + private readonly Dictionary _computeCosts = new(); private readonly Dictionary<(ulong Hash, uint CodeSize, ulong Address, ulong ContinuationAddressOffset), ShaderCodeCapture> _loadedCodes = new(); private readonly List _loadedComputes = []; + private readonly HashSet _pixels = []; + private readonly List _loadedPixels = []; private readonly HashSet<(ulong Hash, uint CodeSize, ulong Address, ulong ContinuationAddressOffset)> _graphicsCodes = []; private readonly HashSet _stages = []; private readonly HashSet _graphics = []; private readonly Dictionary<(ulong Hash, uint CodeSize, ulong Address, ulong ContinuationAddressOffset), ShaderCodeCapture> _loadedGraphicsCodes = new(); private readonly Dictionary _loadedStages = new(); private readonly List<(ulong Identity, GraphicsPrewarmRecord Record)> _loadedGraphics = []; - private readonly System.Collections.Concurrent.ConcurrentDictionary _stageByModule = new(); + private readonly ConcurrentDictionary _stageByModule = new(); private bool _failed; - private ShaderPrewarmList(string stampPath, string progressPath) + private ShaderPrewarmList(FileStream file, FileStream extension, string stampPath, string progressPath, string extensionProgressPath) { + _file = file; + _extension = extension; + _extensionProgressPath = extensionProgressPath; _stampPath = stampPath; _progressPath = progressPath; } + private string _loadedCoverage = string.Empty; + public int LoadedComputeCount => _loadedComputes.Count; - public int LoadedGraphicsCount => _loadedGraphics.Count; + public int LoadedPixelCount => _loadedPixels.Count; + public int LoadedPipelineCount => _loadedGraphics.Count; public string StampPath => _stampPath; - public string CoverageStamp(string stamp) => - $"{stamp}|coverage-v1|{_computeFile?.Coverage}|graphics-v1|{_graphicsFile?.Coverage}"; + // The main list's coverage; with pipelines also the pipeline file's, for a prewarm that builds whole pipelines. + public string CoverageStamp(string stamp, bool pipelines = false) => pipelines + ? $"{stamp}|coverage-v1|{_loadedCoverage}|graphics-v1|{_graphicsFile?.Coverage}" + : $"{stamp}|coverage-v1|{_loadedCoverage}"; public static string CacheStamp(string coverageStamp, ReadOnlySpan cache) => $"{coverageStamp}|cache-v1|{Convert.ToHexString(SHA256.HashData(cache))}"; @@ -349,14 +432,37 @@ public static string CacheStamp(string coverageStamp, ReadOnlySpan cache) try { Directory.CreateDirectory(directory); - var list = new ShaderPrewarmList(Path.Combine(directory, StampFileName), Path.Combine(directory, ProgressFileName)); - list._computeFile = PrewarmRecordFile.Open( - Path.Combine(directory, FileName), Magic, FormatVersion, SchemaFingerprint, list.TryLoadRecord); + var path = Path.Combine(directory, FileName); + var file = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read); + FileStream extension; + try + { + extension = new FileStream(Path.Combine(directory, ExtensionFileName), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read); + } + catch + { + file.Dispose(); + throw; + } + + var list = new ShaderPrewarmList(file, extension, Path.Combine(directory, StampFileName), Path.Combine(directory, ProgressFileName), + Path.Combine(directory, ExtensionProgressFileName)); + try + { + list.Load(); + } + catch + { + file.Dispose(); + extension.Dispose(); + throw; + } + try { list._graphicsFile = PrewarmRecordFile.Open( Path.Combine(directory, GraphicsFileName), GraphicsMagic, GraphicsFormatVersion, GraphicsSchemaFingerprint, - list.TryLoadGraphicsRecord); + list.TryLoadPipelineRecord); } catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) { @@ -372,21 +478,46 @@ public static string CacheStamp(string coverageStamp, ReadOnlySpan cache) } } - public IReadOnlyList<(ComputePrewarmRecord Record, ShaderCodeCapture Code)> LoadedComputes() + // The recorded compute programs in prewarm order (LoadedComputeStarts). + public IReadOnlyList<(ComputePrewarmRecord Record, ShaderCodeCapture Code)> LoadedComputes() => + [.. LoadedComputeStarts().Select(static item => (item.Record, item.Code))]; + + // The recorded compute programs by the time each must start to be ready at its earliest use (the recorded first use + // minus the recorded compile time; infinite for an untimed record), then the untimed ones, each group in list + // order. Sessions record first uses and the prewarm its compile times while the list is open, so the times are read + // under the gate; the loaded records and codes are written only while the file loads. + public IReadOnlyList<(ComputePrewarmRecord Record, ShaderCodeCapture Code, float StartBy)> LoadedComputeStarts() { - var result = new List<(ComputePrewarmRecord, ShaderCodeCapture)>(_loadedComputes.Count); - foreach (var record in _loadedComputes) + var identities = _loadedComputes.Select(static record => Identity(record)).ToArray(); + var startBy = new float[identities.Length]; + lock (_gate) + { + for (var index = 0; index < identities.Length; index++) + { + startBy[index] = StartBy(identities[index]); + } + } + + var result = new List<(ComputePrewarmRecord, ShaderCodeCapture, float)>(identities.Length); + foreach (var index in Enumerable.Range(0, identities.Length).OrderBy(index => startBy[index])) { + var record = _loadedComputes[index]; if (_loadedCodes.TryGetValue(record.CodeKey, out var code)) { - result.Add((record, code)); + result.Add((record, code, startBy[index])); } } return result; } - public IReadOnlyList LoadedGraphics() + private float StartBy(ulong identity) => + _computeFirstUses.TryGetValue(identity, out var firstUse) + ? firstUse - (_computeCosts.TryGetValue(identity, out var cost) ? cost : 0) + : float.PositiveInfinity; + + // The recorded whole pipelines whose stage programs and code loaded, in the order sessions created them. + public IReadOnlyList LoadedPipelines() { var stages = new Dictionary(); PrewarmStage? Stage(ulong identity) @@ -403,13 +534,13 @@ public IReadOnlyList LoadedGraphics() return stage; } - var result = new List(_loadedGraphics.Count); + var result = new List(_loadedGraphics.Count); foreach (var (identity, record) in _loadedGraphics) { var pixel = record.PixelStage == 0 ? null : Stage(record.PixelStage); if (Stage(record.VertexStage) is { } vertex && (record.PixelStage == 0 || pixel is not null)) { - result.Add(new GraphicsPrewarmItem(identity, record, vertex, pixel)); + result.Add(new PipelinePrewarmItem(record, vertex, pixel, identity)); } } @@ -445,24 +576,34 @@ public static void WriteStamp(string path, string stamp) } } + // The global cache stamp cannot certify a separate caller cache or pipeline binary file. + public bool HasLinkedComputes => _loadedComputes.Any(record => record.Linked is not null); + public static ulong Identity(ComputePrewarmRecord record) => XxHash3.HashToUInt64(SerializeCompute(record)); - public HashSet ReadProgress(string stamp) + // A graphics program loaded at another address translates the same (the program cache keys omit the address), so + // its record's identity leaves the address out and a session that meets the program elsewhere records nothing new. + public static ulong Identity(PixelPrewarmRecord record) => XxHash3.HashToUInt64(SerializePixel(record, address: 0)); + + private string ProgressPath(bool extension) => extension ? _extensionProgressPath : _progressPath; + + public HashSet ReadProgress(string stamp, bool extension = false) { var completed = new HashSet(); + var path = ProgressPath(extension); lock (_progressGate) { try { - if (!File.Exists(_progressPath)) + if (!File.Exists(path)) { return completed; } - var lines = File.ReadAllLines(_progressPath); + var lines = File.ReadAllLines(path); if (lines.Length == 0 || lines[0] != ProgressKey(stamp)) { - File.Delete(_progressPath); + File.Delete(path); return completed; } @@ -483,19 +624,20 @@ public HashSet ReadProgress(string stamp) return completed; } - public void AppendProgress(string stamp, IReadOnlyCollection identities) + public void AppendProgress(string stamp, IReadOnlyCollection identities, bool extension = false) { if (identities.Count == 0) { return; } + var path = ProgressPath(extension); lock (_progressGate) { try { var lines = new List(identities.Count + 1); - if (!File.Exists(_progressPath)) + if (!File.Exists(path)) { lines.Add(ProgressKey(stamp)); } @@ -505,7 +647,7 @@ public void AppendProgress(string stamp, IReadOnlyCollection identities) lines.Add(identity.ToString("X16", CultureInfo.InvariantCulture)); } - File.AppendAllLines(_progressPath, lines); + File.AppendAllLines(path, lines); } catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) { @@ -536,19 +678,103 @@ public void RecordCompute(ShaderCodeCapture code, ComputePrewarmRecord record) { var payload = SerializeCompute(record); var identity = XxHash3.HashToUInt64(payload); + var seconds = SessionSeconds(); lock (_gate) { - if (_failed || _computeFile is not { } file || !_computes.Add(identity)) + if (_failed) { return; } - if (_codes.Add(code.Key)) + if (_computes.Add(identity)) { - file.Append(CodeKind, SerializeCode(code)); + if (_codes.Add(code.Key)) + { + Append(CodeKind, SerializeCode(code)); + } + + Append(ComputeKind, payload); + } + + if (record.Linked is null && (!_computeFirstUses.TryGetValue(identity, out var known) || seconds < known)) + { + _computeFirstUses[identity] = seconds; + Append(_extension, ComputeFirstUseKind, IdentitySeconds(identity, seconds)); + } + } + } + + // A prewarm compile of the record took this long. + public void RecordComputeCost(ComputePrewarmRecord record, float seconds) + { + if (seconds < MinimumComputeCostSeconds) + { + return; + } + + var identity = Identity(record); + lock (_gate) + { + if (_failed || (_computeCosts.TryGetValue(identity, out var known) && known >= seconds)) + { + return; + } + + _computeCosts[identity] = seconds; + Append(_extension, ComputeCostKind, IdentitySeconds(identity, seconds)); + } + } + + private static byte[] IdentitySeconds(ulong identity, float seconds) + { + var payload = new byte[ComputeSecondsPayloadBytes]; + BitConverter.TryWriteBytes(payload, identity); + BitConverter.TryWriteBytes(payload.AsSpan(sizeof(ulong)), seconds); + return payload; + } + + public void RecordPixel(ShaderCodeCapture code, PixelPrewarmRecord record) + { + var payload = SerializePixel(record, record.Address); + var identity = Identity(record); + lock (_gate) + { + if (_failed || !_pixels.Add(identity)) + { + return; } - file.Append(ComputeKind, payload); + if (_extensionCodes.Add(code.Key)) + { + Append(_extension, CodeKind, SerializeCode(code)); + } + + Append(_extension, PixelKind, WithFirstUse(payload)); + } + } + + // Linked programs whose module a session saw compile for minutes; their dispatches wait only briefly for it. + public bool IsSlowLinkedCompile(ulong hash) => _linkedCompiles.TryGetValue(hash, out var slow) && slow; + + // Records a linked program's compile outcome when it changes what later sessions know: slow when its module was + // still compiling a minute after its first dispatch waited, fast again when a compile of a slow one ended within the + // normal wait. + public void RecordLinkedCompile(ulong hash, bool slow, long milliseconds) + { + lock (_gate) + { + var known = _linkedCompiles.TryGetValue(hash, out var current); + if (_failed || (known ? current == slow : !slow)) + { + return; + } + + _linkedCompiles[hash] = slow; + var payload = new byte[LinkedCompilePayloadBytes]; + BitConverter.TryWriteBytes(payload, hash); + payload[sizeof(ulong)] = slow ? (byte)1 : (byte)0; + BitConverter.TryWriteBytes(payload.AsSpan(sizeof(ulong) + 1), milliseconds); + Append(_extension, LinkedCompileKind, payload); } } @@ -608,12 +834,143 @@ public void Dispose() lock (_gate) { _failed = true; - _computeFile?.Dispose(); + _file.Dispose(); + _extension.Dispose(); _graphicsFile?.Dispose(); } } - private bool TryLoadGraphicsRecord(byte kind, byte[] payload) + private void Append(byte kind, byte[] payload) => Append(_file, kind, payload); + + private void Append(FileStream file, byte kind, byte[] payload) + { + try + { + var record = new byte[RecordHeaderBytes + 1 + payload.Length]; + record[RecordHeaderBytes] = kind; + payload.CopyTo(record, RecordHeaderBytes + 1); + var body = record.AsSpan(RecordHeaderBytes); + BitConverter.TryWriteBytes(record.AsSpan(0, sizeof(uint)), (uint)body.Length); + BitConverter.TryWriteBytes(record.AsSpan(sizeof(uint), sizeof(ulong)), XxHash3.HashToUInt64(body)); + file.Write(record); + file.Flush(); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ObjectDisposedException) + { + _failed = true; + Console.Error.WriteLine($"[LOADER][WARN] Shader prewarm list write failed: {exception.Message}"); + } + } + + private void Load() + { + LoadMain(); + LoadExtension(); + } + + private void LoadMain() + { + var content = new byte[_file.Length]; + _file.Position = 0; + _file.ReadExactly(content); + var validEnd = 0L; + if (content.Length >= 3 * sizeof(uint) && + BitConverter.ToUInt32(content, 0) == Magic && + BitConverter.ToUInt32(content, sizeof(uint)) == FormatVersion && + BitConverter.ToUInt32(content, 2 * sizeof(uint)) == SchemaFingerprint) + { + validEnd = 3 * sizeof(uint); + var offset = (int)validEnd; + while (content.Length - offset >= RecordHeaderBytes + 1) + { + var length = BitConverter.ToUInt32(content, offset); + var checksum = BitConverter.ToUInt64(content, offset + sizeof(uint)); + if (length == 0 || length > content.Length - offset - RecordHeaderBytes) + { + break; + } + + var body = content.AsSpan(offset + RecordHeaderBytes, (int)length); + if (XxHash3.HashToUInt64(body) != checksum || !TryLoadRecord(body[0], body[1..].ToArray(), extension: false)) + { + break; + } + + offset += RecordHeaderBytes + (int)length; + validEnd = offset; + } + } + + _loadedCoverage = Convert.ToHexString(SHA256.HashData(content.AsSpan(0, checked((int)validEnd)))); + if (validEnd == 0) + { + _file.SetLength(0); + _file.Position = 0; + Span header = stackalloc byte[3 * sizeof(uint)]; + BitConverter.TryWriteBytes(header, Magic); + BitConverter.TryWriteBytes(header[sizeof(uint)..], FormatVersion); + BitConverter.TryWriteBytes(header[(2 * sizeof(uint))..], SchemaFingerprint); + _file.Write(header); + _file.Flush(); + return; + } + + _file.SetLength(validEnd); + _file.Position = validEnd; + } + + // The side file: a record this build does not know or cannot read is skipped instead of ending the load, so the records + // after it still load and stay in the file. A torn write still ends the load, and the file is cut there. + private void LoadExtension() + { + var content = new byte[_extension.Length]; + _extension.Position = 0; + _extension.ReadExactly(content); + var validEnd = 0L; + if (content.Length >= ExtensionHeaderBytes && + BitConverter.ToUInt32(content, 0) == ExtensionMagic && + BitConverter.ToUInt32(content, sizeof(uint)) == ExtensionFormatVersion) + { + validEnd = ExtensionHeaderBytes; + var offset = (int)validEnd; + while (content.Length - offset >= RecordHeaderBytes + 1) + { + var length = BitConverter.ToUInt32(content, offset); + var checksum = BitConverter.ToUInt64(content, offset + sizeof(uint)); + if (length == 0 || length > content.Length - offset - RecordHeaderBytes) + { + break; + } + + var body = content.AsSpan(offset + RecordHeaderBytes, (int)length); + if (XxHash3.HashToUInt64(body) != checksum) + { + break; + } + + _ = TryLoadRecord(body[0], body[1..].ToArray(), extension: true); + offset += RecordHeaderBytes + (int)length; + validEnd = offset; + } + } + + if (validEnd == 0) + { + _extension.SetLength(0); + _extension.Position = 0; + Span header = stackalloc byte[ExtensionHeaderBytes]; + BitConverter.TryWriteBytes(header, ExtensionMagic); + BitConverter.TryWriteBytes(header[sizeof(uint)..], ExtensionFormatVersion); + _extension.Write(header); + _extension.Flush(); + return; + } + + _extension.SetLength(validEnd); + _extension.Position = validEnd; + } + + private bool TryLoadRecord(byte kind, byte[] payload, bool extension) { try { @@ -622,35 +979,69 @@ private bool TryLoadGraphicsRecord(byte kind, byte[] payload) case CodeKind: { var code = DeserializeCode(payload); - _graphicsCodes.Add(code.Key); - _loadedGraphicsCodes[code.Key] = code; + (extension ? _extensionCodes : _codes).Add(code.Key); + _loadedCodes[code.Key] = code; return true; } - case StageKind: + case ComputeKind: { - var identity = XxHash3.HashToUInt64(payload); - if (_stages.Add(identity)) + // By the record's identity, not its bytes: records that differ only in a buffer's stride word load + // as one. + var record = DeserializeCompute(payload); + if (_computes.Add(Identity(record))) { - _loadedStages[identity] = DeserializeStage(payload); + _loadedComputes.Add(record); } return true; } - case GraphicsKind: + case PixelKind: { - var identity = XxHash3.HashToUInt64(payload); - if (_graphics.Add(identity)) + // A pixel record of another schema is skipped, not refused, so the records after it still load. The + // pixel records of a main list written before the side file existed have no first use. + var (bytes, firstUse) = extension ? SplitFirstUse(payload) : (payload, 0f); + if (TryDeserializePixel(bytes) is { } pixel && _pixels.Add(Identity(pixel))) { - _loadedGraphics.Add((identity, DeserializeGraphics(payload))); + _loadedPixels.Add(pixel); + _graphicsOrder.Add((PixelKind, _loadedPixels.Count - 1, firstUse)); + } + + return true; + } + + case LinkedCompileKind: + if (payload.Length != LinkedCompilePayloadBytes) + { + return false; + } + + _linkedCompiles[BitConverter.ToUInt64(payload, 0)] = payload[sizeof(ulong)] != 0; + return true; + + case ComputeFirstUseKind: + case ComputeCostKind: + { + if (payload.Length != ComputeSecondsPayloadBytes) + { + return false; + } + + var identity = BitConverter.ToUInt64(payload, 0); + var seconds = BitConverter.ToSingle(payload, sizeof(ulong)); + // The earliest first use, the longest compile. + var times = kind == ComputeFirstUseKind ? _computeFirstUses : _computeCosts; + if (!times.TryGetValue(identity, out var known) || (kind == ComputeFirstUseKind ? seconds < known : seconds > known)) + { + times[identity] = seconds; } return true; } default: - return false; + return TryLoadGraphicsRecord(kind, payload); } } catch (Exception exception) when (exception is EndOfStreamException or ArgumentException or IOException) @@ -659,7 +1050,8 @@ private bool TryLoadGraphicsRecord(byte kind, byte[] payload) } } - private bool TryLoadRecord(byte kind, byte[] payload) + // The pipeline file's records; a record of an unknown kind ends the load there. + private bool TryLoadPipelineRecord(byte kind, byte[] payload) { try { @@ -668,18 +1060,32 @@ private bool TryLoadRecord(byte kind, byte[] payload) case CodeKind: { var code = DeserializeCode(payload); - _codes.Add(code.Key); - _loadedCodes[code.Key] = code; + _graphicsCodes.Add(code.Key); + _loadedGraphicsCodes[code.Key] = code; return true; } - case ComputeKind: - if (_computes.Add(XxHash3.HashToUInt64(payload))) + case StageKind: + { + var identity = XxHash3.HashToUInt64(payload); + if (_stages.Add(identity)) { - _loadedComputes.Add(DeserializeCompute(payload)); + _loadedStages[identity] = DeserializeStage(payload); + } + + return true; + } + + case GraphicsKind: + { + var identity = XxHash3.HashToUInt64(payload); + if (_graphics.Add(identity)) + { + _loadedGraphics.Add((identity, DeserializeGraphics(payload))); } return true; + } default: return false; @@ -691,32 +1097,63 @@ private bool TryLoadRecord(byte kind, byte[] payload) } } - private static readonly uint SchemaFingerprint = ComputeSchemaFingerprint( + internal static readonly uint SchemaFingerprint = ComputeSchemaFingerprint(); + + private static uint ComputeSchemaFingerprint() => SchemaFingerprintOf( typeof(ComputeInputInfo), typeof(Gen5ComputeSystemRegisters), typeof(ResourceSpecialization), - typeof(BufferSpecialization), typeof(ImageSpecialization), typeof(BufferCandidateTableSpecialization)); + typeof(BufferSpecialization), typeof(ImageSpecialization), typeof(BufferCandidateTableSpecialization), + typeof(LinkedShaderPrewarm), typeof(LinkedPrewarmFunction), typeof(LinkedPrewarmSite), typeof(LinkedPrewarmTarget)); + + internal static readonly uint PixelSchemaFingerprint = SchemaFingerprintOf( + typeof(PixelPrewarmRecord), typeof(PixelInputInfo), typeof(Gen5PixelOutputBinding), typeof(Gen5ColorComponentMapping), + typeof(ColorComponentMap), typeof(ResourceSpecialization), typeof(BufferSpecialization), typeof(ImageSpecialization), + typeof(BufferCandidateTableSpecialization)); - private static readonly uint GraphicsSchemaFingerprint = ComputeSchemaFingerprint( + internal static readonly uint GraphicsSchemaFingerprint = SchemaFingerprintOf( typeof(StageCompileOptions), typeof(VertexInputInfo), typeof(VertexInputBuffer), typeof(VertexAttributeResource), typeof(ClipSpaceTransform), typeof(PixelInputInfo), typeof(Gen5PixelOutputBinding), typeof(RegisteredShader), typeof(PipelineRenderingState), typeof(PipelineVertexInputState), typeof(PipelineStaticParameters), typeof(ResourceSpecialization), typeof(BufferSpecialization), typeof(ImageSpecialization), typeof(BufferCandidateTableSpecialization)); - private static uint ComputeSchemaFingerprint(params Type[] types) + private static uint SchemaFingerprintOf(params Type[] types) => + (uint)XxHash3.HashToUInt64(Encoding.UTF8.GetBytes(SchemaText(types))); + + // Each type's public properties in name order, with their types. Types are named by Type.ToString, which qualifies + // generic type arguments by namespace but not by assembly; FullName names each argument's assembly with its version, so + // every release and every runtime version would change the fingerprints and discard the recorded lists. + internal static string SchemaText(params Type[] types) { + var vertexRecord = types.Contains(typeof(VertexPrewarmRecord)); var builder = new StringBuilder(); foreach (var type in types) { - builder.Append(type.FullName).Append('{'); + if (type == typeof(BufferSpecialization)) + { + // Records keep a stride word in front of each buffer's format (written as 0, skipped on load) that the + // specialization has no property for, so the schema lists it with the specialization's properties. + builder.Append(type.ToString()).Append("{System.UInt32 DescriptorFormat;System.UInt32 DescriptorSwizzle;System.UInt32 PackedStride;}"); + continue; + } + + builder.Append(type.ToString()).Append('{'); foreach (var property in type.GetProperties().OrderBy(static property => property.Name, StringComparer.Ordinal)) { - builder.Append(property.PropertyType.FullName).Append(' ').Append(property.Name).Append(';'); + // A vertex record holds neither: tessellated programs are not recorded, and the start instance register + // follows the record as an optional field (SerializeVertex), so the lists recorded before them still load. + if (vertexRecord && type == typeof(VertexInputInfo) && + property.Name is nameof(VertexInputInfo.Tessellation) or nameof(VertexInputInfo.StartInstanceUserData)) + { + continue; + } + + builder.Append(property.PropertyType.ToString()).Append(' ').Append(property.Name).Append(';'); } builder.Append('}'); } - return (uint)XxHash3.HashToUInt64(Encoding.UTF8.GetBytes(builder.ToString())); + return builder.ToString(); } private static byte[] SerializeCode(ShaderCodeCapture code) @@ -822,7 +1259,8 @@ private static byte[] SerializeCompute(ComputePrewarmRecord record) writer.Write(info.ThreadsX); writer.Write(info.ThreadsY); writer.Write(info.ThreadsZ); - writer.Write(info.DispatchThreadDimensions); + // 1 counts threads, 2 counts threads the GPU wrote (an older reader reads either as true). + writer.Write((byte)(info.IndirectThreadCounts ? 2 : info.DispatchThreadDimensions ? 1 : 0)); writer.Write(info.GroupIdX); writer.Write(info.GroupIdY); writer.Write(info.GroupIdZ); @@ -845,17 +1283,90 @@ private static byte[] SerializeCompute(ComputePrewarmRecord record) } WriteSpecialization(writer, record.Specialization); + writer.Write(record.Linked is not null); + record.Linked?.Write(writer); + // Optional extension: old records retain their ordinary resource plan and byte identity. + if (record.DeviceRecordCounts) writer.Write((byte)1); + writer.Flush(); return stream.ToArray(); } + private static ComputePrewarmRecord DeserializeCompute(byte[] payload) + { + using var reader = new BinaryReader(new MemoryStream(payload)); + var hash = reader.ReadUInt64(); + var codeSize = reader.ReadUInt32(); + var address = reader.ReadUInt64(); + var continuationAddressOffset = reader.ReadUInt64(); + var userDataBase = reader.ReadUInt32(); + var userDataCount = reader.ReadUInt32(); + var pushDataCursor = reader.ReadUInt32(); + var threadsX = reader.ReadUInt32(); + var threadsY = reader.ReadUInt32(); + var threadsZ = reader.ReadUInt32(); + var threadDimensions = reader.ReadByte(); + var info = new ComputeInputInfo + { + ThreadsX = threadsX, + ThreadsY = threadsY, + ThreadsZ = threadsZ, + DispatchThreadDimensions = threadDimensions != 0, + IndirectThreadCounts = threadDimensions == 2, + GroupIdX = reader.ReadBoolean(), + GroupIdY = reader.ReadBoolean(), + GroupIdZ = reader.ReadBoolean(), + ThreadIdCount = reader.ReadInt32(), + ThreadGroupSizeEnabled = reader.ReadBoolean(), + WaveSize = reader.ReadUInt32(), + LocalDataShareDwords = reader.ReadUInt32(), + ScratchDwords = reader.ReadUInt32(), + IeeeMode = reader.ReadBoolean(), + NeedsLocalDataShareBarriers = reader.ReadBoolean(), + WorkgroupRegister = reader.ReadInt32(), + }; + + Gen5ComputeSystemRegisters? registers = reader.ReadBoolean() + ? new Gen5ComputeSystemRegisters(ReadOptional(reader), ReadOptional(reader), ReadOptional(reader), ReadOptional(reader)) + : null; + + var specialization = ReadSpecialization(reader, payload.Length); + var linked = reader.ReadBoolean() ? LinkedShaderPrewarm.Read(reader) : null; + var deviceRecordCounts = false; + if (reader.BaseStream.Position + 1 == reader.BaseStream.Length) + { + if (reader.ReadByte() != 1) throw new ArgumentException("Unknown prewarm compute extension."); + deviceRecordCounts = true; + } + if (reader.BaseStream.Position != reader.BaseStream.Length) + throw new ArgumentException("Trailing prewarm compute data."); + + return new ComputePrewarmRecord + { + Hash = hash, + CodeSize = codeSize, + Address = address, + UserDataBase = userDataBase, + ContinuationAddressOffset = continuationAddressOffset, + UserDataCount = userDataCount, + PushDataCursor = pushDataCursor, + Info = info, + SystemRegisters = registers, + Specialization = specialization, + Linked = linked, + DeviceRecordCounts = deviceRecordCounts, + }; + } + private static void WriteSpecialization(BinaryWriter writer, ResourceSpecialization specialization) { writer.Write(specialization.BaseBufferCount); + writer.Write(specialization.StableImageBindings); writer.Write(specialization.Buffers.Count); foreach (var buffer in specialization.Buffers) { - writer.Write(buffer.PackedStride); + // The stride word, written as 0: strides are read at run time, and the word keeps the record layout. + writer.Write(0u); writer.Write(buffer.DescriptorFormat); writer.Write(buffer.DescriptorSwizzle); } @@ -885,16 +1396,22 @@ private static void WriteSpecialization(BinaryWriter writer, ResourceSpecializat writer.Write(table.SearchIterations); } - WriteWords(writer, specialization.ImageDescriptorGroups); - WriteWords(writer, specialization.SamplerDescriptorGroups); + writer.Write(specialization.ImageDescriptorGroups.Count); + foreach (var group in specialization.ImageDescriptorGroups) writer.Write(group); + writer.Write(specialization.SamplerDescriptorGroups.Count); + foreach (var group in specialization.SamplerDescriptorGroups) writer.Write(group); } private static ResourceSpecialization ReadSpecialization(BinaryReader reader, int limit) { - var specialization = new ResourceSpecialization { BaseBufferCount = reader.ReadInt32() }; + var specialization = new ResourceSpecialization + { + BaseBufferCount = reader.ReadInt32(), StableImageBindings = reader.ReadBoolean(), + }; for (var count = CheckedCount(reader.ReadInt32(), limit); count > 0; count--) { - specialization.Buffers.Add(new BufferSpecialization(reader.ReadUInt32(), reader.ReadUInt32(), reader.ReadUInt32())); + _ = reader.ReadUInt32(); + specialization.Buffers.Add(new BufferSpecialization(reader.ReadUInt32(), reader.ReadUInt32())); } for (var count = CheckedCount(reader.ReadInt32(), limit); count > 0; count--) @@ -919,8 +1436,10 @@ private static ResourceSpecialization ReadSpecialization(BinaryReader reader, in reader.ReadUInt32(), reader.ReadUInt32(), reader.ReadUInt32(), reader.ReadUInt32())); } - specialization.ImageDescriptorGroups.AddRange(ReadWords(reader, limit)); - specialization.SamplerDescriptorGroups.AddRange(ReadWords(reader, limit)); + for (var count = CheckedCount(reader.ReadInt32(), limit); count > 0; count--) + specialization.ImageDescriptorGroups.Add(reader.ReadUInt32()); + for (var count = CheckedCount(reader.ReadInt32(), limit); count > 0; count--) + specialization.SamplerDescriptorGroups.Add(reader.ReadUInt32()); return specialization; } @@ -952,6 +1471,173 @@ private static void WriteBytes(BinaryWriter writer, byte[] bytes) private static byte[] ReadBytes(BinaryReader reader, int limit) => reader.ReadBytes(CheckedCount(reader.ReadInt32(), limit)); + // address: the record's code address, or 0 for its identity. + private static byte[] SerializePixel(PixelPrewarmRecord record, ulong address) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + writer.Write(PixelSchemaFingerprint); + writer.Write(record.Hash); + writer.Write(record.CodeSize); + writer.Write(address); + writer.Write(record.ContinuationAddressOffset); + writer.Write(record.UserDataBase); + writer.Write(record.UserDataCount); + writer.Write(record.PushDataCursor); + var info = record.Info; + writer.Write(info.InputCount); + writer.Write(info.SystemInputBase); + writer.Write(info.CustomInterpolationMask); + writer.Write(info.PerspectiveCenterRegister); + writer.Write(info.InterpolatorSettings.Length); + foreach (var setting in info.InterpolatorSettings) writer.Write(setting); + writer.Write(info.TargetOutputModes.Length); + writer.Write(info.TargetOutputModes); + writer.Write(info.TargetExportFormats.Length); + writer.Write(info.TargetExportFormats); + writer.Write(info.TargetExportMappings.Length); + foreach (var mapping in info.TargetExportMappings) writer.Write(mapping.Packed); + writer.Write(info.IeeeMode); + writer.Write(info.ScratchDwords); + writer.Write(info.PositionX); + writer.Write(info.PositionY); + writer.Write(info.PositionZ); + writer.Write(info.PositionW); + writer.Write(info.FrontFace); + writer.Write(info.NoPerspective); + writer.Write(info.KillEnable); + writer.Write(info.DepthExportEnable); + writer.Write(info.SampleMaskExportEnable); + writer.Write(info.SampleShading); + writer.Write(info.EarlyDepth); + writer.Write(info.ExecuteOnNoop); + writer.Write(record.Outputs.Length); + foreach (var output in record.Outputs) + { + writer.Write(output.GuestSlot); + writer.Write(output.HostLocation); + writer.Write((int)output.Kind); + writer.Write(output.ComponentMapping.Packed); + writer.Write(output.DualSourceAlpha); + writer.Write(output.ExportTarget); + writer.Write(output.Index); + writer.Write((int)output.ExportFormat); + } + + writer.Write(record.InputEnable); + writer.Write(record.InputAddress); + WriteSpecialization(writer, record.Specialization); + writer.Write(record.DeviceRecordCounts); + writer.Flush(); + return stream.ToArray(); + } + + // Null for a record of another pixel schema or a damaged one. + private static PixelPrewarmRecord? TryDeserializePixel(byte[] payload) + { + try + { + using var reader = new BinaryReader(new MemoryStream(payload)); + if (reader.ReadUInt32() != PixelSchemaFingerprint) + { + return null; + } + + var hash = reader.ReadUInt64(); + var codeSize = reader.ReadUInt32(); + var address = reader.ReadUInt64(); + var continuationAddressOffset = reader.ReadUInt64(); + var userDataBase = reader.ReadUInt32(); + var userDataCount = reader.ReadUInt32(); + var pushDataCursor = reader.ReadUInt32(); + var inputCount = reader.ReadUInt32(); + var systemInputBase = reader.ReadUInt32(); + var customInterpolationMask = reader.ReadUInt32(); + var perspectiveCenterRegister = reader.ReadUInt32(); + var interpolators = new uint[CheckedCount(reader.ReadInt32(), payload.Length)]; + for (var index = 0; index < interpolators.Length; index++) interpolators[index] = reader.ReadUInt32(); + var outputModes = reader.ReadBytes(CheckedCount(reader.ReadInt32(), payload.Length)); + var exportFormats = reader.ReadBytes(CheckedCount(reader.ReadInt32(), payload.Length)); + var mappings = new ColorComponentMap[CheckedCount(reader.ReadInt32(), payload.Length)]; + for (var index = 0; index < mappings.Length; index++) mappings[index] = new ColorComponentMap(reader.ReadByte()); + // Member initializers run in order, so the reads below follow the written layout. + var info = new PixelInputInfo + { + InputCount = inputCount, + SystemInputBase = systemInputBase, + CustomInterpolationMask = customInterpolationMask, + PerspectiveCenterRegister = perspectiveCenterRegister, + InterpolatorSettings = interpolators, + TargetOutputModes = outputModes, + TargetExportFormats = exportFormats, + TargetExportMappings = mappings, + IeeeMode = reader.ReadBoolean(), + ScratchDwords = reader.ReadUInt32(), + PositionX = reader.ReadBoolean(), + PositionY = reader.ReadBoolean(), + PositionZ = reader.ReadBoolean(), + PositionW = reader.ReadBoolean(), + FrontFace = reader.ReadBoolean(), + NoPerspective = reader.ReadBoolean(), + KillEnable = reader.ReadBoolean(), + DepthExportEnable = reader.ReadBoolean(), + SampleMaskExportEnable = reader.ReadBoolean(), + SampleShading = reader.ReadBoolean(), + EarlyDepth = reader.ReadBoolean(), + ExecuteOnNoop = reader.ReadBoolean(), + }; + var outputs = new Gen5PixelOutputBinding[CheckedCount(reader.ReadInt32(), payload.Length)]; + for (var index = 0; index < outputs.Length; index++) + { + var guestSlot = reader.ReadUInt32(); + var hostLocation = reader.ReadUInt32(); + var kind = (Gen5PixelOutputKind)reader.ReadInt32(); + var mapping = new Gen5ColorComponentMapping(reader.ReadByte()); + var dualSourceAlpha = reader.ReadBoolean(); + var exportTarget = reader.ReadUInt32(); + var outputIndex = reader.ReadUInt32(); + var exportFormat = (Gen5PixelExportFormat)reader.ReadInt32(); + outputs[index] = new Gen5PixelOutputBinding(guestSlot, hostLocation, kind, mapping) + { + DualSourceAlpha = dualSourceAlpha, + ExportTarget = exportTarget, + Index = outputIndex, + ExportFormat = exportFormat, + }; + } + + var inputEnable = reader.ReadUInt32(); + var inputAddress = reader.ReadUInt32(); + var specialization = ReadSpecialization(reader, payload.Length); + var deviceRecordCounts = reader.ReadBoolean(); + if (reader.BaseStream.Position != reader.BaseStream.Length) + { + return null; + } + + return new PixelPrewarmRecord + { + Hash = hash, + CodeSize = codeSize, + Address = address, + ContinuationAddressOffset = continuationAddressOffset, + UserDataBase = userDataBase, + UserDataCount = userDataCount, + PushDataCursor = pushDataCursor, + Info = info, + Outputs = outputs, + InputEnable = inputEnable, + InputAddress = inputAddress, + Specialization = specialization, + DeviceRecordCounts = deviceRecordCounts, + }; + } + catch (Exception exception) when (exception is EndOfStreamException or ArgumentException or IOException) + { + return null; + } + } + private static byte[] SerializeStage(StagePrewarmRecord record) { using var stream = new MemoryStream(); @@ -1010,6 +1696,7 @@ private static byte[] SerializeStage(StagePrewarmRecord record) writer.Write(options.PixelInputEnable); writer.Write(options.PixelInputAddress); + writer.Write(options.DeviceRecordCounts); WriteSpecialization(writer, record.Specialization); writer.Flush(); return stream.ToArray(); @@ -1072,6 +1759,11 @@ private static StagePrewarmRecord DeserializeStage(byte[] payload) PixelInputEnable = reader.ReadUInt32(), PixelInputAddress = reader.ReadUInt32(), }; + if (!reader.ReadBoolean()) + { + options = options.WithoutDeviceRecordCounts(); + } + if ((stage == ShaderStage.Vertex && vertexInfo is null) || (stage == ShaderStage.Pixel && pixelInfo is null)) { throw new ArgumentException("The prewarm stage has no input info."); @@ -1306,55 +1998,6 @@ private static GraphicsPrewarmRecord DeserializeGraphics(byte[] payload) }; } - private static ComputePrewarmRecord DeserializeCompute(byte[] payload) - { - using var reader = new BinaryReader(new MemoryStream(payload)); - var hash = reader.ReadUInt64(); - var codeSize = reader.ReadUInt32(); - var address = reader.ReadUInt64(); - var continuationAddressOffset = reader.ReadUInt64(); - var userDataBase = reader.ReadUInt32(); - var userDataCount = reader.ReadUInt32(); - var pushDataCursor = reader.ReadUInt32(); - var info = new ComputeInputInfo - { - ThreadsX = reader.ReadUInt32(), - ThreadsY = reader.ReadUInt32(), - ThreadsZ = reader.ReadUInt32(), - DispatchThreadDimensions = reader.ReadBoolean(), - GroupIdX = reader.ReadBoolean(), - GroupIdY = reader.ReadBoolean(), - GroupIdZ = reader.ReadBoolean(), - ThreadIdCount = reader.ReadInt32(), - ThreadGroupSizeEnabled = reader.ReadBoolean(), - WaveSize = reader.ReadUInt32(), - LocalDataShareDwords = reader.ReadUInt32(), - ScratchDwords = reader.ReadUInt32(), - IeeeMode = reader.ReadBoolean(), - NeedsLocalDataShareBarriers = reader.ReadBoolean(), - WorkgroupRegister = reader.ReadInt32(), - }; - - Gen5ComputeSystemRegisters? registers = reader.ReadBoolean() - ? new Gen5ComputeSystemRegisters(ReadOptional(reader), ReadOptional(reader), ReadOptional(reader), ReadOptional(reader)) - : null; - - var specialization = ReadSpecialization(reader, payload.Length); - return new ComputePrewarmRecord - { - Hash = hash, - CodeSize = codeSize, - Address = address, - UserDataBase = userDataBase, - ContinuationAddressOffset = continuationAddressOffset, - UserDataCount = userDataCount, - PushDataCursor = pushDataCursor, - Info = info, - SystemRegisters = registers, - Specialization = specialization, - }; - } - private static void WriteOptional(BinaryWriter writer, uint? value) { writer.Write(value.HasValue); diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.CallDispatch.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.CallDispatch.cs new file mode 100644 index 000000000..d6e01d20e --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.CallDispatch.cs @@ -0,0 +1,24 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; +using ResourceSnapshot = SharpEmu.ShaderCompiler.Resources.ResourceSnapshot; + +namespace SharpEmu.Libs.Gpu.Pipelines; + +internal sealed partial class ShaderProgramCache +{ + // A ready fallback continues from the caller's current preparation (CallDispatchPreparation) instead of preparing it + // again. SHARPEMU_CALL_DISPATCH_REUSE=0 turns it off. + internal bool ReuseCallDispatch { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_CALL_DISPATCH_REUSE") != "0"; + + internal long CallDispatchReuses { get; private set; } + + // A continuation of this resolution only, never a cache or an asynchronous payload. The library is captured after + // its current reads and union update, before selecting the newest tier. A ready fallback still evaluates its own + // linked resources and record ranges; it need not restart the caller's already completed preparation. + private readonly record struct CallDispatchPreparation( + ProgramKey Key, ProgramSourceEntry Entry, ResourceRuntimeInputs Inputs, + ResourceSnapshot Snapshot, ResourceSpecialization Specialization, ShaderCallLibrary Library); +} diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index 09c433d29..7315bae95 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -46,6 +46,14 @@ public sealed class StageCompileOptions public uint PixelInputAddress { get; init; } public ComputeInputInfo? ComputeInfo { get; init; } public Gen5ComputeSystemRegisters? ComputeSystemRegisters { get; init; } + public DispatchBufferFootprint.Dispatch? ComputeDispatch { get; init; } + public bool DeviceRecordCounts { get; private set; } = true; + public StageCompileOptions WithoutDeviceRecordCounts() + { + var copy = (StageCompileOptions)MemberwiseClone(); + copy.DeviceRecordCounts = false; + return copy; + } public MeshDrawConfiguration? MeshInfo { get; init; } public Gen5TessellationInfo? Tessellation { get; init; } public Gen5TessellationHullInfo? TessellationHull { get; init; } @@ -126,7 +134,6 @@ internal sealed class ProgramPermutation public required ResourceSpecialization Specialization { get; init; } public required ShaderProgramInfo Program { get; init; } public required ShaderProgram Handle { get; init; } - public required IGuestCompiledShader Compiled { get; init; } public BindingLayout Bindings => Program.Bindings!; } @@ -146,10 +153,17 @@ internal sealed class ProgramSourceEntry // The order of its link among all linked programs: a newer program of a caller replaces an older one as its fallback. public long Generation { get; init; } + public string LibraryIdentity { get; init; } = string.Empty; // With RuntimeCallRecords, the hash of the code linked for each of CallTargets, and each site's callees with their code. public byte[][] CallTargetCodes { get; init; } = []; public Dictionary? RuntimeCallees { get; init; } + public LinkedShaderPrewarm? LinkedPrewarm { get; init; } + + // With RuntimeCallRecords, the permutation whose pipeline was still compiling at this program's last full resolution, with + // that resolution's stage resources (RuntimePipelineReady polls it with them, as it polls older compiles). Null once it is + // ready. See SkipPendingPass. + public (ShaderProgram Handle, ShaderStageResources Stage)? PendingPipeline { get; set; } public ConstantFill? ConstantFill { get; init; } public BoundedFill? BoundedFill { get; init; } public BoundedCopy? BoundedCopy { get; init; } @@ -174,15 +188,18 @@ public void AddPermutation(ProgramPermutation permutation) // Programs keyed by identity and static state; each draw materializes its resources and reuses // the permutation whose specialization and push-data start match, else compiles one more. -internal sealed class ShaderProgramCache +internal sealed partial class ShaderProgramCache { private readonly ImageDescriptorTrace _imageDescriptorTrace = new(); private const uint MaxInstructionScan = 16384; private readonly CpuContext _context; + private readonly Func _isRangeMapped; private readonly IGuestGpuBackend _compiler; private readonly IShaderPipelineHost _host; private readonly System.Collections.Concurrent.ConcurrentDictionary _programs = new(ProgramKeyComparer.Instance); + // A plan depends only on its key, and planning a large program takes seconds, so a rejected key stays rejected. + private readonly System.Collections.Concurrent.ConcurrentDictionary _rejectedPrograms = new(ProgramKeyComparer.Instance); private readonly Dictionary<(ProgramKey Key, string Library), ProgramSourceEntry> _linkedPrograms = new(); private readonly System.Collections.Concurrent.ConcurrentDictionary<(ulong Hash, uint CodeSize, ulong ContinuationAddressOffset), Gen5ShaderProgram> _decoded = new(); private readonly System.Collections.Concurrent.ConcurrentDictionary<(ulong Hash, uint CodeSize, ulong ContinuationAddressOffset), ShaderCodeCapture> _codeCaptures = new(); @@ -200,6 +217,57 @@ internal sealed class ShaderProgramCache // links a new layout on a worker and reports the program as not ready, so its dispatches are skipped as they are // while its module compiles; each program links one layout at a time. public bool DeferLinking { get; init; } + + // While the newest program of a runtime-record caller compiles and an older ready program serves its dispatches, a + // dispatch whose resolution selects the permutation still compiling (PendingPermutationServes) polls that compile and, + // while it still compiles, serves the fallback without the newest program's record ranges and stage resources, which + // the fallback would discard: it resolves its own. On by default; SHARPEMU_PENDING_PASS_SKIP=0, or any value but 1, + // turns it off. + // PendingPassSkips counts the dispatches it served. + internal bool SkipPendingPass { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_PENDING_PASS_SKIP") is null or "" or "1"; + internal long PendingPassSkips { get; private set; } + + // The pending-pass skip is decided before the newest program's targets, records and linked materialization. When that + // program has exactly one permutation and it is the one still compiling, every selection serves the fallback: the same + // selection polls that compile, and a new one cannot compile while the stage's linked module compiles + // (TryCreateComputePipeline admits one at a time) and is served by the fallback meanwhile. So the compile is polled + // first, exactly as the late check polls it, and while it still compiles the fallback serves without the + // materialization the late check would have discarded. A new specialization's translation then starts at the first + // full resolution after the compile, not before it; what is served is unchanged. SHARPEMU_PENDING_PASS_EARLY=0 leaves + // the decision to the late check. + internal bool SkipPendingPassEarly { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_PENDING_PASS_EARLY") != "0"; + internal long PendingPassEarlySkips { get; private set; } + + // Whether a layout starts its push data where BindingLayout.Allocate would start it at this cursor. + private static bool StartsAt(BindingLayout layout, uint pushDataCursor) => layout.PushDataStartDword == layout.PushStartFor(pushDataCursor); + + // Whether the stage step serves this permutation for the push-data cursor and specialization (it takes the first that does). + internal static bool Selects(ProgramPermutation candidate, uint pushDataCursor, ResourceSpecialization specialization) => + StartsAt(candidate.Bindings, pushDataCursor) && candidate.Specialization.Equals(specialization); + + // SHARPEMU_VERTEX_PUSH_AT_TOP (on by default; =0 turns it off): a graphics pipeline's pixel stage takes the push + // range first, and its vertex or mesh stage takes the top of the rest (PushData.TopFor), not the place after the + // pixel stage's data. The vertex module then reads its push data at one place for every pixel stage it is paired + // with, so one translation and one pre-rasterization part serve every pairing; a stage whose data does not fit + // beside the pixel stage's uses the shader data block. + internal static readonly bool VertexPushAtTop = Environment.GetEnvironmentVariable("SHARPEMU_VERTEX_PUSH_AT_TOP") != "0"; + + private static bool PushDataAtTop(ShaderStage stage) => VertexPushAtTop && stage is ShaderStage.Vertex or ShaderStage.Mesh; + + // Whether the stage step would select the pending permutation: then it would poll that compile and, while it compiles, + // serve the caller's fallback. Any other selection, or none, is left to the stage step. + internal static bool PendingPermutationServes(IReadOnlyList permutations, ShaderProgram pending, + uint pushDataCursor, ResourceSpecialization specialization) + { + foreach (var candidate in permutations) + { + if (Selects(candidate, pushDataCursor, specialization)) return candidate.Handle.Id == pending.Id; + } + + return false; + } private readonly Dictionary Link)> _pendingLinks = new(); // Callers whose callees cannot read their records at run time: they link a copy per record. @@ -288,8 +356,16 @@ public bool Revalidate(in ShaderStageResources stage) // The functions the call tables name, decoded once while their code stays the same. private readonly ShaderFunctionCache _functions; + // Call-library reuse (SHARPEMU_CALL_LIBRARY_REUSE), on by default. Null on a cache made without its initializers. + private ShaderCallLibraryMemo? _libraryMemo = ShaderCallLibraryMemo.Enabled ? new() : null; + private static readonly bool PrefetchEnabled = Environment.GetEnvironmentVariable("SHARPEMU_RESOURCE_PREFETCH") != "0"; + // An image or sampler descriptor loaded at an index the host cannot evaluate (a bindless heap entry) reads as a null + // descriptor, so the draw or dispatch that uses it still runs. SHARPEMU_BINDLESS_NULL=0 skips that work instead; it is + // read whenever a program is planned. + private static bool BindlessNullDescriptors => Environment.GetEnvironmentVariable("SHARPEMU_BINDLESS_NULL") != "0"; + // On a host that reads call records at run time (descriptor set 1), a linked program keeps one copy of each callee per // call site and reads its records' images and samplers at run time, so tables that gain or lose records, or move their // arguments, link to the same program; only a new callee links a new one. SHARPEMU_RUNTIME_CALL_RECORDS=0 links a copy @@ -301,6 +377,7 @@ public bool Revalidate(in ShaderStageResources stage) public ShaderProgramCache(CpuContext context, IGuestGpuBackend compiler, IShaderPipelineHost host) { _context = context; + _isRangeMapped = context.Memory.CanRead; _compiler = compiler; _host = host; _readGuestWord = host.TryReadGuestWord; @@ -344,7 +421,7 @@ public IEnumerable Entries var shaders = _compiler.CompileTessellationBridge(layout, domain); ShaderProgram Create(IGuestCompiledShader shader, ShaderStage stage) { - var id = ++_nextProgramId; + var id = Interlocked.Increment(ref _nextProgramId); return new(id, _host.CreateShaderModule(shader, stage, 0, id)); } @@ -495,15 +572,19 @@ internal bool TryGetProgramForEntry(ProgramSourceEntry entry, ShaderSource sourc } } - // With runtimeFallback, the caller's dispatch runs that ready program of it (see _runtimeFallbacks). + // With runtimeFallback, the caller's dispatch runs that ready program of it (see _runtimeFallbacks). With preparation, it + // continues from the caller's own preparation (CallDispatchPreparation) instead of redoing it. private ShaderProgram GetOrCompileCore(ShaderSource source, StageCompileOptions options, ref uint pushDataCursor, out ShaderStageResources stage, - bool deferLinking, ProgramSourceEntry? runtimeFallback = null) + bool deferLinking, ProgramSourceEntry? runtimeFallback = null, CallDispatchPreparation? preparation = null) { - ProgramKey? key = null; - ProgramSourceEntry? entry; - using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramCacheLookup)) + var key = preparation?.Key; + var entry = preparation?.Entry; + if (preparation is null) { - entry = FindEntry(source, options, out key); + using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramCacheLookup)) + { + entry = FindEntry(source, options, out key); + } } var sourceWasCached = entry is not null; @@ -520,7 +601,16 @@ private ShaderProgram GetOrCompileCore(ShaderSource source, StageCompileOptions sourceWasCached = entry is not null; if (entry is null) { - entry = CreateEntry(source, options); + try + { + entry = CreateEntry(source, options); + } + catch (ShaderProgramRejectedException exception) + { + _rejectedPrograms.TryAdd(KeyFor(source, options), exception.Message); + throw; + } + BuildStaticState(source.Stage, options); key = BuildProgramKey(source); _programs.TryAdd(key, entry); @@ -529,9 +619,10 @@ private ShaderProgram GetOrCompileCore(ShaderSource source, StageCompileOptions } } - return CompleteProgram(entry, sourceWasCached, key, source, options, ref pushDataCursor, out stage, deferLinking, runtimeFallback); + return CompleteProgram(entry, sourceWasCached, key, source, options, ref pushDataCursor, out stage, deferLinking, runtimeFallback, preparation); } + // The entry of this source and static state, or null; a key whose plan was rejected throws its rejection again. private ProgramSourceEntry? FindEntry(ShaderSource source, StageCompileOptions options, out ProgramKey? key) { BuildStaticState(source.Stage, options); @@ -543,19 +634,26 @@ private ShaderProgram GetOrCompileCore(ShaderSource source, StageCompileOptions return entry; } + if (_rejectedPrograms.GetAlternateLookup().TryGetValue(probe, out _, out var rejection)) + { + throw new ShaderProgramRejectedException(rejection); + } + key = null; return null; } private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCached, ProgramKey? key, ShaderSource source, StageCompileOptions options, - ref uint pushDataCursor, out ShaderStageResources stage, bool deferLinking, ProgramSourceEntry? runtimeFallback = null) + ref uint pushDataCursor, out ShaderStageResources stage, bool deferLinking, ProgramSourceEntry? runtimeFallback = null, + CallDispatchPreparation? preparation = null) { if (runtimeFallback is null) { _lastEntry = entry; } - var inputs = new ResourceRuntimeInputs + var callPreparation = preparation; + var inputs = preparation?.Inputs ?? new ResourceRuntimeInputs { UserData = source.UserData, ShaderBase = source.Address, @@ -566,20 +664,28 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa _imageDescriptorTrace.RecordCandidate(source.Hash, descriptorSource, candidateKey, heap, address, words.Span) : null, ReadResidentMemory = _prefetchResidentGuestBytes, - ComputeState = source.Stage == ShaderStage.Compute && options.ComputeInfo is { } computeState - ? new ComputeSelectorState(computeState.WaveSize, Math.Max(computeState.ThreadsX, 1), - Math.Max(computeState.ThreadsY, 1), Math.Max(computeState.ThreadsZ, 1), computeState.DispatchThreadDimensions, - computeState.LocalDataShareDwords, computeState.ThreadIdCount) - : null, + ComputeState = ComputeStateOf(source, options), + IsRangeMapped = _isRangeMapped, }; + if (entry.Plan.DeviceRecordCounts is { } counts && !counts.SupportsDescriptors(entry.Plan, inputs)) + { + var handle = GetOrCompileCore(source, options.WithoutDeviceRecordCounts(), ref pushDataCursor, out stage, deferLinking); + if (runtimeFallback is null) + { + _lastEntry = entry; + } + + return handle; + } + var hasShaderCalls = entry.HasShaderCalls; if (hasShaderCalls && !_compiler.LinkedShaderCallsSupported) throw new ShaderProgramRejectedException( $"The backend does not support linked shader calls: backend={_compiler.BackendName} stage={source.Label} hash=0x{source.Hash:X16}."); // Both are assigned by the materialization that follows; a failed one throws. - ResourceSnapshot snapshot = null!; - ResourceSpecialization specialization = null!; + ResourceSnapshot snapshot = preparation?.Snapshot!; + ResourceSpecialization specialization = preparation?.Specialization!; var captureIndirectImageFailure = _spirvDumpEnabled ? ShaderPermutationDump.CreateFailureCapture(source) : null; if (Diagnostics.GpuReadTrace.Enabled) { @@ -587,41 +693,48 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa Diagnostics.GpuReadTrace.CurrentStage = source.Label; } - using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ResourceMaterialization)) + if (preparation is null) { - // Failure capture needs the full walk, so a dump run bypasses the cache. - ResourceMaterializationFailure materializationFailure; - var started = System.Diagnostics.Stopwatch.GetTimestamp(); - bool materialized; - MaterializationTally.Outcome outcome; - if (captureIndirectImageFailure is null && ResourceMaterializer.CanMaterializeFast(entry.Plan)) - { - materialized = ResourceMaterializer.MaterializeFast(entry.Plan, inputs, ref snapshot, ref specialization, out materializationFailure); - outcome = ResourceMaterializer.LastFastOutcome; - } - else if (Materializations is { } materializations && captureIndirectImageFailure is null) - { - materialized = materializations.Materialize(entry.Plan, inputs, _readResidentGuestBytes, ref snapshot, ref specialization, - out materializationFailure); - outcome = MaterializationTally.FromCache(materializations.LastOutcome); - } - else + using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ResourceMaterialization)) { - materialized = ResourceMaterializer.Materialize(entry.Plan, inputs, ref snapshot, ref specialization, out materializationFailure, - captureIndirectImageFailure); - outcome = MaterializationTally.Outcome.Full; - } + // Failure capture needs the full walk, so a dump run bypasses the cache. + ResourceMaterializationFailure materializationFailure; + var started = System.Diagnostics.Stopwatch.GetTimestamp(); + bool materialized; + MaterializationTally.Outcome outcome; + if (captureIndirectImageFailure is null && ResourceMaterializer.CanMaterializeFast(entry.Plan)) + { + materialized = ResourceMaterializer.MaterializeFast(entry.Plan, inputs, ref snapshot, ref specialization, out materializationFailure); + outcome = ResourceMaterializer.LastFastOutcome; + } + else if (Materializations is { } materializations && captureIndirectImageFailure is null) + { + materialized = materializations.Materialize(entry.Plan, inputs, _readResidentGuestBytes, ref snapshot, ref specialization, + out materializationFailure); + outcome = MaterializationTally.FromCache(materializations.LastOutcome); + } + else + { + materialized = ResourceMaterializer.Materialize(entry.Plan, inputs, ref snapshot, ref specialization, out materializationFailure, + captureIndirectImageFailure); + outcome = MaterializationTally.Outcome.Full; + } - MaterializationTally.Note(materialized ? outcome : MaterializationTally.Outcome.Failed, - System.Diagnostics.Stopwatch.GetTimestamp() - started, materialized ? snapshot : null); - if (!materialized) - { - var message = $"The shader resources could not be materialized: stage={source.Label} hash=0x{source.Hash:X16} shader=0x{source.Address:X16} reason={materializationFailure}."; - if (materializationFailure is ResourceMaterializationFailure.IncompatibleImageCandidates or ResourceMaterializationFailure.ImageCapacityExceeded) - throw new ShaderProgramRejectedException(message); - throw SubmissionScheduler.Fatal(message); + MaterializationTally.Note(materialized ? outcome : MaterializationTally.Outcome.Failed, + System.Diagnostics.Stopwatch.GetTimestamp() - started, materialized ? snapshot : null); + if (!materialized) + { + var message = $"The shader resources could not be materialized: stage={source.Label} hash=0x{source.Hash:X16} shader=0x{source.Address:X16} reason={materializationFailure}."; + if (materializationFailure is ResourceMaterializationFailure.IncompatibleImageCandidates or ResourceMaterializationFailure.ImageCapacityExceeded) + throw new ShaderProgramRejectedException(message); + throw SubmissionScheduler.Fatal(message); + } } } + else + { + CallDispatchReuses++; + } ulong[] callArguments = []; ulong[] callTargets = []; @@ -639,8 +752,12 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa var caller = entry.Program with { Address = source.Address }; // Tables and function code are read like the caller's code: a stale image over reused memory must not hide them. var runtimeRecords = runtimeFallback is not null || (RuntimeCallRecords && !_perRecordCallers.Contains(source.Hash)); - var library = ShaderCallLibrary.Read(caller, entry.Plan.Memory, snapshot, _readGuestWord, _functions, runtimeRecords); - if (runtimeRecords) + var library = preparation?.Library ?? (_libraryMemo is { } readMemo + ? readMemo.Read(caller, entry.Plan.Memory, snapshot, _readGuestWord, _functions, runtimeRecords, source.UserDataBase, + _readResidentGuestBytes) + : ShaderCallLibrary.Read(caller, entry.Plan.Memory, snapshot, _readGuestWord, _functions, runtimeRecords, + source.UserDataBase, _readResidentGuestBytes)); + if (runtimeRecords && preparation is null) { if (!_calleeUnions.TryGetValue(programKey, out var union)) { @@ -654,14 +771,35 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa } } - library = library.Unite(caller.Address, union, MaxUnitedCallees); + bool unionChanged; + try + { + library = _libraryMemo is { } uniteMemo + ? uniteMemo.Unite(library, caller.Address, union, MaxUnitedCallees, out unionChanged) + : library.Unite(caller.Address, union, MaxUnitedCallees, out unionChanged); + } + catch + { + // A failed unite may have changed the union, so no earlier scan of it stands. + if (_calleeTiers.TryGetValue(programKey, out var failedTiers)) failedTiers.NoteUnionChanged(); + throw; + } + + if (unionChanged && _calleeTiers.TryGetValue(programKey, out var changedTiers)) changedTiers.NoteUnionChanged(); + if (runtimeFallback is null && ReuseCallDispatch && captureIndirectImageFailure is null && !captureLinkedImages) + { + callPreparation = new(programKey, entry, inputs, snapshot, specialization, library); + } + if (_calleeTiers.TryGetValue(programKey, out var tiers)) { if (runtimeFallback is null) { tiers.Observe(library, programKey.Hash, _host); - library = library.WithSiteCallees(caller.Address, - tiers.Choose(union, FallbackGeneration(programKey), _host.CallMarkSnapshots)); + var chosen = tiers.Choose(union, FallbackGeneration(programKey), _host.CallMarkSnapshots); + library = _libraryMemo is { } chosenMemo + ? chosenMemo.WithSiteCallees(library, caller.Address, chosen) + : library.WithSiteCallees(caller.Address, chosen); } } else if (runtimeFallback is null && !_runtimeFallbacks.ContainsKey(programKey)) @@ -669,7 +807,9 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa // A caller with no ready program first links the callees an earlier session kept for it, whose pipeline // the linked cache holds, or none, so its dispatches run within seconds instead of being skipped until // the driver has compiled the callees' code. - library = library.WithSiteCallees(caller.Address, _keptCallees[programKey]); + library = _libraryMemo is { } keptMemo + ? keptMemo.WithSiteCallees(library, caller.Address, _keptCallees[programKey]) + : library.WithSiteCallees(caller.Address, _keptCallees[programKey]); } } @@ -687,14 +827,15 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa } catch (ShaderProgramPendingException) when (runtimeRecords && _runtimeFallbacks.TryGetValue(programKey, out var ready)) { - return GetOrCompileCore(source, options, ref pushDataCursor, out stage, deferLinking, ready); + return GetOrCompileFallback(source, options, ref pushDataCursor, out stage, deferLinking, ready, + null, library.LayoutIdentity, "link", callPreparation); } } else { linked = LinkProgram(caller, library, source.Stage, source.Hash, source.UserDataBase, (uint)source.UserData.Length, waveSize, captureLinkedImages ? plan => failedLinkedPlan = plan : null, runtimeRecords, runtimeRecords && CalleeTiering, - source.Registered.Frontend) ?? + _host.SupportsBindlessHeap, _host.ShaderPrewarm is not null, source.Registered.Frontend) ?? RefuseRuntimeCallRecords(source.Hash); failedLinkedPlan = null; } @@ -708,6 +849,25 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa linkedTiers.LinkedGeneration = linked.Generation; } + if (runtimeFallback is null && SkipPendingPassEarly && SkipPendingPass && + linked.RuntimeCallRecords && linked.PendingPipeline is { } earlyPending && linked.Permutations.Count == 1 && + linked.Permutations[0].Handle.Id == earlyPending.Handle.Id && + _runtimeFallbacks.TryGetValue(programKey, out var earlyFallback) && !ReferenceEquals(earlyFallback, linked)) + { + if (RuntimePipelineReady(programKey, linked, earlyPending.Handle, earlyPending.Stage, options, null)) + { + linked.PendingPipeline = null; + } + // The poll can promote an older compile that finished meanwhile; the fallback it leaves serves. + else if (_runtimeFallbacks.TryGetValue(programKey, out var earlyServing) && !ReferenceEquals(earlyServing, linked)) + { + PendingPassSkips++; + PendingPassEarlySkips++; + return GetOrCompileFallback(source, options, ref pushDataCursor, out stage, deferLinking, earlyServing, + linked.Generation, linked.LibraryIdentity, "pipeline", callPreparation); + } + } + callArguments = library.Arguments; if (linked.RuntimeCallRecords) { @@ -733,6 +893,24 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa : ResourceMaterializer.Materialize(entry.Plan, linkedInputs, ref snapshot, ref specialization); if (!linkedMaterialized) throw new InvalidOperationException("The linked shader resources could not be materialized."); + if (runtimeFallback is null && linked.PendingPipeline is { } pending && SkipPendingPass && + PendingPermutationServes(linked.Permutations, pending.Handle, pushDataCursor, specialization) && + _runtimeFallbacks.TryGetValue(programKey, out var fallbackBefore) && !ReferenceEquals(fallbackBefore, linked)) + { + if (RuntimePipelineReady(programKey, linked, pending.Handle, pending.Stage, options, null)) + { + linked.PendingPipeline = null; + } + // The poll can promote an older compile that finished meanwhile; the fallback it leaves serves, as after + // the stage step's own poll. + else if (_runtimeFallbacks.TryGetValue(programKey, out var servingWhilePending) && !ReferenceEquals(servingWhilePending, linked)) + { + PendingPassSkips++; + return GetOrCompileFallback(source, options, ref pushDataCursor, out stage, deferLinking, servingWhilePending, + linked.Generation, linked.LibraryIdentity, "pipeline", callPreparation); + } + } + if (linked.RuntimeCallRecords) (callRecords, callRecordRanges) = CallRecordRanges(entry.Plan, callRecords!, callTargets, linkedInputs, source.UserDataBase); } @@ -751,7 +929,7 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa _imageDescriptorTrace.Record(source, entry.Plan, snapshot); var permutation = Volatile.Read(ref entry.LastPermutation) is { } last && ReferenceEquals(last.Specialization, specialization) && - last.Bindings.PushDataStartDword == PushData.StartFor(pushDataCursor, last.Bindings.ShaderDataDwordCount) + StartsAt(last.Bindings, pushDataCursor) ? last : FindPermutation(entry, specialization, pushDataCursor); if (permutation is null) @@ -769,7 +947,8 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa var ready = ReadyFallback(key!, entry); if (ready is null) throw; - return GetOrCompileCore(source, options, ref pushDataCursor, out stage, deferLinking, ready); + return GetOrCompileFallback(source, options, ref pushDataCursor, out stage, deferLinking, ready, + entry.Generation, entry.LibraryIdentity, "permutation", callPreparation); } } else if (RenderTrace.Enabled && RenderTrace.Pipeline()) @@ -787,12 +966,19 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa { lock (_callGate) { - if (!RuntimePipelineReady(key!, entry, permutation.Handle, stage, options, runtimeFallback)) + var pipelineReady = RuntimePipelineReady(key!, entry, permutation.Handle, stage, options, runtimeFallback); + if (runtimeFallback is null) + { + entry.PendingPipeline = pipelineReady ? null : (permutation.Handle, stage); + } + + if (!pipelineReady) { if (runtimeFallback is not null) throw new ShaderProgramPendingException(); if (ReadyFallback(key!, entry) is { } ready) - return GetOrCompileCore(source, options, ref pushDataCursor, out stage, deferLinking, ready); + return GetOrCompileFallback(source, options, ref pushDataCursor, out stage, deferLinking, ready, + entry.Generation, entry.LibraryIdentity, "pipeline", callPreparation); } } } @@ -840,8 +1026,7 @@ private ProgramKey KeyFor(ShaderSource source, StageCompileOptions options) { foreach (var candidate in entry.Permutations) { - var layout = candidate.Bindings; - if (layout.PushDataStartDword == (layout.UsesTessellationData ? PushData.NoStart : PushData.StartFor(pushDataCursor, layout.ShaderDataDwordCount)) && candidate.Specialization.Equals(specialization)) + if (Selects(candidate, pushDataCursor, specialization)) { return candidate; } @@ -859,24 +1044,51 @@ private ProgramKey KeyFor(ShaderSource source, StageCompileOptions options) } } + // A recursive GetOrCompileCore that serves a ready program; its stage names the fallback (CompileFallback). + private ShaderProgram GetOrCompileFallback(ShaderSource source, StageCompileOptions options, ref uint pushDataCursor, + out ShaderStageResources stage, bool deferLinking, ProgramSourceEntry fallback, + long? requestedGeneration, string requestedLibrary, string reason, CallDispatchPreparation? preparation) + { + var handle = GetOrCompileCore(source, options, ref pushDataCursor, out stage, deferLinking, fallback, preparation); + var selection = new LinkedCompileFallback(source.Hash, requestedGeneration, fallback.Generation, + requestedLibrary, fallback.LibraryIdentity, reason); + stage = stage with { CompileFallback = selection }; + return handle; + } + // The key of the entry the static state was just built for. private ProgramKey BuildProgramKey(ShaderSource source) => new(source.Stage, source.Hash, (uint)source.UserData.Length, source.CodeSize, source.ContinuationAddressOffset, StaticState.ToArray()); + // The compute selector state of a compute stage's inputs, with the dispatch its record counts are proven against. + private static ComputeSelectorState? ComputeStateOf(ShaderSource source, StageCompileOptions options) => + source.Stage == ShaderStage.Compute && options.ComputeInfo is { } computeState + ? new ComputeSelectorState(computeState.WaveSize, Math.Max(computeState.ThreadsX, 1), + Math.Max(computeState.ThreadsY, 1), Math.Max(computeState.ThreadsZ, 1), computeState.DispatchThreadDimensions, + computeState.LocalDataShareDwords, computeState.ThreadIdCount) + { + Dispatch = options.ComputeDispatch, + DeviceCountProof = DeviceRecordCountPlan.Enabled, + } + : null; + // With runtimeRecords, a program whose callees cannot read their records at run time is refused (null), and its caller // links a copy per record from then on (RefuseRuntimeCallRecords). private ProgramSourceEntry? LinkProgram(Gen5ShaderProgram caller, ShaderCallLibrary library, ShaderStage stage, ulong hash, uint userDataBase, uint userDataCount, uint waveSize, Action? beforeResourceTracking, bool runtimeRecords = false, - bool callMarks = false, IShaderFrontend? frontend = null) + bool callMarks = false, bool bindlessHeap = false, bool capturePrewarm = false, IShaderFrontend? frontend = null) { Gen5ShaderProgram program; ShaderResourcePlan plan; try { - program = Gen5ShaderCallLinker.Link(caller, library.Calls, runtimeRecords); + program = runtimeRecords + ? ShaderCallLibrary.LinkLeavingOutUnlinkable(caller, ref library, failure => ReportLeftOutCallee(hash, failure)) + : Gen5ShaderCallLinker.Link(caller, library.Calls, runtimeRecords); plan = ShaderResourcePlan.Extract(program, stage, hash, userDataBase, userDataCount, - beforeResourceTracking: beforeResourceTracking, waveSize: waveSize, callRecords: runtimeRecords, callMarks: callMarks, + beforeResourceTracking: beforeResourceTracking, waveSize: waveSize, bindlessNullDescriptors: BindlessNullDescriptors, + bindlessHeap: bindlessHeap, callRecords: runtimeRecords, callMarks: callMarks, normalizeBufferDescriptor: frontend?.NormalizeBufferDescriptor, normalizeImageDescriptor: ImageNormalizer(frontend), imageNormalizationVersion: frontend?.ImageNormalizationVersion); @@ -893,11 +1105,25 @@ private ProgramKey BuildProgramKey(ShaderSource source) => CallTargets = callTargets, CallTargetCodes = [.. callTargets.Select(address => library.CodeHashes[address])], RuntimeCallees = runtimeRecords ? library.SiteCallees() : null, + LinkedPrewarm = capturePrewarm && stage == ShaderStage.Compute + ? LinkedShaderPrewarm.Capture(library, runtimeRecords, callMarks, bindlessHeap) : null, Generation = Interlocked.Increment(ref _linkGenerations), + LibraryIdentity = library.LayoutIdentity, HasShaderCalls = program.Instructions.Any(instruction => instruction.Opcode == "SSwappcB64"), HasBitwiseExclusiveOr = program.Instructions.Any(instruction => instruction.Opcode.Contains("Xor", StringComparison.Ordinal)) }; } + private static int _leftOutCalleeReports; + + private static void ReportLeftOutCallee(ulong hash, ShaderCallLinkException failure) + { + if (Interlocked.Increment(ref _leftOutCalleeReports) <= 16) + { + Console.Error.WriteLine($"[GPU][WARN][LINKED_PROGRAM] A callee cannot be linked and is left out; its calls return at once: " + + $"hash=0x{hash:X16} {failure.Message}"); + } + } + // The program linked for linkedKey once its worker is done; until then the program is pending. A finished link of // the program's earlier layout is kept, as the game can return to that table, and a failed one is rejected as a // link on the command stream would be. @@ -924,7 +1150,9 @@ private static ((ulong Target, ulong Argument)[] Records, DeviceAddressRange[] R { var first = ranges.Count; if (slotOf.TryGetValue(record.Target, out var slot) && - !CallRecordPlanner.AddRecordRanges(plan, slot, record.Argument, inputs, userDataBase, ranges)) + (!CallRecordPlanner.AddRecordRanges(plan, slot, record.Argument, inputs, userDataBase, ranges) || + ranges.Skip(first).Any(static range => + ClassifyRecordBuffer(range.Base, range.Size, range.Written) == RecordBuffer.LeaveRecordOut))) { ranges.RemoveRange(first, ranges.Count - first); if (_invalidRecordReports++ < 8) @@ -936,6 +1164,14 @@ private static ((ulong Target, ulong Argument)[] Records, DeviceAddressRange[] R continue; } + for (var index = ranges.Count - 1; index >= first; index--) + { + if (ClassifyRecordBuffer(ranges[index].Base, ranges[index].Size, ranges[index].Written) != RecordBuffer.Resident) + { + ranges.RemoveAt(index); + } + } + kept.Add(record); } @@ -944,6 +1180,28 @@ private static ((ulong Target, ulong Argument)[] Records, DeviceAddressRange[] R private static int _invalidRecordReports; + // A record names a buffer of at most 4 GiB inside the address space the device-address cache maps (PageOwnerTable). Other + // words in its place (material constants, say, on a record whose callee does not read the buffer) describe no buffer. + internal static bool DescribesRecordBuffer(ulong address, ulong size) => + size <= 1UL << 32 && address < Buffers.PageOwnerTable.AddressSpaceSize && + size <= Buffers.PageOwnerTable.AddressSpaceSize - address; + + internal enum RecordBuffer + { + Resident, + NotResident, + LeaveRecordOut, + } + + // What a buffer a callee reads through its record's argument needs at a dispatch. A buffer is made resident. Words that + // describe no buffer are not, and a read through them returns zeros, as through any page the cache does not hold; when the + // callee writes the buffer, its record is left out instead (its call returns at once), so no store lands through them. + internal static RecordBuffer ClassifyRecordBuffer(ulong address, ulong size, bool written) => + address == 0 || size == 0 ? RecordBuffer.NotResident + : DescribesRecordBuffer(address, size) ? RecordBuffer.Resident + : written ? RecordBuffer.LeaveRecordOut + : RecordBuffer.NotResident; + // Whether a runtime-record program's pipeline is ready for this compute dispatch; its compile starts or is polled here, and a // ready program becomes the caller's fallback. Without a pipeline host every pipeline counts as ready. private bool RuntimePipelineReady(ProgramKey key, ProgramSourceEntry entry, ShaderProgram handle, ShaderStageResources stage, @@ -1067,7 +1325,7 @@ private static (ulong[] Targets, (ulong Target, ulong Argument)[] Records, bool { if (!served.Contains(address)) { - var key = Convert.ToHexString(code); + var key = ShaderCallLibrary.CodeKey(code); if (!byCode.TryGetValue(key, out var addresses)) { byCode.Add(key, addresses = []); @@ -1080,7 +1338,7 @@ private static (ulong[] Targets, (ulong Target, ulong Argument)[] Records, bool for (var slot = 0; slot < targets.Length; slot++) { if (targets[slot] != NoTarget || slot >= program.CallTargetCodes.Length || - !byCode.TryGetValue(Convert.ToHexString(program.CallTargetCodes[slot]), out var candidates)) + !byCode.TryGetValue(ShaderCallLibrary.CodeKey(program.CallTargetCodes[slot]), out var candidates)) { continue; } @@ -1106,9 +1364,9 @@ private static (ulong[] Targets, (ulong Target, ulong Argument)[] Records, bool } } - var codes = program.CallTargetCodes.Select(Convert.ToHexString).ToHashSet(); + var codes = program.CallTargetCodes.Select(ShaderCallLibrary.CodeKey).ToHashSet(); var unservedCopy = library.CurrentCodeHashes.Any(named => - !served.Contains(named.Key) && codes.Contains(Convert.ToHexString(named.Value))); + !served.Contains(named.Key) && codes.Contains(ShaderCallLibrary.CodeKey(named.Value))); return (targets, [.. library.Records.Where(record => served.Contains(record.Target))], unservedCopy); } @@ -1141,9 +1399,12 @@ private ProgramSourceEntry TakeDeferredLink((ProgramKey Key, string Library) lin var (stage, hash, userDataBase, userDataCount) = (source.Stage, source.Hash, source.UserDataBase, (uint)source.UserData.Length); var callMarks = runtimeRecords && CalleeTiering; + var bindlessHeap = _host.SupportsBindlessHeap; + var capturePrewarm = _host.ShaderPrewarm is not null; var frontend = source.Registered.Frontend; _pendingLinks.Add(source.Hash, (linkedKey, Task.Run(() => - LinkProgram(caller, library, stage, hash, userDataBase, userDataCount, waveSize, null, runtimeRecords, callMarks, frontend)))); + LinkProgram(caller, library, stage, hash, userDataBase, userDataCount, waveSize, null, runtimeRecords, callMarks, bindlessHeap, + capturePrewarm, frontend)))); throw new ShaderProgramPendingException(); } @@ -1158,55 +1419,62 @@ private static ShaderStageResources CreateStageResources( CallTargets = callTargets, CallRecords = callRecords, CallRecordRanges = callRecordRanges, - ThreadLimits = source.Stage == ShaderStage.Compute && options.ComputeInfo is { DispatchThreadDimensions: true } compute + ThreadLimits = source.Stage == ShaderStage.Compute && + options.ComputeInfo is { DispatchThreadDimensions: true, IndirectThreadCounts: false } compute ? new DispatchThreadLimits(compute.DispatchThreadsX, compute.DispatchThreadsY, compute.DispatchThreadsZ) : null, + GpuThreadLimits = source.Stage == ShaderStage.Compute && options.ComputeInfo is { IndirectThreadCounts: true }, }; } - private void BuildStaticState(ShaderStage stage, StageCompileOptions options) + private static void BuildStaticState(ShaderStage stage, StageCompileOptions options) => BuildStaticState(stage, options, StaticState); + + // Into a list of the caller's: the prewarm builds its own. + private static void BuildStaticState(ShaderStage stage, StageCompileOptions options, List state) { switch (stage) { case ShaderStage.Vertex: case ShaderStage.TessellationEvaluation: - StageStaticKey.Build(options.VertexInfo ?? throw new ArgumentException("The vertex lookup has no vertex input info."), options.RequiredVertexOutputCount, StaticState); + StageStaticKey.Build(options.VertexInfo ?? throw new ArgumentException("The vertex lookup has no vertex input info."), options.RequiredVertexOutputCount, state); break; case ShaderStage.Pixel: - StageStaticKey.Build(options.PixelInfo ?? throw new ArgumentException("The pixel lookup has no pixel input info."), StaticState); + StageStaticKey.Build(options.PixelInfo ?? throw new ArgumentException("The pixel lookup has no pixel input info."), state); foreach (var output in options.PixelOutputs) { - StaticState.Add(output.GuestSlot); - StaticState.Add(output.HostLocation); - StaticState.Add(output.ExportTarget); - StaticState.Add(output.Index); - StaticState.Add(output.DualSourceAlpha ? 1u : 0u); + state.Add(output.GuestSlot); + state.Add(output.HostLocation); + state.Add(output.ExportTarget); + state.Add(output.Index); + state.Add(output.DualSourceAlpha ? 1u : 0u); } break; case ShaderStage.Mesh: - StageStaticKey.Build(options.MeshInfo ?? throw new ArgumentException("The mesh lookup has no mesh input info."), options.RequiredVertexOutputCount, StaticState); - StaticState.Add(options.MeshOutputLocationMask.HasValue ? 1u : 0u); - StaticState.Add(options.MeshOutputLocationMask.GetValueOrDefault()); + StageStaticKey.Build(options.MeshInfo ?? throw new ArgumentException("The mesh lookup has no mesh input info."), options.RequiredVertexOutputCount, state); + state.Add(options.MeshOutputLocationMask.HasValue ? 1u : 0u); + state.Add(options.MeshOutputLocationMask.GetValueOrDefault()); break; default: - StageStaticKey.Build(options.ComputeInfo ?? throw new ArgumentException("The compute lookup has no compute input info."), StaticState); + StageStaticKey.Build(options.ComputeInfo ?? throw new ArgumentException("The compute lookup has no compute input info."), state); + if (ScalarDataReadPolicy.Enabled) state.Add(ScalarDataReadPolicy.CacheIdentity); + if (DeviceRecordCountPlan.Enabled && options.DeviceRecordCounts) state.Add(DeviceRecordCountPlan.CacheIdentity); break; } if (options.Tessellation is { } tessellation) { - StaticState.Add((uint)tessellation.Domain); - StaticState.Add((uint)tessellation.Spacing); - StaticState.Add(tessellation.PointMode ? 1u : 0); - StaticState.Add(tessellation.Clockwise ? 1u : 0); + state.Add((uint)tessellation.Domain); + state.Add((uint)tessellation.Spacing); + state.Add(tessellation.PointMode ? 1u : 0); + state.Add(tessellation.Clockwise ? 1u : 0); } if (options.TessellationHull is { } hull) { - StaticState.Add(hull.InputControlPoints); - StaticState.Add(hull.OutputControlPoints); - StaticState.Add(hull.PatchesPerGroup); - StaticState.Add(hull.HullEntryPc); + state.Add(hull.InputControlPoints); + state.Add(hull.OutputControlPoints); + state.Add(hull.PatchesPerGroup); + state.Add(hull.HullEntryPc); } } @@ -1226,15 +1494,8 @@ private ProgramSourceEntry CreateEntry(ShaderSource source, StageCompileOptions ShaderVertexInput[] vertexInputs = []; if (source.Stage == ShaderStage.Vertex && options.VertexInfo is { FetchEmbedded: true } vertexInfo) { - fetch = EmbeddedVertexFetchDetector.Detect( - program, - (int)source.UserDataBase + vertexInfo.FetchAttributeRegister, - (int)source.UserDataBase + vertexInfo.FetchBufferRegister, - source.UserDataBase, - (uint)source.UserData.Length, - waveSize: 32); - vertexInputs = BuildVertexInputs(fetch, vertexInfo, source); - program = fetch.RemoveReplacedTableLoads(program); + (fetch, vertexInputs, program) = PrepareEmbeddedFetch(program, vertexInfo, source.UserDataBase, + (uint)source.UserData.Length, source.Hash, source.Address); } ShaderResourcePlan plan; @@ -1250,6 +1511,9 @@ private ProgramSourceEntry CreateEntry(ShaderSource source, StageCompileOptions ShaderStage.Compute => options.ComputeInfo?.WaveSize ?? 64u, _ => 32u, }, dynamicUserData: options.VertexInfo?.StartInstanceUserData ?? -1, + bindlessNullDescriptors: BindlessNullDescriptors, bindlessHeap: _host.SupportsBindlessHeap, + stableImageLimits: StableImageLimits(_host, source.Stage), + deviceRecordCounts: DeviceRecordCountPlan.Enabled && options.DeviceRecordCounts, normalizeBufferDescriptor: source.Registered.Frontend?.NormalizeBufferDescriptor, normalizeImageDescriptor: ImageNormalizer(source.Registered.Frontend), imageNormalizationVersion: source.Registered.Frontend?.ImageNormalizationVersion); @@ -1260,6 +1524,13 @@ private ProgramSourceEntry CreateEntry(ShaderSource source, StageCompileOptions throw new ShaderProgramRejectedException($"The shader resource plan is invalid: stage={source.Label} hash=0x{source.Hash:X16} shader=0x{source.Address:X16} error={exception.Message}."); } + if (plan.NullBindlessDescriptorPcs.Count != 0) + { + Console.Error.WriteLine( + $"[GPU][WARN] Bindless descriptors read as null: stage={source.Label} hash=0x{source.Hash:X16} shader=0x{source.Address:X16} " + + $"pcs={string.Join(',', plan.NullBindlessDescriptorPcs.Select(pc => $"0x{pc:X}"))}"); + } + var exclusiveOr = false; foreach (var instruction in program.Instructions) { @@ -1281,8 +1552,18 @@ private ProgramSourceEntry CreateEntry(ShaderSource source, StageCompileOptions }; } + // The embedded vertex fetch of a vertex program: its plan, the fixed-function inputs it becomes, and the program + // without the table loads they replace. The graphics prewarm prepares a recorded program the same way. + private static (EmbeddedVertexFetchPlan Fetch, ShaderVertexInput[] Inputs, Gen5ShaderProgram Program) PrepareEmbeddedFetch( + Gen5ShaderProgram program, VertexInputInfo info, uint userDataBase, uint userDataCount, ulong hash, ulong address) + { + var fetch = EmbeddedVertexFetchDetector.Detect(program, (int)userDataBase + info.FetchAttributeRegister, + (int)userDataBase + info.FetchBufferRegister, userDataBase, userDataCount, waveSize: 32); + return (fetch, BuildVertexInputs(fetch, info, hash, address), fetch.RemoveReplacedTableLoads(program)); + } + // One fixed-function input per fetched attribute; later loads of the same attribute alias the first. - private static ShaderVertexInput[] BuildVertexInputs(EmbeddedVertexFetchPlan fetch, VertexInputInfo info, ShaderSource source) + private static ShaderVertexInput[] BuildVertexInputs(EmbeddedVertexFetchPlan fetch, VertexInputInfo info, ulong hash, ulong address) { var inputs = new List(); var inputByLocation = new Dictionary(); @@ -1323,7 +1604,7 @@ private static ShaderVertexInput[] BuildVertexInputs(EmbeddedVertexFetchPlan fet if (location < 0) { throw SubmissionScheduler.Fatal( - $"The vertex program fetches an attribute the tables do not declare: hash=0x{source.Hash:X16} shader=0x{source.Address:X16} attribute={load.AttributeId} pc=0x{load.Pc:X}."); + $"The vertex program fetches an attribute the tables do not declare: hash=0x{hash:X16} shader=0x{address:X16} attribute={load.AttributeId} pc=0x{load.Pc:X}."); } var attribute = info.Attributes[location]; @@ -1350,13 +1631,13 @@ private static ShaderVertexInput[] BuildVertexInputs(EmbeddedVertexFetchPlan fet } throw SubmissionScheduler.Fatal( - $"The vertex program uses an unsupported attribute destination selector: hash=0x{source.Hash:X16} shader=0x{source.Address:X16} attribute={load.AttributeId} pc=0x{load.Pc:X} component={component} selector={selector}."); + $"The vertex program uses an unsupported attribute destination selector: hash=0x{hash:X16} shader=0x{address:X16} attribute={load.AttributeId} pc=0x{load.Pc:X} component={component} selector={selector}."); } if (requiredComponents == 0) { throw SubmissionScheduler.Fatal( - $"The vertex program fetches an attribute without a memory component: hash=0x{source.Hash:X16} shader=0x{source.Address:X16} attribute={load.AttributeId} pc=0x{load.Pc:X}."); + $"The vertex program fetches an attribute without a memory component: hash=0x{hash:X16} shader=0x{address:X16} attribute={load.AttributeId} pc=0x{load.Pc:X}."); } if (inputByLocation.TryGetValue(location, out var existingIndex)) @@ -1436,6 +1717,9 @@ private ProgramPermutation TakeDeferredPermutation(ShaderSource source, StageCom var (sharedInt64Atomics, execGuardElision, signedZeroInfNanPreserve, wave64Native, imageInt64Atomics) = (_host.SharedInt64AtomicsEnabled, _host.ExecGuardElisionEnabled, _host.ShaderSignedZeroInfNanPreserveFloat32Supported, _host.ComputeWave64SubgroupNative, _host.ImageInt64AtomicsEnabled); + var bufferInt64Atomics = _host.BufferInt64AtomicsEnabled; + var robustBufferAccess2 = _host.RobustBufferAccess2Enabled; + var nativeFloat16 = _host.NativeFloat16Conversions; var subgroup32 = _host.ComputeRunsOn32LaneSubgroups(current); var usesBufferLengths = source.Registered.Frontend?.RequiresExplicitBufferLengths ?? false; var tessellationHull = options.TessellationHull; @@ -1446,8 +1730,10 @@ private ProgramPermutation TakeDeferredPermutation(ShaderSource source, StageCom var layout = AllocateLayout(program, plan, resources, userDataBase, userDataCount, pushDataCursor, info.DispatchThreadDimensions, usesBufferLengths: usesBufferLengths, usesTessellationData: usesTessellationData); var request = BuildComputeRequest(plan, resources, layout, info, systemRegisters, sharedInt64Atomics, execGuardElision, - signedZeroInfNanPreserve, wave64Native, subgroup32, imageInt64Atomics, tessellationHull); - var translated = compiler.TryCompileProgram(request, out var compiled, out var error); + signedZeroInfNanPreserve, wave64Native, subgroup32, imageInt64Atomics, bufferInt64Atomics: bufferInt64Atomics, + robustBufferAccess2: robustBufferAccess2, nativeFloat16Conversions: nativeFloat16, tessellationHull: tessellationHull); + var translated = TranslationDiskCache.TryTranslate(compiler, request, + TranslationDiskCache.Key(key, userDataBase, specialization, pushDataCursor, request), out var compiled, out var error); return new DeferredTranslation(resources, layout, request, translated, compiled, error); })); throw new ShaderProgramPendingException(); @@ -1455,7 +1741,10 @@ private ProgramPermutation TakeDeferredPermutation(ShaderSource source, StageCom // Table blocks are for graphics stages: compute programs that read their buffers through them gave wrong results // or stalled, so compute programs keep descriptor buffer bindings. - private bool UsesTableBlocks(ShaderStage stage) => _host.TableBlocks && stage is not (ShaderStage.Compute or ShaderStage.Mesh); + private bool UsesTableBlocks(ShaderStage stage) => UsesTableBlocks(_host, stage); + + private static bool UsesTableBlocks(IShaderPipelineHost host, ShaderStage stage) => + host.TableBlocks && stage is not (ShaderStage.Compute or ShaderStage.Mesh); private ProgramPermutation CompilePermutation( ShaderSource source, @@ -1484,7 +1773,8 @@ private ProgramPermutation CompilePermutation( resources = ResourceMaterializer.ApplyTo(plan, specialization); layout = AllocateLayout(program, plan, resources, source.UserDataBase, (uint)source.UserData.Length, pushDataCursor, source.Stage == ShaderStage.Compute && options.ComputeInfo!.DispatchThreadDimensions, - usesMeshDrawParameters: source.Stage == ShaderStage.Mesh, tableBlocks: UsesTableBlocks(source.Stage), + usesMeshDrawParameters: source.Stage == ShaderStage.Mesh, pushDataAtTop: PushDataAtTop(source.Stage), + tableBlocks: UsesTableBlocks(source.Stage), usesBufferLengths: source.Registered.Frontend?.RequiresExplicitBufferLengths ?? false, usesTessellationData: options.Tessellation is not null || options.TessellationHull is not null); } @@ -1510,8 +1800,10 @@ private ProgramPermutation CompilePermutation( $"components={outputLocations * 4} limit={limits.MaxOutputComponents}."); var outputBytes = mesh.OutputMemoryBytes(parameterCount, limits.OutputPerVertexGranularity, limits.OutputPerPrimitiveGranularity); - if (outputBytes > limits.MaxOutputMemoryBytes || outputBytes > limits.MaxPayloadAndOutputMemoryBytes) - throw new ShaderProgramRejectedException($"The mesh output exceeds device memory limits: bytes={outputBytes} " + + // A task-launched program's payload counts in the payload-and-output limit. + var payloadBytes = mesh.TaskLaunched ? SharpEmu.ShaderCompiler.Vulkan.SpirvMeshTask.PayloadWordCount * 4 : 0u; + if (outputBytes > limits.MaxOutputMemoryBytes || outputBytes + payloadBytes > limits.MaxPayloadAndOutputMemoryBytes) + throw new ShaderProgramRejectedException($"The mesh output exceeds device memory limits: bytes={outputBytes} payload={payloadBytes} " + $"output_limit={limits.MaxOutputMemoryBytes} payload_output_limit={limits.MaxPayloadAndOutputMemoryBytes}."); } var permutationDump = ShaderPermutationDump.WriteInputs( @@ -1528,7 +1820,8 @@ private ProgramPermutation CompilePermutation( { using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramTranslation)) { - translated = _compiler.TryCompileProgram(request, out compiled, out error); + translated = TranslationDiskCache.TryTranslate(_compiler, request, + TranslationDiskCache.Key(key, source.UserDataBase, specialization, layout.AllocationCursor, request), out compiled, out error); } } @@ -1605,11 +1898,64 @@ private ProgramPermutation CompilePermutation( _compiler.CountShaderCompilation(); ShaderPermutationDump.WriteModule(permutationDump, compiled.Payload, compiled.PayloadFileExtension); CompiledShaderDump.Write(source.Label, source.Address, source.Hash, compiled, program); - var id = ++_nextProgramId; + var id = Interlocked.Increment(ref _nextProgramId); var module = _host.CreateShaderModule(compiled, source.Stage, source.Hash, id); var info = CreateProgramInfo(source, entry, resources, layout, request, compiled.InputLocationMask); + if (source.Stage == ShaderStage.Pixel) + { + _host.PixelProgramCreated(info, module); + if (_host.ShaderPrewarm is { } pixelPrewarm && options.PixelInfo is { } pixelInfo && !entry.HasShaderCalls && + _codeCaptures.TryGetValue((source.Hash, source.CodeSize, source.ContinuationAddressOffset), out var pixelCapture)) + { + var pixelRecord = new PixelPrewarmRecord + { + Hash = source.Hash, + CodeSize = source.CodeSize, + Address = pixelCapture.Address, + ContinuationAddressOffset = source.ContinuationAddressOffset, + UserDataBase = source.UserDataBase, + UserDataCount = (uint)source.UserData.Length, + PushDataCursor = pushDataCursor, + Info = pixelInfo, + Outputs = [.. options.PixelOutputs], + InputEnable = options.PixelInputEnable, + InputAddress = options.PixelInputAddress, + Specialization = specialization.Clone(), + DeviceRecordCounts = plan.DeviceRecordCounts is not null, + }; + pixelPrewarm.RecordPixel(pixelCapture, pixelRecord); + } + } + + // Vertex and mesh programs, for the graphics prewarm; the host records their parts' states under the identity. The + // part of a task-launched mesh program also takes the generic task stage, which its record determines (TaskLaunch). + if (source.Stage is ShaderStage.Vertex or ShaderStage.Mesh && _host.ShaderPrewarm is { } vertexPrewarm && + !entry.HasShaderCalls && + _codeCaptures.TryGetValue((source.Hash, source.CodeSize, source.ContinuationAddressOffset), out var vertexCapture)) + { + var identity = vertexPrewarm.RecordVertex(vertexCapture, new VertexPrewarmRecord + { + Mesh = source.Stage == ShaderStage.Mesh, + Hash = source.Hash, + CodeSize = source.CodeSize, + Address = vertexCapture.Address, + ContinuationAddressOffset = source.ContinuationAddressOffset, + UserDataBase = source.UserDataBase, + UserDataCount = (uint)source.UserData.Length, + PushDataCursor = layout.AllocationCursor, + VertexInfo = options.VertexInfo, + MeshInfo = options.MeshInfo, + RequiredVertexOutputCount = options.RequiredVertexOutputCount, + MeshOutputLocationMask = options.MeshOutputLocationMask, + Specialization = specialization.Clone(), + DeviceRecordCounts = plan.DeviceRecordCounts is not null, + }); + _host.VertexProgramRecorded(module, identity); + } + if (source.Stage == ShaderStage.Compute && options.TessellationHull is null && _host.ShaderPrewarm is { } prewarm && + (!Gen5ShaderCallLinker.IsLinked(program) || entry.LinkedPrewarm is not null) && _codeCaptures.TryGetValue((source.Hash, source.CodeSize, source.ContinuationAddressOffset), out var capture)) { prewarm.RecordCompute(capture, new ComputePrewarmRecord @@ -1624,6 +1970,8 @@ _host.ShaderPrewarm is { } prewarm && Info = options.ComputeInfo!, SystemRegisters = options.ComputeSystemRegisters, Specialization = specialization.Clone(), + Linked = entry.LinkedPrewarm, + DeviceRecordCounts = plan.DeviceRecordCounts is not null, }); } @@ -1655,7 +2003,113 @@ _host.ShaderPrewarm is { } stagePrewarm && Specialization = specialization, Program = info, Handle = new ShaderProgram(id, module), - Compiled = compiled, + }; + } + + // The vertex or domain request of a program; the prewarm (TryCompileVertexPrewarm) builds the same one. + private static ShaderCompileRequest BuildVertexRequest(IShaderPipelineHost host, ShaderResourcePlan plan, + SpecializedResourceInfo resources, BindingLayout layout, StageCompileOptions options, ShaderVertexInput[] vertexInputs, + bool tessellationEvaluation = false) + { + var info = options.VertexInfo!; + return new ShaderCompileRequest(plan, resources, layout) + { + WaveSize = 32, + TraceDeviceAddressFaults = SharpEmu.HLE.GpuMemory.GuestGpuMemoryHook.TraceEnabled, + IeeeMode = info.IeeeMode, + ScratchDwords = info.ScratchDwords, + EnableGraphicsSubgroupOperations = !tessellationEvaluation && host.GraphicsSubgroupOperationsEnabled, + SupportsSharedInt64Atomics = host.SharedInt64AtomicsEnabled, + SupportsImageInt64Atomics = host.ImageInt64AtomicsEnabled, + SupportsBufferInt64Atomics = host.BufferInt64AtomicsEnabled, + SupportsShaderDeviceClock = host.ShaderDeviceClockEnabled, + ShaderSignedZeroInfNanPreserveFloat32Supported = host.ShaderSignedZeroInfNanPreserveFloat32Supported, + RobustBufferAccess2 = host.RobustBufferAccess2Enabled, + NativeFloat16Conversions = host.NativeFloat16Conversions, + RequiredVertexOutputCount = options.RequiredVertexOutputCount, + Tessellation = options.Tessellation, + VertexInputs = vertexInputs, + PositionExportControl = info.PositionExportControl, + SupportsClipDistance = host.ClipDistanceEnabled, + SupportsDrawParameters = host.ShaderDrawParametersSupported, + StartInstanceUserData = info.StartInstanceUserData, + ClipSpace = new ShaderClipSpaceTransform( + info.ClipSpace.Enabled, + info.ClipSpace.ScaleX, + info.ClipSpace.ScaleY, + info.ClipSpace.OffsetX, + info.ClipSpace.OffsetY, + info.ClipSpace.HalfExtentX, + info.ClipSpace.HalfExtentY), + }; + } + + // The mesh request of a program; the prewarm (TryCompileVertexPrewarm) builds the same one. + private static ShaderCompileRequest BuildMeshRequest(IShaderPipelineHost host, ShaderResourcePlan plan, + SpecializedResourceInfo resources, BindingLayout layout, StageCompileOptions options) + { + var info = options.MeshInfo!; + return new ShaderCompileRequest(plan, resources, layout) + { + WaveSize = info.Geometry.WaveSize, + TraceDeviceAddressFaults = SharpEmu.HLE.GpuMemory.GuestGpuMemoryHook.TraceEnabled, + IeeeMode = info.Geometry.IeeeMode, + ScratchDwords = info.Geometry.ScratchDwords, + EnableGraphicsSubgroupOperations = host.GraphicsSubgroupOperationsEnabled, + SupportsImageInt64Atomics = host.ImageInt64AtomicsEnabled, + SupportsBufferInt64Atomics = host.BufferInt64AtomicsEnabled, + SupportsShaderDeviceClock = host.ShaderDeviceClockEnabled, + RobustBufferAccess2 = host.RobustBufferAccess2Enabled, + NativeFloat16Conversions = host.NativeFloat16Conversions, + RequiredVertexOutputCount = options.RequiredVertexOutputCount, + PositionExportControl = info.Geometry.PositionExportControl, + MeshOutputLocationMask = options.MeshOutputLocationMask, + ClipSpace = new ShaderClipSpaceTransform( + info.Geometry.ClipSpace.Enabled, + info.Geometry.ClipSpace.ScaleX, + info.Geometry.ClipSpace.ScaleY, + info.Geometry.ClipSpace.OffsetX, + info.Geometry.ClipSpace.OffsetY, + info.Geometry.ClipSpace.HalfExtentX, + info.Geometry.ClipSpace.HalfExtentY), + LocalSizeX = info.Geometry.ThreadsPerGroup, + Mesh = new MeshShaderConfiguration(info.Geometry.OutputVertexCapacity, info.Geometry.OutputPrimitiveCapacity, + info.Geometry.ProvokingVertex, info.Geometry.InputPrimitiveCountPerWorkgroup, info.Geometry.InputVertexCountPerWorkgroup, + info.Geometry.LocalDataShareDwords, info.Geometry.InputTriangleStrip, info.Execution.DeviceSubgroupLaneCount, + info.Geometry.InputPointList, info.Geometry.InputLineList, TaskLaunched: info.Geometry.TaskLaunched), + }; + } + + // The pixel request of a program; the prewarm (TryCompilePixelPrewarm) builds the same one. + private static ShaderCompileRequest BuildPixelRequest(IShaderPipelineHost host, ShaderResourcePlan plan, + SpecializedResourceInfo resources, BindingLayout layout, StageCompileOptions options) + { + var info = options.PixelInfo!; + var interpolators = new uint[info.InputCount]; + Array.Copy(info.InterpolatorSettings, interpolators, interpolators.Length); + return new ShaderCompileRequest(plan, resources, layout) + { + WaveSize = 32, + TraceDeviceAddressFaults = SharpEmu.HLE.GpuMemory.GuestGpuMemoryHook.TraceEnabled, + IeeeMode = info.IeeeMode, + ScratchDwords = info.ScratchDwords, + EnableGraphicsSubgroupOperations = host.GraphicsSubgroupOperationsEnabled, + SupportsSharedInt64Atomics = host.SharedInt64AtomicsEnabled, + SupportsImageInt64Atomics = host.ImageInt64AtomicsEnabled, + SupportsBufferInt64Atomics = host.BufferInt64AtomicsEnabled, + SupportsShaderDeviceClock = host.ShaderDeviceClockEnabled, + ShaderSignedZeroInfNanPreserveFloat32Supported = host.ShaderSignedZeroInfNanPreserveFloat32Supported, + RobustBufferAccess2 = host.RobustBufferAccess2Enabled, + NativeFloat16Conversions = host.NativeFloat16Conversions, + PixelOutputs = options.PixelOutputs, + PixelDepthExportEnable = info.DepthExportEnable, + PixelInputEnable = options.PixelInputEnable, + PixelCustomInterpolationMask = info.CustomInterpolationMask, + SupportsPerVertexPixelInputs = host.PerVertexPixelInputsSupported, + PixelInputAddress = options.PixelInputAddress, + PixelInputCntl = interpolators, + MipStatisticsSubgroupReduction = host.MipStatisticsSubgroupReduction, + SubgroupArithmetic = host.PixelSubgroupArithmetic, }; } @@ -1666,110 +2120,39 @@ private ShaderCompileRequest BuildRequest( SpecializedResourceInfo resources, BindingLayout layout) { - var enableGraphicsSubgroups = _host.GraphicsSubgroupOperationsEnabled; var sharedInt64Atomics = _host.SharedInt64AtomicsEnabled; var imageInt64Atomics = _host.ImageInt64AtomicsEnabled; + var bufferInt64Atomics = _host.BufferInt64AtomicsEnabled; + var shaderDeviceClock = _host.ShaderDeviceClockEnabled; var signedZeroInfNanPreserve = _host.ShaderSignedZeroInfNanPreserveFloat32Supported; switch (source.Stage) { case ShaderStage.Vertex: case ShaderStage.TessellationEvaluation: - { - var info = options.VertexInfo!; - return new ShaderCompileRequest(entry.Plan, resources, layout) - { - WaveSize = 32, - TraceDeviceAddressFaults = SharpEmu.HLE.GpuMemory.GuestGpuMemoryHook.TraceEnabled, - IeeeMode = info.IeeeMode, - ScratchDwords = info.ScratchDwords, - EnableGraphicsSubgroupOperations = source.Stage != ShaderStage.TessellationEvaluation && enableGraphicsSubgroups, - SupportsSharedInt64Atomics = sharedInt64Atomics, - SupportsImageInt64Atomics = imageInt64Atomics, - ShaderSignedZeroInfNanPreserveFloat32Supported = signedZeroInfNanPreserve, - RequiredVertexOutputCount = options.RequiredVertexOutputCount, - Tessellation = options.Tessellation, - VertexInputs = entry.VertexInputs, - PositionExportControl = info.PositionExportControl, - SupportsClipDistance = _host.ClipDistanceEnabled, - SupportsDrawParameters = _host.ShaderDrawParametersSupported, - StartInstanceUserData = info.StartInstanceUserData, - ClipSpace = new ShaderClipSpaceTransform( - info.ClipSpace.Enabled, - info.ClipSpace.ScaleX, - info.ClipSpace.ScaleY, - info.ClipSpace.OffsetX, - info.ClipSpace.OffsetY, - info.ClipSpace.HalfExtentX, - info.ClipSpace.HalfExtentY), - }; - } + return BuildVertexRequest(_host, entry.Plan, resources, layout, options, entry.VertexInputs, + tessellationEvaluation: source.Stage == ShaderStage.TessellationEvaluation); case ShaderStage.Pixel: - { - var info = options.PixelInfo!; - var interpolators = new uint[info.InputCount]; - Array.Copy(info.InterpolatorSettings, interpolators, interpolators.Length); - return new ShaderCompileRequest(entry.Plan, resources, layout) - { - WaveSize = 32, - TraceDeviceAddressFaults = SharpEmu.HLE.GpuMemory.GuestGpuMemoryHook.TraceEnabled, - IeeeMode = info.IeeeMode, - ScratchDwords = info.ScratchDwords, - EnableGraphicsSubgroupOperations = enableGraphicsSubgroups, - SupportsSharedInt64Atomics = sharedInt64Atomics, - SupportsImageInt64Atomics = imageInt64Atomics, - ShaderSignedZeroInfNanPreserveFloat32Supported = signedZeroInfNanPreserve, - PixelOutputs = options.PixelOutputs, - PixelDepthExportEnable = info.DepthExportEnable, - PixelInputEnable = options.PixelInputEnable, - PixelCustomInterpolationMask = info.CustomInterpolationMask, - SupportsPerVertexPixelInputs = _host.PerVertexPixelInputsSupported, - PixelInputAddress = options.PixelInputAddress, - PixelInputCntl = interpolators, - MipStatisticsSubgroupReduction = _host.MipStatisticsSubgroupReduction, - }; - } + return BuildPixelRequest(_host, entry.Plan, resources, layout, options); case ShaderStage.Mesh: - { - var info = options.MeshInfo!; - return new ShaderCompileRequest(entry.Plan, resources, layout) - { - WaveSize = info.Geometry.WaveSize, - TraceDeviceAddressFaults = SharpEmu.HLE.GpuMemory.GuestGpuMemoryHook.TraceEnabled, - IeeeMode = info.Geometry.IeeeMode, - ScratchDwords = info.Geometry.ScratchDwords, - EnableGraphicsSubgroupOperations = enableGraphicsSubgroups, - SupportsImageInt64Atomics = imageInt64Atomics, - RequiredVertexOutputCount = options.RequiredVertexOutputCount, - PositionExportControl = info.Geometry.PositionExportControl, - MeshOutputLocationMask = options.MeshOutputLocationMask, - ClipSpace = new ShaderClipSpaceTransform( - info.Geometry.ClipSpace.Enabled, - info.Geometry.ClipSpace.ScaleX, - info.Geometry.ClipSpace.ScaleY, - info.Geometry.ClipSpace.OffsetX, - info.Geometry.ClipSpace.OffsetY, - info.Geometry.ClipSpace.HalfExtentX, - info.Geometry.ClipSpace.HalfExtentY), - LocalSizeX = info.Geometry.ThreadsPerGroup, - Mesh = new MeshShaderConfiguration(info.Geometry.OutputVertexCapacity, info.Geometry.OutputPrimitiveCapacity, - info.Geometry.ProvokingVertex, info.Geometry.InputPrimitiveCountPerWorkgroup, info.Geometry.InputVertexCountPerWorkgroup, - info.Geometry.LocalDataShareDwords, info.Geometry.InputTriangleStrip, info.Execution.DeviceSubgroupLaneCount, - info.Geometry.InputPointList, info.Geometry.InputLineList), - }; - } + return BuildMeshRequest(_host, entry.Plan, resources, layout, options); default: return BuildComputeRequest(entry.Plan, resources, layout, options.ComputeInfo!, options.ComputeSystemRegisters, sharedInt64Atomics, _host.ExecGuardElisionEnabled, signedZeroInfNanPreserve, _host.ComputeWave64SubgroupNative, - _host.ComputeRunsOn32LaneSubgroups(options.ComputeInfo!), imageInt64Atomics, options.TessellationHull); + _host.ComputeRunsOn32LaneSubgroups(options.ComputeInfo!), imageInt64Atomics, shaderDeviceClock, + bufferInt64Atomics, _host.RobustBufferAccess2Enabled, _host.NativeFloat16Conversions, options.TessellationHull); } } + // The budget within which a program's images bind one per slot, whatever descriptors a draw repeats (StableImageBindings). + private static StableImageDescriptorLimits StableImageLimits(IShaderPipelineHost host, ShaderStage stage) => + stage == ShaderStage.Compute ? host.ComputeImageDescriptorLimits : host.GraphicsImageDescriptorLimits; + private static BindingLayout AllocateLayout(Gen5ShaderProgram program, ShaderResourcePlan plan, SpecializedResourceInfo resources, uint userDataBase, uint userDataCount, uint pushDataCursor, bool usesDispatchThreadLimits, bool usesMeshDrawParameters = false, - bool usesBufferLengths = false, bool usesTessellationData = false, bool tableBlocks = false) => + bool pushDataAtTop = false, bool usesBufferLengths = false, bool usesTessellationData = false, bool tableBlocks = false) => BindingLayout.Allocate( resources.Info, BindingLayout.CollectUserDataRegisters(program, userDataBase, userDataCount, plan.Graph.ExcludedUserDataRegisters), @@ -1781,13 +2164,15 @@ private static BindingLayout AllocateLayout(Gen5ShaderProgram program, ShaderRes usesMeshDrawParameters: usesMeshDrawParameters, callArgumentCount: BindingLayout.CountCallArguments(program), callTargetCount: BindingLayout.CountCallTargets(program), + pushDataAtTop: pushDataAtTop, usesBufferLengths: usesBufferLengths, usesTessellationData: usesTessellationData, tableBlock: tableBlocks); private static ShaderCompileRequest BuildComputeRequest(ShaderResourcePlan plan, SpecializedResourceInfo resources, BindingLayout layout, ComputeInputInfo info, Gen5ComputeSystemRegisters? systemRegisters, bool sharedInt64Atomics, bool execGuardElision, bool signedZeroInfNanPreserve, bool hostWave64Supported = false, bool hostComputeSubgroup32 = false, - bool imageInt64Atomics = false, Gen5TessellationHullInfo? tessellationHull = null) => + bool imageInt64Atomics = false, bool shaderDeviceClock = false, bool bufferInt64Atomics = false, + bool robustBufferAccess2 = false, bool nativeFloat16Conversions = false, Gen5TessellationHullInfo? tessellationHull = null) => new(plan, resources, layout) { WaveSize = info.WaveSize, @@ -1801,7 +2186,11 @@ private static ShaderCompileRequest BuildComputeRequest(ShaderResourcePlan plan, ScratchDwords = info.ScratchDwords, SupportsSharedInt64Atomics = sharedInt64Atomics, SupportsImageInt64Atomics = imageInt64Atomics, + SupportsBufferInt64Atomics = bufferInt64Atomics, + SupportsShaderDeviceClock = shaderDeviceClock, ShaderSignedZeroInfNanPreserveFloat32Supported = signedZeroInfNanPreserve, + RobustBufferAccess2 = robustBufferAccess2, + NativeFloat16Conversions = nativeFloat16Conversions, ComputeSystemRegisters = systemRegisters, LocalDataShareDwords = info.LocalDataShareDwords, LocalSizeX = Math.Max(info.ThreadsX, 1), @@ -1812,7 +2201,9 @@ private static ShaderCompileRequest BuildComputeRequest(ShaderResourcePlan plan, internal static bool TryCompilePrewarm(ComputePrewarmRecord record, ShaderCodeCapture code, IGuestGpuBackend compiler, bool sharedInt64Atomics, bool execGuardElision, bool signedZeroInfNanPreserve, out IGuestCompiledShader? compiled, out BindingLayout? layout, out string error, bool hostWave64Supported = false, bool hostComputeSubgroup32 = false, - bool imageInt64Atomics = false, bool tableBlocks = false, Func? frontendOf = null) + bool imageInt64Atomics = false, bool shaderDeviceClock = false, bool bindlessHeap = false, + StableImageDescriptorLimits stableImageLimits = default, bool bufferInt64Atomics = false, bool robustBufferAccess2 = false, + bool nativeFloat16Conversions = false, bool tableBlocks = false, Func? frontendOf = null) { compiled = null; layout = null; @@ -1844,18 +2235,33 @@ internal static bool TryCompilePrewarm(ComputePrewarmRecord record, ShaderCodeCa return false; } + var linked = record.Linked; + if (linked is not null) + { + if (linked.BindlessHeap != bindlessHeap) + throw new InvalidOperationException("The linked prewarm binding policy differs from the host."); + program = linked.Link(program); + } + if (program.Instructions.Any(instruction => instruction.Opcode == "SSwappcB64")) + throw new InvalidOperationException("The prewarm program has unresolved shader calls."); var plan = ShaderResourcePlan.Extract(program, ShaderStage.Compute, record.Hash, record.UserDataBase, record.UserDataCount, - waveSize: record.Info.WaveSize, + waveSize: record.Info.WaveSize, bindlessNullDescriptors: BindlessNullDescriptors, bindlessHeap: bindlessHeap, + // Match LinkProgram's extraction policy; linked plans currently do not use stable image tables. + stableImageLimits: linked is null ? stableImageLimits : default, + callRecords: linked?.RuntimeRecords ?? false, callMarks: linked?.CallMarks ?? false, + deviceRecordCounts: record.DeviceRecordCounts, normalizeBufferDescriptor: frontend?.NormalizeBufferDescriptor, normalizeImageDescriptor: frontend?.NormalizeImageDescriptor, imageNormalizationVersion: frontend?.ImageNormalizationVersion); - var resources = ResourceMaterializer.ApplyTo(plan, record.Specialization); + // A record's storage image selects as the session keeps them (RuntimeImageSwizzle.Canonical). + var specialization = RuntimeImageSwizzle.Canonical(plan, record.Specialization); + var resources = ResourceMaterializer.ApplyTo(plan, specialization); layout = AllocateLayout(program, plan, resources, record.UserDataBase, record.UserDataCount, record.PushDataCursor, record.Info.DispatchThreadDimensions, usesBufferLengths: frontend?.RequiresExplicitBufferLengths ?? false, tableBlocks: tableBlocks); var request = BuildComputeRequest(plan, resources, layout, record.Info, record.SystemRegisters, sharedInt64Atomics, execGuardElision, signedZeroInfNanPreserve, hostWave64Supported, hostComputeSubgroup32, - imageInt64Atomics); + imageInt64Atomics, shaderDeviceClock, bufferInt64Atomics, robustBufferAccess2, nativeFloat16Conversions); return compiler.TryCompileProgram(request, out compiled, out error) && compiled is not null; } catch (Exception exception) @@ -1865,6 +2271,127 @@ internal static bool TryCompilePrewarm(ComputePrewarmRecord record, ShaderCodeCa } } + // A recorded pixel program translated again as its session translated it (CreateEntry, then the specialized + // translation through the translation cache); the caller compiles its pixel library. + internal static bool TryCompilePixelPrewarm(PixelPrewarmRecord record, ShaderCodeCapture code, IGuestGpuBackend compiler, + IShaderPipelineHost host, out IGuestCompiledShader? compiled, out BindingLayout? layout, out string error) + { + compiled = null; + layout = null; + try + { + if (!Gen5ShaderTranslator.TryDecodeProgram(code.CreateContext(), code.Address, out var program, out error)) + { + return false; + } + + if (program.Instructions.Any(static instruction => instruction.Opcode == "SSwappcB64")) + { + error = "the recorded pixel program has shader calls"; + return false; + } + + var plan = ShaderResourcePlan.Extract(program, ShaderStage.Pixel, record.Hash, record.UserDataBase, record.UserDataCount, + waveSize: 32, bindlessNullDescriptors: BindlessNullDescriptors, bindlessHeap: host.SupportsBindlessHeap, + stableImageLimits: host.GraphicsImageDescriptorLimits, + deviceRecordCounts: DeviceRecordCountPlan.Enabled && record.DeviceRecordCounts); + // A record's storage image selects as the session keeps them (RuntimeImageSwizzle.Canonical). + var specialization = RuntimeImageSwizzle.Canonical(plan, record.Specialization); + var resources = ResourceMaterializer.ApplyTo(plan, specialization); + layout = AllocateLayout(program, plan, resources, record.UserDataBase, record.UserDataCount, record.PushDataCursor, false, + tableBlocks: UsesTableBlocks(host, ShaderStage.Pixel)); + var options = new StageCompileOptions + { + PixelInfo = record.Info, + PixelOutputs = record.Outputs, + PixelInputEnable = record.InputEnable, + PixelInputAddress = record.InputAddress, + }; + var request = BuildPixelRequest(host, plan, resources, layout, options); + var state = new List(); + BuildStaticState(ShaderStage.Pixel, options, state); + var key = new ProgramKey(ShaderStage.Pixel, record.Hash, record.UserDataCount, record.CodeSize, + record.ContinuationAddressOffset, [.. state]); + return TranslationDiskCache.TryTranslate(compiler, request, + TranslationDiskCache.Key(key, record.UserDataBase, specialization, record.PushDataCursor, request), + out compiled, out error) && compiled is not null; + } + catch (Exception exception) + { + error = exception.Message; + return false; + } + } + + // A recorded vertex or mesh program translated again as its session translated it (CreateEntry, then the specialized + // translation through the translation cache), with the task launch of a task-launched mesh program; the caller compiles + // its pre-rasterization libraries. + internal static bool TryCompileVertexPrewarm(VertexPrewarmRecord record, ShaderCodeCapture code, IGuestGpuBackend compiler, + IShaderPipelineHost host, out IGuestCompiledShader? compiled, out BindingLayout? layout, out MeshTaskLaunchInfo? task, + out string error) + { + compiled = null; + layout = null; + task = null; + try + { + if (!Gen5ShaderTranslator.TryDecodeProgram(code.CreateContext(), code.Address, out var program, out error)) + { + return false; + } + + if (program.Instructions.Any(static instruction => instruction.Opcode == "SSwappcB64")) + { + error = "the recorded vertex program has shader calls"; + return false; + } + + var stage = record.Mesh ? ShaderStage.Mesh : ShaderStage.Vertex; + var options = new StageCompileOptions + { + VertexInfo = record.VertexInfo, + MeshInfo = record.MeshInfo, + RequiredVertexOutputCount = record.RequiredVertexOutputCount, + MeshOutputLocationMask = record.MeshOutputLocationMask, + }; + EmbeddedVertexFetchPlan? fetch = null; + ShaderVertexInput[] vertexInputs = []; + if (!record.Mesh && record.VertexInfo is { FetchEmbedded: true } vertexInfo) + { + (fetch, vertexInputs, program) = PrepareEmbeddedFetch(program, vertexInfo, record.UserDataBase, record.UserDataCount, + record.Hash, record.Address); + } + + var plan = ShaderResourcePlan.Extract(program, stage, record.Hash, record.UserDataBase, record.UserDataCount, + fetch?.Loads.Select(load => load.Pc).ToHashSet(), waveSize: record.Mesh ? record.MeshInfo!.Geometry.WaveSize : 32u, + dynamicUserData: record.VertexInfo?.StartInstanceUserData ?? -1, + bindlessNullDescriptors: BindlessNullDescriptors, bindlessHeap: host.SupportsBindlessHeap, + stableImageLimits: host.GraphicsImageDescriptorLimits, + deviceRecordCounts: DeviceRecordCountPlan.Enabled && record.DeviceRecordCounts); + // A record's storage image selects as the session keeps them (RuntimeImageSwizzle.Canonical). + var specialization = RuntimeImageSwizzle.Canonical(plan, record.Specialization); + var resources = ResourceMaterializer.ApplyTo(plan, specialization); + layout = AllocateLayout(program, plan, resources, record.UserDataBase, record.UserDataCount, record.PushDataCursor, false, + usesMeshDrawParameters: record.Mesh, pushDataAtTop: PushDataAtTop(stage), tableBlocks: UsesTableBlocks(host, stage)); + var request = record.Mesh + ? BuildMeshRequest(host, plan, resources, layout, options) + : BuildVertexRequest(host, plan, resources, layout, options, vertexInputs); + task = TaskLaunch(request); + var state = new List(); + BuildStaticState(stage, options, state); + var key = new ProgramKey(stage, record.Hash, record.UserDataCount, record.CodeSize, record.ContinuationAddressOffset, + [.. state]); + return TranslationDiskCache.TryTranslate(compiler, request, + TranslationDiskCache.Key(key, record.UserDataBase, specialization, layout.AllocationCursor, request), + out compiled, out error) && compiled is not null; + } + catch (Exception exception) + { + error = exception.Message; + return false; + } + } + // A fill kernel computes its thread index, moves one constant into a VGPR and stores it once. internal static uint? FindConstantStoreValue(Gen5ShaderProgram program) { @@ -1958,7 +2485,7 @@ private static ShaderProgramInfo CreateProgramInfo( for (var index = 0; index < buffers.Length; index++) { var buffer = info.Buffers[index]; - buffers[index] = new BufferResourceInfo(buffer.Read, buffer.Written, buffer.Atomic, buffer.Formatted, buffer.Scalar, buffer.MaxByteExtent, buffer.PackedStride); + buffers[index] = new BufferResourceInfo(buffer.Read, buffer.Written, buffer.Atomic, buffer.Formatted, buffer.Scalar, buffer.MaxByteExtent); } var images = new ImageResourceInfo[info.Images.Count]; @@ -2021,8 +2548,14 @@ private static ShaderProgramInfo CreateProgramInfo( Resources = resources, Bindings = layout, CallRecordCallees = request.CallRecordCallees, + MeshTask = TaskLaunch(request), }; } + + // What a task-launched mesh program's pipelines specialize the generic task stage with; the prewarm takes the same. + internal static MeshTaskLaunchInfo? TaskLaunch(ShaderCompileRequest request) => request.Mesh is { TaskLaunched: true } mesh + ? new MeshTaskLaunchInfo(mesh.InputPrimitiveCountPerWorkgroup, mesh.InputPointList) + : null; } // Writes each compiled module and its decoded listing when the dump switch is on. diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/SliceDescriptorHeap.cs b/src/SharpEmu.Libs/Gpu/Pipelines/SliceDescriptorHeap.cs new file mode 100644 index 000000000..2f2a1a56c --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/Pipelines/SliceDescriptorHeap.cs @@ -0,0 +1,163 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections.Concurrent; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Gpu.Scheduling; +using Silk.NET.Vulkan; + +namespace SharpEmu.Libs.Gpu.Pipelines; + +public sealed unsafe class DescriptorPoolStock : IDisposable +{ + private readonly GpuDeviceInfo _device; + private readonly ConcurrentBag _free = new(); + private readonly List _all = new(); + private bool _disposed; + + public DescriptorPoolStock(GpuDeviceInfo device) + { + _device = device; + } + + public DescriptorPool Rent() + { + if (_free.TryTake(out var pool)) + { + return pool; + } + + pool = DescriptorHeap.CreatePool(_device); + lock (_all) + { + _all.Add(pool); + } + + return pool; + } + + public void Return(DescriptorPool pool) + { + lock (_all) + { + if (_disposed) + { + return; + } + + var reset = _device.Vk.ResetDescriptorPool(_device.Device, pool, 0); + if (reset != Result.Success) + { + throw SubmissionScheduler.Fatal($"vkResetDescriptorPool failed: result={reset}."); + } + } + + _free.Add(pool); + } + + public void Dispose() + { + lock (_all) + { + if (_disposed) + { + return; + } + + _disposed = true; + foreach (var pool in _all) + { + _device.Vk.DestroyDescriptorPool(_device.Device, pool, null); + } + + _all.Clear(); + } + + while (_free.TryTake(out _)) + { + } + } +} + +public sealed class SliceDescriptorHeap(GpuDeviceInfo device, DescriptorPoolStock stock) +{ + private sealed class SetBatchState + { + public readonly DescriptorSet[] Sets = new DescriptorSet[DescriptorHeap.SetBatch]; + public uint Size; + public uint Allocation = DescriptorHeap.SetBatch; + } + + private readonly Dictionary _sets = new(); + private readonly List _pools = new(); + private DescriptorPool _currentPool; + private DescriptorSetDemand _remaining; + private uint _remainingSets; + + public DescriptorSet Commit(DescriptorSetLayout layout, in DescriptorSetDemand demand) + { + if (layout.Handle == 0) + { + throw SubmissionScheduler.Fatal("The slice descriptor heap needs a set layout."); + } + + if (!_sets.TryGetValue(layout.Handle, out var batch)) + { + batch = new SetBatchState(); + _sets.Add(layout.Handle, batch); + } + + if (batch.Size != 0) + { + return batch.Sets[--batch.Size]; + } + + if (_currentPool.Handle != 0 && Allocate(layout, in demand, batch)) + { + return batch.Sets[--batch.Size]; + } + + _currentPool = stock.Rent(); + _pools.Add(_currentPool); + _remaining = DescriptorHeap.PoolCapacity; + _remainingSets = DescriptorHeap.SetsPerPool; + batch.Allocation = DescriptorHeap.SetBatch; + if (!Allocate(layout, in demand, batch)) + { + throw SubmissionScheduler.Fatal( + $"The slice descriptor heap cannot allocate a set from a fresh pool: buffers={demand.StorageBuffers} sampled={demand.SampledImages} storage={demand.StorageImages} samplers={demand.Samplers}."); + } + + return batch.Sets[--batch.Size]; + } + + public List TakePools() + { + if (_pools.Count == 0) + { + return []; + } + + var taken = new List(_pools); + _pools.Clear(); + _currentPool = default; + foreach (var batch in _sets.Values) + { + batch.Size = 0; + batch.Allocation = DescriptorHeap.SetBatch; + } + + return taken; + } + + private bool Allocate(DescriptorSetLayout layout, in DescriptorSetDemand demand, SetBatchState batch) + { + if (!DescriptorHeap.TryAllocateBatch(device, _currentPool, layout, in demand, batch.Sets, ref batch.Allocation, ref _remainingSets, ref _remaining)) + { + return false; + } + + batch.Size = batch.Allocation; + return true; + } +} diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/StageStaticKey.cs b/src/SharpEmu.Libs/Gpu/Pipelines/StageStaticKey.cs index 1bd3ccddf..4c48ce58f 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/StageStaticKey.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/StageStaticKey.cs @@ -127,8 +127,16 @@ public static void Build(MeshDrawConfiguration info, int requiredOutputCount, Li key.Add(Bits(info.Geometry.ClipSpace.HalfExtentX)); key.Add(Bits(info.Geometry.ClipSpace.HalfExtentY)); } + + // A task-launched program is another translation; the keys of the others are unchanged. + if (info.Geometry.TaskLaunched) + { + key.Add(TaskLaunchedMark); + } } + private const uint TaskLaunchedMark = 0x7A5C1A0Du; + // The dispatch mode is static; exact thread limits arrive with each dispatch. public static void Build(ComputeInputInfo info, List key) { @@ -148,5 +156,10 @@ public static void Build(ComputeInputInfo info, List key) key.Add(info.ThreadsZ); key.Add(Bit(info.GroupIdZ)); key.Add(Bit(info.ThreadGroupSizeEnabled)); + // A program whose thread counts are in GPU memory keeps its shader data out of push data. + if (info.IndirectThreadCounts) + { + key.Add(1); + } } } diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/TranslationDiskCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/TranslationDiskCache.cs new file mode 100644 index 000000000..584fe592c --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/Pipelines/TranslationDiskCache.cs @@ -0,0 +1,444 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections; +using System.IO.Compression; +using System.Reflection; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.Libs.Gpu.Pipelines; + +// SHARPEMU_TRANSLATION_CACHE=0 turns it off. Each game keeps the programs it translated on disk, so a later session +// takes a program's SPIR-V from disk instead of translating it again. The key is everything the translation reads: the +// translated program's instructions, every field of the request (pipeline state, specialization, binding layout, memory +// plan), the program cache key with its static state, the builds of the three assemblies that plan and translate, the +// device's translation stamp and the SHARPEMU_ variables that are not paths, dumps, logs or profiles. A change +// therefore misses; it never serves another program. +internal static class TranslationDiskCache +{ + private const int Version = 1; + private const string Extension = ".spvc"; + private const int MaxEntryBytes = 64 * 1024 * 1024; + // 8 GiB per game, trimmed by last use: a game's opening alone can keep hundreds of megabytes of live translations + // and play keeps adding programs, so a small cap would soon evict what a replay of the early game needs. + private const long MaxCacheBytes = 8L * 1024 * 1024 * 1024; + // Each build keeps its entries in its own folder (no key of one build can hit in another). A game folder keeps the + // builds used last (two builds used in turn, or a rollback) and deletes the rest, so a new build leaves no dead + // entries under the cap. + private const int KeptBuilds = 2; + private const long TrimTargetBytes = MaxCacheBytes / 10 * 9; + private static readonly string Mode = Environment.GetEnvironmentVariable("SHARPEMU_TRANSLATION_CACHE") ?? "1"; + public static readonly bool Enabled = Mode == "1"; + private static readonly JsonSerializerOptions Json = new() + { + ReferenceHandler = ReferenceHandler.IgnoreCycles, + MaxDepth = 64, + NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals, + }; + // Every request field but the program (written instruction by instruction). + private static readonly PropertyInfo[] RequestProperties = typeof(ShaderCompileRequest) + .GetProperties(BindingFlags.Public | BindingFlags.Instance) + .Where(static property => property.GetIndexParameters().Length == 0 && + property.Name != nameof(ShaderCompileRequest.Program)) + .OrderBy(static property => property.Name, StringComparer.Ordinal) + .ToArray(); + private static readonly string[] Builds = + [ + typeof(ShaderCompileRequest).Module.ModuleVersionId.ToString("N"), + typeof(SharpEmu.ShaderCompiler.Vulkan.Gen5SpirvTranslator).Module.ModuleVersionId.ToString("N"), + typeof(TranslationDiskCache).Module.ModuleVersionId.ToString("N"), + ]; + private static readonly (string Name, string Value)[] Variables = Environment.GetEnvironmentVariables() + .Cast() + .Select(static entry => (Name: ((string)entry.Key).ToUpperInvariant(), Value: (string?)entry.Value ?? "")) + .Where(static entry => entry.Name.StartsWith("SHARPEMU_", StringComparison.Ordinal) && !IgnoredVariable(entry.Name)) + .OrderBy(static entry => entry.Name, StringComparer.Ordinal) + .ToArray(); + // S_GETPC reads the shader base from push data, so one module serves every load address, and the translator's one + // other read of the address (ProgramAddress) makes a call's return address, which its control holds in the key, + // relative to the program. Only the translator's debugging switches that change the shaders at chosen addresses + // (each compares Program.Address in Gen5SpirvTranslator) make the address part of every key. A test of the names + // (TITLE, CAPTURE, ADDRESS) would also take switches that never touch a shader and put each program's load address + // in its key, so a program that loads elsewhere in each session would miss its translation. + private static readonly string[] AddressSelectingVariables = + [ + "SHARPEMU_CAPTURE_PIXEL_IMAGE_ADDRESS", + "SHARPEMU_CAPTURE_PIXEL_VGPR_ADDRESS", + "SHARPEMU_FORCE_PACKED_EXPORT_STORE_ONE", + "SHARPEMU_FORCE_PACKED_STORE_EXEC_VALUES", + "SHARPEMU_FORCE_PIXEL_EXPORT_ADDRESS", + "SHARPEMU_FORCE_PIXEL_EXPORT_VGPR_ADDRESS", + "SHARPEMU_FORCE_TITLE_COMPARE_4D4", + "SHARPEMU_FORCE_TITLE_COMPARE_540", + "SHARPEMU_FORCE_TITLE_EARLY_COLOR", + "SHARPEMU_FORCE_TITLE_EXPORT_EXEC", + "SHARPEMU_FORCE_TITLE_SINGLE_MRT", + "SHARPEMU_FORCE_TITLE_VERTEX_OUTPUTS_ONE", + "SHARPEMU_TRACE_PACKED_EXPORT_ADDRESS", + "SHARPEMU_TRACE_TITLE_INTERFACE", + "SHARPEMU_TRACE_TITLE_SHADER_STATE", + ]; + private static readonly bool AddressInKey = Variables.Any(static variable => AddressSelectsTranslation(variable.Name)); + private static readonly object WriteLock = new(); + private static volatile string? _folder; + private static volatile string? _stamp; + private static long _countedBytes = -1; + private static int _reportedFailure; + + // The running game's folder, beside its pipeline cache, and the device's translation stamp (the prewarm stamp); null stops. + // Entries go to this build's folder inside it. + public static void UseGameFolder(string? folder, string? stamp) + { + _stamp = stamp; + _countedBytes = -1; + _folder = folder is null || stamp is null || !Enabled ? null : UseBuildFolder(folder, stamp); + } + + internal static string? Folder => _folder; + + // This build's folder, marked as used now. Other builds' folders but the newest KeptBuilds - 1 are deleted, and so are the + // flat entries of the first layout. + private static string UseBuildFolder(string gameFolder, string stamp) + { + var name = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(string.Join('|', [Version.ToString(), .. Builds, stamp]))))[..16]; + var current = Path.Combine(gameFolder, name); + try + { + Directory.CreateDirectory(current); + Directory.SetLastWriteTimeUtc(current, DateTime.UtcNow); + var game = new DirectoryInfo(gameFolder); + foreach (var flat in game.GetFiles("*" + Extension)) + { + flat.Delete(); + } + + foreach (var old in game.GetDirectories().Where(directory => directory.Name != name) + .OrderByDescending(static directory => directory.LastWriteTimeUtc).Skip(KeptBuilds - 1)) + { + old.Delete(recursive: true); + } + } + catch (Exception error) when (IsCacheFailure(error)) + { + } + + return current; + } + + internal static bool AddressSelectsTranslation(string name) => + Array.IndexOf(AddressSelectingVariables, name.ToUpperInvariant()) >= 0; + + // Paths, dumps, logs and profiles never change a translation; neither does this cache's own mode. + internal static bool IgnoredVariable(string name) + { + var upper = name.ToUpperInvariant(); + return upper == "SHARPEMU_TRANSLATION_CACHE" || + upper.EndsWith("_PATH", StringComparison.Ordinal) || upper.EndsWith("_FILE", StringComparison.Ordinal) || + upper.EndsWith("_DIR", StringComparison.Ordinal) || upper.EndsWith("_FOLDER", StringComparison.Ordinal) || + upper.Contains("DUMP", StringComparison.Ordinal) || + upper.StartsWith("SHARPEMU_PROFILE", StringComparison.Ordinal) || + upper.StartsWith("SHARPEMU_LOG", StringComparison.Ordinal); + } + + // The key of one translation; null while the cache is off, before a game names its folder, or when a request field + // cannot be written (that request is translated without the cache). + public static string? Key(ProgramKey programKey, uint userDataBase, ResourceSpecialization specialization, uint pushDataCursor, + ShaderCompileRequest request) + { + if (!Enabled || _folder is null || _stamp is not { } stamp) + { + return null; + } + + try + { + using var stream = new MemoryStream(); + using (var writer = new BinaryWriter(stream, Encoding.UTF8, true)) + { + writer.Write(Version); + foreach (var build in Builds) writer.Write(build); + writer.Write(stamp); + writer.Write(Variables.Length); + foreach (var (name, value) in Variables) + { + writer.Write(name); + writer.Write(value); + } + + writer.Write((int)programKey.Stage); + writer.Write(programKey.Hash); + writer.Write(programKey.UserDataCount); + writer.Write(programKey.CodeSize); + writer.Write(programKey.ContinuationAddressOffset); + writer.Write(programKey.StaticState.Length); + foreach (var word in programKey.StaticState) writer.Write(word); + writer.Write(userDataBase); + writer.Write(pushDataCursor); + writer.Write(JsonSerializer.Serialize(specialization, Json)); + WriteProgram(writer, request.Program); + foreach (var property in RequestProperties) + { + var value = property.GetValue(request); + writer.Write(property.Name); + writer.Write(value is null ? "null" : JsonSerializer.Serialize(value, value.GetType(), Json)); + } + } + + var bytes = stream.GetBuffer().AsSpan(0, (int)stream.Length); + return Convert.ToHexString(SHA256.HashData(bytes)); + } + catch (Exception error) + { + // A cache never fails a translation: a request it cannot write is translated without the cache. + if (Interlocked.Exchange(ref _reportedFailure, 1) == 0) + { + Console.Error.WriteLine($"[PERF][TRANSLATION_CACHE] key failed: {error.GetType().Name}: {error.Message}"); + } + + return null; + } + } + + private static void WriteProgram(BinaryWriter writer, Gen5ShaderProgram program) + { + writer.Write(AddressInKey ? program.Address : 0); + writer.Write(program.IsFusedProgram); + var functionAccesses = program.FunctionBufferAccesses.Order().ToArray(); + writer.Write(functionAccesses.Length); + foreach (var access in functionAccesses) writer.Write(access); + writer.Write(program.Instructions.Count); + foreach (var instruction in program.Instructions) + { + writer.Write(instruction.Pc); + writer.Write(instruction.ProgramOffset); + writer.Write((int)instruction.Encoding); + writer.Write(instruction.Opcode); + writer.Write(instruction.Words.Count); + foreach (var word in instruction.Words) writer.Write(word); + writer.Write(instruction.Sources.Count); + foreach (var operand in instruction.Sources) + { + writer.Write((int)operand.Kind); + writer.Write(operand.Value); + } + + writer.Write(instruction.Destinations.Count); + foreach (var operand in instruction.Destinations) + { + writer.Write((int)operand.Kind); + writer.Write(operand.Value); + } + + // Controls are decoded records: their runtime type and every property. + writer.Write(instruction.Control?.GetType().FullName ?? ""); + writer.Write(instruction.Control is { } control ? JsonSerializer.Serialize(control, control.GetType(), Json) : ""); + } + } + + // Translates request, or takes its program from the cache under key (null: the cache does not take part). + public static bool TryTranslate(IGuestGpuBackend compiler, ShaderCompileRequest request, string? key, + out IGuestCompiledShader? compiled, out string error) + { + if (key is null) + { + return compiler.TryCompileProgram(request, out compiled, out error); + } + + var cached = TryLoad(key, compiler); + if (cached is not null) + { + compiled = cached; + error = string.Empty; + return true; + } + + if (!compiler.TryCompileProgram(request, out compiled, out error) || compiled is null) + { + return false; + } + + Store(key, compiled); + return true; + } + + // The stored program for key as the backend's shader; null on a miss or a damaged entry. + internal static IGuestCompiledShader? TryLoad(string key, IGuestGpuBackend backend) + { + if (_folder is not { } folder) + { + return null; + } + + try + { + var path = Path.Combine(folder, key + Extension); + if (!File.Exists(path)) + { + return null; + } + + var file = File.ReadAllBytes(path); + if (file.Length is <= 32 or > MaxEntryBytes || + !CryptographicOperations.FixedTimeEquals(file.AsSpan(0, 32), SHA256.HashData(file.AsSpan(32)))) + { + return null; + } + + using var reader = new BinaryReader(Inflate(file, 32)); + if (reader.ReadInt32() != Version || reader.ReadString() != key) + { + return null; + } + + uint? mask = reader.ReadBoolean() ? reader.ReadUInt32() : null; + var payloadLength = Checked(reader.ReadInt32()); + var payload = reader.ReadBytes(payloadLength); + if (payload.Length != payloadLength) + { + return null; + } + + var shader = backend.CreateCachedShader(payload, mask); + if (shader is not null) + { + MarkUsed(path); + } + + return shader; + } + catch (Exception) + { + return null; + } + } + + internal static void Store(string key, IGuestCompiledShader shader) + { + if (_folder is not { } folder) + { + return; + } + + try + { + using var content = new MemoryStream(); + using (var writer = new BinaryWriter(content, Encoding.UTF8, true)) + { + writer.Write(Version); + writer.Write(key); + writer.Write(shader.InputLocationMask.HasValue); + if (shader.InputLocationMask is { } mask) writer.Write(mask); + writer.Write(shader.Payload.Length); + writer.Write(shader.Payload); + } + + using var compressed = new MemoryStream(); + using (var zlib = new ZLibStream(compressed, CompressionLevel.Fastest, leaveOpen: true)) + { + zlib.Write(content.GetBuffer(), 0, (int)content.Length); + } + + var bytes = compressed.GetBuffer().AsSpan(0, (int)compressed.Length); + if (bytes.Length + 32L > MaxEntryBytes) + { + return; + } + + var path = Path.Combine(folder, key + Extension); + lock (WriteLock) + { + Directory.CreateDirectory(folder); + var entryBytes = bytes.Length + 32L; + if (_countedBytes < 0 || _countedBytes + entryBytes > MaxCacheBytes) + { + _countedBytes = Trim(folder, entryBytes, MaxCacheBytes, TrimTargetBytes); + } + + _countedBytes += entryBytes; + var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; + try + { + using (var file = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + file.Write(SHA256.HashData(bytes)); + file.Write(bytes); + } + + File.Move(temporary, path, true); + } + finally + { + File.Delete(temporary); + } + } + } + catch (Exception) + { + } + } + + private static int Checked(int count) => + count is >= 0 and <= MaxEntryBytes ? count : throw new InvalidDataException("Translation cache entry count out of range."); + + private static MemoryStream Inflate(byte[] compressed, int offset) + { + var inflated = new MemoryStream(); + using (var zlib = new ZLibStream(new MemoryStream(compressed, offset, compressed.Length - offset, false), CompressionMode.Decompress)) + { + var buffer = new byte[81920]; + int read; + while ((read = zlib.Read(buffer, 0, buffer.Length)) > 0) + { + if (inflated.Length + read > MaxEntryBytes) throw new InvalidDataException("Translation cache entry too large."); + inflated.Write(buffer, 0, read); + } + } + + inflated.Position = 0; + return inflated; + } + + // A hit marks its entry used: Trim drops the entries used longest ago. + private static void MarkUsed(string path) + { + try + { + File.SetLastAccessTimeUtc(path, DateTime.UtcNow); + } + catch (Exception error) when (IsCacheFailure(error)) + { + } + } + + // When an entry of entryBytes would take the folder past capBytes, deletes the entries used longest ago until it fits + // within targetBytes. Returns the bytes that remain. + internal static long Trim(string directory, long entryBytes, long capBytes, long targetBytes) + { + var entries = new DirectoryInfo(directory).GetFiles("*" + Extension); + var total = entries.Sum(static entry => entry.Length); + if (total + entryBytes <= capBytes) + { + return total; + } + + foreach (var entry in entries.OrderBy(LastUse)) + { + if (total + entryBytes <= targetBytes) break; + total -= entry.Length; + entry.Delete(); + } + + return total; + } + + private static DateTime LastUse(FileInfo entry) => + entry.LastAccessTimeUtc > entry.LastWriteTimeUtc ? entry.LastAccessTimeUtc : entry.LastWriteTimeUtc; + + private static bool IsCacheFailure(Exception error) => error is IOException or UnauthorizedAccessException or + InvalidDataException or ArgumentException or OverflowException or EndOfStreamException; +} diff --git a/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs b/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs index 74c74ad8b..ac8da911a 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs @@ -100,6 +100,15 @@ private void Collect(ResolvedDispatch record, in ShaderStageResources stage) } var resources = stage.Resources; + // Runtime callees and heap accesses can touch resources outside the snapshot below. + // Keep their barriers until the chain can account for that complete access set. + if (program.CallRecordCallees.Count != 0 || program.Bindings is { UsesBindlessHeap: true } || + stage.CallRecordRanges is { Length: > 0 }) + { + _recordConservative = true; + return; + } + if (program.Bindings?.Find(DescriptorBindingKind.GlobalDataShare) is not null) { _recordConservative = true; diff --git a/src/SharpEmu.Libs/Gpu/Rendering/DispatchThreadsPipeline.cs b/src/SharpEmu.Libs/Gpu/Rendering/DispatchThreadsPipeline.cs new file mode 100644 index 000000000..0a1cc6b58 --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/Rendering/DispatchThreadsPipeline.cs @@ -0,0 +1,233 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Gpu.Scheduling; +using SharpEmu.Libs.Gpu.Vulkan; +using SharpEmu.ShaderCompiler.Vulkan; +using Silk.NET.Vulkan; + +namespace SharpEmu.Libs.Gpu.Rendering; + +// The groups and thread limits of a dispatch whose guest arguments count threads and were written by a shader +// (SpirvDispatchThreads). The counts stay on the GPU: the command stream records the dispatch without waiting for their +// writer, as the hardware's command processor converts them itself. +internal sealed unsafe class DispatchThreadsPipeline : IDisposable +{ + private const ulong GroupBytes = 4 * sizeof(uint); + private const ulong CountBytes = 3 * sizeof(uint); + private readonly GpuDeviceInfo _device; + private DescriptorSetLayout _setLayout; + private PipelineLayout _layout; + private Pipeline _pipeline; + private RecycledDescriptorSets? _sets; + // Group buffers return here after their GPU work completes. + private readonly object _resourceGate = new(); + private readonly Stack _freeGroups = new(); + private bool _disposed; + + public DispatchThreadsPipeline(GpuDeviceInfo device) + { + _device = device; + ShaderModule module = default; + try + { + var bindings = stackalloc DescriptorSetLayoutBinding[3]; + for (uint index = 0; index < 3; index++) + bindings[index] = new DescriptorSetLayoutBinding(index, DescriptorType.StorageBuffer, 1, ShaderStageFlags.ComputeBit); + var setInfo = new DescriptorSetLayoutCreateInfo + { + SType = StructureType.DescriptorSetLayoutCreateInfo, BindingCount = 3, PBindings = bindings, + }; + Check(device.Vk.CreateDescriptorSetLayout(device.Device, &setInfo, null, out _setLayout)); + _sets = new RecycledDescriptorSets(device, _setLayout, 3); + var setLayout = _setLayout; + var pushRange = new PushConstantRange(ShaderStageFlags.ComputeBit, 0, SpirvDispatchThreads.PushWordCount * 4); + var layoutInfo = new PipelineLayoutCreateInfo + { + SType = StructureType.PipelineLayoutCreateInfo, SetLayoutCount = 1, PSetLayouts = &setLayout, + PushConstantRangeCount = 1, PPushConstantRanges = &pushRange, + }; + Check(device.Vk.CreatePipelineLayout(device.Device, &layoutInfo, null, out _layout)); + var spirv = SpirvDispatchThreads.Create(); + fixed (byte* code = spirv) + { + var moduleInfo = new ShaderModuleCreateInfo + { + SType = StructureType.ShaderModuleCreateInfo, CodeSize = (nuint)spirv.Length, PCode = (uint*)code, + }; + Check(device.Vk.CreateShaderModule(device.Device, &moduleInfo, null, out module)); + } + fixed (byte* entry = "main\0"u8) + { + var pipelineInfo = new ComputePipelineCreateInfo + { + SType = StructureType.ComputePipelineCreateInfo, Layout = _layout, + Stage = new PipelineShaderStageCreateInfo + { + SType = StructureType.PipelineShaderStageCreateInfo, Stage = ShaderStageFlags.ComputeBit, + Module = module, PName = entry, + }, + }; + Check(device.Vk.CreateComputePipelines(device.Device, default, 1, &pipelineInfo, null, out _pipeline)); + } + } + catch + { + Dispose(); + throw; + } + finally + { + if (module.Handle != 0) device.Vk.DestroyShaderModule(device.Device, module, null); + } + } + + // groupSize and physicalAxis are per logical axis; the groups land in the pipeline's physical axis order. Without + // limits the shader writes none, and the arguments fill the unused binding. + public PreparedDispatch Prepare(SubmissionScheduler scheduler, BufferBinding arguments, BufferBinding? limits, + ReadOnlySpan groupSize, ReadOnlySpan physicalAxis) => + new(this, scheduler, arguments, limits, groupSize, physicalAxis); + + private GpuBuffer RentGroups(SubmissionScheduler scheduler) + { + lock (_resourceGate) + if (_freeGroups.TryPop(out var reused)) return reused; + return new GpuBuffer(_device, scheduler, GpuBufferUsage.DeviceLocal, 0, GpuBuffer.AllFlags, GroupBytes); + } + + private void ReturnResources(GpuBuffer? groups, DescriptorSet set) + { + lock (_resourceGate) + { + if (_disposed) + { + groups?.Dispose(); + return; + } + if (groups is not null) _freeGroups.Push(groups); + if (set.Handle != 0) _sets!.Return(set); + } + } + + public void Dispose() + { + lock (_resourceGate) + { + _disposed = true; + foreach (var buffer in _freeGroups) buffer.Dispose(); + _freeGroups.Clear(); + _sets?.Dispose(); + _sets = null; + } + if (_pipeline.Handle != 0) _device.Vk.DestroyPipeline(_device.Device, _pipeline, null); + if (_layout.Handle != 0) _device.Vk.DestroyPipelineLayout(_device.Device, _layout, null); + if (_setLayout.Handle != 0) _device.Vk.DestroyDescriptorSetLayout(_device.Device, _setLayout, null); + _pipeline = default; + _layout = default; + _setLayout = default; + } + + private static void Check(Result result) + { + if (result != Result.Success) throw SubmissionScheduler.Fatal($"The thread dispatch resource could not be created: result={result}."); + } + + internal sealed class PreparedDispatch : IDisposable + { + private readonly DispatchThreadsPipeline _owner; + private readonly uint[] _push = new uint[SpirvDispatchThreads.PushWordCount]; + private GpuBuffer? _groups; + private DescriptorSet _set; + + internal PreparedDispatch(DispatchThreadsPipeline owner, SubmissionScheduler scheduler, BufferBinding arguments, + BufferBinding? limits, ReadOnlySpan groupSize, ReadOnlySpan physicalAxis) + { + _owner = owner; + if (groupSize.Length != 3 || physicalAxis.Length != 3) + throw SubmissionScheduler.Fatal("The thread dispatch needs three group sizes and axes."); + var device = owner._device; + try + { + _groups = owner.RentGroups(scheduler); + _set = owner._sets!.Rent(); + var alignment = device.MinStorageBufferOffsetAlignment; + var argumentsBase = arguments.Offset / alignment * alignment; + var limitsBinding = limits ?? arguments; + var limitsBase = limitsBinding.Offset / alignment * alignment; + var infos = stackalloc DescriptorBufferInfo[3]; + infos[0] = new(new Silk.NET.Vulkan.Buffer(arguments.Handle), argumentsBase, arguments.Offset - argumentsBase + CountBytes); + infos[1] = new(_groups.Handle, 0, GroupBytes); + infos[2] = new(new Silk.NET.Vulkan.Buffer(limitsBinding.Handle), limitsBase, limitsBinding.Offset - limitsBase + CountBytes); + var writes = stackalloc WriteDescriptorSet[3]; + for (uint index = 0; index < 3; index++) + { + writes[index] = new WriteDescriptorSet + { + SType = StructureType.WriteDescriptorSet, DstSet = _set, DstBinding = index, + DescriptorCount = 1, DescriptorType = DescriptorType.StorageBuffer, PBufferInfo = infos + index, + }; + } + device.Vk.UpdateDescriptorSets(device.Device, 3, writes, 0, null); + var maximum = device.MaxComputeWorkGroupCount; + ReadOnlySpan physicalLimit = [maximum.X, maximum.Y, maximum.Z]; + _push[0] = checked((uint)((arguments.Offset - argumentsBase) / sizeof(uint))); + for (var axis = 0; axis < 3; axis++) + { + if (physicalAxis[axis] is < 0 or > 2) + throw SubmissionScheduler.Fatal("The thread dispatch axis is out of range."); + _push[1 + axis] = Math.Max(groupSize[axis], 1u); + _push[4 + axis] = (uint)physicalAxis[axis]; + _push[8 + axis] = physicalLimit[physicalAxis[axis]]; + } + _push[7] = limits is null + ? SpirvDispatchThreads.NoLimits + : checked((uint)((limitsBinding.Offset - limitsBase) / sizeof(uint))); + } + catch + { + Dispose(); + throw; + } + } + + public Silk.NET.Vulkan.Buffer GroupsBuffer => _groups!.Handle; + + public void Record(CommandBuffer command) + { + var vk = _owner._device.Vk; + // The arguments' shader writer and the shader data upload come before the read. + var before = new MemoryBarrier2 + { + SType = StructureType.MemoryBarrier2, + SrcAccessMask = AccessFlags2.MemoryWriteBit | AccessFlags2.HostWriteBit, + DstAccessMask = AccessFlags2.ShaderReadBit | AccessFlags2.ShaderWriteBit, + }; + VulkanSynchronization.PipelineBarrier(vk, command, PipelineStageFlags.AllCommandsBit | PipelineStageFlags.HostBit, + PipelineStageFlags.ComputeShaderBit, 0, 1, &before, 0, null, 0, null); + vk.CmdBindPipeline(command, PipelineBindPoint.Compute, _owner._pipeline); + var set = _set; + vk.CmdBindDescriptorSets(command, PipelineBindPoint.Compute, _owner._layout, 0, 1, &set, 0, null); + fixed (uint* push = _push) + vk.CmdPushConstants(command, _owner._layout, ShaderStageFlags.ComputeBit, 0, SpirvDispatchThreads.PushWordCount * 4, push); + // The guest dispatch binds its own pipeline and sets again. + NativeBindingEpoch.Advance(); + vk.CmdDispatch(command, 1, 1, 1); + var after = new MemoryBarrier2 + { + SType = StructureType.MemoryBarrier2, SrcAccessMask = AccessFlags2.ShaderWriteBit, + DstAccessMask = AccessFlags2.IndirectCommandReadBit | AccessFlags2.ShaderReadBit | AccessFlags2.UniformReadBit, + }; + VulkanSynchronization.PipelineBarrier(vk, command, PipelineStageFlags.ComputeShaderBit, + PipelineStageFlags.DrawIndirectBit | PipelineStageFlags.ComputeShaderBit, 0, 1, &after, 0, null, 0, null); + } + + public void Dispose() + { + // The owner calls this before recording or after the GPU work completes. + _owner.ReturnResources(_groups, _set); + _set = default; + _groups = null; + } + } +} diff --git a/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs b/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs index 3a593d7a8..331c7cb70 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs @@ -11,6 +11,20 @@ namespace SharpEmu.Libs.Gpu.Rendering; // A host buffer and the byte offset a guest address maps to inside it. public readonly record struct BufferBinding(ulong Handle, ulong Offset); +// A dispatch whose groups the GPU computes from guest arguments that count threads (IRenderHost.PrepareThreadDispatch). +public interface IThreadDispatch : IDisposable +{ + void Dispatch(); +} + +// Registers indirect arguments before resource binding. Rebind acquires the current native view +// after resource preparation and is permitted only before GPU use; +// disposal retains a used allocation through the submission that last consumed it. +public interface IIndirectDispatchArguments : IDisposable +{ + void Rebind(); +} + // The packet arguments of a draw the host keeps until the next flip. public readonly record struct TargetlessDrawArguments(ulong SubmitId, bool Indexed, GpuCommands.DrawIndexedArguments Indexed_, GpuCommands.DrawAutoArguments Auto); @@ -64,6 +78,8 @@ public readonly record struct DynamicDrawState( uint ColorWriteCount, byte ColorWriteEnableMask, uint DepthCountControl = 0, + StencilOperations FrontStencilOperations = default, + StencilOperations BackStencilOperations = default, bool DepthBoundsTestEnabled = false, float DepthMinBounds = 0f, float DepthMaxBounds = 1f); @@ -171,6 +187,13 @@ IIndirectMeshDraw PrepareIndirectMeshDraw(in IndirectMeshDrawRequest request) => // Opens the preparation scope; a ring wrap inside it is refused, and disposal releases it on every path. IResourcePreparation BeginPreparation(); + // Changes whenever a buffer owner is unregistered; buffers bound before a change are bound again (RebindBuffers). + long BufferOwnerGeneration => 0; + + void RebindBuffers(IPreparedBindings prepared) + { + } + IPreparedBindings PrepareBindings(ShaderStageResources stage); void UpdateTessellationData(IPreparedBindings prepared, uint[] data) => @@ -203,6 +226,7 @@ void PrepareMemoryWritingDraw() { } void DrawIndexedIndirect(BufferBinding arguments) => throw new NotSupportedException("The render host does not draw from indirect arguments."); + // One draw whose counts the GPU reads from the buffer (VkDrawIndirectCommand layout). void DrawIndirect(BufferBinding arguments) => throw new NotSupportedException("The render host does not draw from indirect arguments."); @@ -217,6 +241,25 @@ void DrawMeshTasks(uint groupCountX, uint groupCountY, uint groupCountZ) => // consume the guest buffer directly. Backends without native indirect dispatch return false. bool TryDispatchIndirect(ulong argumentsAddress, ReadOnlySpan physicalAxisOfLogical); + // Registers three uint32 argument words before binding; call Rebind after resource preparation. A backend that + // returns null takes the dispatch through TryDispatchIndirect(ulong, ...) or the direct dispatch fallback. + IIndirectDispatchArguments? PrepareIndirectDispatchArguments(ulong argumentsAddress) => null; + + // Records the command from prepared arguments without acquiring more guest resources; the group counts are + // permuted to the pipeline's physical axis order as for TryDispatchIndirect(ulong, ...). + bool TryDispatchIndirect(IIndirectDispatchArguments arguments, ReadOnlySpan physicalAxisOfLogical) => false; + + // True when an indirect dispatch whose guest arguments count threads keeps the counts on the GPU (PrepareThreadDispatch), + // so the interpreter need not read them back first. + bool ResolvesIndirectThreadDispatchOnGpu => false; + + // Records the groups (in the pipeline's physical axis order) and the thread limits of such a dispatch from its arguments, + // after final owner stabilization and before bindings are committed. Dispose the result even if the consumer fails. + // groupSize and physicalAxis are per logical axis. + IThreadDispatch PrepareThreadDispatch(IIndirectDispatchArguments arguments, IPreparedBindings bindings, ReadOnlySpan groupSize, + ReadOnlySpan physicalAxis) => + throw new NotSupportedException("The render host does not compute thread dispatch groups on the GPU."); + // Orders the buffer writes of the given shader stages before every later access. void ShaderWriteBarrier(PipelineStageFlags sourceStages); diff --git a/src/SharpEmu.Libs/Gpu/Rendering/IShaderPipelineProvider.cs b/src/SharpEmu.Libs/Gpu/Rendering/IShaderPipelineProvider.cs index 50fa91b91..dc6fd808f 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/IShaderPipelineProvider.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/IShaderPipelineProvider.cs @@ -157,6 +157,17 @@ GraphicsPrograms GetGraphicsPrograms( int startInstanceUserData) => GetGraphicsPrograms(banks, targetExportMapping, pixelActive, depthBound); + // taskLaunch: an automatic indirect draw launched by the task stage (MeshTaskLaunch). Providers without task launches + // never see it: the decision is made only while MeshTaskLaunch is active. + GraphicsPrograms GetMeshGraphicsPrograms( + RegisterBanks banks, + UserConfigRegisters userConfig, + ReadOnlySpan targetExportMapping, + bool pixelActive, + bool depthBound, + bool taskLaunch) => + GetMeshGraphicsPrograms(banks, userConfig, targetExportMapping, pixelActive, depthBound); + PipelineHandle CreateGraphicsPipeline( ReadOnlySpan colors, in DepthAttachmentState depth, @@ -186,10 +197,24 @@ ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitiator, ui ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitiator, uint dimensionX, uint dimensionY, uint dimensionZ, bool indirect) => GetComputeProgram(banks, dispatchInitiator, dimensionX, dimensionY, dimensionZ); + // gpuThreadCounts: the thread counts are in GPU memory (the dimensions are zero); the program reads its thread limits + // from shader data the GPU writes (ComputeInputInfo.IndirectThreadCounts). + ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitiator, uint dimensionX, uint dimensionY, uint dimensionZ, bool indirect, + bool gpuThreadCounts) => + GetComputeProgram(banks, dispatchInitiator, dimensionX, dimensionY, dimensionZ, indirect); + PipelineHandle CreateComputePipeline(ComputeInputInfo input, ShaderProgram program); Task? GetComputePipelineCompletion(ShaderProgram program) => null; + // Whether a session saw this linked program's module compile for minutes (ShaderPrewarmList.IsSlowLinkedCompile). + bool IsSlowLinkedCompile(ulong hash) => false; + + // Records what this session learned about a linked program's module compile. + void RecordLinkedCompile(ulong hash, bool slow, long milliseconds) + { + } + // False means the host is still compiling this pipeline; asking again returns it once // the compile finishes, without starting a second one. bool TryCreateComputePipeline(ComputeInputInfo input, ShaderProgram program, out PipelineHandle handle) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/IndirectMeshDraw.cs b/src/SharpEmu.Libs/Gpu/Rendering/IndirectMeshDraw.cs index 5d752ab8f..b66ad4938 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/IndirectMeshDraw.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/IndirectMeshDraw.cs @@ -15,4 +15,13 @@ public readonly record struct IndirectMeshDrawRequest( bool PointList, uint PrimitivesPerGroup, MeshExecutionLimits Limits) { public const uint MaximumIndexCapacity = 1 << 20; + + // An automatic draw reads no index buffer; its arguments are (vertexCount, instanceCount, firstVertex, firstInstance). + public bool Automatic => IndexElementSize == 0; + + // The draw's mesh program is task-launched (MeshTaskLaunch): the task stage converts the arguments. + public bool TaskLaunched { get; init; } + + public static IndirectMeshDrawRequest ForAutomaticDraw(ulong argumentsAddress, bool pointList, uint primitivesPerGroup, + MeshExecutionLimits limits) => new(argumentsAddress, 0, 0, 0, pointList, primitivesPerGroup, limits); } diff --git a/src/SharpEmu.Libs/Gpu/Rendering/MeshIndirectPipeline.cs b/src/SharpEmu.Libs/Gpu/Rendering/MeshIndirectPipeline.cs index 617703a77..6b339f760 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/MeshIndirectPipeline.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/MeshIndirectPipeline.cs @@ -92,13 +92,13 @@ private GpuBuffer RentOutput(SubmissionScheduler scheduler, ulong size) GpuBuffer.AllFlags | BufferUsageFlags.ShaderDeviceAddressBit, bucket); } + // No host clear: the helper's invocation 0 writes the status word on every exit (each dispatch has at least one + // group, and the shader has no early return), before the completion action reads it. private GpuBuffer RentStatus(SubmissionScheduler scheduler) { GpuBuffer? status = null; lock (_resourceGate) _freeStatuses.TryPop(out status); status ??= new GpuBuffer(_device, scheduler, GpuBufferUsage.Download, 0, GpuBuffer.AllFlags, 4); - status.Mapped.Clear(); - status.Flush(0, 4); return status; } @@ -148,10 +148,16 @@ private static void Check(Result result) if (result != Result.Success) throw SubmissionScheduler.Fatal($"The indirect mesh resource could not be created: result={result}."); } + [System.Runtime.CompilerServices.InlineArray((int)SpirvMeshIndirect.PushWordCount)] + private struct PushWords + { + private uint _word; + } + internal sealed class PreparedDraw : IDisposable { private readonly MeshIndirectPipeline _owner; - private readonly uint[] _push; + private PushWords _push; private readonly uint _capacity; private GpuBuffer? _output; private GpuBuffer? _status; @@ -162,9 +168,10 @@ internal PreparedDraw(MeshIndirectPipeline owner, SubmissionScheduler scheduler, { _owner = owner; _capacity = request.IndexCapacity; - _push = new uint[SpirvMeshIndirect.PushWordCount]; - if (_capacity is 0 or > IndirectMeshDrawRequest.MaximumIndexCapacity || request.IndexElementSize is not (2 or 4) || - request.PrimitivesPerGroup is 0 or > IndirectMeshDrawRequest.MaximumIndexCapacity) + var validIndices = request.Automatic + ? _capacity == 0 && request.IndexAddress == 0 + : _capacity is not (0 or > IndirectMeshDrawRequest.MaximumIndexCapacity) && (request.IndexElementSize is 2 or 4); + if (!validIndices || request.PrimitivesPerGroup is 0 or > IndirectMeshDrawRequest.MaximumIndexCapacity) throw SubmissionScheduler.Fatal("The indirect mesh preparation has invalid bounds."); var device = owner._device; try @@ -176,8 +183,10 @@ internal PreparedDraw(MeshIndirectPipeline owner, SubmissionScheduler scheduler, var alignment = device.MinStorageBufferOffsetAlignment; var argumentsBase = arguments.Offset / alignment * alignment; var indicesBase = indices.Offset / alignment * alignment; - var indexSize = (indexByteOffset + (ulong)_capacity * request.IndexElementSize + 3) & ~3ul; - infos[0] = new(new Silk.NET.Vulkan.Buffer(arguments.Handle), argumentsBase, arguments.Offset - argumentsBase + 20); + var argumentsSize = request.Automatic ? 16ul : 20ul; + // An automatic draw reads no indices; its arguments fill the unused binding. + var indexSize = request.Automatic ? argumentsSize : (indexByteOffset + (ulong)_capacity * request.IndexElementSize + 3) & ~3ul; + infos[0] = new(new Silk.NET.Vulkan.Buffer(arguments.Handle), argumentsBase, arguments.Offset - argumentsBase + argumentsSize); infos[1] = new(new Silk.NET.Vulkan.Buffer(indices.Handle), indicesBase, indices.Offset - indicesBase + indexSize); infos[2] = new(_output.Handle, 0, _output.Size); infos[3] = new(_status.Handle, 0, 4); @@ -195,7 +204,8 @@ internal PreparedDraw(MeshIndirectPipeline owner, SubmissionScheduler scheduler, device.Vk.UpdateDescriptorSets(device.Device, 4, writes, 0, null); _push[0] = checked((uint)((arguments.Offset - argumentsBase) / 4)); _push[1] = checked((uint)(indices.Offset - indicesBase + indexByteOffset)); - _push[2] = _capacity; + // Nothing bounds an automatic draw's vertices but the group limits. + _push[2] = request.Automatic ? uint.MaxValue : _capacity; _push[3] = request.IndexElementSize; _push[4] = request.PrimitivesPerGroup; _push[5] = request.PointList ? 1u : 0u; @@ -230,10 +240,10 @@ public void Record(CommandBuffer command) vk.CmdBindPipeline(command, PipelineBindPoint.Compute, _owner._pipeline); var set = _set; vk.CmdBindDescriptorSets(command, PipelineBindPoint.Compute, _owner._layout, 0, 1, &set, 0, null); - fixed (uint* push = _push) + fixed (uint* push = &_push[0]) vk.CmdPushConstants(command, _owner._layout, ShaderStageFlags.ComputeBit, 0, SpirvMeshIndirect.PushWordCount * 4, push); NativeBindingEpoch.Advance(); - vk.CmdDispatch(command, (_capacity + 63) / 64, 1, 1); + vk.CmdDispatch(command, Math.Max(1u, (_capacity + 63) / 64), 1, 1); var after = new MemoryBarrier2 { SType = StructureType.MemoryBarrier2, SrcAccessMask = AccessFlags2.ShaderWriteBit, diff --git a/src/SharpEmu.Libs/Gpu/Rendering/MeshTaskLaunch.cs b/src/SharpEmu.Libs/Gpu/Rendering/MeshTaskLaunch.cs new file mode 100644 index 000000000..dcfe5771f --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/Rendering/MeshTaskLaunch.cs @@ -0,0 +1,26 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Libs.Gpu.Rendering; + +// An automatic indirect mesh draw is launched by a task stage instead of a conversion dispatch. One task workgroup reads +// the draw's current arguments, applies the conversion's count, limit and zero rules and emits the mesh groups with the +// draw parameters in its payload, so the draw needs no conversion dispatch, no pass break and no barriers. +// SHARPEMU_MESH_TASK_LAUNCH=0 keeps the conversion dispatch and leaves the device's task shader feature off (a device +// feature changes the driver's shader cache keys). +public static class MeshTaskLaunch +{ + public static readonly bool Configured = Environment.GetEnvironmentVariable("SHARPEMU_MESH_TASK_LAUNCH") != "0"; + + private static volatile bool _deviceSupported; + + // Set by the renderer when it created its device with task shaders and the task push range fits. + public static bool DeviceSupported + { + get => _deviceSupported; + set => _deviceSupported = value; + } + + // Whether an automatic indirect mesh draw resolved now is task-launched. + public static bool Active => Configured && _deviceSupported; +} diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Adaptations.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Adaptations.cs index 4f7c5bb45..7f859b6e4 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Adaptations.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Adaptations.cs @@ -106,11 +106,16 @@ private static bool IsPremultipliedFillBlend(in BlendRegisters blend) => blend.Enable && blend.ColorSourceFactor == BlendFactorOne && blend.ColorDestinationFactor == BlendFactorOneMinusSourceAlpha && blend.ColorFunction == BlendFunctionAdd; // A covering quad that only programs the DCC clear codes; its shaded output is discarded. - private bool IsMetadataClearQuad(RegisterBanks banks, in DrawCall draw, ref DrawState state) + private bool IsMetadataClearQuad(RegisterBanks banks, in DrawCall draw, ref DrawState state) => + draw.Count == DccFastClearVertexCount && MayBeMetadataClearQuad(banks, ref state) && + CoversClipSpace(state.Programs.PositionStream, draw.Count); + + // Everything of a metadata clear quad but its count and positions. + private bool MayBeMetadataClearQuad(RegisterBanks banks, ref DrawState state) { var programs = state.Programs; var context = banks.Context; - if (draw.Count != DccFastClearVertexCount || (GuestPrimitiveType)banks.UserConfig.PrimitiveType != GuestPrimitiveType.TriangleStrip || + if ((GuestPrimitiveType)banks.UserConfig.PrimitiveType != GuestPrimitiveType.TriangleStrip || state.ColorCount == 0 || programs.PixelInput.Stage.Program is not { Images.Length: 0 } || programs.VertexInput.Stage.Program is not { Images.Length: 0 }) { return false; @@ -126,7 +131,7 @@ private bool IsMetadataClearQuad(RegisterBanks banks, in DrawCall draw, ref Draw var slot = state.Colors[0].Slot; var words = context.ColorTargets[slot]; - return words.DccEnabled && words.ClearWord0 == 0 && context.ColorClearWord1[slot] == 0 && CoversClipSpace(programs.PositionStream, draw.Count); + return words.DccEnabled && words.ClearWord0 == 0 && context.ColorClearWord1[slot] == 0; } // The quad covers the clip volume when its positions span [-1, 1] on both axes. diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Compute.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Compute.cs index 1ffa134c7..df76b3a6b 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Compute.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.Compute.cs @@ -24,6 +24,11 @@ public sealed partial class RenderExecutor private const uint ImageClearStride = 16; private const uint ImageClearUserDataCount = 8; + // Thread counts a shader wrote stay on the GPU, which converts them to groups (IRenderHost.PrepareThreadDispatch). + internal bool GpuThreadCountsFor(uint dispatchInitiator, ulong indirectArgumentsAddress) => + (dispatchInitiator & DispatchInitiatorUseThreadDimensions) != 0 && indirectArgumentsAddress != 0 && + _host.ResolvesIndirectThreadDispatchOnGpu; + public void Dispatch(ulong submitId, RegisterBanks banks, uint groupsX, uint groupsY, uint groupsZ, uint dispatchInitiator, ulong indirectArgumentsAddress = 0) { var compute = banks.Shader.Compute; @@ -51,7 +56,9 @@ public void Dispatch(ulong submitId, RegisterBanks banks, uint groupsX, uint gro } var useThreadDimensions = (dispatchInitiator & DispatchInitiatorUseThreadDimensions) != 0; - if ((indirectArgumentsAddress == 0 || useThreadDimensions) && IsEmptyDispatch(compute, useThreadDimensions, groupsX, groupsY, groupsZ)) + var gpuThreadCounts = GpuThreadCountsFor(dispatchInitiator, indirectArgumentsAddress); + if (!gpuThreadCounts && (indirectArgumentsAddress == 0 || useThreadDimensions) && + IsEmptyDispatch(compute, useThreadDimensions, groupsX, groupsY, groupsZ)) { if (RenderTrace.Enabled && RenderTrace.ZeroDispatch()) { @@ -66,7 +73,8 @@ public void Dispatch(ulong submitId, RegisterBanks banks, uint groupsX, uint gro ComputeProgram computeProgram; using (VideoOut.RenderPhaseProfile.MeasureDetail(VideoOut.RenderPhaseProfile.Phase.DrawProgramResolution)) { - computeProgram = _pipelines.GetComputeProgram(banks, dispatchInitiator, groupsX, groupsY, groupsZ, indirectArgumentsAddress != 0); + computeProgram = _pipelines.GetComputeProgram(banks, dispatchInitiator, groupsX, groupsY, groupsZ, indirectArgumentsAddress != 0, + gpuThreadCounts); } if (computeProgram.ImageCopy is not null) @@ -136,7 +144,7 @@ public void Dispatch(ulong submitId, RegisterBanks banks, uint groupsX, uint gro } } - if (useThreadDimensions) + if (useThreadDimensions && !gpuThreadCounts) { indirectArgumentsAddress = 0; var threadsX = groupsX; @@ -176,6 +184,7 @@ public void Dispatch(ulong submitId, RegisterBanks banks, uint groupsX, uint gro record.GroupsY = groupsY; record.GroupsZ = groupsZ; record.IndirectArgumentsAddress = indirectArgumentsAddress; + record.GpuThreadCounts = gpuThreadCounts; record.HasStorageWrites = hasStorageWrites; var resources = input.Stage.Resources; Diagnostics.DispatchRunTally.NoteResolved(computeProgram.Program.Id, resources.Images, resources.Samplers, program.Bindings?.UsesTableBlock == true, @@ -191,16 +200,126 @@ public void Dispatch(ulong submitId, RegisterBanks banks, uint groupsX, uint gro // frames. private static readonly System.Collections.Concurrent.ConcurrentDictionary LinkedCompileSkips = new(); + // Not every linked program is such a pass. A skipped dispatch that set up later work is lost for good (a + // shader-call path whose first dispatches are skipped during its compile can leave an object out for the rest of + // the session), so a dispatch first waits for its module, as an unlinked dispatch does, for at most + // SHARPEMU_LINKED_COMPILE_WAIT_MS (default 5000, 0 = skip at once, at most 600000). A program whose compile + // outlasts the bound is skipped while it compiles and never waited for again. + internal static readonly long LinkedCompileWaitTicks = + (long.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_LINKED_COMPILE_WAIT_MS"), out var waitMs) ? Math.Clamp(waitMs, 0, 600_000) : 5000) * + System.Diagnostics.Stopwatch.Frequency / 1000; + // This executor's bound (tests change it) and the programs whose compile outlasted it. + internal long LinkedCompileWait = LinkedCompileWaitTicks; + private readonly System.Collections.Concurrent.ConcurrentDictionary _linkedCompileSlow = new(); + + // A program whose module a session saw compile for minutes waits at most this long for it (default 250 ms, + // SHARPEMU_LINKED_KNOWN_SLOW_WAIT_MS, never longer than LinkedCompileWait). That is time enough for a module + // created from stored data, while a fresh compile would outlast LinkedCompileWait anyway and hold the stream for + // nothing. + internal static readonly long KnownSlowLinkedCompileWaitTicks = + (long.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_LINKED_KNOWN_SLOW_WAIT_MS"), out var knownSlowMs) ? Math.Clamp(knownSlowMs, 0, 600_000) : 250) * + System.Diagnostics.Stopwatch.Frequency / 1000; + internal long KnownSlowLinkedCompileWait = KnownSlowLinkedCompileWaitTicks; + // A module still compiling this long after its program's first dispatch waited is recorded as slow. + internal long SlowLinkedCompileRecordTicks = 60 * System.Diagnostics.Stopwatch.Frequency; + // When this session's first dispatch of each linked program began waiting for its module, and whether the program + // was known slow then; removed once the module is ready. + private readonly System.Collections.Concurrent.ConcurrentDictionary _linkedCompileWaits = new(); + private readonly System.Collections.Concurrent.ConcurrentDictionary _linkedCompileRecorded = new(); + + // Polls until ready() holds, sleeping on the compile's completion when there is one, for at most boundTicks. + internal static bool WaitForLinkedModule(Func ready, Func completion, long boundTicks) + { + var started = System.Diagnostics.Stopwatch.GetTimestamp(); + while (true) + { + var left = boundTicks - (System.Diagnostics.Stopwatch.GetTimestamp() - started); + if (left <= 0) return ready(); + // A completed compile whose pipeline is not ready yet polls with sleeps, as no compile does: the wait never spins. + if (completion() is { IsCompleted: false } task) + { + try + { + task.Wait(TimeSpan.FromSeconds((double)left / System.Diagnostics.Stopwatch.Frequency)); + } + catch (AggregateException) + { + // A failed compile surfaces where the pipeline is taken, as for an unlinked dispatch. + } + } + else + { + Thread.Sleep(1); + } + + if (ready()) return true; + } + } + private bool SkipWhileLinkedModuleCompiles(ComputeInputInfo input, ShaderProgram handle, ShaderProgramInfo program) { - if (program.Bindings is not { CallTargetCount: not 0 } || - _pipelines.TryCreateComputePipeline(input, handle, out _)) return false; + if (program.Bindings is not { CallTargetCount: not 0 }) return false; + var ready = _pipelines.TryCreateComputePipeline(input, handle, out _); + if (!ready && LinkedCompileWait > 0 && !_linkedCompileSlow.ContainsKey(program.Hash)) + { + var waiting = System.Diagnostics.Stopwatch.GetTimestamp(); + var knownSlow = _pipelines.IsSlowLinkedCompile(program.Hash); + _linkedCompileWaits.TryAdd(program.Hash, (waiting, knownSlow)); + var bound = knownSlow ? Math.Min(LinkedCompileWait, KnownSlowLinkedCompileWait) : LinkedCompileWait; + using (VideoOut.RenderPhaseProfile.MeasureDetail(VideoOut.RenderPhaseProfile.Phase.ComputePipelineWait)) + { + ready = WaitForLinkedModule(() => _pipelines.TryCreateComputePipeline(input, handle, out _), + () => _pipelines.GetComputePipelineCompletion(handle), bound); + } + + var waitedMs = (System.Diagnostics.Stopwatch.GetTimestamp() - waiting) * 1000 / System.Diagnostics.Stopwatch.Frequency; + if (!ready) _linkedCompileSlow.TryAdd(program.Hash, 0); + Console.Error.WriteLine(ready + ? $"[GPU][INFO][LINKED_COMPILE] A dispatch waited {waitedMs} ms for its linked module: hash=0x{program.Hash:X16}." + : knownSlow + ? $"[GPU][INFO][LINKED_COMPILE] A linked module a session saw compile for minutes still compiles after {waitedMs} ms; its dispatches are skipped until it is ready: hash=0x{program.Hash:X16}." + : $"[GPU][WARN][LINKED_COMPILE] A linked module still compiles after {waitedMs} ms; its dispatches are skipped until it is ready: hash=0x{program.Hash:X16}."); + } + + if (_linkedCompileWaits.TryGetValue(program.Hash, out var wait)) + { + NoteLinkedCompileWait(program.Hash, wait, ready); + } + + if (ready) return false; var skipped = LinkedCompileSkips.AddOrUpdate(program.Hash, 1, static (_, count) => count + 1); if ((skipped & (skipped - 1)) == 0) Console.Error.WriteLine($"[GPU][WARN][LINKED_COMPILE] Dispatches of a linked program are skipped while its module compiles: hash=0x{program.Hash:X16} skipped={skipped}."); return true; } + // What later sessions learn from a module this session waited for. Still compiling SlowLinkedCompileRecordTicks + // after the first wait: slow (unless already known). Ready within LinkedCompileWait once the short bound of a known + // slow program had run out: not slow. A module ready within the short bound was created from stored data and says + // nothing about a fresh compile. + private void NoteLinkedCompileWait(ulong hash, (long Started, bool KnownSlow) wait, bool ready) + { + var elapsed = System.Diagnostics.Stopwatch.GetTimestamp() - wait.Started; + var milliseconds = elapsed * 1000 / System.Diagnostics.Stopwatch.Frequency; + if (!ready) + { + if (!wait.KnownSlow && elapsed >= SlowLinkedCompileRecordTicks && _linkedCompileRecorded.TryAdd(hash, 0)) + { + _pipelines.RecordLinkedCompile(hash, slow: true, milliseconds); + Console.Error.WriteLine($"[GPU][INFO][LINKED_COMPILE] Recorded a linked module that compiles for minutes: hash=0x{hash:X16} compiling_ms={milliseconds}."); + } + + return; + } + + _linkedCompileWaits.TryRemove(hash, out _); + if (wait.KnownSlow && _linkedCompileSlow.ContainsKey(hash) && elapsed < LinkedCompileWait) + { + _pipelines.RecordLinkedCompile(hash, slow: false, milliseconds); + Console.Error.WriteLine($"[GPU][INFO][LINKED_COMPILE] Recorded a linked module that no longer compiles for minutes: hash=0x{hash:X16} ready_ms={milliseconds}."); + } + } + // The dispatch counts threads; the host counts groups of the shader's thread size. public static long ZeroGroupSkips; @@ -370,7 +489,7 @@ private MetadataBufferProbe[] DecodeMetadataClear(ComputeInputInfo input) var descriptor = BufferDescriptorWords.From(words); if (!resource.Formatted || !resource.Written || resource.Read || resource.Atomic || resource.Scalar || resource.MaxByteExtent != ImageClearStride || descriptor.Stride != ImageClearStride || descriptor.Format != BufferDescriptorWords.Format32x4UInt || descriptor.SwizzleEnabled || - descriptor.IndexStride != 0 || descriptor.AddThreadId || resource.PackedStride != descriptor.PackedStride || + descriptor.IndexStride != 0 || descriptor.AddThreadId || program.UserDataBase != 0 || resources.UserData.Length != ImageClearUserDataCount) { return null; diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.DynamicState.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.DynamicState.cs index b03afcd6c..2e06ff334 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.DynamicState.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.DynamicState.cs @@ -170,6 +170,8 @@ private DynamicDrawState BuildDynamicState(RegisterBanks banks, in DrawState sta (uint)position, colorWriteMask, context.DepthCountControl, + depthState.FrontOperations, + depthState.BackOperations, depthState.DepthBoundsTestEnabled, depthState.DepthMinBounds, depthState.DepthMaxBounds); diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.PendingWrites.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.PendingWrites.cs index ed4d961d2..ff162ad4c 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.PendingWrites.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.PendingWrites.cs @@ -163,6 +163,15 @@ private void MarkStageWrites(in ShaderStageResources stage, long sequence) PendingWrites.Mark(range.Base, range.Size, sequence, PendingWriteKind.Range); } } + + // The buffers the stage's call records name for their callees (ShaderStageResources.CallRecordRanges). + foreach (var range in stage.CallRecordRanges ?? []) + { + if (range.Written) + { + PendingWrites.Mark(range.Base, range.Size, sequence, PendingWriteKind.Range); + } + } } private static bool TryGetImageData(ShaderProgramInfo program, ImageResource image, uint[] words, int imageIndex, out GuestSpan data) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.cs index 201920d8a..5c49a736f 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.cs @@ -359,14 +359,18 @@ void TraceDisposition(string disposition) TraceDrawState(submitId, banks, in draw, in state); var indirect = arguments.OffsetSource == DrawOffsetSource.IndirectArguments; + // An offset the indirect packet passes in a named register is 0 in the arguments; a fetch the host replaced adds it + // from that register (ResolveVertexOffset(0, ...) and ResolveInstanceOffset are 0 for a program that fetches itself). var vertexOffset = indirect - ? arguments.BaseVertex + ? arguments.BaseVertex + (arguments.BaseVertexInRegister ? ResolveVertexOffset(0, state.Programs.VertexInput) : 0) : ResolveVertexOffset(userConfig.IndexOffset, state.Programs.VertexInput) + arguments.BaseVertex; var emission = new DrawEmission( true, vertexOffset, 0, - indirect ? arguments.FirstInstance : ResolveInstanceOffset(state.Programs.VertexInput), + indirect + ? arguments.FirstInstance + (arguments.FirstInstanceInRegister ? ResolveInstanceOffset(state.Programs.VertexInput) : 0) + : ResolveInstanceOffset(state.Programs.VertexInput), arguments.IndirectArgumentsAddress); record.IndexedTrace = traceSample; record.PacketAddress = tracePacket; @@ -398,7 +402,12 @@ public void DrawAuto(ulong submitId, RegisterBanks banks, in DrawAutoArguments a private bool CanDrawAutoIndirectOnGpu(RegisterBanks banks, ulong argumentsAddress) { - if (UsesMeshExecution(banks) || Pipelines.ShaderPipelineCache.IsMergedTessellationMask(banks.Context.ShaderStages) || + if (UsesMeshExecution(banks)) + { + return CanDrawMeshAutoIndirectOnGpu(banks, argumentsAddress); + } + + if (Pipelines.ShaderPipelineCache.IsMergedTessellationMask(banks.Context.ShaderStages) || (argumentsAddress & 3) != 0 || argumentsAddress > ulong.MaxValue - AutoIndirectArgumentsSize || _host.ClampMappedSize(argumentsAddress, AutoIndirectArgumentsSize) != AutoIndirectArgumentsSize) { @@ -410,6 +419,20 @@ GuestPrimitiveType.LineStrip or GuestPrimitiveType.TriangleList or GuestPrimitiv GuestPrimitiveType.TriangleFan or GuestPrimitiveType.Polygon or GuestPrimitiveType.RectangleList; } + // A mesh program of a point or triangle list reads the arguments of an automatic indirect + // draw on the GPU, which derives its workgroup counts; every other mesh draw reads them here. + private bool CanDrawMeshAutoIndirectOnGpu(RegisterBanks banks, ulong argumentsAddress) + { + if (!_host.SupportsIndirectMeshDraw || + (GuestPrimitiveType)banks.UserConfig.PrimitiveType is not (GuestPrimitiveType.PointList or GuestPrimitiveType.TriangleList) || + (argumentsAddress & 3) != 0 || argumentsAddress > ulong.MaxValue - AutoIndirectArgumentsSize) + { + return false; + } + + return _host.ClampMappedSize(argumentsAddress, AutoIndirectArgumentsSize) == AutoIndirectArgumentsSize; + } + private void DrawAutoWithCpuArguments(ulong submitId, RegisterBanks banks, in DrawAutoArguments arguments) { Span bytes = stackalloc byte[(int)AutoIndirectArgumentsSize]; @@ -445,7 +468,8 @@ private void DrawAutoCore(ulong submitId, RegisterBanks banks, in DrawAutoArgume var userConfig = banks.UserConfig; var shader = banks.Shader; - if (arguments.VertexCount == 0 || arguments.InstanceCount == 0) + // An indirect draw's counts are still on the GPU. + if (arguments.IndirectArgumentsAddress == 0 && (arguments.VertexCount == 0 || arguments.InstanceCount == 0)) { TraceDrawTargets(banks, "zero-count"); Record(record); @@ -524,7 +548,17 @@ private void DrawAutoCore(ulong submitId, RegisterBanks banks, in DrawAutoArgume return; } - ResolveShaderPrograms(banks, ref state); + ResolveShaderPrograms(banks, ref state, indirect: arguments.IndirectArgumentsAddress != 0); + if (arguments.IndirectArgumentsAddress != 0 && + (state.Programs.SolidClear is not null || (state.Programs.Available && MayBeMetadataClearQuad(banks, ref state)))) + { + // A clear program stands in for the draw only when the draw has something to draw, and a metadata clear + // quad is recognized from its count and positions. + Record(record); + DrawAutoWithCpuArguments(submitId, banks, in arguments); + return; + } + var vertexInput = state.Programs.VertexInput; var pixelInput = state.Programs.PixelInput; var rectangleList = topology == PrimitiveTopology.PatchList; @@ -553,14 +587,17 @@ private void DrawAutoCore(ulong submitId, RegisterBanks banks, in DrawAutoArgume TraceDrawState(submitId, banks, in draw, in state); var indirect = arguments.OffsetSource == DrawOffsetSource.IndirectArguments; + // As for indexed draws: a named register's offset reaches a fetch the host replaced. var vertexOffset = indirect - ? (int)arguments.FirstVertex + ? (int)arguments.FirstVertex + (arguments.FirstVertexInRegister ? ResolveVertexOffset(0, vertexInput) : 0) : ResolveVertexOffset(userConfig.IndexOffset, vertexInput) + (int)arguments.FirstVertex; var emission = new DrawEmission( false, 0, (uint)vertexOffset, - indirect ? arguments.FirstInstance : ResolveInstanceOffset(vertexInput), + indirect + ? arguments.FirstInstance + (arguments.FirstInstanceInRegister ? ResolveInstanceOffset(vertexInput) : 0) + : ResolveInstanceOffset(vertexInput), arguments.IndirectArgumentsAddress); record.PacketAddress = arguments.PacketAddress; FillDraw(record, banks, in draw, ref state, topology, in emission, default, primitiveRestart: false, setBindDebug: false, setAutoDebug: true); @@ -954,7 +991,7 @@ private void ValidateChangedDrawRegisters(RegisterBanks banks) resolution.ValidatedUserConfigStamp = userConfigStamp; } - private void ResolveShaderPrograms(RegisterBanks banks, ref DrawState state, bool indexed = false) + private void ResolveShaderPrograms(RegisterBanks banks, ref DrawState state, bool indexed = false, bool indirect = false) { if (state.Programs is not null) { @@ -980,7 +1017,9 @@ private void ResolveShaderPrograms(RegisterBanks banks, ref DrawState state, boo userConfig.PrimitiveType = (uint)GuestPrimitiveType.TriangleList; } - state.Programs = _pipelines.GetMeshGraphicsPrograms(banks, userConfig, targetExportMapping, state.PixelActive, state.Depth.HasTarget); + var taskLaunch = indirect && !indexed && MeshTaskLaunch.Active; + state.Programs = _pipelines.GetMeshGraphicsPrograms(banks, userConfig, targetExportMapping, state.PixelActive, state.Depth.HasTarget, + taskLaunch); return; } diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Compute.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Compute.cs index c32f9df3a..959aa4b42 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Compute.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Compute.cs @@ -114,6 +114,11 @@ private void RecordDispatch(ResolvedDispatch record) _keptComputePipeline = pipeline; } + // The indirect arguments are registered before the resources bind, so acquiring them merges no owner the + // dispatch already bound. + using var arguments = record.IndirectArgumentsAddress != 0 + ? _host.PrepareIndirectDispatchArguments(record.IndirectArgumentsAddress) + : null; var bindings = PrepareBindings(input.Stage); if (program.UsesDeviceAddresses) { @@ -121,6 +126,28 @@ private void RecordDispatch(ResolvedDispatch record) } _host.BindResources(bindings); + var owners = _host.BufferOwnerGeneration; + // Diagnostic readbacks may finish a submission. Complete them before final native bindings. + var imageSnapshot = _host.BeginComputeImageSnapshot(bindings); + arguments?.Rebind(); + for (var attempt = 0; _host.BufferOwnerGeneration != owners; attempt++) + { + if (attempt == 8) + { + throw _host.Fatal("Compute buffer owners did not stabilize."); + } + + owners = _host.BufferOwnerGeneration; + _host.RebindBuffers(bindings); + arguments?.Rebind(); + } + + // The groups and thread limits come from the GPU-written counts; the pass binds its own pipeline, so it is + // recorded before this dispatch's bindings and outside its checked window. + using var threadDispatch = record.GpuThreadCounts + ? _host.PrepareThreadDispatch(arguments ?? throw _host.Fatal("GPU thread counts have no prepared arguments."), + bindings, [input.ThreadsX, input.ThreadsY, input.ThreadsZ], GroupAxisOrder(input)) + : null; Span stages = [bindings]; _host.CommitBindings(PipelineBindPoint.Compute, in pipeline, stages); var chain = _dispatchChain ??= new DispatchChain(); @@ -130,10 +157,13 @@ private void RecordDispatch(ResolvedDispatch record) _host.ShaderWriteHazardBarrier(); } - var imageSnapshot = _host.BeginComputeImageSnapshot(bindings); _host.BeginCheckedDispatch(); _host.BindPipeline(PipelineBindPoint.Compute, in pipeline); - if (record.IndirectArgumentsAddress == 0 || !_host.TryDispatchIndirect(record.IndirectArgumentsAddress, GroupAxisOrder(input))) + if (threadDispatch is not null) + { + threadDispatch.Dispatch(); + } + else if (record.IndirectArgumentsAddress == 0 || !TryDispatchIndirect(record, arguments, input)) { var (groupsX, groupsY, groupsZ) = PhysicalGroups(input, record); _host.Dispatch(groupsX, groupsY, groupsZ); @@ -260,6 +290,11 @@ private bool TryClearMetadata(MetadataBufferProbe[] probes, bool hasExclusiveOr, return false; } + private bool TryDispatchIndirect(ResolvedDispatch record, IIndirectDispatchArguments? arguments, ComputeInputInfo input) => + arguments is not null + ? _host.TryDispatchIndirect(arguments, GroupAxisOrder(input)) + : _host.TryDispatchIndirect(record.IndirectArgumentsAddress, GroupAxisOrder(input)); + private static int[] GroupAxisOrder(ComputeInputInfo input) => Gen5SpirvTranslator.ComputeGroupAxisOrder(input.ThreadsX, input.ThreadsY, input.ThreadsZ, input.GroupIdX, input.GroupIdY, input.GroupIdZ); diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Tessellation.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Tessellation.cs index 8cb8e956b..067c881a4 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Tessellation.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Tessellation.cs @@ -21,7 +21,6 @@ private void RecordTessellation(ResolvedDraw record, ref DrawState state) var draw = record.Draw; var count = draw.Count; var instances = draw.InstanceCount; - var firstInstance = draw.FirstInstance; var indexAddress = record.TessellationIndexAddress; var indexSize = record.TessellationIndexSize; var vertexOffset = record.TessellationVertexOffset; @@ -52,7 +51,10 @@ private void RecordTessellation(ResolvedDraw record, ref DrawState state) localDataSlotBytes = System.Numerics.BitOperations.RoundUpToPowerOf2(Math.Max(input.LocalDataShareDwords, 1u)) * sizeof(uint); if (ringAddress == 0 || ringBytes < localDataSlotBytes) throw _host.Fatal("The tessellation local data ring is unavailable or smaller than one hull group."); - offchipBuffers = (uint)Math.Min(ringBytes / localDataSlotBytes, uint.MaxValue); + // A group also takes a slot of the local data ring, so the ring bounds the groups as well. It does not lift + // the off-chip bound: a group past the guest's off-chip buffers would write its off-chip data beyond them. + var ringSlots = (uint)Math.Min(ringBytes / localDataSlotBytes, uint.MaxValue); + offchipBuffers = offchipBuffers == 0 ? ringSlots : Math.Min(offchipBuffers, ringSlots); } var groupsPerBatch = offchipBuffers == 0 ? 1u : (uint)Math.Clamp(Math.Min(offchipBuffers, factorSize / groupFactorBytes), 1, uint.MaxValue); var batchCapacity = groupsPerBatch * layout.PatchesPerGroup; @@ -80,7 +82,6 @@ private void RecordTessellation(ResolvedDraw record, ref DrawState state) data[Gen5TessellationData.FirstPatch] = firstPatch; data[Gen5TessellationData.PatchCount] = batchPatches; data[Gen5TessellationData.VertexOffset] = unchecked((uint)vertexOffset); - data[Gen5TessellationData.InstanceId] = firstInstance; data[Gen5TessellationData.PatchesPerInstance] = patches; data[Gen5TessellationData.IndexSize] = indexSize; data[Gen5TessellationData.FactorBytes] = batchPatches * patchFactorBytes; diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs index ccc44d1fc..c7299e5b1 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs @@ -28,6 +28,7 @@ internal sealed partial class RenderRecorder : IResolvedCommandSink private readonly KeptPipeline _pipeline = new(); private readonly InPlaceDraw _inPlace = new(); private long _sequence; + private static int _meshDrawsOverLimits; private static readonly ThreadCounter _inPlaceDraws = new(); private static readonly ThreadCounter _inPlaceRefused = new(); @@ -378,10 +379,20 @@ private void RecordDrawCommands(ResolvedDraw record, ref DrawState state, bool i ref readonly var indexSource = ref record.Index; using var preparation = _host.BeginPreparation(); using var indirectMesh = meshInput is not null && emission.IndirectArgumentsAddress != 0 - ? _host.PrepareIndirectMeshDraw(new IndirectMeshDrawRequest(emission.IndirectArgumentsAddress, - indexSource.Address, draw.Count, indexSource.Type == IndexType.Uint16 ? 2u : 4u, - topology == PrimitiveTopology.PointList, meshInput.Geometry.InputPrimitiveCountPerWorkgroup, meshInput.Execution)) + ? _host.PrepareIndirectMeshDraw(emission.Indexed + ? new IndirectMeshDrawRequest(emission.IndirectArgumentsAddress, + indexSource.Address, draw.Count, indexSource.Type == IndexType.Uint16 ? 2u : 4u, + topology == PrimitiveTopology.PointList, meshInput.Geometry.InputPrimitiveCountPerWorkgroup, meshInput.Execution) + : IndirectMeshDrawRequest.ForAutomaticDraw(emission.IndirectArgumentsAddress, + topology == PrimitiveTopology.PointList, meshInput.Geometry.InputPrimitiveCountPerWorkgroup, meshInput.Execution) + with { TaskLaunched = meshInput.Geometry.TaskLaunched }) : null; + // Only an automatic indirect draw resolves a task-launched program; anything else is a broken join. + if (meshInput is { Geometry.TaskLaunched: true } && (emission.IndirectArgumentsAddress == 0 || emission.Indexed)) + { + throw _host.Fatal("A task-launched mesh program reached a draw that is not automatic and indirect."); + } + var meshVertexCount = draw.Count; if (MeshDrawTrace.Active) MeshDrawTrace.Write("programs", $"mesh={meshInput is not null} vertexHash=0x{vertexInput.Stage.Program?.Hash:X16} pixelHash=0x{pixelInput.Stage.Program?.Hash:X16} pixelActive={state.PixelActive}"); @@ -484,6 +495,7 @@ private void RecordDrawCommands(ResolvedDraw record, ref DrawState state, bool i _host.PrepareDeviceAddresses(); } + var owners = _host.BufferOwnerGeneration; _host.BindResources(vertexBindings); if (pixelBindings is not null) { @@ -510,6 +522,35 @@ private void RecordDrawCommands(ResolvedDraw record, ref DrawState state, bool i state.Rendering = AcquireAttachments(ref state); } + + // An owner bound above can be merged by a later stage or acquisition; bind and acquire the buffers again + // until none changes, so the draw records no retired owner. + for (var attempt = 0; _host.BufferOwnerGeneration != owners; attempt++) + { + if (attempt == 8) + { + throw _host.Fatal("Buffer owners kept changing while a draw was prepared."); + } + + owners = _host.BufferOwnerGeneration; + _host.RebindBuffers(vertexBindings); + if (pixelBindings is not null) + { + _host.RebindBuffers(pixelBindings); + } + + if (meshInput is null) + { + vertexBuffers = AcquireVertexBuffers(vertexInput); + indexBuffer = AcquireIndexBuffer(in indexSource); + if (emission.IndirectArgumentsAddress != 0) + { + indirectArguments = _host.ObtainBuffer(emission.IndirectArgumentsAddress, + emission.Indexed ? RenderExecutor.IndexedIndirectArgumentsSize : RenderExecutor.AutoIndirectArgumentsSize, isWritten: false); + } + } + } + var pipeline = ResolvePipeline(record, ref state, vertexInput, state.PixelActive ? pixelInput : null); if (record.SetBindDebug) { @@ -627,9 +668,17 @@ private void DrawMeshTasks(ResolvedDraw record, MeshDrawConfiguration mesh, uint if (groupCount > mesh.Execution.MaxGroupCountX || draw.InstanceCount > mesh.Execution.MaxGroupCountY || totalGroupCount > mesh.Execution.MaxGroupTotalCount) { - throw _host.Fatal($"The mesh draw exceeds device group limits: groups={groupCount}/{mesh.Execution.MaxGroupCountX} " + - $"instances={draw.InstanceCount}/{mesh.Execution.MaxGroupCountY} " + - $"total={totalGroupCount}/{mesh.Execution.MaxGroupTotalCount}."); + // Left out, as the GPU preparation leaves out an indirect draw over the limits. + var left = Interlocked.Increment(ref _meshDrawsOverLimits); + if ((left & (left - 1)) == 0) + { + Console.Error.WriteLine($"[GPU][WARN] A mesh draw over the device group limits was left out ({left} so far): " + + $"groups={groupCount}/{mesh.Execution.MaxGroupCountX} instances={draw.InstanceCount}/{mesh.Execution.MaxGroupCountY} " + + $"total={totalGroupCount}/{mesh.Execution.MaxGroupTotalCount} vertices={draw.Count} " + + $"hash=0x{(record.State.Programs.VertexInput.Stage.Program?.Hash ?? 0ul):X16}."); + } + + return; } if (RenderTrace.Enabled) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ResolvedCommands.cs b/src/SharpEmu.Libs/Gpu/Rendering/ResolvedCommands.cs index 9d8486e41..05cafcbad 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ResolvedCommands.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ResolvedCommands.cs @@ -170,6 +170,8 @@ internal sealed class ResolvedDispatch public uint GroupsY; public uint GroupsZ; public ulong IndirectArgumentsAddress; + // The indirect arguments count threads the GPU converts to groups (IRenderHost.PrepareThreadDispatch). + public bool GpuThreadCounts; public MetadataBufferProbe[]? MetadataClear; public bool MetadataClearHasExclusiveOr; public ConstantFillCandidate? ConstantFill; @@ -190,6 +192,7 @@ public void Reset() GroupsY = 0; GroupsZ = 0; IndirectArgumentsAddress = 0; + GpuThreadCounts = false; MetadataClear = null; MetadataClearHasExclusiveOr = false; ConstantFill = null; diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs b/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs index 696a193d0..ff25eaa83 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs @@ -33,8 +33,7 @@ public readonly record struct BufferResourceInfo( bool Atomic, bool Formatted, bool Scalar, - uint MaxByteExtent, - uint PackedStride); + uint MaxByteExtent); // How a compiled program uses one image resource. public readonly record struct ImageResourceInfo(ImageResourceClass Class, bool Written); @@ -83,15 +82,29 @@ public class ShaderProgramInfo // What the host resolves for each record of each callee, by callee slot, when the program reads its records' // descriptors at run time (ShaderCompileRequest.CallRecordCallees). public IReadOnlyList CallRecordCallees { get; init; } = []; + + // A task-launched mesh program: its pipelines take the task stage, specialized with these values. + public MeshTaskLaunchInfo? MeshTask { get; init; } } +// Null RequestedGeneration means the requested link is still pending: its exact layout identity is known, but no +// linked generation exists yet. "link", "permutation" and "pipeline" name the work that forced the fallback. +public sealed record LinkedCompileFallback(ulong CallerHash, long? RequestedGeneration, long ServedGeneration, + string RequestedLibrary, string ServedLibrary, string Reason); + // One shader stage bound to a draw or dispatch: its program, the resources it reads and its code base. public readonly record struct ShaderStageResources(ShaderProgramInfo? Program, ResourceSnapshot Resources, ulong ShaderBase = 0) { public bool IsValid => Program is not null; + // Per-resolution provenance of a compile fallback (ShaderProgramCache). It is never stored on a shared module. + public LinkedCompileFallback? CompileFallback { get; init; } + public DispatchThreadLimits? ThreadLimits { get; init; } + // The thread limits come from GPU memory (ComputeInputInfo.IndirectThreadCounts); the host writes none. + public bool GpuThreadLimits { get; init; } + public MeshDrawParameters? MeshDraw { get; init; } public uint[]? TessellationData { get; init; } @@ -126,7 +139,7 @@ public void WriteTessellationData(Span shaderData) public void WriteDispatchThreadLimits(Span shaderData) { - if (Program?.Bindings is not { UsesDispatchThreadLimits: true } layout) return; + if (Program?.Bindings is not { UsesDispatchThreadLimits: true } layout || GpuThreadLimits) return; if (ThreadLimits is not { } limits || shaderData.Length != layout.ShaderDataDwordCount) { throw SubmissionScheduler.Fatal("The compute dispatch has missing thread limits or invalid shader data."); @@ -264,8 +277,13 @@ public readonly record struct GuestGeometryConfiguration public uint LocalDataShareDwords { get; init; } public uint PositionExportControl { get; init; } public ClipSpaceTransform ClipSpace { get; init; } + // The program is launched by the task stage (MeshTaskLaunch): it reads its draw parameters from the task payload. + public bool TaskLaunched { get; init; } } +// What the task stage of a task-launched mesh program is specialized with. +public readonly record struct MeshTaskLaunchInfo(uint PrimitivesPerGroup, bool PointList); + public sealed class PixelInputInfo { public const int InterpolatorCount = 32; @@ -313,6 +331,8 @@ public sealed class ComputeInputInfo public uint ThreadsY { get; init; } public uint ThreadsZ { get; init; } public bool DispatchThreadDimensions { get; init; } + // The thread counts are in GPU memory: the GPU writes the thread limits (IRenderHost.PrepareThreadDispatch). + public bool IndirectThreadCounts { get; init; } public uint DispatchThreadsX { get; set; } public uint DispatchThreadsY { get; set; } public uint DispatchThreadsZ { get; set; } diff --git a/src/SharpEmu.Libs/Gpu/Scheduling/PendingGuestPublications.cs b/src/SharpEmu.Libs/Gpu/Scheduling/PendingGuestPublications.cs index 284db5e40..c3f086180 100644 --- a/src/SharpEmu.Libs/Gpu/Scheduling/PendingGuestPublications.cs +++ b/src/SharpEmu.Libs/Gpu/Scheduling/PendingGuestPublications.cs @@ -15,8 +15,10 @@ internal sealed class Entry(int queue, ulong address, ulong size) internal bool Registered; internal volatile bool Completed; internal bool DeferredLabel; - // A held-back command write: command-processor reads wait for it, unlike a label they forward. + // A held-back command write: CPU reads wait for its publication; command-processor reads take Payload, as + // they take a deferred label, and keep their order after it (ForwardHeldWrites). internal bool HeldWrite; + internal byte[]? Payload; internal ulong Value; // A dump with a GPU slot can be copied into a reading buffer instead of waited for. internal long GpuSlot = -1; @@ -58,6 +60,17 @@ internal bool QueueFollows(int queue, long ordinal) private volatile Entry[] _dumps = []; private volatile Exception? _failure; + // A dump lookup remembers, per thread, the empty gap between pending dumps that its range fell in, and a later lookup + // inside that gap of the same dump array answers without a scan. SHARPEMU_PUBLICATION_GAPS=0 scans every lookup. + internal bool ReusePublicationGaps { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_PUBLICATION_GAPS") != "0"; + + // Only immutable range membership is cached, never Tick/Publishing/GpuSlot. + // Index replaces the array on every ranged dump addition and removal. One + // thread cannot borrow or mutate another thread's proof, even for this owner. + private readonly record struct DumpGap(PendingGuestPublications Owner, Entry[] Snapshot, ulong Start, ulong End); + [ThreadStatic] private static DumpGap _lastDumpGap; + private static int FilterSlot(ulong page) => (int)((page * 0x9E37_79B9_7F4A_7C15UL) >> (64 - PageFilterBits)); // Descriptor and buffer lookups call this often; a range with no pending page skips the lock. @@ -101,13 +114,48 @@ private bool DumpOverlap(ulong address, ulong size, bool skipGpuSlots, out ulong { var found = false; tick = 0; - foreach (var dump in _dumps) + var dumps = _dumps; + if (dumps.Length == 0) return false; + var reuse = ReusePublicationGaps; + if (!reuse) { - if (address >= dump.Address + dump.Size || dump.Address >= address + size) continue; + foreach (var dump in dumps) + { + if (address >= dump.Address + dump.Size || dump.Address >= address + size) continue; + if (skipGpuSlots && dump.GpuSlot >= 0) continue; + found = true; + if (!dump.Publishing) tick = Math.Max(tick, dump.Tick); + } + return found; + } + var end = address + size; // The callers already rejected overflow/empty ranges. + var gap = _lastDumpGap; + if (ReferenceEquals(gap.Owner, this) && ReferenceEquals(gap.Snapshot, dumps) && + address >= gap.Start && end <= gap.End) + { + return false; + } + + ulong left = 0, right = ulong.MaxValue; + var rawOverlap = false; + foreach (var dump in dumps) + { + if (address >= dump.Address + dump.Size) + { + left = Math.Max(left, dump.Address + dump.Size); + continue; + } + if (dump.Address >= end) + { + right = Math.Min(right, dump.Address); + continue; + } + rawOverlap = true; if (skipGpuSlots && dump.GpuSlot >= 0) continue; found = true; if (!dump.Publishing) tick = Math.Max(tick, dump.Tick); } + if (!rawOverlap) _lastDumpGap = new(this, dumps, left, right); return found; } @@ -160,7 +208,27 @@ internal bool TryOverlayLabels(int readerQueue, ulong address, Span bytes, foreach (var entry in _entries) { if (entry.Size == 0 || address >= entry.Address + entry.Size || entry.Address >= address + size) continue; - if (!entry.DeferredLabel) return false; + if (!entry.DeferredLabel) + { + // A command-processor reader may take a held write's known bytes; the CPU never does. + if (!(entry.HeldWrite && entry.Payload is { } payload && readerQueue >= 0 && ForwardHeldWrites)) + { + return false; + } + + if (entry.Queue != readerQueue) newestForeign = entry; + var heldFirst = Math.Max(address, entry.Address); + var heldLast = Math.Min(address + size, entry.Address + entry.Size); + for (var byteAddress = heldFirst; byteAddress < heldLast; byteAddress++) + { + var index = (int)(byteAddress - address); + bytes[index] = payload[byteAddress - entry.Address]; + coveredMask |= 1 << index; + } + + continue; + } + if (readerQueue >= 0 && entry.Queue != readerQueue) newestForeign = entry; var first = Math.Max(address, entry.Address); var last = Math.Min(address + size, entry.Address + entry.Size); @@ -204,14 +272,21 @@ internal Entry AddOrdering(int queue) } // A held-back command-processor write; readers wait for it like a dump. - internal Entry AddWrite(int queue, ulong address, ulong size) + // A command-processor label read takes a held write's bytes instead of waiting for its publication: the write was + // held only so the CPU sees it after the foreign label it follows, and the reading queue keeps its own order after + // it. SHARPEMU_FORWARD_HELD_WRITES=0 makes the reads wait again. + private static readonly bool DefaultForwardHeldWrites = Environment.GetEnvironmentVariable("SHARPEMU_FORWARD_HELD_WRITES") != "0"; + + internal bool ForwardHeldWrites { get; set; } = DefaultForwardHeldWrites; + + internal Entry AddWrite(int queue, ulong address, ulong size, byte[]? payload = null) { if (size == 0 || address > ulong.MaxValue - size) throw new ArgumentOutOfRangeException(nameof(size)); lock (_gate) { ThrowIfFailed(); - var entry = new Entry(queue, address, size) { HeldWrite = true }; + var entry = new Entry(queue, address, size) { HeldWrite = true, Payload = payload }; _entries.Add(entry); Track(entry); Index(entry, 1); diff --git a/src/SharpEmu.Libs/Gpu/Scheduling/SubmissionScheduler.cs b/src/SharpEmu.Libs/Gpu/Scheduling/SubmissionScheduler.cs index 8fccf0b73..058eec343 100644 --- a/src/SharpEmu.Libs/Gpu/Scheduling/SubmissionScheduler.cs +++ b/src/SharpEmu.Libs/Gpu/Scheduling/SubmissionScheduler.cs @@ -184,6 +184,10 @@ internal static Exception Fatal(string message) } Console.Error.WriteLine($"[GPU][FATAL] {message}"); + if (message.Contains("DeviceLost", StringComparison.Ordinal)) + { + SharpEmu.Libs.Gpu.Vulkan.DeviceFaultReport.Write(); + } OnFatal(message); return new InvalidOperationException(message); } diff --git a/src/SharpEmu.Libs/Gpu/Scheduling/SubmitBundle.cs b/src/SharpEmu.Libs/Gpu/Scheduling/SubmitBundle.cs index 0384b5285..cc0dbbd36 100644 --- a/src/SharpEmu.Libs/Gpu/Scheduling/SubmitBundle.cs +++ b/src/SharpEmu.Libs/Gpu/Scheduling/SubmitBundle.cs @@ -31,6 +31,13 @@ public SubmitBundle(SubmitBundle source) public int WaitCount { get; private set; } + // Empties the bundle for reuse (the native recorder's submissions). + internal void Clear() + { + WaitCount = 0; + SignalCount = 0; + } + public int SignalCount { get; private set; } public void AddWait(ulong semaphore, ulong tick = 1, uint stage = AllCommandsStage) diff --git a/src/SharpEmu.Libs/Gpu/Vulkan/DeviceFaultReport.cs b/src/SharpEmu.Libs/Gpu/Vulkan/DeviceFaultReport.cs new file mode 100644 index 000000000..0651bce88 --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/Vulkan/DeviceFaultReport.cs @@ -0,0 +1,186 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections.Concurrent; +using System.Runtime.InteropServices; +using Silk.NET.Vulkan; + +namespace SharpEmu.Libs.Gpu.Vulkan; + +// Local diagnostic (SHARPEMU_DEVICE_FAULT_REPORT=1): on a lost device, print the driver's fault report +// (VK_EXT_device_fault) and the buffers whose device address ranges hold or precede each reported address. +internal static unsafe class DeviceFaultReport +{ + internal static readonly bool Requested = Environment.GetEnvironmentVariable("SHARPEMU_DEVICE_FAULT_REPORT") == "1"; + + private static readonly ConcurrentDictionary Buffers = new(); + private static readonly ConcurrentQueue<(ulong Address, ulong Size, string Usage, ulong CpuAddress, long Created, long Released)> Released = new(); + private static Vk? _vk; + private static Device _device; + private static int _written; + private static long _sequence; + + internal static void Attach(Vk vk, Device device, bool vendorBinary) + { + _device = device; + _written = 0; + Done.Reset(); + _vk = vk; + Console.Error.WriteLine($"[GPU][FAULT] VK_EXT_device_fault enabled vendor_binary={(vendorBinary ? 1 : 0)}"); + } + + internal static void Detach(Device device) + { + if (_device.Handle != device.Handle) return; + _vk = null; + Buffers.Clear(); + Released.Clear(); + } + + internal static void Track(ulong deviceAddress, ulong size, string usage, ulong cpuAddress) + { + if (!Requested || deviceAddress == 0) return; + Buffers[deviceAddress] = (size, usage, cpuAddress, Interlocked.Increment(ref _sequence)); + } + + internal static void Untrack(ulong deviceAddress) + { + if (!Requested || deviceAddress == 0 || !Buffers.TryRemove(deviceAddress, out var buffer)) return; + Released.Enqueue((deviceAddress, buffer.Size, buffer.Usage, buffer.CpuAddress, buffer.Created, Interlocked.Increment(ref _sequence))); + while (Released.Count > 4096 && Released.TryDequeue(out _)) + { + } + } + + private static readonly ManualResetEventSlim Done = new(false); + + // Every lost-device fatal waits here, so the first report is complete before any of them stops the process. + internal static void Write() + { + var vk = _vk; + if (vk is null) return; + if (Interlocked.Exchange(ref _written, 1) != 0) + { + Done.Wait(TimeSpan.FromSeconds(20)); + return; + } + + var report = new System.Text.StringBuilder(); + try + { + var get = (delegate* unmanaged) + vk.GetDeviceProcAddr(_device, "vkGetDeviceFaultInfoEXT").Handle; + if (get is null) + { + report.AppendLine("[GPU][FAULT] vkGetDeviceFaultInfoEXT is unavailable"); + return; + } + + var counts = new DeviceFaultCountsEXT { SType = StructureType.DeviceFaultCountsExt }; + var result = get(_device, &counts, null); + report.AppendLine($"[GPU][FAULT] counts result={result} addresses={counts.AddressInfoCount} vendor={counts.VendorInfoCount} binary={counts.VendorBinarySize}"); + if (result != Result.Success && result != Result.Incomplete) return; + var addresses = new DeviceFaultAddressInfoEXT[Math.Max(1, checked((int)counts.AddressInfoCount))]; + var vendors = new DeviceFaultVendorInfoEXT[Math.Max(1, checked((int)counts.VendorInfoCount))]; + var binary = new byte[Math.Max(1, checked((int)counts.VendorBinarySize))]; + fixed (DeviceFaultAddressInfoEXT* addressInfos = addresses) + fixed (DeviceFaultVendorInfoEXT* vendorInfos = vendors) + fixed (byte* binaryData = binary) + { + var info = new DeviceFaultInfoEXT + { + SType = StructureType.DeviceFaultInfoExt, + PAddressInfos = counts.AddressInfoCount != 0 ? addressInfos : null, + PVendorInfos = counts.VendorInfoCount != 0 ? vendorInfos : null, + PVendorBinaryData = counts.VendorBinarySize != 0 ? binaryData : null, + }; + result = get(_device, &counts, &info); + report.AppendLine($"[GPU][FAULT] info result={result} description=\"{Text(info.Description)}\""); + if (result != Result.Success && result != Result.Incomplete) return; + var live = Buffers.ToArray(); + Array.Sort(live, (left, right) => left.Key.CompareTo(right.Key)); + var released = Released.ToArray(); + var seen = new HashSet<(DeviceFaultAddressTypeEXT, ulong)>(); + for (var index = 0u; index < counts.AddressInfoCount; index++) + { + var address = addressInfos[index]; + if (!seen.Add((address.AddressType, address.ReportedAddress))) continue; + report.AppendLine( + $"[GPU][FAULT] address[{index}] type={address.AddressType} reported=0x{address.ReportedAddress:X16} precision=0x{address.AddressPrecision:X}"); + DescribeBuffers(report, live, released, address.ReportedAddress); + } + + for (var index = 0u; index < counts.VendorInfoCount; index++) + { + var vendor = vendorInfos[index]; + report.AppendLine( + $"[GPU][FAULT] vendor code=0x{vendor.VendorFaultCode:X} data=0x{vendor.VendorFaultData:X} description=\"{Text(vendor.Description)}\""); + } + + if (counts.VendorBinarySize != 0) + { + var path = Path.Combine(Path.GetTempPath(), $"sharpemu-device-fault-{Environment.ProcessId}.bin"); + File.WriteAllBytes(path, binary.AsSpan(0, checked((int)counts.VendorBinarySize)).ToArray()); + report.AppendLine($"[GPU][FAULT] vendor binary written: {path}"); + } + } + } + catch (Exception exception) + { + report.AppendLine($"[GPU][FAULT] report failed: {exception.GetType().Name}: {exception.Message}"); + } + finally + { + try + { + Console.Error.Write(report.ToString()); + Console.Error.Flush(); + } + finally + { + Done.Set(); + } + } + } + + private static void DescribeBuffers(System.Text.StringBuilder report, + KeyValuePair[] live, + (ulong Address, ulong Size, string Usage, ulong CpuAddress, long Created, long Released)[] released, ulong address) + { + var low = 0; + var high = live.Length; + while (low < high) + { + var middle = low + (high - low) / 2; + if (live[middle].Key <= address) low = middle + 1; + else high = middle; + } + + for (var index = Math.Max(0, low - 2); index < low; index++) + { + var (start, buffer) = (live[index].Key, live[index].Value); + var end = start + buffer.Size; + var relation = address < end ? "inside" : $"past_end_by=0x{address - end:X}"; + report.AppendLine( + $"[GPU][FAULT] buffer 0x{start:X16}..0x{end:X16} size=0x{buffer.Size:X} usage={buffer.Usage} cpu=0x{buffer.CpuAddress:X16} seq={buffer.Created} {relation}"); + } + + if (low < live.Length) + { + var (start, buffer) = (live[low].Key, live[low].Value); + report.AppendLine( + $"[GPU][FAULT] next buffer 0x{start:X16} size=0x{buffer.Size:X} usage={buffer.Usage} cpu=0x{buffer.CpuAddress:X16} gap=0x{start - address:X}"); + } + + foreach (var entry in released) + { + if (address >= entry.Address && address - entry.Address < entry.Size) + { + report.AppendLine( + $"[GPU][FAULT] released buffer 0x{entry.Address:X16} size=0x{entry.Size:X} usage={entry.Usage} cpu=0x{entry.CpuAddress:X16} seq={entry.Created}..{entry.Released}"); + } + } + } + + private static string Text(byte* text) => Marshal.PtrToStringUTF8((nint)text) ?? string.Empty; +} diff --git a/src/SharpEmu.Libs/Gpu/Vulkan/VulkanGuestGpuBackend.cs b/src/SharpEmu.Libs/Gpu/Vulkan/VulkanGuestGpuBackend.cs index 80337c295..c8b82d9d3 100644 --- a/src/SharpEmu.Libs/Gpu/Vulkan/VulkanGuestGpuBackend.cs +++ b/src/SharpEmu.Libs/Gpu/Vulkan/VulkanGuestGpuBackend.cs @@ -37,6 +37,9 @@ public bool TryCompileProgram(ShaderCompileRequest request, out IGuestCompiledSh return true; } + public IGuestCompiledShader? CreateCachedShader(byte[] payload, uint? inputLocationMask) => + new VulkanCompiledGuestShader(payload) { InputLocationMask = inputLocationMask }; + public IGuestCompiledShader GetDepthOnlyFragmentShader() => DepthOnlyFragmentShader; diff --git a/src/SharpEmu.Libs/Kernel/KernelAprCompatExports.cs b/src/SharpEmu.Libs/Kernel/KernelAprCompatExports.cs index 1242b9d34..d2d995b1d 100644 --- a/src/SharpEmu.Libs/Kernel/KernelAprCompatExports.cs +++ b/src/SharpEmu.Libs/Kernel/KernelAprCompatExports.cs @@ -21,8 +21,7 @@ private readonly record struct AprSubmission( ulong CommandBuffer, ulong Priority, ulong ResultAddress, - int ExecutionResult, - uint ErrorOffset); + AmprExports.AmprSubmission Execution); [SysAbiExport( Nid = "ASoW5WE-UPo", @@ -47,24 +46,30 @@ public static int KernelAprSubmitCommandBufferAndGetResult(CpuContext ctx) submissionId = unchecked((uint)Interlocked.Increment(ref _nextSubmissionId)); } - var completionResult = AmprExports.CompleteCommandBuffer( + // A buffer that had to wait writes its result when it finishes on its queue. + var completionResult = AmprExports.SubmitCommandBuffer( ctx, commandBuffer, - out var executionResult, - out var errorOffset); + AmprExports.AmprEngine.Apr, + unchecked((uint)priority), + resultAddress == 0 + ? null + : (context, executionResult, errorOffset) => TryWriteAprResult(context, resultAddress, executionResult, errorOffset), + out var execution); if (completionResult != (int)OrbisGen2Result.ORBIS_GEN2_OK) { return completionResult; } _submittedCommandBuffers[submissionId] = - new AprSubmission(commandBuffer, priority, resultAddress, executionResult, errorOffset); + new AprSubmission(commandBuffer, priority, resultAddress, execution!); if (outSubmissionId != 0 && !ctx.TryWriteUInt32(outSubmissionId, submissionId)) { return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT; } - if (resultAddress != 0 && !TryWriteAprResult(ctx, resultAddress, executionResult, errorOffset)) + if (resultAddress != 0 && execution!.CompletedInline && + !TryWriteAprResult(ctx, resultAddress, execution.ExecutionResult, execution.ErrorOffset)) { return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT; } @@ -90,8 +95,9 @@ public static int KernelAprWaitCommandBuffer(CpuContext ctx) return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND; } + submission.Execution.Wait(); if (submission.ResultAddress != 0 && - !TryWriteAprResult(ctx, submission.ResultAddress, submission.ExecutionResult, submission.ErrorOffset)) + !TryWriteAprResult(ctx, submission.ResultAddress, submission.Execution.ExecutionResult, submission.Execution.ErrorOffset)) { return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT; } @@ -114,19 +120,22 @@ public static int KernelAprSubmitCommandBuffer(CpuContext ctx) } var submissionId = unchecked((uint)Interlocked.Increment(ref _nextSubmissionId)); - var completionResult = AmprExports.CompleteCommandBuffer( + var priority = ctx[CpuRegister.Rsi]; + var completionResult = AmprExports.SubmitCommandBuffer( ctx, commandBuffer, - out var executionResult, - out var errorOffset); + AmprExports.AmprEngine.Apr, + unchecked((uint)priority), + onQueuedCompletion: null, + out var execution); if (completionResult != (int)OrbisGen2Result.ORBIS_GEN2_OK) { return completionResult; } _submittedCommandBuffers[submissionId] = - new AprSubmission(commandBuffer, ctx[CpuRegister.Rsi], 0, executionResult, errorOffset); + new AprSubmission(commandBuffer, priority, 0, execution!); - TraceApr(ctx, "submit", submissionId, commandBuffer, ctx[CpuRegister.Rsi], 0); + TraceApr(ctx, "submit", submissionId, commandBuffer, priority, 0); return (int)OrbisGen2Result.ORBIS_GEN2_OK; } @@ -145,24 +154,27 @@ public static int KernelAprSubmitCommandBufferAndGetId(CpuContext ctx) } var submissionId = unchecked((uint)Interlocked.Increment(ref _nextSubmissionId)); - var completionResult = AmprExports.CompleteCommandBuffer( + var priority = ctx[CpuRegister.Rsi]; + var completionResult = AmprExports.SubmitCommandBuffer( ctx, commandBuffer, - out var executionResult, - out var errorOffset); + AmprExports.AmprEngine.Apr, + unchecked((uint)priority), + onQueuedCompletion: null, + out var execution); if (completionResult != (int)OrbisGen2Result.ORBIS_GEN2_OK) { return completionResult; } _submittedCommandBuffers[submissionId] = - new AprSubmission(commandBuffer, ctx[CpuRegister.Rsi], 0, executionResult, errorOffset); + new AprSubmission(commandBuffer, priority, 0, execution!); if (!ctx.TryWriteUInt32(outSubmissionId, submissionId)) { return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT; } - TraceApr(ctx, "submit_get_id", submissionId, commandBuffer, ctx[CpuRegister.Rsi], outSubmissionId); + TraceApr(ctx, "submit_get_id", submissionId, commandBuffer, priority, outSubmissionId); return (int)OrbisGen2Result.ORBIS_GEN2_OK; } diff --git a/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.cs b/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.cs index ab3ab9cde..5fc028528 100644 --- a/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.cs +++ b/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.cs @@ -3691,6 +3691,16 @@ public static int KernelQueryMemoryProtection(CpuContext ctx) } } + // A loaded module's own segments (its code and data) are mapped by the loader, not by these calls. + if (KernelModuleRegistry.TryGetModuleSegment(queryAddress, out var segment)) + { + return (startOut != 0 && !ctx.TryWriteUInt64(startOut, segment.Start)) || + (endOut != 0 && !ctx.TryWriteUInt64(endOut, segment.End - 1)) || + (protectionOut != 0 && !TryWriteInt32(ctx, protectionOut, segment.Protection)) + ? (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT + : (int)OrbisGen2Result.ORBIS_GEN2_OK; + } + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND; } @@ -6059,7 +6069,7 @@ private static int KernelBatchMapTransaction(CpuContext ctx, int flags) return result; } - private static int InvokeKernelMemoryOperation( + internal static int InvokeKernelMemoryOperation( CpuContext ctx, Func operation, ulong rdi = 0, diff --git a/src/SharpEmu.Libs/Kernel/KernelModuleRegistry.cs b/src/SharpEmu.Libs/Kernel/KernelModuleRegistry.cs index 6462c5f11..2cca06927 100644 --- a/src/SharpEmu.Libs/Kernel/KernelModuleRegistry.cs +++ b/src/SharpEmu.Libs/Kernel/KernelModuleRegistry.cs @@ -20,6 +20,7 @@ public enum ModuleStartState private static readonly object _gate = new(); private static readonly Dictionary _modulesByHandle = new(); private static readonly Dictionary> _symbolsByHandle = new(); + private static readonly Dictionary _segmentsByHandle = new(); private static readonly Dictionary _handleByPath = new(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary _handleByName = new(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary _sysmoduleHandleById = new(); @@ -63,6 +64,7 @@ public static void Reset() { _modulesByHandle.Clear(); _symbolsByHandle.Clear(); + _segmentsByHandle.Clear(); _handleByPath.Clear(); _handleByName.Clear(); _sysmoduleHandleById.Clear(); @@ -341,6 +343,41 @@ public static void RegisterModuleSymbols(int handle, IReadOnlyDictionary= candidate.Start && address < candidate.End) + { + segment = candidate; + return true; + } + } + } + } + + segment = default; + return false; + } + public static bool TryResolveModuleSymbol(int handle, string symbolName, out ulong address) { address = 0; diff --git a/src/SharpEmu.Libs/Kernel/KernelPthreadState.cs b/src/SharpEmu.Libs/Kernel/KernelPthreadState.cs index 3307e08d2..bc7a8284a 100644 --- a/src/SharpEmu.Libs/Kernel/KernelPthreadState.cs +++ b/src/SharpEmu.Libs/Kernel/KernelPthreadState.cs @@ -129,6 +129,8 @@ private static ulong AllocateThreadHandle(ulong uniqueId, string name) { var pointer = Marshal.AllocHGlobal(ThreadObjectSize); Marshal.Copy(ZeroThreadObject, 0, pointer, ThreadObjectSize); + // A pthread starts with its kernel thread id, which titles read through the pthread_t. + Marshal.WriteInt64(pointer, unchecked((long)uniqueId)); var handle = unchecked((ulong)pointer.ToInt64()); Threads[handle] = new ThreadIdentity(uniqueId, string.IsNullOrWhiteSpace(name) ? $"Thread-{uniqueId:X}" : name); diff --git a/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs b/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs index d101c3bd9..efb4d10fe 100644 --- a/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs +++ b/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs @@ -833,6 +833,8 @@ internal static bool ContainsPrtRange(ulong address, ulong size) { if (size == 0 || address > ulong.MaxValue - size) return false; + if (Ampr.AmprExports.ContainsAmmRange(address, size)) + return true; lock (_prtApertureGate) { return _prtApertures.Any(aperture => address >= aperture.Base && diff --git a/src/SharpEmu.Libs/Network/HttpExports.Requests.cs b/src/SharpEmu.Libs/Network/HttpExports.Requests.cs new file mode 100644 index 000000000..9c1def4eb --- /dev/null +++ b/src/SharpEmu.Libs/Network/HttpExports.Requests.cs @@ -0,0 +1,197 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using System.Collections.Concurrent; + +namespace SharpEmu.Libs.Network; + +// Connections and requests. There is no network: objects are created as on a console, and sending a request fails +// because the host name never resolves, so no response exists. +public static partial class HttpExports +{ + private const int HttpErrorBeforeSend = unchecked((int)0x80431065); + private const int HttpErrorResolverNoDns = unchecked((int)0x80436002); + + private static readonly ConcurrentDictionary Connections = new(); + private static readonly ConcurrentDictionary Requests = new(); + + private sealed record HttpConnection(int TemplateId, ulong ServerNameAddress, ushort Port); + + private sealed record HttpRequest(int ConnectionId, int Method, ulong ContentLength); + + [SysAbiExport( + Nid = "Kiwv9r4IZCc", + ExportName = "sceHttpCreateConnection", + Target = Generation.Gen4 | Generation.Gen5, + LibraryName = "libSceHttp")] + public static int HttpCreateConnection(CpuContext ctx) + { + // tmplId, serverName, scheme, port, isEnableKeepalive. + var templateId = unchecked((int)ctx[CpuRegister.Rdi]); + var serverNameAddress = ctx[CpuRegister.Rsi]; + if (!Templates.ContainsKey(templateId)) + { + return ctx.SetReturn(HttpErrorInvalidId); + } + + if (serverNameAddress == 0 || ctx[CpuRegister.Rdx] == 0) + { + return ctx.SetReturn(HttpErrorInvalidValue); + } + + var id = Interlocked.Increment(ref _nextTemplateId); + var port = unchecked((ushort)ctx[CpuRegister.Rcx]); + Connections[id] = new HttpConnection(templateId, serverNameAddress, port); + TraceHttp("create_connection", id, unchecked((ulong)templateId), serverNameAddress, port, ctx[CpuRegister.R8]); + ctx[CpuRegister.Rax] = unchecked((ulong)id); + return (int)OrbisGen2Result.ORBIS_GEN2_OK; + } + + [SysAbiExport( + Nid = "P6A3ytpsiYc", + ExportName = "sceHttpDeleteConnection", + Target = Generation.Gen4 | Generation.Gen5, + LibraryName = "libSceHttp")] + public static int HttpDeleteConnection(CpuContext ctx) + { + var connectionId = unchecked((int)ctx[CpuRegister.Rdi]); + if (!Connections.TryRemove(connectionId, out _)) + { + return ctx.SetReturn(HttpErrorInvalidId); + } + + foreach (var pair in Requests) + { + if (pair.Value.ConnectionId == connectionId) + { + Requests.TryRemove(pair.Key, out _); + } + } + + return ctx.SetReturn(0); + } + + [SysAbiExport( + Nid = "tsGVru3hCe8", + ExportName = "sceHttpCreateRequest", + Target = Generation.Gen4 | Generation.Gen5, + LibraryName = "libSceHttp")] + public static int HttpCreateRequest(CpuContext ctx) + { + // connId, method, path, contentLength. + var connectionId = unchecked((int)ctx[CpuRegister.Rdi]); + if (!Connections.ContainsKey(connectionId)) + { + return ctx.SetReturn(HttpErrorInvalidId); + } + + if (ctx[CpuRegister.Rdx] == 0) + { + return ctx.SetReturn(HttpErrorInvalidValue); + } + + var id = Interlocked.Increment(ref _nextTemplateId); + var method = unchecked((int)ctx[CpuRegister.Rsi]); + Requests[id] = new HttpRequest(connectionId, method, ctx[CpuRegister.Rcx]); + TraceHttp("create_request", id, unchecked((ulong)connectionId), unchecked((ulong)method), ctx[CpuRegister.Rdx], ctx[CpuRegister.Rcx]); + ctx[CpuRegister.Rax] = unchecked((ulong)id); + return (int)OrbisGen2Result.ORBIS_GEN2_OK; + } + + [SysAbiExport( + Nid = "qe7oZ+v4PWA", + ExportName = "sceHttpDeleteRequest", + Target = Generation.Gen4 | Generation.Gen5, + LibraryName = "libSceHttp")] + public static int HttpDeleteRequest(CpuContext ctx) => + Requests.TryRemove(unchecked((int)ctx[CpuRegister.Rdi]), out _) + ? ctx.SetReturn(0) + : ctx.SetReturn(HttpErrorInvalidId); + + // Headers apply to a template, a connection or a request; nothing is ever sent, so they are not kept. + [SysAbiExport( + Nid = "EY28T2bkN7k", + ExportName = "sceHttpAddRequestHeader", + Target = Generation.Gen4 | Generation.Gen5, + LibraryName = "libSceHttp")] + public static int HttpAddRequestHeader(CpuContext ctx) + { + var id = unchecked((int)ctx[CpuRegister.Rdi]); + if (!Templates.ContainsKey(id) && !Connections.ContainsKey(id) && !Requests.ContainsKey(id)) + { + return ctx.SetReturn(HttpErrorInvalidId); + } + + return ctx[CpuRegister.Rsi] == 0 || ctx[CpuRegister.Rdx] == 0 + ? ctx.SetReturn(HttpErrorInvalidValue) + : ctx.SetReturn(0); + } + + [SysAbiExport( + Nid = "PTiFIUxCpJc", + ExportName = "sceHttpSetRequestContentLength", + Target = Generation.Gen4 | Generation.Gen5, + LibraryName = "libSceHttp")] + public static int HttpSetRequestContentLength(CpuContext ctx) + { + var id = unchecked((int)ctx[CpuRegister.Rdi]); + if (!Requests.TryGetValue(id, out var request)) + { + return ctx.SetReturn(HttpErrorInvalidId); + } + + Requests[id] = request with { ContentLength = ctx[CpuRegister.Rsi] }; + return ctx.SetReturn(0); + } + + [SysAbiExport( + Nid = "1e2BNwI-XzE", + ExportName = "sceHttpSendRequest", + Target = Generation.Gen4 | Generation.Gen5, + LibraryName = "libSceHttp")] + public static int HttpSendRequest(CpuContext ctx) + { + var id = unchecked((int)ctx[CpuRegister.Rdi]); + if (!Requests.ContainsKey(id)) + { + return ctx.SetReturn(HttpErrorInvalidId); + } + + TraceHttp("send_request_no_network", id, ctx[CpuRegister.Rsi], ctx[CpuRegister.Rdx], 0, 0); + return ctx.SetReturn(HttpErrorResolverNoDns); + } + + [SysAbiExport( + Nid = "0a2TBNfE3BU", + ExportName = "sceHttpGetStatusCode", + Target = Generation.Gen4 | Generation.Gen5, + LibraryName = "libSceHttp")] + public static int HttpGetStatusCode(CpuContext ctx) => NoResponse(ctx); + + [SysAbiExport( + Nid = "yuO2H2Uvnos", + ExportName = "sceHttpGetResponseContentLength", + Target = Generation.Gen4 | Generation.Gen5, + LibraryName = "libSceHttp")] + public static int HttpGetResponseContentLength(CpuContext ctx) => NoResponse(ctx); + + [SysAbiExport( + Nid = "aCYPMSUIaP8", + ExportName = "sceHttpGetAllResponseHeaders", + Target = Generation.Gen4 | Generation.Gen5, + LibraryName = "libSceHttp")] + public static int HttpGetAllResponseHeaders(CpuContext ctx) => NoResponse(ctx); + + [SysAbiExport( + Nid = "P5pdoykPYTk", + ExportName = "sceHttpReadData", + Target = Generation.Gen4 | Generation.Gen5, + LibraryName = "libSceHttp")] + public static int HttpReadData(CpuContext ctx) => NoResponse(ctx); + + private static int NoResponse(CpuContext ctx) => + Requests.ContainsKey(unchecked((int)ctx[CpuRegister.Rdi])) + ? ctx.SetReturn(HttpErrorBeforeSend) + : ctx.SetReturn(HttpErrorInvalidId); +} diff --git a/src/SharpEmu.Libs/Network/HttpExports.cs b/src/SharpEmu.Libs/Network/HttpExports.cs index f6d098396..fa8773589 100644 --- a/src/SharpEmu.Libs/Network/HttpExports.cs +++ b/src/SharpEmu.Libs/Network/HttpExports.cs @@ -14,6 +14,7 @@ public static partial class HttpExports private static readonly ConcurrentDictionary Contexts = new(); private static readonly ConcurrentDictionary Templates = new(); private static int _nextContextId; + // Templates, connections and requests share these ids: the setters accept any of the three. private static int _nextTemplateId = 0x1000; private sealed record HttpContext(int NetMemoryId, int SslContextId, ulong PoolSize); diff --git a/src/SharpEmu.Libs/Np/NpEntitlementAccessExports.cs b/src/SharpEmu.Libs/Np/NpEntitlementAccessExports.cs index 030e5e9ee..d716a61ec 100644 --- a/src/SharpEmu.Libs/Np/NpEntitlementAccessExports.cs +++ b/src/SharpEmu.Libs/Np/NpEntitlementAccessExports.cs @@ -23,8 +23,15 @@ public static class NpEntitlementAccessExports private const int NpEntitlementAccessErrorParameter = unchecked((int)0x817D0002); private const int NpEntitlementAccessErrorNoEntitlement = unchecked((int)0x817D0007); + private const int NpEntitlementAccessErrorSignedOut = unchecked((int)0x817D0014); + private const int NpEntitlementAccessErrorRequestNotFound = unchecked((int)0x817D0015); + private const int NpEntitlementAccessPollFinished = 0; private const int EntitlementKeySize = 16; + // Asynchronous requests by id, with the result each one finished with. + private static readonly System.Collections.Concurrent.ConcurrentDictionary Requests = new(); + private static long _nextRequestId; + // Offline entitlements queried by titles through NpEntitlementAccess. // GTA V Enhanced (PPSA04264) gates Story Mode on these three labels; without // them the frontend offers "Buy GTAV Story Mode" despite a full dump. @@ -254,6 +261,90 @@ public static int NpEntitlementAccessGetEntitlementKey(CpuContext ctx) : NpEntitlementAccessErrorNoEntitlement); } + // Unified entitlements are kept on the PSN servers. The user is signed out, as in libSceNpManager, so a request + // finishes at once with that result and no entitlements. + [SysAbiExport( + Nid = "uCZf2L27th8", + ExportName = "sceNpEntitlementAccessRequestUnifiedEntitlementInfoList", + Target = Generation.Gen5, + LibraryName = "libSceNpEntitlementAccess")] + public static int NpEntitlementAccessRequestUnifiedEntitlementInfoList(CpuContext ctx) + { + // userId, serviceLabel, label list (null for every label), list size, parameters, request id out. + var listAddress = ctx[CpuRegister.Rdx]; + var listNum = unchecked((uint)ctx[CpuRegister.Rcx]); + var requestIdAddress = ctx[CpuRegister.R9]; + if (requestIdAddress == 0 || (listAddress == 0 && listNum != 0)) + { + return ctx.SetReturn(NpEntitlementAccessErrorParameter); + } + + var requestId = Interlocked.Increment(ref _nextRequestId); + if (!ctx.TryWriteUInt64(requestIdAddress, unchecked((ulong)requestId))) + { + return ctx.SetReturn(OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); + } + + Requests[requestId] = NpEntitlementAccessErrorSignedOut; + TraceNpEntitlementAccess($"request_unified_list id={requestId} labels={listNum}"); + return ctx.SetReturn(OrbisGen2Result.ORBIS_GEN2_OK); + } + + [SysAbiExport( + Nid = "nAEqawEZG5s", + ExportName = "sceNpEntitlementAccessPollUnifiedEntitlementInfoList", + Target = Generation.Gen5, + LibraryName = "libSceNpEntitlementAccess")] + public static int NpEntitlementAccessPollUnifiedEntitlementInfoList(CpuContext ctx) + { + // requestId, result out, info list, list size, hit count out, next offset out, previous offset out (stack). + var requestId = unchecked((long)ctx[CpuRegister.Rdi]); + var resultAddress = ctx[CpuRegister.Rsi]; + var hitNumAddress = ctx[CpuRegister.R8]; + var nextOffsetAddress = ctx[CpuRegister.R9]; + if (!Requests.TryGetValue(requestId, out var result)) + { + return ctx.SetReturn(NpEntitlementAccessErrorRequestNotFound); + } + + if (resultAddress == 0) + { + return ctx.SetReturn(NpEntitlementAccessErrorParameter); + } + + _ = ctx.TryGetImportStackArgument(0, out var previousOffsetAddress); + if (!ctx.TryWriteInt32(resultAddress, result) || + (hitNumAddress != 0 && !ctx.TryWriteUInt32(hitNumAddress, 0)) || + (nextOffsetAddress != 0 && !ctx.TryWriteInt32(nextOffsetAddress, 0)) || + (previousOffsetAddress != 0 && !ctx.TryWriteInt32(previousOffsetAddress, 0))) + { + return ctx.SetReturn(OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); + } + + return ctx.SetReturn(NpEntitlementAccessPollFinished); + } + + [SysAbiExport( + Nid = "Z0eQj8m7XA8", + ExportName = "sceNpEntitlementAccessDeleteRequest", + Target = Generation.Gen5, + LibraryName = "libSceNpEntitlementAccess")] + public static int NpEntitlementAccessDeleteRequest(CpuContext ctx) => + ctx.SetReturn(Requests.TryRemove(unchecked((long)ctx[CpuRegister.Rdi]), out _) + ? (int)OrbisGen2Result.ORBIS_GEN2_OK + : NpEntitlementAccessErrorRequestNotFound); + + // Every request has finished by the time the title can abort it. + [SysAbiExport( + Nid = "HFcQl9TMcFQ", + ExportName = "sceNpEntitlementAccessAbortRequest", + Target = Generation.Gen5, + LibraryName = "libSceNpEntitlementAccess")] + public static int NpEntitlementAccessAbortRequest(CpuContext ctx) => + ctx.SetReturn(Requests.ContainsKey(unchecked((long)ctx[CpuRegister.Rdi])) + ? (int)OrbisGen2Result.ORBIS_GEN2_OK + : NpEntitlementAccessErrorRequestNotFound); + private static bool TryWriteAddcontEntitlementInfo( CpuContext ctx, ulong address, diff --git a/src/SharpEmu.Libs/Pad/PadExports.cs b/src/SharpEmu.Libs/Pad/PadExports.cs index 44088c47f..d291170c1 100644 --- a/src/SharpEmu.Libs/Pad/PadExports.cs +++ b/src/SharpEmu.Libs/Pad/PadExports.cs @@ -79,6 +79,33 @@ public static int PadUnknownN3kSX62fgNo(CpuContext ctx) { return ctx.SetReturn(0); } + + // Uncatalogued name; the NID and import library identify this export. Observed ABI: a pad handle and an int32 + // output; callers read the output only after a zero result and take zero as the default state. + [SysAbiExport( + Nid = "zBsgF0q8DIM", + ExportName = "scePadUnknownZBsgF0q8DIM", + Target = Generation.Gen5, + LibraryName = "libScePad")] + public static int PadUnknownZBsgF0q8DIM(CpuContext ctx) + { + var handle = unchecked((int)ctx[CpuRegister.Rdi]); + var valueAddress = ctx[CpuRegister.Rsi]; + if (!TryGetSession(ctx, handle, out _)) + { + return ctx.SetReturn(OrbisPadErrorInvalidHandle); + } + + if (valueAddress == 0) + { + return ctx.SetReturn(OrbisPadErrorInvalidArgument); + } + + ReadOnlySpan value = [0, 0, 0, 0]; + return ctx.Memory.TryWrite(valueAddress, value) + ? ctx.SetReturn(0) + : ctx.SetReturn((int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT); + } #pragma warning restore SHEM006 [SysAbiExport( diff --git a/src/SharpEmu.Libs/PlayGo/PlayGoExports.cs b/src/SharpEmu.Libs/PlayGo/PlayGoExports.cs index 2130ddb54..aacb66db9 100644 --- a/src/SharpEmu.Libs/PlayGo/PlayGoExports.cs +++ b/src/SharpEmu.Libs/PlayGo/PlayGoExports.cs @@ -824,6 +824,11 @@ private static PlayGoMetadata LoadPlayGoMetadata() } var chunkIds = LoadChunkIds(chunkDefsXml); + if (chunkIds.Length == 0) + { + chunkIds = LoadChunkDatChunkIds(playGoDat); + } + if (chunkIds.Length == 0) { TracePlayGo("metadata_has_no_chunk_definitions; installed chunk ids unknown"); @@ -914,6 +919,47 @@ private static ushort[] LoadChunkIds(string chunkDefsXml) } } + // The chunk count from the playgo-chunk.dat header ("plgo" on PS4, "plgx" on PS5): magic, two version halves, the + // image count, the chunk count, two more counts and the file size. Chunks are numbered from 0. A header that does + // not match its file leaves the ids unknown. + private static ushort[] LoadChunkDatChunkIds(string playGoDat) + { + const uint MagicPs4 = 0x6F676C70; + const uint MagicPs5 = 0x78676C70; + try + { + if (!File.Exists(playGoDat)) + { + return Array.Empty(); + } + + using var stream = File.OpenRead(playGoDat); + Span header = stackalloc byte[0x14]; + if (stream.ReadAtLeast(header, header.Length, throwOnEndOfStream: false) < header.Length || + BinaryPrimitives.ReadUInt32LittleEndian(header) is not (MagicPs4 or MagicPs5) || + BinaryPrimitives.ReadUInt32LittleEndian(header[0x10..]) != stream.Length) + { + return Array.Empty(); + } + + var chunkIds = new ushort[BinaryPrimitives.ReadUInt16LittleEndian(header[0x0A..])]; + for (var index = 0; index < chunkIds.Length; index++) + { + chunkIds[index] = (ushort)index; + } + + return chunkIds; + } + catch (IOException) + { + return Array.Empty(); + } + catch (UnauthorizedAccessException) + { + return Array.Empty(); + } + } + private static void AddChunkIds(string xml, Regex pattern, HashSet chunkIds) { foreach (Match match in pattern.Matches(xml)) diff --git a/src/SharpEmu.Libs/SaveData/SaveDataExports.cs b/src/SharpEmu.Libs/SaveData/SaveDataExports.cs index 3eac9da7d..55b22db91 100644 --- a/src/SharpEmu.Libs/SaveData/SaveDataExports.cs +++ b/src/SharpEmu.Libs/SaveData/SaveDataExports.cs @@ -21,6 +21,7 @@ public static class SaveDataExports private const int OrbisSaveDataErrorResourceFull = unchecked((int)0x809F001A); private const int OrbisSaveDataErrorResourceBusy = unchecked((int)0x809F001B); private const int OrbisSaveDataErrorResourceInvalid = unchecked((int)0x809F001C); + private const int OrbisSaveDataErrorNoNeedConvert = unchecked((int)0x809F001E); private const int SaveDataTitleIdSize = 10; private const int SaveDataDirNameSize = 32; private const int SaveDataParamSize = 0x530; @@ -554,6 +555,52 @@ public static int SaveDataGetProgress(CpuContext ctx) [SysAbiExport(Nid = "dQ2GohUHXzk", ExportName = "sceSaveDataAbort", Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceSaveData")] public static int SaveDataAbort(CpuContext ctx) => SetReturn(ctx, 0); + // Converts a save directory written in the previous format. This emulator writes one format only, so an existing + // directory needs no conversion and a missing one is not found; titles treat both as "mount as usual". + [SysAbiExport(Nid = "2mfSRGdshtk", ExportName = "sceSaveDataConvert", Target = Generation.Gen5, LibraryName = "libSceSaveData")] + public static int SaveDataConvert(CpuContext ctx) + { + // SceSaveDataConvert: +0x00 userId, +0x08 source dirName*, +0x10 destination dirName* (or null), +0x18 blocks. + var convertAddress = ctx[CpuRegister.Rdi]; + if (convertAddress == 0 || + !TryReadInt32(ctx, convertAddress, out var userId) || + !ctx.TryReadUInt64(convertAddress + 0x08, out var sourceAddress) || + sourceAddress == 0 || + !TryReadFixedAscii(ctx, sourceAddress, SaveDataDirNameSize, out var source) || + string.IsNullOrWhiteSpace(source)) + { + return SetReturn(ctx, OrbisSaveDataErrorParameter); + } + + var slotDir = SaveDataStorage.SlotDir(ResolveTitleSaveRoot(userId, ResolveConfiguredTitleId()), source); + var exists = Directory.Exists(slotDir); + TraceSaveData($"convert user={userId} dir='{source}' exists={exists}"); + return SetReturn(ctx, exists ? OrbisSaveDataErrorNoNeedConvert : OrbisSaveDataErrorNotFound); + } + + // No conversion ever runs (see sceSaveDataConvert), so none is in flight. + [SysAbiExport(Nid = "8EA5OMIL1lQ", ExportName = "sceSaveDataGetConvertProgress", Target = Generation.Gen5, LibraryName = "libSceSaveData")] + public static int SaveDataGetConvertProgress(CpuContext ctx) => SaveDataGetProgress(ctx); + + // Cancels a prepared update. Writes go straight to the host directory, so only the prepared state is released. + [SysAbiExport(Nid = "e6y3WMBYbiM", ExportName = "sceSaveDataCancel", Target = Generation.Gen5, LibraryName = "libSceSaveData")] + public static int SaveDataCancel(CpuContext ctx) + { + var resource = unchecked((int)ctx[CpuRegister.Rdi]); + lock (_stateGate) + { + if (!_transactionResources.Contains(resource)) + { + return SetReturn(ctx, OrbisSaveDataErrorResourceInvalid); + } + + _preparedTransactionResources.Remove(resource); + } + + TraceSaveData($"cancel resource={resource}"); + return SetReturn(ctx, 0); + } + [SysAbiExport(Nid = "eBSSNIG6hMk", ExportName = "sceSaveDataGetEventInfo", Target = Generation.Gen4 | Generation.Gen5, LibraryName = "libSceSaveData")] public static int SaveDataGetEventInfo(CpuContext ctx) => SetReturn(ctx, 0); diff --git a/src/SharpEmu.Libs/VideoOut/DriverShaderCacheFolder.cs b/src/SharpEmu.Libs/VideoOut/DriverShaderCacheFolder.cs new file mode 100644 index 000000000..2e6d607ce --- /dev/null +++ b/src/SharpEmu.Libs/VideoOut/DriverShaderCacheFolder.cs @@ -0,0 +1,51 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Libs.VideoOut; + +// SHARPEMU_DRIVER_CACHE_FOLDER=0 turns it off. The NVIDIA driver keeps this game's shader disk cache beside the game's +// other caches (.driver) instead of in the driver's global shader cache folder. NVIDIA compresses +// pipeline binaries with the dictionary of the executable's driver cache file and refuses them once that file is +// replaced. The global folder has one size budget for every OpenGL and Vulkan program together (about 1000 MiB), so +// another program's compiles can evict this executable's file, and with it the use of every stored binary: the next +// session then builds its stored pipelines again from scratch. A per-game folder is used by the game alone and moves +// with the game's caches. The driver reads the path when it loads, so it is set before the Vulkan loader first runs. A +// path already set is kept. The switch ends in _FOLDER, so translation keys ignore it +// (TranslationDiskCache.IgnoredVariable). The first session in a new folder starts a new driver file: binaries stored +// under the global file's dictionary are refused once and stored again. +internal static class DriverShaderCacheFolder +{ + internal const string PathVariable = "__GL_SHADER_DISK_CACHE_PATH"; + internal const string Suffix = ".driver"; + + // The folder to give the driver: null when the switch is off or a path is already set. + internal static string? Resolve(string? mode, string? configuredPath, string pipelineCachePath) => + mode != "0" && string.IsNullOrEmpty(configuredPath) ? pipelineCachePath + Suffix : null; + + // Points the driver at the game's folder (creating it) unless the switch is off or a path is already set. Call it + // before Vk.GetApi. Returns the folder, or null when nothing was set. + internal static string? Apply(string pipelineCachePath) + { + var folder = Resolve(Environment.GetEnvironmentVariable("SHARPEMU_DRIVER_CACHE_FOLDER"), + Environment.GetEnvironmentVariable(PathVariable), pipelineCachePath); + if (folder is null) + { + return null; + } + + try + { + Directory.CreateDirectory(folder); + var files = new DirectoryInfo(folder).GetFiles("*", SearchOption.AllDirectories); + Environment.SetEnvironmentVariable(PathVariable, folder); + Console.Error.WriteLine($"[LOADER][INFO] Driver shader cache: folder={folder} files={files.Length} " + + $"bytes={files.Sum(static file => file.Length)}"); + return folder; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + Console.Error.WriteLine($"[LOADER][WARN] Driver shader cache folder unavailable: {exception.Message}"); + return null; + } + } +} diff --git a/src/SharpEmu.Libs/VideoOut/HostVideoOptions.cs b/src/SharpEmu.Libs/VideoOut/HostVideoOptions.cs index 20d4a3e46..ac97af16f 100644 --- a/src/SharpEmu.Libs/VideoOut/HostVideoOptions.cs +++ b/src/SharpEmu.Libs/VideoOut/HostVideoOptions.cs @@ -86,6 +86,8 @@ public static class HostVideoHost public static HostVideoOptions CurrentOptions => Volatile.Read(ref _currentOptions); + internal static bool IsVideoConfigured => Volatile.Read(ref _videoConfigured); + public static void ConfigureSplashFont(Stream font) => ShaderCacheProgressOverlay.SetFont(font); internal static bool IsHdrOutputSupported => diff --git a/src/SharpEmu.Libs/VideoOut/LinkedCompileAdmission.cs b/src/SharpEmu.Libs/VideoOut/LinkedCompileAdmission.cs new file mode 100644 index 000000000..eaaeca54d --- /dev/null +++ b/src/SharpEmu.Libs/VideoOut/LinkedCompileAdmission.cs @@ -0,0 +1,61 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Libs.VideoOut; + +// Which linked compute compiles may run at once. A linked compile can hold over 10 GB of driver memory for minutes, and +// two of that size at once can exhaust the commit limit and lose the device; running linked compiles strictly one at a +// time instead holds every other one back behind a long one for a whole session, and their programs' dispatches are +// skipped meanwhile. So a compile starts when the free commit, less the estimates of the linked compiles already +// running, still holds its own estimate (0.7 GB per MB of SPIR-V) plus a margin. A compile whose estimate reaches the +// margin starts only while no other one that large runs, and while the free commit cannot be read, one compile runs at +// a time. +internal sealed class LinkedCompileAdmission(Func availableCommit) +{ + internal const long BytesPerSpirvByte = 700; + internal const long MarginBytes = 4L << 30; + + private readonly object _gate = new(); + private long _reserved; + private int _running; + private bool _largeRunning; + + internal static long Estimate(long spirvBytes) => Math.Max(0, spirvBytes) * BytesPerSpirvByte; + + // Starts the compile when it fits, and then reserves its estimate until Release. available is the free commit it read + // (-1 when unknown) and reserved the estimates of the compiles running before it. + public bool TryAdmit(long spirvBytes, out long available, out long reserved) + { + var estimate = Estimate(spirvBytes); + var large = estimate >= MarginBytes; + lock (_gate) + { + available = availableCommit(); + reserved = _reserved; + var fits = available < 0 ? _running == 0 : available - _reserved >= estimate + MarginBytes; + if (!fits || (large && _largeRunning)) + { + return false; + } + + _reserved += estimate; + _running++; + _largeRunning |= large; + return true; + } + } + + public void Release(long spirvBytes) + { + var estimate = Estimate(spirvBytes); + lock (_gate) + { + _reserved -= estimate; + _running--; + if (estimate >= MarginBytes) + { + _largeRunning = false; + } + } + } +} diff --git a/src/SharpEmu.Libs/VideoOut/PipelineBinaryStorePolicy.cs b/src/SharpEmu.Libs/VideoOut/PipelineBinaryStorePolicy.cs new file mode 100644 index 000000000..0b3408901 --- /dev/null +++ b/src/SharpEmu.Libs/VideoOut/PipelineBinaryStorePolicy.cs @@ -0,0 +1,27 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Globalization; + +namespace SharpEmu.Libs.VideoOut; + +// SHARPEMU_PIPELINE_BINARY_MS= (default 20): the build time from which a pipeline's binaries are stored +// (VK_KHR_pipeline_binary). While binaries are on, every pipeline captures its data and is created without a pipeline +// cache, and the NVIDIA driver adds none of these pipelines to its own disk cache (its cache file is not written during +// a session). A build under the threshold is therefore kept nowhere and compiles again in each session, so a high +// threshold leaves the render thread waiting for many pipelines of tens to hundreds of milliseconds each time; stored, +// they load from their binaries. Builds under 20 ms are mostly links of parts already built and cost no more than a +// load. +internal static class PipelineBinaryStorePolicy +{ + internal const double DefaultMilliseconds = 20; + + internal static readonly double Milliseconds = Parse(Environment.GetEnvironmentVariable("SHARPEMU_PIPELINE_BINARY_MS")); + + // The threshold a setting names: a finite number of milliseconds, zero or more. Anything else keeps the default. + internal static double Parse(string? value) => + double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var milliseconds) && + double.IsFinite(milliseconds) && milliseconds >= 0 + ? milliseconds + : DefaultMilliseconds; +} diff --git a/src/SharpEmu.Libs/VideoOut/PipelineBuildGate.cs b/src/SharpEmu.Libs/VideoOut/PipelineBuildGate.cs new file mode 100644 index 000000000..b94674956 --- /dev/null +++ b/src/SharpEmu.Libs/VideoOut/PipelineBuildGate.cs @@ -0,0 +1,69 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Libs.VideoOut; + +// One build of a driver pipeline key at a time (CreatePipelineWithBinaries). A creation whose key another thread is +// building waits for that build and then loads the binaries it stored, instead of compiling the same pipeline beside +// it: at boot the session can ask for compute pipelines the prewarm is still compiling. A waiter lends a lower-priority +// builder (a below-normal prewarm worker) its own priority until the build ends. +internal sealed class PipelineBuildGate +{ + private readonly Dictionary _builds = new(StringComparer.Ordinal); + + internal sealed class Build + { + public required string Key { get; init; } + public required Thread Builder { get; init; } + public required ThreadPriority Priority { get; init; } + public bool Raised; + public readonly TaskCompletionSource Done = new(TaskCreationOptions.RunContinuationsAsynchronously); + } + + // Registers the calling thread as the builder of key, after waiting for any other thread that builds it now. + public Build Begin(string key) + { + var thread = Thread.CurrentThread; + while (true) + { + Build? running; + lock (_builds) + { + if (!_builds.TryGetValue(key, out running)) + { + var build = new Build { Key = key, Builder = thread, Priority = thread.Priority }; + _builds.Add(key, build); + return build; + } + + if (running.Builder.Priority < thread.Priority) + { + running.Builder.Priority = thread.Priority; + running.Raised = true; + } + } + + running.Done.Task.Wait(); + } + } + + // Ends the calling thread's build: restores a priority a waiter raised and wakes the waiters, also when the restore fails. + public void Finish(Build build) + { + try + { + lock (_builds) + { + _builds.Remove(build.Key); + if (build.Raised) + { + build.Builder.Priority = build.Priority; + } + } + } + finally + { + build.Done.SetResult(); + } + } +} diff --git a/src/SharpEmu.Libs/VideoOut/PrewarmPool.cs b/src/SharpEmu.Libs/VideoOut/PrewarmPool.cs new file mode 100644 index 000000000..178cade06 --- /dev/null +++ b/src/SharpEmu.Libs/VideoOut/PrewarmPool.cs @@ -0,0 +1,155 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Libs.VideoOut; + +using SharpEmu.Libs.Gpu.Scheduling; + +// The boot prewarm's threads, shared by its lanes (the compute records and the graphics parts). Each turn a worker runs +// the next item of the lane whose next item must start first: the lowest start, the time by which the item must start +// to be ready at its first use. At boot the compute records need far more threads than the graphics parts, and a few +// long compute compiles can hold every compute thread while short records due in the first seconds wait, so the threads +// follow the deadlines instead of half going to each lane. +internal sealed class PrewarmPool(Func stopping) +{ + private readonly object _gate = new(); + private readonly List _threads = []; + private Lane[] _lanes = []; + private bool _started; + + // Adds a lane and threads; every thread serves every lane. Threads added before Start begin there, so their first + // turns already see every lane; threads added after it begin at once. A lane without items is finished at once. + public void Add(Lane lane, int threads, string name) + { + lock (_gate) + { + Volatile.Write(ref _lanes, [.. _lanes, lane]); + for (var index = 0; index < threads; index++) + { + var thread = new Thread(Work) { IsBackground = true, Priority = ThreadPriority.BelowNormal, Name = $"{name} {index}" }; + _threads.Add(thread); + if (_started) + { + thread.Start(); + } + } + } + + if (lane.Done) + { + lane.Finish(); + } + } + + public void Start() + { + lock (_gate) + { + if (_started) + { + return; + } + + _started = true; + foreach (var thread in _threads) + { + thread.Start(); + } + } + } + + // Waits for every thread, then finishes the lanes the pool stopped before their last item. + public void Stop() + { + Thread[] threads; + lock (_gate) + { + threads = _started ? [.. _threads] : []; + } + + foreach (var thread in threads) + { + thread.Join(); + } + + foreach (var lane in Volatile.Read(ref _lanes)) + { + lane.Finish(); + } + } + + private void Work() + { + // A fatal condition in an item abandons the item, whose failure path notes it, instead of ending the process: the + // session compiles the same work itself and fails there if the condition is real. + SubmissionScheduler.ThrowOnFatal = true; + while (!stopping()) + { + var lanes = Volatile.Read(ref _lanes); + Lane? next = null; + var nextStart = float.PositiveInfinity; + foreach (var lane in lanes) + { + if (lane.TryPeek(out var start) && (next is null || start < nextStart)) + { + (next, nextStart) = (lane, start); + } + } + + // No lane has an item to take: the items left, if any, are with other workers, which run them (a worker that + // puts a busy caller's record back takes it again itself). + if (next is null) + { + return; + } + + if (next.Run(mayWait: false) || lanes.Any(lane => lane != next && lane.TryPeek(out _) && lane.Run(mayWait: false))) + { + continue; + } + + // Each item left waits on a busy linked caller and no other lane has one: wait for a caller. + next.Run(mayWait: true); + } + } + + // One kind of work: items, how many items run takes in all. peek: the next item's start, false when none is left to take. + // run: takes and runs the next item, false when it took none (none was left, or each one left waits on a busy linked + // caller and mayWait is false). finished: once, after the last item ran or when the pool stopped. + internal sealed class Lane(int items, Lane.Peek peek, Func run, Action finished) + { + internal delegate bool Peek(out float start); + + // The items not run yet. A queue that looks empty does not end a lane: a worker that puts a busy caller's + // record back holds it outside the queue for a moment. + private int _left = items; + private int _finished; + + internal bool Done => Volatile.Read(ref _left) == 0; + + internal bool TryPeek(out float start) => peek(out start); + + internal bool Run(bool mayWait) + { + if (!run(mayWait)) + { + return false; + } + + if (Interlocked.Decrement(ref _left) == 0) + { + Finish(); + } + + return true; + } + + internal void Finish() + { + if (Interlocked.Exchange(ref _finished, 1) == 0) + { + finished(); + } + } + } +} diff --git a/src/SharpEmu.Libs/VideoOut/ShaderPrewarmQueue.cs b/src/SharpEmu.Libs/VideoOut/ShaderPrewarmQueue.cs new file mode 100644 index 000000000..2ba61259f --- /dev/null +++ b/src/SharpEmu.Libs/VideoOut/ShaderPrewarmQueue.cs @@ -0,0 +1,182 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Libs.VideoOut; + +using System.Collections.Concurrent; + +// The boot prewarm's records, shared by its workers (VulkanVideoPresenter.ShaderPrewarm). The permutations of one linked +// caller write the same linked cache file, so they compile one at a time. A worker that takes a record of a caller another +// worker is compiling puts it back and takes the next record instead; only after a whole pass found nothing but busy +// callers does it wait, until a caller is released. Each caller's linked records take that caller's places in the list +// newest first: the last recorded permutation is the one the last run asked for. Every record is kept and taken once. +internal sealed class ShaderPrewarmQueue +{ + private readonly ConcurrentQueue _work; + private readonly Func _caller; + private readonly ConcurrentDictionary _gates = new(); + private readonly object _released = new(); + private long _releases; + private long _deferrals; + + // caller: the linked caller's hash of a record, or null for a record without linked callees. keepOrder takes the + // records in the order given (the background lane's LinkedLaneOrder) instead of each caller's newest first. + public ShaderPrewarmQueue(IReadOnlyList records, Func caller, bool keepOrder = false) + { + _caller = caller; + _work = new ConcurrentQueue(keepOrder ? records : NewestLinkedFirst(records, caller)); + } + + public int Count => _work.Count; + + // Records put back because their caller was busy (tests). + internal long Deferrals => Interlocked.Read(ref _deferrals); + + // Waits for a release at most this long before it looks again, so stopping is seen. + internal const int ReleaseWaitMilliseconds = 250; + + // The next record without taking it (PrewarmPool orders the prewarm's lanes by it); false when none is left. + public bool TryPeek(out T record) => _work.TryPeek(out record!); + + // The next record this worker may compile now, with the gate it then holds (null for a plain record); false when none + // is left or stopping says so, and, without mayWait, when every record left waits on a busy caller. Release(gate) after + // the compile. + public bool TryTake(Func stopping, out T record, out SemaphoreSlim? gate, bool mayWait = true) + { + var deferred = 0; + var passStart = Interlocked.Read(ref _releases); + while (!stopping() && _work.TryDequeue(out record!)) + { + gate = _caller(record) is { } caller ? _gates.GetOrAdd(caller, static _ => new SemaphoreSlim(1, 1)) : null; + if (gate is null || gate.Wait(0)) + { + return true; + } + + _work.Enqueue(record); + Interlocked.Increment(ref _deferrals); + if (++deferred <= _work.Count) + { + continue; + } + + // Every record of the pass waits on a busy caller. + if (!mayWait) + { + break; + } + + lock (_released) + { + while (Interlocked.Read(ref _releases) == passStart && !stopping()) + { + Monitor.Wait(_released, ReleaseWaitMilliseconds); + } + } + + deferred = 0; + passStart = Interlocked.Read(ref _releases); + } + + record = default!; + gate = null; + return false; + } + + public void Release(SemaphoreSlim? gate) + { + if (gate is null) + { + return; + } + + gate.Release(); + Interlocked.Increment(ref _releases); + lock (_released) + { + Monitor.PulseAll(_released); + } + } + + internal static T[] NewestLinkedFirst(IReadOnlyList records, Func caller) + { + var ordered = records.ToArray(); + var places = new Dictionary>(); + for (var index = 0; index < ordered.Length; index++) + { + if (caller(ordered[index]) is not { } hash) + { + continue; + } + + if (!places.TryGetValue(hash, out var list)) + { + places.Add(hash, list = []); + } + + list.Add(index); + } + + foreach (var list in places.Values) + { + for (int low = 0, high = list.Count - 1; low < high; low++, high--) + { + (ordered[list[low]], ordered[list[high]]) = (ordered[list[high]], ordered[list[low]]); + } + } + + return ordered; + } + + // The workers of the background lane of linked records (VulkanVideoPresenter.StartLinkedPrewarm), each keeping one driver + // compile running: two on a machine with sixteen or more hardware threads, else one, beside the session and the other + // prewarm lanes. + internal static int LinkedLaneWorkers(int processorCount) => processorCount >= 16 ? 2 : 1; + + // The order of the background lane of linked records (VulkanVideoPresenter.StartLinkedPrewarm), which compiles one at a + // time. Every caller's first record goes before any caller's second, since one ready permutation already runs the + // caller's dispatches while a newer one compiles. A caller's first record is the one its next session asks for first + // (firstAsked: the library of the callees a session kept for it, which the session links first); without one, the + // oldest, since a session then links what the caller's tables name at its first dispatch, which sessions record before + // the later permutations. The caller's other records follow newest first. Within each round, callers a session saw + // compile for minutes go first, since a session cannot compile those in time itself; otherwise callers keep the order + // in which they were first recorded. + internal static T[] LinkedLaneOrder(IReadOnlyList records, Func caller, Func slow, + Func firstAsked) + { + var callers = new Dictionary Records)>(); + for (var index = 0; index < records.Count; index++) + { + var hash = caller(records[index]); + if (!callers.TryGetValue(hash, out var entry)) + { + callers.Add(hash, entry = (index, [])); + } + + entry.Records.Add(records[index]); + } + + var keyed = new List<(T Record, int Round, bool Slow, int Place)>(records.Count); + foreach (var (hash, (place, list)) in callers) + { + var first = Math.Max(0, list.FindIndex(record => firstAsked(record))); + var lane = new List(list.Count) { list[first] }; + for (var index = list.Count - 1; index >= 0; index--) + { + if (index != first) + { + lane.Add(list[index]); + } + } + + var isSlow = slow(hash); + for (var round = 0; round < lane.Count; round++) + { + keyed.Add((lane[round], round, isSlow, place)); + } + } + + return [.. keyed.OrderBy(static entry => entry.Round).ThenByDescending(static entry => entry.Slow) + .ThenBy(static entry => entry.Place).Select(static entry => entry.Record)]; + } +} diff --git a/src/SharpEmu.Libs/VideoOut/VideoOutExports.cs b/src/SharpEmu.Libs/VideoOut/VideoOutExports.cs index 97d33c1e9..f86b8a599 100644 --- a/src/SharpEmu.Libs/VideoOut/VideoOutExports.cs +++ b/src/SharpEmu.Libs/VideoOut/VideoOutExports.cs @@ -159,6 +159,24 @@ public static void ConfigureApplicationInfo(string? title, string? titleId, stri RenderDocCapture.SetCaptureDirectory(GetApplicationTitleId()); } + // Once the runtime knows the game, the presenter (window, Vulkan device and shader prewarm) starts at the size the + // host configured, while the game's modules load and initialize. Started at the guest's first video call instead, + // it begins seconds after the process, and the compute programs the game asks for right after that hold the boot + // while they compile. Hosts that configure no video (tests, tools) start nothing here. + // SHARPEMU_EARLY_PRESENTER=0 keeps the start at the first video call. + private static readonly bool EarlyPresenter = Environment.GetEnvironmentVariable("SHARPEMU_EARLY_PRESENTER") != "0"; + + public static void StartPresenter() + { + if (!EarlyPresenter || !HostVideoHost.IsVideoConfigured) + { + return; + } + + var options = HostVideoHost.CurrentOptions; + GuestGpu.Current.EnsureStarted((uint)options.Width, (uint)options.Height); + } + internal static string GetApplicationTitleId() { lock (_stateGate) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.BindingShadow.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.BindingShadow.cs index 260af27f8..6e843904c 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.BindingShadow.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.BindingShadow.cs @@ -27,6 +27,7 @@ private sealed partial class RecordingHost private ShaderStageFlags _shadowPushStages; private uint[]? _shadowPushData; private DescriptorShadow? _graphicsDescriptorShadow; + private DescriptorShadow? _graphicsPixelDescriptorShadow; private DescriptorShadow? _computeDescriptorShadow; private ulong[]? _shadowVertexBindings; private int _shadowVertexCount = -1; @@ -69,6 +70,11 @@ private bool SyncNativeShadow(CommandBuffer command) _graphicsDescriptorShadow.Valid = false; } + if (_graphicsPixelDescriptorShadow is not null) + { + _graphicsPixelDescriptorShadow.Valid = false; + } + if (_computeDescriptorShadow is not null) { _computeDescriptorShadow.Valid = false; @@ -124,7 +130,10 @@ private void PushConstantsShadowed(CommandBuffer command, PipelineLayout layout, } } - private bool DescriptorsAlreadyBound(CommandBuffer command, PipelineBindPoint bindPoint, PipelineLayout layout, ReadOnlySpan writes) + // setIndex: the set the writes go to; a pipeline linked from libraries binds its pixel stage's descriptors in a set of + // their own (PixelDescriptorSet). + private bool DescriptorsAlreadyBound(CommandBuffer command, PipelineBindPoint bindPoint, PipelineLayout layout, ReadOnlySpan writes, + uint setIndex = 0) { if (!SyncNativeShadow(command)) { @@ -134,7 +143,9 @@ private bool DescriptorsAlreadyBound(CommandBuffer command, PipelineBindPoint bi var length = DescriptorKey(writes); var shadow = bindPoint == PipelineBindPoint.Compute ? _computeDescriptorShadow ??= new DescriptorShadow() - : _graphicsDescriptorShadow ??= new DescriptorShadow(); + : setIndex == 0 + ? _graphicsDescriptorShadow ??= new DescriptorShadow() + : _graphicsPixelDescriptorShadow ??= new DescriptorShadow(); var key = _descriptorKeyScratch.AsSpan(0, length); var reused = shadow.Valid && shadow.Layout.Handle == layout.Handle && key.SequenceEqual(shadow.Key.AsSpan(0, shadow.Length)); CountNativeState(NativeStateKind.Descriptors, reused); @@ -143,6 +154,7 @@ private bool DescriptorsAlreadyBound(CommandBuffer command, PipelineBindPoint bi return true; } + DropSetsOfOtherLayouts(bindPoint, layout); if (shadow.Key.Length < length) { shadow.Key = new ulong[Math.Max(length, shadow.Key.Length * 2)]; @@ -155,6 +167,38 @@ private bool DescriptorsAlreadyBound(CommandBuffer command, PipelineBindPoint bi return false; } + // A set bound without a descriptor commit (the bindless heap) disturbs the other sets the same way. + private void NoteSetBinding(CommandBuffer command, PipelineBindPoint bindPoint, PipelineLayout layout) + { + if (SyncNativeShadow(command)) + { + DropSetsOfOtherLayouts(bindPoint, layout); + } + } + + // Binding a set with one layout disturbs the sets of the same bind point that an incompatible layout bound (pipeline + // layout compatibility counts the sets below the one bound), so their shadows go and the next commit binds them again. + // Any other layout counts as incompatible. + private void DropSetsOfOtherLayouts(PipelineBindPoint bindPoint, PipelineLayout layout) + { + if (bindPoint == PipelineBindPoint.Compute) + { + DropUnlessBoundWith(_computeDescriptorShadow, layout); + return; + } + + DropUnlessBoundWith(_graphicsDescriptorShadow, layout); + DropUnlessBoundWith(_graphicsPixelDescriptorShadow, layout); + } + + private static void DropUnlessBoundWith(DescriptorShadow? shadow, PipelineLayout layout) + { + if (shadow is not null && shadow.Layout.Handle != layout.Handle) + { + shadow.Valid = false; + } + } + private int DescriptorKey(ReadOnlySpan writes) { var length = 0; diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.BindlessHeap.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.BindlessHeap.cs index 2d5cb7646..6f490bc33 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.BindlessHeap.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.BindlessHeap.cs @@ -1,6 +1,8 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using System.Numerics; +using System.Runtime.InteropServices; using SharpEmu.Libs.Gpu.Buffers; using SharpEmu.Libs.Gpu.Images; using SharpEmu.Libs.Gpu.Scheduling; @@ -9,24 +11,128 @@ namespace SharpEmu.Libs.VideoOut; -// Descriptor set 1: the images and samplers of call records (see BindlessHeap and VulkanVideoPresenter.CallRecords). Every -// element starts as a null descriptor; the host writes a descriptor's view or sampler when a dispatch's records first name -// it, and a record image's contents and layout are made current before each command that reads set 1. +// Descriptor set 1: the bindless heaps a program reads at a record only its shader knows (see BindlessHeap). Every +// element starts as a null descriptor. The shader marks each record it reads in a feedback bitset; once the marking +// work completes, the host reads the record's T# or S# from the guest heap and writes its view or sampler. Records are +// read again periodically, and a heap image's contents and layout are made current before each command that reads +// set 1. internal static unsafe partial class VulkanVideoPresenter { + // Revalidation reads the heap records it compares in runs, one guest read per run of nearby records, instead of one + // read per record (SHARPEMU_HEAP_BULK_READS=0 reads each record on its own). A run that cannot be read falls back to + // reading its records one by one, so every entry compares the words its own read would return. + internal static readonly bool HeapBulkReadsConfigured = Environment.GetEnvironmentVariable("SHARPEMU_HEAP_BULK_READS") != "0"; + // Tests set it. + internal static bool? HeapBulkReadsOverride; + internal static bool HeapBulkReadsActive => HeapBulkReadsOverride ?? HeapBulkReadsConfigured; + + // A run spans at most this many bytes and skips at most HeapRunGapBytes between two records it reads. + internal const uint HeapRunMaxBytes = 64 << 10; + internal const uint HeapRunGapBytes = 1 << 10; + + // The end (exclusive) of the run of sorted record indexes that starts at start: every index in it is below records, + // the run spans at most HeapRunMaxBytes, and no two neighbors are more than HeapRunGapBytes of records apart. + internal static int HeapRecordRunEnd(ReadOnlySpan indexes, int start, uint recordBytes, uint records) + { + var first = indexes[start]; + var last = first; + var end = start + 1; + while (end < indexes.Length) + { + var next = indexes[end]; + if (next >= records || (ulong)(next - last) * recordBytes > HeapRunGapBytes + recordBytes || + ((ulong)next - first + 1) * recordBytes > HeapRunMaxBytes) + { + break; + } + + last = next; + end++; + } + + return end; + } + + // What revalidation in runs reads and visits. The presenter implements it over its heaps, guest memory and + // entries (Presenter.HeapRunVisitor); tests implement it over fakes. + internal interface IHeapRunVisitor + { + // The heap as it is now: a resolve may move it. + BindlessHeapDescriptor Heap(bool sampler); + + bool TryRead(ulong address, Span destination); + + // The record of the entry at position, read on its own as ReadHeapRecord reads it; the word count. + int ReadRecord(int position, Span words); + + // Touches and compares the entry at position, and resolves it again when its words changed; true when it did. + bool Visit(int position, ReadOnlySpan words); + } + + // Visits the entries at positions [from, to) of one heap, whose sorted record indexes are indexes, each with the + // words of its record. Records are read in runs (HeapRecordRunEnd) into buffer. A visit that resolved ends its run: + // the next entry starts a new one, read after that resolve, with the heap as the resolve left it. So no entry compares + // bytes read before an earlier entry's resolve (which may land GPU data or move the heap), and buffer is never read + // across one (a nested revalidation may reuse it). A run that cannot be read falls back to one read per entry, each + // right before its visit. Entries the heap cannot hold get no words, as ReadHeapRecord gives them. + internal static void VisitHeapRuns(ref T visitor, ReadOnlySpan indexes, int from, int to, bool sampler, + Span buffer, Span scratch) where T : IHeapRunVisitor + { + var bytes = sampler ? BindlessHeap.SamplerRecordBytes : BindlessHeap.ImageRecordBytes; + indexes = indexes[..to]; + var start = from; + while (start < to) + { + var heap = visitor.Heap(sampler); + if (heap.Base == 0 || indexes[start] >= heap.Records) + { + _ = visitor.Visit(start, ReadOnlySpan.Empty); + start++; + continue; + } + + var end = HeapRecordRunEnd(indexes, start, bytes, heap.Records); + var first = indexes[start]; + var run = buffer[..checked((int)(((ulong)indexes[end - 1] - first + 1) * bytes))]; + if (!visitor.TryRead(heap.Base + (ulong)first * bytes, run)) + { + for (; start < end; start++) + { + _ = visitor.Visit(start, scratch[..visitor.ReadRecord(start, scratch)]); + } + + continue; + } + + while (start < end) + { + var offset = checked((int)((indexes[start] - first) * bytes)); + var resolved = visitor.Visit(start, System.Runtime.InteropServices.MemoryMarshal.Cast(run.Slice(offset, (int)bytes))); + start++; + if (resolved) + { + break; + } + } + } + } + private sealed partial class Presenter { private const DescriptorBindingFlags HeapElementFlags = DescriptorBindingFlags.UpdateAfterBindBit | DescriptorBindingFlags.PartiallyBoundBit | DescriptorBindingFlags.UpdateUnusedWhilePendingBit; - // The images set 1 holds are marked in use again after this many submission ticks, so the image cache keeps them. + // Records are read again after this many submission ticks, so a rewritten record gets its new view. private const ulong HeapRevalidationTicks = 16; - // Programs linked with run-time call records read their records through set 1, on every device that supports it. + // Set 1 exists on every device that supports it: programs linked with run-time call records read their records + // through it, and other programs read guest heap records through it. bool Gpu.Pipelines.IShaderPipelineHost.RuntimeCallRecordsSupported => _bindlessHeapSupported; - // One element of set 1: the descriptor words it was resolved from and what it holds. + private static ulong FeedbackBytes => (ulong)BindlessHeap.FeedbackWords * sizeof(uint); + + // One record the shaders marked: the words it was resolved from and what set 1 holds for it. private sealed class HeapEntry { public int Slot; @@ -42,12 +148,30 @@ private sealed class HeapEntry private DescriptorSetLayout _heapSetLayout; private DescriptorPool _heapPool; private DescriptorSet _heapSet; + private GpuBuffer? _heapFeedback; + private GpuBuffer? _heapFeedbackReadback; + private Action? _heapFeedbackCopyCompleted; + private int _heapFeedbackReady; + private int _heapFeedbackCopyPending; + private uint[] _heapMarked = []; + private readonly Dictionary<(int Slot, uint Index), HeapEntry> _heapEntries = new(); private readonly Dictionary> _heapEntriesByImage = new(ReferenceEqualityComparer.Instance); private readonly HashSet _heapChangedImages = new(ReferenceEqualityComparer.Instance); + private BindlessHeapDescriptor _textureHeap; + private BindlessHeapDescriptor _samplerHeap; private ulong _heapRevalidatedTick; private object? _heapPreparedFor; + // Changes whenever _heapEntries does; the entries in record order (image heap, then sampler heap, each by + // index), their indexes and where the sampler heap's begin, as of _heapRunVersion; and the run buffer. + private long _heapEntriesVersion; + private long _heapRunVersion; + private HeapEntry[]? _heapRunOrder; + private uint[]? _heapRunIndexes; + private int _heapRunSamplerStart; + private byte[]? _heapRunBytes; private Sampler _heapNullSampler; private Action? _heapImageChanged; + private int _heapReports; // Called during device setup with the queried features; the layout is made when the device supports the heap. private static bool BindlessHeapSupported(in PhysicalDeviceVulkan12Features features, bool nullDescriptor) => @@ -71,16 +195,21 @@ private void CreateBindlessHeapLayout() indexing.MaxPerStageDescriptorUpdateAfterBindSampledImages < images || indexing.MaxDescriptorSetUpdateAfterBindSamplers < samplers || indexing.MaxPerStageDescriptorUpdateAfterBindSamplers < samplers || - indexing.MaxPerStageUpdateAfterBindResources < images + samplers) + indexing.MaxPerStageUpdateAfterBindResources < images + samplers + 1) { - // Linked programs then link a copy of each callee per record. + Console.Error.WriteLine( + $"[LOADER][WARN] The device cannot hold the bindless heap arrays: images={images} " + + $"max_images={indexing.MaxDescriptorSetUpdateAfterBindSampledImages} samplers={samplers} " + + $"max_samplers={indexing.MaxDescriptorSetUpdateAfterBindSamplers}; programs that read bindless heap records will fail."); _bindlessHeapSupported = false; return; } + // Every stage a program that reads heap records can run in, the stages of a tessellated pipeline too. var stages = ShaderStageFlags.VertexBit | ShaderStageFlags.FragmentBit | ShaderStageFlags.ComputeBit | - (_supportsMeshShader ? ShaderStageFlags.MeshBitExt : 0); - var count = BindlessHeap.ArrayCount; + (_supportsMeshShader ? ShaderStageFlags.MeshBitExt : 0) | + (_supportsTessellation ? ShaderStageFlags.TessellationControlBit | ShaderStageFlags.TessellationEvaluationBit : 0); + var count = BindlessHeap.ArrayCount + 1; var bindings = stackalloc DescriptorSetLayoutBinding[count]; var flags = stackalloc DescriptorBindingFlags[count]; for (var slot = 0; slot < BindlessHeap.ArrayCount; slot++) @@ -95,6 +224,14 @@ private void CreateBindlessHeapLayout() flags[slot] = HeapElementFlags; } + bindings[count - 1] = new DescriptorSetLayoutBinding + { + Binding = BindlessHeap.FeedbackBinding, + DescriptorType = DescriptorType.StorageBuffer, + DescriptorCount = 1, + StageFlags = stages, + }; + flags[count - 1] = 0; var bindingFlags = new DescriptorSetLayoutBindingFlagsCreateInfo { SType = StructureType.DescriptorSetLayoutBindingFlagsCreateInfo, @@ -116,9 +253,9 @@ private DescriptorSetLayout RequireHeapSetLayout() => _heapSetLayout.Handle != 0 ? _heapSetLayout : throw SubmissionScheduler.Fatal( - "A program reads call records, but the device has no descriptor set 1 for them (it needs descriptor indexing)."); + "A program reads bindless heap records, but the device has no bindless heap set."); - // The set and its null elements, made at the first command that reads set 1. + // The set, its null elements and the feedback bitsets, made at the first command that reads the heap. private void EnsureBindlessHeap() { if (_heapSet.Handle != 0) @@ -127,15 +264,16 @@ private void EnsureBindlessHeap() } var layout = RequireHeapSetLayout(); - var sizes = stackalloc DescriptorPoolSize[2]; + var sizes = stackalloc DescriptorPoolSize[3]; sizes[0] = new DescriptorPoolSize { Type = DescriptorType.SampledImage, DescriptorCount = (uint)BindlessHeap.ImageKinds.Length * BindlessHeap.Capacity }; sizes[1] = new DescriptorPoolSize { Type = DescriptorType.Sampler, DescriptorCount = 2 * BindlessHeap.Capacity }; + sizes[2] = new DescriptorPoolSize { Type = DescriptorType.StorageBuffer, DescriptorCount = 1 }; var poolInfo = new DescriptorPoolCreateInfo { SType = StructureType.DescriptorPoolCreateInfo, Flags = DescriptorPoolCreateFlags.UpdateAfterBindBit, MaxSets = 1, - PoolSizeCount = 2, + PoolSizeCount = 3, PPoolSizes = sizes, }; Check(_vk.CreateDescriptorPool(_device, &poolInfo, null, out _heapPool), "vkCreateDescriptorPool(bindless heap)"); @@ -154,6 +292,18 @@ private void EnsureBindlessHeap() $"sampler_arrays=2 capacity={BindlessHeap.Capacity}"); SetDebugName(ObjectType.DescriptorSet, set.Handle, "SharpEmu bindless heap"); + _heapFeedback = new GpuBuffer(_deviceInfo, _scheduler, GpuBufferUsage.DeviceLocal, 0, GpuBuffer.AllFlags, FeedbackBytes); + _heapFeedbackReadback = new GpuBuffer(_deviceInfo, _scheduler, GpuBufferUsage.Download, 0, GpuBuffer.AllFlags, FeedbackBytes); + var completedReadback = _heapFeedbackReadback; + _heapFeedbackCopyCompleted = () => + { + // A callback from a retired heap must not make a replacement slot appear complete. + if (ReferenceEquals(_heapFeedbackReadback, completedReadback)) + Volatile.Write(ref _heapFeedbackReady, 1); + }; + _ = BeginBatchedGuestCommands(); + _heapFeedback.Fill(0, FeedbackBytes, 0); + _heapMarked = new uint[BindlessHeap.FeedbackWords]; Span nullSampler = stackalloc uint[4]; _heapNullSampler = _samplerStore.GetSampler(new SamplerDescriptorWords(nullSampler), integerView: false); _heapImageChanged = image => @@ -169,7 +319,8 @@ private void EnsureBindlessHeap() Array.Fill(nullImages, new DescriptorImageInfo { ImageLayout = ImageLayout.General }); var nullSamplers = new DescriptorImageInfo[BindlessHeap.Capacity]; Array.Fill(nullSamplers, new DescriptorImageInfo { Sampler = _heapNullSampler }); - var writes = new WriteDescriptorSet[BindlessHeap.ArrayCount]; + var feedback = new DescriptorBufferInfo { Buffer = _heapFeedback.Handle, Offset = 0, Range = FeedbackBytes }; + var writes = new WriteDescriptorSet[BindlessHeap.ArrayCount + 1]; fixed (DescriptorImageInfo* images = nullImages) fixed (DescriptorImageInfo* samplers = nullSamplers) fixed (WriteDescriptorSet* writePointer = writes) @@ -188,20 +339,40 @@ private void EnsureBindlessHeap() }; } + writes[BindlessHeap.ArrayCount] = new WriteDescriptorSet + { + SType = StructureType.WriteDescriptorSet, + DstSet = set, + DstBinding = BindlessHeap.FeedbackBinding, + DescriptorCount = 1, + DescriptorType = DescriptorType.StorageBuffer, + PBufferInfo = &feedback, + }; _vk.UpdateDescriptorSets(_device, (uint)writes.Length, writePointer, 0, null); } } private void DestroyBindlessHeap() { + // The image cache disposes every slot after this, the ones the heap holds too. foreach (var image in _heapEntriesByImage.Keys) { image.HeapChanged = null; + image.DeferredErase = null; } _heapEntriesByImage.Clear(); + _heapEntries.Clear(); + _heapEntriesVersion++; _callRecordEntries.Clear(); Array.Clear(_callRecordNext); + _heapFeedback?.Dispose(); + _heapFeedbackReadback?.Dispose(); + _heapFeedback = null; + _heapFeedbackReadback = null; + _heapFeedbackCopyCompleted = null; + Volatile.Write(ref _heapFeedbackReady, 0); + Volatile.Write(ref _heapFeedbackCopyPending, 0); if (_heapPool.Handle != 0) { _vk.DestroyDescriptorPool(_device, _heapPool, null); @@ -216,9 +387,20 @@ private void DestroyBindlessHeap() } } - // Before the images of a draw or dispatch that reads set 1 are found: set 1 exists, its images stay in use, and those - // whose contents or layout changed are made current. - internal void PrepareBindlessHeap(object preparation) + // The recording host reuses one preparation object for every draw, so the first stage of each draw that reads set 1 + // forgets the heap prepared for the previous one; otherwise the heap is prepared once and the records later draws + // mark never get images. + internal void ForgetHeapPreparation(object preparation) + { + if (ReferenceEquals(_heapPreparedFor, preparation)) + { + _heapPreparedFor = null; + } + } + + // Before the images of a draw or dispatch that reads set 1 are found: the heap V#s, the records marked since the + // last look, records rewritten since they were read, and heap images whose contents or layout changed. + internal void PrepareBindlessHeap(object preparation, BindlessHeapDescriptor[] heaps) { if (ReferenceEquals(_heapPreparedFor, preparation)) { @@ -227,9 +409,29 @@ internal void PrepareBindlessHeap(object preparation) _heapPreparedFor = preparation; EnsureBindlessHeap(); - if (_scheduler.CurrentTick - _heapRevalidatedTick >= HeapRevalidationTicks) + var revalidate = _scheduler.CurrentTick - _heapRevalidatedTick >= HeapRevalidationTicks; + foreach (var heap in heaps) { - KeepHeapImagesInUse(); + ref var current = ref heap.Sampler ? ref _samplerHeap : ref _textureHeap; + if (current == heap) + { + continue; + } + + if (current.Base != 0 && current.Base != heap.Base && _heapReports++ < 16) + { + Console.Error.WriteLine( + $"[GPU][WARN] Bindless {(heap.Sampler ? "sampler" : "texture")} heap moved: from=0x{current.Base:X16} to=0x{heap.Base:X16} records={heap.Records}"); + } + + current = heap; + revalidate = true; + } + + PollHeapFeedback(); + if (revalidate) + { + RevalidateHeapEntries(); } RefreshChangedHeapImages(); @@ -240,16 +442,91 @@ public void BindBindlessHeap(CommandBuffer command, PipelineBindPoint bindPoint, var set = _heapSet; if (set.Handle == 0) { - throw SubmissionScheduler.Fatal("A program reads call records before descriptor set 1 exists."); + throw SubmissionScheduler.Fatal("A program reads bindless heap records before the heap set exists."); } _vk.CmdBindDescriptorSets(command, bindPoint, layout, BindlessHeap.DescriptorSet, 1, &set, 0, null); } - // A call record entry is named by its words, which never change; its image stays in use. - private void KeepHeapImagesInUse() + // Takes the marks of the last completed copy and starts the next copy; one copy is in flight at a time. + private void PollHeapFeedback() + { + if (Interlocked.Exchange(ref _heapFeedbackReady, 0) != 0) + { + var completed = _heapFeedbackReadback!; + completed.Invalidate(0, FeedbackBytes); + // Keep the slot pending through consumption, including any reentrant preparation. No later GPU copy + // may overwrite these mapped words until every marked record has been resolved. + ResolveMarkedRecords(MemoryMarshal.Cast(completed.Mapped[..(int)FeedbackBytes])); + Volatile.Write(ref _heapFeedbackCopyPending, 0); + } + + if (Volatile.Read(ref _heapFeedbackCopyPending) != 0) + { + return; + } + + var feedback = _heapFeedback!; + var readback = _heapFeedbackReadback!; + Volatile.Write(ref _heapFeedbackCopyPending, 1); + _ = BeginBatchedGuestCommands(); + readback.CopyFrom( + _scheduler.Current, feedback, 0, 0, FeedbackBytes, + AccessFlags.ShaderWriteBit | AccessFlags.MemoryWriteBit, AccessFlags.None, + AccessFlags.ShaderReadBit | AccessFlags.ShaderWriteBit | AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit, + AccessFlags.HostReadBit); + _scheduler.QueueCompletionAction(_heapFeedbackCopyCompleted!); + } + + private void ResolveMarkedRecords(ReadOnlySpan marked) + { + for (var word = 0; word < marked.Length && word < _heapMarked.Length; word++) + { + var fresh = marked[word] & ~_heapMarked[word]; + if (fresh == 0) + { + continue; + } + + _heapMarked[word] |= fresh; + var slot = word / (int)BindlessHeap.FeedbackWordsPerArray; + var first = (uint)(word % (int)BindlessHeap.FeedbackWordsPerArray) * 32; + while (fresh != 0) + { + var index = first + (uint)BitOperations.TrailingZeroCount(fresh); + fresh &= fresh - 1; + if (index >= BindlessHeap.CallRecordFirstIndex) + { + // Call records own these elements; the shader reads a heap record past the heap's range as null. + continue; + } + + var entry = new HeapEntry { Slot = slot, Index = index }; + _heapEntries[(slot, index)] = entry; + _heapEntriesVersion++; + entry.Words = ReadHeapRecord(slot, index); + ResolveHeapEntry(entry); + } + } + } + + private void RevalidateHeapEntries() { _heapRevalidatedTick = _scheduler.CurrentTick; + Span scratch = stackalloc uint[8]; + if (HeapBulkReadsActive) + { + RevalidateHeapEntriesInRuns(scratch); + } + else + { + foreach (var entry in _heapEntries.Values) + { + RevalidateHeapEntry(entry, scratch[..ReadHeapRecord(entry.Slot, entry.Index, scratch)]); + } + } + + // A call record entry is named by its words, which never change; its image stays in use. foreach (var entry in _callRecordEntries.Values) { if (entry.Image is { } image && _imageCache.TryGetImage(entry.ImageIdentifier, out var found) && ReferenceEquals(found, image)) @@ -259,22 +536,108 @@ private void KeepHeapImagesInUse() } } + // True when the entry's words changed and it was resolved again. + private bool RevalidateHeapEntry(HeapEntry entry, ReadOnlySpan words) + { + if (entry.Image is { } image && _imageCache.TryGetImage(entry.ImageIdentifier, out var found) && ReferenceEquals(found, image)) + { + // Keeps the image the heap reads from the cache's collection of unused images. + _ = _imageCache.GetImage(entry.ImageIdentifier); + } + + if (words.SequenceEqual(entry.Words)) + { + return false; + } + + entry.Words = words.ToArray(); + ResolveHeapEntry(entry); + return true; + } + + // The presenter's side of VisitHeapRuns, over the entries in record order. + private readonly struct HeapRunVisitor(Presenter owner, HeapEntry[] order) : IHeapRunVisitor + { + public BindlessHeapDescriptor Heap(bool sampler) => sampler ? owner._samplerHeap : owner._textureHeap; + + public bool TryRead(ulong address, Span destination) => owner._guestMemory.TryRead(address, destination); + + public int ReadRecord(int position, Span words) => + owner.ReadHeapRecord(order[position].Slot, order[position].Index, words); + + public bool Visit(int position, ReadOnlySpan words) => owner.RevalidateHeapEntry(order[position], words); + } + + // Every entry, in record order, compared with words read in runs (HeapRecordRunEnd). + private void RevalidateHeapEntriesInRuns(Span scratch) + { + if (_heapRunOrder is null || _heapRunIndexes is null || _heapRunVersion != _heapEntriesVersion) + { + var order = _heapEntries.Values.ToArray(); + Array.Sort(order, static (left, right) => + { + var heap = (left.Slot >= BindlessHeap.ImageKinds.Length).CompareTo(right.Slot >= BindlessHeap.ImageKinds.Length); + return heap != 0 ? heap : left.Index != right.Index ? left.Index.CompareTo(right.Index) : left.Slot.CompareTo(right.Slot); + }); + _heapRunOrder = order; + _heapRunIndexes = Array.ConvertAll(order, static entry => entry.Index); + _heapRunSamplerStart = Array.FindIndex(order, static entry => entry.Slot >= BindlessHeap.ImageKinds.Length); + if (_heapRunSamplerStart < 0) _heapRunSamplerStart = order.Length; + _heapRunVersion = _heapEntriesVersion; + } + + // The arrays are replaced, never changed, when the entries change: a nested revalidation leaves these intact. + var runOrder = _heapRunOrder!; + var runIndexes = _heapRunIndexes!; + var samplerStart = _heapRunSamplerStart; + var visitor = new HeapRunVisitor(this, runOrder); + var buffer = (_heapRunBytes ??= new byte[HeapRunMaxBytes]).AsSpan(); + VisitHeapRuns(ref visitor, runIndexes, 0, samplerStart, sampler: false, buffer, scratch); + VisitHeapRuns(ref visitor, runIndexes, samplerStart, runOrder.Length, sampler: true, buffer, scratch); + } + + // The record's words, or none when the heap has no such record or it cannot be read. + private uint[] ReadHeapRecord(int slot, uint index) + { + Span words = stackalloc uint[8]; + return words[..ReadHeapRecord(slot, index, words)].ToArray(); + } + + // Revalidation compares current words in scratch; only a changed entry needs a new retained array. + private int ReadHeapRecord(int slot, uint index, Span words) + { + var sampler = slot >= BindlessHeap.ImageKinds.Length; + var heap = sampler ? _samplerHeap : _textureHeap; + var bytes = sampler ? BindlessHeap.SamplerRecordBytes : BindlessHeap.ImageRecordBytes; + if (heap.Base == 0 || index >= heap.Records) + { + return 0; + } + + var count = checked((int)(bytes / sizeof(uint))); + return _guestMemory.TryRead(heap.Base + (ulong)index * bytes, MemoryMarshal.AsBytes(words[..count])) ? count : 0; + } + private void ResolveHeapEntry(HeapEntry entry) { - DetachHeapEntry(entry); + var released = DetachHeapEntry(entry); if (entry.Slot >= BindlessHeap.ImageKinds.Length) { WriteHeapSampler(entry); - return; } - - ImageView view = default; - if (entry.Words.Length == 8 && ResourceMaterializer.IsFloatHeapImage(entry.Words)) + else { - view = AcquireHeapImage(entry); + ImageView view = default; + if (entry.Words.Length == 8 && ResourceMaterializer.IsFloatHeapImage(entry.Words)) + { + view = AcquireHeapImage(entry); + } + + WriteHeapImage(entry.Slot, entry.Index, view); } - WriteHeapImage(entry.Slot, entry.Index, view); + // A deleted image is freed once no element of the heap names its view. + released?.Invoke(); } private static ShaderImageShape HeapImageShape(int slot) @@ -351,8 +714,10 @@ private ImageView AcquireHeapImage(HeapEntry entry) return view; } - private void DetachHeapEntry(HeapEntry entry) + // Returns the held erase of an image deleted while the heap named it, when this was its last element. + private Action? DetachHeapEntry(HeapEntry entry) { + Action? released = null; if (entry.Image is { } image && _heapEntriesByImage.TryGetValue(image, out var entries)) { entries.Remove(entry); @@ -360,12 +725,15 @@ private void DetachHeapEntry(HeapEntry entry) { _heapEntriesByImage.Remove(image); image.HeapChanged = null; + released = image.DeferredErase; + image.DeferredErase = null; } } entry.Image = null; entry.ImageIdentifier = default; entry.Resolved = false; + return released; } private void WriteHeapImage(int slot, uint index, ImageView view) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CallRecordSpans.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CallRecordSpans.cs new file mode 100644 index 000000000..523b6a02b --- /dev/null +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CallRecordSpans.cs @@ -0,0 +1,377 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.Libs.VideoOut; + +// Call record spans. A record's image and sampler fields and buffer V#s lie a few dozen bytes past its argument, and +// the per-field preparation (PrepareCallRecordsOriginal) reads each of them on its own, every buffer V# twice +// (LeavesRecordOut, then the ranges), while a ray-traced dispatch can prepare thousands of records. Here each record is +// read once over the span of its callee's fields and V#s (CallRecordSpan), and the slot map, rows and ranges use +// scratch kept between dispatches. A span that cannot be read whole is read field by field, as the per-field +// preparation does. The rows and their order, the elements CallRecordElement assigns (in first use), the words table +// and the merged ranges are the per-field preparation's. On by default; SHARPEMU_CALL_RECORD_SPANS=0, or any value but +// 1, turns it off. +internal static unsafe partial class VulkanVideoPresenter +{ + internal enum CallRecordSpanMode { Off, On } + + internal static readonly CallRecordSpanMode ConfiguredCallRecordSpans = + Environment.GetEnvironmentVariable("SHARPEMU_CALL_RECORD_SPANS") switch + { + null or "" or "1" => CallRecordSpanMode.On, + _ => CallRecordSpanMode.Off, + }; + + // Tests: this thread's mode, whatever the configuration; and the element a field's words map to, instead of the + // bindless heap (which needs a device). + [ThreadStatic] internal static CallRecordSpanMode? CallRecordSpanOverride; + [ThreadStatic] internal static Func? CallRecordElementForTests; + + internal static CallRecordSpanMode CallRecordSpans => CallRecordSpanOverride ?? ConfiguredCallRecordSpans; + + // The bytes past a record's argument that its callee's fields (32 bytes for an image, 16 for a sampler) and buffer V#s + // (16 bytes) occupy: from the lowest immediate, Length bytes. Zero length when it reads none, or when they lie more than + // MaxCallRecordSpan bytes apart; such records are read field by field. + private readonly record struct CallRecordSpan(uint First, int Length); + + private const int MaxCallRecordSpan = 512; + + private static readonly ConditionalWeakTable> CallRecordSpanTable = new(); + + private static CallRecordSpan SpanOf(CallRecordCallee callee) => CallRecordSpanTable.GetValue(callee, static callee => + { + var first = ulong.MaxValue; + var end = 0ul; + foreach (var field in callee.Fields) + { + first = Math.Min(first, field.Immediate); + end = Math.Max(end, (ulong)field.Immediate + (field.Sampler ? 16u : 32u)); + } + + foreach (var buffer in callee.Buffers) + { + first = Math.Min(first, buffer.Immediate); + end = Math.Max(end, (ulong)buffer.Immediate + 16u); + } + + return new StrongBox(first == ulong.MaxValue || end - first > MaxCallRecordSpan + ? default : new CallRecordSpan((uint)first, (int)(end - first))); + }).Value; + + private sealed partial class Presenter + { + // A record the preparation keeps, with the offset of its span's bytes in the scratch (-1: read field by field). + private readonly record struct CallRecordRow(uint Low, uint High, uint Callee, ulong Argument, int Bytes, uint First); + + private sealed class CallRecordScratch + { + public readonly Dictionary SlotOf = new(); + public readonly List Rows = new(); + public readonly List Ranges = new(); + public readonly List Merged = new(); + public byte[] Bytes = new byte[4096]; + public int ByteCount; + public ulong[] Keys = new ulong[256]; + public DeviceAddressRange[] Sorted = new DeviceAddressRange[256]; + public ulong[] RowKeys = new ulong[256]; + public CallRecordRow[] SortedRows = new CallRecordRow[256]; + public CallRecordSpan[] Spans = new CallRecordSpan[16]; + } + + private CallRecordScratch? _callRecordScratch; + + // The words table the shader's call entries search and the memory their callees read through the records. + internal (uint[] Words, DeviceAddressRange[] Ranges) PrepareCallRecords(ShaderProgramInfo program, ShaderStageResources stage) => + CallRecordSpans == CallRecordSpanMode.Off + ? PrepareCallRecordsOriginal(program, stage) + : PrepareCallRecordsSpanned(program, stage); + + // PrepareCallRecordsOriginal with each record read once over its span (see above). + private (uint[] Words, DeviceAddressRange[] Ranges) PrepareCallRecordsSpanned(ShaderProgramInfo program, ShaderStageResources stage) + { + var callees = program.CallRecordCallees; + var targets = stage.CallTargets ?? []; + var scratch = _callRecordScratch ??= new CallRecordScratch(); + var slotOf = scratch.SlotOf; + slotOf.Clear(); + for (var slot = 0; slot < targets.Length; slot++) + { + slotOf.TryAdd(targets[slot], slot); + } + + var rows = scratch.Rows; + rows.Clear(); + scratch.ByteCount = 0; + if (scratch.Spans.Length < callees.Count) scratch.Spans = new CallRecordSpan[callees.Count]; + for (var slot = 0; slot < callees.Count; slot++) + { + scratch.Spans[slot] = SpanOf(callees[slot]); + } + + // Rows sort on argument and callee slot packed in 64 bits while every argument fits in 48: the original's order + // (argument high word, low word, then slot; one row per argument and slot). + var packable = callees.Count <= ushort.MaxValue; + foreach (var (target, argument) in stage.CallRecords ?? []) + { + if (!slotOf.TryGetValue(target, out var slot) || slot >= callees.Count) + { + continue; + } + + var callee = callees[slot]; + var span = scratch.Spans[slot]; + var bytes = -1; + if (span.Length != 0) + { + if (scratch.Bytes.Length - scratch.ByteCount < span.Length) + { + Array.Resize(ref scratch.Bytes, Math.Max(scratch.Bytes.Length * 2, scratch.ByteCount + span.Length)); + } + + if (_guestMemory.TryRead(argument + span.First, scratch.Bytes.AsSpan(scratch.ByteCount, span.Length))) + { + bytes = scratch.ByteCount; + scratch.ByteCount += span.Length; + } + } + + var row = new CallRecordRow((uint)argument, (uint)(argument >> 32), (uint)slot, argument, bytes, span.First); + if (!LeavesRecordOut(callee, target, program.Hash, scratch, row)) + { + rows.Add(row); + packable &= argument >> 48 == 0; + } + } + + if (packable && rows.Count > 1) + { + if (scratch.RowKeys.Length < rows.Count) + { + scratch.RowKeys = new ulong[Math.Max(rows.Count, scratch.RowKeys.Length * 2)]; + scratch.SortedRows = new CallRecordRow[scratch.RowKeys.Length]; + } + + for (var index = 0; index < rows.Count; index++) + { + scratch.RowKeys[index] = rows[index].Argument << 16 | rows[index].Callee; + scratch.SortedRows[index] = rows[index]; + } + + Array.Sort(scratch.RowKeys, scratch.SortedRows, 0, rows.Count); + for (var index = 0; index < rows.Count; index++) + { + rows[index] = scratch.SortedRows[index]; + } + } + else + { + rows.Sort(static (left, right) => + left.High != right.High ? left.High.CompareTo(right.High) : + left.Low != right.Low ? left.Low.CompareTo(right.Low) : left.Callee.CompareTo(right.Callee)); + } + if (rows.Count > BindlessHeap.CallRecordMaximumRows) + { + if (_callRecordReports++ < 8) + { + Console.Error.WriteLine( + $"[GPU][WARN] A dispatch has more call records than the shader searches: records={rows.Count} " + + $"searched={BindlessHeap.CallRecordMaximumRows} hash=0x{program.Hash:X16}."); + } + + rows.RemoveRange((int)BindlessHeap.CallRecordMaximumRows, rows.Count - (int)BindlessHeap.CallRecordMaximumRows); + } + + var fieldWords = 0; + foreach (var row in rows) + { + fieldWords += callees[(int)row.Callee].Fields.Length; + } + + var keyWords = (int)BindlessHeap.CallRecordKeyWords; + var rowStarts = 1 + rows.Count * keyWords; + var words = new uint[Math.Max(rowStarts + rows.Count + fieldWords, (int)BindlessHeap.CallRecordMinimumWords)]; + words[0] = (uint)rows.Count; + var cursor = rowStarts + rows.Count; + var ranges = scratch.Ranges; + ranges.Clear(); + Span descriptor = stackalloc uint[8]; + var argumentBase = 0ul; + var argumentEnd = 0ul; + var argumentOpen = false; + for (var index = 0; index < rows.Count; index++) + { + var row = rows[index]; + words[1 + index * keyWords] = row.Low; + words[2 + index * keyWords] = row.High; + words[3 + index * keyWords] = row.Callee; + words[rowStarts + index] = (uint)cursor; + var callee = callees[(int)row.Callee]; + foreach (var field in callee.Fields) + { + // As CallRecordElement(field, argument): the words past a sampler's four stay zero in the key. + descriptor.Clear(); + words[cursor++] = ReadRecordWords(scratch, row, field.Immediate, descriptor[..(field.Sampler ? 4 : 8)]) + ? CallRecordElement(field, descriptor) + : BindlessHeap.CallRecordNullIndex; + } + + if (callee.ArgumentBytes != 0) + { + // An argument range that overlaps or meets the open one (rows ascend by argument) joins it, as the merge + // joins them; one whose end wraps is added on its own. + var end = row.Argument + callee.ArgumentBytes; + if (argumentOpen && row.Argument <= argumentEnd && end > row.Argument) + { + argumentEnd = Math.Max(argumentEnd, end); + } + else + { + if (argumentOpen) + { + ranges.Add(new DeviceAddressRange(uint.MaxValue, argumentBase, argumentEnd - argumentBase, true, false)); + argumentOpen = false; + } + + if (end > row.Argument) + { + (argumentBase, argumentEnd, argumentOpen) = (row.Argument, end, true); + } + else + { + ranges.Add(new DeviceAddressRange(uint.MaxValue, row.Argument, callee.ArgumentBytes, true, false)); + } + } + } + + foreach (var field in callee.Buffers) + { + var buffer = descriptor[..4]; + if (!ReadRecordWords(scratch, row, field.Immediate, buffer)) + { + continue; + } + + var address = buffer[0] | ((ulong)(buffer[1] & 0xFFFF) << 32); + var stride = (buffer[1] >> 16) & 0x3FFF; + var size = (ulong)buffer[2] * Math.Max(stride, 1u); + if (Gpu.Pipelines.ShaderProgramCache.ClassifyRecordBuffer(address, size, field.Written) == + Gpu.Pipelines.ShaderProgramCache.RecordBuffer.Resident) + { + ranges.Add(new DeviceAddressRange(uint.MaxValue, address, size, true, field.Written)); + } + } + } + + if (argumentOpen) + { + ranges.Add(new DeviceAddressRange(uint.MaxValue, argumentBase, argumentEnd - argumentBase, true, false)); + } + + ranges.AddRange(stage.CallRecordRanges ?? []); + return (words, MergeCallRecordRangesKeyed(scratch)); + } + + // MergeCallRecordRanges, sorted on 64-bit keys (written in the top bit, then the base) instead of a comparison. Ranges + // with equal keys join into the same range in any order, so the result is the same. A base with its top bit set + // takes the original merge. + private DeviceAddressRange[] MergeCallRecordRangesKeyed(CallRecordScratch scratch) + { + var ranges = scratch.Ranges; + var count = ranges.Count; + if (count == 0) + { + return []; + } + + if (scratch.Keys.Length < count) + { + scratch.Keys = new ulong[Math.Max(count, scratch.Keys.Length * 2)]; + scratch.Sorted = new DeviceAddressRange[scratch.Keys.Length]; + } + + var keys = scratch.Keys; + var sorted = scratch.Sorted; + for (var index = 0; index < count; index++) + { + var range = ranges[index]; + if ((range.Base >> 63) != 0) + { + return MergeCallRecordRanges(ranges); + } + + keys[index] = (range.Written ? 1ul << 63 : 0) | range.Base; + sorted[index] = range; + } + + Array.Sort(keys, sorted, 0, count); + var merged = scratch.Merged; + merged.Clear(); + var current = sorted[0]; + for (var index = 1; index < count; index++) + { + var range = sorted[index]; + var end = current.Base + current.Size; + if (range.Written == current.Written && + (range.Base <= end || (range.Base - end <= 4096 && _guestMemory.CanRead(end, range.Base - end)))) + { + current = current with { Size = Math.Max(end, range.Base + range.Size) - current.Base }; + continue; + } + + merged.Add(current); + current = range; + } + + merged.Add(current); + return [.. merged]; + } + + // LeavesRecordOut(callee, target, argument, hash) on the record's span. + private bool LeavesRecordOut(CallRecordCallee callee, ulong target, ulong hash, CallRecordScratch scratch, in CallRecordRow row) + { + Span buffer = stackalloc uint[4]; + foreach (var field in callee.Buffers) + { + if (!ReadRecordWords(scratch, row, field.Immediate, buffer)) + { + continue; + } + + var address = buffer[0] | ((ulong)(buffer[1] & 0xFFFF) << 32); + var size = (ulong)buffer[2] * Math.Max((buffer[1] >> 16) & 0x3FFF, 1u); + if (Gpu.Pipelines.ShaderProgramCache.ClassifyRecordBuffer(address, size, field.Written) == + Gpu.Pipelines.ShaderProgramCache.RecordBuffer.LeaveRecordOut) + { + if (_callRecordReports++ < 8) + { + Console.Error.WriteLine($"[GPU][WARN][LINKED_PROGRAM] A call record's buffer describes no buffer; its call returns at once: " + + $"hash=0x{hash:X16} target=0x{target:X} argument=0x{row.Argument:X} base=0x{address:X} size=0x{size:X}."); + } + + return true; + } + } + + return false; + } + + // The words at an immediate past a record's argument: from its span when it was read whole, else read now as the + // original reads them. + private bool ReadRecordWords(CallRecordScratch scratch, in CallRecordRow row, uint immediate, Span destination) + { + var target = MemoryMarshal.AsBytes(destination); + if (row.Bytes < 0) + { + return _guestMemory.TryRead(row.Argument + immediate, target); + } + + scratch.Bytes.AsSpan(row.Bytes + (int)(immediate - row.First), target.Length).CopyTo(target); + return true; + } + } +} diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CallRecords.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CallRecords.cs index 7193b011b..7cbbd82ab 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CallRecords.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CallRecords.cs @@ -9,7 +9,7 @@ namespace SharpEmu.Libs.VideoOut; // The call records of a program linked with run-time record arguments (CallRecordSelector). For every record of a dispatch's // tables, the host reads each image and sampler its callee reads through the record's argument, gives each distinct -// descriptor an element of set 1, and writes the table the shader's call entries +// descriptor an element of set 1 from BindlessHeap.CallRecordFirstIndex on, and writes the table the shader's call entries // search (BindlessHeap.CallRecordKeyWords). The memory a callee reads through its record, its own reads and its buffers, is // made resident through the device-address table as a planned range would be. internal static unsafe partial class VulkanVideoPresenter @@ -23,7 +23,8 @@ private sealed partial class Presenter private readonly uint[] _callRecordNext = new uint[BindlessHeap.ArrayCount]; private int _callRecordReports; - internal (uint[] Words, DeviceAddressRange[] Ranges) PrepareCallRecords(ShaderProgramInfo program, ShaderStageResources stage) + // The preparation without call record spans (VulkanVideoPresenter.CallRecordSpans.cs), which is also their reference. + private (uint[] Words, DeviceAddressRange[] Ranges) PrepareCallRecordsOriginal(ShaderProgramInfo program, ShaderStageResources stage) { var callees = program.CallRecordCallees; var targets = stage.CallTargets ?? []; @@ -36,7 +37,8 @@ private sealed partial class Presenter var rows = new List<(uint Low, uint High, uint Callee, ulong Argument)>(stage.CallRecords?.Length ?? 0); foreach (var (target, argument) in stage.CallRecords ?? []) { - if (slotOf.TryGetValue(target, out var slot) && slot < callees.Count) + if (slotOf.TryGetValue(target, out var slot) && slot < callees.Count && + !LeavesRecordOut(callees[slot], target, argument, program.Hash)) { rows.Add(((uint)argument, (uint)(argument >> 32), (uint)slot, argument)); } @@ -98,7 +100,8 @@ private sealed partial class Presenter var address = buffer[0] | ((ulong)(buffer[1] & 0xFFFF) << 32); var stride = (buffer[1] >> 16) & 0x3FFF; var size = (ulong)buffer[2] * Math.Max(stride, 1u); - if (size != 0 && address != 0) + if (Gpu.Pipelines.ShaderProgramCache.ClassifyRecordBuffer(address, size, field.Written) == + Gpu.Pipelines.ShaderProgramCache.RecordBuffer.Resident) { ranges.Add(new DeviceAddressRange(uint.MaxValue, address, size, true, field.Written)); } @@ -109,6 +112,36 @@ private sealed partial class Presenter return (words, MergeCallRecordRanges(ranges)); } + // Whether a record is left out because a buffer its callee writes holds no buffer descriptor + // (ShaderProgramCache.ClassifyRecordBuffer): its call returns at once instead of storing through it. + private bool LeavesRecordOut(CallRecordCallee callee, ulong target, ulong argument, ulong hash) + { + Span buffer = stackalloc uint[4]; + foreach (var field in callee.Buffers) + { + if (!_guestMemory.TryRead(argument + field.Immediate, MemoryMarshal.AsBytes(buffer))) + { + continue; + } + + var address = buffer[0] | ((ulong)(buffer[1] & 0xFFFF) << 32); + var size = (ulong)buffer[2] * Math.Max((buffer[1] >> 16) & 0x3FFF, 1u); + if (Gpu.Pipelines.ShaderProgramCache.ClassifyRecordBuffer(address, size, field.Written) == + Gpu.Pipelines.ShaderProgramCache.RecordBuffer.LeaveRecordOut) + { + if (_callRecordReports++ < 8) + { + Console.Error.WriteLine($"[GPU][WARN][LINKED_PROGRAM] A call record's buffer describes no buffer; its call returns at once: " + + $"hash=0x{hash:X16} target=0x{target:X} argument=0x{argument:X} base=0x{address:X} size=0x{size:X}."); + } + + return true; + } + } + + return false; + } + // The element of set 1 that holds the descriptor a record's callee reads Immediate bytes past its argument: one per // distinct descriptor and array, resolved when it is first seen. private uint CallRecordElement(CallRecordField field, ulong argument) @@ -120,6 +153,18 @@ private uint CallRecordElement(CallRecordField field, ulong argument) return BindlessHeap.CallRecordNullIndex; } + return CallRecordElement(field, words); + } + + // The element of a field whose descriptor words were read: eight words, a sampler's last four zero. + private uint CallRecordElement(CallRecordField field, ReadOnlySpan words) + { + var count = field.Sampler ? 4 : 8; + if (CallRecordElementForTests is { } element) + { + return element(field.Slot, words.ToArray()); + } + static ulong Pair(uint low, uint high) => low | ((ulong)high << 32); var key = (field.Slot, new CallRecordWords(Pair(words[0], words[1]), Pair(words[2], words[3]), Pair(words[4], words[5]), Pair(words[6], words[7]))); @@ -129,7 +174,7 @@ private uint CallRecordElement(CallRecordField field, ulong argument) } var next = _callRecordNext[field.Slot]; - if (next >= BindlessHeap.CallRecordNullIndex) + if (BindlessHeap.CallRecordFirstIndex + next >= BindlessHeap.CallRecordNullIndex) { if (_callRecordReports++ < 8) { @@ -140,7 +185,7 @@ private uint CallRecordElement(CallRecordField field, ulong argument) } _callRecordNext[field.Slot] = next + 1; - entry = new HeapEntry { Slot = field.Slot, Index = next, Words = words[..count].ToArray() }; + entry = new HeapEntry { Slot = field.Slot, Index = BindlessHeap.CallRecordFirstIndex + next, Words = words[..count].ToArray() }; _callRecordEntries.Add(key, entry); ResolveHeapEntry(entry); return entry.Index; diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandStream.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandStream.cs index 9faba4241..c92dd0a52 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandStream.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandStream.cs @@ -590,6 +590,11 @@ private bool ReadOnCommandThread(ulong address, Span destination, RenderRe } RenderPhaseProfile.RecordCleanRead(hit: false); + if (!_guestMemory.CanRead(address, size)) + { + return false; + } + var thread = _commandThread!; if (thread.TryReadShadow(address, destination, out var shadowSequence, out var shadowSource) && !NewerPendingWrite(address, size, shadowSequence) && !thread.HasPendingRangeAfter(address, size, shadowSequence)) @@ -999,6 +1004,9 @@ public void RecordEndOfPipe(in EndOfPipeWrite write) default: throw SubmissionScheduler.Fatal($"The end-of-pipe write kind is unknown: kind={write.Kind}."); } + + // SHARPEMU_END_OF_PIPE_SOFT_WAITS: the release completes with the recording it is in now; batching is unchanged. + write.Landing?.Recorded(_scheduler.CurrentTick); } public void TriggerInterrupt(int eventId, uint contextId) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.DeferredSignals.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.DeferredSignals.cs index 5ffd2f9d0..b6380dffa 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.DeferredSignals.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.DeferredSignals.cs @@ -107,19 +107,24 @@ private bool InAnyCrossQueueOrderWindow() return false; } + // Test hook: runs between MustHoldForCrossQueueOrder's window check and its wake arm. + internal Action? CrossQueueHoldCheckedForTest; + public bool MustHoldForCrossQueueOrder(int queueId) { if (!InCrossQueueOrderWindow(queueId)) return false; - // The foreign label is deferred, so its publication must wake this suspended queue. + CrossQueueHoldCheckedForTest?.Invoke(); + // The foreign label is deferred, so its publication must wake this suspended queue. Check again after arming: a + // publication that completed the entry before the arm saw no armed wake, so holding then would never be woken. Volatile.Write(ref _partialLabelReadBlocked, 1); - return true; + return InCrossQueueOrderWindow(queueId); } public bool TryDeferOrderedWrite(int queueId, ulong address, ReadOnlySpan source) { if (!InCrossQueueOrderWindow(queueId)) return false; - var entry = _guestPublications.AddWrite(queueId, address, (ulong)source.Length); var payload = source.ToArray(); + var entry = _guestPublications.AddWrite(queueId, address, (ulong)source.Length, payload); try { if (OnCommandThread) _commandThread!.Post(() => RecordDeferredWrite(entry, payload)); diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs index 8b1729315..55b324efc 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs @@ -23,11 +23,13 @@ namespace SharpEmu.Libs.VideoOut; internal static unsafe partial class VulkanVideoPresenter { // The shader bounds a storage binding in whole dwords (OpArrayLength), so the view ends on a dword: a 16-bit element - // in the binding's last partial dword stays in range. A view that would not fit keeps its exact size. + // in the binding's last partial dword stays in range. A view that would not fit ends on the dword before, which + // ArrayLength leaves out as well, so robustBufferAccess2 bounds a dword where ArrayLength does; under four bytes it + // keeps its exact size. internal static ulong StorageBufferViewRange(ulong bytes, ulong available, ulong maxRange) { var rounded = (bytes + 3) & ~3UL; - return rounded <= available && rounded <= maxRange ? rounded : bytes; + return rounded <= available && rounded <= maxRange ? rounded : bytes >= 4 ? bytes & ~3UL : bytes; } private static long _stageMemoHits; @@ -38,11 +40,34 @@ internal static ulong StorageBufferViewRange(ulong bytes, ulong available, ulong private static long _stageMemoAcquireReuses; private static long _stageMemoContentHits; private static long _stageMemoEvictions; + private static readonly ThreadCounter _nullImageHits = new(); + private static readonly ThreadCounter _nullImageVerified = new(); + private static readonly ThreadCounter _nullImageMismatches = new(); + private static int _nullImageMismatchReports; + + internal enum NullImageMemoMode + { + Off, + On, + Verify, + } + + // The image binding memo keeps the binding of a descriptor that names no memory like any other. + // SHARPEMU_NULL_IMAGE_MEMO=0 keeps none; =verify looks the placeholder up again on every use and counts the uses where + // the lookup found another image. + internal static readonly NullImageMemoMode ConfiguredNullImageMemo = + Environment.GetEnvironmentVariable("SHARPEMU_NULL_IMAGE_MEMO") switch + { + "0" => NullImageMemoMode.Off, + "verify" => NullImageMemoMode.Verify, + _ => NullImageMemoMode.On, + }; internal static string TakeStagePreparationReport() => FormattableString.Invariant($"[PERF][STAGE_MEMO] hits={Interlocked.Exchange(ref _stageMemoHits, 0)} misses={Interlocked.Exchange(ref _stageMemoMisses, 0)} captures={Interlocked.Exchange(ref _stageMemoCaptures, 0)} ") + FormattableString.Invariant($"stale={Interlocked.Exchange(ref _stageMemoStale, 0)} invalidations={Interlocked.Exchange(ref _stageMemoInvalidations, 0)} acquire_reuses={Interlocked.Exchange(ref _stageMemoAcquireReuses, 0)} ") + - FormattableString.Invariant($"content_hits={Interlocked.Exchange(ref _stageMemoContentHits, 0)} evictions={Interlocked.Exchange(ref _stageMemoEvictions, 0)}"); + FormattableString.Invariant($"content_hits={Interlocked.Exchange(ref _stageMemoContentHits, 0)} evictions={Interlocked.Exchange(ref _stageMemoEvictions, 0)} ") + + FormattableString.Invariant($"null_images=hits:{_nullImageHits.Take()},verified:{_nullImageVerified.Take()},mismatches:{_nullImageMismatches.Take()}"); private sealed class StagePreparationSet { @@ -126,6 +151,10 @@ public void Reset(ShaderStageResources stage, ShaderProgramInfo program) Memoized = false; TexturesKept = false; Memo = null; + // Only programs with call records prepare these; a reused stage must not hand the previous program's + // records and ranges to the next one, which would bind, upload and mark written memory it never uses. + CallRecordWords = []; + CallRecordRanges = []; Descriptors.GlobalDataShare = default; Descriptors.FlattenedTable = default; Descriptors.ShaderData = default; @@ -192,6 +221,38 @@ private struct ImageBindingMemo public ResourceSlotIdentifier Found; public uint MetadataBaseLayer; public bool CompletesLookup; + // Found is the image cache's placeholder for a descriptor that names no memory. The cache keeps each placeholder + // for its lifetime, so it stays the lookup's answer for these words whatever images are created or removed. + public bool NullImage; + } + + // Tests choose the mode per host. + internal NullImageMemoMode NullImageMemo = ConfiguredNullImageMemo; + + // Null bindings this host served from the memo, looked up again in verify mode, and found to differ. + internal long NullImageHits { get; private set; } + + internal long NullImageVerifications { get; private set; } + + internal long NullImageMismatches { get; private set; } + + private void NoteNullImageVerification(ResourceSlotIdentifier kept, ResourceSlotIdentifier found, ShaderProgramInfo program, int index) + { + NullImageVerifications++; + _nullImageVerified.Increment(); + if (kept == found) + { + return; + } + + NullImageMismatches++; + _nullImageMismatches.Increment(); + if (Interlocked.Increment(ref _nullImageMismatchReports) <= 16) + { + Console.Error.WriteLine( + $"[GPU][WARN] The image binding memo's placeholder differs from the lookup: stage={program.Stage} hash=0x{program.Hash:X16} " + + $"image={index} memo={kept} found={found}"); + } } private readonly record struct ImageBindingKey(ulong Words01, ulong Words23, ulong Words45, ulong Words67, int Length, ShaderImageShape Shape) @@ -558,11 +619,19 @@ private TextureResource ResolveImageBinding(ImageResource image, uint[] words, S TextureRequestResolution resolution; ResourceSlotIdentifier imageIdentifier; if (known && - (_worker - ? _imageCache.TryRememberedForSlice(memo.Found, ref memo.Generation, memo.Begin, memo.End) - : _imageCache.TryTouchRemembered(memo.Found, ref memo.Generation, memo.Begin, memo.End))) + (memo.NullImage + ? NullImageMemo == NullImageMemoMode.On + : _worker + ? _imageCache.TryRememberedForSlice(memo.Found, ref memo.Generation, memo.Begin, memo.End) + : _imageCache.TryTouchRemembered(memo.Found, ref memo.Generation, memo.Begin, memo.End))) { GuestImageCache.CountBindingMemo(hit: true); + if (memo.NullImage) + { + NullImageHits++; + _nullImageHits.Increment(); + } + resolution = memo.Resolution; imageIdentifier = memo.Found; if (memo.CompletesLookup) @@ -582,20 +651,30 @@ private TextureResource ResolveImageBinding(ImageResource image, uint[] words, S } else { + // Read before the memo is replaced: the placeholder a kept null binding would have served (verify mode). + var keptPlaceholder = known && memo.NullImage && NullImageMemo == NullImageMemoMode.Verify + ? memo.Found : ResourceSlotIdentifier.Invalid; GuestImageCache.CountBindingMemo(hit: false); resolution = originalResolution; var request = resolution.Request; var metadataBaseLayer = request.View.BaseLayer; imageIdentifier = LookUpImage(ref request, resolution.ExactFormat); resolution = resolution with { Request = request }; - if (!ImageDescription.IsEmptyRange(request.Description.Data)) + var nullImage = ImageDescription.IsEmptyRange(request.Description.Data); + if (keptPlaceholder.IsValid) + { + NoteNullImageVerification(keptPlaceholder, imageIdentifier, program, index); + } + + if (!nullImage || NullImageMemo != NullImageMemoMode.Off) { if (memos.Count >= ImageBindingMemoCapacity) { memos.Clear(); } - var remembered = _imageCache.RememberedRange(imageIdentifier, request); + // The lookup returns a placeholder without completing a lookup, so a kept placeholder completes none. + var remembered = nullImage ? default : _imageCache.RememberedRange(imageIdentifier, request); memos[key] = new ImageBindingMemo { Generation = _imageCache.LookupGeneration, @@ -605,8 +684,9 @@ private TextureResource ResolveImageBinding(ImageResource image, uint[] words, S OriginalResolution = originalResolution, Found = imageIdentifier, MetadataBaseLayer = metadataBaseLayer, - CompletesLookup = request.Description.Metadata.Kind == MetadataKind.Dcc || - Image(imageIdentifier).Description.DccSliceSize != 0, + CompletesLookup = !nullImage && (request.Description.Metadata.Kind == MetadataKind.Dcc || + Image(imageIdentifier).Description.DccSliceSize != 0), + NullImage = nullImage, }; } } @@ -820,7 +900,13 @@ public IPreparedBindings PrepareBindings(ShaderStageResources stage) throw Serial("bindless heap", resumable: true); } - _presenter.PrepareBindlessHeap(preparation); + // One preparation object serves every draw: the first stage of a draw that reads set 1 prepares the heap again. + if (!ReadsBindlessHeap(preparation.Stages)) + { + _presenter.ForgetHeapPreparation(preparation); + } + + _presenter.PrepareBindlessHeap(preparation, snapshot.Heaps); } if (layout.Find(DescriptorBindingKind.CallMarks) is not null) @@ -946,6 +1032,19 @@ public IPreparedBindings PrepareBindings(ShaderStageResources stage) return prepared; } + private static bool ReadsBindlessHeap(List stages) + { + foreach (var stage in stages) + { + if (stage.Layout.UsesBindlessHeap) + { + return true; + } + } + + return false; + } + // Reject incompatible draw views before buffer writes or image transitions are recorded. private void ValidateDrawImageTypes(PreparedStageBindings prepared) { @@ -1265,6 +1364,7 @@ public void BindResources(IPreparedBindings prepared) var stage = (PreparedStageBindings)prepared; var info = stage.Resources.Info; using var stallProfile = DescriptorStallProfile.Measure(DescriptorStallProfile.Operation.Bind, stage.Program.Hash, info.Buffers.Count, info.Images.Count, info.Samplers.Count); + var owners = _worker ? 0 : _bufferCache.OwnerGeneration; if (!_worker) { _bufferCache.BeginUploadBatch(); @@ -1296,9 +1396,46 @@ public void BindResources(IPreparedBindings prepared) BindImages(stage); } + // Binding an image can merge an owner bound above (an image source that grows it); bind the buffers again until no + // owner changes, so the stage never keeps a retired owner's handle. Render workers merge no owners. + for (var attempt = 0; !_worker && _bufferCache.OwnerGeneration != owners; attempt++) + { + if (attempt == 8) + { + throw SubmissionScheduler.Fatal($"Buffer owners kept changing while a stage was bound: hash=0x{stage.Program.Hash:X16}."); + } + + owners = _bufferCache.OwnerGeneration; + RebindBuffers(stage); + } + _preparedTextures.Add(stage.Textures); } + long IRenderHost.BufferOwnerGeneration => _worker ? 0 : _bufferCache.OwnerGeneration; + + public void RebindBuffers(IPreparedBindings prepared) + { + var stage = (PreparedStageBindings)prepared; + if (!_worker) + { + _bufferCache.BeginUploadBatch(); + } + + try + { + BindBuffers(stage); + ObtainDeviceAddressRanges(stage); + } + finally + { + if (!_worker) + { + _bufferCache.EndUploadBatch(); + } + } + } + // Textures bound for the draw being prepared; cleared when its preparation closes. private readonly List _preparedTextures = new(); @@ -1460,7 +1597,9 @@ private ulong UploadTableBlock(ReadOnlySpan bytes, ShaderProgramInfo progr return stream.DeviceAddress + offset; } - throw SubmissionScheduler.Fatal($"No upload ring could take a table block: bytes={bytes.Length} hash=0x{program.Hash:X16}."); + // The ring cannot wrap over the open preparation's own uploads; a host buffer of the draw then takes the block, + // as it takes other transient uploads. + return UploadHostBufferAddress(bytes, $"table block buffer of program 0x{program.Hash:X16}"); } private const uint TableBlockAlignment = 16; @@ -1505,6 +1644,9 @@ private void BindBuffers(PreparedStageBindings prepared) BindBufferViews(prepared, shaderData); } + WriteBufferStrides(prepared, shaderData); + // Each written image's store channel map, from its bound T# (RuntimeImageSwizzle). + RuntimeImageSwizzle.WriteStoreMaps(shaderData, layout, info.Images, snapshot.Images); if (layout.MipStatisticsCount != 0) { if (_worker && _presenter._lodStatistics is null) @@ -1532,6 +1674,22 @@ private void BindBuffers(PreparedStageBindings prepared) } } + // The stride indexed accesses of each binding multiply their index by, two to a dword. + private static void WriteBufferStrides(PreparedStageBindings prepared, uint[] shaderData) + { + var layout = prepared.Layout; + if (layout.BufferStrideCount == 0) + { + return; + } + + Array.Clear(shaderData, (int)layout.BufferStridesDword, (int)((layout.BufferStrideCount + 1) / 2)); + for (var index = 0; index < layout.BufferStrideCount; index++) + { + shaderData[layout.BufferStridesDword + (uint)index / 2] |= prepared.BufferSources[index].Descriptor.Stride << (index % 2 * 16); + } + } + private void BindBufferViews(PreparedStageBindings prepared, uint[] shaderData) { var program = prepared.Program; @@ -1790,6 +1948,51 @@ private void ReturnStageScratch(PreparedStageBindings stage) } } + // Pushes one set's descriptors, or writes them to a set from the heap and binds it; nothing when the same layout and + // descriptors are already bound there. + private void CommitDescriptorSet(CommandBuffer command, PipelineBindPoint bindPoint, PipelineLayout layout, uint setIndex, + DescriptorSetLayout setLayout, in DescriptorSetDemand demand, bool push, Span writes) + { + if (writes.Length == 0) + { + return; + } + + if (DescriptorsAlreadyBound(command, bindPoint, layout, writes, setIndex)) + { + Interlocked.Increment(ref _descriptorsShadowed); + return; + } + + fixed (WriteDescriptorSet* writePointer = writes) + { + if (push) + { + using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.VulkanCommands)) + { + _presenter._pushDescriptorApi.CmdPushDescriptorSet(command, bindPoint, layout, setIndex, (uint)writes.Length, writePointer); + } + + ShaderCacheCounters.CountPushSet(); + return; + } + + var set = _worker ? _sliceDescriptors!.Commit(setLayout, in demand) : _descriptorHeap.Commit(setLayout, in demand); + for (var index = 0; index < writes.Length; index++) + { + writes[index].DstSet = set; + } + + _vk.UpdateDescriptorSets(_device, (uint)writes.Length, writePointer, 0, null); + using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.VulkanCommands)) + { + _vk.CmdBindDescriptorSets(command, bindPoint, layout, setIndex, 1, &set, 0, null); + } + + ShaderCacheCounters.CountHeapSet(); + } + } + private static DescriptorImageInfo ImageInfo(TextureResource texture, uint element, ShaderProgramInfo program, int index) { var view = texture.MipViews.Length == 0 @@ -1884,6 +2087,7 @@ public void CommitBindings(PipelineBindPoint bindPoint, in PipelineHandle pipeli var bufferIndex = 0; var imageIndex = 0; var writeIndex = 0; + var pixelWriteStart = -1; var uploadStage = bindPoint == PipelineBindPoint.Compute ? PipelineStageFlags.ComputeShaderBit : PipelineStageFlags.FragmentShaderBit; var textures = textureCount == 0 ? [] : System.Buffers.ArrayPool.Shared.Rent(textureCount); var textureIndex = 0; @@ -1934,6 +2138,11 @@ public void CommitBindings(PipelineBindPoint bindPoint, in PipelineHandle pipeli textures[textureIndex++] = texture; } + if (shaderStage == ShaderStage.Pixel) + { + pixelWriteStart = writeIndex; + } + var occurrences = occurrenceScratch[..descriptors.Images.Length]; occurrences.Clear(); var bindings = stage.Layout.Descriptors; @@ -2087,55 +2296,23 @@ public void CommitBindings(PipelineBindPoint bindPoint, in PipelineHandle pipeli if (hasPushData) { - var pushStages = bindPoint == PipelineBindPoint.Graphics - ? ((entry.Description?.VertexStage.Stage == ShaderStageKind.Mesh - ? ShaderStageFlags.MeshBitExt : ShaderStageFlags.VertexBit) | - ShaderStageFlags.FragmentBit | - (entry.Description?.Tessellation is null - ? 0 : ShaderStageFlags.TessellationControlBit | ShaderStageFlags.TessellationEvaluationBit)) - : ShaderStageFlags.ComputeBit; + var pushStages = bindPoint != PipelineBindPoint.Graphics + ? ShaderStageFlags.ComputeBit + : entry.LinkedFromLibraries + ? _presenter.LibraryPushStages + : (entry.Description?.VertexStage.Stage == ShaderStageKind.Mesh + ? ShaderStageFlags.MeshBitExt : ShaderStageFlags.VertexBit) | + ShaderStageFlags.FragmentBit | + (entry.Description?.Tessellation is null + ? 0 : ShaderStageFlags.TessellationControlBit | ShaderStageFlags.TessellationEvaluationBit); PushConstantsShadowed(command, entry.Layout, pushStages, pushData); } - if (writeIndex != 0 && DescriptorsAlreadyBound(command, bindPoint, entry.Layout, writes[..writeIndex])) - { - Interlocked.Increment(ref _descriptorsShadowed); - } - else if (writeIndex != 0) - { - fixed (WriteDescriptorSet* writePointer = writes) - { - if (entry.UsesPushDescriptors) - { - using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.VulkanCommands)) - { - _presenter._pushDescriptorApi.CmdPushDescriptorSet(command, bindPoint, entry.Layout, 0, (uint)writeIndex, writePointer); - } - ShaderCacheCounters.CountPushSet(); - } - else - { - if (_worker) - { - throw Serial("descriptor heap", resumable: true); - } - - var set = _descriptorHeap.Commit(entry.SetLayout, in entry.Demand); - for (var index = 0; index < writeIndex; index++) - { - writes[index].DstSet = set; - } - - _vk.UpdateDescriptorSets(_device, (uint)writeIndex, writePointer, 0, null); - using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.VulkanCommands)) - { - _vk.CmdBindDescriptorSets(command, bindPoint, entry.Layout, 0, 1, &set, 0, null); - } - ShaderCacheCounters.CountHeapSet(); - } - } - } - + // A pipeline linked from libraries binds set 0 (vertex), the heap (set 1), then set 2 (pixel): binding a set + // with another layout disturbs the sets above it. + var vertexWrites = entry.LinkedFromLibraries && pixelWriteStart >= 0 ? pixelWriteStart : writeIndex; + CommitDescriptorSet(command, bindPoint, entry.Layout, 0, entry.SetLayout, in entry.Demand, entry.UsesPushDescriptors, + writes[..vertexWrites]); if (entry.UsesBindlessHeap) { if (_worker) @@ -2143,8 +2320,15 @@ public void CommitBindings(PipelineBindPoint bindPoint, in PipelineHandle pipeli throw Serial("bindless heap", resumable: true); } + NoteSetBinding(command, bindPoint, entry.Layout); _presenter.BindBindlessHeap(command, bindPoint, entry.Layout); } + + if (vertexWrites != writeIndex) + { + CommitDescriptorSet(command, bindPoint, entry.Layout, Presenter.PixelDescriptorSet, entry.PixelSetLayout, in entry.PixelDemand, + push: false, writes[vertexWrites..writeIndex]); + } } var spare = _worker ? null : _presenter._spareSubmissionResources ??= new Stack(); diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Device.Setup.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Device.Setup.cs index 58fc5eebb..10c811828 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Device.Setup.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Device.Setup.cs @@ -48,6 +48,9 @@ private sealed partial class Presenter private bool _supportsDualSourceBlend; internal bool _supportsDepthBiasClamp; private bool _supportsShaderSignedZeroInfNanPreserveFloat32; + internal bool _robustBufferAccess2Enabled; + private bool _nativeFloat16Conversions; + private bool _supportsPipelineBinaries; private uint _maxColorAttachments; internal Device _device; private PipelineCache _pipelineCache; @@ -60,7 +63,7 @@ private sealed partial class Presenter private const long PipelineCacheRetryMs = 1_000; private long _pipelineCacheRetryTick; private const ulong MaxPipelineCacheBytes = 256UL * 1024 * 1024; - private HashSet? _resetPipelineCachePaths; + private System.Collections.Concurrent.ConcurrentDictionary? _resetPipelineCachePaths; private nuint _pipelineCacheSavedBytes; private Queue _queue; private uint _queueFamilyIndex; @@ -74,6 +77,9 @@ private void Initialize() { _relay.BindCurrentThread(); WaitForRenderDocAttachIfRequested(); + DriverShaderCacheFolder.Apply(VulkanPipelineCacheStorage.ResolvePath( + VideoOutExports.GetApplicationTitleId(), + Environment.GetEnvironmentVariable("SHARPEMU_VK_PIPELINE_CACHE_PATH"))); _vk = Vk.GetApi(); uint loaderVersion = Vk.Version10; Check(_vk.EnumerateInstanceVersion(ref loaderVersion), "vkEnumerateInstanceVersion"); @@ -88,6 +94,20 @@ private void Initialize() SelectPhysicalDevice(); CreateDevice(); CreatePipelineCache(); + // The scalar graph and translation disk caches keep this game's entries beside its pipeline cache. + var gameCache = VulkanPipelineCacheStorage.ResolvePath( + VideoOutExports.GetApplicationTitleId(), + Environment.GetEnvironmentVariable("SHARPEMU_VK_PIPELINE_CACHE_PATH")); + SharpEmu.ShaderCompiler.Resources.ShaderAnalysisCache.UseGameFolder(gameCache + ".analysis"); + TranslationDiskCache.UseGameFolder(gameCache + ".translations", + BuildShaderPrewarmStamp(typeof(SharpEmu.Libs.Gpu.Vulkan.VulkanGuestGpuBackend), DriverCacheSignature())); + if (_supportsPipelineBinaries) + { + InitializePipelineBinaries(VulkanPipelineCacheStorage.ResolvePath( + VideoOutExports.GetApplicationTitleId(), + Environment.GetEnvironmentVariable("SHARPEMU_VK_PIPELINE_CACHE_PATH")) + ".binaries"); + } + CreateSwapchain(); CreateCommandResources(); CreateGuestDrawResources(); @@ -636,6 +656,13 @@ private void LoadComputeDeviceLimits() _vk.GetPhysicalDeviceProperties2(_physicalDevice, &properties2); _supportsShaderSignedZeroInfNanPreserveFloat32 = floatControls.ShaderSignedZeroInfNanPreserveFloat32; + // The 16-bit float controls of NativeFloat16Conversions, which must not need the same modes for 32 or 64 bits; + // CreateDevice adds shaderFloat16. SHARPEMU_NATIVE_FLOAT16=0 keeps the integer conversions. + _nativeFloat16Conversions = floatControls.ShaderRoundingModeRtefloat16 && floatControls.ShaderDenormPreserveFloat16 && + floatControls.ShaderSignedZeroInfNanPreserveFloat16 && + floatControls.RoundingModeIndependence == ShaderFloatControlsIndependence.IndependenceAll && + floatControls.DenormBehaviorIndependence == ShaderFloatControlsIndependence.IndependenceAll && + Environment.GetEnvironmentVariable("SHARPEMU_NATIVE_FLOAT16") != "0"; if (pushDescriptorProperties.PNext != null) { var ignoreMeshGranularity = _physicalDeviceVendorId == AmdVendorId; @@ -773,6 +800,8 @@ private void LoadComputeDeviceLimits() private bool _supportsShaderLayer; internal bool _supportsShaderClipDistance; internal bool _supportsMeshShader; + // Task shaders for task-launched mesh draws (MeshTaskLaunch), off with SHARPEMU_MESH_TASK_LAUNCH=0. + internal bool _supportsTaskShader; internal MeshShaderLimits _meshShaderLimits; internal delegate* unmanaged _cmdDrawMeshTasks; private const string FragmentShaderBarycentricExtensionName = "VK_KHR_fragment_shader_barycentric"; @@ -780,6 +809,7 @@ private void LoadComputeDeviceLimits() private const string ImageViewMinLodExtensionName = "VK_EXT_image_view_min_lod"; private const string FillRectangleExtensionName = "VK_NV_fill_rectangle"; private const string ShaderImageAtomicInt64ExtensionName = "VK_EXT_shader_image_atomic_int64"; + private const string ShaderClockExtensionName = "VK_KHR_shader_clock"; private const string UnifiedImageLayoutsExtensionName = "VK_KHR_unified_image_layouts"; private bool _supportsImageViewMinLod; private const string MeshShaderExtensionName = "VK_EXT_mesh_shader"; @@ -948,6 +978,48 @@ private void CreateDevice() supportsMaintenance5 = maintenance5Features.Maintenance5; } + var pipelineBinaryFeatures = new PhysicalDevicePipelineBinaryFeaturesKHR + { + SType = StructureType.PhysicalDevicePipelineBinaryFeaturesKhr, + }; + if (supportsMaintenance5 && PipelineBinariesRequested() && IsDeviceExtensionAvailable(PipelineBinaryExtensionName)) + { + var pipelineBinaryQuery = new PhysicalDeviceFeatures2 + { + SType = StructureType.PhysicalDeviceFeatures2, + PNext = &pipelineBinaryFeatures, + }; + _vk.GetPhysicalDeviceFeatures2(_physicalDevice, &pipelineBinaryQuery); + _supportsPipelineBinaries = pipelineBinaryFeatures.PipelineBinaries; + } + + var graphicsPipelineLibraryFeatures = new PhysicalDeviceGraphicsPipelineLibraryFeaturesEXT + { + SType = StructureType.PhysicalDeviceGraphicsPipelineLibraryFeaturesExt, + }; + if (GraphicsPipelineLibrariesRequested() && IsDeviceExtensionAvailable(PipelineLibraryExtensionName) && + IsDeviceExtensionAvailable(GraphicsPipelineLibraryExtensionName)) + { + var libraryProperties = new PhysicalDeviceGraphicsPipelineLibraryPropertiesEXT + { + SType = StructureType.PhysicalDeviceGraphicsPipelineLibraryPropertiesExt, + }; + var libraryPropertiesQuery = new PhysicalDeviceProperties2 + { + SType = StructureType.PhysicalDeviceProperties2, + PNext = &libraryProperties, + }; + _vk.GetPhysicalDeviceProperties2(_physicalDevice, &libraryPropertiesQuery); + var libraryQuery = new PhysicalDeviceFeatures2 + { + SType = StructureType.PhysicalDeviceFeatures2, + PNext = &graphicsPipelineLibraryFeatures, + }; + _vk.GetPhysicalDeviceFeatures2(_physicalDevice, &libraryQuery); + _graphicsPipelineLibraries = (bool)graphicsPipelineLibraryFeatures.GraphicsPipelineLibrary && + (bool)libraryProperties.GraphicsPipelineLibraryFastLinking; + } + var imageViewMinLodFeatures = new PhysicalDeviceImageViewMinLodFeaturesEXT { SType = StructureType.PhysicalDeviceImageViewMinLodFeaturesExt, @@ -980,6 +1052,24 @@ private void CreateDevice() } SetImageInt64AtomicsCapability(supportsImageInt64Atomics); + + var shaderClockFeatures = new PhysicalDeviceShaderClockFeaturesKHR + { + SType = StructureType.PhysicalDeviceShaderClockFeaturesKhr, + }; + var supportsShaderDeviceClock = false; + if (supportedFeatures.ShaderInt64 && IsDeviceExtensionAvailable(ShaderClockExtensionName)) + { + var shaderClockQuery = new PhysicalDeviceFeatures2 + { + SType = StructureType.PhysicalDeviceFeatures2, + PNext = &shaderClockFeatures, + }; + _vk.GetPhysicalDeviceFeatures2(_physicalDevice, &shaderClockQuery); + supportsShaderDeviceClock = shaderClockFeatures.ShaderDeviceClock; + } + + SetShaderDeviceClockCapability(supportsShaderDeviceClock); if (!supportsImageInt64Atomics) { Console.Error.WriteLine( @@ -1058,9 +1148,22 @@ private void CreateDevice() _supportsMeshShader = meshExtensionAvailable && meshFeatures.MeshShader && vulkan13Features.ComputeFullSubgroups && ((ShaderStageFlags)Volatile.Read(ref _nativeSubgroupShaderStages) & ShaderStageFlags.MeshBitExt) != 0; + _vk.GetPhysicalDeviceProperties(_physicalDevice, out var taskLimitProperties); + _supportsTaskShader = MeshTaskLaunch.Configured && _supportsMeshShader && meshFeatures.TaskShader && + taskLimitProperties.Limits.MaxPushConstantsSize >= + SharpEmu.ShaderCompiler.Vulkan.SpirvMeshTask.PushOffsetBytes + SharpEmu.ShaderCompiler.Vulkan.SpirvMeshTask.PushWordCount * 4u; + MeshTaskLaunch.DeviceSupported = _supportsTaskShader; + if (MeshTaskLaunch.Configured) + { + Console.Error.WriteLine($"[GPU][INFO] Task-launched mesh draws: {(_supportsTaskShader ? "on" : "off")} " + + $"(task_shader={(bool)meshFeatures.TaskShader} max_push={taskLimitProperties.Limits.MaxPushConstantsSize})."); + } var supportsTimelineSemaphore = vulkan12Features.TimelineSemaphore; var supportsBufferDeviceAddress = vulkan12Features.BufferDeviceAddress; var supportsSharedInt64Atomics = vulkan12Features.ShaderSharedInt64Atomics; + var supportsBufferInt64Atomics = vulkan12Features.ShaderBufferInt64Atomics; + _nativeFloat16Conversions &= vulkan12Features.ShaderFloat16; + Console.Error.WriteLine($"[LOADER][INFO] Vulkan native f16 conversions: {(_nativeFloat16Conversions ? "on" : "off")}"); _supportsShaderLayer = vulkan12Features.ShaderOutputLayer; var supportsViewportIndexLayer = IsDeviceExtensionAvailable("VK_EXT_shader_viewport_index_layer") && vulkan12Features.ShaderOutputViewportIndex && vulkan12Features.ShaderOutputLayer; @@ -1074,6 +1177,13 @@ private void CreateDevice() _canRequireComputeSubgroup32 &= vulkan13Features.SubgroupSizeControl; _canRequireComputeSubgroup64 &= vulkan13Features.SubgroupSizeControl; SetSharedInt64AtomicsCapability(supportsSharedInt64Atomics); + SetBufferInt64AtomicsCapability(supportsBufferInt64Atomics); + if (!supportsBufferInt64Atomics) + { + Console.Error.WriteLine( + "[LOADER][WARN] GPU does not support shaderBufferInt64Atomics: " + + "64-bit buffer atomics fall back to a non-atomic pair of 32-bit atomics."); + } if (!supportsSharedInt64Atomics) { Console.Error.WriteLine( @@ -1123,6 +1233,11 @@ private void CreateDevice() var meshExtension = (byte*)SilkMarshal.StringToPtr(MeshShaderExtensionName); var imageAtomicInt64Extension = (byte*)SilkMarshal.StringToPtr(ShaderImageAtomicInt64ExtensionName); var unifiedImageLayoutsExtension = (byte*)SilkMarshal.StringToPtr(UnifiedImageLayoutsExtensionName); + var shaderClockExtension = (byte*)SilkMarshal.StringToPtr(ShaderClockExtensionName); + var pipelineBinaryExtension = (byte*)SilkMarshal.StringToPtr(PipelineBinaryExtensionName); + var pipelineLibraryExtension = (byte*)SilkMarshal.StringToPtr(PipelineLibraryExtensionName); + var graphicsPipelineLibraryExtension = (byte*)SilkMarshal.StringToPtr(GraphicsPipelineLibraryExtensionName); + var deviceFaultExtension = (byte*)SilkMarshal.StringToPtr("VK_EXT_device_fault"); try { var extensions = stackalloc byte*[24]; @@ -1166,6 +1281,11 @@ private void CreateDevice() extensions[extensionCount++] = maintenance5Extension; } + if (_supportsPipelineBinaries) + { + extensions[extensionCount++] = pipelineBinaryExtension; + } + if (_supportsImageViewMinLod) { extensions[extensionCount++] = imageViewMinLodExtension; @@ -1186,6 +1306,11 @@ private void CreateDevice() extensions[extensionCount++] = imageAtomicInt64Extension; } + if (supportsShaderDeviceClock) + { + extensions[extensionCount++] = shaderClockExtension; + } + if (supportsRobustness2) { extensions[extensionCount++] = robustness2Extension; @@ -1201,6 +1326,7 @@ private void CreateDevice() maintenance8Features.PNext = null; robustness2Features.RobustBufferAccess2 = supportsRobustBufferAccess2 && supportedFeatures.RobustBufferAccess; + _robustBufferAccess2Enabled = supportsRobustness2 && (bool)robustness2Features.RobustBufferAccess2; robustness2Features.RobustImageAccess2 = supportsRobustImageAccess2; robustness2Features.NullDescriptor = supportsNullDescriptor; robustness2Features.PNext = supportsMaintenance8 ? &maintenance8Features : null; @@ -1222,6 +1348,8 @@ private void CreateDevice() TimelineSemaphore = true, BufferDeviceAddress = true, ShaderSharedInt64Atomics = supportsSharedInt64Atomics, + ShaderBufferInt64Atomics = supportsBufferInt64Atomics, + ShaderFloat16 = _nativeFloat16Conversions, ShaderOutputLayer = _supportsShaderLayer, ShaderOutputViewportIndex = supportsViewportIndexLayer, DescriptorIndexing = _bindlessHeapSupported, @@ -1241,6 +1369,7 @@ private void CreateDevice() { SType = StructureType.PhysicalDeviceMeshShaderFeaturesExt, MeshShader = true, + TaskShader = _supportsTaskShader, PNext = renderingChain, }; renderingChain = &meshFeatures; @@ -1272,6 +1401,16 @@ private void CreateDevice() }; renderingChain = &maintenance5Features; } + if (_supportsPipelineBinaries) + { + pipelineBinaryFeatures = new PhysicalDevicePipelineBinaryFeaturesKHR + { + SType = StructureType.PhysicalDevicePipelineBinaryFeaturesKhr, + PipelineBinaries = true, + PNext = renderingChain, + }; + renderingChain = &pipelineBinaryFeatures; + } if (_supportsImageViewMinLod) { imageViewMinLodFeatures = new PhysicalDeviceImageViewMinLodFeaturesEXT @@ -1304,6 +1443,16 @@ private void CreateDevice() }; renderingChain = &unifiedImageLayoutsFeatures; } + if (supportsShaderDeviceClock) + { + shaderClockFeatures = new PhysicalDeviceShaderClockFeaturesKHR + { + SType = StructureType.PhysicalDeviceShaderClockFeaturesKhr, + ShaderDeviceClock = true, + PNext = renderingChain, + }; + renderingChain = &shaderClockFeatures; + } if (_supportsDepthClipEnable) { depthClipEnableFeatures = new PhysicalDeviceDepthClipEnableFeaturesEXT @@ -1337,6 +1486,38 @@ private void CreateDevice() renderingChain = &colorWriteEnableFeatures; } + if (_graphicsPipelineLibraries) + { + extensions[extensionCount++] = pipelineLibraryExtension; + extensions[extensionCount++] = graphicsPipelineLibraryExtension; + graphicsPipelineLibraryFeatures = new PhysicalDeviceGraphicsPipelineLibraryFeaturesEXT + { + SType = StructureType.PhysicalDeviceGraphicsPipelineLibraryFeaturesExt, + GraphicsPipelineLibrary = true, + PNext = renderingChain, + }; + renderingChain = &graphicsPipelineLibraryFeatures; + } + var faultFeatures = new PhysicalDeviceFaultFeaturesEXT { SType = StructureType.PhysicalDeviceFaultFeaturesExt }; + var reportDeviceFaults = false; + if (SharpEmu.Libs.Gpu.Vulkan.DeviceFaultReport.Requested && IsDeviceExtensionAvailable("VK_EXT_device_fault")) + { + var faultSupport = new PhysicalDeviceFeatures2 + { + SType = StructureType.PhysicalDeviceFeatures2, + PNext = &faultFeatures, + }; + _vk.GetPhysicalDeviceFeatures2(_physicalDevice, &faultSupport); + reportDeviceFaults = faultFeatures.DeviceFault; + if (reportDeviceFaults) + { + // VendorBinary is a separate feature; retain only the capabilities the driver reported. + extensions[extensionCount++] = deviceFaultExtension; + faultFeatures.PNext = renderingChain; + renderingChain = &faultFeatures; + } + } + vulkan13Features = new PhysicalDeviceVulkan13Features { SType = StructureType.PhysicalDeviceVulkan13Features, @@ -1363,6 +1544,13 @@ private void CreateDevice() }; Check(_vk.CreateDevice(_physicalDevice, &createInfo, null, out _device), "vkCreateDevice"); + if (reportDeviceFaults) + SharpEmu.Libs.Gpu.Vulkan.DeviceFaultReport.Attach(_vk, _device, faultFeatures.DeviceFaultVendorBinary); + else if (SharpEmu.Libs.Gpu.Vulkan.DeviceFaultReport.Requested) + Console.Error.WriteLine("[GPU][FAULT] VK_EXT_device_fault requested but unsupported"); + Console.Error.WriteLine(_graphicsPipelineLibraries + ? "[LOADER][INFO] Vulkan graphics pipeline libraries: on (SHARPEMU_GRAPHICS_PIPELINE_LIBRARY=0 builds whole pipelines)" + : "[LOADER][INFO] Vulkan graphics pipeline libraries: off"); if (_supportsMeshShader) { _cmdDrawMeshTasks = (delegate* unmanaged) @@ -1384,6 +1572,11 @@ private void CreateDevice() SilkMarshal.Free((nint)unifiedImageLayoutsExtension); SilkMarshal.Free((nint)fillRectangleExtension); SilkMarshal.Free((nint)imageAtomicInt64Extension); + SilkMarshal.Free((nint)shaderClockExtension); + SilkMarshal.Free((nint)pipelineBinaryExtension); + SilkMarshal.Free((nint)pipelineLibraryExtension); + SilkMarshal.Free((nint)graphicsPipelineLibraryExtension); + SilkMarshal.Free((nint)deviceFaultExtension); SilkMarshal.Free((nint)robustness2Extension); SilkMarshal.Free((nint)portabilitySubsetExtension); SilkMarshal.Free((nint)colorWriteEnableExtension); @@ -1630,10 +1823,28 @@ private void CheckpointPipelineCache() SavePipelineCache(force: false); } + // Compiles start under these locks (TryCreateComputePipeline, TryCreateGraphicsPipeline), from the command stream and + // the resolve workers. + private bool AnyPipelineCompiling() + { + lock (_pendingComputePipelines) + { + if (_pendingComputePipelines.Values.Any(pending => !pending.Compile.IsCompleted)) + { + return true; + } + } + + lock (_pendingGraphicsPipelines) + { + return _pendingGraphicsPipelines.Values.Any(pending => !pending.Compile.IsCompleted); + } + } + private void SavePipelineCache(bool force) { // Cache export must not race asynchronous pipeline creation. - if (_pendingComputePipelines.Values.Any(pending => !pending.Compile.IsCompleted)) return; + if (AnyPipelineCompiling()) return; _lastPipelineCacheSaveTick = Environment.TickCount64; SaveGuestPipelineCaches(); if (_pipelineCache.Handle == 0 || string.IsNullOrWhiteSpace(_pipelineCachePath)) @@ -1690,7 +1901,8 @@ private bool SaveDriverPipelineCache(PipelineCache cache, string path, ulong byt if (size > byteLimit) { - if ((_resetPipelineCachePaths ??= new HashSet(StringComparer.Ordinal)).Add(path)) + if (LazyInitializer.EnsureInitialized(ref _resetPipelineCachePaths, + static () => new System.Collections.Concurrent.ConcurrentDictionary(StringComparer.Ordinal)).TryAdd(path, 0)) { WritePipelineCacheFile(path, []); Console.Error.WriteLine( @@ -1748,7 +1960,7 @@ private void WritePipelineCacheFile(string path, ReadOnlySpan data) Directory.CreateDirectory(directory); } - var temporaryPath = path + $".{Environment.ProcessId}.tmp"; + var temporaryPath = path + $".{Environment.ProcessId}.{Environment.CurrentManagedThreadId}.tmp"; File.WriteAllBytes(temporaryPath, PipelineCacheSignature.Wrap(DriverCacheSignature(), data)); File.Move(temporaryPath, path, overwrite: true); } diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Device.Teardown.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Device.Teardown.cs index 848398796..62e4f6230 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Device.Teardown.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Device.Teardown.cs @@ -28,8 +28,12 @@ private void DisposeVulkan() _vk.DeviceWaitIdle(_device); } + // Linked compiles still waiting for admission give up, so neither the prewarm's stop nor the drain below waits for + // them. + _linkedAdmissionClosed = true; StopShaderPrewarm(); DrainPendingComputePipelines(); + DrainPendingGraphicsPipelines(); SavePipelineCache(force: true); DrainFrameSlots(); CollectCompletedGuestSubmissions(waitForOldest: false); @@ -38,6 +42,8 @@ private void DisposeVulkan() DestroyBindlessHeap(); DestroyCallMarks(); _descriptorHeap.Dispose(); + _descriptorPoolStock?.Dispose(); + _descriptorPoolStock = null; _contentUploads.Dispose(); _imageCache.Dispose(); _samplerStore.Dispose(); @@ -71,6 +77,7 @@ private void DisposeVulkan() _vk.DestroyPipelineCache(_device, _pipelineCache, null); _pipelineCache = default; } + SharpEmu.Libs.Gpu.Vulkan.DeviceFaultReport.Detach(_device); _vk.DestroyDevice(_device, null); _device = default; } diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.DispatchThreads.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.DispatchThreads.cs new file mode 100644 index 000000000..802f7421a --- /dev/null +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.DispatchThreads.cs @@ -0,0 +1,163 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Gpu.Scheduling; + +namespace SharpEmu.Libs.VideoOut; + +internal static unsafe partial class VulkanVideoPresenter +{ + private sealed partial class Presenter + { + internal DispatchThreadsPipeline? _dispatchThreadsPipeline; + + // Indirect dispatches that count threads keep their GPU-written counts on the GPU (DispatchThreadsPipeline). + public bool ResolvesIndirectThreadDispatchOnGpu => ResolvesIndirectDispatchOnGpu; + } + + private sealed partial class RecordingHost + { + public bool ResolvesIndirectThreadDispatchOnGpu => _presenter.ResolvesIndirectThreadDispatchOnGpu; + + // On the render thread the arguments register before the stage's resources, so no later acquisition can merge an + // owner the dispatch binds. A render worker never merges an owner: its arguments are acquired with the dispatch. + public IIndirectDispatchArguments PrepareIndirectDispatchArguments(ulong argumentsAddress) + { + _ = RequirePreparation(); + return _worker ? new SliceDispatchArguments(argumentsAddress) : new PreparedDispatchArguments(this, argumentsAddress); + } + + public IThreadDispatch PrepareThreadDispatch(IIndirectDispatchArguments arguments, IPreparedBindings bindings, ReadOnlySpan groupSize, + ReadOnlySpan physicalAxis) + { + if (_worker) + { + throw Serial("thread dispatch", resumable: true); + } + + _ = RequirePreparation(); + var stage = (PreparedStageBindings)bindings; + var layout = stage.Layout; + BufferBinding? limits = null; + if (layout.UsesDispatchThreadLimits) + { + if (layout.UsesPushData) + { + throw SubmissionScheduler.Fatal( + $"A dispatch with GPU thread counts keeps its thread limits in push data: hash=0x{stage.Program.Hash:X16}."); + } + + var shaderData = stage.Descriptors.ShaderData; + limits = new BufferBinding(shaderData.Buffer.Handle, shaderData.Offset + layout.DispatchThreadLimitsDword * sizeof(uint)); + } + + var retained = (PreparedDispatchArguments)arguments; + var pipeline = _presenter._dispatchThreadsPipeline ??= new DispatchThreadsPipeline(_deviceInfo); + var resources = pipeline.Prepare(_scheduler, retained.Use(), limits, groupSize, physicalAxis); + var dispatch = new ThreadDispatch(this, resources); + try + { + dispatch.Record(BeginBatchedGuestCommands()); + return dispatch; + } + catch + { + dispatch.Dispose(); + throw; + } + } + + // A render worker's arguments: TryDispatchIndirect acquires them from the slice's buffer snapshot. + private sealed class SliceDispatchArguments(ulong address) : IIndirectDispatchArguments + { + public ulong Address => address; + + public void Rebind() + { + } + + public void Dispose() + { + } + } + + private sealed class PreparedDispatchArguments : IIndirectDispatchArguments + { + private readonly RecordingHost _owner; + private readonly ulong _address; + private RetainedMeshInput? _input; + private bool _used; + private bool _disposed; + + public PreparedDispatchArguments(RecordingHost owner, ulong address) + { + _owner = owner; + _address = address; + _ = owner._bufferCache.FindBuffer(address, 3u * sizeof(uint)); + } + + public void Rebind() + { + if (_used || _disposed) throw SubmissionScheduler.Fatal("Indirect arguments cannot be rebound after GPU use or disposal."); + var replacement = _owner.RetainMeshInput(_address, 3u * sizeof(uint)); + var previous = _input; + _input = replacement; + previous?.Dispose(); + } + + public BufferBinding Use() + { + var input = _input ?? throw SubmissionScheduler.Fatal("Indirect arguments were already released."); + _used = true; + return input.Binding; + } + + public void Dispose() + { + _disposed = true; + var input = Interlocked.Exchange(ref _input, null); + if (input is null) return; + if (_used) _owner._scheduler.QueueCompletionAction(input.Dispose); + else input.Dispose(); + } + } + + private sealed class ThreadDispatch(RecordingHost owner, DispatchThreadsPipeline.PreparedDispatch resources) : IThreadDispatch + { + private DispatchThreadsPipeline.PreparedDispatch? _resources = resources; + private bool _recorded; + + public void Record(Silk.NET.Vulkan.CommandBuffer command) + { + _recorded = true; + _resources!.Record(command); + } + + public void Dispatch() + { + var resources = _resources ?? throw SubmissionScheduler.Fatal("The converted dispatch was already released."); + using var profileScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.DrawRecording); + var command = owner.BeginBatchedGuestCommands(); + using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.VulkanCommands)) + { + owner._vk.CmdDispatchIndirect(command, resources.GroupsBuffer, 0); + } + + owner.CountDraw(); + owner.NoteShaderMayWriteMappedMemory(); + Dispose(); + } + + public void Dispose() + { + var resources = Interlocked.Exchange(ref _resources, null); + if (resources is null) return; + // A later consumer may be in a different submission from the conversion. + // Cancellation also waits for a recorded conversion before returning its pool lease. + if (_recorded) owner._scheduler.QueueCompletionAction(resources.Dispose); + else resources.Dispose(); + } + } + } +} diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.GraphicsPrewarm.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.GraphicsPrewarm.cs new file mode 100644 index 000000000..5a63bff8d --- /dev/null +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.GraphicsPrewarm.cs @@ -0,0 +1,343 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Libs.VideoOut; + +using System.Collections.Concurrent; +using System.Diagnostics; +using SharpEmu.Libs.Gpu; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using Silk.NET.Core.Native; +using Silk.NET.Vulkan; + +internal static unsafe partial class VulkanVideoPresenter +{ + private sealed partial class Presenter + { + // The graphics prewarm (SHARPEMU_GRAPHICS_PREWARM=0 off). The pixel programs and the vertex and mesh programs + // with their pre-rasterization states that earlier sessions recorded are translated again at boot (through the + // translation cache), and their libraries are compiled the way the session builds them, into the pipeline cache. + // After a new build or translator change, a program's first draw then links cached libraries instead of compiling + // them while the command stream waits, which can take seconds per library. Items go in the order sessions first + // met them, on the prewarm pool's below-normal threads beside the compute records, the more urgent first + // (PrewarmPool); the side file's progress skips the items this build already prewarmed. + private static readonly bool GraphicsPrewarmEnabled = Environment.GetEnvironmentVariable("SHARPEMU_GRAPHICS_PREWARM") != "0"; + + private readonly ConcurrentQueue _graphicsPrewarmCompleted = new(); + // The payloads the prewarm compiled, and the pixel modules the session created while it runs: the prewarm leaves a + // pixel item of a session module to the session's early pixel library, which compiles the same part. A + // pre-rasterization item always compiles: a program can take several states, and a part the session compiled already + // is found in the pipeline cache. + private ConcurrentDictionary? _prewarmedGraphicsModules; + private readonly ConcurrentDictionary _sessionPixelModules = new(StringComparer.Ordinal); + // The prewarm identity of each vertex or mesh module the session recorded (VertexProgramRecorded). + private readonly ConcurrentDictionary _vertexPrewarmIdentities = new(); + private int _graphicsPrewarmCompiled; + private int _graphicsPrewarmTaken; + private int _graphicsPrewarmFailed; + private int _graphicsPrewarmProgress; + private int _runtimePixelModules; + private int _runtimePixelHits; + private int _runtimeVertexModules; + private int _runtimeVertexHits; + + private void StartGraphicsPrewarm(ShaderPrewarmList list, string buildStamp, IGuestGpuBackend compiler) + { + // Only where the device has pipeline binaries, like the compute prewarm; a capture layer that hides the extension + // runs without a prewarm. + if (!GraphicsPrewarmEnabled || !_graphicsPipelineLibraries || _pipelineBinaries is null || _pipelineBinaryDirectory is null) + { + return; + } + + var items = list.LoadedGraphicsPrewarm(); + var missing = list.LoadedPixelCount + list.LoadedPreRasterizationCount - items.Count; + // A pixel item builds the part early pixel libraries build (PixelProgramCreated); without them, draws compile their + // pixel parts for their own sample states. + IReadOnlyList pending = _earlyPixelLibraries + ? items + : items.Where(static item => item is not PixelPrewarmItem).ToList(); + var recorded = pending.Count; + if (PrewarmBinarySkip && recorded != 0 && list.ReadProgress(buildStamp, extension: true) is { Count: > 0 } completed) + { + pending = pending.Where(item => !completed.Contains(item.Identity)).ToList(); + } + + if (pending.Count == 0) + { + if (recorded != 0) + { + Console.Error.WriteLine($"[LOADER][INFO] Graphics prewarm skipped: items={recorded} resumed={recorded}"); + } + + return; + } + + _prewarmedGraphicsModules = new ConcurrentDictionary(StringComparer.Ordinal); + var work = new ConcurrentQueue(pending); + var workerCount = Math.Clamp(Environment.ProcessorCount / 4, 1, 4); + var started = Stopwatch.GetTimestamp(); + Interlocked.Add(ref _shaderPrewarmGraphicsTotal, pending.Count); + Interlocked.Add(ref _shaderPrewarmWorkers, workerCount); + Console.Error.WriteLine( + $"[LOADER][INFO] Graphics prewarm started: pixel={pending.Count(static item => item is PixelPrewarmItem)} " + + $"pre_rasterization={pending.Count(static item => item is PreRasterizationPrewarmItem)} " + + $"resumed={recorded - pending.Count} missing={missing} workers={workerCount}"); + PrewarmWorkers.Add(new PrewarmPool.Lane(pending.Count, + (out float start) => + { + var any = work.TryPeek(out var next); + start = any ? next!.FirstUse : 0; + return any; + }, + _ => + { + if (!work.TryDequeue(out var item)) + { + return false; + } + + if (Prewarm(item, compiler)) + { + _graphicsPrewarmCompleted.Enqueue(item.Identity); + } + + Interlocked.Increment(ref _shaderPrewarmGraphicsDone); + if (Interlocked.Increment(ref _graphicsPrewarmProgress) % PrewarmProgressBatch == 0) + { + FlushGraphicsPrewarmProgress(list, buildStamp); + } + + return true; + }, + () => + { + FlushGraphicsPrewarmProgress(list, buildStamp); + Console.Error.WriteLine( + $"[LOADER][INFO] Graphics prewarm done: compiled={Volatile.Read(ref _graphicsPrewarmCompiled)} " + + $"taken={Volatile.Read(ref _graphicsPrewarmTaken)} failed={Volatile.Read(ref _graphicsPrewarmFailed)} " + + $"stopped={_shaderPrewarmStopping} ms={Stopwatch.GetElapsedTime(started).TotalMilliseconds:F0}"); + }), + workerCount, "SharpEmu graphics prewarm"); + } + + private void FlushGraphicsPrewarmProgress(ShaderPrewarmList list, string stamp) + { + var batch = new List(); + while (_graphicsPrewarmCompleted.TryDequeue(out var identity)) + { + batch.Add(identity); + } + + list.AppendProgress(stamp, batch, extension: true); + } + + private bool Prewarm(GraphicsPrewarmItem item, IGuestGpuBackend compiler) => item switch + { + PixelPrewarmItem pixel => PrewarmPixelLibrary(pixel.Record, pixel.Code, compiler), + PreRasterizationPrewarmItem part => PrewarmPreRasterizationLibrary(part.Program, part.Code, part.State, compiler), + _ => false, + }; + + // The translation and the pixel library of one record. The module (the same payload CreateShaderModule gives the + // session) and the library go once the compile has put the part in the pipeline cache. + private bool PrewarmPixelLibrary(PixelPrewarmRecord record, ShaderCodeCapture code, IGuestGpuBackend compiler) + { + var name = $"ps=0x{record.Hash:X16} shader=0x{record.Address:X16}"; + if (!ShaderProgramCache.TryCompilePixelPrewarm(record, code, compiler, this, out var compiled, out var layout, out var error)) + { + NoteGraphicsPrewarmFailure(name, error); + return false; + } + + ShaderModule module = default; + var library = default(Pipeline); + try + { + var payload = WithDescriptorSet(compiled!.Payload, 0, PixelDescriptorSet); + var identity = VulkanPipelineCacheStorage.CompiledShaderIdentity(payload); + if (LeftToSession(identity)) + { + return true; + } + + module = CreateShaderModule(payload); + var bindings = new List(); + CollectLayoutBindings(bindings, layout!, ShaderStage.Pixel); + library = CreateEarlyPixelLibrary(module.Handle, bindings, $"vs=prewarm {name}"); + return NoteGraphicsPrewarmLibrary(library, identity, name); + } + catch (Exception exception) + { + NoteGraphicsPrewarmFailure(name, exception.Message); + return false; + } + finally + { + if (library.Handle != 0) + { + _vk.DestroyPipeline(_device, library, null); + } + + if (module.Handle != 0) + { + _vk.DestroyShaderModule(_device, module, null); + } + } + } + + // The translation of a vertex or mesh record and its pre-rasterization library for one recorded state, built as + // CompilePreRasterizationPart builds the session's, with the task stage of a task-launched mesh program. + private bool PrewarmPreRasterizationLibrary(VertexPrewarmRecord program, ShaderCodeCapture code, PreRasterizationState state, + IGuestGpuBackend compiler) + { + var name = $"{(program.Mesh ? "ms" : "vs")}=0x{program.Hash:X16} shader=0x{program.Address:X16}"; + if (!ShaderProgramCache.TryCompileVertexPrewarm(program, code, compiler, this, out var compiled, out var layout, + out var task, out var error)) + { + NoteGraphicsPrewarmFailure(name, error); + return false; + } + + if (task is not null && !_supportsTaskShader) + { + NoteGraphicsPrewarmFailure(name, "the device has no task shaders"); + return false; + } + + ShaderModule module = default; + DescriptorSetLayout set = default; + PipelineLayout pipelineLayout = default; + var library = default(Pipeline); + var taskEntries = stackalloc SpecializationMapEntry[TaskSpecializationValues]; + var taskValues = stackalloc uint[TaskSpecializationValues]; + var taskSpecialization = new SpecializationInfo(); + var entryPoint = (byte*)SilkMarshal.StringToPtr("main"); + try + { + var payload = compiled!.Payload; + var identity = VulkanPipelineCacheStorage.CompiledShaderIdentity(payload); + module = CreateShaderModule(payload); + var bindings = new List(); + CollectLayoutBindings(bindings, layout!, program.Mesh ? ShaderStage.Mesh : ShaderStage.Vertex); + if (bindings.Count != 0) + { + set = CreateDescriptorSetLayout(bindings, allowPush: true, out _, out _); + } + + pipelineLayout = CreateLibraryPipelineLayout(set, default); + var taskStage = task is { } launch ? TaskStageInfo(launch, taskEntries, taskValues, &taskSpecialization, entryPoint) : default; + library = CreatePreRasterizationLibrary(VertexStageInfo(program.Mesh, module, entryPoint), task is null ? null : &taskStage, + state, pipelineLayout, $"{name} prewarm"); + return NoteGraphicsPrewarmLibrary(library, identity, name); + } + catch (Exception exception) + { + NoteGraphicsPrewarmFailure(name, exception.Message); + return false; + } + finally + { + if (library.Handle != 0) + { + _vk.DestroyPipeline(_device, library, null); + } + + if (pipelineLayout.Handle != 0) + { + _vk.DestroyPipelineLayout(_device, pipelineLayout, null); + } + + if (set.Handle != 0) + { + _vk.DestroyDescriptorSetLayout(_device, set, null); + } + + if (module.Handle != 0) + { + _vk.DestroyShaderModule(_device, module, null); + } + + SilkMarshal.Free((nint)entryPoint); + } + } + + // True when the session already created this pixel module: its early pixel library compiles the same part. + private bool LeftToSession(string identity) + { + if (!_sessionPixelModules.ContainsKey(identity)) + { + return false; + } + + Interlocked.Increment(ref _graphicsPrewarmTaken); + return true; + } + + private bool NoteGraphicsPrewarmLibrary(Pipeline library, string identity, string name) + { + if (library.Handle == 0) + { + NoteGraphicsPrewarmFailure(name, "the library was not created"); + return false; + } + + _prewarmedGraphicsModules![identity] = 0; + Interlocked.Increment(ref _graphicsPrewarmCompiled); + return true; + } + + private void NoteGraphicsPrewarmFailure(string name, string error) + { + if (Interlocked.Increment(ref _graphicsPrewarmFailed) <= MaxLoggedPrewarmFailures) + { + Console.Error.WriteLine($"[LOADER][WARN] Graphics prewarm failed: {name} error={error}"); + } + } + + // A vertex or mesh program the program cache recorded; the states its pre-rasterization parts compile with are + // recorded under its identity (RecordPreRasterization). + public void VertexProgramRecorded(ulong module, ulong prewarmIdentity) => _vertexPrewarmIdentities[module] = prewarmIdentity; + + private void RecordPreRasterization(ulong module, PreRasterizationState state) + { + if (Volatile.Read(ref _shaderPrewarmList) is { } list && _vertexPrewarmIdentities.TryGetValue(module, out var program)) + { + list.RecordPreRasterization(program, state); + } + } + + // The session's pixel, vertex and mesh modules while a graphics prewarm runs, with a census of those whose payload the + // prewarm compiled. + private void NoteRuntimeGraphicsModule(string identity, ShaderStage stage) + { + if (_prewarmedGraphicsModules is not { } prewarmed) + { + return; + } + + var hit = prewarmed.ContainsKey(identity); + if (stage == ShaderStage.Pixel) + { + _sessionPixelModules.TryAdd(identity, 0); + NoteRuntimeHit("Pixel", "pixel", ref _runtimePixelModules, ref _runtimePixelHits, hit); + } + else + { + NoteRuntimeHit("Vertex", "vertex", ref _runtimeVertexModules, ref _runtimeVertexHits, hit); + } + } + + private static void NoteRuntimeHit(string name, string key, ref int modules, ref int hits, bool hit) + { + var count = Interlocked.Increment(ref modules); + var matched = hit ? Interlocked.Increment(ref hits) : Volatile.Read(ref hits); + if (count is 1 or 10 or 50 or 100 or 200 or 400 or 800) + { + Console.Error.WriteLine($"[LOADER][INFO] {name} prewarm hits: {matched} of runtime_{key}_modules={count}"); + } + } + } +} diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.LodStatistics.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.LodStatistics.cs index b1619f531..7ce891412 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.LodStatistics.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.LodStatistics.cs @@ -37,6 +37,12 @@ internal LodStatisticsRecorder LodStatistics() => bool Gpu.Pipelines.IShaderPipelineHost.MipStatisticsSubgroupReduction => FragmentSubgroupArithmetic && GraphicsSubgroupOperationsEnabled; + bool Gpu.Pipelines.IShaderPipelineHost.PixelSubgroupArithmetic => + VulkanGraphicsSubgroupPolicy.ShouldUsePixelSubgroupArithmetic( + unchecked((uint)Volatile.Read(ref _nativeSubgroupSize)), + GraphicsSubgroupOperationsEnabled, + FragmentSubgroupArithmetic); + bool Gpu.GpuCommands.ICommandStreamHost.TryRecordLodStatistics(ulong destination, uint size) { if (!ResourceMaterializer.RecordMipStatistics) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.MeshIndirect.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.MeshIndirect.cs index 5757a3234..3d0485dd2 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.MeshIndirect.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.MeshIndirect.cs @@ -20,6 +20,7 @@ private sealed partial class Presenter private sealed partial class RecordingHost { private static int _clampWarned; + private static int _overLimitDraws; public bool SupportsIndirectMeshDraw => _presenter._supportsMeshShader && _presenter._cmdDrawMeshTasksIndirect is not null; @@ -32,17 +33,28 @@ public IIndirectMeshDraw PrepareIndirectMeshDraw(in IndirectMeshDrawRequest requ _ = RequirePreparation(); if (!SupportsIndirectMeshDraw) throw SubmissionScheduler.Fatal("The Vulkan device has no indirect mesh command."); - var indexBase = request.IndexAddress & ~3ul; - var prefix = checked((uint)(request.IndexAddress - indexBase)); - var size = (prefix + (ulong)request.IndexCapacity * request.IndexElementSize + 3) & ~3ul; - var arguments = RetainMeshInput(request.ArgumentsAddress, 20); + if (request.TaskLaunched) + { + return PrepareTaskLaunchedMeshDraw(in request); + } + + var arguments = RetainMeshInput(request.ArgumentsAddress, request.Automatic ? 16ul : 20ul); RetainedMeshInput? indices = null; MeshIndirectPipeline.PreparedDraw? resources = null; try { - indices = RetainMeshInput(indexBase, size); + var prefix = 0u; + if (!request.Automatic) + { + var indexBase = request.IndexAddress & ~3ul; + prefix = checked((uint)(request.IndexAddress - indexBase)); + var size = (prefix + (ulong)request.IndexCapacity * request.IndexElementSize + 3) & ~3ul; + indices = RetainMeshInput(indexBase, size); + } + var pipeline = _presenter._meshIndirectPipeline ??= new MeshIndirectPipeline(_deviceInfo); - resources = pipeline.Prepare(_scheduler, arguments.Binding, indices.Binding, prefix, request); + // An automatic draw reads no indices; its arguments fill the unused binding. + resources = pipeline.Prepare(_scheduler, arguments.Binding, (indices ?? arguments).Binding, prefix, request); return new PreparedIndirectMesh(this, resources, arguments, indices, request.ArgumentsAddress, request.IndexCapacity); } catch @@ -54,6 +66,111 @@ public IIndirectMeshDraw PrepareIndirectMeshDraw(in IndirectMeshDrawRequest requ } } + // The task stage converts the arguments (MeshTaskLaunch): it reads them by device address, or from the push words when + // they sit in a host ring without one (a CPU-written range staged for this recording, so the CPU bytes are current). + private IIndirectMeshDraw PrepareTaskLaunchedMeshDraw(in IndirectMeshDrawRequest request) + { + if (!request.Automatic || !_presenter._supportsTaskShader) + throw SubmissionScheduler.Fatal("A task-launched mesh draw needs an automatic draw and task shaders."); + // The task stage loads the arguments as dwords, as the command processor reads them. + if ((request.ArgumentsAddress & 3) != 0) + throw SubmissionScheduler.Fatal($"A task-launched mesh draw's arguments are not dword aligned: 0x{request.ArgumentsAddress:X16}."); + var arguments = RetainMeshInput(request.ArgumentsAddress, 16); + try + { + var draw = new TaskLaunchedMesh(this, arguments, request.ArgumentsAddress); + if (arguments.Buffer.HasDeviceAddress) + { + draw.SetAddress(arguments.Buffer.DeviceAddress + arguments.Offset); + } + else if (arguments.Buffer.Mapped.Length >= checked((int)arguments.Offset) + 16) + { + draw.SetInline(arguments.Buffer.Mapped.Slice((int)arguments.Offset, 16)); + } + else + { + throw SubmissionScheduler.Fatal("A task-launched mesh draw's arguments have neither a device address nor host memory."); + } + + return draw; + } + catch + { + arguments.Dispose(); + throw; + } + } + + // The task stage leaves out a draw over the device group limits and clamps a range past the vertices, as the + // conversion does. It reports neither: the host never reads a word the GPU may still write, and the draw records + // inside the rendering, where no barrier to the host can follow it (push words 2-3 stay 0). With meshtask listed + // the conversion runs and reports them. + private sealed class TaskLaunchedMesh(RecordingHost owner, RetainedMeshInput arguments, ulong argumentsAddress) + : IIndirectMeshDraw + { + private readonly uint[] _words = new uint[SharpEmu.ShaderCompiler.Vulkan.SpirvMeshTask.PushWordCount]; + private bool _drawn; + private bool _disposed; + + // The mesh program reads its parameters from the task payload. + public ulong ParametersAddress => 0; + + public void SetAddress(ulong address) + { + _words[0] = (uint)address; + _words[1] = (uint)(address >> 32); + } + + public void SetInline(ReadOnlySpan arguments) + { + for (var index = 0; index < 4; index++) + _words[4 + index] = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(arguments[(index * 4)..]); + } + + // Nothing to record before the pass. + public void Prepare() + { + if (_drawn || _disposed) throw new InvalidOperationException("The task-launched mesh draw is not available."); + } + + public void Draw() + { + using var profileScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.DrawRecording); + if (_drawn || _disposed || owner._boundGraphicsPipeline is not { } pipeline) + throw SubmissionScheduler.Fatal("The task-launched mesh draw has no bound pipeline."); + if (owner._presenter._cmdDrawMeshTasks is null) + throw SubmissionScheduler.Fatal("The Vulkan device has no mesh shader draw command."); + var command = owner.BeginBatchedGuestCommands(); + owner._gpuCommandProfile?.WriteMarker(command, VulkanCommandProfile.IntervalKind.Preparation); + fixed (uint* words = _words) + { + owner._vk.CmdPushConstants(command, pipeline.Layout, ShaderStageFlags.TaskBitExt, + SharpEmu.ShaderCompiler.Vulkan.SpirvMeshTask.PushOffsetBytes, + SharpEmu.ShaderCompiler.Vulkan.SpirvMeshTask.PushWordCount * 4u, words); + } + + owner._presenter._cmdDrawMeshTasks(command, 1, 1, 1); + _drawn = true; + // The arguments' buffer stays retained until the GPU has read them. + owner._scheduler.QueueCompletionAction(arguments.Dispose); + owner._presenter._occlusionQueries?.TraceDraw(); + if (MeshDrawTrace.Active) MeshDrawTrace.RecordedCommand((ulong)command.Handle); + owner._gpuCommandProfile?.WriteMarker(command, VulkanCommandProfile.IntervalKind.MeshDraw, + pipeline.Id, 1, 1, 1, + owner._profileMeshDrawState with { Width = owner._renderingState.Width, Height = owner._renderingState.Height }); + owner.CountDraw(); + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + if (!_drawn) arguments.Dispose(); + } + + public override string ToString() => $"task-launched mesh draw arguments=0x{argumentsAddress:X16}"; + } + private RetainedMeshInput RetainMeshInput(ulong address, ulong size) { var (buffer, offset) = _bufferCache.ObtainBuffer(address, size, false); @@ -65,10 +182,14 @@ private sealed class RetainedMeshInput : IDisposable private GpuBuffer? _buffer; private readonly IDisposable? _stream; public BufferBinding Binding { get; } + public GpuBuffer Buffer { get; } + public ulong Offset { get; } public RetainedMeshInput(GpuBuffer buffer, ulong offset) { _buffer = buffer; + Buffer = buffer; + Offset = offset; Binding = new BufferBinding(buffer.Handle.Handle, offset); _stream = (buffer as GpuRingBuffer)?.RetainContents(); buffer.RetainForeignRead(); @@ -84,7 +205,7 @@ public void Dispose() } private sealed class PreparedIndirectMesh(RecordingHost owner, MeshIndirectPipeline.PreparedDraw resources, - RetainedMeshInput arguments, RetainedMeshInput indices, ulong argumentsAddress, uint capacity) : IIndirectMeshDraw + RetainedMeshInput arguments, RetainedMeshInput? indices, ulong argumentsAddress, uint capacity) : IIndirectMeshDraw { private bool _recorded; private bool _disposed; @@ -103,9 +224,15 @@ public void Prepare() uint status; try { status = resources.ReadStatus(); } finally { ReleaseResources(); } - // The CPU path also rejects draws over the device group limits. + // The preparation launched no groups for a draw over the device group limits; the CPU path leaves such + // a draw out too. if (status == 2) - throw SubmissionScheduler.Fatal("The indirect mesh draw exceeds device group limits."); + { + var left = Interlocked.Increment(ref _overLimitDraws); + if ((left & (left - 1)) == 0) + Console.Error.WriteLine($"[GPU][WARN] An indirect mesh draw over the device group limits was left out ({left} so far): " + + $"arguments=0x{argumentsAddress:X16} capacity={capacity}."); + } if (status == 1 && Interlocked.Exchange(ref _clampWarned, 1) == 0) Console.Error.WriteLine($"[GPU][WARN] An indirect mesh draw read past its index range; the extra indices were dropped: " + $"arguments=0x{argumentsAddress:X16} capacity={capacity}."); @@ -140,7 +267,7 @@ public void Dispose() private void ReleaseResources() { resources.Dispose(); - indices.Dispose(); + indices?.Dispose(); arguments.Dispose(); } } diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.PipelineBinaries.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.PipelineBinaries.cs new file mode 100644 index 000000000..a4cd81327 --- /dev/null +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.PipelineBinaries.cs @@ -0,0 +1,543 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Libs.VideoOut; + +using System.Buffers; +using System.Buffers.Binary; +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Security.Cryptography; +using System.Text; +using SharpEmu.Libs.Gpu.Pipelines; +using Silk.NET.Vulkan; +using Silk.NET.Vulkan.Extensions.KHR; + +internal static unsafe partial class VulkanVideoPresenter +{ + private sealed partial class Presenter + { + // Pipelines that take time to build are kept as pipeline binaries (VK_KHR_pipeline_binary), one file per driver + // pipeline key. The driver's own shader cache does not keep them: a pipeline that captures its data is built + // without a pipeline cache, and NVIDIA's cache has a size limit besides (1 GiB for every Vulkan and OpenGL program + // together, storing nothing once it is full). A pipeline whose key has a file is created from its binaries without + // compiling. A build that takes the store threshold or longer (PipelineBinaryStorePolicy, 20 ms by default) writes + // its file at once, since a forced close saves nothing. + // NVIDIA compresses the binaries with the dictionary of the executable's own shader cache file and adds that 2 MiB + // dictionary to every graphics pipeline's binaries, so large binaries are kept once, by content, in the shared + // folder. Once the driver starts a new cache file (a new dictionary), it refuses the old files: those pipelines + // build and write their files again. A pipeline created from binaries or capturing them is created without a + // pipeline cache, as Vulkan requires. SHARPEMU_VK_PIPELINE_BINARIES=0 or SHARPEMU_VK_PIPELINE_CACHE=0 turns this off. + private const string PipelineBinaryExtensionName = "VK_KHR_pipeline_binary"; + private const int MaxPipelineBinaryRefusalReports = 8; + private const int MaxPipelineBinariesPerFile = 16; + + // The data size written for a binary kept in the shared folder; its SHA-256 follows. + private const int SharedPipelineBinaryMarker = -1; + private KhrPipelineBinary? _pipelineBinaries; + private string? _pipelineBinaryDirectory; + private string _pipelineBinaryGlobalKey = ""; + private int _pipelineBinaryRefusals; + private int _pipelineBinaryLoads; + private int _pipelineBinaryStores; + private readonly ConcurrentDictionary _sharedPipelineBinaries = new(); + private readonly PipelineBuildGate _pipelineBuilds = new(); + + // A build at least this long stores its binaries (PipelineBinaryStorePolicy: SHARPEMU_PIPELINE_BINARY_MS, default + // 20 ms), and a binary at least this large is shared (tests lower both). + private double _pipelineBinarySlowMilliseconds = PipelineBinaryStorePolicy.Milliseconds; + private int _sharedPipelineBinaryBytes = 1 << 20; + + private static bool PipelineBinariesRequested() => + Environment.GetEnvironmentVariable("SHARPEMU_VK_PIPELINE_CACHE") != "0" && + Environment.GetEnvironmentVariable("SHARPEMU_VK_PIPELINE_BINARIES") != "0"; + + // Once the device exists: the files go beside the pipeline cache path, under the driver's global key, which a + // driver change replaces. + private void InitializePipelineBinaries(string directory) + { + if (!_vk.TryGetDeviceExtension(_instance, _device, out KhrPipelineBinary binaries)) + { + Console.Error.WriteLine("[LOADER][WARN] Vulkan pipeline binaries unavailable: the extension did not load."); + return; + } + + var globalKey = new PipelineBinaryKeyKHR { SType = StructureType.PipelineBinaryKeyKhr }; + var result = binaries.GetPipelineKey(_device, null, &globalKey); + if (result != Result.Success || globalKey.KeySize == 0) + { + Console.Error.WriteLine($"[LOADER][WARN] Vulkan pipeline binaries unavailable: global key result={result}"); + return; + } + + _pipelineBinaries = binaries; + _pipelineBinaryDirectory = directory; + _pipelineBinaryGlobalKey = Convert.ToHexString(new ReadOnlySpan(globalKey.Key, (int)globalKey.KeySize)); + Console.Error.WriteLine( + $"[LOADER][INFO] Vulkan pipeline binaries ready: directory={directory} store_ms={_pipelineBinarySlowMilliseconds}"); + } + + // The first line of a pipeline's file: the format, the driver's global key and the pipeline key. + private string PipelineBinarySignature(byte[] key) => $"SharpEmuPB2:{_pipelineBinaryGlobalKey}:{Convert.ToHexString(key)}\n"; + + private static Result CreateGraphicsPipelineCall(Vk vk, Device device, PipelineCache cache, void* info, Pipeline* pipeline) => + vk.CreateGraphicsPipelines(device, cache, 1, (GraphicsPipelineCreateInfo*)info, null, pipeline); + + private static Result CreateComputePipelineCall(Vk vk, Device device, PipelineCache cache, void* info, Pipeline* pipeline) => + vk.CreateComputePipelines(device, cache, 1, (ComputePipelineCreateInfo*)info, null, pipeline); + + // Creates a pipeline from the binaries stored under its driver key, else builds it (capturing its data while + // binaries are on) and stores the binaries of a slow build. next is the create info's pNext field. cache is used + // only by a build that neither uses nor captures binaries (VUIDs pNext-09616 and pNext-09617). Safe on compile + // workers: it reads only state that device setup wrote. One thread at a time creates a key (PipelineBuildGate), so + // milliseconds includes any wait for another thread's build of it. + private Result CreatePipelineWithBinaries( + void* createInfo, + void** next, + PipelineCache cache, + delegate* create, + out Pipeline pipeline, + out double milliseconds, + PipelineCreateFlags2 extraFlags = 0) + { + var started = Stopwatch.GetTimestamp(); + var key = PipelineBinaryKey(createInfo); + var build = key is null ? null : _pipelineBuilds.Begin(Convert.ToHexString(key)); + try + { + var result = LoadOrBuildPipeline(createInfo, next, cache, create, key, out pipeline, extraFlags); + milliseconds = Stopwatch.GetElapsedTime(started).TotalMilliseconds; + return result; + } + finally + { + if (build is not null) + { + _pipelineBuilds.Finish(build); + } + } + } + + private Result LoadOrBuildPipeline( + void* createInfo, + void** next, + PipelineCache cache, + delegate* create, + byte[]? key, + out Pipeline pipeline, + PipelineCreateFlags2 extraFlags) + { + var started = Stopwatch.GetTimestamp(); + var original = *next; + Pipeline created = default; + Result result; + if (key is not null && LoadPipelineBinaries(key) is { } loaded) + { + fixed (PipelineBinaryKHR* handles = loaded) + { + var binaryInfo = new PipelineBinaryInfoKHR + { + SType = StructureType.PipelineBinaryInfoKhr, + PNext = original, + BinaryCount = (uint)loaded.Length, + PPipelineBinaries = handles, + }; + *next = &binaryInfo; + result = create(_vk, _device, default, createInfo, &created); + *next = original; + } + + foreach (var handle in loaded) + { + _pipelineBinaries!.DestroyPipelineBinary(_device, handle, null); + } + + if (result == Result.Success) + { + ReportPipelineBinaryCount("loaded", Interlocked.Increment(ref _pipelineBinaryLoads)); + pipeline = created; + return result; + } + + ReportPipelineBinaryRefusal("create", key, result); + } + + var capture = new PipelineCreateFlags2CreateInfoKHR + { + SType = StructureType.PipelineCreateFlags2CreateInfoKhr, + PNext = original, + Flags = PipelineCreateFlags2.Vk2CaptureDataBitKhr | extraFlags, + }; + if (key is not null) + { + *next = &capture; + } + + result = create(_vk, _device, key is not null ? default : cache, createInfo, &created); + *next = original; + if (key is not null && result == Result.Success) + { + if (Stopwatch.GetElapsedTime(started).TotalMilliseconds >= _pipelineBinarySlowMilliseconds) + { + StorePipelineBinaries(created, key); + } + + var release = new ReleaseCapturedPipelineDataInfoKHR + { + SType = StructureType.ReleaseCapturedPipelineDataInfoKhr, + Pipeline = created, + }; + _pipelineBinaries!.ReleaseCapturedPipelineData(_device, &release, null); + } + + pipeline = created; + return result; + } + + // The driver's key for a create info and its pNext chain; null while binaries are off. + private byte[]? PipelineBinaryKey(void* createInfo) + { + if (_pipelineBinaries is not { } binaries || _pipelineBinaryDirectory is null) + { + return null; + } + + var info = new PipelineCreateInfoKHR { SType = StructureType.PipelineCreateInfoKhr, PNext = createInfo }; + var key = new PipelineBinaryKeyKHR { SType = StructureType.PipelineBinaryKeyKhr }; + return binaries.GetPipelineKey(_device, &info, &key) == Result.Success && key.KeySize != 0 + ? new ReadOnlySpan(key.Key, (int)key.KeySize).ToArray() + : null; + } + + private string PipelineBinaryPath(byte[] key) => Path.Combine(_pipelineBinaryDirectory!, Convert.ToHexString(key) + ".bin"); + + // A pipeline's file is PipelineCacheSignature.Wrap of its signature and a payload: the binary count, then for each + // binary its key size, key, data size and data, or SharedPipelineBinaryMarker and the SHA-256 of a binary in the + // shared folder. A file of another format, driver or pipeline key is not read; a damaged one is refused. + private PipelineBinaryKHR[]? LoadPipelineBinaries(byte[] key) + { + byte[] file; + try + { + var path = PipelineBinaryPath(key); + if (!File.Exists(path)) + { + return null; + } + + file = File.ReadAllBytes(path); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return null; + } + + var signature = PipelineBinarySignature(key); + if (!file.AsSpan().StartsWith(Encoding.ASCII.GetBytes(signature))) + { + return null; + } + + if (!PipelineCacheSignature.TryUnwrap(signature, file, out var payload)) + { + return Refused("hash"); + } + + var offset = 0; + if (!TryReadInt32(payload, ref offset, out var count) || count is <= 0 or > MaxPipelineBinariesPerFile) + { + return Refused("parse"); + } + + var keyArray = new PipelineBinaryKeyKHR[count]; + var parts = new ReadOnlyMemory[count]; + for (var index = 0; index < count; index++) + { + if (!TryReadInt32(payload, ref offset, out var keyLength) || keyLength is <= 0 or > 32 || + keyLength > payload.Length - offset) + { + return Refused("parse"); + } + + var binaryKey = new PipelineBinaryKeyKHR { SType = StructureType.PipelineBinaryKeyKhr, KeySize = (uint)keyLength }; + payload.AsSpan(offset, keyLength).CopyTo(new Span(binaryKey.Key, keyLength)); + keyArray[index] = binaryKey; + offset += keyLength; + if (!TryReadInt32(payload, ref offset, out var dataLength)) + { + return Refused("parse"); + } + + if (dataLength == SharedPipelineBinaryMarker) + { + if (SHA256.HashSizeInBytes > payload.Length - offset || + LoadSharedPipelineBinary(payload.AsSpan(offset, SHA256.HashSizeInBytes)) is not { } shared) + { + return Refused("shared"); + } + + parts[index] = shared; + offset += SHA256.HashSizeInBytes; + } + else if (dataLength > 0 && dataLength <= payload.Length - offset) + { + parts[index] = payload.AsMemory(offset, dataLength); + offset += dataLength; + } + else + { + return Refused("parse"); + } + } + + if (offset != payload.Length) + { + return Refused("parse"); + } + + var handles = new PipelineBinaryKHR[count]; + var pins = new MemoryHandle[count]; + Result result; + try + { + fixed (PipelineBinaryKeyKHR* keyPointer = keyArray) + fixed (PipelineBinaryKHR* handlePointer = handles) + { + var dataArray = stackalloc PipelineBinaryDataKHR[count]; + for (var index = 0; index < count; index++) + { + pins[index] = parts[index].Pin(); + dataArray[index] = new PipelineBinaryDataKHR + { + DataSize = (nuint)parts[index].Length, + PData = pins[index].Pointer, + }; + } + + var keysAndData = new PipelineBinaryKeysAndDataKHR + { + BinaryCount = (uint)keyArray.Length, + PPipelineBinaryKeys = keyPointer, + PPipelineBinaryData = dataArray, + }; + var createInfo = new PipelineBinaryCreateInfoKHR + { + SType = StructureType.PipelineBinaryCreateInfoKhr, + PKeysAndDataInfo = &keysAndData, + }; + var handleInfo = new PipelineBinaryHandlesInfoKHR + { + SType = StructureType.PipelineBinaryHandlesInfoKhr, + PipelineBinaryCount = (uint)handles.Length, + PPipelineBinaries = handlePointer, + }; + result = _pipelineBinaries!.CreatePipelineBinaries(_device, &createInfo, null, &handleInfo); + } + } + finally + { + foreach (var pin in pins) + { + pin.Dispose(); + } + } + + if (result == Result.Success) + { + return handles; + } + + foreach (var handle in handles) + { + if (handle.Handle != 0) + { + _pipelineBinaries!.DestroyPipelineBinary(_device, handle, null); + } + } + + return Refused(result.ToString()); + + PipelineBinaryKHR[]? Refused(string reason) + { + ReportPipelineBinaryRefusal(reason, key, result: null); + return null; + } + } + + private static bool TryReadInt32(byte[] data, ref int offset, out int value) + { + value = 0; + if (offset < 0 || sizeof(int) > data.Length - offset) + { + return false; + } + + value = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(offset)); + offset += sizeof(int); + return true; + } + + // Writes the binaries of a pipeline created with captured data to its key's file. + private void StorePipelineBinaries(Pipeline pipeline, byte[] key) + { + var binaries = _pipelineBinaries!; + var createInfo = new PipelineBinaryCreateInfoKHR { SType = StructureType.PipelineBinaryCreateInfoKhr, Pipeline = pipeline }; + var handleInfo = new PipelineBinaryHandlesInfoKHR { SType = StructureType.PipelineBinaryHandlesInfoKhr }; + var result = binaries.CreatePipelineBinaries(_device, &createInfo, null, &handleInfo); + if (result != Result.Success || handleInfo.PipelineBinaryCount is 0 or > MaxPipelineBinariesPerFile) + { + ReportPipelineBinaryRefusal("capture", key, result); + return; + } + + var handles = new PipelineBinaryKHR[handleInfo.PipelineBinaryCount]; + try + { + fixed (PipelineBinaryKHR* handlePointer = handles) + { + handleInfo.PPipelineBinaries = handlePointer; + result = binaries.CreatePipelineBinaries(_device, &createInfo, null, &handleInfo); + } + + if (result != Result.Success) + { + ReportPipelineBinaryRefusal("capture", key, result); + return; + } + + using var stream = new MemoryStream(); + stream.Write(BitConverter.GetBytes(handles.Length)); + foreach (var handle in handles) + { + var dataInfo = new PipelineBinaryDataInfoKHR { SType = StructureType.PipelineBinaryDataInfoKhr, PipelineBinary = handle }; + var binaryKey = new PipelineBinaryKeyKHR { SType = StructureType.PipelineBinaryKeyKhr }; + nuint size = 0; + result = binaries.GetPipelineBinaryData(_device, &dataInfo, &binaryKey, &size, null); + if (result != Result.Success || size == 0) + { + ReportPipelineBinaryRefusal("data", key, result); + return; + } + + var data = new byte[checked((int)size)]; + fixed (byte* dataPointer = data) + { + result = binaries.GetPipelineBinaryData(_device, &dataInfo, &binaryKey, &size, dataPointer); + } + + if (result != Result.Success) + { + ReportPipelineBinaryRefusal("data", key, result); + return; + } + + stream.Write(BitConverter.GetBytes((int)binaryKey.KeySize)); + stream.Write(new ReadOnlySpan(binaryKey.Key, (int)binaryKey.KeySize)); + if (data.Length >= _sharedPipelineBinaryBytes) + { + stream.Write(BitConverter.GetBytes(SharedPipelineBinaryMarker)); + stream.Write(StoreSharedPipelineBinary(data)); + } + else + { + stream.Write(BitConverter.GetBytes(data.Length)); + stream.Write(data); + } + } + + WriteFileAtomically(PipelineBinaryPath(key), PipelineCacheSignature.Wrap(PipelineBinarySignature(key), stream.ToArray())); + ReportPipelineBinaryCount("stored", Interlocked.Increment(ref _pipelineBinaryStores)); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + Console.Error.WriteLine($"[LOADER][WARN] Vulkan pipeline binaries not saved: {exception.Message}"); + } + finally + { + foreach (var handle in handles) + { + if (handle.Handle != 0) + { + binaries.DestroyPipelineBinary(_device, handle, null); + } + } + } + } + + private string SharedPipelineBinaryPath(ReadOnlySpan hash) => + Path.Combine(_pipelineBinaryDirectory!, "shared", Convert.ToHexString(hash) + ".bin"); + + // Writes a shared binary unless its file is there with the same contents; returns its SHA-256. + private byte[] StoreSharedPipelineBinary(byte[] data) + { + var hash = SHA256.HashData(data); + if (LoadSharedPipelineBinary(hash) is null) + { + WriteFileAtomically(SharedPipelineBinaryPath(hash), data); + _sharedPipelineBinaries.TryAdd(Convert.ToHexString(hash), data); + } + + return hash; + } + + // A shared binary whose contents still match its hash; null when it is missing or changed. + private byte[]? LoadSharedPipelineBinary(ReadOnlySpan hash) + { + var name = Convert.ToHexString(hash); + if (_sharedPipelineBinaries.TryGetValue(name, out var known)) + { + return known; + } + + byte[] data; + try + { + var path = SharedPipelineBinaryPath(hash); + if (!File.Exists(path)) + { + return null; + } + + data = File.ReadAllBytes(path); + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + return null; + } + + if (!SHA256.HashData(data).AsSpan().SequenceEqual(hash)) + { + return null; + } + + _sharedPipelineBinaries.TryAdd(name, data); + return data; + } + + private static void WriteFileAtomically(string path, byte[] contents) + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + var temporaryPath = path + $".{Environment.ProcessId}.{Environment.CurrentManagedThreadId}.tmp"; + File.WriteAllBytes(temporaryPath, contents); + File.Move(temporaryPath, path, overwrite: true); + } + + // Logs at counts 1, 2, 4, 8, ... + private static void ReportPipelineBinaryCount(string what, int count) + { + if ((count & (count - 1)) == 0) + { + Console.Error.WriteLine($"[LOADER][INFO] Vulkan pipeline binaries {what}: {count}"); + } + } + + private void ReportPipelineBinaryRefusal(string stage, byte[] key, Result? result) + { + if (Interlocked.Increment(ref _pipelineBinaryRefusals) <= MaxPipelineBinaryRefusalReports) + { + Console.Error.WriteLine( + $"[LOADER][WARN] Vulkan pipeline binaries refused: stage={stage} key={Convert.ToHexString(key)} result={result}"); + } + } + } +} diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.PipelineLibraries.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.PipelineLibraries.cs new file mode 100644 index 000000000..aed6e4766 --- /dev/null +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.PipelineLibraries.cs @@ -0,0 +1,924 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.Diagnostics; +using System.Text; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Silk.NET.Core.Native; +using Silk.NET.Vulkan; + +namespace SharpEmu.Libs.VideoOut; + +// Graphics pipeline libraries (VK_EXT_graphics_pipeline_library). A graphics pipeline compiles its vertex and pixel programs +// together, so a program that many pipelines share (a material vertex shader paired with each material's pixel shader, or +// a pixel shader drawn into other targets) is compiled again for each of them. With libraries each part compiles once: +// the vertex input, the vertex or mesh stage with its rasterization state, the pixel stage, and the color outputs. A +// pipeline links its parts without optimizing across them. +// Parts link only through layouts with independent sets: the vertex stage's bindings are set 0 and the pixel stage's set 2 +// (PixelDescriptorSet: each pixel module's set-0 variables move there), the bindless heap stays set 1. The vertex set is +// pushed when it fits, the pixel set is allocated, so each set's layout depends on its own stage alone. The heap set is in +// every part's layout, read by its stage or not: its bindings are visible to every graphics stage, and parts with +// independent sets may leave out only a set none of the other part's stages can see. +// Every depth and stencil state is dynamic (BaseDynamicStates), so the pixel stage's part depends on the pixel program +// alone. It starts compiling on a worker as soon as the program is translated (PixelProgramCreated), usually before the +// draw that needs it, and the programs a scene brings at once compile side by side instead of one draw after another. +// SHARPEMU_GRAPHICS_PIPELINE_LIBRARY=0 keeps whole pipelines with one set; SHARPEMU_EARLY_PIXEL_LIBRARIES=0 compiles each +// part when a pipeline first needs it. +internal static unsafe partial class VulkanVideoPresenter +{ + private sealed partial class Presenter + { + internal const uint PixelDescriptorSet = 2; + private const uint DescriptorSetDecoration = 34; + private const string PipelineLibraryExtensionName = "VK_KHR_pipeline_library"; + private const string GraphicsPipelineLibraryExtensionName = "VK_EXT_graphics_pipeline_library"; + + private static bool GraphicsPipelineLibrariesRequested() => + Environment.GetEnvironmentVariable("SHARPEMU_GRAPHICS_PIPELINE_LIBRARY") != "0"; + + private static readonly bool _earlyPixelLibraries = + Environment.GetEnvironmentVariable("SHARPEMU_EARLY_PIXEL_LIBRARIES") != "0"; + + // Device setup sets this when the device links libraries fast. + private bool _graphicsPipelineLibraries; + + // The compiled parts by the state each holds, and the parts a thread is compiling now, both under + // _graphicsLibraryLock: pipeline workers and early pixel compiles share them with the command stream. The parts + // are destroyed with the pipelines. + private readonly object _graphicsLibraryLock = new(); + private readonly Dictionary _graphicsLibraries = new(StringComparer.Ordinal); + private readonly Dictionary> _graphicsLibraryCompiles = new(StringComparer.Ordinal); + + // The early pixel compiles not yet waited for; teardown waits for them before the modules go. + private readonly List _earlyPixelLibraryTasks = new(); + + private static readonly SemaphoreSlim _pixelLibrarySlots = new(Math.Max(2, Environment.ProcessorCount / 2)); + + // The states every guest graphics pipeline takes from the draw (SetDynamicState), in this order. + private DynamicState[]? _baseDynamicStates; + + // Tests: told the set layouts 0, 1 and 2 of each layout CreateLibraryPipelineLayout makes. + internal Action? LibraryLayoutCreatedForTest; + + private DynamicState[] BaseDynamicStates => _baseDynamicStates ??= BuildBaseDynamicStates(); + + private DynamicState[] BuildBaseDynamicStates() + { + var states = new List + { + DynamicState.Viewport, + DynamicState.Scissor, + DynamicState.LineWidth, + DynamicState.DepthTestEnableExt, + DynamicState.DepthWriteEnableExt, + DynamicState.DepthCompareOpExt, + DynamicState.DepthBiasEnableExt, + DynamicState.DepthBias, + DynamicState.StencilCompareMask, + DynamicState.StencilReference, + DynamicState.StencilWriteMask, + DynamicState.BlendConstants, + DynamicState.StencilTestEnableExt, + DynamicState.StencilOpExt, + }; + if (_supportsDepthBounds) + { + states.Add(DynamicState.DepthBoundsTestEnableExt); + states.Add(DynamicState.DepthBounds); + } + + return states.ToArray(); + } + + // The push constant stages of every linked pipeline and part. Linked parts need equal ranges, so vertex and mesh + // pipelines share them. + internal ShaderStageFlags LibraryPushStages => + ShaderStageFlags.VertexBit | ShaderStageFlags.FragmentBit | (_supportsMeshShader ? ShaderStageFlags.MeshBitExt : 0); + + // A copy of a SPIR-V module whose descriptor set `from` decorations name set `to`. + internal static byte[] WithDescriptorSet(byte[] code, uint from, uint to) + { + var copy = (byte[])code.Clone(); + for (var offset = 20; offset + 4 <= copy.Length;) + { + var header = BinaryPrimitives.ReadUInt32LittleEndian(copy.AsSpan(offset)); + var wordCount = (int)(header >> 16); + if (wordCount == 0 || wordCount > (copy.Length - offset) / 4) + { + throw new InvalidOperationException("The shader contains an invalid SPIR-V instruction."); + } + + if ((header & 0xFFFF) == (uint)SpirvOp.Decorate && wordCount == 4 && + BinaryPrimitives.ReadUInt32LittleEndian(copy.AsSpan(offset + 8)) == DescriptorSetDecoration && + BinaryPrimitives.ReadUInt32LittleEndian(copy.AsSpan(offset + 12)) == from) + { + BinaryPrimitives.WriteUInt32LittleEndian(copy.AsSpan(offset + 12), to); + } + + offset += wordCount * 4; + } + + return copy; + } + + private RenderPipelineEntry CreateLibraryPipelineEntry(GraphicsPipelineDescription description) + { + var vertexBindings = new List(); + CollectVertexStageBindings(vertexBindings, description); + var pixelBindings = new List(); + if (description.PixelStage is { } pixelStage) + { + CollectLayoutBindings(pixelBindings, pixelStage, ShaderStage.Pixel); + } + + DescriptorSetLayout vertexSet = default; + DescriptorSetDemand vertexDemand = default; + var vertexPush = false; + if (vertexBindings.Count != 0) + { + vertexSet = CreateDescriptorSetLayout(vertexBindings, allowPush: true, out vertexPush, out vertexDemand); + } + + DescriptorSetLayout pixelSet = default; + DescriptorSetDemand pixelDemand = default; + if (pixelBindings.Count != 0) + { + pixelSet = CreateDescriptorSetLayout(pixelBindings, allowPush: false, out _, out pixelDemand); + } + + var heap = UsesBindlessHeap(description.VertexStage) || (description.PixelStage is { } heapStage && UsesBindlessHeap(heapStage)); + return new RenderPipelineEntry + { + SetLayout = vertexSet, + Demand = vertexDemand, + UsesPushDescriptors = vertexPush, + PixelSetLayout = pixelSet, + PixelDemand = pixelDemand, + LinkedFromLibraries = true, + VertexSetSignature = SetSignature(vertexBindings, vertexPush), + PixelSetSignature = SetSignature(pixelBindings, push: false), + Layout = CreateLibraryPipelineLayout(vertexSet, pixelSet), + UsesBindlessHeap = heap, + Description = description, + ProfileVertexHash = description.VertexStage.Hash, + ProfilePixelHash = description.PixelStage?.Hash ?? 0, + }; + } + + private static string SetSignature(List bindings, bool push) + { + var builder = new StringBuilder(push ? "p" : "a"); + foreach (var binding in bindings) + { + builder.Append(';').Append(binding.Binding).Append(',').Append((int)binding.DescriptorType).Append(',') + .Append(binding.DescriptorCount).Append(',').Append((int)binding.StageFlags); + } + + return builder.ToString(); + } + + // The layout of a linked pipeline or of one part of it: sets 0 (vertex) and 2 (pixel), each null where the pipeline or + // part has none, the bindless heap's set 1 whenever the device has the heap, and one push constant range for every + // stage. + private PipelineLayout CreateLibraryPipelineLayout(DescriptorSetLayout vertexSet, DescriptorSetLayout pixelSet) + { + // Linked parts need equal ranges: with task launches on, every part carries the task range too. + var pushRanges = stackalloc PushConstantRange[2]; + pushRanges[0] = new PushConstantRange + { + StageFlags = LibraryPushStages, + Offset = 0, + Size = PushConstantBytes, + }; + var pushRangeCount = 1u; + if (_supportsTaskShader) + { + pushRanges[pushRangeCount++] = TaskPushRange; + } + var setLayouts = stackalloc DescriptorSetLayout[3]; + setLayouts[0] = vertexSet; + setLayouts[1] = _heapSetLayout; + setLayouts[2] = pixelSet; + var create = new PipelineLayoutCreateInfo + { + SType = StructureType.PipelineLayoutCreateInfo, + Flags = PipelineLayoutCreateFlags.IndependentSetsBitExt, + SetLayoutCount = 3, + PSetLayouts = setLayouts, + PushConstantRangeCount = pushRangeCount, + PPushConstantRanges = pushRanges, + }; + Check(_vk.CreatePipelineLayout(_device, &create, null, out var layout), "vkCreatePipelineLayout(independent sets)"); + LibraryLayoutCreatedForTest?.Invoke(setLayouts[0], setLayouts[1], setLayouts[2]); + return layout; + } + + // Links the pipeline from its parts when its entry is laid out for them, else builds it whole, as when a part fails. + // A tessellated pipeline links too: its pre-rasterization part holds the control and evaluation stages, so its pixel + // part, often the largest, is the one the prewarm or an earlier pipeline compiled. + private Result LinkOrBuildGraphicsPipeline(RenderPipelineEntry? libraries, GraphicsPipelineDescription description, + bool expandRectangles, GraphicsPipelineCreateInfo* info, PipelineDynamicStateCreateInfo* baseDynamicState, + PipelineCache cache, out Pipeline pipeline, out double milliseconds) + { + if (libraries is { LinkedFromLibraries: true } && !expandRectangles && + CreateLinkedGraphicsPipeline(libraries, description, info, baseDynamicState, out pipeline, out milliseconds) == Result.Success) + { + return Result.Success; + } + + return CreatePipelineWithBinaries(info, &info->PNext, cache, &CreateGraphicsPipelineCall, out pipeline, + out milliseconds); + } + + // Links a pipeline from its parts, compiling the parts no earlier pipeline compiled. info holds the whole state the + // pipeline would be created with; each part takes its share. A part's dynamic states are the ones that apply to it + // (baseDynamicState: all but color write enable, which only the color outputs take). + private Result CreateLinkedGraphicsPipeline(RenderPipelineEntry entry, GraphicsPipelineDescription description, + GraphicsPipelineCreateInfo* info, PipelineDynamicStateCreateInfo* baseDynamicState, out Pipeline pipeline, + out double milliseconds) + { + var started = Stopwatch.GetTimestamp(); + var mesh = description.VertexStage.Stage == ShaderStageKind.Mesh; + var label = $"vs=0x{description.VertexStage.Hash:X16} ps=0x{description.PixelStage?.Hash ?? 0:X16}"; + var vertexInputKey = mesh ? null : VertexInputKey(info, baseDynamicState); + var preRasterizationKey = PreRasterizationKey(entry, info, baseDynamicState); + var pixelIndex = StageIndex(info, ShaderStageFlags.FragmentBit); + var pixelModule = pixelIndex >= 0 ? info->PStages[pixelIndex].Module.Handle : 0; + var fragmentKey = FragmentKey(pixelModule, entry.PixelSetSignature, info->PMultisampleState, baseDynamicState); + var outputKey = OutputKey(info); + var parts = stackalloc Pipeline[4]; + var count = 0u; + if (vertexInputKey is not null) + { + parts[count++] = GraphicsLibrary(vertexInputKey, GraphicsPipelineLibraryFlagsEXT.VertexInputInterfaceBitExt, + info, baseDynamicState, entry, label); + } + + parts[count++] = GraphicsLibrary(preRasterizationKey, GraphicsPipelineLibraryFlagsEXT.PreRasterizationShadersBitExt, + info, baseDynamicState, entry, label); + parts[count++] = GraphicsLibrary(fragmentKey, GraphicsPipelineLibraryFlagsEXT.FragmentShaderBitExt, info, baseDynamicState, entry, label); + parts[count++] = GraphicsLibrary(outputKey, GraphicsPipelineLibraryFlagsEXT.FragmentOutputInterfaceBitExt, + info, baseDynamicState, entry, label); + for (var index = 0; index < count; index++) + { + if (parts[index].Handle == 0) + { + pipeline = default; + milliseconds = Stopwatch.GetElapsedTime(started).TotalMilliseconds; + return Result.ErrorInitializationFailed; + } + } + + var libraries = new PipelineLibraryCreateInfoKHR + { + SType = StructureType.PipelineLibraryCreateInfoKhr, + LibraryCount = count, + PLibraries = parts, + }; + var link = new GraphicsPipelineCreateInfo + { + SType = StructureType.GraphicsPipelineCreateInfo, + PNext = &libraries, + Layout = entry.Layout, + }; + Pipeline linked; + var result = _vk.CreateGraphicsPipelines(_device, default, 1, &link, null, &linked); + pipeline = linked; + milliseconds = Stopwatch.GetElapsedTime(started).TotalMilliseconds; + return result; + } + + // The part for key from the pipeline state in info: compiled by this thread unless it is compiled already or another + // thread compiles it now. A part that fails is not kept; its pipeline is built whole. + private Pipeline GraphicsLibrary(string key, GraphicsPipelineLibraryFlagsEXT part, GraphicsPipelineCreateInfo* info, + PipelineDynamicStateCreateInfo* baseDynamicState, RenderPipelineEntry entry, string label) + { + if (TryTakeGraphicsLibrary(key, out var library, out var compile)) + { + return library; + } + + var created = default(Pipeline); + try + { + var partInfo = new GraphicsPipelineLibraryCreateInfoEXT + { + SType = StructureType.GraphicsPipelineLibraryCreateInfoExt, + PNext = info->PNext, + Flags = part, + }; + var create = new GraphicsPipelineCreateInfo + { + SType = StructureType.GraphicsPipelineCreateInfo, + PNext = &partInfo, + Flags = PipelineCreateFlags.CreateLibraryBitKhr, + PDynamicState = baseDynamicState, + }; + // Every depth and stencil state is dynamic. + var depthStencil = new PipelineDepthStencilStateCreateInfo { SType = StructureType.PipelineDepthStencilStateCreateInfo }; + PipelineLayout layout = default; + switch (part) + { + case GraphicsPipelineLibraryFlagsEXT.VertexInputInterfaceBitExt: + create.PVertexInputState = info->PVertexInputState; + create.PInputAssemblyState = info->PInputAssemblyState; + break; + case GraphicsPipelineLibraryFlagsEXT.PreRasterizationShadersBitExt: + // Built as the prewarm builds it (CreatePreRasterizationLibrary). + created = CompilePreRasterizationPart(info, entry, label); + return created; + case GraphicsPipelineLibraryFlagsEXT.FragmentShaderBitExt: + var fragmentIndex = StageIndex(info, ShaderStageFlags.FragmentBit); + create.StageCount = fragmentIndex >= 0 ? 1u : 0u; + create.PStages = fragmentIndex >= 0 ? info->PStages + fragmentIndex : null; + create.PMultisampleState = info->PMultisampleState; + create.PDepthStencilState = &depthStencil; + create.Layout = layout = CreateLibraryPipelineLayout(default, entry.PixelSetLayout); + break; + default: + create.PColorBlendState = info->PColorBlendState; + create.PMultisampleState = info->PMultisampleState; + create.PDynamicState = info->PDynamicState; + break; + } + + try + { + created = CompileGraphicsLibrary(&create, part, label); + } + finally + { + if (layout.Handle != 0) + { + _vk.DestroyPipelineLayout(_device, layout, null); + } + } + } + finally + { + FinishGraphicsLibrary(key, compile!, created); + } + + return created; + } + + // The pre-rasterization part of a linked pipeline, from the draw's stage and rasterization state, as the + // graphics prewarm builds it from a recorded state: both compile one create info through the pipeline cache. + private Pipeline CompilePreRasterizationPart(GraphicsPipelineCreateInfo* info, RenderPipelineEntry entry, string label) + { + var state = PreRasterizationStateOf(info); + var taskIndex = StageIndex(info, ShaderStageFlags.TaskBitExt); + var controlIndex = StageIndex(info, ShaderStageFlags.TessellationControlBit); + var evaluationIndex = StageIndex(info, ShaderStageFlags.TessellationEvaluationBit); + var tessellated = controlIndex >= 0 && evaluationIndex >= 0 && info->PTessellationState is not null; + var tessellationStages = stackalloc PipelineShaderStageCreateInfo[2]; + if (tessellated) + { + tessellationStages[0] = info->PStages[controlIndex]; + tessellationStages[1] = info->PStages[evaluationIndex]; + } + + var layout = CreateLibraryPipelineLayout(entry.SetLayout, default); + try + { + var created = CreatePreRasterizationLibrary(info->PStages[0], taskIndex >= 0 ? info->PStages + taskIndex : null, + state, layout, label, tessellated ? tessellationStages : null, tessellated ? info->PTessellationState : null); + // The prewarm records parts of one vertex or mesh stage. + if (created.Handle != 0 && !tessellated) + { + RecordPreRasterization(info->PStages[0].Module.Handle, state); + } + + return created; + } + finally + { + _vk.DestroyPipelineLayout(_device, layout, null); + } + } + + private static PreRasterizationState PreRasterizationStateOf(GraphicsPipelineCreateInfo* info) + { + var raster = info->PRasterizationState; + var viewport = info->PViewportState; + return new PreRasterizationState( + (int)raster->PolygonMode, + (int)raster->CullMode, + (int)raster->FrontFace, + raster->DepthClampEnable, + raster->RasterizerDiscardEnable, + raster->PNext is not null && ((PipelineRasterizationDepthClipStateCreateInfoEXT*)raster->PNext)->DepthClipEnable, + viewport->PNext is not null && ((PipelineViewportDepthClipControlCreateInfoEXT*)viewport->PNext)->NegativeOneToOne); + } + + // A pre-rasterization part from its stage (and a task stage), a rasterization state and its layout. It takes no + // attachment formats, which belong to the color outputs part, so the graphics prewarm builds the same create + // info from a recorded state and one part serves pipelines of any attachments. + private Pipeline CreatePreRasterizationLibrary(PipelineShaderStageCreateInfo stage, PipelineShaderStageCreateInfo* task, + PreRasterizationState state, PipelineLayout layout, string label, + PipelineShaderStageCreateInfo* tessellationStages = null, PipelineTessellationStateCreateInfo* tessellation = null) + { + var stages = stackalloc PipelineShaderStageCreateInfo[4]; + var stageCount = 0u; + stages[stageCount++] = stage; + if (task is not null) + { + stages[stageCount++] = *task; + } + + if (tessellationStages is not null) + { + stages[stageCount++] = tessellationStages[0]; + stages[stageCount++] = tessellationStages[1]; + } + + var clipControl = new PipelineViewportDepthClipControlCreateInfoEXT + { + SType = StructureType.PipelineViewportDepthClipControlCreateInfoExt, + NegativeOneToOne = state.NegativeOneToOne, + }; + var viewport = new PipelineViewportStateCreateInfo + { + SType = StructureType.PipelineViewportStateCreateInfo, + PNext = _supportsDepthClipControl ? &clipControl : null, + ViewportCount = 1, + ScissorCount = 1, + }; + var depthClip = new PipelineRasterizationDepthClipStateCreateInfoEXT + { + SType = StructureType.PipelineRasterizationDepthClipStateCreateInfoExt, + DepthClipEnable = state.DepthClipEnable, + }; + var rasterization = new PipelineRasterizationStateCreateInfo + { + SType = StructureType.PipelineRasterizationStateCreateInfo, + PNext = _supportsDepthClipEnable ? &depthClip : null, + DepthClampEnable = state.DepthClampEnable, + RasterizerDiscardEnable = state.RasterizerDiscardEnable, + PolygonMode = (PolygonMode)state.PolygonMode, + CullMode = (CullModeFlags)state.CullMode, + FrontFace = (FrontFace)state.FrontFace, + LineWidth = 1, + }; + var rendering = new PipelineRenderingCreateInfo { SType = StructureType.PipelineRenderingCreateInfo }; + var states = BaseDynamicStates; + fixed (DynamicState* statePointer = states) + { + var dynamicState = new PipelineDynamicStateCreateInfo + { + SType = StructureType.PipelineDynamicStateCreateInfo, + DynamicStateCount = (uint)states.Length, + PDynamicStates = statePointer, + }; + var partInfo = new GraphicsPipelineLibraryCreateInfoEXT + { + SType = StructureType.GraphicsPipelineLibraryCreateInfoExt, + PNext = &rendering, + Flags = GraphicsPipelineLibraryFlagsEXT.PreRasterizationShadersBitExt, + }; + var create = new GraphicsPipelineCreateInfo + { + SType = StructureType.GraphicsPipelineCreateInfo, + PNext = &partInfo, + Flags = PipelineCreateFlags.CreateLibraryBitKhr, + StageCount = stageCount, + PStages = stages, + PTessellationState = tessellation, + PViewportState = &viewport, + PRasterizationState = &rasterization, + PDynamicState = &dynamicState, + Layout = layout, + }; + return CompileGraphicsLibrary(&create, GraphicsPipelineLibraryFlagsEXT.PreRasterizationShadersBitExt, label); + } + } + + // The vertex or mesh stage of a pipeline or pre-rasterization part; the graphics prewarm builds the same one. + private static PipelineShaderStageCreateInfo VertexStageInfo(bool mesh, ShaderModule module, byte* entryPoint) => new() + { + SType = StructureType.PipelineShaderStageCreateInfo, + Stage = mesh ? ShaderStageFlags.MeshBitExt : ShaderStageFlags.VertexBit, + Flags = mesh ? PipelineShaderStageCreateFlags.RequireFullSubgroupsBit : 0, + Module = module, + PName = entryPoint, + }; + + // True with a compiled part, after waiting while another thread compiles it; false with the completion this + // thread finishes (FinishGraphicsLibrary) once it has compiled the part itself. + private bool TryTakeGraphicsLibrary(string key, out Pipeline library, out TaskCompletionSource? compile) + { + while (true) + { + TaskCompletionSource? running; + lock (_graphicsLibraryLock) + { + if (_graphicsLibraries.TryGetValue(key, out library)) + { + compile = null; + return true; + } + + if (!_graphicsLibraryCompiles.TryGetValue(key, out running)) + { + compile = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _graphicsLibraryCompiles.Add(key, compile); + return false; + } + } + + library = running.Task.GetAwaiter().GetResult(); + if (library.Handle != 0) + { + compile = null; + return true; + } + + // The other thread's compile failed: this thread tries once more itself. + } + } + + private void FinishGraphicsLibrary(string key, TaskCompletionSource compile, Pipeline created) + { + lock (_graphicsLibraryLock) + { + _graphicsLibraryCompiles.Remove(key); + if (created.Handle != 0) + { + _graphicsLibraries.Add(key, created); + } + } + + compile.SetResult(created); + } + + // A part is compiled through the pipeline cache, not from and into pipeline binaries. The vertex input and color + // output parts hold no code: the driver gives them an all-zero pipeline key and no binaries, so on the binary path + // every one of them waited on the same build gate and looked for a binary that is never stored. The parts with code + // reach later pipelines through the cache, which the graphics prewarm fills before the session's draws ask for them. + private Pipeline CompileGraphicsLibrary(GraphicsPipelineCreateInfo* create, GraphicsPipelineLibraryFlagsEXT part, string label) + { + var started = Stopwatch.GetTimestamp(); + var created = default(Pipeline); + var result = _vk.CreateGraphicsPipelines(_device, _pipelineCache, 1, create, null, &created); + var milliseconds = Stopwatch.GetElapsedTime(started).TotalMilliseconds; + if (result == Result.Success) + { + MarkPipelineCacheDirty(); + } + + if (result != Result.Success) + { + Console.Error.WriteLine($"[GPU][WARN] Graphics pipeline library failed: part={PartName(part)} {label} result={result}; the pipeline is built whole."); + return default; + } + + if (milliseconds >= SlowPipelineCreationMilliseconds) + { + var module = create->StageCount != 0 ? create->PStages[0].Module.Handle : 0; + int count; + lock (_graphicsLibraryLock) + { + count = _graphicsLibraries.Count + 1; + } + + Console.Error.WriteLine($"[GPU][INFO] Graphics pipeline library compiled: part={PartName(part)} {label} ms={milliseconds:F0} " + + $"module=0x{module:X} libraries={count}"); + } + + return created; + } + + // A pixel program was translated: its pixel stage part is compiled on a worker for the sample state draws give it + // (one sample, no sample shading), so the draws that use the program link the part instead of compiling it, and + // the programs a scene brings compile side by side. + public void PixelProgramCreated(ShaderProgramInfo program, ulong module) + { + if (!_graphicsPipelineLibraries || !_earlyPixelLibraries || program.Bindings is null || module == 0) + { + return; + } + + var bindings = new List(); + CollectLayoutBindings(bindings, program, ShaderStage.Pixel); + var multisample = SingleSampleState(); + var states = BaseDynamicStates; + string key; + fixed (DynamicState* statePointer = states) + { + var dynamicState = new PipelineDynamicStateCreateInfo + { + SType = StructureType.PipelineDynamicStateCreateInfo, + DynamicStateCount = (uint)states.Length, + PDynamicStates = statePointer, + }; + key = FragmentKey(module, SetSignature(bindings, push: false), &multisample, &dynamicState); + } + + lock (_graphicsLibraryLock) + { + if (_graphicsLibraries.ContainsKey(key) || _graphicsLibraryCompiles.ContainsKey(key)) + { + return; + } + } + + var label = $"vs=early ps=0x{program.Hash:X16}"; + var task = Task.Factory.StartNew( + () => + { + _pixelLibrarySlots.Wait(); + try + { + CompileEarlyPixelLibrary(key, module, bindings, label); + } + catch (Exception exception) + { + Console.Error.WriteLine($"[GPU][WARN] Early pixel library failed: {label} {exception.Message}"); + } + finally + { + _pixelLibrarySlots.Release(); + } + }, + CancellationToken.None, + TaskCreationOptions.LongRunning, + TaskScheduler.Default); + lock (_earlyPixelLibraryTasks) + { + _earlyPixelLibraryTasks.RemoveAll(static item => item.IsCompleted); + _earlyPixelLibraryTasks.Add(task); + } + } + + private static PipelineMultisampleStateCreateInfo SingleSampleState() => new() + { + SType = StructureType.PipelineMultisampleStateCreateInfo, + RasterizationSamples = SampleCountFlags.Count1Bit, + MinSampleShading = 1f, + }; + + // The pixel stage part GraphicsLibrary builds for a one-sample pipeline of this program. + private void CompileEarlyPixelLibrary(string key, ulong module, List bindings, string label) + { + if (TryTakeGraphicsLibrary(key, out _, out var compile)) + { + return; + } + + var created = default(Pipeline); + try + { + created = CreateEarlyPixelLibrary(module, bindings, label); + } + finally + { + FinishGraphicsLibrary(key, compile!, created); + } + } + + // The part itself; the pixel prewarm builds it the same way into the pipeline cache. + private Pipeline CreateEarlyPixelLibrary(ulong module, List bindings, string label) + { + var created = default(Pipeline); + DescriptorSetLayout pixelSet = default; + PipelineLayout layout = default; + var entryPoint = (byte*)SilkMarshal.StringToPtr("main"); + try + { + if (bindings.Count != 0) + { + pixelSet = CreateDescriptorSetLayout(bindings, allowPush: false, out _, out _); + } + + layout = CreateLibraryPipelineLayout(default, pixelSet); + var stage = new PipelineShaderStageCreateInfo + { + SType = StructureType.PipelineShaderStageCreateInfo, + Stage = ShaderStageFlags.FragmentBit, + Module = new ShaderModule(module), + PName = entryPoint, + }; + var multisample = SingleSampleState(); + var depthStencil = new PipelineDepthStencilStateCreateInfo { SType = StructureType.PipelineDepthStencilStateCreateInfo }; + var rendering = new PipelineRenderingCreateInfo { SType = StructureType.PipelineRenderingCreateInfo }; + var states = BaseDynamicStates; + fixed (DynamicState* statePointer = states) + { + var dynamicState = new PipelineDynamicStateCreateInfo + { + SType = StructureType.PipelineDynamicStateCreateInfo, + DynamicStateCount = (uint)states.Length, + PDynamicStates = statePointer, + }; + var partInfo = new GraphicsPipelineLibraryCreateInfoEXT + { + SType = StructureType.GraphicsPipelineLibraryCreateInfoExt, + PNext = &rendering, + Flags = GraphicsPipelineLibraryFlagsEXT.FragmentShaderBitExt, + }; + var create = new GraphicsPipelineCreateInfo + { + SType = StructureType.GraphicsPipelineCreateInfo, + PNext = &partInfo, + Flags = PipelineCreateFlags.CreateLibraryBitKhr, + StageCount = 1, + PStages = &stage, + PMultisampleState = &multisample, + PDepthStencilState = &depthStencil, + PDynamicState = &dynamicState, + Layout = layout, + }; + created = CompileGraphicsLibrary(&create, GraphicsPipelineLibraryFlagsEXT.FragmentShaderBitExt, label); + } + } + finally + { + if (layout.Handle != 0) + { + _vk.DestroyPipelineLayout(_device, layout, null); + } + + if (pixelSet.Handle != 0) + { + _vk.DestroyDescriptorSetLayout(_device, pixelSet, null); + } + + SilkMarshal.Free((nint)entryPoint); + } + + return created; + } + + private static string PartName(GraphicsPipelineLibraryFlagsEXT part) => part switch + { + GraphicsPipelineLibraryFlagsEXT.VertexInputInterfaceBitExt => "vertex-input", + GraphicsPipelineLibraryFlagsEXT.PreRasterizationShadersBitExt => "vertex", + GraphicsPipelineLibraryFlagsEXT.FragmentShaderBitExt => "pixel", + _ => "output", + }; + + private static string DynamicKey(PipelineDynamicStateCreateInfo* dynamicState) + { + var builder = new StringBuilder(); + for (var index = 0; index < dynamicState->DynamicStateCount; index++) + { + builder.Append(',').Append((int)dynamicState->PDynamicStates[index]); + } + + return builder.ToString(); + } + + private static string MultisampleKey(PipelineMultisampleStateCreateInfo* multisample) => + $"{(int)multisample->RasterizationSamples},{(bool)multisample->SampleShadingEnable},{multisample->MinSampleShading}"; + + private static string VertexInputKey(GraphicsPipelineCreateInfo* info, PipelineDynamicStateCreateInfo* dynamicState) + { + var input = info->PVertexInputState; + var builder = new StringBuilder("vi"); + for (var index = 0; index < input->VertexBindingDescriptionCount; index++) + { + var binding = input->PVertexBindingDescriptions[index]; + builder.Append(";b").Append(binding.Binding).Append(',').Append(binding.Stride).Append(',').Append((int)binding.InputRate); + } + + for (var index = 0; index < input->VertexAttributeDescriptionCount; index++) + { + var attribute = input->PVertexAttributeDescriptions[index]; + builder.Append(";a").Append(attribute.Location).Append(',').Append(attribute.Binding).Append(',') + .Append((int)attribute.Format).Append(',').Append(attribute.Offset); + } + + var assembly = info->PInputAssemblyState; + builder.Append(";t").Append((int)assembly->Topology).Append(',').Append((bool)assembly->PrimitiveRestartEnable) + .Append(";d").Append(DynamicKey(dynamicState)); + return builder.ToString(); + } + + // A task stage and its specialization values, or nothing. + private static string TaskKey(GraphicsPipelineCreateInfo* info) + { + var index = StageIndex(info, ShaderStageFlags.TaskBitExt); + if (index < 0) return ""; + var builder = new System.Text.StringBuilder(";task"); + var specialization = info->PStages[index].PSpecializationInfo; + if (specialization is not null) + { + var values = (uint*)specialization->PData; + for (var word = 0; word < (int)(specialization->DataSize / sizeof(uint)); word++) + builder.Append(':').Append(values[word]); + } + + return builder.ToString(); + } + + // The index of the stage of this kind in info, or -1. + // The control and evaluation modules and the patch size of a tessellated part. + private static string TessellationKey(GraphicsPipelineCreateInfo* info) + { + var control = StageIndex(info, ShaderStageFlags.TessellationControlBit); + var evaluation = StageIndex(info, ShaderStageFlags.TessellationEvaluationBit); + return control < 0 || evaluation < 0 || info->PTessellationState is null + ? "" + : $";tess:{info->PStages[control].Module.Handle:X}:{info->PStages[evaluation].Module.Handle:X}:" + + $"{info->PTessellationState->PatchControlPoints}"; + } + + private static int StageIndex(GraphicsPipelineCreateInfo* info, ShaderStageFlags stage) + { + for (var index = 0; index < (int)info->StageCount; index++) + { + if (info->PStages[index].Stage == stage) + { + return index; + } + } + + return -1; + } + + // Depth bias enable and line width are dynamic. + private static string PreRasterizationKey(RenderPipelineEntry entry, GraphicsPipelineCreateInfo* info, + PipelineDynamicStateCreateInfo* dynamicState) + { + var stage = info->PStages[0]; + var task = TaskKey(info) + TessellationKey(info); + var viewport = info->PViewportState; + var clipControl = viewport->PNext is null ? "-" : ((bool)((PipelineViewportDepthClipControlCreateInfoEXT*)viewport->PNext)->NegativeOneToOne).ToString(); + var raster = info->PRasterizationState; + var depthClip = raster->PNext is null ? "-" : ((bool)((PipelineRasterizationDepthClipStateCreateInfoEXT*)raster->PNext)->DepthClipEnable).ToString(); + return $"pr;{stage.Module.Handle:X};{(int)stage.Stage};{(int)stage.Flags}{task};{entry.VertexSetSignature};" + + $"{clipControl};{(int)raster->PolygonMode};{(int)raster->CullMode};{(int)raster->FrontFace};{depthClip};" + + $"{(bool)raster->DepthClampEnable};{(bool)raster->RasterizerDiscardEnable};" + + DynamicKey(dynamicState); + } + + // The pixel stage part depends on the program, its set and the sample state: depth and stencil state are dynamic. + private static string FragmentKey(ulong pixelModule, string pixelSetSignature, + PipelineMultisampleStateCreateInfo* multisample, PipelineDynamicStateCreateInfo* dynamicState) => + $"fs;{pixelModule:X};{pixelSetSignature};{MultisampleKey(multisample)};" + DynamicKey(dynamicState); + + private static string OutputKey(GraphicsPipelineCreateInfo* info) + { + var blend = info->PColorBlendState; + var rendering = (PipelineRenderingCreateInfo*)info->PNext; + var builder = new StringBuilder("fo;"); + builder.Append((bool)blend->LogicOpEnable).Append(',').Append((int)blend->LogicOp); + for (var index = 0; index < blend->AttachmentCount; index++) + { + var attachment = blend->PAttachments[index]; + builder.Append(";c").Append((int)attachment.ColorWriteMask).Append(',').Append((bool)attachment.BlendEnable).Append(',') + .Append((int)attachment.SrcColorBlendFactor).Append(',').Append((int)attachment.DstColorBlendFactor).Append(',') + .Append((int)attachment.ColorBlendOp).Append(',').Append((int)attachment.SrcAlphaBlendFactor).Append(',') + .Append((int)attachment.DstAlphaBlendFactor).Append(',').Append((int)attachment.AlphaBlendOp); + } + + builder.Append(";f"); + for (var index = 0; index < rendering->ColorAttachmentCount; index++) + { + builder.Append(',').Append((int)rendering->PColorAttachmentFormats[index]); + } + + builder.Append(";z").Append((int)rendering->DepthAttachmentFormat).Append(',').Append((int)rendering->StencilAttachmentFormat) + .Append(';').Append(MultisampleKey(info->PMultisampleState)).Append(";d").Append(DynamicKey(info->PDynamicState)); + return builder.ToString(); + } + + // Waits for the early pixel compiles still running: they use program modules, which teardown destroys. + private void WaitForEarlyPixelLibraries() + { + Task[] running; + lock (_earlyPixelLibraryTasks) + { + running = _earlyPixelLibraryTasks.ToArray(); + _earlyPixelLibraryTasks.Clear(); + } + + try + { + Task.WaitAll(running); + } + catch (AggregateException) + { + // Each compile reports its own failure. + } + } + + private void DestroyGraphicsLibraries() + { + WaitForEarlyPixelLibraries(); + lock (_graphicsLibraryLock) + { + foreach (var library in _graphicsLibraries.Values) + { + _vk.DestroyPipeline(_device, library, null); + } + + _graphicsLibraries.Clear(); + } + } + } +} diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Pipelines.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Pipelines.cs index 35da2d5f8..fc54520d8 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Pipelines.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Pipelines.cs @@ -4,6 +4,7 @@ namespace SharpEmu.Libs.VideoOut; using System.Diagnostics; +using System.Collections.Concurrent; using SharpEmu.HLE.GpuMemory; using SharpEmu.Libs.Gpu; using SharpEmu.Libs.Gpu.GpuCommands; @@ -41,6 +42,14 @@ private sealed class RenderPipelineEntry public ulong ProfilePixelHash; public ulong ProfileComputeHash; + // Laid out for pipeline libraries, and linked from them unless built whole: SetLayout is the vertex stage's set 0, + // PixelSetLayout the pixel stage's set 2. + public bool LinkedFromLibraries; + public DescriptorSetLayout PixelSetLayout; + public DescriptorSetDemand PixelDemand; + public string VertexSetSignature = ""; + public string PixelSetSignature = ""; + public bool RectangleList => Description is { Tessellation: null, StaticParameters.Topology: PrimitiveTopology.PatchList }; } @@ -58,10 +67,11 @@ private sealed partial class Presenter : IShaderPipelineHost private static int _vertexSwizzleLines; private static int _vertexOutOfBoundsLines; - private readonly Dictionary _shaderModules = new(); - private readonly System.Collections.Concurrent.ConcurrentDictionary _shaderModuleSpirvBytes = new(); - private readonly System.Collections.Concurrent.ConcurrentDictionary _rectangleStageCode = new(); - private readonly Dictionary _shaderModuleCacheIdentities = new(); + // Graphics and compute resolvers can publish modules concurrently; pipeline workers read their metadata too. + private readonly ConcurrentDictionary _shaderModules = new(); + private readonly ConcurrentDictionary _shaderModuleSpirvBytes = new(); + private readonly ConcurrentDictionary _rectangleStageCode = new(); + private readonly ConcurrentDictionary _shaderModuleCacheIdentities = new(); private long _pipelineCreationMilliseconds; internal KhrPushDescriptor _pushDescriptorApi = null!; private uint _maxPushDescriptors; @@ -71,6 +81,12 @@ private sealed partial class Presenter : IShaderPipelineHost uint IShaderPipelineHost.MaxPushDescriptors => _maxPushDescriptors; + StableImageDescriptorLimits IShaderPipelineHost.ComputeImageDescriptorLimits => + ShaderDescriptorLimits.ComputeImageLimits(_shaderDescriptorLimits); + + StableImageDescriptorLimits IShaderPipelineHost.GraphicsImageDescriptorLimits => + ShaderDescriptorLimits.GraphicsImageLimits(_shaderDescriptorLimits); + bool IShaderPipelineHost.TryCopyImage(in ImageRequest source, in ImageRequest destination) => _imageCache.TryCopyImage(source, destination); bool IShaderPipelineHost.TableBlocks => true; @@ -152,9 +168,13 @@ private uint ComputeRequiredSubgroupSize(ComputeInputInfo input) => bool IShaderPipelineHost.GraphicsSubgroupOperationsEnabled => GraphicsSubgroupOperationsEnabled; bool IShaderPipelineHost.SharedInt64AtomicsEnabled => SharedInt64AtomicsEnabled; + bool IShaderPipelineHost.BufferInt64AtomicsEnabled => BufferInt64AtomicsEnabled; bool IShaderPipelineHost.ImageInt64AtomicsEnabled => ImageInt64AtomicsEnabled; + bool IShaderPipelineHost.ShaderDeviceClockEnabled => ShaderDeviceClockEnabled; bool IShaderPipelineHost.ShaderSignedZeroInfNanPreserveFloat32Supported => _supportsShaderSignedZeroInfNanPreserveFloat32; + bool IShaderPipelineHost.RobustBufferAccess2Enabled => _robustBufferAccess2Enabled; + bool IShaderPipelineHost.NativeFloat16Conversions => _nativeFloat16Conversions; // NVIDIA's compiler rejects the elided-EXEC wave64 compute module with NVVM error 3. bool IShaderPipelineHost.ExecGuardElisionEnabled => _physicalDeviceVendorId != NvidiaVendorId; bool IShaderPipelineHost.PerVertexPixelInputsSupported => _supportsPerVertexPixelInputs; @@ -163,6 +183,8 @@ private uint ComputeRequiredSubgroupSize(ComputeInputInfo input) => bool IShaderPipelineHost.MeshShadersSupported => _supportsMeshShader; + bool IShaderPipelineHost.SupportsBindlessHeap => _bindlessHeapSupported; + MeshShaderLimits IShaderPipelineHost.MeshLimits => _meshShaderLimits; uint IShaderPipelineHost.MeshSubgroupSize => checked((uint)Volatile.Read(ref _nativeSubgroupSize)); bool IShaderPipelineHost.ShaderDrawParametersSupported => _supportsShaderDrawParameters; @@ -662,19 +684,28 @@ private void NoteCleanReadPage(ulong address, ulong size) public ulong CreateShaderModule(IGuestCompiledShader shader, ShaderStage stage, ulong hash, ulong programId) { using var profileScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramCompile); - var module = CreateShaderModule(shader.Payload); + var payload = stage == ShaderStage.Pixel && _graphicsPipelineLibraries + ? WithDescriptorSet(shader.Payload, 0, PixelDescriptorSet) + : shader.Payload; + var module = CreateShaderModule(payload); SetDebugName(ObjectType.ShaderModule, module.Handle, $"SharpEmu {stage} 0x{hash:X16}"); - _shaderModules.Add(programId, module); - _shaderModuleSpirvBytes[module.Handle] = shader.Payload.Length; + _shaderModuleSpirvBytes[module.Handle] = payload.Length; if (stage is ShaderStage.Vertex or ShaderStage.Pixel) - _rectangleStageCode[module.Handle] = shader.Payload; - var identity = VulkanPipelineCacheStorage.CompiledShaderIdentity(shader.Payload); + _rectangleStageCode[module.Handle] = payload; + var identity = VulkanPipelineCacheStorage.CompiledShaderIdentity(payload); _shaderModuleCacheIdentities[module.Handle] = identity; if (stage == ShaderStage.Compute) { NoteRuntimeComputeModule(identity); } + else if (stage is ShaderStage.Pixel or ShaderStage.Vertex or ShaderStage.Mesh) + { + NoteRuntimeGraphicsModule(identity, stage); + } + // Publish the handle only after all metadata is installed. The owning resolver exposes its program next. + if (!_shaderModules.TryAdd(programId, module)) + throw SubmissionScheduler.Fatal($"Duplicate shader program ID: {programId}."); return module.Handle; } @@ -804,6 +835,76 @@ private void CreateBarycentricPipeline() } } + private ShaderModule _meshTaskModule; + private static readonly object MeshTaskModuleGate = new(); + + // The generic task stage of task-launched mesh pipelines; pipelines compile on worker threads. + private ShaderModule RequireMeshTaskModule() + { + lock (MeshTaskModuleGate) + { + if (_meshTaskModule.Handle == 0) + { + _meshTaskModule = CreateShaderModule(SharpEmu.ShaderCompiler.Vulkan.SpirvMeshTask.Create()); + } + + return _meshTaskModule; + } + } + + // The task stage's specialization: the program's primitives per group and point list, the device's group limits. + private void FillTaskSpecialization(MeshTaskLaunchInfo task, SpecializationMapEntry* entries, uint* values, + ref SpecializationInfo specialization) + { + // The task stage divides by it, as the conversion did by its push word. + if (task.PrimitivesPerGroup == 0) + throw SubmissionScheduler.Fatal("A task-launched mesh program has no primitives per group."); + values[0] = task.PrimitivesPerGroup; + values[1] = task.PointList ? 1u : 0u; + values[2] = _meshShaderLimits.MaxGroupCountX; + values[3] = _meshShaderLimits.MaxGroupCountY; + values[4] = _meshShaderLimits.MaxGroupTotalCount; + uint[] ids = + [ + SharpEmu.ShaderCompiler.Vulkan.SpirvMeshTask.SpecPrimitivesPerGroup, + SharpEmu.ShaderCompiler.Vulkan.SpirvMeshTask.SpecPointList, + SharpEmu.ShaderCompiler.Vulkan.SpirvMeshTask.SpecMaxGroupCountX, + SharpEmu.ShaderCompiler.Vulkan.SpirvMeshTask.SpecMaxGroupCountY, + SharpEmu.ShaderCompiler.Vulkan.SpirvMeshTask.SpecMaxGroupTotalCount, + ]; + for (var index = 0; index < ids.Length; index++) + { + entries[index] = new SpecializationMapEntry(ids[index], (uint)(index * sizeof(uint)), sizeof(uint)); + } + + specialization = new SpecializationInfo + { + MapEntryCount = (uint)ids.Length, + PMapEntries = entries, + DataSize = (nuint)(ids.Length * sizeof(uint)), + PData = values, + }; + } + + private const int TaskSpecializationValues = 5; + + // The task stage of a task-launched mesh program's pipeline or pre-rasterization part; the graphics prewarm + // builds the same one. entries and values hold TaskSpecializationValues each and, like specialization, outlive + // the create info. + private PipelineShaderStageCreateInfo TaskStageInfo(MeshTaskLaunchInfo task, SpecializationMapEntry* entries, uint* values, + SpecializationInfo* specialization, byte* entryPoint) + { + FillTaskSpecialization(task, entries, values, ref *specialization); + return new PipelineShaderStageCreateInfo + { + SType = StructureType.PipelineShaderStageCreateInfo, + Stage = ShaderStageFlags.TaskBitExt, + Module = RequireMeshTaskModule(), + PName = entryPoint, + PSpecializationInfo = specialization, + }; + } + private ShaderModule CreateShaderModule(byte[] code) { if (!_supportsShaderClipDistance && RequiresCapability(code, SpirvCapability.ClipDistance)) @@ -886,6 +987,24 @@ private static void CollectLayoutBindings(List bindi private static bool UsesBindlessHeap(ShaderProgramInfo program) => program.Bindings?.UsesBindlessHeap == true; + // The bindings of the stage before rasterization, collected before any other stage's. + private static void CollectVertexStageBindings(List bindings, GraphicsPipelineDescription description) + { + CollectLayoutBindings(bindings, description.VertexStage, + description.Tessellation is not null ? ShaderStage.TessellationEvaluation + : description.VertexStage.Stage == ShaderStageKind.Mesh ? ShaderStage.Mesh : ShaderStage.Vertex); + if (description.Tessellation is not null) + { + // The control bridge reads the domain stage's runtime data. + var dataBinding = BindingLayout.NativeBindingIndex(ShaderStage.TessellationEvaluation, DescriptorBindingKind.ShaderData); + var dataIndex = bindings.FindIndex(binding => binding.Binding == dataBinding); + if (dataIndex < 0) throw SubmissionScheduler.Fatal("The tessellation pipeline has no runtime data binding."); + var dataLayout = bindings[dataIndex]; + dataLayout.StageFlags |= ShaderStageFlags.TessellationControlBit; + bindings[dataIndex] = dataLayout; + } + } + private static void CollectLayoutBindings(List bindings, BindingLayout layout, ShaderStage stage) { foreach (var binding in layout.Descriptors) @@ -903,7 +1022,11 @@ private static void CollectLayoutBindings(List bindi // The set is pushed when its descriptors fit the device limit, else it comes from the heap. private PhysicalDeviceLimits _shaderDescriptorLimits; - private DescriptorSetLayout CreateDescriptorSetLayout(List bindings, out bool usesPushDescriptors, out DescriptorSetDemand demand) + private DescriptorSetLayout CreateDescriptorSetLayout(List bindings, out bool usesPushDescriptors, out DescriptorSetDemand demand) => + CreateDescriptorSetLayout(bindings, allowPush: true, out usesPushDescriptors, out demand); + + private DescriptorSetLayout CreateDescriptorSetLayout(List bindings, bool allowPush, out bool usesPushDescriptors, + out DescriptorSetDemand demand) { ShaderDescriptorLimits.Validate(bindings, _shaderDescriptorLimits); var descriptorCount = 0u; @@ -914,7 +1037,7 @@ private DescriptorSetLayout CreateDescriptorSetLayout(List _maxColorAttachments) { throw SubmissionScheduler.Fatal($"The draw binds more color attachments than the device supports: count={description.Rendering.ColorCount} max={_maxColorAttachments}."); } - var bindings = new List(); - CollectLayoutBindings(bindings, description.VertexStage, - description.Tessellation is not null ? ShaderStage.TessellationEvaluation - : description.VertexStage.Stage == ShaderStageKind.Mesh ? ShaderStage.Mesh : ShaderStage.Vertex); - if (description.Tessellation is not null) + // With libraries every pixel module reads its bindings from set 2 (CreateShaderModule), so every pipeline is laid + // out for them, a tessellated one too (LinkOrBuildGraphicsPipeline). + if (_graphicsPipelineLibraries) { - // The control bridge reads the domain stage's runtime data. - var dataBinding = BindingLayout.NativeBindingIndex(ShaderStage.TessellationEvaluation, DescriptorBindingKind.ShaderData); - var dataIndex = bindings.FindIndex(binding => binding.Binding == dataBinding); - if (dataIndex < 0) throw SubmissionScheduler.Fatal("The tessellation pipeline has no runtime data binding."); - var dataLayout = bindings[dataIndex]; - dataLayout.StageFlags |= ShaderStageFlags.TessellationControlBit; - bindings[dataIndex] = dataLayout; + return CreateLibraryPipelineEntry(description); } + var bindings = new List(); + CollectVertexStageBindings(bindings, description); if (description.PixelStage is { } pixelStage) { CollectLayoutBindings(bindings, pixelStage, ShaderStage.Pixel); @@ -1001,7 +1146,7 @@ description.Tessellation is not null ? ShaderStage.TessellationEvaluation var setLayout = CreateDescriptorSetLayout(bindings, out var usesPushDescriptors, out var demand); var bindlessHeap = UsesBindlessHeap(description.VertexStage) || (description.PixelStage is { } heapPixelStage && UsesBindlessHeap(heapPixelStage)); - var entry = new RenderPipelineEntry + return new RenderPipelineEntry { SetLayout = setLayout, Demand = demand, @@ -1016,13 +1161,145 @@ description.Tessellation is not null ? ShaderStage.TessellationEvaluation ProfileVertexHash = description.VertexStage.Hash, ProfilePixelHash = description.PixelStage?.Hash ?? 0, }; - // Rectangle draws bind a native fill or compatibility variant at draw time. - if (!entry.RectangleList) + } + + // One graphics pipeline whose vkCreateGraphicsPipelines call runs on a worker thread. The command stream prepares + // its layouts, its entry and its pipeline cache source before the compile starts, and registers the pipeline once + // the compile is done (TryCreateGraphicsPipeline). + internal sealed class PendingGraphicsPipeline + { + public required RenderPipelineEntry Entry; + public required Lazy? CacheSource; + public required string Stages; + public required string SpirvBytes; + public Task Compile = Task.FromResult(default(Pipeline)); + public long StartTimestamp; + public long CompileMilliseconds; + } + + private readonly Dictionary _pendingGraphicsPipelines = + new(ReferenceEqualityComparer.Instance); + + private static readonly SemaphoreSlim _graphicsCompileSlots = new(Math.Max(2, Environment.ProcessorCount / 4)); + + // A host shader compiler can spend seconds on one large translated pixel shader, and a game entering a new area + // asks for dozens. Graphics pipelines are built on worker threads, and the draw waits for its pipeline outside the + // pipeline cache's lock (WaitForGraphicsPipeline), so the next draws' programs are translated meanwhile and their + // pixel stage parts compile beside it (PixelProgramCreated). SHARPEMU_ASYNC_GRAPHICS_PIPELINES=0 builds them on the + // command stream. Resolve workers create pipelines concurrently, so the pending compiles are read and changed under + // their own lock. + private static readonly bool _asyncGraphicsPipelines = + Environment.GetEnvironmentVariable("SHARPEMU_ASYNC_GRAPHICS_PIPELINES") != "0"; + + // The command stream waits here, outside the pipeline cache's lock, for a compile TryCreateGraphicsPipeline left + // running; the next TryCreateGraphicsPipeline takes the pipeline. + public void WaitForGraphicsPipeline(GraphicsPipelineDescription description) + { + PendingGraphicsPipeline? pending; + lock (_pendingGraphicsPipelines) { - entry.Pipeline = CreateRenderPipeline(description, description.StaticParameters.Topology, entry.Layout); + if (!_pendingGraphicsPipelines.TryGetValue(description, out pending) || pending.Compile.IsCompleted) + { + return; + } } - return RegisterPipeline(entry); + using var waitScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.GraphicsPipelineDriver); + try + { + pending.Compile.Wait(); + } + catch (AggregateException) + { + // A failed compile throws when its pipeline is taken. + } + } + + public bool TryCreateGraphicsPipeline(GraphicsPipelineDescription description, out PipelineHandle handle) + { + lock (_pendingGraphicsPipelines) + { + return TryCreateGraphicsPipelineCore(description, out handle); + } + } + + private bool TryCreateGraphicsPipelineCore(GraphicsPipelineDescription description, out PipelineHandle handle) + { + if (_pendingGraphicsPipelines.TryGetValue(description, out var pending)) + { + return TryTakeGraphicsPipeline(description, pending, out handle); + } + + // Rectangle lists build their pipelines at draw time. + if (!_asyncGraphicsPipelines || + (description.Tessellation is null && description.StaticParameters.Topology == PrimitiveTopology.PatchList)) + { + handle = CreateGraphicsPipeline(description); + return true; + } + + RenderPipelineEntry entry; + using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.PipelineSetup)) + { + entry = CreateGraphicsPipelineEntry(description); + } + + var vertexModule = description.VertexProgram.Module; + var pixelModule = description.PixelStage is null ? 0 : description.PixelProgram.Module; + var started = new PendingGraphicsPipeline + { + Entry = entry, + CacheSource = GetGuestPipelineCacheSource(GraphicsCacheKey(description.VertexStage.Hash, + description.PixelStage?.Hash ?? 0, vertexModule, pixelModule)), + Stages = $"vs=0x{description.VertexStage.Hash:X16} ps=0x{description.PixelStage?.Hash ?? 0:X16}", + SpirvBytes = pixelModule == 0 ? $"{SpirvBytesOf(vertexModule)}" : $"{SpirvBytesOf(vertexModule)}/{SpirvBytesOf(pixelModule)}", + StartTimestamp = Stopwatch.GetTimestamp(), + }; + var topology = description.StaticParameters.Topology; + started.Compile = Task.Factory.StartNew( + () => + { + _graphicsCompileSlots.Wait(); + var compileStart = Stopwatch.GetTimestamp(); + try + { + return CreateRenderPipeline(description, topology, entry.Layout, worker: started, libraries: entry); + } + finally + { + Interlocked.Exchange(ref started.CompileMilliseconds, (long)Stopwatch.GetElapsedTime(compileStart).TotalMilliseconds); + _graphicsCompileSlots.Release(); + } + }, + CancellationToken.None, + TaskCreationOptions.LongRunning, + TaskScheduler.Default); + _pendingGraphicsPipelines.Add(description, started); + return TryTakeGraphicsPipeline(description, started, out handle); + } + + // Takes a finished compile: reports and names the pipeline and registers its entry. False while the compile runs. + private bool TryTakeGraphicsPipeline(GraphicsPipelineDescription description, PendingGraphicsPipeline pending, out PipelineHandle handle) + { + if (!pending.Compile.IsCompleted) + { + handle = default; + return false; + } + + var pipeline = pending.Compile.GetAwaiter().GetResult(); + ReportPipelineCreation( + Interlocked.Read(ref pending.CompileMilliseconds), + "graphics-async", + $"{pending.Stages} waited_ms={(long)Stopwatch.GetElapsedTime(pending.StartTimestamp).TotalMilliseconds}", + pending.SpirvBytes); + MarkPipelineCacheDirty(); + Interlocked.Increment(ref _perfPipelineCreations); + SetDebugName(ObjectType.Pipeline, pipeline.Handle, + $"SharpEmu graphics {pending.Stages} colors={description.StaticParameters.ColorCount}"); + pending.Entry.Pipeline = pipeline; + handle = RegisterPipeline(pending.Entry, () => _pendingGraphicsPipelines.Remove(description)); + return true; } private static StencilOpState ToVkStencilOpState(in StencilOperations operations) => new() @@ -1150,8 +1427,12 @@ private static void CheckVertexSwizzle(in BufferDescriptorWords descriptor, int } // One graphics pipeline for dynamic rendering: the attachment formats travel in the create info. + // With worker (a compile TryCreateGraphicsPipeline started), this runs on a compiler thread: the pipeline cache comes + // from the source the command stream resolved, and the command stream reports and names the pipeline when it takes it. + // A prewarm pipeline is built in the device pipeline cache and returned unreported. internal Pipeline CreateRenderPipeline(GraphicsPipelineDescription description, PrimitiveTopology topology, PipelineLayout layout, - PolygonMode polygonMode = PolygonMode.Fill, bool expandRectangles = false, bool prewarm = false) + PolygonMode polygonMode = PolygonMode.Fill, bool expandRectangles = false, PendingGraphicsPipeline? worker = null, + RenderPipelineEntry? libraries = null, bool prewarm = false) { var parameters = description.StaticParameters; var rendering = description.Rendering; @@ -1177,17 +1458,12 @@ internal Pipeline CreateRenderPipeline(GraphicsPipelineDescription description, if (pixelCode is not null) rectanglePixelModule = CreateShaderModule(pixelCode); } var shaderStages = stackalloc PipelineShaderStageCreateInfo[5]; + var taskEntries = stackalloc SpecializationMapEntry[TaskSpecializationValues]; + var taskValues = stackalloc uint[TaskSpecializationValues]; + var taskSpecialization = new SpecializationInfo(); var stageCount = 1u; - shaderStages[0] = new PipelineShaderStageCreateInfo - { - SType = StructureType.PipelineShaderStageCreateInfo, - Stage = description.VertexStage.Stage == ShaderStageKind.Mesh - ? ShaderStageFlags.MeshBitExt : ShaderStageFlags.VertexBit, - Flags = description.VertexStage.Stage == ShaderStageKind.Mesh - ? PipelineShaderStageCreateFlags.RequireFullSubgroupsBit : 0, - Module = expandRectangles ? rectangleVertexModule : vertexModule, - PName = entryPoint, - }; + shaderStages[0] = VertexStageInfo(description.VertexStage.Stage == ShaderStageKind.Mesh, + expandRectangles ? rectangleVertexModule : vertexModule, entryPoint); var tessellationState = new PipelineTessellationStateCreateInfo { SType = StructureType.PipelineTessellationStateCreateInfo, @@ -1238,6 +1514,17 @@ internal Pipeline CreateRenderPipeline(GraphicsPipelineDescription description, }; } + // A task-launched mesh program takes the generic task stage, last, specialized for this program. + if (description.VertexStage.MeshTask is { } task) + { + if (!_supportsTaskShader || expandRectangles || description.VertexStage.Stage != ShaderStageKind.Mesh) + { + throw SubmissionScheduler.Fatal("A task-launched mesh program needs task shaders and a mesh pipeline."); + } + + shaderStages[stageCount++] = TaskStageInfo(task, taskEntries, taskValues, &taskSpecialization, entryPoint); + } + var vertexBindings = new VertexInputBindingDescription[description.VertexInput.BindingCount]; var vertexAttributes = new VertexInputAttributeDescription[description.VertexInput.AttributeCount]; BuildVertexAttributes(description, vertexAttributes, vertexBindings); @@ -1357,25 +1644,15 @@ internal Pipeline CreateRenderPipeline(GraphicsPipelineDescription description, MinDepthBounds = 0f, MaxDepthBounds = 1f, }; - var dynamicStates = stackalloc DynamicState[14]; - dynamicStates[0] = DynamicState.Viewport; - dynamicStates[1] = DynamicState.Scissor; - dynamicStates[2] = DynamicState.LineWidth; - dynamicStates[3] = DynamicState.DepthTestEnableExt; - dynamicStates[4] = DynamicState.DepthWriteEnableExt; - dynamicStates[5] = DynamicState.DepthCompareOpExt; - dynamicStates[6] = DynamicState.DepthBiasEnableExt; - dynamicStates[7] = DynamicState.DepthBias; - dynamicStates[8] = DynamicState.StencilCompareMask; - dynamicStates[9] = DynamicState.StencilReference; - dynamicStates[10] = DynamicState.StencilWriteMask; - dynamicStates[11] = DynamicState.BlendConstants; - var dynamicStateCount = 12u; - if (_supportsDepthBounds) + var baseStates = BaseDynamicStates; + var dynamicStates = stackalloc DynamicState[baseStates.Length + 1]; + for (var index = 0; index < baseStates.Length; index++) { - dynamicStates[dynamicStateCount++] = DynamicState.DepthBounds; + dynamicStates[index] = baseStates[index]; } + var dynamicStateCount = (uint)baseStates.Length; + var baseDynamicStateCount = dynamicStateCount; // Last so a pipeline without color attachments can leave it out. if (_colorWriteEnableApi is not null && colorCount != 0) { @@ -1388,6 +1665,7 @@ internal Pipeline CreateRenderPipeline(GraphicsPipelineDescription description, DynamicStateCount = dynamicStateCount, PDynamicStates = dynamicStates, }; + var baseDynamicState = dynamicState with { DynamicStateCount = baseDynamicStateCount }; var renderingInfo = new PipelineRenderingCreateInfo { SType = StructureType.PipelineRenderingCreateInfo, @@ -1414,23 +1692,33 @@ internal Pipeline CreateRenderPipeline(GraphicsPipelineDescription description, Layout = layout, }; var reportStart = Stopwatch.GetTimestamp(); - var cache = prewarm ? _pipelineCache : GetGuestPipelineCache(GraphicsCacheKey(description.VertexStage.Hash, - description.PixelStage?.Hash ?? 0, vertexModule.Handle, pixelModule.Handle)); - var creationStart = RenderPhaseProfile.Enabled ? Stopwatch.GetTimestamp() : 0; + var cache = prewarm ? _pipelineCache + : worker is not null ? ResolveGuestPipelineCache(worker.CacheSource) + : GetGuestPipelineCache(GraphicsCacheKey(description.VertexStage.Hash, + description.PixelStage?.Hash ?? 0, vertexModule.Handle, pixelModule.Handle)); Result creationResult; Pipeline pipeline; - using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.GraphicsPipelineDriver)) + double creationMilliseconds; + if (worker is not null) + { + creationResult = LinkOrBuildGraphicsPipeline(libraries, description, expandRectangles, &pipelineInfo, + &baseDynamicState, cache, out pipeline, out creationMilliseconds); + } + else { - creationResult = _vk.CreateGraphicsPipelines(_device, cache, 1, &pipelineInfo, null, out pipeline); + using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.GraphicsPipelineDriver)) + { + creationResult = LinkOrBuildGraphicsPipeline(libraries, description, expandRectangles, &pipelineInfo, + &baseDynamicState, cache, out pipeline, out creationMilliseconds); + } } if (RenderPhaseProfile.Enabled && !prewarm) { - var creationMilliseconds = Stopwatch.GetElapsedTime(creationStart).TotalMilliseconds; Console.Error.WriteLine($"[PERF][PIPELINE_DRIVER] kind=graphics stage={description.VertexStage.Stage} vertex=0x{description.VertexStage.Hash:X16} pixel=0x{description.PixelStage?.Hash ?? 0:X16} topology={topology} driver_ms={creationMilliseconds:F3} result={creationResult}"); } Check(creationResult, $"vkCreateGraphicsPipelines(rendering vs=0x{description.VertexStage.Hash:X16} ps=0x{description.PixelStage?.Hash ?? 0:X16})"); - if (prewarm) + if (worker is not null || prewarm) { return pipeline; } @@ -1502,15 +1790,15 @@ public PipelineHandle CreateComputePipeline(ComputePipelineDescription descripti }; var reportStart = Stopwatch.GetTimestamp(); var cache = GetGuestPipelineCache(ComputeCacheKey(description.Stage.Hash, computeModule.Handle)); - var creationStart = RenderPhaseProfile.Enabled ? Stopwatch.GetTimestamp() : 0; Result creationResult; + double creationMilliseconds; using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ComputePipelineDriver)) { - creationResult = _vk.CreateComputePipelines(_device, cache, 1, &pipelineInfo, null, out pipeline); + creationResult = CreatePipelineWithBinaries(&pipelineInfo, &pipelineInfo.PNext, cache, + &CreateComputePipelineCall, out pipeline, out creationMilliseconds); } if (RenderPhaseProfile.Enabled) { - var creationMilliseconds = Stopwatch.GetElapsedTime(creationStart).TotalMilliseconds; Console.Error.WriteLine($"[PERF][PIPELINE_DRIVER] kind=compute compute=0x{description.Stage.Hash:X16} driver_ms={creationMilliseconds:F3} result={creationResult}"); } Check(creationResult, $"vkCreateComputePipelines(rendering) hash=0x{description.Stage.Hash:X16}"); @@ -1561,6 +1849,9 @@ private sealed class PendingComputePipeline // A linked program's own pipeline cache (CreateLinkedPipelineCache), written once its pipeline is registered. public DriverCacheShard? LinkedCache; + + // A linked program (Bindings.CallTargetCount != 0): its compile waits for LinkedCompileAdmission. + public bool Linked; } private readonly Dictionary _pendingComputePipelines = new(); @@ -1573,6 +1864,61 @@ private sealed class PendingComputePipeline private static readonly SemaphoreSlim _computeCompileSlots = new(Math.Max(2, Environment.ProcessorCount / 2)); + // A linked compile starts only when LinkedCompileAdmission admits it (free commit for its estimate beside + // the linked compiles already running, one large one at a time). Until then the fallback that serves a pending + // linked program keeps serving it. Shutdown abandons the ones still waiting. + private static readonly LinkedCompileAdmission _linkedCompileAdmission = + new(SharpEmu.Logging.HostSystemInfo.AvailableCommitBytes); + private volatile bool _linkedAdmissionClosed; + + // Waits until the compile is admitted; false when shutdown abandons it. Without mayWait it answers at once (the + // prewarm's linked records). An admitted compile calls ReleaseLinkedAdmission when it ends. + private bool WaitForLinkedAdmission(ulong hash, long spirvBytes, bool mayWait = true) + { + var reported = false; + while (!_linkedAdmissionClosed) + { + if (_linkedCompileAdmission.TryAdmit(spirvBytes, out var available, out var reserved)) + { + if (reported) + { + try + { + Console.Error.WriteLine($"[GPU][LINKED_ADMISSION] admitted hash=0x{hash:X16} available_gb={available / (double)(1L << 30):F1} " + + $"reserved_gb={reserved / (double)(1L << 30):F1}"); + } + catch + { + ReleaseLinkedAdmission(spirvBytes); + throw; + } + } + + return true; + } + + if (!mayWait) + { + return false; + } + + if (!reported) + { + reported = true; + var needed = LinkedCompileAdmission.Estimate(spirvBytes) + LinkedCompileAdmission.MarginBytes; + Console.Error.WriteLine($"[GPU][LINKED_ADMISSION] waiting hash=0x{hash:X16} spirv_mb={spirvBytes / 1048576.0:F1} " + + $"needed_gb={needed / (double)(1L << 30):F1} available_gb={available / (double)(1L << 30):F1} " + + $"reserved_gb={reserved / (double)(1L << 30):F1}"); + } + + Thread.Sleep(500); + } + + return false; + } + + private static void ReleaseLinkedAdmission(long spirvBytes) => _linkedCompileAdmission.Release(spirvBytes); + // A host shader compiler can spend tens of seconds on one large translated // program. Running the compile on a worker thread keeps it out of the pipeline // cache's lock, so other queues can still create their own pipelines meanwhile; @@ -1603,7 +1949,7 @@ private bool TryCreateComputePipelineCore(ComputePipelineDescription description var key = description.Program.Id; if (_pendingComputePipelines.TryGetValue(key, out var pending)) { - if (!pending.Compile.IsCompleted && description.Stage.Bindings is { CallTargetCount: not 0 }) + if (!pending.Compile.IsCompleted) { return false; } @@ -1657,7 +2003,6 @@ private bool TryCreateComputePipelineCore(ComputePipelineDescription description var device = _device; var linkedCache = linked ? CreateLinkedPipelineCache(description.Stage.Hash) : null; - var cacheSource = linkedCache?.Cache ?? GetGuestPipelineCacheSource(ComputeCacheKey(description.Stage.Hash, computeModule.Handle)); var vk = _vk; var requiredSubgroupSize = ComputeRequiredSubgroupSize(description.Input); var started = new PendingComputePipeline @@ -1671,11 +2016,47 @@ private bool TryCreateComputePipelineCore(ComputePipelineDescription description SpirvBytes = SpirvBytesOf(computeModule.Handle), StartTimestamp = Stopwatch.GetTimestamp(), LinkedCache = linkedCache, + Linked = linked, }; + // The prewarm's pipeline for this module and layout is taken instead of compiled again. It keeps the layouts + // it was compiled with, so once its pending entry is published this request's own, defined the same, go; the + // completed-compile branch above registers it. A publication that throws destroys what was taken. + if (!linked && TakePrewarmedComputePipeline(computeModule.Handle, bindings, usesPushDescriptors, bindlessHeap, + requiredSubgroupSize, out var prewarmed)) + { + try + { + started.SetLayout = prewarmed.SetLayout; + started.Layout = prewarmed.Layout; + started.Compile = Task.FromResult(prewarmed.Pipeline); + started.CompletedTimestamp = ComputeCompileProfile.Start(); + _pendingComputePipelines.Add(key, started); + } + catch + { + DestroyPrewarmedComputePipeline(prewarmed); + throw; + } + + _vk.DestroyPipelineLayout(_device, layout, null); + _vk.DestroyDescriptorSetLayout(_device, setLayout, null); + return TryCreateComputePipeline(description, out handle); + } + + var cacheSource = linkedCache?.Cache ?? GetGuestPipelineCacheSource(ComputeCacheKey(description.Stage.Hash, computeModule.Handle)); started.Compile = Task.Factory.StartNew( () => { ComputeCompileProfile.Record(ComputeCompileProfile.Part.StartDelay, started.StartTimestamp); + // A linked compile first waits for its admission (LinkedCompileAdmission). + var linkedAdmitted = started.Linked && WaitForLinkedAdmission(started.Hash, started.SpirvBytes); + if (started.Linked && !linkedAdmitted) + { + return default; + } + + try + { // Each compile blocks its thread inside the Metal compiler service, // so the number in flight is bounded instead of one thread per // program the frame happens to touch. @@ -1703,6 +2084,11 @@ private bool TryCreateComputePipelineCore(ComputePipelineDescription description _computeCompileSlots.Release(); started.CompletedTimestamp = ComputeCompileProfile.Start(); } + } + finally + { + if (linkedAdmitted) ReleaseLinkedAdmission(started.SpirvBytes); + } }, CancellationToken.None, TaskCreationOptions.LongRunning, @@ -1718,7 +2104,7 @@ private bool TryCreateComputePipelineCore(ComputePipelineDescription description // vkCreateComputePipelines is the only call here; Vulkan synchronises host // access to the pipeline cache internally, so several may run at once. - private static Pipeline CompileComputePipeline( + private Pipeline CompileComputePipeline( Vk vk, Device device, PipelineCache cache, @@ -1748,7 +2134,8 @@ private static Pipeline CompileComputePipeline( Stage = stageInfo, Layout = layout, }; - var result = vk.CreateComputePipelines(device, cache, 1, &pipelineInfo, null, out var pipeline); + var result = CreatePipelineWithBinaries(&pipelineInfo, &pipelineInfo.PNext, cache, + &CreateComputePipelineCall, out var pipeline, out _); if (result != Result.Success) { throw SubmissionScheduler.Fatal($"vkCreateComputePipelines(async) failed: {result}."); @@ -1783,6 +2170,26 @@ private void DrainPendingComputePipelines() _linkedComputeCompiles.Clear(); } + private void DrainPendingGraphicsPipelines() + { + foreach (var pending in _pendingGraphicsPipelines.Values) + { + try + { + var pipeline = pending.Compile.GetAwaiter().GetResult(); + if (pipeline.Handle != 0) _vk.DestroyPipeline(_device, pipeline, null); + } + catch (Exception exception) + { + Console.Error.WriteLine($"[LOADER][WARN] Pending graphics pipeline failed during shutdown: {exception.Message}"); + } + _vk.DestroyPipelineLayout(_device, pending.Entry.Layout, null); + _vk.DestroyDescriptorSetLayout(_device, pending.Entry.SetLayout, null); + _vk.DestroyDescriptorSetLayout(_device, pending.Entry.PixelSetLayout, null); + } + _pendingGraphicsPipelines.Clear(); + } + private void DestroyRenderPipelines() { _meshIndirectPipeline?.Dispose(); @@ -1799,15 +2206,23 @@ private void DestroyRenderPipelines() _vk.DestroyPipelineLayout(_device, entry.Layout, null); _vk.DestroyDescriptorSetLayout(_device, entry.SetLayout, null); + _vk.DestroyDescriptorSetLayout(_device, entry.PixelSetLayout, null); } _pipelineEntries.Clear(); + DestroyGraphicsLibraries(); foreach (var module in _shaderModules.Values) { _vk.DestroyShaderModule(_device, module, null); } _shaderModules.Clear(); + lock (MeshTaskModuleGate) + { + if (_meshTaskModule.Handle != 0) _vk.DestroyShaderModule(_device, _meshTaskModule, null); + _meshTaskModule = default; + } + _rectangleStageCode.Clear(); _shaderModuleCacheIdentities.Clear(); } diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.RecordingHost.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.RecordingHost.cs index a768cd29b..1893151f6 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.RecordingHost.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.RecordingHost.cs @@ -66,6 +66,7 @@ public RecordingHost(Presenter presenter, bool worker = false) { _spareBuffers = new ConcurrentBag(); _arena = new SliceArena(presenter._arenaPool!, _deviceInfo.NonCoherentAtomSize); + _sliceDescriptors = new SliceDescriptorHeap(_deviceInfo, presenter._descriptorPoolStock!); _hazards = new SliceHazards(); _workerRecorder = presenter._translation.CreateWorkerRecorder(this); } diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.RenderLoop.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.RenderLoop.cs index f4f8a6e35..fd2710eef 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.RenderLoop.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.RenderLoop.cs @@ -352,7 +352,8 @@ private void RenderCore() } if (acquireResult == Result.Timeout) { - ReleaseUnsubmittedPresentationResources( + DropPresentationAfterAcquireTimeout( + in presentation, frameSlot, ownsPresentedGuestImageVersion, presentedGuestImage); diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs index f6fbd599c..c86a3a55f 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs @@ -145,6 +145,11 @@ public void Dispose() } owner._preparation = null; + if (!owner._worker) + { + owner._bufferCache.EndPreparation(); + } + owner._preparedTextures.Clear(); try { @@ -471,8 +476,14 @@ public ulong UploadMeshVertexIndices(ReadOnlySpan indices) throw Serial("mesh index upload", resumable: true); } + return UploadHostBufferAddress(System.Runtime.InteropServices.MemoryMarshal.AsBytes(indices), "mesh index buffer"); + } + + // A host buffer of the open preparation holds bytes that a shader reads through their device address; the draw + // that consumes them retires it. + private ulong UploadHostBufferAddress(ReadOnlySpan bytes, string label) + { var preparation = RequirePreparation(); - var bytes = System.Runtime.InteropServices.MemoryMarshal.AsBytes(indices); var buffer = _presenter.CreateHostBuffer(bytes, BufferUsageFlags.StorageBufferBit | BufferUsageFlags.ShaderDeviceAddressBit, out var memory, out _); @@ -483,7 +494,7 @@ public ulong UploadMeshVertexIndices(ReadOnlySpan indices) Buffer = buffer, }; var address = _vk.GetBufferDeviceAddress(_device, &addressInfo); - if (address == 0) throw new InvalidOperationException("The mesh index buffer has no device address."); + if (address == 0) throw new InvalidOperationException($"The {label} has no device address."); return address; } @@ -607,6 +618,8 @@ public IResourcePreparation BeginPreparation() EnsureGuestSubmissionCapacity(); EnsureBatchedGuestCommands(); _preparation = (_sparePreparation ??= new RenderPreparation(this)).Open(_bufferCache.GetUtilityBuffer(GpuBufferUsage.Stream).RetainUpcomingAllocations()); + // An owner merged while the scope is open retires only after it closes: the scope's bindings may still name it. + _bufferCache.BeginPreparation(); return _preparation; } @@ -711,9 +724,10 @@ private void RecordStageTextureTransitions(TextureResource[] bindings) var view = binding.Request.View; var range = new SubresourceRange(view.BaseLevel, view.LevelCount, view.BaseLayer, view.LayerCount); var storage = binding.IsStorage; + ref var imageBinding = ref BindingOf(image); if (ImageDescription.IsEmptyRange(image.Description.Data)) { - TransitionImage(image, storage || image.Binding.ShaderWrite ? AccessFlags.ShaderReadBit | AccessFlags.ShaderWriteBit : AccessFlags.ShaderReadBit, range, command); + TransitionImage(image, storage || imageBinding.ShaderWrite ? AccessFlags.ShaderReadBit | AccessFlags.ShaderWriteBit : AccessFlags.ShaderReadBit, range, command); } else if (depthImage is not null && ReferenceEquals(image, depthImage)) { @@ -736,9 +750,9 @@ private void RecordStageTextureTransitions(TextureResource[] bindings) : 0; TransitionImage(image, AccessFlags.ShaderReadBit | attachmentAccess, range, command); } - else if ((image.Binding.ForceGeneral || image.Binding.IsTarget) && !image.Description.IsDepth) + else if ((imageBinding.ForceGeneral || imageBinding.IsTarget) && !image.Description.IsDepth) { - var storageAccess = image.Binding.ShaderWrite ? AccessFlags.ShaderWriteBit : 0; + var storageAccess = imageBinding.ShaderWrite ? AccessFlags.ShaderWriteBit : 0; TransitionImage(image, AccessFlags.ShaderReadBit | storageAccess | AccessFlags.ColorAttachmentReadBit | AccessFlags.ColorAttachmentWriteBit, null, @@ -995,12 +1009,51 @@ public void SetDynamicState(in DynamicDrawState state) } } - if (state.DepthBoundsTestEnabled && _presenter._supportsDepthBounds && (!known || !last.DepthBoundsTestEnabled || - state.DepthMinBounds != last.DepthMinBounds || state.DepthMaxBounds != last.DepthMaxBounds)) + // Pipelines built from libraries keep the stencil test, the stencil operations and the depth bounds test dynamic. + if (!known || state.StencilTestEnabled != last.StencilTestEnabled) + { + using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.VulkanCommands)) + { + _vk.CmdSetStencilTestEnable(command, state.StencilTestEnabled); + } + } + + if (!known || state.FrontStencilOperations != last.FrontStencilOperations) { + var front = state.FrontStencilOperations; using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.VulkanCommands)) { - _vk.CmdSetDepthBounds(command, state.DepthMinBounds, state.DepthMaxBounds); + _vk.CmdSetStencilOp(command, StencilFaceFlags.FaceFrontBit, front.FailOperation, front.PassOperation, front.DepthFailOperation, front.Compare); + } + } + + if (!known || state.BackStencilOperations != last.BackStencilOperations) + { + var back = state.BackStencilOperations; + using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.VulkanCommands)) + { + _vk.CmdSetStencilOp(command, StencilFaceFlags.FaceBackBit, back.FailOperation, back.PassOperation, back.DepthFailOperation, back.Compare); + } + } + + if (_presenter._supportsDepthBounds) + { + if (!known || state.DepthBoundsTestEnabled != last.DepthBoundsTestEnabled) + { + using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.VulkanCommands)) + { + _vk.CmdSetDepthBoundsTestEnable(command, state.DepthBoundsTestEnabled); + } + } + + // The bounds only matter while the test is on. + if (state.DepthBoundsTestEnabled && (!known || !last.DepthBoundsTestEnabled || + state.DepthMinBounds != last.DepthMinBounds || state.DepthMaxBounds != last.DepthMaxBounds)) + { + using (RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.VulkanCommands)) + { + _vk.CmdSetDepthBounds(command, Math.Clamp(state.DepthMinBounds, 0f, 1f), Math.Clamp(state.DepthMaxBounds, 0f, 1f)); + } } } @@ -1546,7 +1599,28 @@ public bool TryDispatchIndirect(ulong argumentsAddress, ReadOnlySpan physic var (obtainedBuffer, offset) = _worker ? ObtainBufferForSlice(argumentsAddress, 3u * sizeof(uint), isWritten: false, isTexelBuffer: false) : _bufferCache.ObtainBuffer(argumentsAddress, 3u * sizeof(uint), false); - var buffer = obtainedBuffer.Handle; + RecordIndirectDispatch(obtainedBuffer.Handle, offset, physicalAxisOfLogical); + return true; + } + + // The arguments were registered before the stage's resources (PrepareIndirectDispatchArguments), so the dispatch + // acquires no guest range here: an acquisition after binding could merge an owner the shader already writes. + public bool TryDispatchIndirect(IIndirectDispatchArguments arguments, ReadOnlySpan physicalAxisOfLogical) + { + if (arguments is SliceDispatchArguments slice) + { + return TryDispatchIndirect(slice.Address, physicalAxisOfLogical); + } + + using var profileScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.DrawRecording); + var binding = ((PreparedDispatchArguments)arguments).Use(); + RecordIndirectDispatch(new VkBuffer(binding.Handle), binding.Offset, physicalAxisOfLogical); + return true; + } + + private void RecordIndirectDispatch(VkBuffer buffer, ulong offset, ReadOnlySpan physicalAxisOfLogical) + { + var permuted = physicalAxisOfLogical is not [0, 1, 2]; var permutedArguments = permuted ? UploadTransient(stackalloc byte[3 * sizeof(uint)], 16) : default; var command = BeginBatchedGuestCommands(); var barrier = new BufferMemoryBarrier2 @@ -1589,7 +1663,6 @@ public bool TryDispatchIndirect(ulong argumentsAddress, ReadOnlySpan physic } CountDraw(); NoteShaderMayWriteMappedMemory(); - return true; } internal static readonly bool BatchBarriers = @@ -1620,6 +1693,7 @@ private void RecordMemoryBarrier(PipelineStageFlags sourceStages, PipelineStageF VulkanSynchronization.PipelineBarrier(_vk,command, sourceStages, destinationStages, 0, 1, &barrier, 0, null, 0, null, BarrierSource.Requested); } + // A task stage reads the automatic indirect arguments of task-launched mesh draws (MeshTaskLaunch). public void ShaderWriteBarrier(PipelineStageFlags sourceStages) { NoteShaderMayWriteMappedMemory(); @@ -1627,7 +1701,11 @@ public void ShaderWriteBarrier(PipelineStageFlags sourceStages) sourceStages, PipelineStageFlags.ComputeShaderBit | PipelineStageFlags.VertexInputBit | PipelineStageFlags.VertexShaderBit | PipelineStageFlags.FragmentShaderBit | PipelineStageFlags.TransferBit | PipelineStageFlags.ColorAttachmentOutputBit | - (_presenter._supportsMeshShader ? PipelineStageFlags.MeshShaderBitExt : PipelineStageFlags.None), + (_presenter._supportsMeshShader ? PipelineStageFlags.MeshShaderBitExt : PipelineStageFlags.None) | + (_presenter._supportsTaskShader ? PipelineStageFlags.TaskShaderBitExt : PipelineStageFlags.None) | + (_presenter._supportsTessellation + ? PipelineStageFlags.TessellationControlShaderBit | PipelineStageFlags.TessellationEvaluationShaderBit + : PipelineStageFlags.None), AccessFlags.ShaderWriteBit, AccessFlags.ShaderReadBit | AccessFlags.ShaderWriteBit | AccessFlags.VertexAttributeReadBit | AccessFlags.IndexReadBit | AccessFlags.UniformReadBit | AccessFlags.TransferReadBit | AccessFlags.TransferWriteBit | diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Scheduler.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Scheduler.cs index 00b6cdd54..16543d91d 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Scheduler.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Scheduler.cs @@ -114,11 +114,14 @@ private void CreateBufferCache() } } - // The image store follows the buffer store; readback of linear images stays off. + // The image store follows the buffer store. A guest can read a linear image the GPU wrote on the CPU, such as + // an occlusion buffer a compute shader fills, so linear images the GPU writes are read back to guest memory; + // SHARPEMU_READBACK_LINEAR_IMAGES=0 turns that readback off. private void CreateImageCache() { var (memory, _, backing) = RequireGuestMemory("image store"); - _imageCache = new GuestImageCache(_deviceInfo, _scheduler, memory.Pages, _bufferCache, backing, readbackLinearImages: false); + _imageCache = new GuestImageCache(_deviceInfo, _scheduler, memory.Pages, _bufferCache, backing, + readbackLinearImages: Environment.GetEnvironmentVariable("SHARPEMU_READBACK_LINEAR_IMAGES") != "0"); _bufferCache.ImageCache = _imageCache; _samplerStore = new SamplerStore(_deviceInfo); } diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.ShaderPrewarm.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.ShaderPrewarm.cs index 2df6a5527..05fcc1ae2 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.ShaderPrewarm.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.ShaderPrewarm.cs @@ -8,7 +8,6 @@ namespace SharpEmu.Libs.VideoOut; using SharpEmu.Libs.Gpu; using SharpEmu.Libs.Gpu.Pipelines; using SharpEmu.Libs.Gpu.Rendering; -using SharpEmu.Libs.Gpu.Scheduling; using SharpEmu.ShaderCompiler; using SharpEmu.ShaderCompiler.Resources; using SharpEmu.ShaderCompiler.Vulkan; @@ -28,12 +27,16 @@ private sealed record ShaderPrewarmCompletion(string StampPath, string CoverageS private ShaderPrewarmList? _shaderPrewarmList; private ConcurrentDictionary? _prewarmedShaderIdentities; private ConcurrentDictionary? _runtimeComputeIdentities; - private Thread[] _shaderPrewarmThreads = []; + private PrewarmPool? _prewarmPool; private volatile bool _shaderPrewarmStopping; private volatile bool _shaderPrewarmFinished; private int _shaderPrewarmCompiled; private int _shaderPrewarmFailed; private int _shaderPrewarmRuntimeHits; + private int _shaderPrewarmDroppedLinked; + // The background lane of the recorded linked permutations (StartLinkedPrewarm); teardown joins it. + private Thread? _linkedPrewarmThread; + // The splash's warm-up view: the items each kind has done and holds, every lane's threads, and the start. private int _shaderPrewarmComputeDone; private int _shaderPrewarmComputeTotal; private int _shaderPrewarmGraphicsDone; @@ -41,13 +44,33 @@ private sealed record ShaderPrewarmCompletion(string StampPath, string CoverageS private int _shaderPrewarmWorkers; private long _shaderPrewarmStarted; private Func? _shaderPrewarmProgressView; - private readonly ConcurrentQueue _shaderPrewarmCompleted = new(); + // The stage programs of the whole pipelines the prewarm builds (StartPipelinePrewarm), each compiled once. private readonly ConcurrentDictionary> _prewarmStages = new(); private readonly ConcurrentBag _prewarmStageModules = []; private sealed record PrewarmedStage(ShaderProgram Handle, ShaderProgramInfo Program); - private readonly record struct PrewarmWork(ComputePrewarmRecord? Compute, ShaderCodeCapture? Code, GraphicsPrewarmItem? Graphics); + // SHARPEMU_PREWARM_BINARY_SKIP (on by default; =0 turns it off): with pipeline binaries on, the graphics prewarm builds + // only the items that no prewarm under the current build stamp completed yet (ShaderPrewarmList progress), and none when + // every item is listed. Each listed item was built through CreatePipelineWithBinaries, which stored its binaries when the + // build took the store threshold (PipelineBinaryStorePolicy) or longer, and the session's own creation loads them. A + // session records a few new items each time, so the next prewarm builds those alone. The progress is keyed by the build + // stamp alone (the translator and compiler assemblies, the device and the translation switches), not by the coverage + // stamp, which also hashes the recorded list and so changes with every session. A new build prewarms every item once. + // The compute prewarm does not skip this way: the translation cache serves its translations and the session takes the + // pipelines it builds, so it runs every session unless CanSkipShaderPrewarm certifies the whole cache (a list without + // linked records whose cache and recording stamps match); skipping it otherwise moves its pipelines to first use. + private static readonly bool PrewarmBinarySkip = Environment.GetEnvironmentVariable("SHARPEMU_PREWARM_BINARY_SKIP") != "0"; + + // A linked permutation can be a whole-module compile of many minutes and gigabytes of driver memory, so the prewarm the + // game waits for leaves the recorded ones out. By default they compile on a background thread the game does not wait + // for (StartLinkedPrewarm); SHARPEMU_PREWARM_LINKED=all compiles them with the rest of the prewarm, =none not at all. + private static readonly string PrewarmLinked = Environment.GetEnvironmentVariable("SHARPEMU_PREWARM_LINKED") switch + { + null or "" or "background" => "background", + "none" => "none", + _ => "all", + }; ShaderPrewarmList? IShaderPipelineHost.ShaderPrewarm => Volatile.Read(ref _shaderPrewarmList); @@ -57,6 +80,9 @@ private void StartShaderPrewarm() { SetShaderPrewarmState(false); } + + // The pool's threads begin once every lane is in. + _prewarmPool?.Start(); } private bool StartShaderPrewarmCore() @@ -83,8 +109,14 @@ _pipelineCacheShardDirectory is not null || Volatile.Write(ref _shaderPrewarmList, list); var compiler = GuestGpu.Current; - var stamp = list.CoverageStamp(ShaderPrewarmStamp(compiler)); - if (list.LoadedComputeCount == 0 && list.LoadedGraphicsCount == 0) + var buildStamp = ShaderPrewarmStamp(compiler); + // Whole pipelines serve a device that creates whole pipelines. With pipeline libraries the session links the parts + // the graphics prewarm stores (StartGraphicsPrewarm) and would never take a whole pipeline built here. + var pipelines = !_graphicsPipelineLibraries; + var stamp = list.CoverageStamp(buildStamp, pipelines); + StartGraphicsPrewarm(list, buildStamp, compiler); + var pipelineCount = pipelines ? list.LoadedPipelineCount : 0; + if (list.LoadedComputeCount == 0 && pipelineCount == 0) { _loadedPrewarmCache = []; _shaderPrewarmFinished = true; @@ -97,94 +129,253 @@ _pipelineCacheShardDirectory is not null || _loadedPrewarmCache = []; _shaderPrewarmFinished = true; Console.Error.WriteLine( - $"[LOADER][INFO] Shader prewarm skipped: compute={list.LoadedComputeCount} graphics={list.LoadedGraphicsCount} " + + $"[LOADER][INFO] Shader prewarm skipped: compute={list.LoadedComputeCount} graphics={pipelineCount} " + "reason=cache-and-recording-match"); return false; } _loadedPrewarmCache = []; - // Progress alone does not prove that the saved cache contains those pipelines. - list.ClearProgress(); - var computes = list.LoadedComputes(); - var graphics = list.LoadedGraphics(); - Interlocked.Add(ref _shaderPrewarmFailed, - list.LoadedComputeCount - computes.Count + list.LoadedGraphicsCount - graphics.Count); + IReadOnlyList<(ComputePrewarmRecord Record, ShaderCodeCapture Code, float StartBy)> pending = list.LoadedComputeStarts(); + var missingCode = list.LoadedComputeCount - pending.Count; + if (PrewarmLinked != "all") + { + var plain = pending.Where(static item => item.Record.Linked is null).ToList(); + if (PrewarmLinked == "background") + { + StartLinkedPrewarm(list, [.. pending.Where(static item => item.Record.Linked is not null) + .Select(static item => (item.Record, item.Code))], compiler); + } + else + { + Volatile.Write(ref _shaderPrewarmDroppedLinked, pending.Count - plain.Count); + } + + pending = plain; + } + + IReadOnlyList graphics = pipelines ? list.LoadedPipelines() : []; + Interlocked.Add(ref _shaderPrewarmFailed, missingCode + pipelineCount - graphics.Count); var started = Stopwatch.GetTimestamp(); - var pendingCount = computes.Count + graphics.Count; - if (pendingCount == 0) + if (pending.Count == 0 && graphics.Count == 0) { FinishShaderPrewarm(list, stamp, started); return false; } - var work = new ConcurrentQueue( - graphics.Select(static item => new PrewarmWork(null, null, item)) - .Concat(computes.Select(static item => new PrewarmWork(item.Record, item.Code, null)))); - var workerCount = Math.Clamp(Environment.ProcessorCount / 2, 1, 8); - var remaining = workerCount; + var work = new ShaderPrewarmQueue<(ComputePrewarmRecord Record, ShaderCodeCapture Code, float StartBy)>(pending, + static item => item.Record.Linked is null ? null : item.Record.Hash); + var workerCount = Math.Clamp(Environment.ProcessorCount / 4, 1, 4); var host = (IShaderPipelineHost)this; var sharedInt64Atomics = host.SharedInt64AtomicsEnabled; var execGuardElision = host.ExecGuardElisionEnabled; - Volatile.Write(ref _shaderPrewarmTotal, pendingCount); + // The game waits until the compute records and the whole pipelines are done: the last lane to end finishes. + var lanes = (pending.Count != 0 ? 1 : 0) + (graphics.Count != 0 ? 1 : 0); + void FinishLane() + { + if (Interlocked.Decrement(ref lanes) == 0) + { + FinishShaderPrewarm(list, stamp, started); + } + } + + Volatile.Write(ref _shaderPrewarmTotal, pending.Count + graphics.Count); Volatile.Write(ref _shaderPrewarmProgress, 0); - Volatile.Write(ref _shaderPrewarmComputeTotal, computes.Count); - Volatile.Write(ref _shaderPrewarmGraphicsTotal, graphics.Count); - Volatile.Write(ref _shaderPrewarmWorkers, workerCount); + Volatile.Write(ref _shaderPrewarmComputeTotal, pending.Count); + Interlocked.Add(ref _shaderPrewarmGraphicsTotal, graphics.Count); + Interlocked.Add(ref _shaderPrewarmWorkers, pending.Count != 0 ? workerCount : 0); _shaderPrewarmStarted = started; _shaderPrewarmProgressView = ShaderPrewarmProgressView; ShowShaderCacheProgress(_shaderPrewarmProgressView); Console.Error.WriteLine( - $"[LOADER][INFO] Shader prewarm started: compute={computes.Count} graphics={graphics.Count} resumed=0 workers={workerCount}"); + $"[LOADER][INFO] Shader prewarm started: compute={pending.Count} graphics={graphics.Count} workers={workerCount} " + + $"dropped_linked={Volatile.Read(ref _shaderPrewarmDroppedLinked)}"); SetShaderPrewarmState(true); - _shaderPrewarmThreads = new Thread[workerCount]; - for (var index = 0; index < workerCount; index++) + if (pending.Count != 0) { - _shaderPrewarmThreads[index] = new Thread(() => - { - SubmissionScheduler.ThrowOnFatal = true; - while (!_shaderPrewarmStopping && work.TryDequeue(out var item)) + PrewarmWorkers.Add(new PrewarmPool.Lane(pending.Count, + (out float start) => { - if (item.Graphics is { } pipeline) + var any = work.TryPeek(out var next); + start = any ? next.StartBy : 0; + return any; + }, + mayWait => + { + if (!work.TryTake(() => _shaderPrewarmStopping, out var item, out var gate, mayWait)) { - if (PrewarmGraphicsPipeline(pipeline, compiler)) - { - _shaderPrewarmCompleted.Enqueue(pipeline.Identity); - } + return false; + } - Interlocked.Increment(ref _shaderPrewarmGraphicsDone); + bool compiled; + var began = Stopwatch.GetTimestamp(); + try + { + compiled = PrewarmComputePipeline(item.Record, item.Code, compiler, sharedInt64Atomics, execGuardElision); + } + finally + { + work.Release(gate); } - else + + if (compiled) + { + list.RecordComputeCost(item.Record, (float)Stopwatch.GetElapsedTime(began).TotalSeconds); + } + + Interlocked.Increment(ref _shaderPrewarmComputeDone); + Interlocked.Increment(ref _shaderPrewarmProgress); + return true; + }, + FinishLane), + workerCount, "SharpEmu shader prewarm"); + } + + if (graphics.Count != 0) + { + StartPipelinePrewarm(graphics, compiler, FinishLane); + } + + return true; + } + + // The compute and graphics prewarms share one pool of below-normal threads. + private PrewarmPool PrewarmWorkers => _prewarmPool ??= new PrewarmPool(() => _shaderPrewarmStopping); + + // The whole pipelines sessions created (RecordGraphics), built again with their stage programs. Each one goes to the + // device pipeline cache, where the session's creation of the same pipeline finds the driver's compile; the stage + // programs and their modules go when the lane ends. + private void StartPipelinePrewarm(IReadOnlyList items, IGuestGpuBackend compiler, Action finished) + { + var work = new ConcurrentQueue(items); + var workerCount = Math.Clamp(Environment.ProcessorCount / 4, 1, 4); + Interlocked.Add(ref _shaderPrewarmWorkers, workerCount); + PrewarmWorkers.Add(new PrewarmPool.Lane(items.Count, + (out float start) => + { + // Sessions do not time a whole pipeline's first use: it is due as an untimed compute record is (StartBy). + start = float.PositiveInfinity; + return !work.IsEmpty; + }, + _ => + { + if (!work.TryDequeue(out var item)) + { + return false; + } + + PrewarmGraphicsPipeline(item, compiler); + Interlocked.Increment(ref _shaderPrewarmGraphicsDone); + Interlocked.Increment(ref _shaderPrewarmProgress); + return true; + }, + () => + { + ReleasePrewarmStages(); + finished(); + }), + workerCount, "SharpEmu pipeline prewarm"); + } + + // The linked permutations earlier sessions recorded, compiled on below-normal threads the game does not wait for. The + // driver can spend minutes on one, and a compile the session starts at the caller's first dispatch can still be + // running when the session ends: then nothing is stored, and every session skips the caller's dispatches as long. + // Started at boot, a permutation is stored when it finishes (its pipeline binaries, or the caller's linked cache), and + // the session's request for the same module waits for that compile and loads its result instead of compiling it + // beside it (the pipeline build gate and LinkedCompileAdmission). Each compile waits for its admission like the + // session's own. The order is ShaderPrewarmQueue.LinkedLaneOrder: each caller's first record is the one its session + // asks for first, since a session that asks for another large module waits for the lane's compile and then compiles + // its own. With cores to spare a second worker takes the next record whose caller the first is not compiling (the + // permutations of one caller share its linked cache file), so callers that compile in a minute or two are ready + // before the session reaches them instead of waiting behind a caller that compiles for several minutes; while they + // wait, the session skips their dispatches and draws without their results. + private void StartLinkedPrewarm(ShaderPrewarmList list, + IReadOnlyList<(ComputePrewarmRecord Record, ShaderCodeCapture Code)> records, IGuestGpuBackend compiler) + { + if (records.Count == 0) + { + return; + } + + var host = (IShaderPipelineHost)this; + var sharedInt64Atomics = host.SharedInt64AtomicsEnabled; + var execGuardElision = host.ExecGuardElisionEnabled; + var workers = ShaderPrewarmQueue<(ComputePrewarmRecord Record, ShaderCodeCapture Code)>.LinkedLaneWorkers( + Environment.ProcessorCount); + var thread = new Thread(() => + { + var started = Stopwatch.GetTimestamp(); + // Read here, off the boot path: the store decodes every kept callee. + var keptCallees = ShaderCallUnionStore.Open(); + var firstAsked = records.Where(item => item.Record.Linked is { } linked && + keptCallees.KeepsCalleesOf(ShaderStage.Compute, item.Record.Hash, linked)) + .Select(static item => item.Record).ToHashSet(ReferenceEqualityComparer.Instance); + var ordered = ShaderPrewarmQueue<(ComputePrewarmRecord Record, ShaderCodeCapture Code)>.LinkedLaneOrder( + records, static item => item.Record.Hash, list.IsSlowLinkedCompile, item => firstAsked.Contains(item.Record)); + Console.Error.WriteLine( + $"[LOADER][INFO] Linked prewarm started: permutations={ordered.Length} workers={workers} callers=" + + string.Join(',', ordered.GroupBy(static item => item.Record.Hash).Select(group => + $"0x{group.Key:X16}x{group.Count()}{(list.IsSlowLinkedCompile(group.Key) ? "(slow)" : "")}" + + $"{(group.Any(item => firstAsked.Contains(item.Record)) ? "(kept)" : "")}"))); + var queue = new ShaderPrewarmQueue<(ComputePrewarmRecord Record, ShaderCodeCapture Code)>( + ordered, static item => item.Record.Hash, keepOrder: true); + var compiled = 0; + void Work() + { + while (queue.TryTake(() => _shaderPrewarmStopping, out var item, out var gate)) + { + try { - if (PrewarmComputePipeline(item.Compute!, item.Code!, compiler, sharedInt64Atomics, execGuardElision)) + var (record, code) = item; + var began = Stopwatch.GetTimestamp(); + if (!PrewarmComputePipelineCore(record, code, compiler, sharedInt64Atomics, execGuardElision, + waitForAdmission: true)) { - _shaderPrewarmCompleted.Enqueue(ShaderPrewarmList.Identity(item.Compute!)); + continue; } - Interlocked.Increment(ref _shaderPrewarmComputeDone); + Interlocked.Increment(ref compiled); + var seconds = Stopwatch.GetElapsedTime(began).TotalSeconds; + list.RecordComputeCost(record, (float)seconds); + Console.Error.WriteLine( + $"[LOADER][INFO] Linked prewarm compiled: hash=0x{record.Hash:X16} " + + $"callees={record.Linked?.Functions.Length ?? 0} seconds={seconds:F1}"); } - - if (Interlocked.Increment(ref _shaderPrewarmProgress) % PrewarmProgressBatch == 0) + finally { - FlushShaderPrewarmProgress(list, stamp); + queue.Release(gate); } } + } - FlushShaderPrewarmProgress(list, stamp); - if (Interlocked.Decrement(ref remaining) == 0) + var helpers = new Thread[workers - 1]; + for (var index = 0; index < helpers.Length; index++) + { + helpers[index] = new Thread(Work) { - ReleasePrewarmStages(); - FinishShaderPrewarm(list, stamp, started); - } - }) + IsBackground = true, + Priority = ThreadPriority.BelowNormal, + Name = $"SharpEmu linked prewarm {index + 2}", + }; + helpers[index].Start(); + } + + Work(); + foreach (var helper in helpers) { - IsBackground = true, - Priority = ThreadPriority.BelowNormal, - Name = $"SharpEmu shader prewarm {index}", - }; - _shaderPrewarmThreads[index].Start(); - } + helper.Join(); + } - return true; + Console.Error.WriteLine( + $"[LOADER][INFO] Linked prewarm {(_shaderPrewarmStopping ? "stopped" : "done")}: compiled={Volatile.Read(ref compiled)} " + + $"of {ordered.Length} seconds={Stopwatch.GetElapsedTime(started).TotalSeconds:F0}"); + }) + { + IsBackground = true, + Priority = ThreadPriority.BelowNormal, + Name = "SharpEmu linked prewarm", + }; + _linkedPrewarmThread = thread; + thread.Start(); } private ShaderCacheProgressView ShaderPrewarmProgressView() => new( @@ -197,7 +388,8 @@ _pipelineCacheShardDirectory is not null || Volatile.Read(ref _shaderPrewarmGraphicsDone), Volatile.Read(ref _shaderPrewarmGraphicsTotal)), ], [ - $"Warmed {Volatile.Read(ref _shaderPrewarmCompiled)} / Failed {Volatile.Read(ref _shaderPrewarmFailed)}", + $"Warmed {Volatile.Read(ref _shaderPrewarmCompiled) + Volatile.Read(ref _graphicsPrewarmCompiled)} / " + + $"Failed {Volatile.Read(ref _shaderPrewarmFailed) + Volatile.Read(ref _graphicsPrewarmFailed)}", string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{Volatile.Read(ref _shaderPrewarmWorkers)} workers / {Stopwatch.GetElapsedTime(_shaderPrewarmStarted).TotalSeconds:F0} seconds"), ], @@ -211,19 +403,9 @@ private void EndShaderPrewarmProgress() } } - private void FlushShaderPrewarmProgress(ShaderPrewarmList list, string stamp) - { - var batch = new List(); - while (_shaderPrewarmCompleted.TryDequeue(out var identity)) - { - batch.Add(identity); - } - - list.AppendProgress(stamp, batch); - } - private static bool CanSkipShaderPrewarm(ShaderPrewarmList list, string stamp, byte[] cache) => - cache.Length != 0 && list.IsStampCurrent(ShaderPrewarmList.CacheStamp(stamp, cache)); + cache.Length != 0 && !list.HasLinkedComputes && + list.IsStampCurrent(ShaderPrewarmList.CacheStamp(stamp, cache)); private static string ShaderPrewarmStampPart(Type type) => type.Assembly.ManifestModule.ModuleVersionId.ToString("N"); @@ -247,6 +429,7 @@ private string BuildShaderPrewarmStamp(Type compilerType, string driverSignature ((IShaderPipelineHost)this).SharedInt64AtomicsEnabled, ((IShaderPipelineHost)this).ExecGuardElisionEnabled, _supportsShaderSignedZeroInfNanPreserveFloat32, + _nativeFloat16Conversions, SharpEmu.HLE.GpuMemory.GuestGpuMemoryHook.TraceEnabled, Volatile.Read(ref _nativeSubgroupSize), _canRequireComputeSubgroup32, @@ -260,21 +443,40 @@ private string BuildShaderPrewarmStamp(Type compilerType, string driverSignature Environment.GetEnvironmentVariable("SHARPEMU_STRUCTURED_FORWARD_BLOCKS"), Environment.GetEnvironmentVariable("SHARPEMU_EXEC_GUARD_ELISION"), Environment.GetEnvironmentVariable("SHARPEMU_EXEC_SELECT_ELIMINATION"), + Environment.GetEnvironmentVariable("SHARPEMU_DEFERRED_EXEC_GUARDS"), + Environment.GetEnvironmentVariable("SHARPEMU_PREWARM_LINKED"), driverSignature.TrimEnd('\n')); + // Different permutations of one caller write the same linked cache file: the prewarm's queue (ShaderPrewarmQueue) + // gives each caller's records to one worker at a time. private bool PrewarmComputePipeline( ComputePrewarmRecord record, ShaderCodeCapture code, IGuestGpuBackend compiler, bool sharedInt64Atomics, - bool execGuardElision) + bool execGuardElision) => + PrewarmComputePipelineCore(record, code, compiler, sharedInt64Atomics, execGuardElision, waitForAdmission: false); + + private bool PrewarmComputePipelineCore( + ComputePrewarmRecord record, + ShaderCodeCapture code, + IGuestGpuBackend compiler, + bool sharedInt64Atomics, + bool execGuardElision, + bool waitForAdmission) { if (!ShaderProgramCache.TryCompilePrewarm( record, code, compiler, sharedInt64Atomics, execGuardElision, _supportsShaderSignedZeroInfNanPreserveFloat32, out var compiled, out var layout, out var error, - ((IShaderPipelineHost)this).ComputeWave64SubgroupNative, - ((IShaderPipelineHost)this).ComputeRunsOn32LaneSubgroups(record.Info), - ImageInt64AtomicsEnabled, + hostWave64Supported: ((IShaderPipelineHost)this).ComputeWave64SubgroupNative, + hostComputeSubgroup32: ((IShaderPipelineHost)this).ComputeRunsOn32LaneSubgroups(record.Info), + imageInt64Atomics: ImageInt64AtomicsEnabled, + shaderDeviceClock: ShaderDeviceClockEnabled, + bindlessHeap: _bindlessHeapSupported, + stableImageLimits: ((IShaderPipelineHost)this).ComputeImageDescriptorLimits, + bufferInt64Atomics: BufferInt64AtomicsEnabled, + robustBufferAccess2: _robustBufferAccess2Enabled, + nativeFloat16Conversions: _nativeFloat16Conversions, frontendOf: Agc.AgcExports.ShaderFrontendForDomain)) { NoteShaderPrewarmFailure("cs", record.Hash, record.Address, error); @@ -286,15 +488,53 @@ private bool PrewarmComputePipeline( DescriptorSetLayout setLayout = default; PipelineLayout pipelineLayout = default; ShaderModule module = default; + Pipeline pipeline = default; + DriverCacheShard? linkedCache = null; + var created = false; + // A linked record compiles only once the admission of the session's linked compiles (LinkedCompileAdmission) + // admits it, so the prewarm's linked compiles keep to the same commit budget. The prewarm the game waits for + // takes only an admission given at once, so none of its threads waits behind the session's, and drops the record + // otherwise; the background lane (StartLinkedPrewarm) waits for it. The try that releases the admission follows + // at once. + var linked = layout!.CallTargetCount != 0; + if (linked && !WaitForLinkedAdmission(record.Hash, payload.Length, mayWait: waitForAdmission)) + { + Interlocked.Increment(ref _shaderPrewarmDroppedLinked); + return false; + } + try { - CollectLayoutBindings(bindings, layout!, ShaderStage.Compute); - setLayout = CreateDescriptorSetLayout(bindings, out _, out _); - pipelineLayout = CreatePipelineLayout(setLayout, ShaderStageFlags.ComputeBit, layout!.UsesBindlessHeap); + // An admission can come after teardown began; a compile that cannot be cancelled must not start then. + if (linked && _shaderPrewarmStopping) + { + return false; + } + + CollectLayoutBindings(bindings, layout, ShaderStage.Compute); + setLayout = CreateDescriptorSetLayout(bindings, out var usesPushDescriptors, out _); + pipelineLayout = CreatePipelineLayout(setLayout, ShaderStageFlags.ComputeBit, layout.UsesBindlessHeap); module = CreateShaderModule(payload); - var pipeline = CompileComputePipeline(_vk, _device, _pipelineCache, module, pipelineLayout, ComputeRequiredSubgroupSize(record.Info)); - _vk.DestroyPipeline(_device, pipeline, null); - _prewarmedShaderIdentities![VulkanPipelineCacheStorage.CompiledShaderIdentity(payload)] = 0; + linkedCache = linked ? CreateLinkedPipelineCache(record.Hash) : null; + var cache = ResolveGuestPipelineCache(linkedCache?.Cache); + var identity = VulkanPipelineCacheStorage.CompiledShaderIdentity(payload); + var requiredSubgroupSize = ComputeRequiredSubgroupSize(record.Info); + pipeline = CompileComputePipeline(_vk, _device, cache, module, pipelineLayout, requiredSubgroupSize); + created = true; + // A plain record's pipeline waits, with the layouts it was compiled with, for the session's request (a + // linked one goes: the session links the callees its own program kept). The handover owns what it took; + // finally destroys the rest. + if (!linked && _prewarmedComputePipelines.TryAdd( + ComputeHandoverKey(identity, SetSignature(bindings, usesPushDescriptors), layout.UsesBindlessHeap, + requiredSubgroupSize), + new PrewarmedComputePipeline(pipeline, setLayout, pipelineLayout))) + { + pipeline = default; + setLayout = default; + pipelineLayout = default; + } + + _prewarmedShaderIdentities![identity] = 0; Interlocked.Increment(ref _shaderPrewarmCompiled); return true; } @@ -305,6 +545,17 @@ private bool PrewarmComputePipeline( } finally { + if (linked) + { + ReleaseLinkedAdmission(payload.Length); + } + + if (pipeline.Handle != 0) + { + _vk.DestroyPipeline(_device, pipeline, null); + } + + ReleaseLinkedPipelineCache(linkedCache, record.Hash, save: created); if (module.Handle != 0) { _vk.DestroyShaderModule(_device, module, null); @@ -322,7 +573,62 @@ private bool PrewarmComputePipeline( } } - private bool PrewarmGraphicsPipeline(GraphicsPrewarmItem item, IGuestGpuBackend compiler) + // The compute prewarm's pipelines, each with the layouts it was compiled with, until the session asks for one + // (TakePrewarmedComputePipeline). The key holds the SHA-256 of the module's SPIR-V, the set layout, whether the layout + // binds the bindless heap and the required subgroup size: everything the pipeline was created from. Teardown destroys + // the ones never asked for (DestroyPrewarmedComputePipelines). + private readonly record struct PrewarmedComputePipeline(Pipeline Pipeline, DescriptorSetLayout SetLayout, PipelineLayout Layout); + + private readonly ConcurrentDictionary _prewarmedComputePipelines = + new(StringComparer.Ordinal); + private int _prewarmedComputeTaken; + + private static string ComputeHandoverKey(string identity, string setSignature, bool bindlessHeap, uint requiredSubgroupSize) => + $"{identity}|{setSignature}|{bindlessHeap}|{requiredSubgroupSize}"; + + // The prewarm's pipeline for this module, set layout, heap and subgroup size, if it built one. + private bool TakePrewarmedComputePipeline(ulong module, List bindings, bool usesPushDescriptors, + bool bindlessHeap, uint requiredSubgroupSize, out PrewarmedComputePipeline prewarmed) + { + prewarmed = default; + if (!_shaderModuleCacheIdentities.TryGetValue(module, out var identity) || !_prewarmedComputePipelines.TryRemove( + ComputeHandoverKey(identity, SetSignature(bindings, usesPushDescriptors), bindlessHeap, requiredSubgroupSize), + out prewarmed)) + { + return false; + } + + Interlocked.Increment(ref _prewarmedComputeTaken); + return true; + } + + private void DestroyPrewarmedComputePipeline(PrewarmedComputePipeline prewarmed) + { + _vk.DestroyPipeline(_device, prewarmed.Pipeline, null); + _vk.DestroyPipelineLayout(_device, prewarmed.Layout, null); + _vk.DestroyDescriptorSetLayout(_device, prewarmed.SetLayout, null); + } + + private void DestroyPrewarmedComputePipelines() + { + var unclaimed = 0; + foreach (var key in _prewarmedComputePipelines.Keys) + { + if (_prewarmedComputePipelines.TryRemove(key, out var prewarmed)) + { + DestroyPrewarmedComputePipeline(prewarmed); + unclaimed++; + } + } + + var taken = Volatile.Read(ref _prewarmedComputeTaken); + if (taken + unclaimed != 0) + { + Console.Error.WriteLine($"[LOADER][INFO] Prewarmed compute pipelines: taken={taken} unclaimed={unclaimed}"); + } + } + + private bool PrewarmGraphicsPipeline(PipelinePrewarmItem item, IGuestGpuBackend compiler) { var vertex = PrewarmStageProgram(item.Vertex, compiler); var pixel = item.Pixel is { } pixelSource ? PrewarmStageProgram(pixelSource, compiler) : null; @@ -441,22 +747,30 @@ private void NoteShaderPrewarmFailure(string kind, ulong hash, ulong address, st } } + // The stage programs of a whole pipeline compile as a session compiles them, with the device's capabilities. private sealed class PrewarmShaderHost(Presenter presenter) : IShaderPipelineHost { private readonly IShaderPipelineHost _inner = presenter; public uint MaxPushDescriptors => _inner.MaxPushDescriptors; + public StableImageDescriptorLimits ComputeImageDescriptorLimits => _inner.ComputeImageDescriptorLimits; + public StableImageDescriptorLimits GraphicsImageDescriptorLimits => _inner.GraphicsImageDescriptorLimits; public bool ComputeWave64Supported => _inner.ComputeWave64Supported; public bool ComputeWave64SubgroupNative => _inner.ComputeWave64SubgroupNative; public bool ComputeRunsOn32LaneSubgroups(ComputeInputInfo input) => _inner.ComputeRunsOn32LaneSubgroups(input); public bool MipStatisticsSubgroupReduction => _inner.MipStatisticsSubgroupReduction; + public bool PixelSubgroupArithmetic => _inner.PixelSubgroupArithmetic; public bool RuntimeCallRecordsSupported => _inner.RuntimeCallRecordsSupported; public bool CallMarksSupported => _inner.CallMarksSupported; public bool TableBlocks => _inner.TableBlocks; public bool GraphicsSubgroupOperationsEnabled => _inner.GraphicsSubgroupOperationsEnabled; public bool SharedInt64AtomicsEnabled => _inner.SharedInt64AtomicsEnabled; + public bool BufferInt64AtomicsEnabled => _inner.BufferInt64AtomicsEnabled; public bool ImageInt64AtomicsEnabled => _inner.ImageInt64AtomicsEnabled; + public bool ShaderDeviceClockEnabled => _inner.ShaderDeviceClockEnabled; public bool ShaderSignedZeroInfNanPreserveFloat32Supported => _inner.ShaderSignedZeroInfNanPreserveFloat32Supported; + public bool RobustBufferAccess2Enabled => _inner.RobustBufferAccess2Enabled; + public bool NativeFloat16Conversions => _inner.NativeFloat16Conversions; public bool ExecGuardElisionEnabled => _inner.ExecGuardElisionEnabled; public bool PerVertexPixelInputsSupported => _inner.PerVertexPixelInputsSupported; public bool ClipDistanceEnabled => _inner.ClipDistanceEnabled; @@ -466,6 +780,7 @@ private sealed class PrewarmShaderHost(Presenter presenter) : IShaderPipelineHos public uint MeshSubgroupSize => _inner.MeshSubgroupSize; public RenderHostLimits Limits => _inner.Limits; public bool SupportsDualSourceBlend => _inner.SupportsDualSourceBlend; + public bool SupportsBindlessHeap => _inner.SupportsBindlessHeap; public SampleCountFlags NoAttachmentSampleCounts => _inner.NoAttachmentSampleCounts; public bool TryResolveColorOutput(uint dataFormat, uint numberType, uint componentSwap, out Gen5PixelOutputKind outputKind, @@ -519,7 +834,8 @@ private void FinishShaderPrewarm(ShaderPrewarmList list, string stamp, long star _pipelineCacheDirty = true; Console.Error.WriteLine( $"[LOADER][INFO] Shader prewarm done: compiled={Volatile.Read(ref _shaderPrewarmCompiled)} " + - $"failed={Volatile.Read(ref _shaderPrewarmFailed)} ms={Stopwatch.GetElapsedTime(started).TotalMilliseconds:F0} " + + $"failed={Volatile.Read(ref _shaderPrewarmFailed)} dropped_linked={Volatile.Read(ref _shaderPrewarmDroppedLinked)} " + + $"ms={Stopwatch.GetElapsedTime(started).TotalMilliseconds:F0} " + $"runtime_compute_modules={runtime.Count} matched={matched}"); } @@ -549,12 +865,15 @@ private void StopShaderPrewarm() _shaderPrewarmStopping = true; EndShaderPrewarmProgress(); SetShaderPrewarmState(false); - foreach (var thread in _shaderPrewarmThreads) - { - thread.Join(TimeSpan.FromSeconds(10)); - } - - _shaderPrewarmThreads = []; + // A worker stops after its current item. Its pipeline create cannot be cancelled and teardown destroys the + // device next, so each one is joined without a bound, as DrainPendingComputePipelines waits for the session's + // own compiles. + _prewarmPool?.Stop(); + _prewarmPool = null; + // The linked lane stops after its current permutation in the same way; one still waiting for its admission gives + // up, as teardown closed the admission first. + Interlocked.Exchange(ref _linkedPrewarmThread, null)?.Join(); + DestroyPrewarmedComputePipelines(); if (Interlocked.Exchange(ref _shaderPrewarmList, null) is { } list) { list.Dispose(); diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs index 991bc3ba5..ea7134865 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs @@ -345,6 +345,7 @@ private sealed class RenderSlice public int Resume; public RecordingHost? Host; public List Chunks = []; + public List DescriptorPools = []; public bool Submitted; public bool Dispatched; public long DispatchedAt; @@ -459,6 +460,7 @@ private sealed partial class Presenter private RenderWorkerPool? _workers; internal SliceArenaPool? _arenaPool; + internal DescriptorPoolStock? _descriptorPoolStock; private void CreateRenderWorkers() { @@ -469,6 +471,7 @@ private void CreateRenderWorkers() _scheduler.MemoryBarrierRecorder ??= RecordRequestedMemoryBarrier; _arenaPool = new SliceArenaPool(_deviceInfo, _scheduler); + _descriptorPoolStock ??= new DescriptorPoolStock(_deviceInfo); _workers = new RenderWorkerPool(this, RenderWorkerCount); Console.Error.WriteLine($"[LOADER][INFO] Render workers: {RenderWorkerCount}"); } @@ -775,6 +778,7 @@ internal void FinishSlice(RenderSlice slice) slice.Done.Wait(); _slicesRecorded.Increment(); _scheduler.NoteSliceJoined(slice.Generation); + RetireSliceDescriptorPools(slice); if (slice.Chunks.Count == 0) { return; @@ -792,6 +796,26 @@ internal void FinishSlice(RenderSlice slice) } } + private void RetireSliceDescriptorPools(RenderSlice slice) + { + if (slice.DescriptorPools.Count == 0) + { + return; + } + + var pools = slice.DescriptorPools; + var stock = _descriptorPoolStock!; + slice.DescriptorPools = []; + if (slice.Submitted) + { + _scheduler.QueueCompletionAction(() => pools.ForEach(stock.Return)); + } + else + { + pools.ForEach(stock.Return); + } + } + private void RecordSlicePrologue(SliceRequests requests) { Recording.EndRendering(); @@ -848,6 +872,7 @@ private sealed partial class RecordingHost : IRenderingState private long _itemSequence; private readonly ConcurrentBag? _spareBuffers; private readonly SliceArena? _arena; + private readonly SliceDescriptorHeap? _sliceDescriptors; private readonly SliceHazards? _hazards; private readonly RenderRecorder? _workerRecorder; private readonly Dictionary _workerBindings = new(ReferenceEqualityComparer.Instance); @@ -944,6 +969,7 @@ internal void RecordSlice(RenderSlice slice) finally { slice.Chunks = _arena!.TakeChunks(); + slice.DescriptorPools = _sliceDescriptors!.TakePools(); _segment = null; } } diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.cs index 3bad40350..47a7cd140 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.cs @@ -47,6 +47,11 @@ internal static bool ShouldUseNativeGraphicsSubgroups(uint nativeSubgroupSize, S (supportedShaderStages & (ShaderStageFlags.VertexBit | ShaderStageFlags.FragmentBit)) == (ShaderStageFlags.VertexBit | ShaderStageFlags.FragmentBit), }; + + // Pixel row reductions (Gen5SpirvTranslator.WaveReductions) need one host subgroup per guest wave32: a native + // subgroup of 32 lanes, which the diagnostic override of graphics subgroups does not provide. + internal static bool ShouldUsePixelSubgroupArithmetic(uint nativeSubgroupSize, bool graphicsSubgroups, bool fragmentArithmetic) => + nativeSubgroupSize == 32 && graphicsSubgroups && fragmentArithmetic; } internal sealed record VulkanOffscreenColorClear( @@ -82,7 +87,9 @@ internal static unsafe partial class VulkanVideoPresenter private static int _nativeSubgroupSize; private static int _nativeSubgroupShaderStages; private static int _sharedInt64AtomicsSupported; + private static int _bufferInt64AtomicsSupported; private static int _imageInt64AtomicsSupported; + private static int _shaderDeviceClockSupported; // True when the device supports shaderSharedInt64Atomics, so LDS 64-bit // atomics can be emitted as real 64-bit atomics. @@ -92,6 +99,14 @@ internal static unsafe partial class VulkanVideoPresenter private static void SetSharedInt64AtomicsCapability(bool supported) => Volatile.Write(ref _sharedInt64AtomicsSupported, supported ? 1 : 0); + // True when the device supports shaderBufferInt64Atomics, so a 64-bit buffer atomic + // (BUFFER_ATOMIC_*_X2) can be one 64-bit atomic instead of two 32-bit ones. + internal static bool BufferInt64AtomicsEnabled => + Volatile.Read(ref _bufferInt64AtomicsSupported) != 0; + + private static void SetBufferInt64AtomicsCapability(bool supported) => + Volatile.Write(ref _bufferInt64AtomicsSupported, supported ? 1 : 0); + // True when the device supports shaderImageInt64Atomics, so an atomic on a 64-bit // image texel can be compiled. internal static bool ImageInt64AtomicsEnabled => @@ -100,6 +115,12 @@ private static void SetSharedInt64AtomicsCapability(bool supported) => private static void SetImageInt64AtomicsCapability(bool supported) => Volatile.Write(ref _imageInt64AtomicsSupported, supported ? 1 : 0); + internal static bool ShaderDeviceClockEnabled => + Volatile.Read(ref _shaderDeviceClockSupported) != 0; + + private static void SetShaderDeviceClockCapability(bool supported) => + Volatile.Write(ref _shaderDeviceClockSupported, supported ? 1 : 0); + internal static bool GraphicsSubgroupOperationsEnabled => VulkanGraphicsSubgroupPolicy.ShouldUseNativeGraphicsSubgroups( unchecked((uint)Volatile.Read(ref _nativeSubgroupSize)), @@ -448,6 +469,22 @@ private void ReleaseUnsubmittedPresentationResources( DestroyGuestImage(presentedGuestImage); } + // No swapchain image within the acquire timeout: the taken frame is dropped as after ErrorOutOfDateKhr. + // Discarding its flip ends the request's wait for the presenter, so a guest queue waiting on that display + // buffer (WaitForFlip) runs again instead of staying suspended. + private void DropPresentationAfterAcquireTimeout( + in Presentation presentation, + int frameSlot, + bool ownsPresentedGuestImageVersion, + GuestImageResource? presentedGuestImage) + { + ReleaseUnsubmittedPresentationResources( + frameSlot, + ownsPresentedGuestImageVersion, + presentedGuestImage); + CompletePresentation(in presentation, presented: false); + } + // Metal cannot blend into integer render targets or 32-bit-per-channel // float targets (unsupported on Apple-family GPUs). Enabling blend on // one makes vkCreateGraphicsPipelines fail with ErrorInitializationFailed diff --git a/src/SharpEmu.Logging/HostSystemInfo.cs b/src/SharpEmu.Logging/HostSystemInfo.cs index 86b954bc5..4e6e08ed7 100644 --- a/src/SharpEmu.Logging/HostSystemInfo.cs +++ b/src/SharpEmu.Logging/HostSystemInfo.cs @@ -122,6 +122,25 @@ private static int ScoreGpu(string? name) return 1; } + // The commit the process can still make (physical memory plus page file), or -1 when it cannot be read. + public static long AvailableCommitBytes() + { + if (!OperatingSystem.IsWindows()) + { + return -1; + } + + try + { + var status = new MemoryStatusEx { dwLength = (uint)Marshal.SizeOf() }; + return GlobalMemoryStatusEx(ref status) ? (long)Math.Min(status.ullAvailPageFile, long.MaxValue) : -1; + } + catch (Exception) + { + return -1; + } + } + private static string GetMemoryDescription() { if (OperatingSystem.IsWindows()) diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Alu.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Alu.cs index 62a64e420..842053955 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Alu.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Alu.cs @@ -925,6 +925,14 @@ private bool TryEmitVectorAlu( { // Every f16 value widens to f32 exactly, and min/max pick one // input, so the f32 result narrows back without rounding. + if (TryGetNativeHalfSources(instruction, 3, selects: true, out var halves)) + { + result = EmitNativeHalfResult(instruction, destination, instruction.Opcode == "VMax3F16" + ? NanIgnoringMinMax(40, NanIgnoringMinMax(40, halves[0], halves[1], _halfType), halves[2], _halfType) + : EmitFloatMedian(halves[0], halves[1], halves[2], _halfType)); + break; + } + var a = GetFloat16Source(instruction, 0); var b = GetFloat16Source(instruction, 1); var c = GetFloat16Source(instruction, 2); @@ -2065,6 +2073,11 @@ private bool TryEmitPackedF16( return false; } + if (TryEmitNativePackedF16(instruction, control, out result)) + { + return true; + } + var low = EmitPackedF16Lane(instruction, control, highLane: false); var high = EmitPackedF16Lane(instruction, control, highLane: true); result = BitwiseOr(low, ShiftLeftLogical(high, UInt(16))); @@ -2220,11 +2233,8 @@ source.Kind is Gen5OperandKind.VectorRegister or Gen5OperandKind.ScalarRegister uint value; if (readAsHalf) { - var raw = GetRawSource(instruction, index); - var half = ((control.OpSelMask >> index) & 1) != 0 - ? ShiftRightLogical(raw, UInt(16)) - : raw; - value = Bitcast(_floatType, EmitHalfToFloat(half)); + value = Bitcast(_floatType, + EmitHalfToFloat(GetRawSource(instruction, index), ((control.OpSelMask >> index) & 1) != 0)); } else { @@ -2329,11 +2339,8 @@ private uint GetPackedF16Source(Gen5ShaderInstruction instruction, int index) => }) : GetRawSource(instruction, index); - private uint EmitPackedF16Half(uint raw, bool highLane) - { - var half = highLane ? ShiftRightLogical(raw, UInt(16)) : raw; - return Bitcast(_floatType, EmitHalfToFloat(half)); - } + private uint EmitPackedF16Half(uint raw, bool highLane) => + Bitcast(_floatType, EmitHalfToFloat(raw, highLane)); // Saturates an f32 bit pattern to [0, 1] the way the VOP3P clamp modifier // does: below 0 (and NaN, since the ordered compare is false for it) becomes @@ -2428,10 +2435,7 @@ private uint EmitPackedF16Operand( { var raw = GetPackedF16Source(instruction, index); var selectMask = highLane ? control.OpSelHiMask : control.OpSelMask; - var half = ((selectMask >> index) & 1) != 0 - ? ShiftRightLogical(raw, UInt(16)) - : raw; - var value = Bitcast(_floatType, EmitHalfToFloat(half)); + var value = Bitcast(_floatType, EmitHalfToFloat(raw, ((selectMask >> index) & 1) != 0)); var negateMask = highLane ? control.NegHiMask : control.NegLoMask; if (((negateMask >> index) & 1) != 0) { @@ -2444,21 +2448,23 @@ private uint EmitPackedF16Operand( // fminnum_like / fmaxnum_like: if one operand is NaN return the other; if both // are NaN return a NaN; otherwise the ordered smaller/larger. The ordering of // -0/+0 is unspecified under these opcodes, so the ordered compare is enough. - private uint EmitPackedF16MinMax(uint left, uint right, bool isMax) + private uint EmitPackedF16MinMax(uint left, uint right, bool isMax, uint type = 0, uint boolType = 0) { + type = type == 0 ? _floatType : type; + boolType = boolType == 0 ? _boolType : boolType; var compare = _module.AddInstruction( isMax ? SpirvOp.FOrdGreaterThan : SpirvOp.FOrdLessThan, - _boolType, + boolType, left, right); var numeric = _module.AddInstruction( - SpirvOp.Select, _floatType, compare, left, right); - var leftNan = _module.AddInstruction(SpirvOp.IsNan, _boolType, left); - var rightNan = _module.AddInstruction(SpirvOp.IsNan, _boolType, right); + SpirvOp.Select, type, compare, left, right); + var leftNan = _module.AddInstruction(SpirvOp.IsNan, boolType, left); + var rightNan = _module.AddInstruction(SpirvOp.IsNan, boolType, right); var withRight = _module.AddInstruction( - SpirvOp.Select, _floatType, rightNan, left, numeric); + SpirvOp.Select, type, rightNan, left, numeric); return _module.AddInstruction( - SpirvOp.Select, _floatType, leftNan, right, withRight); + SpirvOp.Select, type, leftNan, right, withRight); } private uint ReadMinimumHalfBits(Gen5ShaderInstruction instruction, int sourceIndex) @@ -2547,42 +2553,49 @@ private uint EmitMinimumHalfResult(Gen5ShaderInstruction instruction, uint desti return EmitHalfResult(instruction, destination, bits); } - // Widens an f16 value held in the low 16 bits of `halfBits` to an f32 bit + // Widens an f16 value held in the low 16 bits of `halfBits` (the high 16 bits when `high` is set) to an f32 bit // pattern, exactly (subnormals normalised, Inf/NaN and signed zero preserved). - // Mirrors the branchless HalfToFloat reference validated against System.Half. - private uint EmitHalfToFloat(uint halfBits) + // The exponent and mantissa move into place and the exponent is re-biased; + // Inf/NaN take a second re-bias to the all-ones exponent. A subnormal m becomes + // 2^-14 * (1 + m / 1024) - 2^-14: both floats are normal and their difference + // m * 2^-24 is representable, so the subtraction is exact even when the driver + // flushes denormals. + private uint EmitHalfToFloat(uint halfBits, bool high = false) { - var sign = ShiftLeftLogical(BitwiseAnd(halfBits, UInt(0x8000)), UInt(16)); - var exponent = BitwiseAnd(ShiftRightLogical(halfBits, UInt(10)), UInt(0x1F)); - var mantissa = BitwiseAnd(halfBits, UInt(0x3FF)); - - var normal = BitwiseOr( - ShiftLeftLogical(IAdd(exponent, UInt(112)), UInt(23)), - ShiftLeftLogical(mantissa, UInt(13))); - var infinityNan = BitwiseOr(UInt(0x7F80_0000), ShiftLeftLogical(mantissa, UInt(13))); - - // Subnormal: normalise the mantissa. FindUMsb of (mantissa | 1) keeps the - // op defined when mantissa is 0; that lane is discarded by the select below. - var highBit = Ext(75, _uintType, BitwiseOr(mantissa, UInt(1))); - var shift = ISubU(UInt(23), highBit); - var subFraction = BitwiseAnd(ShiftLeftLogical(mantissa, shift), UInt(0x7F_FFFF)); - var subnormal = SelectU( - IsNotZero(mantissa), - BitwiseOr(ShiftLeftLogical(IAdd(highBit, UInt(103)), UInt(23)), subFraction), - UInt(0)); + if (_request.NativeFloat16Conversions && !_module.TryGetConstantValue(halfBits, out _)) + { + return EmitNativeHalfToFloat(halfBits, high); + } + + if (high) + { + halfBits = ShiftRightLogical(halfBits, UInt(16)); + } - var magnitude = SelectU( + var magnitude = ShiftLeftLogical(BitwiseAnd(halfBits, UInt(0x7FFF)), UInt(13)); + var exponent = BitwiseAnd(magnitude, UInt(0x0F80_0000)); + var rebiased = IAdd(magnitude, UInt(112u << 23)); + var infinityNan = IAdd(rebiased, UInt(112u << 23)); + var subnormal = Bitcast(_uintType, _module.AddInstruction(SpirvOp.FSub, _floatType, + Bitcast(_floatType, IAdd(rebiased, UInt(1u << 23))), Float(1f / 16384f))); + var widened = SelectU( Equal(exponent, 0), subnormal, - SelectU(Equal(exponent, 31), infinityNan, normal)); - return BitwiseOr(sign, magnitude); + SelectU(Equal(exponent, 0x0F80_0000), infinityNan, rebiased)); + return BitwiseOr(widened, ShiftLeftLogical(BitwiseAnd(halfBits, UInt(0x8000)), UInt(16))); } // Narrows an f32 bit pattern to an f16 value in the low 16 bits, rounding to // nearest even (subnormals, overflow-to-Inf and NaN/Inf handled). Mirrors the // branchless FloatToHalf reference validated exhaustively against System.Half. + // A NaN becomes the quiet NaN of its sign, 0x7E00. private uint EmitFloatToHalf(uint bits) { + if (_request.NativeFloat16Conversions && !_module.TryGetConstantValue(bits, out _)) + { + return EmitNativeFloatToHalf(bits); + } + var sign = BitwiseAnd(ShiftRightLogical(bits, UInt(16)), UInt(0x8000)); var absolute = BitwiseAnd(bits, UInt(0x7FFF_FFFF)); @@ -2622,7 +2635,7 @@ private uint EmitFloatToHalf(uint bits) _module.AddInstruction( SpirvOp.LogicalAnd, _boolType, - Equal(lowBits, halfWay), + UCmp(SpirvOp.IEqual, lowBits, halfWay), IsNotZero(BitwiseAnd(quotient, UInt(1))))); var subnormal = IAdd(quotient, SelectU(roundUp, UInt(1), UInt(0))); @@ -2631,6 +2644,233 @@ private uint EmitFloatToHalf(uint bits) return SelectU(isInfinityNan, infinityNan, BitwiseOr(sign, finite)); } + private uint _halfType; + private uint _half2Type; + + // The f16 type of the native conversions. Its first use declares it with the float controls under which OpFConvert + // converts as the guest does (the entry point gets their execution modes): round-to-nearest-even, kept denormals, + // kept signed zero, infinity and NaN, all for 16-bit floats. + private uint HalfType() + { + if (_halfType == 0) + { + _module.AddCapability(SpirvCapability.Float16); + _module.AddCapability(SpirvCapability.DenormPreserve); + _module.AddCapability(SpirvCapability.RoundingModeRte); + _module.AddCapability(SpirvCapability.SignedZeroInfNanPreserve); + _halfType = _module.TypeFloat(16); + _half2Type = _module.TypeVector(_halfType, 2); + } + + return _halfType; + } + + // EmitHalfToFloat with NativeFloat16Conversions. OpFConvert widens; a NaN keeps its payload as the integer sequence + // keeps it, which the device need not do: the half at the top of a word, shifted right arithmetically by 3, has the + // sign, exponent and mantissa of the f32 NaN in place, and 0x70000000 fills the rest of its exponent. + private uint EmitNativeHalfToFloat(uint bits, bool high) + { + var half = _module.AddInstruction(SpirvOp.CompositeExtract, HalfType(), Bitcast(_half2Type, bits), high ? 1u : 0u); + var top = high ? BitwiseAnd(bits, UInt(0xFFFF_0000)) : ShiftLeftLogical(bits, UInt(16)); + var nan = BitwiseOr(_module.AddInstruction(SpirvOp.ShiftRightArithmetic, _uintType, top, UInt(3)), UInt(0x7000_0000)); + return Bitcast(_uintType, _module.AddInstruction(SpirvOp.Select, _floatType, + _module.AddInstruction(SpirvOp.IsNan, _boolType, half), + Bitcast(_floatType, nan), + _module.AddInstruction(SpirvOp.FConvert, _floatType, half))); + } + + // EmitFloatToHalf with NativeFloat16Conversions. OpFConvert rounds to nearest even, makes f16 denormals and overflows + // to infinity; a NaN becomes 0x7E00 with its sign, as in the integer sequence. + private uint EmitNativeFloatToHalf(uint bits) + { + var half = HalfType(); + var value = Bitcast(_floatType, bits); + var narrowed = _module.AddInstruction(SpirvOp.CompositeConstruct, _half2Type, + _module.AddInstruction(SpirvOp.FConvert, half, value), _module.Constant(half, 0)); + var nan = SelectU(UCmp(SpirvOp.UGreaterThan, bits, UInt(0x7FFF_FFFF)), UInt(0xFE00), UInt(0x7E00)); + return SelectU(IsNan(value), nan, Bitcast(_uintType, narrowed)); + } + + private uint HalfConstant(uint bits) => _module.Constant(HalfType(), bits); + + // With NativeFloat16Conversions the f16 add, subtract, multiply, maximum and median are f16 ops where they give the + // bits of the f32 forms: one f16 rounding equals the f32 rounding followed by the narrowing (24 >= 2 * 11 + 2 + // significand bits), and the maximum and median select one of their inputs in either width. The f32 forms must keep + // signed zero and NaN (SignedZeroInfNanPreserve for 32 bits), and the abs and neg modifiers are bit operations: an + // NVIDIA driver's f16 negation of a NaN can lose its sign, and its compiler folds x + -x of f16 pairs to -0. A maximum or + // median with a negated operand keeps the f32 forms, whose NaN result takes the sign of the negation or not as the + // driver compiles it. Output scaling, SDWA and DPP keep the f32 forms, as does a constant f16 cannot hold (1/(2 pi)) + // or a NaN constant, whose widened payload the f32 forms compute with. + private bool TryGetNativeHalfSources(Gen5ShaderInstruction instruction, int count, bool selects, out uint[] halves) + { + halves = new uint[count]; + if (!_request.NativeFloat16Conversions || !_request.ShaderSignedZeroInfNanPreserveFloat32Supported || + instruction.Control is not (null or Gen5Vop3Control { OutputModifier: 0 }) || + (selects && instruction.Control is Gen5Vop3Control { NegateMask: not 0 })) + { + return false; + } + + var control = instruction.Control as Gen5Vop3Control; + bool Bit(uint? mask, int index) => ((mask ?? 0) & (1u << index)) != 0; + var constants = new int[count]; + for (var index = 0; index < count; index++) + { + if (!TryGetNativeHalfConstant(instruction.Sources[index], Bit(control?.OperandSelect, index), out constants[index])) + { + return false; + } + } + + for (var index = 0; index < count; index++) + { + var high = Bit(control?.OperandSelect, index); + var sign = high ? 0x8000_0000u : 0x8000u; + var bits = constants[index] >= 0 + ? UInt((uint)constants[index] << (high ? 16 : 0)) + : GetRawSource(instruction, index, applySdwaIntegerModifiers: false); + if (Bit(control?.AbsoluteMask, index)) + { + bits = BitwiseAnd(bits, UInt(~sign)); + } + + if (Bit(control?.NegateMask, index)) + { + bits = BitwiseXor(bits, UInt(sign)); + } + + halves[index] = _module.TryGetConstantValue(bits, out var constant) + ? HalfConstant(high ? constant >> 16 : constant & 0xFFFF) + : _module.AddInstruction(SpirvOp.CompositeExtract, HalfType(), Bitcast(_half2Type, bits), high ? 1u : 0u); + } + + return true; + } + + // The f16 bits of a constant source as GetFloat16Source reads it, or -1 for a register. False when f16 cannot hold + // the value or it is a NaN. + private static bool TryGetNativeHalfConstant(Gen5Operand operand, bool high, out int bits) + { + bits = -1; + if (operand.Kind == Gen5OperandKind.EncodedConstant && + Gen5InlineConstants.TryDecode(operand.Value, out var inline)) + { + var number = operand.Value switch + { + >= 128 and <= 192 => operand.Value - 128f, + >= 193 and <= 208 => 192f - operand.Value, + _ => BitConverter.UInt32BitsToSingle(inline), + }; + bits = BitConverter.HalfToUInt16Bits((Half)number); + return (float)(Half)number == number; + } + + if (operand.Kind == Gen5OperandKind.LiteralConstant) + { + bits = (int)((high ? operand.Value >> 16 : operand.Value) & 0xFFFF); + return (bits & 0x7FFF) <= 0x7C00; + } + + return true; + } + + // A native f16 result as the low half of a word for EmitHalfResult. The clamp is EmitClampToUnitInterval's; without + // it a NaN becomes 0x7E00 with its sign, as the narrowing makes it. + private uint EmitNativeHalfResult(Gen5ShaderInstruction instruction, uint destination, uint value) + { + var clamp = instruction.Control is Gen5Vop3Control { Clamp: true }; + if (clamp) + { + value = ClampHalvesToUnitInterval(value, _halfType, _boolType, HalfConstant(0), HalfConstant(0x3C00)); + } + + var bits = Bitcast(_uintType, _module.AddInstruction(SpirvOp.CompositeConstruct, _half2Type, value, HalfConstant(0))); + return EmitHalfResult(instruction, destination, clamp ? bits : SelectU( + _module.AddInstruction(SpirvOp.IsNan, _boolType, value), + BitwiseOr(BitwiseAnd(bits, UInt(0x8000)), UInt(0x7E00)), + bits)); + } + + // TryEmitPackedF16 on f16 pairs under the rules of TryGetNativeHalfSources; V_PK_FMA_F16 keeps its f32 form. A NaN + // lane becomes 0x7E00 with its sign, as the narrowing of the lane makes it. + private bool TryEmitNativePackedF16(Gen5ShaderInstruction instruction, Gen5Vop3pControl control, out uint result) + { + result = 0; + if (!_request.NativeFloat16Conversions || !_request.ShaderSignedZeroInfNanPreserveFloat32Supported || + instruction.Opcode == "VPkFmaF16" || + (instruction.Opcode is "VPkMaxF16" or "VPkMinF16" && ((control.NegLoMask | control.NegHiMask) & 3) != 0) || + !TryGetNativeHalfPair(instruction, control, 0, out var left) || + !TryGetNativeHalfPair(instruction, control, 1, out var right)) + { + return false; + } + + var bool2 = _module.TypeVector(_boolType, 2); + var value = instruction.Opcode switch + { + "VPkAddF16" => _module.AddInstruction(SpirvOp.FAdd, _half2Type, left, right), + "VPkMulF16" => _module.AddInstruction(SpirvOp.FMul, _half2Type, left, right), + _ => EmitPackedF16MinMax(left, right, instruction.Opcode == "VPkMaxF16", _half2Type, bool2), + }; + if (control.Clamp) + { + result = Bitcast(_uintType, ClampHalvesToUnitInterval(value, _half2Type, bool2, + Bitcast(_half2Type, UInt(0)), Bitcast(_half2Type, UInt(0x3C00_3C00)))); + return true; + } + + var bits = Bitcast(_uintType, value); + var nan = _module.AddInstruction(SpirvOp.IsNan, bool2, value); + var lanes = BitwiseOr( + SelectU(_module.AddInstruction(SpirvOp.CompositeExtract, _boolType, nan, 0u), UInt(0x0000_FFFF), UInt(0)), + SelectU(_module.AddInstruction(SpirvOp.CompositeExtract, _boolType, nan, 1u), UInt(0xFFFF_0000), UInt(0))); + var quiet = BitwiseOr(BitwiseAnd(bits, UInt(0x8000_8000)), UInt(0x7E00_7E00)); + result = BitwiseXor(bits, BitwiseAnd(BitwiseXor(bits, quiet), lanes)); + return true; + } + + // A packed source as an f16 pair: op_sel and op_sel_hi pick the half of each lane and neg_lo and neg_hi flip its sign, + // on the bits. False for a constant with a NaN half. + private bool TryGetNativeHalfPair(Gen5ShaderInstruction instruction, Gen5Vop3pControl control, int index, out uint pair) + { + pair = 0; + var bits = GetPackedF16Source(instruction, index); + var low = (control.OpSelMask >> index) & 1; + var high = (control.OpSelHiMask >> index) & 1; + if (low != 0 || high != 1) + { + bits = BitwiseOr( + low != 0 ? ShiftRightLogical(bits, UInt(16)) : BitwiseAnd(bits, UInt(0xFFFF)), + high != 0 ? BitwiseAnd(bits, UInt(0xFFFF_0000)) : ShiftLeftLogical(bits, UInt(16))); + } + + var negate = (((control.NegLoMask >> index) & 1) << 15) | (((control.NegHiMask >> index) & 1) << 31); + if (negate != 0) + { + bits = BitwiseXor(bits, UInt(negate)); + } + + if (_module.TryGetConstantValue(bits, out var constant) && + ((constant & 0x7FFF) > 0x7C00 || ((constant >> 16) & 0x7FFF) > 0x7C00)) + { + return false; + } + + HalfType(); + pair = Bitcast(_half2Type, bits); + return true; + } + + // EmitClampToUnitInterval on a native f16 value or pair: the ordered compares send NaN and every value up to zero to + // +0 and every value from one to one. + private uint ClampHalvesToUnitInterval(uint value, uint type, uint boolType, uint zero, uint one) + { + var lowerBounded = _module.AddInstruction(SpirvOp.Select, type, + _module.AddInstruction(SpirvOp.FOrdGreaterThan, boolType, value, zero), value, zero); + return _module.AddInstruction(SpirvOp.Select, type, + _module.AddInstruction(SpirvOp.FOrdLessThan, boolType, lowerBounded, one), lowerBounded, one); + } + private uint SelectU(uint condition, uint whenTrue, uint whenFalse) => _module.AddInstruction(SpirvOp.Select, _uintType, condition, whenTrue, whenFalse); @@ -4529,24 +4769,59 @@ private uint ApplyDpp8Source(Gen5Dpp8Control control, uint value) } private uint ApplyDppSource(Gen5DppControl control, uint value) + { + GetDppSource(control, out var safeTarget, out var valid); + var shuffled = _pairedMeshLanes + ? ShufflePairedValue(_pairedDppSources[0], _pairedDppSources[1], safeTarget) + : ShuffleLane(value, safeTarget); + return _module.AddInstruction( + SpirvOp.Select, + _uintType, + valid, + shuffled, + UInt(0)); + } + + // DPP16: the lane src0 is read from (the reading lane itself when the source is invalid) and whether the source is + // valid: in range, and active in the guest unless FI (fetch inactive) is set. An invalid source reads as zero; + // without BOUND_CTRL it also leaves the destination unwritten (IsDppWriteEnabled). + private void GetDppSource(Gen5DppControl control, out uint safeTarget, out uint valid) { GetDppSourceLane(control, out var targetLane, out var inRange); - var lane = GuestWaveLane(); - var safeTarget = _module.AddInstruction( + if (!_pairedMeshLanes && _waveLowering is NativeWave32Lowering && _subgroupInvocationIdInput != 0) + { + // A ballot names the lanes that can be read: an invocation missing from the host subgroup (a fragment warp + // that is not full) is never shuffled from, and without FI neither is a lane the guest has inactive. + _module.AddCapability(SpirvCapability.GroupNonUniformBallot); + var readable = _module.AddInstruction( + SpirvOp.GroupNonUniformBallot, + _uvec4Type, + UInt(3), + control.FetchInactive ? _module.ConstantBool(true) : Load(_boolType, _exec)); + var target = BitwiseAnd(targetLane, UInt(31)); + valid = _module.AddInstruction( + SpirvOp.LogicalAnd, + _boolType, + inRange, + _module.AddInstruction(SpirvOp.GroupNonUniformBallotBitExtract, _boolType, UInt(3), readable, target)); + safeTarget = BitwiseAnd( + _module.AddInstruction(SpirvOp.Select, _uintType, valid, target, GuestWaveLane()), + UInt(NativeLaneMask)); + return; + } + + safeTarget = _module.AddInstruction( SpirvOp.Select, _uintType, inRange, targetLane, - lane); + GuestWaveLane()); if (!_pairedMeshLanes) { safeTarget = BitwiseAnd(safeTarget, UInt(NativeLaneMask)); } - var shuffled = _pairedMeshLanes - ? ShufflePairedValue(_pairedDppSources[0], _pairedDppSources[1], safeTarget) - : ShuffleLane(value, safeTarget); - var sourceAvailable = inRange; + valid = inRange; if (!control.FetchInactive) { var activeWord = _module.AddInstruction( @@ -4558,19 +4833,12 @@ private uint ApplyDppSource(Gen5DppControl control, uint value) var shuffledActive = _pairedMeshLanes ? ShufflePairedValue(_pairedActiveWords[0], _pairedActiveWords[1], safeTarget) : ShuffleLane(activeWord, safeTarget); - sourceAvailable = _module.AddInstruction( + valid = _module.AddInstruction( SpirvOp.LogicalAnd, _boolType, - sourceAvailable, + valid, IsNotZero(shuffledActive)); } - - return _module.AddInstruction( - SpirvOp.Select, - _uintType, - sourceAvailable, - shuffled, - UInt(0)); } private uint ApplySdwaDestination( @@ -4726,19 +4994,21 @@ private void GetDppSourceLane( private uint IsDppWriteEnabled(Gen5DppControl control) { - GetDppSourceLane(control, out _, out var inRange); var lane = GuestWaveLane(); var row = ShiftRightLogical(lane, UInt(4)); - var bank = BitwiseAnd(lane, UInt(3)); + // A bank is four consecutive lanes of each row (RDNA2 ISA, table 90). + var bank = BitwiseAnd(ShiftRightLogical(lane, UInt(2)), UInt(3)); var rowEnabled = IsNotZero(BitwiseAnd( UInt(control.RowMask), ShiftLeftLogical(UInt(1), row))); var bankEnabled = IsNotZero(BitwiseAnd( UInt(control.BankMask), ShiftLeftLogical(UInt(1), bank))); - var sourceAllowsWrite = control.BoundControl - ? _module.ConstantBool(true) - : inRange; + var sourceAllowsWrite = _module.ConstantBool(true); + if (!control.BoundControl) + { + GetDppSource(control, out _, out sourceAllowsWrite); + } return _module.AddInstruction( SpirvOp.LogicalAnd, _boolType, @@ -4788,13 +5058,8 @@ private uint GetFloat16Source( instruction, sourceIndex, applySdwaIntegerModifiers: false); - if (instruction.Control is Gen5Vop3Control control && - (control.OperandSelect & (1u << sourceIndex)) != 0) - { - raw = ShiftRightLogical(raw, UInt(16)); - } - - value = Bitcast(_floatType, EmitHalfToFloat(raw)); + value = Bitcast(_floatType, EmitHalfToFloat(raw, + instruction.Control is Gen5Vop3Control control && (control.OperandSelect & (1u << sourceIndex)) != 0)); } uint absoluteMask = 0; @@ -5127,6 +5392,12 @@ private uint EmitFloat16Binary( SpirvOp operation, bool reverse = false) { + if (TryGetNativeHalfSources(instruction, 2, selects: false, out var halves)) + { + return EmitNativeHalfResult(instruction, destination, + _module.AddInstruction(operation, _halfType, halves[reverse ? 1 : 0], halves[reverse ? 0 : 1])); + } + var left = GetFloat16Source(instruction, reverse ? 1 : 0); var right = GetFloat16Source(instruction, reverse ? 0 : 1); return EmitFloat16Result( @@ -5139,13 +5410,15 @@ private uint EmitFloat16ExtBinary( Gen5ShaderInstruction instruction, uint destination, uint operation) => - EmitFloat16Result( - instruction, - destination, - NanIgnoringMinMax( - operation, - GetFloat16Source(instruction, 0), - GetFloat16Source(instruction, 1))); + TryGetNativeHalfSources(instruction, 2, selects: true, out var halves) + ? EmitNativeHalfResult(instruction, destination, NanIgnoringMinMax(operation, halves[0], halves[1], _halfType)) + : EmitFloat16Result( + instruction, + destination, + NanIgnoringMinMax( + operation, + GetFloat16Source(instruction, 0), + GetFloat16Source(instruction, 1))); private uint EmitFloatBinary( Gen5ShaderInstruction instruction, @@ -5171,17 +5444,19 @@ private uint EmitFloatExtBinary( GetFloatSource(instruction, 0), GetFloatSource(instruction, 1))); - private uint EmitFloatMedian(uint a, uint b, uint c) + // v_med3_f32 with a NaN operand is v_min3_f32 (RDNA2 ISA). Without one no intermediate is NaN, so plain FMin and FMax + // give the median the NaN-ignoring forms would. + private uint EmitFloatMedian(uint a, uint b, uint c, uint type = 0) { - var low = NanIgnoringMinMax(37, a, b); - var high = NanIgnoringMinMax(40, a, b); - var median = NanIgnoringMinMax(40, low, NanIgnoringMinMax(37, high, c)); + type = type == 0 ? _floatType : type; var anyNan = _module.AddInstruction( SpirvOp.LogicalOr, _boolType, - IsNanBits(a), - _module.AddInstruction(SpirvOp.LogicalOr, _boolType, IsNanBits(b), IsNanBits(c))); - return _module.AddInstruction(SpirvOp.Select, _floatType, anyNan, NanIgnoringMinMax(37, low, c), median); + IsNan(a, type), + _module.AddInstruction(SpirvOp.LogicalOr, _boolType, IsNan(b, type), IsNan(c, type))); + var median = Ext(40, type, Ext(37, type, a, b), Ext(37, type, Ext(40, type, a, b), c)); + return _module.AddInstruction(SpirvOp.Select, type, anyNan, + NanIgnoringMinMax(37, NanIgnoringMinMax(37, a, b, type), c, type), median); } private uint EmitFloatTernaryExt( @@ -5197,13 +5472,21 @@ private uint EmitFloatTernaryExt( NanIgnoringMinMax(operation, first, GetFloatSource(instruction, 2))); } - private uint NanIgnoringMinMax(uint operation, uint left, uint right) + private uint NanIgnoringMinMax(uint operation, uint left, uint right, uint type = 0) { - var result = Ext(operation, _floatType, left, right); - result = _module.AddInstruction(SpirvOp.Select, _floatType, IsNanBits(right), left, result); - return _module.AddInstruction(SpirvOp.Select, _floatType, IsNanBits(left), right, result); + type = type == 0 ? _floatType : type; + var result = Ext(operation, type, left, right); + result = _module.AddInstruction(SpirvOp.Select, type, IsNan(right, type), left, result); + return _module.AddInstruction(SpirvOp.Select, type, IsNan(left, type), right, result); } + // A module that declares SignedZeroInfNanPreserve keeps OpIsNan exact; without it a driver may assume no NaN, and + // the test reads the bits. A native f16 value is under the 16-bit float controls. + private uint IsNan(uint value, uint type = 0) => + _request.ShaderSignedZeroInfNanPreserveFloat32Supported || (type != 0 && type == _halfType) + ? _module.AddInstruction(SpirvOp.IsNan, _boolType, value) + : IsNanBits(value); + // NaN tested on the bits, which fast math cannot assume away. private uint IsNanBits(uint value) => _module.AddInstruction( @@ -5223,13 +5506,12 @@ private uint ConvertFloatToUnsignedSaturated(uint value) _module.AddInstruction(SpirvOp.UGreaterThanEqual, _boolType, bits, UInt(0x4F80_0000)), UInt(uint.MaxValue), converted); - // Negative values, including negative NaN, have the sign bit set. - converted = _module.AddInstruction( + // Above +Inf as unsigned bits: a positive NaN or a negative value (negative NaN and -0 included). + return _module.AddInstruction( SpirvOp.Select, _uintType, - _module.AddInstruction(SpirvOp.UGreaterThanEqual, _boolType, bits, UInt(0x8000_0000)), + _module.AddInstruction(SpirvOp.UGreaterThan, _boolType, bits, UInt(0x7F80_0000)), UInt(0), converted); - return _module.AddInstruction(SpirvOp.Select, _uintType, IsNanBits(value), UInt(0), converted); } private uint ConvertDoubleToIntegerSaturated(uint value, bool signed) diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.DeferredGuards.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.DeferredGuards.cs new file mode 100644 index 000000000..b8eaf3c6c --- /dev/null +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.DeferredGuards.cs @@ -0,0 +1,73 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.ShaderCompiler.Vulkan; + +public static partial class Gen5SpirvTranslator +{ + private sealed partial class CompilationContext + { + // A vector register write under a partial EXEC keeps the old value in the lanes EXEC leaves out: + // select(active, new, old). While EXEC and the SPIR-V block stay the same, those lanes of a register are + // read only by instructions that read other lanes or address memory through VGPR values, so one select + // per register and region is enough. A write in the region stores the new value in every lane; the first + // one remembers the value the register had when the region began. The select is emitted when EXEC + // changes, before the block ends or calls, and before an instruction that reads other lanes. + // SHARPEMU_DEFERRED_EXEC_GUARDS=0 guards every write again. + private static readonly bool DeferredExecGuards = !string.Equals( + Environment.GetEnvironmentVariable("SHARPEMU_DEFERRED_EXEC_GUARDS"), "0", StringComparison.Ordinal); + + private bool _deferGuards; + private readonly List<(uint Register, uint Old)> _deferredGuards = []; + private readonly HashSet _deferredGuardRegisters = []; + + // A half wave keeps one guest lane per invocation, as a native wave does. + private bool CanDeferGuards => + DeferredExecGuards && !_pairedLanes && !_pairedMeshLanes && !_hasIndirectControlFlow && + _stage != Gen5SpirvStage.Mesh && _waveLowering is NativeWave32Lowering or NativeWave64Lowering or HalfWave64Lowering; + + // A guarded write inside the current region: the new value goes to every lane. + private bool TryDeferGuard(uint register, uint value) + { + if (!_deferGuards) + { + return false; + } + + if (_deferredGuardRegisters.Add(register)) + { + _deferredGuards.Add((register, LoadV(register))); + } + + Store(VectorPointer(register), value); + return true; + } + + // Ends the region: the lanes EXEC left out get back the values their registers had when it began. + private void FlushDeferredGuards() + { + if (_deferredGuards.Count == 0) + { + return; + } + + var active = Load(_boolType, _exec); + foreach (var (register, old) in _deferredGuards) + { + Store(VectorPointer(register), _module.AddInstruction(SpirvOp.Select, _uintType, active, LoadV(register), old)); + } + + _deferredGuards.Clear(); + _deferredGuardRegisters.Clear(); + } + + // Instructions that can read the vector registers of other lanes (DPP, lane reads and writes, permutes, + // image derivatives, exports), or that address memory through VGPR values outside bounds-checked bindings. + private static bool ReadsOtherLanes(Gen5ShaderInstruction instruction) => + instruction.Control is Gen5DppControl or Gen5Dpp8Control or Gen5DataShareControl { Gds: true } || + instruction.Encoding is Gen5ShaderEncoding.Mimg or Gen5ShaderEncoding.Flat or Gen5ShaderEncoding.Exp || + instruction.Opcode is "VReadlaneB32" or "VReadfirstlaneB32" or "VWritelaneB32" or "VPermlane16B32" or + "VPermlanex16B32" or "DsSwizzleB32" or "DsBpermuteB32" or "DsPermuteB32" || + instruction.Opcode.StartsWith("VMovrel", StringComparison.Ordinal); + } +} diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.DeviceLoadFunction.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.DeviceLoadFunction.cs new file mode 100644 index 000000000..cd7acadb2 --- /dev/null +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.DeviceLoadFunction.cs @@ -0,0 +1,125 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.ShaderCompiler.Vulkan; + +public static partial class Gen5SpirvTranslator +{ + // SHARPEMU_SHARED_DEVICE_LOADS (on by default; =0 turns it off): a compact program reads each device dword through + // one DontInline function (page lookup, fault report, fallback load) instead of emitting that sequence at every + // load. Inline, the sequences can make the driver's compiler take a minute or more for one large outlined call + // body, which compiles in seconds this way, and they lengthen the program's GPU submissions. Tests may set it. + public static bool SharedDeviceLoads { get; set; } = + !string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_SHARED_DEVICE_LOADS"), "0", StringComparison.Ordinal); + + // SHARPEMU_SHARED_DEVICE_RANGES (on by default; =0 turns it off): with the shared function, a range of 2 to 16 + // consecutive device dwords (scalar loads, scalar buffer loads, buffer elements) goes through one DontInline + // function per range length instead of one call per dword. The driver's compile time grows faster than linearly + // with the call sites in a module, so a record of many outlined bodies can take minutes and gigabytes to compile; + // one call per range leaves about a third of the call sites. Tests may set it. + public static bool SharedDeviceRanges { get; set; } = + !string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_SHARED_DEVICE_RANGES"), "0", StringComparison.Ordinal); + + private sealed partial class CompilationContext + { + private uint _deviceDwordFunction; + + // Whether this program's compact device dword loads go through the shared function. + private bool UsesSharedDeviceLoads => + SharedDeviceLoads && _compactMemoryAccess && _pageTable != 0 && _deviceAddressFaultPage != 0 && + !_request.TraceDeviceAddressFaults; + + // One dword through the page table, in the shared function: allowed gates the load (a refused dword reads zero), + // report gates the report of a missing page, as ResolveCompactDeviceAddress's reportFault does. + private uint CallDeviceDword(uint address64, uint allowed, uint report) + { + if (_deviceDwordFunction == 0) + { + _deviceDwordFunction = _module.AllocateId(); + } + + return _module.AddInstruction(SpirvOp.FunctionCall, _uintType, _deviceDwordFunction, address64, allowed, report); + } + + // Each range length's function holds the range's inline form (LoadDeviceDwordRange: the first and last dwords' page + // lookups and fault reports, then each dword's load), which reads and reports as the calls per dword do. + private readonly Dictionary _deviceRangeFunctions = []; + private bool _emittingDeviceRange; + + private bool UsesSharedDeviceRanges => SharedDeviceRanges && UsesSharedDeviceLoads && !_emittingDeviceRange; + + private uint[] CallDeviceDwordRange(uint address64, IReadOnlyList allowed) + { + var count = allowed.Count; + if (!_deviceRangeFunctions.TryGetValue(count, out var range)) + { + range = (_module.AllocateId(), _module.TypeArrayDistinct(_uintType, (uint)count)); + _deviceRangeFunctions[count] = range; + } + + var result = _module.AddInstruction(SpirvOp.FunctionCall, range.ArrayType, [range.Function, address64, .. allowed]); + var values = new uint[count]; + for (var dword = 0; dword < count; dword++) + { + values[dword] = _module.AddInstruction(SpirvOp.CompositeExtract, _uintType, result, (uint)dword); + } + + return values; + } + + // After every function that may call them. + private void EmitDeviceRangeFunctions() + { + const uint dontInline = 2; + foreach (var (count, range) in _deviceRangeFunctions.OrderBy(entry => entry.Key)) + { + var functionType = _module.TypeFunction(range.ArrayType, [_ulongType, .. Enumerable.Repeat(_boolType, count)]); + _module.BeginFunction(range.ArrayType, functionType, dontInline, range.Function); + _module.AddName(range.Function, $"loadDeviceDwords{count}"); + var address = _module.AddFunctionParameter(_ulongType); + var allowed = new uint[count]; + for (var dword = 0; dword < count; dword++) + { + allowed[dword] = _module.AddFunctionParameter(_boolType); + } + + _module.AddLabel(); + InitializeDeviceAddressFallback(); + _emittingDeviceRange = true; + try + { + var values = LoadDeviceDwordRange(address, allowed); + _module.AddStatement(SpirvOp.ReturnValue, _module.AddInstruction(SpirvOp.CompositeConstruct, range.ArrayType, values)); + } + finally + { + _emittingDeviceRange = false; + } + + _module.EndFunction(); + } + } + + // After every function that may call it. + private void EmitDeviceDwordFunction() + { + if (_deviceDwordFunction == 0) + { + return; + } + + const uint dontInline = 2; + var functionType = _module.TypeFunction(_uintType, _ulongType, _boolType, _boolType); + _module.BeginFunction(_uintType, functionType, dontInline, _deviceDwordFunction); + _module.AddName(_deviceDwordFunction, "loadDeviceDword"); + var address = _module.AddFunctionParameter(_ulongType); + var allowed = _module.AddFunctionParameter(_boolType); + var report = _module.AddFunctionParameter(_boolType); + _module.AddLabel(); + InitializeDeviceAddressFallback(); + var (pointer, valid) = ResolveCompactDeviceAddress(address, report); + _module.AddStatement(SpirvOp.ReturnValue, LoadMappedDeviceDword(pointer, LogicalAnd(allowed, valid))); + _module.EndFunction(); + } + } +} diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.HalfWave64Lowering.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.HalfWave64Lowering.cs index 95fdc62f5..d164e8cdd 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.HalfWave64Lowering.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.HalfWave64Lowering.cs @@ -9,9 +9,11 @@ public static partial class Gen5SpirvTranslator { private sealed partial class CompilationContext { - // Independent halves duplicate scalar work; a lane-local proof is not a performance proof. - private static readonly bool LaneLocalWave64Enabled = string.Equals( - Environment.GetEnvironmentVariable("SHARPEMU_WAVE64_LANE_LOCAL"), "1", StringComparison.Ordinal); + // A lane-local wave64 program runs as two independent halves, one guest lane per invocation: its module is about + // half the size of paired lanes and compiles in about half the time, while each half repeats the scalar work. + // SHARPEMU_WAVE64_LANE_LOCAL=0 keeps paired lanes. + private static readonly bool LaneLocalWave64Enabled = !string.Equals( + Environment.GetEnvironmentVariable("SHARPEMU_WAVE64_LANE_LOCAL"), "0", StringComparison.Ordinal); private static bool CanRunHalfWaves(ShaderCompileRequest request, int[] physicalAxisOfLogical) { diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Mesh.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Mesh.cs index d7ac04aee..2728d8750 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Mesh.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Mesh.cs @@ -20,6 +20,7 @@ private sealed partial class CompilationContext private uint _meshAllocation; private uint _meshBarrierWaiting; private uint _meshAnyActive; + private uint _meshTaskPayload; private bool _directMeshBlocks; private readonly List<(int Start, int End)> _meshLoopRegions = []; private bool _convergedMeshDispatch; @@ -98,6 +99,15 @@ private void DeclareMeshOutputs() _interfaces.Add(value); _meshParameters.Add(location, (output, value)); } + + if (mesh.TaskLaunched) + { + // The task stage's payload, which carries the draw parameters (SpirvMeshTask). + _meshTaskPayload = _module.AddGlobalVariable( + _module.TypePointer(SpirvStorageClass.TaskPayloadWorkgroupExt, SpirvMeshTask.PayloadType(_module, _uintType)), + SpirvStorageClass.TaskPayloadWorkgroupExt); + _interfaces.Add(_meshTaskPayload); + } } private uint DeclareMeshOutput(uint elementType, uint length, SpirvBuiltIn builtIn, @@ -402,19 +412,23 @@ private void InitializeMeshInputs() for (var index = 0; index < parameters.Length; index++) { parameters[index] = DeclarePrivateValue(_uintType); - Store(parameters[index], LoadShaderDataDword(UInt(parameterBase + (uint)index))); + Store(parameters[index], mesh.TaskLaunched ? TaskPayloadParameter(index) + : LoadShaderDataDword(UInt(parameterBase + (uint)index))); } - // The reserved index-size tag selects a submission-owned parameter block. - // Both modes keep the same six-word shader-data layout. - var dynamicParameters = _module.AddInstruction(SpirvOp.IEqual, _boolType, - Load(_uintType, parameters[3]), UInt(uint.MaxValue)); - EmitConditional(dynamicParameters, () => + if (!mesh.TaskLaunched) { - var address = Pair64(Load(_uintType, parameters[4]), Load(_uintType, parameters[5])); - for (var index = 0; index < parameters.Length; index++) - Store(parameters[index], _module.AddInstruction(SpirvOp.Load, _uintType, - DeviceWordPointer(IAdd64(address, ULong((ulong)index * 4))), 2u, 4u)); - }); + // The reserved index-size tag selects a submission-owned parameter block. + // Both modes keep the same six-word shader-data layout. + var dynamicParameters = _module.AddInstruction(SpirvOp.IEqual, _boolType, + Load(_uintType, parameters[3]), UInt(uint.MaxValue)); + EmitConditional(dynamicParameters, () => + { + var address = Pair64(Load(_uintType, parameters[4]), Load(_uintType, parameters[5])); + for (var index = 0; index < parameters.Length; index++) + Store(parameters[index], _module.AddInstruction(SpirvOp.Load, _uintType, + DeviceWordPointer(IAdd64(address, ULong((ulong)index * 4))), 2u, 4u)); + }); + } var drawCount = Load(_uintType, parameters[0]); var firstVertex = Load(_uintType, parameters[1]); var firstInstance = Load(_uintType, parameters[2]); @@ -477,6 +491,13 @@ private void InitializeMeshInputs() StoreV(8, IAdd(firstInstance, groupY), guardWithExec: false); } + // A draw parameter of a task-launched draw. The payload holds the first three (SpirvMeshTask); + // the draw is not indexed, so the others are 0. + private uint TaskPayloadParameter(int index) => index < SpirvMeshTask.PayloadWordCount + ? Load(_uintType, _module.AddInstruction(SpirvOp.AccessChain, + _module.TypePointer(SpirvStorageClass.TaskPayloadWorkgroupExt, _uintType), _meshTaskPayload, UInt((uint)index))) + : UInt(0); + private uint SaturatingSubtract(uint value, uint decrement) => _module.AddInstruction(SpirvOp.Select, _uintType, _module.AddInstruction(SpirvOp.ULessThan, _boolType, value, decrement), @@ -638,8 +659,9 @@ private void CommitMeshLaneOutputs(uint vertices, uint primitives) EmitConditional(_module.AddInstruction(SpirvOp.ULessThan, _boolType, lane, primitives), () => { var packed = Load(_uintType, _meshPrimitiveValue); + // Three 9-bit vertex indices at bits 0, 10 and 20; bit 9 of each field is that vertex's edge flag. uint Vertex(uint bit) => _module.AddInstruction(SpirvOp.BitFieldUExtract, - _uintType, packed, UInt(bit), UInt(10)); + _uintType, packed, UInt(bit), UInt(9)); var indices = _module.AddInstruction(SpirvOp.CompositeConstruct, _uvec3Type, Vertex(0), Vertex(10), Vertex(20)); Store(MeshArrayElement(_meshPrimitiveIndicesOutput, _uvec3Type, lane, diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.NativeWave32Lowering.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.NativeWave32Lowering.cs index 3491e4fb6..5176069d6 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.NativeWave32Lowering.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.NativeWave32Lowering.cs @@ -118,7 +118,13 @@ public uint BroadcastFirstActive(uint value) context._uintType, activeLanes, 0); - var firstActiveLane = context.Ext(73, context._uintType, activeLow); + // V_READFIRSTLANE_B32 reads lane 0 when EXEC is empty (RDNA2 ISA 12.8); FindILsb(0) is not a lane. + var firstActiveLane = context._module.AddInstruction( + SpirvOp.Select, + context._uintType, + context._module.AddInstruction(SpirvOp.IEqual, context._boolType, activeLow, context.UInt(0)), + context.UInt(0), + context.Ext(73, context._uintType, activeLow)); return context._module.AddInstruction( SpirvOp.GroupNonUniformBroadcast, context._uintType, diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.NativeWave64Lowering.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.NativeWave64Lowering.cs index d4daa6e1b..8a6b4c213 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.NativeWave64Lowering.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.NativeWave64Lowering.cs @@ -118,12 +118,20 @@ public uint BroadcastFirstActive(uint value) SpirvOp.UConvert, context._uintType, context.ShiftRightLogical64(activeLanes, context._module.Constant64(context._ulongType, 32))); - var firstActiveLane = context._module.AddInstruction( + var firstSetLane = context._module.AddInstruction( SpirvOp.Select, context._uintType, context._module.AddInstruction(SpirvOp.IEqual, context._boolType, activeLow, context.UInt(0)), context.IAdd(context.Ext(73, context._uintType, activeHigh), context.UInt(32)), context.Ext(73, context._uintType, activeLow)); + // V_READFIRSTLANE_B32 reads lane 0 when EXEC is empty (RDNA2 ISA 12.8). + var firstActiveLane = context._module.AddInstruction( + SpirvOp.Select, + context._uintType, + context._module.AddInstruction(SpirvOp.IEqual, context._boolType, activeLanes, + context._module.Constant64(context._ulongType, 0)), + context.UInt(0), + firstSetLane); return context._module.AddInstruction( SpirvOp.GroupNonUniformBroadcast, context._uintType, diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.RayIntersect.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.RayIntersect.cs index 4e1f96991..ed639e09e 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.RayIntersect.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.RayIntersect.cs @@ -105,10 +105,10 @@ private void EmitRayIntersectActive(Gen5RayIntersectControl ray, bool bvh64) Store(result[0], UInt(0x7F80_0000)); Store(result[1], UInt(0x3F80_0000)); Store(result[3], UInt(0)); - var (_, mapped) = ResolveDeviceAddress(nodeAddress); + var (pointer, mapped) = ResolveDeviceAddress(nodeAddress); EmitConditional(mapped, () => { - var values = EmitRayTriangle(nodeAddress, nodeType, barycentrics, origin, direction); + var values = EmitRayTriangle(new RayNode(pointer, pointer), nodeType, barycentrics, origin, direction); for (var component = 0; component < values.Length; component++) Store(result[component], values[component]); }); @@ -116,15 +116,16 @@ private void EmitRayIntersectActive(Gen5RayIntersectControl ray, bool bvh64) // Each box format reads only its own node bytes. void EmitBoxes(bool fp16) { - var (_, mapped) = ResolveDeviceAddress(nodeAddress); + var (first, mapped) = ResolveDeviceAddress(nodeAddress); + var second = first; if (!fp16) { - var (_, secondMapped) = ResolveDeviceAddress(IAdd64(nodeAddress, ULong(64))); + (second, var secondMapped) = ResolveDeviceAddress(IAdd64(nodeAddress, ULong(64))); mapped = LogicalAnd(mapped, secondMapped); } EmitConditional(mapped, () => { - var children = EmitRayBoxes(nodeAddress, fp16, boxGrow, boxSort, extent, origin, inverseDirection); + var children = EmitRayBoxes(new RayNode(first, second), fp16, boxGrow, boxSort, extent, origin, inverseDirection); for (var component = 0; component < children.Length; component++) Store(result[component], children[component]); }); @@ -161,14 +162,20 @@ private uint[] LoadRayVector(Gen5RayIntersectControl ray, bool bvh64, bool inver return values; } - private uint LoadNodeDword(uint nodeAddress, uint dword) => - LoadDeviceDword(IAdd64(nodeAddress, ULong(dword * 4ul))); + // A node's 64-byte units, each resolved once through the page table. A unit is 64-byte aligned and a page is + // larger, so one resolution covers every dword of the unit; a float32 box node has a second unit, which can be + // on the next page. The caller loads only when both are mapped. + private readonly record struct RayNode(uint First, uint Second); - private uint LoadNodeFloat(uint nodeAddress, uint dword) => - Bitcast(_floatType, LoadNodeDword(nodeAddress, dword)); + private uint LoadNodeDword(RayNode node, uint dword) => + _module.AddInstruction(SpirvOp.Load, _uintType, + DeviceWordPointer(IAdd64(dword < 16 ? node.First : node.Second, ULong(dword % 16 * 4ul))), 2u, 4u); + + private uint LoadNodeFloat(RayNode node, uint dword) => + Bitcast(_floatType, LoadNodeDword(node, dword)); // Project onto the dominant ray axis. Shared edges use a top-left rule. - private uint[] EmitRayTriangle(uint nodeAddress, uint nodeType, uint barycentrics, + private uint[] EmitRayTriangle(RayNode nodeAddress, uint nodeType, uint barycentrics, IReadOnlyList origin, IReadOnlyList direction) { _module.AddName(nodeType, "rayTriangleType"); @@ -292,7 +299,7 @@ private uint RayArithmetic(SpirvOp opcode, uint left, uint right) } // Grow only the exit distance. The ray extent remains an exclusive limit. - private uint[] EmitRayBoxes(uint nodeAddress, bool fp16, uint boxGrow, uint boxSort, uint extent, + private uint[] EmitRayBoxes(RayNode nodeAddress, bool fp16, uint boxGrow, uint boxSort, uint extent, IReadOnlyList origin, IReadOnlyList inverseDirection) { var label = fp16 ? "rayBox16" : "rayBox32"; @@ -359,7 +366,7 @@ private uint[] EmitRayBoxes(uint nodeAddress, bool fp16, uint boxGrow, uint boxS } // Bound 0-2 is the minimum, 3-5 the maximum of one child box. - private uint BoxBound(uint nodeAddress, bool fp16, uint child, uint bound) + private uint BoxBound(RayNode nodeAddress, bool fp16, uint child, uint bound) { var index = child * 6 + bound; if (!fp16) diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Resources.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Resources.cs index 6d099d75e..d7defaef8 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Resources.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Resources.cs @@ -165,6 +165,7 @@ private sealed partial class CompilationContext private readonly Dictionary _imageClasses = []; private readonly Dictionary _indirectKeyScratch = []; private readonly Dictionary _heapArrays = []; + private uint _heapFeedback; private uint _pushData; private uint _shaderData; private uint _mipStatistics; @@ -210,6 +211,7 @@ public CompilationContext(ShaderCompileRequest request, SharedCallBodies? shared ulong[]? callArguments = null, ulong[]? callTargets = null, bool inheritBlockState = true) { _module = new SpirvModuleBuilder { InheritBlockState = inheritBlockState }; + _module.BeforeBlockExit = FlushDeferredGuards; _request = request; // The layout decides: ShaderResourcePlan binds the fallback address for a program it lowers compactly. _compactMemoryAccess = Gen5ShaderCallLinker.IsLinked(request.Program) || @@ -226,6 +228,8 @@ public CompilationContext(ShaderCompileRequest request, SharedCallBodies? shared _usesCoherentBufferPairs = request.Program.Instructions.Any(static instruction => instruction.Opcode is "BufferLoadDwordx2" or "BufferStoreDwordx2" && instruction.Control is Gen5BufferMemoryControl { Glc: true }); + _usesBufferQwordAtomics = request.SupportsBufferInt64Atomics && request.Program.Instructions.Any(static instruction => + instruction.Opcode is "BufferAtomicSwapX2" or "BufferAtomicAndX2" or "BufferAtomicOrX2"); _stage = request.Stage switch { ShaderStage.Vertex => Gen5SpirvStage.Vertex, @@ -391,6 +395,15 @@ instruction.Control is Gen5ImageControl && _interfaces.Add(_runtimeBufferBiases); } + if (layout.BufferStrideCount != 0) + { + var strideArrayType = _module.TypeArray(_uintType, layout.BufferStrideCount); + _runtimeBufferStrides = _module.AddGlobalVariable(_module.TypePointer(SpirvStorageClass.Private, strideArrayType), + SpirvStorageClass.Private, _module.ConstantNull(strideArrayType)); + _module.AddName(_runtimeBufferStrides, "guestBufferStride"); + _interfaces.Add(_runtimeBufferStrides); + } + if (info.UsesDeviceAddresses || _stage == Gen5SpirvStage.Mesh || layout.UsesTessellationData || layout.UsesTableBlock) { _module.AddCapability(SpirvCapability.PhysicalStorageBufferAddresses); @@ -509,6 +522,11 @@ private void DeclareBufferArray(uint count, uint bindingNumber) { DeclareBufferPairArray(count, bindingNumber); } + + if (_usesBufferQwordAtomics) + { + DeclareBufferQwordArray(count, bindingNumber); + } } // The same buffers as dword pairs. The GPU does an aligned DWORDX2 access as one 64-bit access, so a thread @@ -538,6 +556,31 @@ private void DeclareBufferPairArray(uint count, uint bindingNumber) _interfaces.Add(_globalBufferPairs); } + // The same buffers as 64-bit words. The GPU does each X2 buffer atomic (SWAP, AND, OR) as one 64-bit atomic, so a + // thread group reading another's {value, status} pair never takes one half of it from an older update. + private void DeclareBufferQwordArray(uint count, uint bindingNumber) + { + _module.AddCapability(SpirvCapability.Int64Atomics); + var block = _module.TypeStruct(AddressRuntimeArray()); + _module.AddDecoration(block, SpirvDecoration.Block); + _module.AddMemberDecoration(block, 0, SpirvDecoration.Offset, 0); + _globalBufferQwords = _module.AddGlobalVariable( + _module.TypePointer(SpirvStorageClass.StorageBuffer, _module.TypeArray(block, count)), + SpirvStorageClass.StorageBuffer); + _module.AddName(_globalBufferQwords, "guestBufferQwords"); + _module.AddDecoration(_globalBufferQwords, SpirvDecoration.DescriptorSet, 0); + _module.AddDecoration(_globalBufferQwords, SpirvDecoration.Binding, bindingNumber); + if (!_usesCoherentBufferPairs) + { + // The pair view already marks the dword view aliased. + _module.AddDecoration(_globalBuffers, SpirvDecoration.Aliased); + } + + _module.AddDecoration(_globalBufferQwords, SpirvDecoration.Aliased); + _module.AddDecoration(_globalBufferQwords, SpirvDecoration.Coherent); + _interfaces.Add(_globalBufferQwords); + } + // One storage block holding a runtime array of dwords. private uint DeclareWordBlock(string name, uint bindingNumber) { @@ -661,8 +704,8 @@ private void DeclareImageClass(DescriptorBinding binding, uint bindingNumber) // ---- initial state ---- - // User data comes from push data or the shader-data buffer, and the packed memory - // offset bytes become the per-buffer byte biases. + // User data comes from push data or the shader-data buffer, the packed memory offset bytes become the per-buffer + // byte biases, and the packed strides the per-buffer strides. private void EmitLayoutInitialState() { var layout = _request.Bindings; @@ -678,6 +721,13 @@ private void EmitLayoutInitialState() Store(RuntimeBufferBiasPointer((int)buffer), bias); } + for (uint buffer = 0; buffer < layout.BufferStrideCount; buffer++) + { + var packed = LoadShaderDataDword(UInt(layout.BufferStridesDword + (buffer / 2))); + var stride = BitwiseAnd(ShiftRightLogical(packed, UInt((buffer % 2) * 16)), UInt(0x3FFF)); + Store(RuntimeBufferStridePointer((int)buffer), stride); + } + if (layout.UsesTableBlock) { Store(_tableBlock, Pair64(LoadShaderDataDword(UInt(layout.TableBlockDword)), LoadShaderDataDword(UInt(layout.TableBlockDword + 1)))); @@ -723,13 +773,17 @@ private uint TableBufferLength(int binding) => private readonly Dictionary _bufferBaseValues = []; private readonly Dictionary _bufferLengthValues = []; private readonly Dictionary _bufferBiasValues = []; + private readonly Dictionary _bufferStrideValues = []; private uint _bufferValuesFunction; + // The per-buffer byte biases, strides and table-block bases and lengths, read once per function after they are stored + // (main) or on entry (outlined bodies); later uses in the same function take these values instead of loading again. private void CaptureBufferTableValues() { _bufferBaseValues.Clear(); _bufferLengthValues.Clear(); _bufferBiasValues.Clear(); + _bufferStrideValues.Clear(); _bufferValuesFunction = _module.CurrentFunction; var count = _request.Resources.Info.Buffers.Count; for (var buffer = 0; buffer < count; buffer++) @@ -745,6 +799,11 @@ private void CaptureBufferTableValues() _bufferLengthValues[buffer] = Load(_uintType, TableBufferLengthPointer(buffer)); } } + + for (var buffer = 0; buffer < _request.Bindings.BufferStrideCount; buffer++) + { + _bufferStrideValues[buffer] = Load(_uintType, RuntimeBufferStridePointer(buffer)); + } } private uint? CapturedBufferValue(Dictionary values, int binding) => @@ -768,9 +827,28 @@ private uint LoadShaderDataDword(uint dwordIndex) return LoadBlockWord(_shaderData, dwordIndex); } - // A bounds-checked dword of a storage block; outside the block reads zero. + // A shader-data dword the layout places (inside the push data or the block the host binds whole), loaded in the current + // function's entry block: the host writes shader data before the dispatch and the invocation never writes it, so the + // operations of it and of constants run once per function (SpirvModuleBuilder.EntryWordLoad). In place when the entry + // is not open. + private uint LoadShaderDataDwordAtEntry(uint dwordIndex) + { + var layout = _request.Bindings; + var value = layout.UsesPushData + ? _module.EntryWordLoad(_uintType, _pushConstantUintPointer, _pushData, UInt(0), UInt(layout.PushDataStartDword + dwordIndex)) + : _module.EntryWordLoad(_uintType, _storageUintPointer, _shaderData, UInt(0), UInt(dwordIndex)); + return value != 0 ? value : LoadShaderDataDword(UInt(dwordIndex)); + } + + // A bounds-checked dword of a storage block; outside the block reads zero. The host binds these blocks as whole + // dwords (UploadDwords, the 64 KiB GDS), so robustBufferAccess2 bounds them where the length does. private uint LoadBlockWord(uint block, uint dwordIndex) { + if (_request.RobustBufferAccess2) + { + return Load(_uintType, BlockWordPointer(block, RobustDwordIndex(dwordIndex))); + } + var length = StorageBlockLength(block); var inRange = _module.AddInstruction(SpirvOp.ULessThan, _boolType, dwordIndex, length); var safeIndex = _module.AddInstruction(SpirvOp.Select, _uintType, inRange, dwordIndex, UInt(0)); @@ -802,9 +880,12 @@ private void InitializeStorageBlockLengths() } // A compact program's fallback address (ResolveCompactDeviceAddress): a readable address the host binds - // (DescriptorBindingKind.DeviceAddressFallback), read once. + // (DescriptorBindingKind.DeviceAddressFallback), read once. The page table's length is read beside it, once per + // function (main and each outlined body); a lookup in any other function reads it itself. private uint _deviceAddressFallback; private uint _deviceFallbackPointer; + private uint _pageTableLength; + private uint _pageTableLengthFunction; private void InitializeDeviceAddressFallback() { @@ -812,6 +893,8 @@ private void InitializeDeviceAddressFallback() { _deviceFallbackPointer = Pair64(Load(_uintType, BlockWordPointer(_deviceAddressFallback, UInt(0))), Load(_uintType, BlockWordPointer(_deviceAddressFallback, UInt(1)))); + _pageTableLength = _module.AddInstruction(SpirvOp.ArrayLength, _uintType, _pageTable, 0); + _pageTableLengthFunction = _module.CurrentFunction; } } @@ -992,7 +1075,9 @@ private uint Pair64(uint low, uint high) => { var masked = And64(address64, ULong(DeviceAddressMask)); var pageIndex64 = _module.AddInstruction(SpirvOp.ShiftRightLogical, _ulongType, masked, ULong(DeviceAddressPageBits)); - var tableLength = _module.AddInstruction(SpirvOp.ArrayLength, _uintType, _pageTable, 0); + var tableLength = _pageTableLengthFunction != 0 && _module.CurrentFunction == _pageTableLengthFunction + ? _pageTableLength + : _module.AddInstruction(SpirvOp.ArrayLength, _uintType, _pageTable, 0); var inTable = ULessThan64(pageIndex64, Widen(tableLength)); var pageIndex = Narrow(pageIndex64); var entry = Load(_ulongType, _module.AddInstruction(SpirvOp.AccessChain, _storageUlongPointer, _pageTable, UInt(0), @@ -1085,6 +1170,12 @@ private uint LoadMappedDeviceDword(uint pointer, uint valid) // Loads one aligned dword through a device address; an unmapped page reads zero. private uint LoadDeviceDword(uint address64) { + if (UsesSharedDeviceLoads) + { + var always = _module.ConstantBool(true); + return CallDeviceDword(address64, always, always); + } + var (pointer, valid) = ResolveDeviceAddress(address64); if (_compactMemoryAccess) { @@ -1100,6 +1191,11 @@ private uint LoadDeviceDword(uint address64) // As above when allowed, in a compact program; otherwise the dword reads zero and reports no fault. private uint LoadDeviceDword(uint address64, uint allowed) { + if (UsesSharedDeviceLoads) + { + return CallDeviceDword(address64, allowed, allowed); + } + var (pointer, valid) = ResolveCompactDeviceAddress(address64, allowed); return LoadMappedDeviceDword(pointer, LogicalAnd(allowed, valid)); } @@ -1108,7 +1204,9 @@ private void StoreDeviceDword(uint address64, uint value, uint allowed) { var (pointer, valid) = ResolveDeviceAddress(address64); EmitConditional(LogicalAnd(allowed, valid), () => - _module.AddStatement(SpirvOp.Store, DeviceWordPointer(pointer), value, 2u, 4u)); + { + _module.AddStatement(SpirvOp.Store, DeviceWordPointer(pointer), value, 2u, 4u); + }); } private void StoreDeviceMaskedWord(uint address64, uint value, uint mask, uint allowed) @@ -1314,7 +1412,28 @@ private uint[] LoadDeviceDwordRange(uint address64, IReadOnlyList allowed) return [LoadDeviceDword(address64, allowed[0])]; } - // The page offset of the first dword decides which dwords lie in its page. + // The whole range through one shared function per range length, which holds the form below. + if (UsesSharedDeviceRanges) + { + return CallDeviceDwordRange(address64, allowed); + } + + // Through the shared function, one call per dword in order: the last call that reports a missing page leaves it, + // as the second page's report after the first page's does below. + if (UsesSharedDeviceLoads && !_emittingDeviceRange) + { + var called = new uint[count]; + for (var dword = 0; dword < count; dword++) + { + called[dword] = CallDeviceDword(dword == 0 ? address64 : IAdd64(address64, ULong((ulong)dword * sizeof(uint))), + allowed[dword], allowed[dword]); + } + + return called; + } + + // The page offset of the first dword decides which dwords lie in its page: dword i does when + // pageOffset + 4i < PageSize, tested as pageOffset < PageSize - 4i (both terms are below the page size). var pageOffset = Narrow(And64(address64, ULong(DeviceAddressPageSize - 1))); var firstPage = new uint[count]; var firstAllowed = allowed[0]; @@ -1323,21 +1442,22 @@ private uint[] LoadDeviceDwordRange(uint address64, IReadOnlyList allowed) for (var index = 1; index < count; index++) { firstPage[index] = _module.AddInstruction(SpirvOp.ULessThan, _boolType, - IAdd(pageOffset, UInt((uint)index * sizeof(uint))), UInt((uint)DeviceAddressPageSize)); + pageOffset, UInt((uint)DeviceAddressPageSize - (uint)index * sizeof(uint))); firstAllowed = _module.AddInstruction(SpirvOp.LogicalOr, _boolType, firstAllowed, LogicalAnd(allowed[index], firstPage[index])); lastAllowed = _module.AddInstruction(SpirvOp.LogicalOr, _boolType, lastAllowed, LogicalAnd(allowed[index], LogicalNot(firstPage[index]))); } var (firstPointer, firstMapped) = ResolveCompactDeviceAddress(address64, firstAllowed); var (lastPointer, lastMapped) = ResolveCompactDeviceAddress(IAdd64(address64, ULong((ulong)(count - 1) * sizeof(uint))), lastAllowed); + // Dword i is its page's base + 4i; the last page's base is its pointer moved back to dword 0. var values = new uint[count]; + var lastBase = ISub64(lastPointer, ULong((ulong)(count - 1) * sizeof(uint))); for (var index = 0; index < count; index++) { var pointer = index == 0 ? firstPointer - : _module.AddInstruction(SpirvOp.Select, _ulongType, firstPage[index], - IAdd64(firstPointer, ULong((ulong)index * sizeof(uint))), - ISub64(lastPointer, ULong((ulong)(count - 1 - index) * sizeof(uint)))); + : IAdd64(_module.AddInstruction(SpirvOp.Select, _ulongType, firstPage[index], firstPointer, lastBase), + ULong((ulong)index * sizeof(uint))); var mapped = index == 0 ? firstMapped : _module.AddInstruction(SpirvOp.Select, _boolType, firstPage[index], firstMapped, lastMapped); @@ -2042,6 +2162,7 @@ private bool TryEmitPhysicalStorageBufferMemory( out string error) { error = string.Empty; + FlushDeferredGuards(); if (control.Typed || instruction.Opcode.Contains("Format", StringComparison.Ordinal)) { error = $"runtime buffer descriptor does not support the formatted access {instruction.Opcode}"; @@ -2168,6 +2289,12 @@ uint InRange(uint index) private uint LoadBoundedDeviceDword(uint address64, uint inRange) { + // The compact path below reports a missing page whether or not the dword is in range. + if (UsesSharedDeviceLoads) + { + return CallDeviceDword(address64, inRange, _module.ConstantBool(true)); + } + var (pointer, valid) = ResolveDeviceAddress(address64); if (_compactMemoryAccess) { @@ -2286,7 +2413,8 @@ private bool TryResolveLayoutImage( out uint imageObject, out uint dstSelect, out string error, - (uint Resource, uint Element)? fixedElement = null) + (uint Resource, uint Element)? fixedElement = null, + bool heapVolumeLayers = false) { error = string.Empty; resource = default; @@ -2338,16 +2466,33 @@ private bool TryResolveLayoutImage( return false; } - // A call record's image is the element of set 1 the host resolved for the record its callee's entry found, not its - // null element in set 0. + // A bindless heap image reads the record its key picks from set 1, not its null element in set 0. var heapImageSlot = BindlessHeap.ImageSlot(kind.Value); - var fromHeap = false; + HeapRecordUse heapImage = default; + var fromHeap = fixedElement is null && heapImageSlot >= 0 && + request.HeapImageByMemoryIndex.TryGetValue(memoryIndex, out heapImage); + if (heapVolumeLayers) + { + if (!fromHeap || heapImageSlot != BindlessHeap.VolumeSlot) + { + error = "only a 3D heap image read has a layered alternative"; + return false; + } + + heapImageSlot = BindlessHeap.VolumeLayerSlot; + imageClass = VolumeLayerClass(); + } uint elementPointer; uint imageValue; - if (fixedElement is null && heapImageSlot >= 0 && + if (fromHeap) + { + (elementPointer, imageValue) = LoadHeapElement(heapImageSlot, imageClass.ImageType, HeapRecordIndex(heapImage)); + } + else if (fixedElement is null && heapImageSlot >= 0 && request.CallRecordImageByMemoryIndex.TryGetValue(memoryIndex, out var recordImage)) { - (elementPointer, imageValue) = LoadHeapElement(heapImageSlot, imageClass.ImageType, CallRecordElement(recordImage.Field)); + // A call record's image is the element the host resolved for the record its callee's entry found. + (elementPointer, imageValue) = LoadHeapElement(heapImageSlot, imageClass.ImageType, CallRecordElement(recordImage.Field), mark: false); fromHeap = true; } else @@ -2361,9 +2506,15 @@ private bool TryResolveLayoutImage( if (UsesSampler(instruction.Opcode)) { uint sampler; - if (fixedElement is null && request.CallRecordSamplerByMemoryIndex.TryGetValue(memoryIndex, out var recordSampler)) + if (fixedElement is null && request.HeapSamplerByMemoryIndex.TryGetValue(memoryIndex, out var heapSampler)) + { + var samplerSlot = imageInfo.DepthCompare ? BindlessHeap.CompareSamplerSlot : BindlessHeap.SamplerSlot; + (_, sampler) = LoadHeapElement(samplerSlot, _module.TypeSampler(), HeapRecordIndex(heapSampler)); + fromHeap = true; + } + else if (fixedElement is null && request.CallRecordSamplerByMemoryIndex.TryGetValue(memoryIndex, out var recordSampler)) { - (_, sampler) = LoadHeapElement(recordSampler.Slot, _module.TypeSampler(), CallRecordElement(recordSampler.Field)); + (_, sampler) = LoadHeapElement(recordSampler.Slot, _module.TypeSampler(), CallRecordElement(recordSampler.Field), mark: false); fromHeap = true; } else @@ -2419,13 +2570,36 @@ private bool TryResolveLayoutImage( imageInfo.ConversionFormat, imageInfo.ShaderSwizzle, imageInfo.EmulatedCompareFunction, - resourceIndex); + resourceIndex, + SwizzleSlot: fromHeap || request.Bindings.StorageImageSwizzleCount == 0 ? -1 + : RuntimeImageSwizzle.Slot(info.Images, resourceIndex)); dstSelect = imageInfo.ShaderSwizzle; return true; } // ---- bindless heap ---- + // The float 2D-array class of set 1, which a 3D heap read takes for a record that holds a 2D texture. + private LayoutImageClass VolumeLayerClass() + { + var imageType = _module.TypeImage(_floatType, SpirvImageDim.Dim2D, depth: false, arrayed: true, multisampled: false, + sampled: 1u, SpirvImageFormat.Unknown); + return new LayoutImageClass(0, imageType, _module.TypePointer(SpirvStorageClass.UniformConstant, imageType), _floatType, + ImageComponentKind.Float, IsStorage: false, Arrayed: true, Cube: false, Multisampled: false, SpirvImageDim.Dim2D, []); + } + + // The record a heap read picks: the dynamic offset its key read kept plus the read's immediate, in records. + private uint HeapRecordIndex(HeapRecordUse use) + { + var key = _indirectKeyScratch.TryGetValue(use.KeyMemoryIndex, out var scratch) ? Load(_uintType, scratch) : UInt(0); + var shift = use.RecordBytes == BindlessHeap.SamplerRecordBytes ? 4u : 5u; + var record = ShiftRightLogical(IAdd(key, UInt(use.Immediate)), UInt(shift)); + // Set 1 holds the heap's records below CallRecordFirstIndex (call records own the elements above); any other record + // reads the null element. + var inHeap = _module.AddInstruction(SpirvOp.ULessThan, _boolType, record, UInt(BindlessHeap.CallRecordFirstIndex)); + return _module.AddInstruction(SpirvOp.Select, _uintType, inHeap, record, UInt(BindlessHeap.CallRecordNullIndex)); + } + // One runtime array of set 1, declared at its first use. private uint HeapArray(int slot, uint elementType) { @@ -2452,8 +2626,8 @@ private uint HeapArray(int slot, uint elementType) return variable; } - // Loads one element of a set-1 array. - private (uint Pointer, uint Value) LoadHeapElement(int slot, uint elementType, uint index) + // Loads one element of a set-1 array; a heap record is marked in the feedback bitset, so the host gives it a view. + private (uint Pointer, uint Value) LoadHeapElement(int slot, uint elementType, uint index, bool mark = true) { var array = HeapArray(slot, elementType); var pointer = _module.AddInstruction( @@ -2461,6 +2635,11 @@ private uint HeapArray(int slot, uint elementType) _module.AddDecoration(pointer, SpirvDecoration.NonUniform); var value = Load(elementType, pointer); _module.AddDecoration(value, SpirvDecoration.NonUniform); + if (mark) + { + MarkHeapRecord(slot, index); + } + return (pointer, value); } @@ -2594,6 +2773,53 @@ uint Clamped(uint index) => _module.AddInstruction(SpirvOp.Select, _uintType, return _module.AddInstruction(SpirvOp.Select, _uintType, found, element, UInt(BindlessHeap.CallRecordNullIndex)); } + // The records marked since the last branch, by slot, index and EXEC value (0: EXEC known full), and the block the + // last of those marks ended in. + private readonly HashSet<(int Slot, uint Index, uint Exec)> _markedHeapRecords = []; + private uint _markedHeapRecordsBlock; + + // Sets the record's bit in its array's feedback words; a plain read first keeps marked records from repeating the atomic. + // A record marked again under the same EXEC value with no branch since finds its bit set, so that mark is left out. + private void MarkHeapRecord(int slot, uint index) + { + if (_heapFeedback == 0) + { + var block = _module.TypeStruct(WordRuntimeArray()); + _module.AddDecoration(block, SpirvDecoration.Block); + _module.AddMemberDecoration(block, 0, SpirvDecoration.Offset, 0); + _heapFeedback = _module.AddGlobalVariable( + _module.TypePointer(SpirvStorageClass.StorageBuffer, block), SpirvStorageClass.StorageBuffer); + _module.AddName(_heapFeedback, "heapFeedback"); + _module.AddDecoration(_heapFeedback, SpirvDecoration.DescriptorSet, BindlessHeap.DescriptorSet); + _module.AddDecoration(_heapFeedback, SpirvDecoration.Binding, BindlessHeap.FeedbackBinding); + _interfaces.Add(_heapFeedback); + } + + if (_module.CurrentBlock != _markedHeapRecordsBlock) + { + _markedHeapRecords.Clear(); + } + + // Only a lane the guest runs marks its record: the idle lanes of a waterfall hold keys nothing samples. + var exec = _execKnownFull ? 0 : Load(_boolType, _exec); + if (!_markedHeapRecords.Add((slot, index, exec))) + { + return; + } + + var word = IAdd(UInt((uint)slot * BindlessHeap.FeedbackWordsPerArray), ShiftRightLogical(index, UInt(5))); + var bit = ShiftLeftLogical(UInt(1), BitwiseAnd(index, UInt(31))); + var pointer = BlockWordPointer(_heapFeedback, word); + var unmarked = _module.AddInstruction(SpirvOp.IEqual, _boolType, BitwiseAnd(Load(_uintType, pointer), bit), UInt(0)); + if (exec != 0) + { + unmarked = LogicalAnd(unmarked, exec); + } + + EmitConditional(unmarked, () => _module.AddInstruction(SpirvOp.AtomicOr, _uintType, pointer, UInt(1), UInt(0), bit)); + _markedHeapRecordsBlock = _module.CurrentBlock; + } + private const uint MipStatisticsEntries = 257; private const uint MipStatisticsNoCounter = 0x8000; @@ -2826,6 +3052,7 @@ private bool TryEmitGlobalDataShare(Gen5ShaderInstruction instruction, Gen5DataS return true; } case "DsRead2B64": + case "DsRead2St64B64": return TryEmitDataShareReadPair64(instruction, control, out error); case "DsRead2B32": { @@ -2883,6 +3110,9 @@ private bool TryEmitDataShareReadPair64(Gen5ShaderInstruction instruction, Gen5D return false; } + // The ST64 form counts its offsets in 64 pairs of dwords, as DS_WRITE2ST64_B64 does. + var offsetStride = instruction.Opcode == "DsRead2St64B64" ? 512u : 8u; + EmitExecConditional(() => { var address = GetRawSource(instruction, 0); @@ -2891,7 +3121,7 @@ private bool TryEmitDataShareReadPair64(Gen5ShaderInstruction instruction, Gen5D for (var component = 0; component < values.Length; component++) { var pairOffset = component < 2 ? control.Offset0 : control.Offset1; - var byteOffset = pairOffset * sizeof(ulong) + (uint)(component % 2) * sizeof(uint); + var byteOffset = pairOffset * offsetStride + (uint)(component % 2) * sizeof(uint); values[component] = control.Gds ? LoadBlockWord(_globalDataShare, GlobalDataShareIndex(address, byteOffset)) : Load(_uintType, LdsPointer(address, byteOffset)); diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.SharedCalls.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.SharedCalls.cs index 3ffc51272..4339eed2b 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.SharedCalls.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.SharedCalls.cs @@ -680,6 +680,8 @@ private bool TryEmitSharedBodyCall(SharedBodyCallControl call, out string error) return false; } + // The body reads and writes the registers of every lane: the EXEC guards deferred in this block land first. + FlushDeferredGuards(); Store(_programCounter, UInt((uint)body.First)); _module.AddInstruction(SpirvOp.FunctionCall, _voidType, body.Function); return true; @@ -741,6 +743,7 @@ private void EmitOutlinedBodyCall(int first, uint function) _module.AddStatement(SpirvOp.SelectionMerge, merge, 0); _module.AddStatement(SpirvOp.BranchConditional, enters, call, merge); _module.AddLabel(call); + FlushDeferredGuards(); _module.AddInstruction(SpirvOp.FunctionCall, _voidType, function); _module.AddStatement(SpirvOp.Branch, merge); _module.AddLabel(merge); diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Tessellation.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Tessellation.cs index 298edc976..35ab39967 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Tessellation.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Tessellation.cs @@ -132,8 +132,9 @@ uint WaveCount(uint controlPoints) }); StoreV(registers.HullVertexVector, IAdd(Load(_uintType, vertex), TessellationWord(Gen5TessellationData.VertexOffset)), false); StoreV(registers.HullLocalVector, local, false); - var instance = IAdd(TessellationWord(Gen5TessellationData.InstanceId), - _module.AddInstruction(SpirvOp.UDiv, _uintType, inputPatch, perInstance)); + // The hardware numbers the instances of a draw from zero. A start instance reaches a program only + // through the user data register its draw packet names. + var instance = _module.AddInstruction(SpirvOp.UDiv, _uintType, inputPatch, perInstance); foreach (var register in registers.HullInstanceVectors) StoreV(register, instance, false); } diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.WaveReductions.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.WaveReductions.cs new file mode 100644 index 000000000..98c250f07 --- /dev/null +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.WaveReductions.cs @@ -0,0 +1,361 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler; + +namespace SharpEmu.ShaderCompiler.Vulkan; + +public static partial class Gen5SpirvTranslator +{ + private sealed partial class CompilationContext + { + // A wave32 row reduction (MIN, MAX, OR, AND, XOR or ADD) computed with a DPP scan and read at the end of a row: + // S_AND_B32 mask, x, entry entry holds a subset of the entry EXEC (IsEntryExecSubset) + // S_ORN2_SAVEEXEC_B32 saved, x EXEC = x | ~EXEC, every lane (x holds EXEC) + // V_CNDMASK_B32 v, identity, value, mask (VOP3) + // V_ v, v, v DPP row_shr:1, 2, 4 and 8, full masks, FI and BOUND_CTRL clear + // [S_MOV_B32 exec_lo, saved] + // V_READLANE_B32 s, v, 15 and/or V_READLANE_B32 s, v, 31 + // On the PS5 every lane of the wave exists, and V_CNDMASK gives each lane outside mask the identity, so lane 15 (31) + // holds the operation over row 0 (1). A host subgroup can lack invocations (a fragment warp that is not full), and + // a pixel shader's V_READLANE reads its own lane. Each read is replaced by a subgroup reduction of the V_CNDMASK + // result over its row, the other rows taking the identity. mask selects only lanes of the entry EXEC, so a lane + // missing from the host subgroup takes the identity on the PS5 too and leaving it out changes nothing. + // The scan itself is emitted unchanged. + private readonly record struct WaveReduction(int CndmaskIndex, uint Vector, SpirvOp Operation, uint Identity, int Row); + + // VCC_LO: SGPRs from here on (VCC, trap registers, M0, NULL, EXEC) are written by instructions that do not name them. + private const uint FirstSpecialScalarRegister = 106; + + private readonly Dictionary _waveReductionValues = new(); + + // The reductions of a block by instruction index: the V_CNDMASK (Row -1) and each replaced V_READLANE. Null when the + // block has none or the host subgroup cannot compute them (one host subgroup must be one guest wave32). + private Dictionary? FindWaveReductions(ShaderBlock block) + { + if (!_request.SubgroupArithmetic || _waveLaneCount != 32 || _pairedLanes || _pairedMeshLanes || + _subgroupInvocationIdInput == 0 || _waveLowering is not NativeWave32Lowering) + { + return null; + } + + Dictionary? found = null; + for (var index = block.StartIndex; index < block.EndIndex; index++) + { + TryMatchWaveReduction(block, index, ref found); + } + + return found; + } + + // After the instruction at index was emitted: keeps a V_CNDMASK result, or replaces a row read. + private void ApplyWaveReduction(Dictionary reductions, int index) + { + if (!reductions.TryGetValue(index, out var reduction)) + { + return; + } + + if (reduction.Row < 0) + { + _waveReductionValues[reduction.CndmaskIndex] = LoadV(reduction.Vector); + return; + } + + if (!_waveReductionValues.TryGetValue(reduction.CndmaskIndex, out var value)) + { + return; + } + + var inRow = _module.AddInstruction( + SpirvOp.IEqual, + _boolType, + ShiftRightLogical(GuestWaveLane(), UInt(4)), + UInt((uint)reduction.Row)); + var contribution = _module.AddInstruction(SpirvOp.Select, _uintType, inRow, value, UInt(reduction.Identity)); + _module.AddCapability(SpirvCapability.GroupNonUniform); + _module.AddCapability(SpirvCapability.GroupNonUniformArithmetic); + StoreS( + _request.Program.Instructions[index].Destinations[0].Value, + _module.AddInstruction(reduction.Operation, _uintType, UInt(3), 0u, contribution)); + } + + // index names the S_ORN2_SAVEEXEC_B32 of a reduction. + private void TryMatchWaveReduction(ShaderBlock block, int index, ref Dictionary? found) + { + var instructions = _request.Program.Instructions; + var saveexec = instructions[index]; + if (saveexec.Opcode != "SOrn2SaveexecB32" || + saveexec.Destinations is not [{ Kind: Gen5OperandKind.ScalarRegister } saved] || + saveexec.Sources is not [{ Kind: Gen5OperandKind.ScalarRegister } execSource] || + !HoldsExec(block, index, execSource.Value)) + { + return; + } + + var at = index + 1; + while (at < block.EndIndex && instructions[at].Opcode is "SWaitcnt" or "SNop") at++; + // The VOP3 form, whose mask is a named SGPR: the VOP2 form reads VCC, which compares and carries write unnamed. + if (at >= block.EndIndex || + instructions[at] is not { Opcode: "VCndmaskB32" } cndmask || + cndmask.Destinations is not [{ Kind: Gen5OperandKind.VectorRegister } scanned] || + cndmask.Sources is not [var identitySource, _, { Kind: Gen5OperandKind.ScalarRegister } mask] || + cndmask.Control is not Gen5Vop3Control { AbsoluteMask: 0, NegateMask: 0, OutputModifier: 0, Clamp: false } || + !TryGetConstantOperand(identitySource, out var identity) || + !SelectsEntryLanes(block, at, mask.Value)) + { + return; + } + + var cndmaskIndex = at; + var vector = scanned.Value; + string? scan = null; + foreach (var shift in new uint[] { 1, 2, 4, 8 }) + { + if (++at >= block.EndIndex || + instructions[at] is not { Control: Gen5DppControl dpp } step || + dpp is not { FetchInactive: false, BoundControl: false, AbsoluteMask: 0, NegateMask: 0, BankMask: 15, RowMask: 15 } || + dpp.Control != 0x110 + shift || + step.Destinations is not [{ Kind: Gen5OperandKind.VectorRegister } written] || written.Value != vector || + step.Sources is not [{ Kind: Gen5OperandKind.VectorRegister } left, { Kind: Gen5OperandKind.VectorRegister } right] || + left.Value != vector || right.Value != vector || + (scan ??= step.Opcode) != step.Opcode) + { + return; + } + } + + var (operation, expectedIdentity) = scan switch + { + "VMaxU32" => (SpirvOp.GroupNonUniformUMax, 0u), + "VMinU32" => (SpirvOp.GroupNonUniformUMin, uint.MaxValue), + "VMaxI32" => (SpirvOp.GroupNonUniformSMax, 0x8000_0000u), + "VMinI32" => (SpirvOp.GroupNonUniformSMin, 0x7FFF_FFFFu), + "VOrB32" => (SpirvOp.GroupNonUniformBitwiseOr, 0u), + "VAndB32" => (SpirvOp.GroupNonUniformBitwiseAnd, uint.MaxValue), + "VXorB32" => (SpirvOp.GroupNonUniformBitwiseXor, 0u), + "VAddU32" => (SpirvOp.GroupNonUniformIAdd, 0u), + _ => (default(SpirvOp), 1u), + }; + if (operation == default || identity != expectedIdentity) + { + return; + } + + at++; + if (at < block.EndIndex && instructions[at] is { Opcode: "SMovB32" } restore && + restore.Destinations is [{ Kind: Gen5OperandKind.ScalarRegister, Value: 126 }] && + restore.Sources is [{ Kind: Gen5OperandKind.ScalarRegister } restored] && restored.Value == saved.Value) + { + at++; + } + + var reads = new List<(int Index, int Row)>(); + for (; at < block.EndIndex && reads.Count < 2; at++) + { + if (instructions[at] is not { Opcode: "VReadlaneB32" } readlane || + readlane.Destinations is not [{ Kind: Gen5OperandKind.ScalarRegister }] || + readlane.Sources.Count < 2 || + readlane.Sources[0] is not { Kind: Gen5OperandKind.VectorRegister } source || source.Value != vector || + !TryGetFixedLane(readlane.Sources[1], out var lane) || lane is not (15 or 31) || + reads.Exists(read => read.Row == (int)(lane >> 4))) + { + break; + } + + reads.Add((at, (int)(lane >> 4))); + } + + if (reads.Count == 0) + { + return; + } + + found ??= new Dictionary(); + found[cndmaskIndex] = new WaveReduction(cndmaskIndex, vector, operation, identity, -1); + foreach (var (readIndex, row) in reads) + { + found[readIndex] = new WaveReduction(cndmaskIndex, vector, operation, identity, row); + } + } + + // Whether the scalar register holds EXEC when the instruction at index runs: it is EXEC itself, or the last + // instruction of the block that may write EXEC before it is S_MOV_B32 exec_lo, register and nothing between them + // writes the register. + private bool HoldsExec(ShaderBlock block, int index, uint register) + { + if (register == 126) + { + return true; + } + + if (register >= FirstSpecialScalarRegister) + { + return false; + } + + var instructions = _request.Program.Instructions; + for (var at = index - 1; at >= block.StartIndex; at--) + { + var instruction = instructions[at]; + if (instruction is { Opcode: "SMovB32", Sources: [{ Kind: Gen5OperandKind.ScalarRegister } source] } && + instruction.Destinations is [{ Kind: Gen5OperandKind.ScalarRegister, Value: 126 }] && + source.Value == register) + { + return true; + } + + if (MayWriteExec(instruction) || MayWriteScalar(instruction, register)) + { + return false; + } + } + + return false; + } + + // Whether the SGPR mask that V_CNDMASK reads at cndmaskIndex selects only lanes of the wave's entry EXEC: its last + // write in the block is S_AND_B32 mask, x, entry (in either order), entry holding a subset of the entry EXEC. + private bool SelectsEntryLanes(ShaderBlock block, int cndmaskIndex, uint mask) + { + if (mask >= FirstSpecialScalarRegister) + { + return false; + } + + var instructions = _request.Program.Instructions; + for (var at = cndmaskIndex - 1; at >= block.StartIndex; at--) + { + var instruction = instructions[at]; + if (MayWriteScalar(instruction, mask)) + { + return instruction is { Opcode: "SAndB32", Sources: [var left, var right] } && + (IsEntryExecSubset(left, at) || IsEntryExecSubset(right, at)); + } + } + + return false; + } + + // Whether the operand is an SGPR that holds a subset of the wave's entry EXEC when the instruction at useIndex runs. + // Its one copy S_MOV_B32 register, exec_lo comes before useIndex, in the entry block (which no branch reaches) and + // before any EXEC write; every other write of it is S_AND_B32 or S_ANDN2_B32 of itself, which keeps a subset. + private bool IsEntryExecSubset(Gen5Operand operand, int useIndex) + { + if (operand.Kind != Gen5OperandKind.ScalarRegister || operand.Value >= FirstSpecialScalarRegister) + { + return false; + } + + var register = operand.Value; + var instructions = _request.Program.Instructions; + var copy = -1; + var inEntryBlock = true; + var execWritten = false; + for (var at = 0; at < instructions.Count; at++) + { + var instruction = instructions[at]; + if (instruction is { Opcode: "SMovB32", Sources: [{ Kind: Gen5OperandKind.ScalarRegister, Value: 126 }] } && + instruction.Destinations is [{ Kind: Gen5OperandKind.ScalarRegister } destination] && + destination.Value == register) + { + if (copy >= 0 || !inEntryBlock || execWritten) + { + return false; + } + + copy = at; + } + else if (MayWriteScalar(instruction, register) && !KeepsSubset(instruction, register)) + { + return false; + } + + execWritten |= MayWriteExec(instruction); + inEntryBlock &= !IsBranch(instruction.Opcode) && instruction.Opcode is not ("SEndpgm" or "SBarrier") && + instruction.Control is not ShaderCallEntryControl; + } + + if (copy < 0 || copy >= useIndex) + { + return false; + } + + // A branch into the entry block would run the copy again, after EXEC may have changed. + for (var at = 0; at < instructions.Count; at++) + { + if (!IsBranch(instructions[at].Opcode) || !TryGetBranchTargetPc(instructions[at], out var target)) + { + continue; + } + + for (var entry = 0; entry <= copy; entry++) + { + if (instructions[entry].Pc == target) + { + return false; + } + } + } + + return true; + } + + // S_AND_B32 register, register, x (either order) and S_ANDN2_B32 register, register, x keep a subset of register. + private static bool KeepsSubset(Gen5ShaderInstruction instruction, uint register) => + instruction.Destinations is [{ Kind: Gen5OperandKind.ScalarRegister } destination] && + destination.Value == register && + instruction switch + { + { Opcode: "SAndB32", Sources: [var left, var right] } => IsScalar(left, register) || IsScalar(right, register), + { Opcode: "SAndn2B32", Sources: [var left, _] } => IsScalar(left, register), + _ => false, + }; + + private static bool IsScalar(Gen5Operand operand, uint register) => + operand.Kind == Gen5OperandKind.ScalarRegister && operand.Value == register; + + // Whether the instruction may write EXEC: a named write of exec_lo or exec_hi, a SAVEEXEC/WREXEC form, or V_CMPX. + private static bool MayWriteExec(Gen5ShaderInstruction instruction) => + MayWriteScalar(instruction, 126) || MayWriteScalar(instruction, 127) || + instruction.Opcode.Contains("exec", StringComparison.OrdinalIgnoreCase) || + instruction.Opcode.StartsWith("VCmpx", StringComparison.Ordinal); + + // Whether the instruction may write the SGPR register. A 64-bit scalar result writes a register pair, of which + // SOP1, SOP2 and SOPK name only the first; a VOP3 or SDWA scalar destination is a pair in wave64. A relative move + // writes an SGPR chosen at run time, and a call entry sets registers it does not name. + private static bool MayWriteScalar(Gen5ShaderInstruction instruction, uint register) + { + if (instruction.Opcode.StartsWith("SMovrel", StringComparison.Ordinal) || + instruction.Control is ShaderCallEntryControl or ShaderCallMatchControl or ShaderCallGroupControl or ShaderCallFaultControl) + { + return true; + } + + var pair = instruction.Opcode.Contains("64", StringComparison.Ordinal); + foreach (var destination in instruction.Destinations) + { + if (destination.Kind == Gen5OperandKind.ScalarRegister && + (destination.Value == register || pair && destination.Value + 1 == register)) + { + return true; + } + } + + var secondary = instruction.Control switch + { + Gen5Vop3Control { ScalarDestination: { } vop3 } => vop3, + Gen5SdwaControl { ScalarDestination: { } sdwa } => sdwa, + _ => (uint?)null, + }; + return secondary is { } value && (value == register || value + 1 == register); + } + + private static bool TryGetConstantOperand(Gen5Operand operand, out uint value) + { + value = operand.Value; + return operand.Kind == Gen5OperandKind.LiteralConstant || + operand.Kind == Gen5OperandKind.EncodedConstant && TryDecodeInlineConstant(operand.Value, out value); + } + } +} diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.cs index 8e4f547f4..44c40dee9 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.cs @@ -87,6 +87,7 @@ private sealed partial class CompilationContext private readonly Dictionary> _savedLaneValues = new(); private readonly bool _usesBufferAtomics; private readonly bool _usesCoherentBufferPairs; + private readonly bool _usesBufferQwordAtomics; // Safety valve for the PC-dispatcher loop. Each iteration executes one // GCN basic block; a correctly-translated shader always reaches its @@ -152,6 +153,7 @@ private sealed partial class CompilationContext private uint _intType; private uint _longType; private uint _ulongType; + private uint _steppedClock; private uint _floatType; private uint _vec2Type; private uint _vec3Type; @@ -163,6 +165,7 @@ private sealed partial class CompilationContext private uint _privateVec2Pointer; private readonly HashSet _flagVariables = []; private uint _runtimeBufferBiases; + private uint _runtimeBufferStrides; // One Private variable per register the program touches, declared on first use. A whole // register-file array is kept only for the VGPRs of a program that indexes them at run time // (V_MOVREL*): MoltenVK lowers a 512-entry private array to thread memory, and every @@ -187,6 +190,7 @@ private sealed partial class CompilationContext private readonly Dictionary<(uint Register, uint Lane), uint> _laneSpillSlots = new(); private uint _globalBuffers; private uint _globalBufferPairs; + private uint _globalBufferQwords; private uint _gfx10BufferFormatTable; private uint _storageBlockPointer; private uint _storagePairBlockPointer; @@ -255,7 +259,10 @@ private readonly record struct SpirvImageResource( uint ConversionFormat = 0, uint ShaderSwizzle = 0, int EmulatedCompareFunction = -1, - int ResourceIndex = -1); + int ResourceIndex = -1, + // The slot of the image's store channel map in shader data (RuntimeImageSwizzle.Slot), or -1 when its stores + // keep the select of the module. + int SwizzleSlot = -1); private readonly record struct SpirvVertexInput( uint Variable, @@ -498,6 +505,8 @@ uint EncodeBool(uint condition) => // After every function that may call it. EmitTypedElementDecoder(); EmitCallRecordSearch(); + EmitDeviceRangeFunctions(); + EmitDeviceDwordFunction(); var model = _stage switch { @@ -519,6 +528,12 @@ uint EncodeBool(uint condition) => SpirvExecutionMode.SignedZeroInfNanPreserve, 32); } + if (_halfType != 0) + { + _module.AddExecutionMode(main, SpirvExecutionMode.RoundingModeRte, 16); + _module.AddExecutionMode(main, SpirvExecutionMode.DenormPreserve, 16); + _module.AddExecutionMode(main, SpirvExecutionMode.SignedZeroInfNanPreserve, 16); + } if (_stage == Gen5SpirvStage.Pixel) { _module.AddExecutionMode(main, SpirvExecutionMode.OriginUpperLeft); @@ -1548,7 +1563,22 @@ private void StoreComputeSystemRegister( private enum SharedMemoryPhase { None, Read, Write } + private IReadOnlyList? _dispatcherStartBlocks; + private int _dispatcherStart; + + // Every block body asks for the dispatcher start of the same immutable block list: scan it once. private int FindComputeDispatcherStart(IReadOnlyList blocks) + { + if (!ReferenceEquals(blocks, _dispatcherStartBlocks)) + { + _dispatcherStart = ScanComputeDispatcherStart(blocks); + _dispatcherStartBlocks = blocks; + } + + return _dispatcherStart; + } + + private int ScanComputeDispatcherStart(IReadOnlyList blocks) { if (_stage != Gen5SpirvStage.Compute || _hasIndirectControlFlow) return 0; var start = blocks.Count; @@ -1712,6 +1742,8 @@ private bool TryEmitBlockBody( } var passedWorkgroupBarrier = false; var pendingSharedReads = false; + var waveReductions = FindWaveReductions(block); + _deferGuards = waveReductions is null && CanDeferGuards; for (var index = block.StartIndex; index < block.EndIndex; index++) { var instruction = _request.Program.Instructions[index]; @@ -1721,6 +1753,11 @@ private bool TryEmitBlockBody( continue; } + if (_deferGuards && ReadsOtherLanes(instruction)) + { + FlushDeferredGuards(); + } + if (lastWorkgroupBarrierIndex >= 0) { if (instruction.Opcode == "SBarrier") @@ -1760,12 +1797,19 @@ private bool TryEmitBlockBody( return false; } + if (waveReductions is not null) + { + ApplyWaveReduction(waveReductions, index); + } + CapturePixelVgprs(instruction); CapturePixelVgprPoints(instruction); MarkPixelPath(instruction); CapturePixelExec(instruction); } + FlushDeferredGuards(); + _deferGuards = false; if (_stage != Gen5SpirvStage.Mesh) _waveLowering.EndBlock(); return true; } @@ -2559,6 +2603,14 @@ Gen5ShaderEncoding.Sopc or return TryEmitScalarAlu(instruction, out error); } + if (instruction.Opcode is "SMemtime" or "SMemrealtime") + { + var clock = ReadShaderClock(); + StoreS(instruction.Destinations[0].Value, Narrow(clock)); + StoreS(instruction.Destinations[1].Value, Narrow(ShiftRightLogical64(clock, ULong(32)))); + return true; + } + if (instruction.Encoding is Gen5ShaderEncoding.Sopp or Gen5ShaderEncoding.Smrd or @@ -2941,6 +2993,7 @@ private bool TryEmitDataShare( return true; } case "DsRead2B64": + case "DsRead2St64B64": return TryEmitDataShareReadPair64(instruction, control, out error); case "DsRead2B32": case "DsRead2St64B32": @@ -3390,6 +3443,26 @@ private void EmitBufferAtomicInRange(uint inRange, bool glc, uint dataRegister, }); } + // An X2 buffer atomic (SWAP, AND, OR) as one 64-bit atomic on the pair in the data registers, low dword first; with + // glc the registers take the pair from before it. + private void EmitQwordAtomic(SpirvOp op, uint pointer, Gen5BufferMemoryControl control) + { + _module.AddCapability(SpirvCapability.Int64Atomics); + var original = EmitAtomic( + op, + _ulongType, + pointer, + scope: 1, + semantics: 0x48, + value: () => Pair64(LoadV(control.VectorData), LoadV(control.VectorData + 1)), + comparator: () => ULong(0)); + if (control.Glc) + { + StoreV(control.VectorData, Narrow(original)); + StoreV(control.VectorData + 1, Narrow(ShiftRightLogical64(original, ULong(32)))); + } + } + // Maps the AMD atomic-op name suffix shared by buffer/image atomics to a SPIR-V opcode. // Inc/Dec approximate the AMD wrap-clamp semantics (MEM = tmp >= DATA ? 0 : tmp + 1), // which is exact for the common 0xFFFFFFFF clamp operand. @@ -3713,7 +3786,6 @@ private bool EmitResolvedBufferMemory( } var specialized = info.Buffers[bindingIndex]; - var stride = UInt(specialized.PackedStride & 0x3FFF); var descriptorFormat = specialized.DescriptorFormat; var descriptorSwizzle = specialized.DescriptorSwizzle; var descriptorWord3 = UInt((specialized.DescriptorFormat << 12) | (specialized.DescriptorSwizzle & 0xFFF)); @@ -3731,14 +3803,22 @@ private bool EmitResolvedBufferMemory( UInt(unchecked((uint)control.OffsetBytes)), scalarOffset); byteAddress = IAdd(byteAddress, vectorOffset); - byteAddress = IAdd( - byteAddress, - _module.AddInstruction(SpirvOp.IMul, _uintType, vectorIndex, stride)); + if (control.IndexEnabled) + { + byteAddress = IAdd(byteAddress, _module.AddInstruction(SpirvOp.IMul, _uintType, vectorIndex, RuntimeBufferStride(bindingIndex))); + } + byteAddress = ApplyGuestBufferByteBias(bindingIndex, byteAddress); var dwordAddress = ShiftRightLogical(byteAddress, UInt(2)); - if (instruction.Opcode is "BufferAtomicSwapX2" or "BufferAtomicOrX2") + if (instruction.Opcode is "BufferAtomicSwapX2" or "BufferAtomicAndX2" or "BufferAtomicOrX2") { + var atomicOp = instruction.Opcode switch + { + "BufferAtomicSwapX2" => SpirvOp.AtomicExchange, + "BufferAtomicAndX2" => SpirvOp.AtomicAnd, + _ => SpirvOp.AtomicOr, + }; EmitExecConditional(() => { var firstInRange = IsBufferWordInRange(bindingIndex, dwordAddress); @@ -3746,30 +3826,70 @@ private bool EmitResolvedBufferMemory( var secondInRange = IsBufferWordInRange(bindingIndex, secondAddress); EmitBufferAtomicInRange(LogicalAnd(firstInRange, secondInRange), control.Glc, control.VectorData, 2, () => { - var atomicOp = instruction.Opcode == "BufferAtomicSwapX2" - ? SpirvOp.AtomicExchange - : SpirvOp.AtomicOr; - var first = EmitAtomic( - atomicOp, - _uintType, - BufferWordPointer(bindingIndex, dwordAddress), - scope: 1, - semantics: 0x48, - value: () => LoadV(control.VectorData), - comparator: () => UInt(0)); - var second = EmitAtomic( - atomicOp, - _uintType, - BufferWordPointer(bindingIndex, secondAddress), - scope: 1, - semantics: 0x48, - value: () => LoadV(control.VectorData + 1), - comparator: () => UInt(0)); - if (control.Glc) + void EmitDwordAtomics() { - StoreV(control.VectorData, first); - StoreV(control.VectorData + 1, second); + var first = EmitAtomic( + atomicOp, + _uintType, + BufferWordPointer(bindingIndex, dwordAddress), + scope: 1, + semantics: 0x48, + value: () => LoadV(control.VectorData), + comparator: () => UInt(0)); + var second = EmitAtomic( + atomicOp, + _uintType, + BufferWordPointer(bindingIndex, secondAddress), + scope: 1, + semantics: 0x48, + value: () => LoadV(control.VectorData + 1), + comparator: () => UInt(0)); + if (control.Glc) + { + StoreV(control.VectorData, first); + StoreV(control.VectorData + 1, second); + } } + + if (!_usesBufferQwordAtomics) + { + EmitDwordAtomics(); + return; + } + + // An 8-byte aligned pair is one 64-bit word; any other address names none, so it stays two dword atomics. + if (_request.Bindings.UsesTableBlock) + { + // A table-block buffer is addressed through its device address, so the pair is aligned when that is. + var address = TableBufferByteAddress(bindingIndex, dwordAddress); + EmitConditional( + LogicalAnd( + _module.AddInstruction(SpirvOp.IEqual, _boolType, BitwiseAnd(byteAddress, UInt(3)), UInt(0)), + _module.AddInstruction(SpirvOp.IEqual, _boolType, And64(address, ULong(7)), ULong(0))), + () => EmitQwordAtomic( + atomicOp, + _module.AddInstruction( + SpirvOp.ConvertUToPtr, + _module.TypePointer(SpirvStorageClass.PhysicalStorageBuffer, _ulongType), + address), + control), + EmitDwordAtomics); + return; + } + + EmitConditional( + _module.AddInstruction(SpirvOp.IEqual, _boolType, BitwiseAnd(byteAddress, UInt(7)), UInt(0)), + () => EmitQwordAtomic( + atomicOp, + _module.AddInstruction( + SpirvOp.AccessChain, + _storageUlongPointer, + _globalBufferQwords, + UInt((uint)bindingIndex), + UInt(0), + ShiftRightLogical(dwordAddress, UInt(1))), + control), + EmitDwordAtomics); }); }); return true; @@ -4111,6 +4231,8 @@ private bool TryEmitDeviceDescriptorBufferMemory( out string error) { error = string.Empty; + // Addresses come from VGPRs, as on the physical storage buffer path: inactive lanes must hold their own values. + FlushDeferredGuards(); if (control.Typed || instruction.Opcode.StartsWith("TBuffer", StringComparison.Ordinal)) { error = $"device buffer descriptor operation {instruction.Opcode} is not supported"; @@ -4160,6 +4282,13 @@ private bool TryEmitDeviceDescriptorBufferMemory( return true; } + if (instruction.Opcode.StartsWith("BufferStoreFormat", StringComparison.Ordinal) && + !instruction.Opcode.Contains("D16", StringComparison.Ordinal)) + { + EmitExecConditional(() => EmitDeviceBufferFormatStore(baseAddress, size, byteAddress, descriptorWord3, control)); + return true; + } + if (instruction.Opcode.Contains("Format", StringComparison.Ordinal)) { error = $"device buffer descriptor operation {instruction.Opcode} is not supported"; @@ -4265,9 +4394,14 @@ private bool TryEmitDeviceDescriptorBufferAtomic( { error = string.Empty; var atomicSuffix = instruction.Opcode["BufferAtomic".Length..]; - if (atomicSuffix is "SwapX2" or "OrX2") + if (atomicSuffix is "SwapX2" or "AndX2" or "OrX2") { - var atomicOp = atomicSuffix == "SwapX2" ? SpirvOp.AtomicExchange : SpirvOp.AtomicOr; + var atomicOp = atomicSuffix switch + { + "SwapX2" => SpirvOp.AtomicExchange, + "AndX2" => SpirvOp.AtomicAnd, + _ => SpirvOp.AtomicOr, + }; EmitExecConditional(() => { var valid = IsDeviceBufferByteRangeInRange(size, byteAddress, 2 * sizeof(uint)); @@ -4275,23 +4409,53 @@ private bool TryEmitDeviceDescriptorBufferAtomic( var secondAddress = And64(IAdd64(baseAddress, Widen(IAdd(byteAddress, UInt(sizeof(uint))))), ULong(DeviceAddressMask & ~3ul)); EmitBufferAtomicInRange(valid, control.Glc, control.VectorData, 2, () => { - var (firstPointer, firstMapped) = ResolveDeviceAddress(firstAddress); - var (secondPointer, secondMapped) = ResolveDeviceAddress(secondAddress); - var bothMapped = LogicalAnd(firstMapped, secondMapped); - EmitBufferAtomicInRange(bothMapped, control.Glc, control.VectorData, 2, () => + void EmitDwordAtomics() { - var originalLow = EmitAtomic( - atomicOp, _uintType, DeviceWordPointer(firstPointer), 1, 0x48, - () => LoadV(control.VectorData), () => UInt(0)); - var originalHigh = EmitAtomic( - atomicOp, _uintType, DeviceWordPointer(secondPointer), 1, 0x48, - () => LoadV(control.VectorData + 1), () => UInt(0)); - if (control.Glc) + var (firstPointer, firstMapped) = ResolveDeviceAddress(firstAddress); + var (secondPointer, secondMapped) = ResolveDeviceAddress(secondAddress); + var bothMapped = LogicalAnd(firstMapped, secondMapped); + EmitBufferAtomicInRange(bothMapped, control.Glc, control.VectorData, 2, () => { - StoreV(control.VectorData, originalLow); - StoreV(control.VectorData + 1, originalHigh); - } - }); + var originalLow = EmitAtomic( + atomicOp, _uintType, DeviceWordPointer(firstPointer), 1, 0x48, + () => LoadV(control.VectorData), () => UInt(0)); + var originalHigh = EmitAtomic( + atomicOp, _uintType, DeviceWordPointer(secondPointer), 1, 0x48, + () => LoadV(control.VectorData + 1), () => UInt(0)); + if (control.Glc) + { + StoreV(control.VectorData, originalLow); + StoreV(control.VectorData + 1, originalHigh); + } + }); + } + + if (!_request.SupportsBufferInt64Atomics) + { + EmitDwordAtomics(); + return; + } + + // An 8-byte aligned pair is one 64-bit word on one page; any other address names none. + var aligned = _module.AddInstruction( + SpirvOp.IEqual, + _boolType, + And64(IAdd64(baseAddress, Widen(byteAddress)), ULong(7)), + ULong(0)); + EmitConditional(aligned, () => + { + var (pointer, mapped) = ResolveDeviceAddress(firstAddress); + EmitBufferAtomicInRange(mapped, control.Glc, control.VectorData, 2, () => + { + EmitQwordAtomic( + atomicOp, + _module.AddInstruction( + SpirvOp.ConvertUToPtr, + _module.TypePointer(SpirvStorageClass.PhysicalStorageBuffer, _ulongType), + pointer), + control); + }); + }, EmitDwordAtomics); }); }); return true; @@ -4775,6 +4939,7 @@ private uint[] BufferFormatLoadValues( var canonical = new uint[4]; var componentBounds = new uint[4]; + var elementWords = new Dictionary(); for (var component = 0; component < canonical.Length; component++) { canonical[component] = LoadGfx10BufferFormatComponent( @@ -4783,7 +4948,8 @@ private uint[] BufferFormatLoadValues( dataFormat, numberFormat, component, - out componentBounds[component]); + out componentBounds[component], + elementWords); } // Only selected memory components contribute to the shared bounds check. @@ -4909,6 +5075,7 @@ private bool TryEmitTypedBufferFormatLoad( UInt(Gfx10UnifiedFormat.GetAccessByteSize(dataFormat, control.DwordCount) - 1))); var dataFormatId = UInt(dataFormat); var numberFormatId = UInt(numberFormat); + var elementWords = new Dictionary(); for (uint destination = 0; destination < control.DwordCount; destination++) { var value = destination < componentCount @@ -4918,7 +5085,8 @@ private bool TryEmitTypedBufferFormatLoad( dataFormatId, numberFormatId, (int)destination, - out _) + out _, + elementWords) : UInt(0); StoreV( control.VectorData + destination, @@ -4989,7 +5157,7 @@ private bool TryEmitBufferFormatStore( componentValue(component), bitCount, numberFormat, - dataFormat); + IsUnsignedMiniFloat(numberFormat, dataFormat)); var dword = (int)(byteOffset / 4); var bit = ((byteOffset & 3) * 8) + bitOffset; var (value, mask) = element[dword]; @@ -5003,8 +5171,175 @@ private bool TryEmitBufferFormatStore( return true; } + // A runtime V# names its format only when the shader runs, so each buffer format stores through its own + // branch, converting the registers as a formatted store through a bound buffer does. A branch depends only on + // its format's store shape (DeviceFormatStoreShape), so the formats of one shape share one branch. + private void EmitDeviceBufferFormatStore( + uint baseAddress, + uint size, + uint byteAddress, + uint descriptorWord3, + Gen5BufferMemoryControl control) + { + var unifiedFormat = BitwiseAnd(ShiftRightLogical(descriptorWord3, UInt(12)), UInt(0x7F)); + var shapes = new List<(DeviceFormatStoreShape Shape, List Formats)>(); + for (uint format = 1; format <= 0x7F; format++) + { + if (!TryGetDeviceFormatStoreShape(format, control.DwordCount, out var shape)) + { + continue; + } + + var known = shapes.FindIndex(entry => entry.Shape.Equals(shape)); + if (known < 0) + { + shapes.Add((shape, [format])); + } + else + { + shapes[known].Formats.Add(format); + } + } + + foreach (var (shape, formats) in shapes) + { + uint matches = 0; + foreach (var format in formats) + { + var match = _module.AddInstruction(SpirvOp.IEqual, _boolType, unifiedFormat, UInt(format)); + matches = matches == 0 ? match : _module.AddInstruction(SpirvOp.LogicalOr, _boolType, matches, match); + } + + var selected = LogicalAnd(matches, IsDeviceBufferByteRangeInRange(size, byteAddress, shape.ElementBytes)); + EmitConditional(selected, () => + { + var element = new (uint Value, uint Mask)[(shape.ElementBytes + 3) / 4]; + for (var index = 0; index < element.Length; index++) + { + element[index] = (UInt(0), 0); + } + + for (var component = 0; component < shape.Components.Length; component++) + { + var (byteOffset, bitOffset, bitCount, numberFormat, miniFloat) = shape.Components[component]; + var register = LoadV(control.VectorData + (uint)component); + var dword = (int)(byteOffset / 4); + if (bitCount == 32) + { + // Dword components keep their register bits. + element[dword] = (register, uint.MaxValue); + continue; + } + + var encoded = EncodeGfx10BufferComponent(register, bitCount, numberFormat, miniFloat); + var bit = ((byteOffset & 3) * 8) + bitOffset; + var (value, mask) = element[dword]; + element[dword] = ( + BitwiseOr(value, bit == 0 ? encoded : ShiftLeftLogical(encoded, UInt(bit))), + mask | (((1u << (int)bitCount) - 1) << (int)bit)); + } + + StoreDeviceElementBits(baseAddress, byteAddress, element); + }); + } + } + + // What a device store's branch for one format depends on: the bytes its element spans, and for each stored component + // its layout and encoding (EncodeGfx10BufferComponent's inputs; a 32-bit component keeps its register bits, so it has + // no encoding). + private readonly record struct DeviceFormatStoreComponent(uint ByteOffset, uint BitOffset, uint BitCount, uint NumberFormat, bool MiniFloat); + + private sealed record DeviceFormatStoreShape(uint ElementBytes, DeviceFormatStoreComponent[] Components) + { + public bool Equals(DeviceFormatStoreShape? other) => + other is not null && ElementBytes == other.ElementBytes && Components.AsSpan().SequenceEqual(other.Components); + + public override int GetHashCode() => HashCode.Combine(ElementBytes, Components.Length); + } + + private static bool TryGetDeviceFormatStoreShape(uint format, uint dwordCount, out DeviceFormatStoreShape shape) + { + shape = null!; + if (!Gfx10UnifiedFormat.TryDecode(format, out var dataFormat, out var numberFormat)) + { + return false; + } + + var componentCount = Math.Min(dwordCount, Gfx10UnifiedFormat.ComponentCount(dataFormat)); + if (componentCount == 0) + { + return false; + } + + var components = new DeviceFormatStoreComponent[componentCount]; + for (uint component = 0; component < componentCount; component++) + { + Gfx10UnifiedFormat.TryGetComponentLayout(dataFormat, component, out var byteOffset, out var bitOffset, out var bitCount); + components[component] = bitCount == 32 + ? new(byteOffset, bitOffset, bitCount, 0, false) + : new(byteOffset, bitOffset, bitCount, numberFormat, IsUnsignedMiniFloat(numberFormat, dataFormat)); + } + + shape = new(Gfx10UnifiedFormat.GetAccessByteSize(dataFormat, componentCount), components); + return true; + } + + // The device form of StoreBufferElementBits: each dword the element touches takes its masked bits. + private void StoreDeviceElementBits(uint baseAddress, uint byteAddress, IReadOnlyList<(uint Value, uint Mask)> element) + { + var alignment = BitwiseAnd(byteAddress, UInt(3)); + var shift = ShiftLeftLogical(alignment, UInt(3)); + var aligned = _module.AddInstruction(SpirvOp.IEqual, _boolType, alignment, UInt(0)); + var carryShift = _module.AddInstruction(SpirvOp.ISub, _uintType, UInt(32), shift); + var firstAddress = And64( + IAdd64(baseAddress, Widen(BitwiseAnd(byteAddress, UInt(~3u)))), + ULong(DeviceAddressMask & ~3ul)); + for (var index = 0; index <= element.Count; index++) + { + var value = UInt(0); + var mask = UInt(0); + if (index < element.Count) + { + var (elementValue, elementMask) = element[index]; + value = ShiftLeftLogical(BitwiseAnd(elementValue, UInt(elementMask)), shift); + mask = ShiftLeftLogical(UInt(elementMask), shift); + } + + if (index > 0) + { + // An unaligned element carries its high bits into the next dword. + var (previousValue, previousMask) = element[index - 1]; + value = BitwiseOr( + value, + _module.AddInstruction( + SpirvOp.Select, + _uintType, + aligned, + UInt(0), + ShiftRightLogical(BitwiseAnd(previousValue, UInt(previousMask)), carryShift))); + mask = BitwiseOr( + mask, + _module.AddInstruction( + SpirvOp.Select, + _uintType, + aligned, + UInt(0), + ShiftRightLogical(UInt(previousMask), carryShift))); + } + + StoreDeviceMaskedWord( + index == 0 ? firstAddress : IAdd64(firstAddress, ULong((ulong)index * sizeof(uint))), + value, + mask, + _module.ConstantBool(true)); + } + } + + // The 10_11_11 and 11_11_10 float formats store unsigned mini-floats. + private static bool IsUnsignedMiniFloat(uint numberFormat, uint dataFormat) => numberFormat == 7 && dataFormat is 6 or 7; + // Converts one register to the bits its component stores, per the number format. - private uint EncodeGfx10BufferComponent(uint value, uint bitCount, uint numberFormat, uint dataFormat) + private uint EncodeGfx10BufferComponent(uint value, uint bitCount, uint numberFormat, bool miniFloat) { if (bitCount == 32) { @@ -5038,7 +5373,7 @@ private uint EncodeGfx10BufferComponent(uint value, uint bitCount, uint numberFo _module.Constant(_intType, signedMaximum))), UInt(mask)); case 7: - if (dataFormat is 6 or 7) + if (miniFloat) { return EncodeUnsignedMiniFloat(value, bitCount); } @@ -5218,13 +5553,17 @@ private uint IsDescriptorBound(uint descriptorWord3) UInt(0xFF))); } + // elementWords, when given, holds the dwords of this element already read, by their index from the element's first + // dword. A known component at a dword offset takes its two dwords from there, so neighbouring components share + // their reads: a 32_32_32_32 element reads 5 dwords instead of 8. private uint LoadGfx10BufferFormatComponent( int bindingIndex, uint elementAddress, uint dataFormat, uint numberFormat, int component, - out uint componentInBounds) + out uint componentInBounds, + Dictionary? elementWords = null) { var byteOffset = UInt(0); var bitOffset = UInt(0); @@ -5266,15 +5605,66 @@ void SetLayout(uint format, uint bytes, uint bits, uint count) } } - var packed = LoadUnalignedBufferWord( - bindingIndex, - IAdd(elementAddress, byteOffset)); - var componentBytes = ShiftRightLogical(IAdd(IAdd(bitOffset, bitCount), UInt(7)), UInt(3)); - componentInBounds = _module.AddInstruction( - SpirvOp.LogicalOr, _boolType, - _module.AddInstruction(SpirvOp.IEqual, _boolType, bitCount, UInt(0)), - IsBufferElementInRange(bindingIndex, IAdd(elementAddress, byteOffset), - _module.AddInstruction(SpirvOp.ISub, _uintType, componentBytes, UInt(1)))); + var knownLayout = _module.TryGetConstantValue(byteOffset, out var knownByteOffset) & + _module.TryGetConstantValue(bitOffset, out var knownBitOffset) & + _module.TryGetConstantValue(bitCount, out var knownBitCount); + if (knownLayout && knownBitCount == 0) + { + // The format has no such component: it reads as zero (one for W), and nothing is loaded. + componentInBounds = _module.ConstantBool(true); + return component == 3 ? Gfx10FormatOne(numberFormat) : UInt(0); + } + + uint packed; + if (elementWords is not null && knownLayout && (knownByteOffset & 3) == 0) + { + // The component's bytes start in the element's dword knownByteOffset / 4 and end in that dword or the + // next, as the element's own byte offset carries; those are the dwords whose bounds it needs. A field in + // one byte never reaches the next dword. Dword i is the one (elementAddress + 4 * i) >> 2 names in 32 bits, + // so the index wraps at 2^30. + var elementDword = ShiftRightLogical(elementAddress, UInt(2)); + uint ElementDword(uint index) => index == 0 ? elementDword : BitwiseAnd(IAdd(elementDword, UInt(index)), UInt(0x3FFF_FFFF)); + uint ElementWord(uint index) + { + if (!elementWords.TryGetValue(index, out var word)) + { + word = LoadBufferWord(bindingIndex, ElementDword(index)); + elementWords[index] = word; + } + + return word; + } + + var first = knownByteOffset / 4; + var lastByte = (knownBitOffset + knownBitCount + 7) / 8 - 1; + var firstInRange = IsBufferWordInRange(bindingIndex, ElementDword(first)); + if (lastByte == 0) + { + packed = ShiftRightLogical(ElementWord(first), ShiftLeftLogical(BitwiseAnd(elementAddress, UInt(3)), UInt(3))); + componentInBounds = firstInRange; + } + else + { + packed = SpliceUnalignedWord(elementAddress, ElementWord(first), ElementWord(first + 1)); + var endsInNext = _module.AddInstruction(SpirvOp.UGreaterThan, _boolType, + IAdd(BitwiseAnd(elementAddress, UInt(3)), UInt(lastByte)), UInt(3)); + componentInBounds = LogicalAnd(firstInRange, _module.AddInstruction(SpirvOp.Select, _boolType, endsInNext, + IsBufferWordInRange(bindingIndex, ElementDword(first + 1)), firstInRange)); + } + } + else + { + packed = LoadUnalignedBufferWord( + bindingIndex, + IAdd(elementAddress, byteOffset)); + var componentBytes = ShiftRightLogical(IAdd(IAdd(bitOffset, bitCount), UInt(7)), UInt(3)); + componentInBounds = _module.AddInstruction( + SpirvOp.LogicalOr, _boolType, + _module.AddInstruction(SpirvOp.IEqual, _boolType, bitCount, UInt(0)), + IsBufferElementInRange(bindingIndex, IAdd(elementAddress, byteOffset), + _module.AddInstruction(SpirvOp.ISub, _uintType, componentBytes, UInt(1)))); + } + var raw = _module.AddInstruction( SpirvOp.BitFieldUExtract, _uintType, @@ -5884,6 +6274,11 @@ private bool TryEmitImage( return false; } + if (IsHeapVolumeRead(instruction, out var heapVolume, out var volumeType)) + { + return TryEmitHeapVolumeRead(instruction, image, heapVolume, volumeType, out error); + } + if (!TryResolveLayoutImage(instruction, image, out resource, out imageObject, out dstSelect, out error)) { return false; @@ -5898,6 +6293,73 @@ private bool TryEmitImage( return EmitImageOperation(instruction, image, resource, imageObject, dstSelect, mipLevel, out error); } + // A heap record a 3D read picks can hold a 2D texture, whose 3D element stays null; the hardware then takes the + // third coordinate as the array layer. Reads that place their operands alike in both shapes (no gradients) try + // the 3D element and, when it is null, the record's 2D-array element. + private bool IsHeapVolumeRead(Gen5ShaderInstruction instruction, out HeapRecordUse heapImage, out uint volumeType) + { + heapImage = default; + volumeType = 0; + var opcode = instruction.Opcode; + var sameOperands = opcode is "ImageLoad" or "ImageLoadMip" || opcode.StartsWith("ImageGather4", StringComparison.Ordinal) || + (opcode.StartsWith("ImageSample", StringComparison.Ordinal) && !opcode.Contains("SampleD", StringComparison.Ordinal) && + !opcode.Contains("SampleCD", StringComparison.Ordinal) && !opcode.Contains("SampleCd", StringComparison.Ordinal) && + !opcode.Contains("SampleCCd", StringComparison.Ordinal)); + if (!sameOperands || !_request.Memory.TryGetIndex(instruction.Pc, 0, out var memoryIndex) || + !_request.HeapImageByMemoryIndex.TryGetValue(memoryIndex, out heapImage)) + { + return false; + } + + var entry = _request.Memory[memoryIndex]; + var info = _request.Resources.Info; + if (entry.Resource >= (uint)info.Images.Count || + ImageDescriptorBinding.ForImage(info.Images[(int)entry.Resource]) is not { } kind || + BindlessHeap.ImageSlot(kind) != BindlessHeap.VolumeSlot || !_imageClasses.TryGetValue(kind, out var volumeClass)) + { + return false; + } + + volumeType = volumeClass.ImageType; + return true; + } + + private bool TryEmitHeapVolumeRead(Gen5ShaderInstruction instruction, Gen5ImageControl image, HeapRecordUse heapImage, + uint volumeType, out string error) + { + // A null descriptor reports no levels. Each branch builds its sampled image in the block that samples it, so the + // query loads the 3D element on its own. + _module.AddCapability(SpirvCapability.ImageQuery); + var (_, volumeImage) = LoadHeapElement(BindlessHeap.VolumeSlot, volumeType, HeapRecordIndex(heapImage)); + var levels = _module.AddInstruction(SpirvOp.ImageQueryLevels, _uintType, volumeImage); + _module.AddDecoration(levels, SpirvDecoration.NonUniform); + var isVolume = _module.AddInstruction(SpirvOp.INotEqual, _boolType, levels, UInt(0)); + var emitted = true; + var branchError = string.Empty; + EmitConditional(isVolume, () => + emitted = TryResolveLayoutImage(instruction, image, out var volume, out var volumeObject, out var volumeSelect, out branchError) && + EmitImageOperation(instruction, image, volume, volumeObject, volumeSelect, + HeapReadMipLevel(instruction, image, volume), out branchError)); + if (!emitted) + { + error = branchError; + return false; + } + + EmitConditional(_module.AddInstruction(SpirvOp.LogicalNot, _boolType, isVolume), () => + emitted = TryResolveLayoutImage(instruction, image, out var layers, out var layersObject, out var layersSelect, out branchError, + heapVolumeLayers: true) && + EmitImageOperation(instruction, image, layers, layersObject, layersSelect, + HeapReadMipLevel(instruction, image, layers), out branchError)); + error = branchError; + return emitted; + } + + private uint HeapReadMipLevel(Gen5ShaderInstruction instruction, Gen5ImageControl image, SpirvImageResource resource) => + instruction.Opcode == "ImageLoadMip" + ? LoadImageIntegerAddress(image, (int)ImageCoordinateComponentCount(resource)) + : UInt(0); + // One image operation over a resolved image object; its results are register writes. private bool EmitImageOperation( Gen5ShaderInstruction instruction, @@ -6017,6 +6479,13 @@ private bool EmitImageOperation( image, 0, coordinateComponentCount); + if (resource.SwizzleSlot >= 0) + { + var mapped = PackImageTexel(resource, RuntimeSwizzleStoreTexel(image, resource)); + EmitExecConditional(() => _module.AddStatement(SpirvOp.ImageWrite, imageObject, coordinates, mapped)); + return true; + } + var components = new uint[4]; for (var component = 0; component < components.Length; component++) { @@ -6200,6 +6669,10 @@ instruction.Opcode is not ("ImageLoad" or "ImageLoadMip")) image, 0, coordinateComponentCount); + if (resource.Arrayed) + { + coordinates = ClampFetchLayer(resource, fetchedImage, coordinates, coordinateComponentCount); + } if (resource.Multisampled) { var sample = LoadImageIntegerAddress( @@ -7163,6 +7636,42 @@ private uint LoadImageIntegerAddress(Gen5ImageControl image, int component) UInt(0xFFFF)); } + // A store's texel when the image's select is shader data (RuntimeImageSwizzle): the words of the components the + // dmask enables, in data-register order (zero for the others), each moved to the physical channel its slot's map names + // (a code xor its channel; 4 stores zero), as GetImageStoreSourceIndex places them for a select baked into the module. + // The map's decode is of an entry load and constants, so it runs once per function; a store adds a pick and a select + // per channel. The words are the bits the baked store writes, cast once. + private uint RuntimeSwizzleStoreTexel(Gen5ImageControl image, SpirvImageResource resource) + { + var dmask = (image.Dmask & 0xFu) == 0 ? 1u : image.Dmask & 0xFu; + var logical = new uint[4]; + var source = 0u; + for (var component = 0; component < logical.Length; component++) + { + logical[component] = (dmask & (1u << component)) != 0 ? LoadImageStoreComponent(image, resource, source++) : UInt(0); + } + + var words = _module.AddInstruction(SpirvOp.CompositeConstruct, _uvec4Type, logical); + var slot = (uint)resource.SwizzleSlot; + var map = LoadShaderDataDwordAtEntry(_request.Bindings.StorageImageSwizzlesDword + slot / 2); + var physical = new uint[4]; + for (var channel = 0u; channel < 4; channel++) + { + var code = _module.AddInstruction(SpirvOp.BitFieldUExtract, _uintType, map, UInt(slot % 2 * 16 + channel * 3), UInt(3)); + if (channel != 0) + { + code = _module.AddInstruction(SpirvOp.BitwiseXor, _uintType, code, UInt(channel)); + } + + var stored = _module.AddInstruction(SpirvOp.ULessThan, _boolType, code, UInt(4)); + var picked = _module.AddInstruction(SpirvOp.VectorExtractDynamic, _uintType, words, BitwiseAnd(code, UInt(3))); + physical[channel] = _module.AddInstruction(SpirvOp.Select, _uintType, stored, picked, UInt(0)); + } + + var texel = _module.AddInstruction(SpirvOp.CompositeConstruct, _uvec4Type, physical); + return resource.ComponentKind == ImageComponentKind.Uint ? texel : Bitcast(resource.VectorType, texel); + } + private uint LoadImageStoreComponent( Gen5ImageControl image, SpirvImageResource resource, @@ -7247,6 +7756,23 @@ private uint BuildIntegerCoordinates( components); } + // The hardware clamps the slice of an image read to the T#'s last layer, while Vulkan fetches zero past a view's + // last layer. A 2D texture an array read is bound to (ResourceMaterializer.SampledArrayRead) is a one-layer view, + // so a fetch with a nonzero slice reads its only layer, as on the hardware. + private uint ClampFetchLayer(SpirvImageResource resource, uint image, uint coordinates, uint componentCount) + { + var vectorType = ImageIntegerCoordinateType(componentCount); + var size = resource.Multisampled + ? _module.AddInstruction(SpirvOp.ImageQuerySize, vectorType, image) + : _module.AddInstruction(SpirvOp.ImageQuerySizeLod, vectorType, image, UInt(0)); + var layerComponent = componentCount - 1; + var layers = Bitcast(_uintType, _module.AddInstruction(SpirvOp.CompositeExtract, _intType, size, layerComponent)); + var layer = Bitcast(_uintType, _module.AddInstruction(SpirvOp.CompositeExtract, _intType, coordinates, layerComponent)); + var lastLayer = _module.AddInstruction(SpirvOp.ISub, _uintType, layers, UInt(1)); + var clamped = Ext(38, _uintType, layer, lastLayer); + return _module.AddInstruction(SpirvOp.CompositeInsert, vectorType, Bitcast(_intType, clamped), coordinates, layerComponent); + } + private uint BuildImageOffset( Gen5ImageControl image, int component, @@ -8543,6 +9069,14 @@ private uint GetPixelOutputType(Gen5PixelOutputKind kind) => private uint LoadBufferWord(int binding, uint dwordAddress) { + // robustBufferAccess2 reads zero past the view's range, as the selects below do. A view ends on a whole dword + // (StorageBufferViewRange), so the device bounds the load where ArrayLength does; a length of zero leaves both + // unbounded. A table-block buffer is read through its device address, which robust access does not bound. + if (_request.RobustBufferAccess2 && !_request.Bindings.UsesTableBlock) + { + return Load(_uintType, BufferWordPointer(binding, RobustDwordIndex(dwordAddress))); + } + var inRange = IsBufferWordInRange(binding, dwordAddress); var safeAddress = _module.AddInstruction( SpirvOp.Select, @@ -8559,6 +9093,12 @@ private uint LoadBufferWord(int binding, uint dwordAddress) UInt(0)); } + // A robust load's dword index stays below 2^30: NVIDIA's robust access takes the byte offset modulo 2^32, so a larger + // index would read the view's start instead of zero. From 0x3FFFFFFF on an index is past every view (at most 2^32 - 1 + // bytes), so the clamp changes no result, and it folds away when the index cannot pass it (a byte address >> 2). + private uint RobustDwordIndex(uint dwordIndex) => Ext(38, _uintType, dwordIndex, UInt(0x3FFF_FFFF)); + + // The packed memory-offset byte of this buffer, loaded at entry. private uint ApplyGuestBufferByteBias(int binding, uint byteAddress) => IAdd(byteAddress, CapturedBufferValue(_bufferBiasValues, binding) ?? Load(_uintType, RuntimeBufferBiasPointer(binding))); @@ -8566,7 +9106,10 @@ private void StoreBufferWord(int binding, uint dwordAddress, uint value) { EmitConditional( IsBufferWordInRange(binding, dwordAddress), - () => Store(BufferWordPointer(binding, dwordAddress), value)); + () => + { + Store(BufferWordPointer(binding, dwordAddress), value); + }); } // A GLC DWORDX2 access: one 64-bit access when it is aligned and inside the pair view, else two dword accesses. @@ -8593,9 +9136,12 @@ private void StoreBufferPair(int binding, uint dwordAddress, uint low, uint high var pairIndex = ShiftRightLogical(dwordAddress, UInt(1)); EmitConditional( IsBufferPairInRange(binding, dwordAddress, pairIndex), - () => Store( - BufferPairPointer(binding, pairIndex), - _module.AddInstruction(SpirvOp.CompositeConstruct, _uvec2Type, low, high)), + () => + { + Store( + BufferPairPointer(binding, pairIndex), + _module.AddInstruction(SpirvOp.CompositeConstruct, _uvec2Type, low, high)); + }, () => { StoreBufferWord(binding, dwordAddress, low); @@ -8647,13 +9193,24 @@ private uint IsBufferWordInRange(int binding, uint dwordAddress) _uintType, buffer, 0); - return _module.AddInstruction( - SpirvOp.ULessThan, - _boolType, - dwordAddress, - length); + // NVIDIA's driver reports a length of zero for a storage binding over 2 GiB, though its loads read the + // memory. A bound view holds at least a dword, so zero is an unknown length: robust buffer access bounds + // those accesses. + return LogicalOr( + _module.AddInstruction(SpirvOp.IEqual, _boolType, length, UInt(0)), + _module.AddInstruction( + SpirvOp.ULessThan, + _boolType, + dwordAddress, + length)); } + // The device address of a dword of a table-block buffer. + private uint TableBufferByteAddress(int binding, uint dwordAddress) => + IAdd64( + CapturedBufferValue(_bufferBaseValues, binding) ?? Load(_ulongType, TableBufferBasePointer(binding)), + ShiftLeftLogical64(Widen(dwordAddress), ULong(2))); + private uint BufferWordPointer(int binding, uint dwordAddress) => _request.Bindings.UsesTableBlock ? TableBufferWordPointer(binding, dwordAddress) : _module.AddInstruction( @@ -8791,6 +9348,20 @@ private uint RuntimeBufferBiasPointer(int binding) => _runtimeBufferBiases, UInt(checked((uint)binding))); + // The stride an indexed access multiplies its index by, from the binding's V# at run time. + private uint RuntimeBufferStride(int binding) => + _runtimeBufferStrides != 0 && (uint)binding < _request.Bindings.BufferStrideCount + ? CapturedBufferValue(_bufferStrideValues, binding) ?? Load(_uintType, RuntimeBufferStridePointer(binding)) + : throw new ResourcePlanException( + $"buffer binding {binding} is indexed, but the layout carries {_request.Bindings.BufferStrideCount} buffer strides"); + + private uint RuntimeBufferStridePointer(int binding) => + _module.AddInstruction( + SpirvOp.AccessChain, + _privateUintPointer, + _runtimeBufferStrides, + UInt(checked((uint)binding))); + private uint VectorPointer(uint register) { if (_vectorRegisters != 0) @@ -8927,6 +9498,30 @@ private uint PackedHalfRegisters() return _packedHalfRegisters; } + // Programs wait on these counters, so they must run. Without a device clock each read moves a + // per-invocation counter 2^32 ahead, which ends any wait for a 32-bit number of ticks. + private uint ReadShaderClock() + { + if (_request.SupportsShaderDeviceClock) + { + _module.AddCapability(SpirvCapability.ShaderClockKhr); + _module.AddExtension("SPV_KHR_shader_clock"); + return _module.AddInstruction(SpirvOp.ReadClockKhr, _ulongType, UInt(1)); + } + + if (_steppedClock == 0) + { + _steppedClock = _module.AddGlobalVariable( + _module.TypePointer(SpirvStorageClass.Private, _ulongType), SpirvStorageClass.Private, ULong(0)); + _module.AddName(_steppedClock, "steppedClock"); + _interfaces.Add(_steppedClock); + } + + var value = Load(_ulongType, _steppedClock); + Store(_steppedClock, IAdd64(value, ULong(1UL << 32))); + return value; + } + private uint LoadS(uint register) => _scalarSnapshot is { } snapshot && snapshot.TryGetValue(register, out var value) ? value @@ -9025,6 +9620,11 @@ private void StoreV(uint register, uint value, bool guardWithExec = true, bool p if (!preserveSavedLanes) _savedLaneValues.Remove(register); if (guardWithExec && !_execKnownFull && !_unobservedWrites.Contains(register)) { + if (TryDeferGuard(register, value)) + { + return; + } + var active = Load(_boolType, _exec); var oldValue = LoadV(register); value = _module.AddInstruction( @@ -9111,6 +9711,12 @@ private uint Load(uint type, uint pointer) private void Store(uint pointer, uint value) { + if (pointer == _exec && _deferredGuards.Count != 0) + { + // The region of the current EXEC ends. + FlushDeferredGuards(); + } + if (_executingWave != 0 && pointer == _exec) value = LogicalAnd(value, _executingWave); if (_executingWave != 0 && (pointer == _scc || pointer == _programActive)) { diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/SpirvDispatchThreads.cs b/src/SharpEmu.ShaderCompiler.Vulkan/SpirvDispatchThreads.cs new file mode 100644 index 000000000..c303cd213 --- /dev/null +++ b/src/SharpEmu.ShaderCompiler.Vulkan/SpirvDispatchThreads.cs @@ -0,0 +1,106 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.ShaderCompiler.Vulkan; + +// The groups of a dispatch whose guest arguments count threads (DISPATCH_INITIATOR.USE_THREAD_DIMENSIONS) when a shader +// wrote them: one invocation reads the three thread counts (binding 0), writes the groups of the shader's group size in the +// pipeline's axis order for vkCmdDispatchIndirect (binding 1), and the counts as the shader's thread limits (binding 2), as +// the CPU path does with counts it read. A zero count launches nothing. +public static class SpirvDispatchThreads +{ + // [0] the arguments' word in binding 0; per logical axis i: [1 + i] the group size, [4 + i] the axis in binding 1 + // (the pipeline's physical axis), [8 + i] the device's group limit on that axis; [7] the limits' word in binding 2, or + // NoLimits. + public const uint PushWordCount = 11; + public const uint NoLimits = uint.MaxValue; + + public static byte[] Create() + { + var module = new SpirvModuleBuilder(); + module.AddCapability(SpirvCapability.Shader); + var voidType = module.TypeVoid(); + var uintType = module.TypeInt(32, false); + var boolType = module.TypeBool(); + uint Constant(uint value) => module.Constant(uintType, value); + uint Operation(SpirvOp operation, uint left, uint right) => module.AddInstruction(operation, uintType, left, right); + uint Compare(SpirvOp operation, uint left, uint right) => module.AddInstruction(operation, boolType, left, right); + uint Select(uint condition, uint yes, uint no) => module.AddInstruction(SpirvOp.Select, uintType, condition, yes, no); + var array = module.TypeRuntimeArray(uintType); + module.AddDecoration(array, SpirvDecoration.ArrayStride, 4); + var structure = module.TypeStruct(array); + module.AddDecoration(structure, SpirvDecoration.Block); + module.AddMemberDecoration(structure, 0, SpirvDecoration.Offset, 0); + var bufferPointer = module.TypePointer(SpirvStorageClass.StorageBuffer, structure); + var wordPointer = module.TypePointer(SpirvStorageClass.StorageBuffer, uintType); + var buffers = new uint[3]; + for (uint index = 0; index < buffers.Length; index++) + { + buffers[index] = module.AddGlobalVariable(bufferPointer, SpirvStorageClass.StorageBuffer); + module.AddDecoration(buffers[index], SpirvDecoration.DescriptorSet, 0); + module.AddDecoration(buffers[index], SpirvDecoration.Binding, index); + } + + var pushArray = module.TypeArray(uintType, PushWordCount); + module.AddDecoration(pushArray, SpirvDecoration.ArrayStride, 4); + var pushStructure = module.TypeStruct(pushArray); + module.AddDecoration(pushStructure, SpirvDecoration.Block); + module.AddMemberDecoration(pushStructure, 0, SpirvDecoration.Offset, 0); + var push = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.PushConstant, pushStructure), SpirvStorageClass.PushConstant); + var pushWord = module.TypePointer(SpirvStorageClass.PushConstant, uintType); + var main = module.BeginFunction(voidType, module.TypeFunction(voidType)); + module.AddLabel(); + uint Pointer(int buffer, uint index) => module.AddInstruction(SpirvOp.AccessChain, wordPointer, buffers[buffer], Constant(0), index); + uint LoadParameter(uint index) => module.AddInstruction(SpirvOp.Load, uintType, + module.AddInstruction(SpirvOp.AccessChain, pushWord, push, Constant(0), Constant(index))); + void If(uint condition, Action body) + { + var yes = module.AllocateId(); + var end = module.AllocateId(); + module.AddStatement(SpirvOp.SelectionMerge, end, 0); + module.AddStatement(SpirvOp.BranchConditional, condition, yes, end); + module.AddLabel(yes); + body(); + module.AddStatement(SpirvOp.Branch, end); + module.AddLabel(end); + } + + var argumentsWord = LoadParameter(0); + var threads = new uint[3]; + for (uint axis = 0; axis < 3; axis++) + { + threads[axis] = module.AddInstruction(SpirvOp.Load, uintType, Pointer(0, Operation(SpirvOp.IAdd, argumentsWord, Constant(axis)))); + } + + var empty = module.AddInstruction(SpirvOp.LogicalOr, boolType, + module.AddInstruction(SpirvOp.LogicalOr, boolType, + Compare(SpirvOp.IEqual, threads[0], Constant(0)), Compare(SpirvOp.IEqual, threads[1], Constant(0))), + Compare(SpirvOp.IEqual, threads[2], Constant(0))); + for (uint axis = 0; axis < 3; axis++) + { + var size = LoadParameter(1 + axis); + size = Select(Compare(SpirvOp.IEqual, size, Constant(0)), Constant(1), size); + // (threads - 1) / size + 1 rounds up without overflow; a zero count was handled above. + var groups = Operation(SpirvOp.IAdd, Operation(SpirvOp.UDiv, + Operation(SpirvOp.ISub, threads[axis], Constant(1)), size), Constant(1)); + var limit = LoadParameter(8 + axis); + groups = Select(Compare(SpirvOp.UGreaterThan, groups, limit), limit, groups); + var output = LoadParameter(4 + axis); + module.AddStatement(SpirvOp.Store, Pointer(1, output), Select(empty, Constant(0), groups)); + } + + var limitsWord = LoadParameter(7); + If(Compare(SpirvOp.INotEqual, limitsWord, Constant(NoLimits)), () => + { + for (uint axis = 0; axis < 3; axis++) + { + module.AddStatement(SpirvOp.Store, Pointer(2, Operation(SpirvOp.IAdd, limitsWord, Constant(axis))), threads[axis]); + } + }); + module.AddStatement(SpirvOp.Return); + module.EndFunction(); + module.AddEntryPoint(SpirvExecutionModel.GLCompute, main, "main", [.. buffers, push]); + module.AddExecutionMode(main, SpirvExecutionMode.LocalSize, 1, 1, 1); + return module.Build(); + } +} diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/SpirvMeshIndirect.cs b/src/SharpEmu.ShaderCompiler.Vulkan/SpirvMeshIndirect.cs index 361744381..42035c9ec 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/SpirvMeshIndirect.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/SpirvMeshIndirect.cs @@ -68,6 +68,9 @@ void If(uint condition, Action body) var indexByteOffset = LoadPush(1); var capacity = LoadPush(2); var elementSize = LoadPush(3); + // An element size of 0 marks an automatic draw: no index buffer, and the arguments are + // (vertexCount, instanceCount, firstVertex, firstInstance) instead of the indexed five. + var automatic = Compare(SpirvOp.IEqual, elementSize, Constant(0)); var perGroup = LoadPush(4); var pointList = Compare(SpirvOp.INotEqual, LoadPush(5), Constant(0)); // The count is bounded by the buffer, as on the CPU path; status 1 reports a first index past it. @@ -79,7 +82,7 @@ void If(uint condition, Action body) var room = Operation(SpirvOp.ISub, capacity, firstIndex); var count = Select(Compare(SpirvOp.ULessThan, requested, room), requested, room); var baseVertex = Read(0, Operation(SpirvOp.IAdd, argumentsOffset, Constant(3))); - var firstInstance = Read(0, Operation(SpirvOp.IAdd, argumentsOffset, Constant(4))); + var firstInstance = Read(0, Operation(SpirvOp.IAdd, argumentsOffset, Select(automatic, Constant(3), Constant(4)))); uint IndexAt(uint ordinal) { var byteOffset = Operation(SpirvOp.IAdd, indexByteOffset, @@ -109,15 +112,16 @@ uint IndexAt(uint ordinal) Write(2, 1, Select(execute, instances, Constant(0))); Write(2, 2, Constant(1)); Write(2, 4, Select(execute, vertices, Constant(0))); - Write(2, 5, Constant(0)); + // An automatic draw counts its vertices from the first one; an indexed draw reads the expanded indices. + Write(2, 5, Select(automatic, firstIndex, Constant(0))); Write(2, 6, firstInstance); - Write(2, 7, Constant(4)); - Write(2, 8, LoadPush(9)); - Write(2, 9, LoadPush(10)); + Write(2, 7, Select(automatic, Constant(0), Constant(4))); + Write(2, 8, Select(automatic, Constant(0), LoadPush(9))); + Write(2, 9, Select(automatic, Constant(0), LoadPush(10))); var error = Select(limitsValid, Select(rangeValid, Constant(0), Constant(1)), Constant(2)); Write(3, 0, Select(requestedActive, error, Constant(0))); }); - If(And(execute, Compare(SpirvOp.ULessThan, id, vertices)), () => + If(And(And(execute, Compare(SpirvOp.INotEqual, elementSize, Constant(0))), Compare(SpirvOp.ULessThan, id, vertices)), () => module.AddStatement(SpirvOp.Store, Pointer(2, Operation(SpirvOp.IAdd, id, Constant(HeaderWords))), Operation(SpirvOp.IAdd, IndexAt(id), baseVertex))); module.AddStatement(SpirvOp.Return); diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/SpirvMeshTask.cs b/src/SharpEmu.ShaderCompiler.Vulkan/SpirvMeshTask.cs new file mode 100644 index 000000000..7ef0c13ab --- /dev/null +++ b/src/SharpEmu.ShaderCompiler.Vulkan/SpirvMeshTask.cs @@ -0,0 +1,157 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.ShaderCompiler.Vulkan; + +// The task stage of an automatic indirect mesh draw, launched as one workgroup of one invocation. +// It applies SpirvMeshIndirect's rules for an automatic draw to the current arguments, passes the +// mesh shader its draw parameters in the payload and launches the groups of the helper's command. +public static class SpirvMeshTask +{ + // The task stage's push range directly follows the push data the other stages share. + public const uint PushOffsetBytes = PushData.ByteSize; + + // Words 0-1: the arguments' device address. Words 2-3: the address of two diagnostic counters + // (draws over the mesh limits, draws past the range), 0 for none. Words 4-7: the arguments, + // read only when their address is 0. + public const uint PushWordCount = 8; + + // SpirvMeshIndirect's push words 4-8: primitives per group, point list and the mesh group limits. + public const uint SpecPrimitivesPerGroup = 0; + public const uint SpecPointList = 1; + public const uint SpecMaxGroupCountX = 2; + public const uint SpecMaxGroupCountY = 3; + public const uint SpecMaxGroupTotalCount = 4; + + // { DrawCount, FirstVertex, FirstInstance }: the first three of the mesh shader's draw parameters. + public const uint PayloadWordCount = 3; + + public static byte[] Create() + { + var module = new SpirvModuleBuilder(); + module.AddCapability(SpirvCapability.Shader); + module.AddCapability(SpirvCapability.Int64); + module.AddCapability(SpirvCapability.PhysicalStorageBufferAddresses); + module.AddCapability(SpirvCapability.MeshShadingExt); + module.AddExtension("SPV_EXT_mesh_shader"); + module.SetPhysicalStorageBuffer64MemoryModel(); + var voidType = module.TypeVoid(); + var uintType = module.TypeInt(32, false); + var ulongType = module.TypeInt(64, false); + var boolType = module.TypeBool(); + uint Constant(uint value) => module.Constant(uintType, value); + uint Constant64(ulong value) => module.Constant64(ulongType, value); + uint Operation(SpirvOp operation, uint left, uint right) => module.AddInstruction(operation, uintType, left, right); + uint Compare(SpirvOp operation, uint left, uint right) => module.AddInstruction(operation, boolType, left, right); + uint And(uint left, uint right) => Compare(SpirvOp.LogicalAnd, left, right); + uint Not(uint value) => module.AddInstruction(SpirvOp.LogicalNot, boolType, value); + uint Select(uint condition, uint yes, uint no) => module.AddInstruction(SpirvOp.Select, uintType, condition, yes, no); + uint Specialization(uint id, uint defaultValue) => module.SpecConstant(uintType, id, defaultValue); + var perGroup = Specialization(SpecPrimitivesPerGroup, 1); + var pointListValue = Specialization(SpecPointList, 0); + var maxGroupsX = Specialization(SpecMaxGroupCountX, 1); + var maxGroupsY = Specialization(SpecMaxGroupCountY, 1); + var maxGroups = Specialization(SpecMaxGroupTotalCount, 1); + var pushArray = module.TypeArray(uintType, PushWordCount); + module.AddDecoration(pushArray, SpirvDecoration.ArrayStride, 4); + var pushStructure = module.TypeStruct(pushArray); + module.AddDecoration(pushStructure, SpirvDecoration.Block); + module.AddMemberDecoration(pushStructure, 0, SpirvDecoration.Offset, PushOffsetBytes); + var push = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.PushConstant, pushStructure), SpirvStorageClass.PushConstant); + var pushWord = module.TypePointer(SpirvStorageClass.PushConstant, uintType); + var payload = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.TaskPayloadWorkgroupExt, + PayloadType(module, uintType)), SpirvStorageClass.TaskPayloadWorkgroupExt); + var payloadWord = module.TypePointer(SpirvStorageClass.TaskPayloadWorkgroupExt, uintType); + var deviceWord = module.TypePointer(SpirvStorageClass.PhysicalStorageBuffer, uintType); + var main = module.BeginFunction(voidType, module.TypeFunction(voidType)); + var entry = module.AddLabel(); + uint LoadPush(uint index) => module.AddInstruction(SpirvOp.Load, uintType, + module.AddInstruction(SpirvOp.AccessChain, pushWord, push, Constant(0), Constant(index))); + uint Address(uint low, uint high) => module.AddInstruction(SpirvOp.BitwiseOr, ulongType, + module.AddInstruction(SpirvOp.UConvert, ulongType, low), + module.AddInstruction(SpirvOp.ShiftLeftLogical, ulongType, module.AddInstruction(SpirvOp.UConvert, ulongType, high), Constant64(32))); + uint DeviceWord(uint address, uint byteOffset) => module.AddInstruction(SpirvOp.ConvertUToPtr, deviceWord, + module.AddInstruction(SpirvOp.IAdd, ulongType, address, Constant64(byteOffset))); + void If(uint condition, Action body) + { + var yes = module.AllocateId(); + var end = module.AllocateId(); + module.AddStatement(SpirvOp.SelectionMerge, end, 0); + module.AddStatement(SpirvOp.BranchConditional, condition, yes, end); + module.AddLabel(yes); + body(); + module.AddStatement(SpirvOp.Branch, end); + module.AddLabel(end); + } + var argumentsAddress = Address(LoadPush(0), LoadPush(1)); + var counterAddress = Address(LoadPush(2), LoadPush(3)); + // The arguments (vertexCount, instanceCount, firstVertex, firstInstance) are read through their + // address, or come in the push words when the host has none. Address 0 is never read. + var pushed = new uint[4]; + for (uint index = 0; index < pushed.Length; index++) + pushed[index] = LoadPush(4 + index); + var addressed = Compare(SpirvOp.INotEqual, argumentsAddress, Constant64(0)); + var read = module.AllocateId(); + var merge = module.AllocateId(); + module.AddStatement(SpirvOp.SelectionMerge, merge, 0); + module.AddStatement(SpirvOp.BranchConditional, addressed, read, merge); + module.AddLabel(read); + var loaded = new uint[4]; + for (uint index = 0; index < loaded.Length; index++) + loaded[index] = module.AddInstruction(SpirvOp.Load, uintType, DeviceWord(argumentsAddress, index * 4), 2u, 4u); + module.AddStatement(SpirvOp.Branch, merge); + module.AddLabel(merge); + uint Argument(int index) => module.AddInstruction(SpirvOp.Phi, uintType, loaded[index], read, pushed[index], entry); + var requested = Argument(0); + var instances = Argument(1); + var requestedFirst = Argument(2); + var firstInstance = Argument(3); + // From here on as SpirvMeshIndirect for an automatic draw, whose capacity is the whole range. + var capacity = Constant(uint.MaxValue); + requested = Select(Compare(SpirvOp.ULessThan, requested, capacity), requested, capacity); + var firstIndex = Select(Compare(SpirvOp.ULessThan, requestedFirst, capacity), requestedFirst, capacity); + var room = Operation(SpirvOp.ISub, capacity, firstIndex); + var count = Select(Compare(SpirvOp.ULessThan, requested, room), requested, room); + var pointList = Compare(SpirvOp.INotEqual, pointListValue, Constant(0)); + var primitives = Select(pointList, count, Operation(SpirvOp.UDiv, count, Constant(3))); + var vertices = Select(pointList, count, Operation(SpirvOp.IMul, primitives, Constant(3))); + var groups = Operation(SpirvOp.UDiv, Operation(SpirvOp.IAdd, primitives, + Operation(SpirvOp.ISub, perGroup, Constant(1))), perGroup); + var active = And(Compare(SpirvOp.INotEqual, count, Constant(0)), Compare(SpirvOp.INotEqual, instances, Constant(0))); + var requestedActive = And(Compare(SpirvOp.INotEqual, requested, Constant(0)), Compare(SpirvOp.INotEqual, instances, Constant(0))); + var rangeValid = And(Compare(SpirvOp.ULessThanEqual, requestedFirst, capacity), + Compare(SpirvOp.ULessThanEqual, requested, room)); + var nonzeroGroups = Select(Compare(SpirvOp.IEqual, groups, Constant(0)), Constant(1), groups); + var limitsValid = And(And(Compare(SpirvOp.ULessThanEqual, groups, maxGroupsX), + Compare(SpirvOp.ULessThanEqual, instances, maxGroupsY)), + Compare(SpirvOp.LogicalOr, Compare(SpirvOp.IEqual, groups, Constant(0)), + Compare(SpirvOp.ULessThanEqual, instances, Operation(SpirvOp.UDiv, maxGroups, nonzeroGroups)))); + var execute = And(active, limitsValid); + // The helper's nonzero statuses, counted: 2 (over the mesh limits) in word 0, 1 (a range past + // the capacity) in word 1. Device-scope relaxed atomics. + var counted = Compare(SpirvOp.INotEqual, counterAddress, Constant64(0)); + void Count(uint condition, uint byteOffset) => If(And(counted, condition), () => + module.AddInstruction(SpirvOp.AtomicIAdd, uintType, DeviceWord(counterAddress, byteOffset), Constant(1), Constant(0), Constant(1))); + Count(And(requestedActive, Not(limitsValid)), 0); + Count(And(And(requestedActive, limitsValid), Not(rangeValid)), 4); + // The draw parameters the helper wrote for the mesh shader, then its indirect command. The + // only invocation emits it once, in uniform control flow. + void Pass(uint member, uint value) => module.AddStatement(SpirvOp.Store, + module.AddInstruction(SpirvOp.AccessChain, payloadWord, payload, Constant(member)), value); + Pass(0, Select(execute, vertices, Constant(0))); + Pass(1, firstIndex); + Pass(2, firstInstance); + module.AddStatement(SpirvOp.EmitMeshTasksExt, Select(execute, groups, Constant(0)), + Select(execute, instances, Constant(0)), Select(execute, Constant(1), Constant(0)), payload); + module.EndFunction(); + module.AddEntryPoint(SpirvExecutionModel.TaskExt, main, "main", [push, payload]); + module.AddExecutionMode(main, SpirvExecutionMode.LocalSize, 1, 1, 1); + return module.Build(); + } + + // The payload's type. The mesh shader of a task-launched draw declares the same one. + internal static uint PayloadType(SpirvModuleBuilder module, uint uintType) => + module.TypeStruct([.. Enumerable.Repeat(uintType, (int)PayloadWordCount)]); +} diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/SpirvModuleBuilder.Simplify.cs b/src/SharpEmu.ShaderCompiler.Vulkan/SpirvModuleBuilder.Simplify.cs index b8aafad3f..54ac17e1f 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/SpirvModuleBuilder.Simplify.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/SpirvModuleBuilder.Simplify.cs @@ -10,18 +10,31 @@ public sealed partial class SpirvModuleBuilder private const uint GlslFrexp = 51; private const uint SubgroupScope = 3; private static readonly uint[] GlslMinMax = [37, 38, 39, 40, 41, 42, 79, 80]; + private const uint GlslUMin = 38; private readonly Dictionary _resultTypes = []; private readonly Dictionary _integerTypeInfo = []; private readonly Dictionary _wideConstantValues = []; private readonly Dictionary _floatConstantBits = []; private readonly Dictionary _definitions = []; - private readonly Dictionary _blockValues = []; + // The current block's expressions. A snapshot (BlockState) and the blocks that inherit all of it share one table: it + // is copied before its first change and replaced instead of cleared, so neither a branch nor an inheriting block + // entry copies it. + private ExpressionTable _blockValues = new(); + private bool _blockValuesShared; + // A copy of a shared table holds all of its entries with the same values: a shared table never changes again, and a + // copy only gains entries. A table is cleared only while unshared, so no other table names it as a base. + private const int MaxExpressionBases = 32; + private int _blockValuesSerial; + private int[] _blockValuesBases = []; + private int _nextExpressionSerial; private readonly HashSet _localVariables = []; private readonly HashSet _escapedVariables = []; private readonly Dictionary _elementBases = []; private readonly HashSet _scalarPointerTypes = []; private readonly HashSet _inputVariables = []; + // Variables nothing writes while the invocation runs: descriptors (UniformConstant) and push constants. + private readonly HashSet _immutableVariables = []; private readonly HashSet _changingInputs = []; private readonly Dictionary _entryValues = []; private readonly Dictionary _entryOperations = []; @@ -49,7 +62,59 @@ public sealed partial class SpirvModuleBuilder private readonly record struct Definition(SpirvOp Opcode, uint Type, uint[] Operands); - private sealed record BlockState(Dictionary Values, Dictionary Expressions); + // ExpressionSerial names the expression table; ExpressionBases are the tables it was copied from, nearest first. + private sealed record BlockState(Dictionary Values, ExpressionTable Expressions, + int ExpressionSerial, int[] ExpressionBases); + + // A block expression table: an immutable base, shared with other tables, and the table's own entries, which never + // repeat a key of the base. A copy keeps the base and copies only the own entries; once those are many, the copy + // folds them into a new base. A table that shares an inherited table of thousands of entries copies a few. + private sealed class ExpressionTable + { + private const int MaxOwnEntries = 512; + + private Dictionary? _base; + private Dictionary _own = []; + + public int Count => (_base?.Count ?? 0) + _own.Count; + + public Dictionary? Base => _base; + + public Dictionary Own => _own; + + public bool TryGetValue(InstructionKey key, out uint value) => + _own.TryGetValue(key, out value) || (_base is not null && _base.TryGetValue(key, out value)); + + public void Set(InstructionKey key, uint value) => _own[key] = value; + + public void Clear() + { + _base = null; + _own.Clear(); + } + + public ExpressionTable Copy() + { + if (_own.Count < MaxOwnEntries) + { + return new ExpressionTable { _base = _base, _own = new Dictionary(_own) }; + } + + if (_base is null) + { + return new ExpressionTable { _base = new Dictionary(_own) }; + } + + var merged = new Dictionary(_base); + merged.EnsureCapacity(_base.Count + _own.Count); + foreach (var (key, value) in _own) + { + merged.Add(key, value); + } + + return new ExpressionTable { _base = merged }; + } + } private readonly struct InstructionKey : IEquatable { @@ -110,7 +175,8 @@ public uint AddInstruction(SpirvOp opcode, uint resultType, params uint[] operan return element; } - NoteVariableUses(operands); + // ExtInst's operation number is a literal, even when its value equals a variable id. + NoteVariableUses(operands, opcode == SpirvOp.ExtInst ? 1 : -1); if (TryFold(opcode, resultType, operands, out var folded) || TrySimplify(opcode, resultType, operands, out folded)) { @@ -141,11 +207,17 @@ public uint AddInstruction(SpirvOp opcode, uint resultType, params uint[] operan var result = EmitResult(_functions, opcode, resultType, operands); var key = new InstructionKey(opcode, resultType, operands.ToArray()); - _blockValues[key] = result; + WritableBlockValues().Set(key, result); _definitions[result] = new Definition(opcode, resultType, key.Operands); return result; } + // Runs before a statement that ends the current block, or a call made through AddStatement, so the emitter can + // finish work it keeps for the block (deferred EXEC guards). A call made through AddInstruction does not run it: the + // emitter flushes before each call into guest code itself. + public Action? BeforeBlockExit { get; set; } + private bool _inBlockExit; + public void AddStatement(SpirvOp opcode, params uint[] operands) { if (opcode == SpirvOp.Store) @@ -154,6 +226,22 @@ public void AddStatement(SpirvOp opcode, params uint[] operands) return; } + if (BeforeBlockExit is not null && !_inBlockExit && + opcode is SpirvOp.SelectionMerge or SpirvOp.LoopMerge or SpirvOp.Branch or SpirvOp.BranchConditional or + SpirvOp.Switch or SpirvOp.Return or SpirvOp.ReturnValue or SpirvOp.Kill or SpirvOp.Unreachable or + SpirvOp.FunctionCall) + { + _inBlockExit = true; + try + { + BeforeBlockExit(); + } + finally + { + _inBlockExit = false; + } + } + NoteVariableUses(operands); if (opcode == SpirvOp.LoopMerge) { @@ -197,7 +285,7 @@ private bool TryAddElementPointer(uint resultType, uint[] operands, out uint ele { element = EmitResult(_functions, SpirvOp.AccessChain, resultType, operands); var key = new InstructionKey(SpirvOp.AccessChain, resultType, operands.ToArray()); - _blockValues[key] = element; + WritableBlockValues().Set(key, element); _definitions[element] = new Definition(SpirvOp.AccessChain, resultType, key.Operands); } @@ -214,8 +302,27 @@ private uint AddLoad(uint resultType, uint[] operands) return EntryLoad(resultType, pointer); } + // A load of memory nothing writes is a value: the block values reuse it like arithmetic. + if (operands.Length == 1 && IsImmutablePointer(pointer)) + { + var lookup = new InstructionKey(SpirvOp.Load, resultType, operands); + if (_blockValues.TryGetValue(lookup, out var loaded)) + { + return loaded; + } + + var value = EmitResult(_functions, SpirvOp.Load, resultType, operands); + WritableBlockValues().Set(new InstructionKey(SpirvOp.Load, resultType, operands.ToArray()), value); + return value; + } + if (operands.Length != 1 || !IsTrackedPointer(pointer)) { + if (operands.Length != 1) + { + InvalidateExplicitAccessMemoryState(pointer); + } + return EmitResult(_functions, SpirvOp.Load, resultType, operands); } @@ -232,6 +339,11 @@ private uint AddLoad(uint resultType, uint[] operands) var result = EmitResult(_functions, SpirvOp.Load, resultType, operands); _inheritedPointers.Remove(pointer); _pendingStores.Remove(pointer); + if (_elementBases.TryGetValue(pointer, out var elementBase)) + { + _pendingStores.Remove(elementBase); + } + if (_localVariables.Contains(pointer)) { ForgetElements(pointer, keepValues: true); @@ -246,7 +358,11 @@ private void AddStore(uint[] operands) var pointer = operands[0]; if (operands.Length != 2 || !IsTrackedPointer(pointer)) { - if (_localVariables.Contains(pointer)) + if (operands.Length != 2) + { + InvalidateExplicitAccessMemoryState(pointer); + } + else if (_localVariables.Contains(pointer)) { _variableValues.Remove(pointer); _pendingStores.Remove(pointer); @@ -301,8 +417,34 @@ private uint EntryLoad(uint resultType, uint pointer) return result; } + // A load, in the current function's entry block, of a word the invocation never writes (the host's shader data), through + // constant indices: operations of it and of constants then join the entry too (CanHoistToEntry), once per function. + // Zero when the entry block is not open or an index is not a constant. + public uint EntryWordLoad(uint resultType, uint pointerType, uint variable, params uint[] constantIndices) + { + if (!IsEntryAvailable() || constantIndices.Any(index => !_scalarConstantValues.ContainsKey(index))) + { + return 0; + } + + uint[] chain = [variable, .. constantIndices]; + var key = new InstructionKey(SpirvOp.AccessChain, pointerType, chain); + if (!_entryOperations.TryGetValue(key, out var pointer)) + { + pointer = AppendToEntry(SpirvOp.AccessChain, pointerType, chain); + _entryOperations[key] = pointer; + _definitions[pointer] = new Definition(SpirvOp.AccessChain, pointerType, chain); + } + + return EntryLoad(resultType, pointer); + } + private bool IsEntryAvailable() => CurrentFunction != 0 && !_entryLabelPending && _entryLabelOffset >= 0; + private bool IsImmutablePointer(uint pointer) => + _immutableVariables.Contains(pointer) || + (Defines(pointer, SpirvOp.AccessChain, out var chain) && _immutableVariables.Contains(chain.Operands[0])); + private bool CanHoistToEntry(SpirvOp opcode, uint[] operands) { if (!IsEntryAvailable() || opcode is SpirvOp.ExtInst or SpirvOp.CompositeExtract or SpirvOp.CompositeInsert or @@ -368,10 +510,12 @@ private bool IsTrackedVariable(uint pointer) => private bool IsTrackedPointer(uint pointer) => IsTrackedVariable(pointer) || (_elementBases.TryGetValue(pointer, out var variable) && IsTrackedVariable(variable)); - private void NoteVariableUses(uint[] operands) + private void NoteVariableUses(uint[] operands, int literalIndex = -1) { - foreach (var operand in operands) + for (var index = 0; index < operands.Length; index++) { + if (index == literalIndex) continue; + var operand = operands[index]; if (_localVariables.Contains(operand)) { EscapeVariable(operand); @@ -448,7 +592,8 @@ private void NoteBranchTargets(SpirvOp opcode, uint[] operands) continue; } - state ??= new BlockState(new Dictionary(_variableValues), new Dictionary(_blockValues)); + state ??= new BlockState(new Dictionary(_variableValues), ShareBlockValues(), _blockValuesSerial, + _blockValuesBases); if (!_incomingStates.TryGetValue(target, out var incoming)) { incoming = []; @@ -470,12 +615,24 @@ private void EnterBlock(uint label) } var first = incoming[0].State; - foreach (var (expression, value) in first.Expressions) + if (incoming.Count == 1) + { + // One predecessor: the block inherits every expression of its state. + InheritBlockValues(first); + } + else if (CommonExpressionBase(incoming) is { } common) + { + // Every incoming table is this one or a copy of it with more entries: their common expressions are its own. + InheritBlockValues(common); + } + else { - if (incoming.All(entry => entry.State.Expressions.TryGetValue(expression, out var other) && other == value)) + if (first.Expressions.Base is { } inherited) { - _blockValues[expression] = value; + InheritHeldExpressions(incoming, inherited); } + + InheritHeldExpressions(incoming, first.Expressions.Own); } if (!_loopHeaders.Contains(label)) @@ -494,6 +651,64 @@ private void EnterBlock(uint label) _inheritedLabels[label] = incoming.Count; } + private void InheritBlockValues(BlockState state) + { + _blockValues = state.Expressions; + _blockValuesShared = true; + _blockValuesSerial = state.ExpressionSerial; + _blockValuesBases = state.ExpressionBases; + } + + // The incoming state whose expression table every incoming table is or was copied from, if one is. + private static BlockState? CommonExpressionBase(List<(uint Block, BlockState State)> incoming) + { + var candidate = incoming[0].State; + foreach (var (_, state) in incoming) + { + if (state.Expressions.Count < candidate.Expressions.Count) + { + candidate = state; + } + } + + foreach (var (_, state) in incoming) + { + if (state.ExpressionSerial != candidate.ExpressionSerial && + Array.IndexOf(state.ExpressionBases, candidate.ExpressionSerial) < 0) + { + return null; + } + } + + return candidate; + } + + private void InheritHeldExpressions(List<(uint Block, BlockState State)> incoming, Dictionary expressions) + { + foreach (var (expression, value) in expressions) + { + if (HeldByOthers(incoming, expression, value)) + { + _blockValues.Set(expression, value); + } + } + } + + // Whether every incoming state after the first holds the first state's expression with the same value. A loop, not a + // closure and delegate per expression: blocks inherit thousands of expressions. + private static bool HeldByOthers(List<(uint Block, BlockState State)> incoming, InstructionKey expression, uint value) + { + for (var index = 1; index < incoming.Count; index++) + { + if (!incoming[index].State.Expressions.TryGetValue(expression, out var other) || other != value) + { + return false; + } + } + + return true; + } + private uint MergeIncomingValue(uint pointer, uint value, List<(uint Block, BlockState State)> incoming) { var type = TypeOf(value); @@ -549,6 +764,20 @@ private void LeaveLoopHeader() _inheritedPointers.Clear(); } + private void InvalidateExplicitAccessMemoryState(uint pointer) + { + if (!IsTrackedPointer(pointer) && !_localVariables.Contains(pointer)) + { + return; + } + + // The access bypasses forwarding, but must still end pending-store eligibility. + // Preserve evidence of an inherited value already used in this block. + var inheritedValueUsed = _inheritedValueUsed; + ResetMemoryState(); + _inheritedValueUsed = inheritedValueUsed; + } + private void ResetMemoryState() { _variableValues.Clear(); @@ -560,7 +789,41 @@ private void ResetMemoryState() private void ResetBlockState() { ResetMemoryState(); - _blockValues.Clear(); + if (_blockValuesShared) + { + _blockValues = new ExpressionTable(); + _blockValuesShared = false; + } + else + { + _blockValues.Clear(); + } + + _blockValuesSerial = ++_nextExpressionSerial; + _blockValuesBases = []; + } + + // The expression table for a snapshot: the live dictionary itself, which is copied before its next change. + private ExpressionTable ShareBlockValues() + { + _blockValuesShared = true; + return _blockValues; + } + + private ExpressionTable WritableBlockValues() + { + if (_blockValuesShared) + { + _blockValues = _blockValues.Copy(); + _blockValuesShared = false; + var bases = new int[Math.Min(_blockValuesBases.Length + 1, MaxExpressionBases)]; + bases[0] = _blockValuesSerial; + Array.Copy(_blockValuesBases, 0, bases, 1, bases.Length - 1); + _blockValuesBases = bases; + _blockValuesSerial = ++_nextExpressionSerial; + } + + return _blockValues; } private void NoteResultType(uint id, uint type) => _resultTypes[id] = type; @@ -579,6 +842,30 @@ private bool IsUnsignedInteger(uint type, uint width) => private bool Defines(uint id, SpirvOp opcode, out Definition definition) => _definitions.TryGetValue(id, out definition) && definition.Opcode == opcode; + // The largest value a 32-bit unsigned id can hold, from its definition: a constant, a logical right shift by a constant + // or an AND with a constant. + private ulong UpperBound(uint id) + { + if (IsIntegerConstant(id, out var value)) + { + return value; + } + + if (Defines(id, SpirvOp.ShiftRightLogical, out var shift) && IsIntegerConstant(shift.Operands[1], out var amount) && + amount < 32) + { + return uint.MaxValue >> (int)amount; + } + + if (Defines(id, SpirvOp.BitwiseAnd, out var and)) + { + return Math.Min(IsIntegerConstant(and.Operands[0], out var left) ? left : uint.MaxValue, + IsIntegerConstant(and.Operands[1], out var right) ? right : uint.MaxValue); + } + + return uint.MaxValue; + } + private bool IsIntegerConstant(uint id, out ulong value) { if (_wideConstantValues.TryGetValue(id, out value)) @@ -679,6 +966,10 @@ private bool TrySimplify(SpirvOp opcode, uint resultType, uint[] operands, out u operands[2] == operands[3] && HasType(operands[2], resultType): result = operands[2]; return true; + case SpirvOp.ExtInst when operands.Length == 4 && operands[1] == GlslUMin && IsUnsignedInteger(resultType, 32) && + IsIntegerConstant(operands[3], out var limit) && UpperBound(operands[2]) <= limit: + result = operands[2]; + return true; case SpirvOp.IEqual or SpirvOp.INotEqual when operands.Length == 2: return TrySimplifyZeroTest(opcode == SpirvOp.INotEqual, resultType, operands, out result); case SpirvOp.Bitcast when operands.Length == 1: @@ -1136,7 +1427,8 @@ private bool IsRemovableDefinition(List words, int offset, int wordCount) var opcode = (SpirvOp)(words[offset] & 0xFFFF); if (opcode == SpirvOp.Load) { - return wordCount == 4 && (_localVariables.Contains(words[offset + 3]) || _elementBases.ContainsKey(words[offset + 3])); + // A load without memory operands yields its value and nothing else; no module declares Volatile memory. + return wordCount == 4; } if (wordCount < 3) @@ -1157,11 +1449,21 @@ private bool IsRemovableDefinition(List words, int offset, int wordCount) return IsValueOperation(opcode, []); } + // The passes over every function word index ids in arrays (every id is below _nextId); a word at or past it is a + // literal that names no variable, chain or definition. private HashSet FindUnreadVariables(out HashSet unreadPointers) { var words = _functions; - var chainBases = new Dictionary(); - var read = new HashSet(); + var local = new bool[_nextId]; + foreach (var variable in _localVariables) + { + local[variable] = true; + } + + // The variable of each access chain into a local variable, once the scan has passed the chain (0: none). + var chainBases = new uint[_nextId]; + var chains = new List(); + var read = new bool[_nextId]; for (var offset = 0; offset < words.Count; offset += (int)(words[offset] >> 16)) { var wordCount = (int)(words[offset] >> 16); @@ -1174,7 +1476,8 @@ private HashSet FindUnreadVariables(out HashSet unreadPointers) case SpirvOp.Store when wordCount == 3: first = 2; break; - case SpirvOp.AccessChain when wordCount >= 4 && _localVariables.Contains(words[offset + 3]): + case SpirvOp.AccessChain when wordCount >= 4 && words[offset + 3] < (uint)local.Length && local[words[offset + 3]]: + chains.Add(words[offset + 2]); chainBases[words[offset + 2]] = words[offset + 3]; first = 4; break; @@ -1182,23 +1485,29 @@ private HashSet FindUnreadVariables(out HashSet unreadPointers) for (var word = first; word < wordCount; word++) { + if (opcode == SpirvOp.ExtInst && word == 4) continue; var id = words[offset + word]; - if (_localVariables.Contains(id)) + if (id >= (uint)local.Length) { - read.Add(id); + continue; } - else if (chainBases.TryGetValue(id, out var variable)) + + if (local[id]) { - read.Add(variable); + read[id] = true; + } + else if (chainBases[id] != 0) + { + read[chainBases[id]] = true; } } } - var unread = KeepsUnreadVariables ? [] : new HashSet(_localVariables.Where(variable => !read.Contains(variable))); + var unread = KeepsUnreadVariables ? [] : new HashSet(_localVariables.Where(variable => !read[variable])); unreadPointers = new HashSet(unread); - foreach (var (chain, variable) in chainBases) + foreach (var chain in chains) { - if (unread.Contains(variable)) + if (unread.Contains(chainBases[chain])) { unreadPointers.Add(chain); } @@ -1279,8 +1588,10 @@ private List CompactFunctions(HashSet removedIds, HashSet unre } var removed = new bool[starts.Count]; - var uses = new Dictionary(); - var definers = new Dictionary(); + var uses = new int[_nextId]; + // The instruction (index + 1; 0: none) defining an id whose definition may be removed, and those ids in order. + var definers = new int[_nextId]; + var defined = new List(); for (var index = 0; index < starts.Count; index++) { var offset = starts[index]; @@ -1297,23 +1608,28 @@ private List CompactFunctions(HashSet removedIds, HashSet unre var first = 1; if (IsRemovableDefinition(words, offset, wordCount)) { - definers[words[offset + 2]] = index; + definers[words[offset + 2]] = index + 1; + defined.Add(words[offset + 2]); first = 3; } for (var word = first; word < wordCount; word++) { + if (opcode == SpirvOp.ExtInst && word == 4) continue; var id = words[offset + word]; - uses[id] = uses.GetValueOrDefault(id) + 1; + if (id < (uint)uses.Length) + { + uses[id]++; + } } } var pending = new Stack(); - foreach (var (id, index) in definers) + foreach (var id in defined) { - if (uses.GetValueOrDefault(id) == 0) + if (uses[id] == 0) { - pending.Push(index); + pending.Push(definers[id] - 1); } } @@ -1327,19 +1643,20 @@ private List CompactFunctions(HashSet removedIds, HashSet unre removed[index] = true; var offset = starts[index]; var wordCount = (int)(words[offset] >> 16); + var opcode = (SpirvOp)(words[offset] & 0xFFFF); removedIds.Add(words[offset + 2]); for (var word = 3; word < wordCount; word++) { + if (opcode == SpirvOp.ExtInst && word == 4) continue; var id = words[offset + word]; - if (!uses.TryGetValue(id, out var count)) + if (id >= (uint)uses.Length || uses[id] == 0) { continue; } - uses[id] = --count; - if (count == 0 && definers.TryGetValue(id, out var definer) && !removed[definer]) + if (--uses[id] == 0 && definers[id] != 0 && !removed[definers[id] - 1]) { - pending.Push(definer); + pending.Push(definers[id] - 1); } } } diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/SpirvModuleBuilder.cs b/src/SharpEmu.ShaderCompiler.Vulkan/SpirvModuleBuilder.cs index 00c3c8135..8776eed7c 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/SpirvModuleBuilder.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/SpirvModuleBuilder.cs @@ -35,6 +35,7 @@ public enum SpirvOp : ushort Constant = 43, ConstantComposite = 44, ConstantNull = 46, + SpecConstant = 50, Function = 54, FunctionParameter = 55, FunctionEnd = 56, @@ -177,13 +178,23 @@ public enum SpirvOp : ushort GroupNonUniformBroadcast = 337, GroupNonUniformBroadcastFirst = 338, GroupNonUniformBallot = 339, + GroupNonUniformBallotBitExtract = 341, GroupNonUniformBallotBitCount = 342, GroupNonUniformShuffle = 345, GroupNonUniformShuffleXor = 346, GroupNonUniformShuffleUp = 347, GroupNonUniformShuffleDown = 348, + GroupNonUniformIAdd = 349, + GroupNonUniformSMin = 353, GroupNonUniformUMin = 354, + GroupNonUniformSMax = 356, + GroupNonUniformUMax = 357, + GroupNonUniformBitwiseAnd = 359, + GroupNonUniformBitwiseOr = 360, + GroupNonUniformBitwiseXor = 361, + EmitMeshTasksExt = 5294, SetMeshOutputsExt = 5295, + ReadClockKhr = 5056, } public enum SpirvCapability : uint @@ -223,8 +234,11 @@ public enum SpirvCapability : uint RuntimeDescriptorArray = 5302, SampledImageArrayNonUniformIndexing = 5307, PhysicalStorageBufferAddresses = 5347, + DenormPreserve = 4464, SignedZeroInfNanPreserve = 4466, + RoundingModeRte = 4467, MeshShadingExt = 5283, + ShaderClockKhr = 5055, } public enum SpirvStorageClass : uint @@ -240,6 +254,7 @@ public enum SpirvStorageClass : uint Image = 11, StorageBuffer = 12, PhysicalStorageBuffer = 5349, + TaskPayloadWorkgroupExt = 5402, } public enum SpirvExecutionModel : uint @@ -249,6 +264,7 @@ public enum SpirvExecutionModel : uint TessellationEvaluation = 2, Fragment = 4, GLCompute = 5, + TaskExt = 5364, MeshExt = 5365, } @@ -266,7 +282,9 @@ public enum SpirvExecutionMode : uint OriginUpperLeft = 7, DepthReplacing = 12, LocalSize = 17, + DenormPreserve = 4459, SignedZeroInfNanPreserve = 4461, + RoundingModeRte = 4462, OutputVertices = 26, OutputPrimitivesExt = 5270, OutputTrianglesExt = 5298, @@ -274,6 +292,7 @@ public enum SpirvExecutionMode : uint public enum SpirvDecoration : uint { + SpecId = 1, Block = 2, ArrayStride = 6, BuiltIn = 11, @@ -849,6 +868,16 @@ public uint ConstantNull(uint type) return id; } + // A 32-bit specialization constant. It is never folded or shared with a constant, because + // the pipeline sets its value. + public uint SpecConstant(uint type, uint specId, uint defaultValue) + { + var id = AllocateId(); + Emit(_typesConstantsGlobals, SpirvOp.SpecConstant, type, id, defaultValue); + AddDecoration(id, SpirvDecoration.SpecId, specId); + return id; + } + public uint AddGlobalVariable( uint pointerType, SpirvStorageClass storageClass, @@ -878,6 +907,10 @@ public uint AddGlobalVariable( { _inputVariables.Add(id); } + else if (storageClass is SpirvStorageClass.UniformConstant or SpirvStorageClass.PushConstant) + { + _immutableVariables.Add(id); + } return id; } @@ -901,6 +934,9 @@ public uint BeginFunction(uint returnType, uint functionType, uint functionContr public uint AddFunctionParameter(uint type) => EmitResult(_functions, SpirvOp.FunctionParameter, type); + // The label of the block being emitted. + public uint CurrentBlock => _currentBlock; + public uint AddLabel(uint? id = null) { var result = id ?? AllocateId(); @@ -1157,11 +1193,10 @@ private uint EmitResult( params uint[] operands) { var result = AllocateId(); - var values = new uint[operands.Length + 2]; - values[0] = resultType; - values[1] = result; - operands.CopyTo(values, 2); - Emit(section, opcode, values); + section.Add(((uint)(operands.Length + 3) << 16) | (ushort)opcode); + section.Add(resultType); + section.Add(result); + section.AddRange(operands); NoteResultType(result, resultType); return result; } diff --git a/src/SharpEmu.ShaderCompiler/Gen5ShaderCallLinker.cs b/src/SharpEmu.ShaderCompiler/Gen5ShaderCallLinker.cs index f7ebb768f..72badf986 100644 --- a/src/SharpEmu.ShaderCompiler/Gen5ShaderCallLinker.cs +++ b/src/SharpEmu.ShaderCompiler/Gen5ShaderCallLinker.cs @@ -6,6 +6,12 @@ namespace SharpEmu.ShaderCompiler; public sealed record ShaderCallTarget(ulong Address, ulong Argument, Gen5ShaderProgram Program); + +// A call target whose code cannot be inlined; the message names the target and the instruction. +public sealed class ShaderCallLinkException(string message, ShaderCallTarget target) : InvalidOperationException(message) +{ + public ShaderCallTarget Target { get; } = target; +} public sealed record ShaderCallSite(uint Pc, uint AddressRegister, uint ArgumentRegister, uint ReturnRegister, ulong ReturnAddress, IReadOnlyList Targets); // With RuntimeArgument, the test of the callee alone: every record of it matches. @@ -43,7 +49,7 @@ public static class Gen5ShaderCallLinker // the records; otherwise one copy per record, whose argument the plan reads. public static Gen5ShaderProgram Link(Gen5ShaderProgram caller, IReadOnlyList calls, bool runtimeArguments = false) { - if (caller.IsFusedProgram || caller.Instructions.Any(instruction => instruction.Opcode is "SGetpcB64" or "SSetpcB64")) + if (caller.IsFusedProgram || caller.Instructions.Any(instruction => instruction.Opcode is "SSetpcB64")) throw new InvalidOperationException("The caller uses an unsupported program-address operation."); var instructions = new List(); var functionBuffers = new HashSet(); @@ -64,14 +70,16 @@ void Branch(int body, uint target) branches.Add((instructions.Count, body, target)); Append(new(0, Gen5ShaderEncoding.Sopp, "SBranch", [0xBF820000], [], [], null)); } - foreach (var instruction in caller.Instructions) + foreach (var instruction in caller.Instructions.Select(WithoutDebuggerBranch)) { labels.Add((0, instruction.Pc), pc); if (instruction.Opcode != "SSwappcB64") { if (Gen5IrBranchResolver.Instance.TryGetBranchTarget(instruction, out var target)) branches.Add((instructions.Count, 0, target)); - Append(instruction); + // S_GETPC_B64 reads the shader base plus the instruction's offset in the caller's code, to address the + // constants placed after the code, say. The copy keeps that offset after the callee bodies before it moved it. + Append(instruction.Opcode == "SGetpcB64" ? instruction with { AddressOffset = instruction.ProgramOffset } : instruction); continue; } // A site whose table holds only null records has no target: it links to its fault, which the @@ -98,13 +106,15 @@ void Branch(int body, uint target) RuntimeArgument = runtimeArguments, Callee = target.Address, })); - foreach (var operation in target.Program.Instructions) + foreach (var operation in target.Program.Instructions.Select(WithoutDebuggerBranch)) { labels.Add((body, operation.Pc), pc); - if (operation.Opcode == "SSetpcB64") + // A function may also return with s_swappc_b64 null, s[ret:ret+1], which jumps without saving an address. + if (operation.Opcode == "SSetpcB64" || Gen5ShaderTranslator.IsSwapProgramCounterWithoutReturnAddress(operation)) { if (operation.Sources.Count != 1 || operation.Sources[0] != Gen5Operand.Scalar(call.ReturnRegister)) - throw new InvalidOperationException("The shader function has an unresolved return target."); + throw new ShaderCallLinkException( + $"The shader function has an unresolved return target: {Describe(target, operation)}.", target); Branch(0, returnPc); continue; } @@ -112,7 +122,8 @@ void Branch(int body, uint target) "SMovreldB32" or "SMovreldB64" or "SMovrelsd2B32" || operation.Destinations.Any(destination => destination.Kind == Gen5OperandKind.ScalarRegister && destination.Value < call.ReturnRegister + 2 && destination.Value + operation.DestinationWidth > call.ReturnRegister)) - throw new InvalidOperationException("The shader function changes its return address or calls another function."); + throw new ShaderCallLinkException( + $"The shader function changes its return address or calls another function: {Describe(target, operation)}.", target); if (Gen5IrBranchResolver.Instance.TryGetBranchTarget(operation, out var destinationPc)) branches.Add((instructions.Count, body, destinationPc)); if (operation.Control is Gen5BufferMemoryControl || operation.Opcode.StartsWith("SBufferLoad", StringComparison.Ordinal)) @@ -128,8 +139,9 @@ void Branch(int body, uint target) } : operation); } - if (target.Program.Instructions.LastOrDefault()?.Opcode is not ("SSetpcB64" or "SEndpgm")) - throw new InvalidOperationException("The shader function has no terminal return."); + if (target.Program.Instructions.LastOrDefault() is not { } last || + last.Opcode is not ("SSetpcB64" or "SEndpgm") && !Gen5ShaderTranslator.IsSwapProgramCounterWithoutReturnAddress(last)) + throw new ShaderCallLinkException($"The shader function has no terminal return: target=0x{target.Address:X}.", target); var test = instructions[testIndex]; instructions[testIndex] = test with { Control = ((ShaderCallMatchControl)test.Control!) with { TargetPc = pc } }; } @@ -184,4 +196,15 @@ [.. program.Instructions.Select(instruction => instruction.Control).OfType program.Instructions.Any(static instruction => instruction.Control is ShaderCallEntryControl or ShaderCallFaultControl); + + // S_CBRANCH_CDBG* branch only under an attached GPU debugger, and the translators emit them as never taken. Their targets + // are debugger stubs past S_ENDPGM that the decode leaves out, so a linked program holds them as S_NOP. + private static Gen5ShaderInstruction WithoutDebuggerBranch(Gen5ShaderInstruction instruction) => + instruction.Opcode.StartsWith("SCbranchCdbg", StringComparison.Ordinal) + ? instruction with { Opcode = "SNop", Words = [0xBF800000], Sources = [], Destinations = [], Control = null } + : instruction; + + private static string Describe(ShaderCallTarget target, Gen5ShaderInstruction operation) => + $"target=0x{target.Address:X} pc=0x{operation.Pc:X} {operation.Opcode} {string.Join(',', operation.Destinations)} <- " + + string.Join(',', operation.Sources); } diff --git a/src/SharpEmu.ShaderCompiler/Gen5ShaderTranslator.cs b/src/SharpEmu.ShaderCompiler/Gen5ShaderTranslator.cs index ffa61b2e0..6aff5ad2a 100644 --- a/src/SharpEmu.ShaderCompiler/Gen5ShaderTranslator.cs +++ b/src/SharpEmu.ShaderCompiler/Gen5ShaderTranslator.cs @@ -354,7 +354,7 @@ private static bool TryReadDeclaredShaderSize( // S_SWAPPC_B64 stores the address of the next instruction in its destination. With the NULL destination // it stores nothing, so it jumps like S_SETPC_B64 does and the code after it is not reached from here. - private static bool IsSwapProgramCounterWithoutReturnAddress(Gen5ShaderInstruction instruction) => + internal static bool IsSwapProgramCounterWithoutReturnAddress(Gen5ShaderInstruction instruction) => string.Equals(instruction.Opcode, "SSwappcB64", StringComparison.Ordinal) && instruction.Destinations is [{ Kind: Gen5OperandKind.ScalarRegister, Value: NullScalarRegister }]; @@ -1642,6 +1642,7 @@ private static bool DecodeDs( 0x4F => "DsWrite2St64B64", 0x76 => "DsReadB64", 0x77 => "DsRead2B64", + 0x78 => "DsRead2St64B64", 0xA0 => "DsWriteB8D16Hi", 0xA1 => "DsWriteB16D16Hi", 0xA2 => "DsReadU8D16", @@ -1810,6 +1811,7 @@ public static string MubufOpcodeName(uint opcode) 0x4B => "BufferAtomicXor", 0x4C => "BufferAtomicInc", 0x50 => "BufferAtomicSwapX2", + 0x59 => "BufferAtomicAndX2", 0x5A => "BufferAtomicOrX2", 0x71 => "BufferGl0Inv", 0x72 => "BufferGl1Inv", @@ -1925,6 +1927,8 @@ private static bool DecodeSmem(uint word, out string name, out uint sizeDwords, 0x0A => "SBufferLoadDwordx4", 0x0B => "SBufferLoadDwordx8", 0x0C => "SBufferLoadDwordx16", + 0x24 => "SMemtime", + 0x25 => "SMemrealtime", _ => string.Empty, }; @@ -2437,6 +2441,13 @@ .. Enumerable.Range(0, checked((int)storeCount)).Select(index => dynamicOffsetRegister); break; } + case Gen5ShaderEncoding.Smem when opcode is "SMemtime" or "SMemrealtime": + { + // A clock read writes an SGPR pair and touches no memory. + var clockDestination = (word >> 6) & 0x7F; + destinations = [Gen5Operand.Scalar(clockDestination), Gen5Operand.Scalar(clockDestination + 1)]; + break; + } case Gen5ShaderEncoding.Smem: { var extra = words[1]; @@ -2791,7 +2802,7 @@ _ when IsDataShareAtomic(opcode) => [ Gen5Operand.Vector(vectorDestination + 1), Gen5Operand.Vector(vectorDestination + 2), ], - "DsReadB128" or "DsRead2B64" => [ + "DsReadB128" or "DsRead2B64" or "DsRead2St64B64" => [ Gen5Operand.Vector(vectorDestination), Gen5Operand.Vector(vectorDestination + 1), Gen5Operand.Vector(vectorDestination + 2), @@ -2951,7 +2962,7 @@ _ when IsDataShareAtomic(opcode) && "BufferStoreDwordx2" => 2u, "BufferStoreDwordx3" => 3u, "BufferStoreDwordx4" => 4u, - "BufferAtomicCmpswap" or "BufferAtomicSwapX2" or "BufferAtomicOrX2" => 2u, + "BufferAtomicCmpswap" or "BufferAtomicSwapX2" or "BufferAtomicAndX2" or "BufferAtomicOrX2" => 2u, _ when opcode.StartsWith("BufferAtomic", StringComparison.Ordinal) => 1u, _ => 0u, }; diff --git a/src/SharpEmu.ShaderCompiler/Gen5TessellationData.cs b/src/SharpEmu.ShaderCompiler/Gen5TessellationData.cs index 39c145df2..2a998f40b 100644 --- a/src/SharpEmu.ShaderCompiler/Gen5TessellationData.cs +++ b/src/SharpEmu.ShaderCompiler/Gen5TessellationData.cs @@ -7,7 +7,7 @@ namespace SharpEmu.ShaderCompiler; public static class Gen5TessellationData { public const uint DwordCount = 22; - public const uint FirstPatch = 0, PatchCount = 1, VertexOffset = 2, InstanceId = 3; + public const uint FirstPatch = 0, PatchCount = 1, VertexOffset = 2; public const uint IndexAddress = 4, IndexSize = 6; public const uint FactorAddress = 7, FactorBytes = 9; public const uint OffchipOffset = 10, FactorOffset = 11; diff --git a/src/SharpEmu.ShaderCompiler/Resources/BindingLayout.cs b/src/SharpEmu.ShaderCompiler/Resources/BindingLayout.cs index faf23f27e..0b92bea1d 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/BindingLayout.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/BindingLayout.cs @@ -40,6 +40,11 @@ public static class PushData public static bool CanFit(uint start, uint size) => size != 0 && start <= DwordCount && size <= DwordCount - start; public static uint StartFor(uint cursor, uint size) => CanFit(cursor, size) ? cursor : NoStart; + + // The start of data placed at the top of the range, when it fits above cursor: it depends on the data's size alone, so + // the stage that takes it (a graphics pipeline's vertex or mesh stage, after its pixel stage) has one place whichever + // stage comes before it. NoStart when it does not fit, exactly where StartFor finds no room. + public static uint TopFor(uint cursor, uint size) => CanFit(cursor, size) ? DwordCount - size : NoStart; } public sealed record DescriptorBinding(DescriptorBindingKind Kind, IReadOnlyList Resources); @@ -355,6 +360,10 @@ public sealed class BindingLayout : IEquatable public uint PushDataStartDword { get; init; } = PushData.NoStart; public uint AllocationCursor { get; init; } + + // The shader data takes the top of the push range when it fits above the cursor (PushData.TopFor), not the cursor's + // place; the allocation cursor is then the start it took, or the end of the range when it did not fit. + public bool PushDataAtTop { get; init; } public uint ShaderBaseDword { get; init; } = NoShaderBase; public uint MemoryOffsetDword { get; init; } public uint MemoryOffsetCount { get; init; } @@ -371,7 +380,15 @@ public sealed class BindingLayout : IEquatable // The addresses of the module's callees (Gen5ShaderCallLinker.CallTargets), two dwords each. public uint CallTargetCount { get; init; } - // The program reads call records through descriptor set 1 (see BindlessHeap). + + // The V# stride of every buffer binding, two to a dword (16 bits each), when some access indexes its buffer + // (ShaderResourceInfo.UsesIndexedBuffers); otherwise none. + public uint BufferStrideCount { get; init; } + + // The store channel map (RuntimeImageSwizzle.StoreChannelMap) of every written image that takes its destination select + // from shader data (ShaderResourceInfo.UsesRuntimeImageSwizzles), in image order, two to a dword (16 bits each). + public uint StorageImageSwizzleCount { get; init; } + // The program reads bindless heap records through descriptor set 1 (see BindlessHeap). public bool UsesBindlessHeap { get; init; } public IReadOnlyList UserDataRegisters { get; init; } = []; public IReadOnlyList Descriptors { get; init; } = []; @@ -399,12 +416,23 @@ public sealed class BindingLayout : IEquatable public uint CallTargetsDword => CallArgumentsDword + CallArgumentCount * 2; - public uint ShaderDataDwordCount => CallTargetsDword + CallTargetCount * 2; + public uint BufferStridesDword => CallTargetsDword + CallTargetCount * 2; + + public uint StorageImageSwizzlesDword => BufferStridesDword + (BufferStrideCount + 1) / 2; + + public uint ShaderDataDwordCount => StorageImageSwizzlesDword + (StorageImageSwizzleCount + 1) / 2; public bool UsesPushData => PushDataStartDword != PushData.NoStart; public bool UsesShaderBase => ShaderBaseDword != NoShaderBase; + // The push data start this layout takes after cursor: a permutation serves a stage whose cursor gives its own start. + // Tessellation runtime data never takes push data. + public uint PushStartFor(uint cursor) => + UsesTessellationData ? PushData.NoStart + : PushDataAtTop ? PushData.TopFor(cursor, ShaderDataDwordCount) + : PushData.StartFor(cursor, ShaderDataDwordCount); + public void AdvancePushData(ref uint cursor) { if (UsesPushData) @@ -646,6 +674,7 @@ public static BindingLayout Allocate( bool usesMeshDrawParameters = false, uint callArgumentCount = 0, uint callTargetCount = 0, + bool pushDataAtTop = false, bool tableBlock = false, bool usesBufferLengths = false, bool usesTessellationData = false) @@ -657,10 +686,15 @@ public static BindingLayout Allocate( var memoryOffsetCount = usesTableBlock ? 0u : (uint)info.Buffers.Count; var mipStatisticsCount = info.Images.Any(static image => image.MipStatistics) ? (uint)info.Images.Count : 0u; usesBufferLengths &= memoryOffsetCount != 0 && !usesTableBlock; + var bufferStrideCount = info.UsesIndexedBuffers ? (uint)info.Buffers.Count : 0u; + var storageImageSwizzleCount = info.UsesRuntimeImageSwizzles ? RuntimeImageSwizzle.SlotCount(info.Images) : 0u; var shaderDataDwords = memoryOffsetDword + (usesTableBlock ? 2u : (memoryOffsetCount + 3) / 4) + (usesBufferLengths ? memoryOffsetCount : 0) + (usesDispatchThreadLimits ? 3u : 0u) + mipStatisticsCount + (usesMeshDrawParameters ? 6u : 0u) + - (usesTessellationData ? Gen5TessellationData.DwordCount : 0u) + callArgumentCount * 2 + callTargetCount * 2; - var pushStart = usesTessellationData ? PushData.NoStart : PushData.StartFor(pushDataStartDword, shaderDataDwords); + (usesTessellationData ? Gen5TessellationData.DwordCount : 0u) + callArgumentCount * 2 + callTargetCount * 2 + + (bufferStrideCount + 1) / 2 + (storageImageSwizzleCount + 1) / 2; + var pushStart = usesTessellationData ? PushData.NoStart + : pushDataAtTop ? PushData.TopFor(pushDataStartDword, shaderDataDwords) + : PushData.StartFor(pushDataStartDword, shaderDataDwords); var descriptors = new List(); if (info.Buffers.Count != 0 && !usesTableBlock) { @@ -753,7 +787,8 @@ public static BindingLayout Allocate( return new BindingLayout { PushDataStartDword = pushStart, - AllocationCursor = pushDataStartDword, + AllocationCursor = !pushDataAtTop ? pushDataStartDword : pushStart != PushData.NoStart ? pushStart : PushData.DwordCount, + PushDataAtTop = pushDataAtTop, ShaderBaseDword = shaderBaseDword, MemoryOffsetDword = memoryOffsetDword, MemoryOffsetCount = memoryOffsetCount, @@ -767,6 +802,8 @@ public static BindingLayout Allocate( UsesMeshDrawParameters = usesMeshDrawParameters, CallArgumentCount = callArgumentCount, CallTargetCount = callTargetCount, + BufferStrideCount = bufferStrideCount, + StorageImageSwizzleCount = storageImageSwizzleCount, UsesBindlessHeap = info.UsesBindlessHeap, UserDataRegisters = userDataRegisters, Descriptors = descriptors, @@ -777,6 +814,7 @@ public static BindingLayout Allocate( public bool Equals(BindingLayout? other) => other is not null && PushDataStartDword == other.PushDataStartDword && + PushDataAtTop == other.PushDataAtTop && ShaderBaseDword == other.ShaderBaseDword && MemoryOffsetDword == other.MemoryOffsetDword && MemoryOffsetCount == other.MemoryOffsetCount && @@ -790,6 +828,8 @@ other is not null && UsesMeshDrawParameters == other.UsesMeshDrawParameters && CallArgumentCount == other.CallArgumentCount && CallTargetCount == other.CallTargetCount && + BufferStrideCount == other.BufferStrideCount && + StorageImageSwizzleCount == other.StorageImageSwizzleCount && UsesBindlessHeap == other.UsesBindlessHeap && UserDataRegisters.SequenceEqual(other.UserDataRegisters) && Descriptors.Count == other.Descriptors.Count && @@ -828,7 +868,8 @@ public static void Validate( var expected = BindingLayout.Allocate(info, userDataRegisters, usesGlobalDataShare, usesFlattenedTable, usesShaderBase, layout.AllocationCursor, layout.UsesDispatchThreadLimits, layout.UsesMeshDrawParameters, layout.CallArgumentCount, layout.CallTargetCount, - tableBlock: layout.UsesTableBlock, usesBufferLengths: layout.UsesBufferLengths, usesTessellationData: layout.UsesTessellationData); + layout.PushDataAtTop, tableBlock: layout.UsesTableBlock, usesBufferLengths: layout.UsesBufferLengths, + usesTessellationData: layout.UsesTessellationData); if (!expected.Equals(layout)) { throw new ResourcePlanException( @@ -838,7 +879,7 @@ public static void Validate( } private static string Describe(BindingLayout layout) => - $"push={layout.PushDataStartDword} base={layout.ShaderBaseDword} offsets={layout.MemoryOffsetDword}+{layout.MemoryOffsetCount} table={layout.UsesTableBlock} " + + $"push={layout.PushDataStartDword}{(layout.PushDataAtTop ? "(top)" : "")} base={layout.ShaderBaseDword} offsets={layout.MemoryOffsetDword}+{layout.MemoryOffsetCount} table={layout.UsesTableBlock} " + $"user=[{string.Join(",", layout.UserDataRegisters)}] " + string.Join(" ", layout.Descriptors.Select(binding => $"{binding.Kind}:{string.Join(",", binding.Resources)}")); } diff --git a/src/SharpEmu.ShaderCompiler/Resources/BindlessHeap.cs b/src/SharpEmu.ShaderCompiler/Resources/BindlessHeap.cs index 39eb7efe1..cd50ffcf1 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/BindlessHeap.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/BindlessHeap.cs @@ -3,16 +3,22 @@ namespace SharpEmu.ShaderCompiler.Resources; -// Descriptor set 1: the images and samplers of call records (CallRecordSelector), which a program linked with run-time call -// records reads at elements the host assigns. It holds one array per supported image class and two sampler arrays (plain -// and depth compare). +// The descriptor heaps a bindless shader indexes at run time: a texture heap of 32-byte T# records and a sampler heap of +// 16-byte S# records, each read at a record only the shader knows. Descriptor set 1 holds one array per supported image +// class and two sampler arrays (plain and depth compare), indexed by the record number, and a bitset per array in which +// the shader marks every record it reads, so that the host can give that record a view. public static class BindlessHeap { public const uint DescriptorSet = 1; - public const uint Capacity = 16384; - - // The host gives each distinct call record descriptor an element of its array, by the descriptor's words. - // CallRecordNullIndex stays null. + public const uint Capacity = 65536; + public const uint ImageRecordBytes = 32; + public const uint SamplerRecordBytes = 16; + public const uint FeedbackBinding = 63; + public const uint FeedbackWordsPerArray = Capacity / 32; + + // Set-1 elements from CallRecordFirstIndex on hold the views and samplers of call records (CallRecordSelector), which the + // host assigns by their descriptor words; guest heap records use the elements below. CallRecordNullIndex stays null. + public const uint CallRecordFirstIndex = 49152; public const uint CallRecordNullIndex = Capacity - 1; // The call records buffer of a dispatch (DescriptorBindingKind.CallRecords): word 0 holds the row count N, then N rows of @@ -26,18 +32,27 @@ public static class BindlessHeap // The buffer holds at least this many words, so the lookup of an empty table reads inside it. public const uint CallRecordMinimumWords = 8; - // The image classes set 1 declares, in binding order; the sampler arrays follow them. A record's image is sampled as - // float, since its format is unknown until the shader finds its record. + // The image classes set 1 declares, in binding order; the sampler arrays follow them. A heap image is sampled as + // float, since its format is unknown until the shader picks its record. public static readonly HeapImageClass[] ImageClasses = BuildImageClasses(); public static readonly DescriptorBindingKind[] ImageKinds = ImageClasses.Select(static heapClass => heapClass.Kind).ToArray(); + // A 3D read of a record that holds a 2D texture reads it through the float 2D-array class: the hardware takes the + // third coordinate as the layer. + public static readonly int VolumeSlot = Array.FindIndex(ImageClasses, static heapClass => heapClass.Dimension == ImageDimension.Dim3D); + + public static readonly int VolumeLayerSlot = Array.FindIndex(ImageClasses, static heapClass => + heapClass is { Dimension: ImageDimension.Dim2DArray, Cube: false, Compare: false }); + public static int SamplerSlot => ImageKinds.Length; public static int CompareSamplerSlot => ImageKinds.Length + 1; public static int ArrayCount => ImageKinds.Length + 2; + public static uint FeedbackWords => (uint)ArrayCount * FeedbackWordsPerArray; + // The binding of an image class in set 1, or -1 when set 1 has no array for it. public static int ImageSlot(DescriptorBindingKind kind) => Array.IndexOf(ImageKinds, kind); @@ -70,6 +85,17 @@ static HeapImageClass Class(ImageDimension dimension, bool cube = false, bool co // One image array of set 1: its binding kind and the view it holds. public readonly record struct HeapImageClass(DescriptorBindingKind Kind, ImageDimension Dimension, bool Cube, bool Compare); +// A descriptor the shader reads from a bindless heap at a record it picks at run time: the heap V# source, the scalar +// read of the record's first dword (whose dynamic offset the shader keeps), that read's immediate offset and the record +// size. A cube image is sampled through a cube view. +public sealed record HeapRecordSelector(uint HeapSource, int KeyMemoryIndex, uint Immediate, uint RecordBytes) +{ + public bool Cube { get; init; } +} + +// One image access whose image or sampler is a heap record. +public sealed record HeapRecordAccess(int MemoryIndex, uint Source, bool Sampler); + // An image or sampler a linked callee reads through its record's run-time argument (ShaderCallEntryControl.RuntimeArgument), // Immediate bytes past it. Every record of the callee has its own; the host resolves them into set 1 for the records of each // dispatch. A cube image is sampled through a cube view. @@ -104,3 +130,16 @@ public sealed record CallRecordBufferWords(ScalarValue[] Words, bool Written); // its buffers, which the host makes resident through the device-address table, and the bytes past the argument the callee // reads itself. public sealed record CallRecordCallee(CallRecordField[] Fields, CallRecordBuffer[] Buffers, uint ArgumentBytes); + +// A heap V# the plan evaluates for every draw, and whether it holds samplers. +public sealed record HeapRecordSource(uint Source, bool Sampler); + +// One heap V# a draw's bindless accesses read: its base address, record count and stride. +public readonly record struct BindlessHeapDescriptor(bool Sampler, ulong Base, uint Records, uint Stride) +{ + public static BindlessHeapDescriptor FromWords(bool sampler, ReadOnlySpan words) => + new(sampler, words[0] | ((ulong)(words[1] & 0xFFFF) << 32), words[2], (words[1] >> 16) & 0x3FFF); +} + +// How the shader reads one heap record: the key read whose dynamic offset it kept, the immediate offset and the record size. +public readonly record struct HeapRecordUse(int KeyMemoryIndex, uint Immediate, uint RecordBytes); diff --git a/src/SharpEmu.ShaderCompiler/Resources/CallRecordPlanner.cs b/src/SharpEmu.ShaderCompiler/Resources/CallRecordPlanner.cs index f34292d75..ec15f159c 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/CallRecordPlanner.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/CallRecordPlanner.cs @@ -159,6 +159,20 @@ public static IReadOnlyList Plan(ShaderResourcePlan plan) // record's argument is not the callee's. public static bool AddRecordRanges(ShaderResourcePlan plan, int callee, ulong argument, ResourceRuntimeInputs inputs, uint userDataBase, List ranges) + { + if ((uint)callee >= (uint)plan.CallRecordCallees.Count || plan.CallRecordCallees[callee].BufferWords.Length == 0) + { + return true; + } + + return CompiledDeviceAddressRanges.Configured == CompiledDeviceAddressRanges.Mode.Off + ? AddRecordRangesInterpreted(plan, callee, argument, inputs, userDataBase, ranges) + : CompiledDeviceAddressRanges.ServeRecord(plan, callee, argument, inputs, userDataBase, ranges); + } + + // An evaluator per record; the reference of the compiled records. + internal static bool AddRecordRangesInterpreted(ShaderResourcePlan plan, int callee, ulong argument, ResourceRuntimeInputs inputs, + uint userDataBase, List ranges) { const ulong MaxRecordBufferBytes = 1UL << 32; if ((uint)callee >= (uint)plan.CallRecordCallees.Count || plan.CallRecordCallees[callee].BufferWords.Length == 0) @@ -166,7 +180,8 @@ public static bool AddRecordRanges(ShaderResourcePlan plan, int callee, ulong ar return true; } - var evaluator = new RuntimeValueEvaluator(plan, inputs.WithCallArguments(userDataBase, [argument])); + using var scratch = RuntimeEvaluationScratch.Rent(); + var evaluator = new RuntimeValueEvaluator(scratch, plan, inputs.WithCallArguments(userDataBase, [argument])); Span words = stackalloc uint[4]; foreach (var buffer in plan.CallRecordCallees[callee].BufferWords) { @@ -189,9 +204,16 @@ public static bool AddRecordRanges(ShaderResourcePlan plan, int callee, ulong ar continue; } + // Words that describe no buffer (constants in its place, on a record whose callee does not take the path that reads + // it): a read-only buffer is not made resident, and a written one leaves the record out, so no store lands through it. if (size > MaxRecordBufferBytes || address + size > 1UL << 48) { - return false; + if (buffer.Written) + { + return false; + } + + continue; } ranges.Add(new DeviceAddressRange(uint.MaxValue, address, size, true, buffer.Written)); diff --git a/src/SharpEmu.ShaderCompiler/Resources/CompiledBranchTransaction.cs b/src/SharpEmu.ShaderCompiler/Resources/CompiledBranchTransaction.cs new file mode 100644 index 000000000..afd7527cb --- /dev/null +++ b/src/SharpEmu.ShaderCompiler/Resources/CompiledBranchTransaction.cs @@ -0,0 +1,407 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace SharpEmu.ShaderCompiler.Resources; + +// Values one call already evaluated before a compiled branch transaction runs: the branch selection's clean evaluator. +internal interface IEvaluatedValues +{ + bool TryGetEvaluated(ScalarValue value, out ulong result); +} + +// The compiled form of a plan whose uniform branches select its descriptor sources (ResourceBranches), which +// CompiledResourceTransaction refuses. RuntimeValueEvaluator.EvaluateActiveSources still selects the sources, fresh on +// every call; this evaluates what the fallback evaluates after that selection, in its order and with its memo: the words +// of each active source in MaterializationSources order, then every table read. A value is evaluated in the first active +// region (a source or the table) that needs it, in the order the fallback's recursion meets it, and never again: an +// inactive source reads nothing, a value it shares with a later region is read there (inside the table phase when that +// region is the table), and a clean value the selection already evaluated is taken from the selection. +internal sealed class CompiledBranchTransaction +{ + private static readonly MethodInfo EvaluateOperation = typeof(ScalarOperationSemantics) + .GetMethod(nameof(ScalarOperationSemantics.TryEvaluateFixed), BindingFlags.NonPublic | BindingFlags.Static)!; + private static readonly MethodInfo ReadWord = typeof(CompiledResourceTransaction) + .GetMethod(nameof(CompiledResourceTransaction.ReadWord), BindingFlags.NonPublic | BindingFlags.Static)!; + private static readonly MethodInfo ReadUserData = typeof(CompiledResourceTransaction) + .GetMethod(nameof(CompiledResourceTransaction.ReadUserData), BindingFlags.NonPublic | BindingFlags.Static)!; + private static readonly MethodInfo SetTablePhase = typeof(CompiledResourceTransaction) + .GetMethod(nameof(CompiledResourceTransaction.SetTablePhase), BindingFlags.NonPublic | BindingFlags.Static)!; + private static readonly MethodInfo TryGetEvaluated = typeof(IEvaluatedValues) + .GetMethod(nameof(IEvaluatedValues.TryGetEvaluated))!; + + private readonly Func, uint[], bool> _evaluate; + private readonly int[] _descriptorSizes; + private readonly int _tableWords; + private readonly int _sourceCount; + private readonly bool _requiresCleanReader; + + private CompiledBranchTransaction(Func, uint[], bool> evaluate, + int[] descriptorSizes, int tableWords, int sourceCount, bool requiresCleanReader) + { + _evaluate = evaluate; + _descriptorSizes = descriptorSizes; + _tableWords = tableWords; + _sourceCount = sourceCount; + _requiresCleanReader = requiresCleanReader; + } + + // As the fallback after its selection: on failure neither output changes and both stay empty. + internal bool Evaluate(ResourceRuntimeInputs inputs, int additionalTableWords, bool[] active, IEvaluatedValues selection, + out List descriptors, out uint[] table) + { + using var profile = ResourceMaterializationProfile.Measure(ResourceMaterializationProfile.Phase.CompiledBranchEvaluation); + descriptors = []; + table = []; + if (active.Length != _sourceCount || (_requiresCleanReader && inputs.ReadCleanMemory is null)) return false; + var nextDescriptors = new List(_descriptorSizes.Length); + foreach (var size in _descriptorSizes) + nextDescriptors.Add(new DescriptorWords(new uint[size])); + var nextTable = new uint[checked(_tableWords + additionalTableWords)]; + if (!_evaluate(inputs, active, selection, nextDescriptors, nextTable)) return false; + descriptors = nextDescriptors; + table = nextTable; + return true; + } + + internal static CompiledBranchTransaction? Build(ShaderResourcePlan plan) + { + if (plan.ResourceBranches.Count == 0 || !RuntimeFeature.IsDynamicCodeSupported || + Environment.GetEnvironmentVariable("SHARPEMU_SRT_NATIVE") == "0") return null; + var builder = new Builder(plan); + try + { + return builder.Build(); + } + catch (NotSupportedException) + { + ResourceMaterializationCache.RecordTransactionBuild(plan, false, "branches:" + builder.Reason); + return null; + } + } + + // One value as one evaluator context reads it: the general reader, or the clean one (a clean table slot and + // everything below it). The fallback memoizes each pair once per call; the transaction gives each a local. + private sealed class Pair(ScalarValue value, bool clean) + { + public readonly ScalarValue Value = value; + public readonly bool Clean = clean; + public ParameterExpression? Local; + public ParameterExpression? Flag; + public int FirstRegion = -1; + public int LastRegion = -1; + public int Regions; + public bool Selection; + } + + // A region the fallback evaluates in order: one MaterializationSources entry (Position) or the table. + private readonly record struct Region(int Position, uint Source, bool Conditional, bool Table); + + private sealed class Builder(ShaderResourcePlan plan) + { + private const int MaximumDepth = 64; + private const int MaximumLocals = 4096; + private readonly Dictionary<(ScalarValue, bool), Pair> _pairs = new(); + private readonly List _locals = []; + private readonly ParameterExpression _input = Expression.Parameter(typeof(ResourceRuntimeInputs), "inputs"); + private readonly ParameterExpression _active = Expression.Parameter(typeof(bool[]), "active"); + private readonly ParameterExpression _selection = Expression.Parameter(typeof(IEvaluatedValues), "selection"); + private readonly ParameterExpression _descriptors = Expression.Parameter(typeof(List), "descriptors"); + private readonly ParameterExpression _table = Expression.Parameter(typeof(uint[]), "table"); + private readonly LabelTarget _done = Expression.Label(typeof(bool)); + + public string Reason { get; private set; } = "unsupported_shape_or_limit"; + + public CompiledBranchTransaction Build() + { + var conditional = new HashSet(); + foreach (var block in plan.ResourceBranches) + foreach (var source in block.Sources) conditional.Add(source); + var regions = new List(); + for (var position = 0; position < plan.MaterializationSources.Count; position++) + { + var source = plan.MaterializationSources[position]; + // The fallback fails every call on such a source; it keeps serving them. + if (source >= (uint)plan.DescriptorSources.Count) throw new NotSupportedException(); + regions.Add(new Region(position, source, conditional.Contains(source), false)); + } + + foreach (var read in plan.TableReads) + if (read.FlatOffset >= (uint)plan.TableReads.Count) throw new NotSupportedException(); + regions.Add(new Region(-1, 0, false, true)); + + // Each region's values in the order the fallback's recursion completes them: operands first, then the value. + var orders = new List[regions.Count]; + for (var region = 0; region < regions.Count; region++) + { + var order = orders[region] = []; + var seen = new HashSet(); + var visiting = new HashSet<(ScalarValue, bool)>(); + if (regions[region].Table) + { + foreach (var read in plan.TableReads) + Visit(read.Value, IsCleanSlot((int)read.FlatOffset), region, seen, order, visiting); + } + else + { + foreach (var word in plan.DescriptorSources[(int)regions[region].Source].Dwords) + Visit(word, false, region, seen, order, visiting); + } + } + + // The clean values the selection may already hold: everything its conditions evaluate. + var selection = new HashSet<(ScalarValue, bool)>(); + foreach (var block in plan.ResourceBranches) + if (block.Condition is { } condition) CollectSelection(condition, selection); + foreach (var pair in _pairs.Values) + pair.Selection = pair.Clean && selection.Contains((pair.Value, true)); + + var body = new List(); + // Evaluated by an unconditional region: every later region already has it. + var settled = new HashSet(); + for (var region = 0; region < regions.Count; region++) + { + var info = regions[region]; + var statements = new List(); + foreach (var pair in orders[region]) + if (!settled.Contains(pair)) EmitSite(pair, regions, statements); + if (info.Table) + { + foreach (var read in plan.TableReads) + statements.Add(Expression.Assign(Expression.ArrayAccess(_table, Expression.Constant((int)read.FlatOffset)), + Word(read.Value, IsCleanSlot((int)read.FlatOffset)))); + statements.Add(Expression.Empty()); + body.Add(Expression.Call(SetTablePhase, _input, Expression.Constant(true))); + body.Add(Expression.TryFinally(Expression.Block(statements), + Expression.Call(SetTablePhase, _input, Expression.Constant(false)))); + continue; + } + + var words = Expression.Property(Expression.Property(_descriptors, "Item", Expression.Constant(info.Position)), + nameof(DescriptorWords.Dwords)); + var dwords = plan.DescriptorSources[(int)info.Source].Dwords; + for (var index = 0; index < dwords.Length; index++) + statements.Add(Expression.Assign(Expression.ArrayAccess(words, Expression.Constant(index)), Word(dwords[index], false))); + if (info.Conditional) + { + statements.Add(Expression.Empty()); + body.Add(Expression.IfThen(Expression.ArrayIndex(_active, Expression.Constant((int)info.Source)), + Expression.Block(statements))); + } + else + { + body.AddRange(statements); + foreach (var pair in orders[region]) settled.Add(pair); + } + } + + body.Add(Expression.Label(_done, Expression.Constant(true))); + var lambda = Expression.Lambda, uint[], bool>>( + Expression.Block(_locals, body), _input, _active, _selection, _descriptors, _table); + return new CompiledBranchTransaction(lambda.Compile(), + plan.MaterializationSources.Select(index => plan.DescriptorSources[(int)index].Dwords.Length).ToArray(), + plan.TableReads.Count, plan.DescriptorSources.Count, plan.CleanFlatSlots.Any(slot => slot != 0)); + } + + private bool IsCleanSlot(int slot) => slot < plan.CleanFlatSlots.Count && plan.CleanFlatSlots[slot] != 0; + + private void Visit(ScalarValue value, bool clean, int region, HashSet seen, List order, + HashSet<(ScalarValue, bool)> visiting) + { + if (value.IsConstant) return; + if (!_pairs.TryGetValue((value, clean), out var pair)) + { + if (_pairs.Count >= MaximumLocals) throw new NotSupportedException(); + _pairs.Add((value, clean), pair = new Pair(value, clean)); + } + + if (seen.Contains(pair)) return; + if (!visiting.Add((value, clean)) || visiting.Count > MaximumDepth) throw new NotSupportedException(); + if (!TryOperands(value, clean, out var operands, out var reason)) + { + Reason = reason; + throw new NotSupportedException(); + } + + foreach (var (operand, operandClean) in operands) + Visit(operand, operandClean, region, seen, order, visiting); + visiting.Remove((value, clean)); + seen.Add(pair); + order.Add(pair); + if (pair.LastRegion == region) return; + if (pair.FirstRegion < 0) pair.FirstRegion = region; + pair.LastRegion = region; + pair.Regions++; + } + + // The values the selection's clean evaluator meets below a condition, as far as the transaction can name them. + private void CollectSelection(ScalarValue condition, HashSet<(ScalarValue, bool)> selection) + { + var pending = new Stack(); + pending.Push(condition); + while (pending.TryPop(out var value)) + { + if (value.IsConstant || !selection.Add((value, true)) || !TryOperands(value, true, out var operands, out _)) continue; + foreach (var (operand, _) in operands) pending.Push(operand); + } + } + + // The operands a value's evaluation evaluates, in the order RuntimeValueEvaluator and CompiledResourceTransaction + // evaluate them, with the reader each uses. + private bool TryOperands(ScalarValue value, bool clean, out (ScalarValue, bool)[] operands, out string reason) + { + operands = []; + reason = "unsupported_shape_or_limit"; + switch (value.Kind) + { + case ScalarValueKind.UserData: + return value.UserDataRegister >= plan.UserDataBase; + case ScalarValueKind.ShaderBase: + case ScalarValueKind.MemoryAperture: + return true; + case ScalarValueKind.ResourceTableWord: + if (value.Payload >= (ulong)plan.TableReads.Count) return false; + operands = [(plan.TableReads[(int)value.Payload].Value, clean || IsCleanSlot((int)value.Payload))]; + return true; + case ScalarValueKind.ScalarAddressWord: + case ScalarValueKind.ScalarBufferWord: + { + if (value.Operands.Length < 2 || (uint)value.MemoryIndex >= (uint)plan.Memory.Count) return false; + var handle = value.Operands[0]; + if (value.Kind == ScalarValueKind.ScalarAddressWord) + { + if (handle.Operands.Length < 2) return false; + operands = [(handle.Operands[0], clean), (handle.Operands[1], clean), (value.Operands[1], clean)]; + return true; + } + + if (handle.Operands.Length != 4) return false; + operands = [(handle.Operands[0], clean), (handle.Operands[1], clean), (value.Operands[1], clean), + (handle.Operands[2], clean), (handle.Operands[3], clean)]; + return true; + } + case ScalarValueKind.Phi: + if (plan.Graph.ResolveInvariantPhi(value) is not { } invariant) return false; + operands = [(invariant, clean)]; + return true; + case ScalarValueKind.Select: + if (value.Operands.Length != 3) return false; + operands = [(value.Operands[0], clean), (value.Operands[1], clean), (value.Operands[2], clean)]; + return true; + case ScalarValueKind.Operation: + if (!RuntimeValueValidator.IsUniformOperation(value.Operation) || value.Operands.Length > 4) + { + reason = $"operation:{value.Operation}"; + return false; + } + + operands = value.Operands.Select(operand => (operand, clean)).ToArray(); + return true; + default: + reason = $"node:{value.Kind}"; + return false; + } + } + + private ParameterExpression Local(Type type) + { + var local = Expression.Variable(type); + _locals.Add(local); + if (_locals.Count > MaximumLocals) throw new NotSupportedException(); + return local; + } + + private Expression Operand(ScalarValue value, bool clean) => + value.IsConstant ? Expression.Constant(value.Payload) : _pairs[(value, clean)].Local!; + + private Expression Word(ScalarValue value, bool clean) => + value.IsConstant ? Expression.Constant(unchecked((uint)value.Payload)) : Expression.Convert(Operand(value, clean), typeof(uint)); + + private Expression Require(Expression condition) => + Expression.IfThen(Expression.Not(condition), Expression.Return(_done, Expression.Constant(false))); + + // One place a region evaluates a value. A value several regions need, first needed by a conditional one, is + // evaluated by the first of them that runs; a clean value the selection holds is taken from it instead. + private void EmitSite(Pair pair, List regions, List statements) + { + pair.Local ??= Local(typeof(ulong)); + var compute = new List(); + Compute(pair, compute); + compute.Add(Expression.Empty()); + Expression site = Expression.Block(compute); + if (pair.Selection) + site = Expression.IfThen(Expression.Not(Expression.Call(_selection, TryGetEvaluated, Expression.Constant(pair.Value), + pair.Local)), site); + if (pair.Regions >= 2 && regions[pair.FirstRegion].Conditional) + { + pair.Flag ??= Local(typeof(bool)); + site = Expression.IfThen(Expression.Not(pair.Flag), Expression.Block(site, Expression.Assign(pair.Flag, Expression.Constant(true)))); + } + + statements.Add(site); + } + + // As CompiledResourceTransaction compiles each node kind; the operands are already in their locals. + private void Compute(Pair pair, List compute) + { + var value = pair.Value; + var clean = pair.Clean; + var local = pair.Local!; + switch (value.Kind) + { + case ScalarValueKind.UserData: + compute.Add(Require(Expression.Call(ReadUserData, _input, + Expression.Constant((ulong)(value.UserDataRegister - plan.UserDataBase)), local))); + break; + case ScalarValueKind.ShaderBase: + compute.Add(Expression.Assign(local, Expression.Property(_input, nameof(ResourceRuntimeInputs.ShaderBase)))); + break; + case ScalarValueKind.ResourceTableWord: + { + var slot = (int)value.Payload; + compute.Add(Expression.Assign(local, Operand(plan.TableReads[slot].Value, clean || IsCleanSlot(slot)))); + break; + } + case ScalarValueKind.ScalarAddressWord: + case ScalarValueKind.ScalarBufferWord: + { + var handle = value.Operands[0]; + var buffer = value.Kind == ScalarValueKind.ScalarBufferWord; + compute.Add(Require(Expression.Call(ReadWord, _input, Expression.Constant(clean), Expression.Constant(value.Kind), + Operand(handle.Operands[0], clean), Operand(handle.Operands[1], clean), Operand(value.Operands[1], clean), + buffer ? Operand(handle.Operands[2], clean) : Expression.Constant(0UL), + Expression.Constant((long)(int)plan.Memory[value.MemoryIndex].Offset), + Expression.Constant(RuntimeValueEvaluator.IsAbsoluteAddress(value.Kind, handle)), local, + Expression.Constant(plan), Expression.Constant(value)))); + break; + } + case ScalarValueKind.MemoryAperture: + compute.Add(Expression.Assign(local, Expression.Constant(Gen5InlineConstants.DecodeAperture64((uint)value.Payload) >> 32))); + break; + case ScalarValueKind.Phi: + compute.Add(Expression.Assign(local, Operand(plan.Graph.ResolveInvariantPhi(value)!, clean))); + break; + case ScalarValueKind.Select: + // Both arms are evaluated, as the scalar evaluator does. + compute.Add(Expression.Assign(local, Expression.Condition( + Expression.NotEqual(Operand(value.Operands[0], clean), Expression.Constant(0UL)), + Operand(value.Operands[1], clean), Operand(value.Operands[2], clean)))); + break; + case ScalarValueKind.Operation: + { + var operands = new Expression[4]; + for (var index = 0; index < operands.Length; index++) + operands[index] = index < value.Operands.Length ? Operand(value.Operands[index], clean) : Expression.Constant(0UL); + compute.Add(Require(Expression.Call(EvaluateOperation, Expression.Constant(value.Operation), + operands[0], operands[1], operands[2], operands[3], local))); + break; + } + default: + throw new NotSupportedException(); + } + } + } +} diff --git a/src/SharpEmu.ShaderCompiler/Resources/CompiledDeviceAddressRanges.cs b/src/SharpEmu.ShaderCompiler/Resources/CompiledDeviceAddressRanges.cs new file mode 100644 index 000000000..f7987ced8 --- /dev/null +++ b/src/SharpEmu.ShaderCompiler/Resources/CompiledDeviceAddressRanges.cs @@ -0,0 +1,980 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace SharpEmu.ShaderCompiler.Resources; + +// A plan's device-address ranges evaluated by code compiled once per plan on the SRT compiler thread. +// On by default; SHARPEMU_COMPILED_RANGES=0, or any value but 1, turns it off. +// DeviceAddressRangePlanner.EvaluateInterpreted is the reference, one evaluator for every range and then the function +// V#s, and the compiled code keeps its rules: +// - each node is evaluated at most once per call, its operands in the evaluator's order, and the first failure ends +// the value (a failed base low skips its base high); +// - only a successful node keeps its value, so a node that failed is evaluated (and read) again when a later range +// or V# needs it; +// - a phi is its invariant value and a table word its table read, in the same evaluator; +// - a first-lane value runs its own evaluator, empty each time, which takes a select on the value's active mask as the +// select's first value. +// The range assembly and the function-buffer tail are the reference's code with only the value evaluation replaced. +// The function-buffer accesses are listed once per plan, and a call allocates nothing but its result array. +// A plan with a cycle, a malformed node or more than MaxBlocks nodes stays on the interpreter. +// CallRecordPlanner.AddRecordRanges evaluates each callee's computed V#s (CallRecordBufferWords) the same way, compiled +// once per callee, with the record helper's own rules: one memo per record, shared by its buffers; the user data a record +// reads is what WithCallArguments builds (the draw's, zeros up to the argument registers, then the argument) without +// building it. A record's reads of one handle at consecutive constant offsets take one read of the resident reader, fresh +// each record, as RawReadPrefetch's runs do; a refused read, or no resident reader, leaves them to word reads. +internal sealed class CompiledDeviceAddressRanges +{ + internal enum Mode : byte { Off, On } + + internal static Mode Parse(string? value) => value switch + { + null or "" or "1" => Mode.On, + _ => Mode.Off, + }; + + // Tests change it; plans compile their ranges only while it is on. + internal static Mode Configured { get; set; } = Parse(Environment.GetEnvironmentVariable("SHARPEMU_COMPILED_RANGES")); + + private const int MaxBlocks = 2048; + // A large plan gets bounded methods, not an unbounded version of the small method. Slot identity and State stay + // shared across methods, preserving successful-read memoization and first-lane evaluator contexts across roots. + // SHARPEMU_COMPILED_LARGE_RANGES=0 leaves large plans on the interpreter. + internal static readonly bool LargeConfigured = Environment.GetEnvironmentVariable("SHARPEMU_COMPILED_LARGE_RANGES") != "0"; + private const int MaxLargeBlocks = 262144; + private const int MaxLargeSlots = 262144; + private const int MaxLargeRoots = 262144; + private const int MaxDistinctLargeRoots = 65536; + private const int MaxDepth = 64; + private const ulong AddressMask = 0x0000_FFFF_FFFF_FFFFul; + + // A function-buffer access in the order the reference's loop visits it. A null handle is where that loop throws for a + // missing descriptor, so the list ends there. + internal readonly record struct FunctionBuffer(ScalarValue? Handle, bool Written); + + private readonly IReadOnlyList _ranges; + private readonly FunctionBuffer[]? _functions; + private readonly Func? _evaluate; + private readonly int _slots; + private readonly RecordRanges?[] _records; + + internal string? Refusal { get; } + internal int Partitions { get; } + internal int RootCount { get; } + internal int DistinctRootCount { get; } + + private CompiledDeviceAddressRanges(ShaderResourcePlan plan, FunctionBuffer[]? functions, Func? evaluate, + int slots, string? refusal, RecordRanges?[] records, int partitions = 0, int roots = 0, int distinctRoots = 0) + { + _ranges = plan.DeviceAddressRanges; + _functions = functions; + _evaluate = evaluate; + _slots = slots; + Refusal = refusal; + _records = records; + Partitions = partitions; + RootCount = roots; + DistinctRootCount = distinctRoots; + } + + // A callee's compiled V#s; null for a callee without computed V#s. + internal RecordRanges? Record(int callee) => (uint)callee < (uint)_records.Length ? _records[callee] : null; + + internal static FunctionBuffer[]? FunctionBuffers(ShaderResourcePlan plan) + { + var accesses = plan.Graph.Program.FunctionBufferAccesses; + if (accesses.Count == 0) return null; + var functions = new List(); + foreach (var memory in plan.Memory.Entries) + { + if (!memory.DeviceDescriptor || !accesses.Contains(memory.Pc)) continue; + if (!plan.Memory.TryGetIndex(memory.Pc, memory.ComponentIndex, out var memoryIndex) || + plan.Accesses[memoryIndex]?.Handle is not { Kind: ScalarValueKind.BufferHandle, Operands.Length: 4 } handle) + { + functions.Add(new(null, false)); + break; + } + + functions.Add(new(handle, memory.Access is MemoryAccess.Write or MemoryAccess.Atomic)); + } + + return [.. functions]; + } + + // ShaderResourcePlan.CompileEvaluatorNow builds it under the plan's compile gate; null while the switch is off. + internal static CompiledDeviceAddressRanges? TryBuild(ShaderResourcePlan plan) + { + if (Configured == Mode.Off) return null; + CompiledDeviceAddressRanges compiled; + try + { + compiled = Build(plan); + } + catch (Exception exception) when (exception is not OutOfMemoryException) + { + compiled = new(plan, null, null, 0, "error:" + exception.GetType().Name, []); + } + + return compiled; + } + + // Roots: 2r is range r's base low and 2r + 1 its base high; 2R + 4f + w is word w of function buffer f. + internal static CompiledDeviceAddressRanges Build(ShaderResourcePlan plan, bool? compileLarge = null) + { + if (!RuntimeFeature.IsDynamicCodeSupported || Environment.GetEnvironmentVariable("SHARPEMU_SRT_NATIVE") == "0") + return new(plan, null, null, 0, "no_dynamic_code", []); + var records = new RecordRanges?[plan.CallRecordCallees.Count]; + for (var callee = 0; callee < records.Length; callee++) + { + if (plan.CallRecordCallees[callee].BufferWords is { Length: > 0 } buffers) records[callee] = RecordRanges.Build(plan, buffers); + } + + var ranges = plan.DeviceAddressRanges; + var functions = FunctionBuffers(plan); + var roots = new List<(int Root, ScalarValue Value)>(); + for (var index = 0; index < ranges.Count; index++) + { + if (!ranges[index].Plannable) continue; + roots.Add((2 * index, ranges[index].BaseLow)); + roots.Add((2 * index + 1, ranges[index].BaseHigh)); + } + + for (var function = 0; function < (functions?.Length ?? 0); function++) + { + if (functions![function].Handle is not { } handle) continue; + for (var word = 0; word < 4; word++) + roots.Add((2 * ranges.Count + 4 * function + word, handle.Operands[word])); + } + + if (roots.Count == 0) return new(plan, functions, null, 0, null, records); + var builder = new Builder(plan, records: false); + try + { + var evaluate = builder.Compile(roots); + return new(plan, functions, evaluate, builder.Slots, null, records); + } + catch (RefusedShape refused) + { + if (refused.Message == "too_large" && (compileLarge ?? LargeConfigured)) + { + // Retry compilation only. No guest reads have occurred, and malformed/deep/cyclic roots keep refusing. + var partitioned = new Builder(plan, records: false); + try + { + var evaluate = partitioned.CompilePartitioned(roots, out var pieces); + return new(plan, functions, evaluate, partitioned.Slots, null, records, pieces, roots.Count, partitioned.DistinctRoots); + } + catch (RefusedShape largeRefusal) + { + return new(plan, null, null, 0, largeRefusal.Message, records, roots: roots.Count, distinctRoots: partitioned.DistinctRoots); + } + } + return new(plan, null, null, 0, refused.Message, records); + } + } + + // Serves DeviceAddressRangePlanner.Evaluate while the switch is on. + internal static DeviceAddressRange[] Serve(ShaderResourcePlan plan, ResourceRuntimeInputs inputs) + { + if (Configured == Mode.Off) return DeviceAddressRangePlanner.EvaluateInterpreted(plan, inputs); + var compiled = plan.CompiledRanges; + if (compiled is null || compiled.Refusal is not null || !ReferenceEquals(compiled._ranges, plan.DeviceAddressRanges)) + return DeviceAddressRangePlanner.EvaluateInterpreted(plan, inputs); + return compiled.Evaluate(plan, inputs); + } + + internal DeviceAddressRange[] Evaluate(ShaderResourcePlan plan, ResourceRuntimeInputs inputs) + { + var ranges = _ranges; + var state = State.Rent(_slots, 0, plan, inputs); + try + { + if (_functions is null) + { + if (ranges.Count == 0) return []; + var result = new DeviceAddressRange[ranges.Count]; + for (var index = 0; index < result.Length; index++) + result[index] = Range(state, ranges[index], index); + return result; + } + + var functionRanges = state.Ranges; + for (var index = 0; index < ranges.Count; index++) + functionRanges.Add(Range(state, ranges[index], index)); + var seen = state.Seen; + Span words = stackalloc uint[4]; + for (var function = 0; function < _functions.Length; function++) + { + var entry = _functions[function]; + if (entry.Handle is null) throw new ResourcePlanException(DeviceAddressRangePlanner.MissingFunctionDescriptor); + var root = 2 * ranges.Count + 4 * function; + var resolved = true; + for (var component = 0; component < 4 && resolved; component++) + resolved = Root(state, root + component, out words[component]); + if (!resolved) + { + // A V# of a callee linked with run-time arguments: the host resolves it for each record (CallRecordCallee). + if (plan.CallRecordCallees.Count != 0) continue; + throw new ResourcePlanException(DeviceAddressRangePlanner.UnresolvedFunctionBuffer); + } + var address = words[0] | ((ulong)(words[1] & 0xFFFF) << 32); + if ((words[1] & 0x80000000) != 0) + throw new ResourcePlanException(DeviceAddressRangePlanner.SwizzledFunctionBuffer); + var stride = (words[1] >> 16) & 0x3FFF; + var size = (ulong)words[2] * Math.Max(stride, 1u); + if (size == 0) continue; + if (size > AddressMask - address + 1) + throw new ResourcePlanException(DeviceAddressRangePlanner.WrappingFunctionBuffer); + if (seen.Add((address, size, entry.Written))) + functionRanges.Add(new((uint)functionRanges.Count, address, size, true, entry.Written)); + } + return functionRanges.ToArray(); + } + finally + { + state.Return(); + } + } + + private DeviceAddressRange Range(State state, DeviceAddressRangePlan range, int index) + { + uint low = 0; + uint high = 0; + var planned = range.Plannable && Root(state, 2 * index, out low) && Root(state, 2 * index + 1, out high); + return DeviceAddressRangePlanner.EvaluateRange(range, planned, low, high); + } + + private bool Root(State state, int root, out uint value) => Root(_evaluate!, state, root, out value); + + private static bool Root(Func evaluate, State state, int root, out uint value) + { + if (!evaluate(state, root)) + { + value = 0; + return false; + } + + value = (uint)state.Result; + return true; + } + + // Serves CallRecordPlanner.AddRecordRanges while the switch is on, for a callee with computed V#s. + internal static bool ServeRecord(ShaderResourcePlan plan, int callee, ulong argument, ResourceRuntimeInputs inputs, + uint userDataBase, List ranges) + { + if (Configured == Mode.Off || plan.CompiledRanges is not { } compiled) + return CallRecordPlanner.AddRecordRangesInterpreted(plan, callee, argument, inputs, userDataBase, ranges); + + // User data that reaches the argument registers: the interpreter throws WithCallArguments' exception. + if (compiled.Record(callee) is not { Refusal: null } record || !record.Compiles(plan.CallRecordCallees[callee].BufferWords) || + userDataBase > ScalarValueGraph.CallArgumentRegisterBase || + inputs.UserData.Count > ScalarValueGraph.CallArgumentRegisterBase - userDataBase) + return CallRecordPlanner.AddRecordRangesInterpreted(plan, callee, argument, inputs, userDataBase, ranges); + return record.Add(plan, argument, inputs, userDataBase, ranges); + } + + // One callee's computed V#s (CallRecordBufferWords), evaluated for each record: root 4b + w is word w of buffer b. + internal sealed class RecordRanges + { + private readonly CallRecordBufferWords[] _buffers; + private readonly Func? _evaluate; + private readonly int _slots; + private readonly int _groups; + + internal string? Refusal { get; } + + private RecordRanges(CallRecordBufferWords[] buffers, Func? evaluate, int slots, int groups, string? refusal) + { + _buffers = buffers; + _evaluate = evaluate; + _slots = slots; + _groups = groups; + Refusal = refusal; + } + + internal static RecordRanges Build(ShaderResourcePlan plan, CallRecordBufferWords[] buffers) + { + var roots = new List<(int Root, ScalarValue Value)>(); + for (var buffer = 0; buffer < buffers.Length; buffer++) + { + if (buffers[buffer].Words.Length != 4) return new(buffers, null, 0, 0, "malformed_buffer"); + for (var word = 0; word < 4; word++) roots.Add((4 * buffer + word, buffers[buffer].Words[word])); + } + + var builder = new Builder(plan, records: true); + try + { + var evaluate = builder.Compile(roots); + return new(buffers, evaluate, builder.Slots, builder.Groups, null); + } + catch (RefusedShape refused) + { + return new(buffers, null, 0, 0, refused.Message); + } + catch (Exception exception) when (exception is not OutOfMemoryException) + { + // One callee's failure leaves the plan's ranges and the other callees compiled. + return new(buffers, null, 0, 0, "error:" + exception.GetType().Name); + } + } + + // Compiled from these buffers' words. + internal bool Compiles(CallRecordBufferWords[] buffers) => ReferenceEquals(buffers, _buffers); + + // CallRecordPlanner.AddRecordRangesInterpreted with only the value evaluation replaced. + internal bool Add(ShaderResourcePlan plan, ulong argument, ResourceRuntimeInputs inputs, uint userDataBase, + List ranges) + { + const ulong MaxRecordBufferBytes = 1UL << 32; + var state = State.Rent(_slots, _groups, plan, inputs); + state.RecordFirst = ScalarValueGraph.CallArgumentRegisterBase - userDataBase; + state.Argument = argument; + try + { + Span words = stackalloc uint[4]; + for (var index = 0; index < _buffers.Length; index++) + { + var buffer = _buffers[index]; + var resolved = true; + for (var dword = 0; dword < 4 && resolved; dword++) + { + resolved = Root(_evaluate!, state, 4 * index + dword, out words[dword]); + } + + if (!resolved) + { + continue; + } + + var address = words[0] | ((ulong)(words[1] & 0xFFFF) << 32); + var stride = (words[1] >> 16) & 0x3FFF; + var size = (ulong)words[2] * Math.Max(stride, 1u); + if (address == 0 || size == 0) + { + continue; + } + + if (size > MaxRecordBufferBytes || address + size > 1UL << 48) + { + if (buffer.Written) + { + return false; + } + + continue; + } + + ranges.Add(new DeviceAddressRange(uint.MaxValue, address, size, true, buffer.Written)); + } + + return true; + } + finally + { + state.Return(); + } + } + } + + // One call's values. Known[i] is set when node i succeeded; a failed node stays unknown and is evaluated again. + internal sealed class State + { + [ThreadStatic] + private static State? _available; + + public ulong[] Values = []; + public bool[] Known = []; + public ulong Result; + public ulong ShaderBase; + public GuestWordReader? Reader; + public bool ReadsClean; + public IReadOnlyList UserData = []; + public uint[]? UserDataArray; + public ShaderResourcePlan? Plan; + public readonly List Ranges = []; + public readonly HashSet<(ulong Base, ulong Size, bool Written)> Seen = []; + // A record's: where its argument registers start in the user data, its argument, the resident reader and the read + // groups it has tried. + public uint RecordFirst; + public ulong Argument; + public ResidentGuestBytesReader? Resident; + public bool[] GroupsTried = []; + + internal static State Rent(int slots, int groups, ShaderResourcePlan plan, ResourceRuntimeInputs inputs) + { + var state = _available ?? new State(); + _available = null; + if (state.Values.Length < slots) + { + state.Values = new ulong[slots]; + state.Known = new bool[slots]; + } + else + { + Array.Clear(state.Known, 0, slots); + } + + if (state.GroupsTried.Length < groups) state.GroupsTried = new bool[groups]; + else Array.Clear(state.GroupsTried, 0, groups); + state.Plan = plan; + state.ShaderBase = inputs.ShaderBase; + state.Reader = inputs.ReadMemory; + state.ReadsClean = inputs.ReadsClean; + state.UserData = inputs.UserData; + state.UserDataArray = inputs.UserData as uint[]; + state.Resident = inputs.ReadResidentMemory; + return state; + } + + internal void Return() + { + Plan = null; + Reader = null; + Resident = null; + UserData = []; + UserDataArray = null; + Ranges.Clear(); + if (Seen.Count != 0) Seen.Clear(); + _available = this; + } + } + + private static bool ReadUserData(State state, uint index, out ulong value) + { + if (state.UserDataArray is { } array) + { + if (index < (uint)array.Length) + { + value = array[index]; + return true; + } + } + else if (index < (uint)state.UserData.Count) + { + value = state.UserData[(int)index]; + return true; + } + + value = 0; + return false; + } + + // The user data ResourceRuntimeInputs.WithCallArguments builds for a record, without building it: the draw's, zeros up + // to the argument registers, then the argument's two dwords. + private static bool ReadRecordUserData(State state, uint index, out ulong value) + { + if (index < (uint)state.UserData.Count) return ReadUserData(state, index, out value); + var first = state.RecordFirst; + value = index == first ? (uint)state.Argument : index == first + 1 ? (uint)(state.Argument >> 32) : 0; + return index <= first + 1; + } + + // A record's reads of one handle at consecutive constant offsets, made by one read of the resident reader the first time + // one of them is evaluated in the record. A refused read, or no resident reader, leaves them to word reads. + private sealed class Group(int index, long relative, int[] slots, int[] words, ScalarValue[] nodes) + { + public readonly int Index = index; + public readonly long Relative = relative; + public readonly int Words = words[^1] + 1; + public readonly int[] Slots = slots; + public readonly int[] Word = words; + public readonly ScalarValue[] Nodes = nodes; + } + + private const int MaxGroupWords = 64; + + private static void ReadGroup(State state, Group group, ulong low, ulong high) + { + if (state.GroupsTried[group.Index]) return; + state.GroupsTried[group.Index] = true; + var reader = state.Resident; + var baseAddress = ((high << 32) | (uint)low) & AddressMask; + // As RawReadPrefetch: the word reader must exist, a null base keeps its own rule, and the words must not wrap. + if (reader is null || state.Reader is null || (baseAddress & ~3ul) == 0 || + RuntimeValueEvaluator.ResolveRawAddress(ScalarValueKind.ScalarAddressWord, baseAddress, high, 0, group.Relative, 0, + out var first) != RuntimeValueEvaluator.RawAddress.Read || + RuntimeValueEvaluator.ResolveRawAddress(ScalarValueKind.ScalarAddressWord, baseAddress, high, 0, + group.Relative + 4L * (group.Words - 1), 0, out var last) != RuntimeValueEvaluator.RawAddress.Read || + last - first != 4ul * (uint)(group.Words - 1)) + return; + Span bytes = stackalloc byte[4 * MaxGroupWords]; + bytes = bytes[..(4 * group.Words)]; + if (!reader(first, bytes, state.ReadsClean)) return; + var values = state.Values; + var known = state.Known; + for (var member = 0; member < group.Slots.Length; member++) + { + var slot = group.Slots[member]; + if (known[slot]) continue; + var word = group.Word[member]; + values[slot] = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(bytes[(4 * word)..]); + known[slot] = true; + ResourceMaterializationCache.RecordReadConsumer(state.Plan!, group.Nodes[member], first + 4ul * (uint)word); + } + } + + // RuntimeValueEvaluator.ReadRawWord through the call's reader. + private static bool ReadWord(State state, ScalarValueKind kind, ulong low, ulong high, ulong offset, ulong records, + long immediate, bool absolute, ScalarValue node, out ulong value) + { + value = 0; + var baseAddress = ((high << 32) | (uint)low) & AddressMask; + switch (RuntimeValueEvaluator.ResolveRawAddress(kind, baseAddress, high, records, immediate, (uint)offset, out var address)) + { + case RuntimeValueEvaluator.RawAddress.Failed: + return false; + case RuntimeValueEvaluator.RawAddress.Zero: + return true; + } + + var reader = state.Reader; + if (reader is null || !reader(address, out var word)) + { + // As in the evaluator: a null base, or an absolute address the shader carries that nothing maps, reads zero. + return (baseAddress & ~3ul) == 0 || (absolute && reader is not null && !state.ReadsClean); + } + + value = word; + ResourceMaterializationCache.RecordReadConsumer(state.Plan!, node, address); + return true; + } + + private sealed class RefusedShape(string reason) : Exception(reason); + + // Each root is straight-line code: a node's statements run under "if (!known[node])" where the root first needs it, + // and its later uses in that root read its value (a failure anywhere ends the root, so a later use finds it known). + // A record's code reads the user data as ReadRecordUserData does and groups its reads (Group). + private sealed class Builder(ShaderResourcePlan plan, bool records) + { + private static readonly MethodInfo EvaluateOperation = typeof(ScalarOperationSemantics) + .GetMethod(nameof(ScalarOperationSemantics.TryEvaluateFixed), BindingFlags.NonPublic | BindingFlags.Static)!; + private static readonly MethodInfo ReadWordMethod = typeof(CompiledDeviceAddressRanges) + .GetMethod(nameof(ReadWord), BindingFlags.NonPublic | BindingFlags.Static)!; + private static readonly MethodInfo ReadUserDataMethod = typeof(CompiledDeviceAddressRanges) + .GetMethod(nameof(ReadUserData), BindingFlags.NonPublic | BindingFlags.Static)!; + private static readonly MethodInfo ReadRecordUserDataMethod = typeof(CompiledDeviceAddressRanges) + .GetMethod(nameof(ReadRecordUserData), BindingFlags.NonPublic | BindingFlags.Static)!; + private static readonly MethodInfo ReadGroupMethod = typeof(CompiledDeviceAddressRanges) + .GetMethod(nameof(ReadGroup), BindingFlags.NonPublic | BindingFlags.Static)!; + + private readonly ParameterExpression _state = Expression.Parameter(typeof(State), "state"); + private readonly ParameterExpression _root = Expression.Parameter(typeof(int), "root"); + private readonly ParameterExpression _values = Expression.Variable(typeof(ulong[]), "values"); + private readonly ParameterExpression _known = Expression.Variable(typeof(bool[]), "known"); + private readonly ParameterExpression _word = Expression.Variable(typeof(ulong), "word"); + private readonly LabelTarget _return = Expression.Label(typeof(bool), "return"); + private readonly Context _planContext = new(null); + private readonly Dictionary<(Context, ScalarValue), Context> _contexts = []; + private readonly Dictionary<(Context, ScalarValue), int> _slots = []; + private readonly Dictionary _groups = new(ReferenceEqualityComparer.Instance); + private int _groupCount; + private int _blocks; + + // One evaluator: the plan's, or a first-lane value's, which starts empty each time that value is evaluated and + // takes a select on its active mask as the select's first value. + private sealed class Context(ScalarValue? mask) + { + public readonly ScalarValue? Mask = mask; + public readonly List Slots = []; + } + + // One run of a context in a root: the nodes it has made known so far. + private sealed class Run(Context context) + { + public readonly Context Context = context; + public readonly HashSet Emitted = []; + } + + internal int Slots => _slots.Count; + + internal int Groups => _groupCount; + internal int DistinctRoots { get; private set; } + + internal Func Compile(List<(int Root, ScalarValue Value)> roots) + { + if (records) CollectGroups(roots); + var cases = new List(roots.Count); + foreach (var (root, value) in roots) + { + var statements = new List(); + var result = Emit(value, statements, new Run(_planContext), []); + if (result is not null) + { + statements.Add(Expression.Assign(Expression.Field(_state, nameof(State.Result)), result)); + statements.Add(Expression.Return(_return, Expression.Constant(true))); + } + else + { + statements.Add(Fail()); + } + + cases.Add(Expression.SwitchCase(Expression.Block(typeof(void), statements), Expression.Constant(root))); + } + + return CompileCases(cases); + } + + private Func CompileCases(List cases) + { + var body = Expression.Block(typeof(bool), [_values, _known, _word], + Expression.Assign(_values, Expression.Field(_state, nameof(State.Values))), + Expression.Assign(_known, Expression.Field(_state, nameof(State.Known))), + Expression.Switch(typeof(void), _root, Fail(), null, cases), + Expression.Label(_return, Expression.Constant(false))); + return Expression.Lambda>(body, _state, _root).Compile(); + } + + internal Func CompilePartitioned(List<(int Root, ScalarValue Value)> roots, out int partitions) + { + if (records || roots.Count == 0 || roots.Count > MaxLargeRoots || + roots.Any(root => root.Root < 0 || root.Root >= MaxLargeRoots)) + throw new RefusedShape("large_root_budget"); + // Function-buffer access sites often name the very same scalar nodes thousands of times. Emit each + // reference-identical root once; the external sequence still invokes it each time, including retries after + // a failed read. This shares code only, not a cached result or a first-lane execution context. + var aliases = new int[roots.Max(root => root.Root) + 1]; + Array.Fill(aliases, -1); + var distinct = new List(); + var identities = new Dictionary(ReferenceEqualityComparer.Instance); + foreach (var (root, value) in roots) + { + if (!identities.TryGetValue(value, out var index)) + { + index = distinct.Count; + DistinctRoots = index + 1; + if (DistinctRoots > MaxDistinctLargeRoots) throw new RefusedShape("large_distinct_root_budget"); + identities.Add(value, index); + distinct.Add(value); + } + aliases[root] = index; + } + var dispatch = new Func?[distinct.Count]; + var cases = new List(); + var indices = new List(); + var pieceBlocks = 0; + var totalBlocks = 0; + var pieces = 0; + void FinishPiece() + { + if (cases.Count == 0) return; + var evaluate = CompileCases(cases); + foreach (var root in indices) dispatch[root] = evaluate; + cases.Clear(); + indices.Clear(); + pieceBlocks = 0; + pieces++; + } + + for (var root = 0; root < distinct.Count; root++) + { + // Each root keeps its own depth and block checks; only the cumulative budget across roots is split. + // The same builder owns every slot/context: creating a new builder here would repeat guest reads. + _blocks = 0; + var statements = new List(); + var result = Emit(distinct[root], statements, new Run(_planContext), []); + totalBlocks += _blocks; + if (totalBlocks > MaxLargeBlocks) throw new RefusedShape("large_total_budget"); + if (Slots > MaxLargeSlots) throw new RefusedShape("large_slot_budget"); + if (pieceBlocks + _blocks > MaxBlocks || cases.Count == 64) FinishPiece(); + if (result is not null) + { + statements.Add(Expression.Assign(Expression.Field(_state, nameof(State.Result)), result)); + statements.Add(Expression.Return(_return, Expression.Constant(true))); + } + else statements.Add(Fail()); + cases.Add(Expression.SwitchCase(Expression.Block(typeof(void), statements), Expression.Constant(root))); + indices.Add(root); + pieceBlocks += _blocks; + } + FinishPiece(); + partitions = pieces; + // Only large plans take this extra dispatch over their pieces; small plans keep their direct call. + return (state, root) => (uint)root < (uint)aliases.Length && aliases[root] is var index && index >= 0 && + dispatch[index] is { } evaluate && evaluate(state, index); + } + + private Expression Fail() => Expression.Return(_return, Expression.Constant(false)); + + private IndexExpression Value(int slot) => Expression.ArrayAccess(_values, Expression.Constant(slot)); + + private IndexExpression Known(int slot) => Expression.ArrayAccess(_known, Expression.Constant(slot)); + + // The node one evaluator computes for a value: a phi's invariant value, a table word's read. + private ScalarValue? Resolve(ScalarValue value) + { + for (var step = 0; step < MaxDepth; step++) + { + if (value.Kind == ScalarValueKind.Phi) + { + if (plan.Graph.ResolveInvariantPhi(value) is not { } invariant) return null; + value = invariant; + } + else if (value.Kind == ScalarValueKind.ResourceTableWord) + { + if (value.Payload >= (ulong)plan.TableReads.Count) return null; + value = plan.TableReads[(int)value.Payload].Value; + } + else + { + return value; + } + } + + throw new RefusedShape("cycle"); + } + + private int Slot(Context context, ScalarValue node) + { + if (!_slots.TryGetValue((context, node), out var slot)) + { + _slots.Add((context, node), slot = _slots.Count); + context.Slots.Add(slot); + } + + return slot; + } + + // The plan evaluator's reads of one address handle at constant offsets, in runs of consecutive words. The walk takes + // the operands Emit evaluates in that evaluator; a first-lane value's reads are its own evaluator's and stay word reads. + private void CollectGroups(List<(int Root, ScalarValue Value)> roots) + { + var reads = new Dictionary>(ReferenceEqualityComparer.Instance); + var visited = new HashSet(ReferenceEqualityComparer.Instance); + var pending = new Stack(); + for (var index = roots.Count - 1; index >= 0; index--) pending.Push(roots[index].Value); + while (pending.TryPop(out var value)) + { + if (ResolveOrNull(value) is not { } node || !visited.Add(node)) continue; + switch (node.Kind) + { + case ScalarValueKind.Select: + case ScalarValueKind.Operation when RuntimeValueValidator.IsUniformOperation(node.Operation): + foreach (var operand in node.Operands) pending.Push(operand); + break; + case ScalarValueKind.ScalarAddressWord or ScalarValueKind.ScalarBufferWord when node.Operands.Length >= 2: + foreach (var operand in node.Operands[0].Operands) pending.Push(operand); + pending.Push(node.Operands[1]); + if (node.Kind == ScalarValueKind.ScalarAddressWord && node.Operands[0].Operands.Length >= 2 && + node.MemoryIndex >= 0 && node.MemoryIndex < plan.Memory.Count && + ResolveOrNull(node.Operands[1]) is { Kind: ScalarValueKind.Constant } offset) + { + if (!reads.TryGetValue(node.Operands[0], out var list)) reads.Add(node.Operands[0], list = []); + // RuntimeValueEvaluator.ResolveRawAddress's offset from the base. + var relative = ((long)(int)plan.Memory[node.MemoryIndex].Offset & ~3L) + ((uint)offset.Payload & ~3u); + list.Add((relative, visited.Count, node)); + } + + break; + } + } + + foreach (var list in reads.Values) + { + list.Sort(static (left, right) => left.Relative != right.Relative + ? left.Relative.CompareTo(right.Relative) : left.Order.CompareTo(right.Order)); + var start = 0; + for (var end = 1; end <= list.Count; end++) + { + if (end < list.Count && list[end].Relative - list[end - 1].Relative <= 4 && + list[end].Relative - list[start].Relative < 4L * MaxGroupWords) + continue; + if (list[end - 1].Relative != list[start].Relative) AddGroup(list, start, end); + start = end; + } + } + } + + private void AddGroup(List<(long Relative, int Order, ScalarValue Node)> list, int start, int end) + { + var slots = new int[end - start]; + var words = new int[slots.Length]; + var nodes = new ScalarValue[slots.Length]; + for (var member = 0; member < slots.Length; member++) + { + var (relative, _, node) = list[start + member]; + slots[member] = Slot(_planContext, node); + words[member] = (int)((relative - list[start].Relative) / 4); + nodes[member] = node; + } + + var group = new Group(_groupCount++, list[start].Relative, slots, words, nodes); + foreach (var node in nodes) _groups[node] = group; + } + + private ScalarValue? ResolveOrNull(ScalarValue value) + { + try + { + return Resolve(value); + } + catch (RefusedShape) + { + return null; + } + } + + // Adds what makes the value known to statements (a failure returns false) and returns the expression of its + // value, or null when the statements end in a failure the value cannot avoid. + private Expression? Emit(ScalarValue value, List statements, Run run, List path) + { + var node = Resolve(value); + if (node is null) + { + statements.Add(Fail()); + return null; + } + + switch (node.Kind) + { + case ScalarValueKind.Constant: + return Expression.Constant(node.Payload); + case ScalarValueKind.MemoryAperture: + return Expression.Constant(Gen5InlineConstants.DecodeAperture64((uint)node.Payload) >> 32); + case ScalarValueKind.ShaderBase: + return Expression.Field(_state, nameof(State.ShaderBase)); + case ScalarValueKind.Select when node.Operands.Length == 3 && run.Context.Mask is { } mask && + ReferenceEquals(node.Operands[0], mask): + { + if (path.Contains(node)) throw new RefusedShape("cycle"); + if (path.Count >= MaxDepth) throw new RefusedShape("too_deep"); + path.Add(node); + var selected = Emit(node.Operands[1], statements, run, path); + path.RemoveAt(path.Count - 1); + return selected; + } + case ScalarValueKind.UserData when node.UserDataRegister >= plan.UserDataBase: + case ScalarValueKind.Operation when RuntimeValueValidator.IsUniformOperation(node.Operation): + case ScalarValueKind.Select or ScalarValueKind.FirstLane: + case ScalarValueKind.ScalarAddressWord or ScalarValueKind.ScalarBufferWord: + break; + default: + // Undefined, a handle, a register below the user data or a non-uniform operation fails before any + // operand is evaluated. + statements.Add(Fail()); + return null; + } + + if (path.Contains(node)) throw new RefusedShape("cycle"); + var slot = Slot(run.Context, node); + if (run.Emitted.Contains(node)) return Value(slot); + if (path.Count >= MaxDepth) throw new RefusedShape("too_deep"); + if (++_blocks > MaxBlocks) throw new RefusedShape("too_large"); + path.Add(node); + var block = new List(); + var complete = EmitNode(node, slot, block, run, path); + path.RemoveAt(path.Count - 1); + statements.Add(Expression.IfThen(Expression.Not(Known(slot)), Expression.Block(typeof(void), block))); + if (!complete) return null; + run.Emitted.Add(node); + return Value(slot); + } + + // RuntimeValueEvaluator.EvaluateNode for the kinds Emit keeps. + private bool EmitNode(ScalarValue node, int slot, List block, Run run, List path) + { + Expression call; + switch (node.Kind) + { + case ScalarValueKind.UserData: + call = Expression.Call(records ? ReadRecordUserDataMethod : ReadUserDataMethod, _state, + Expression.Constant(node.UserDataRegister - plan.UserDataBase), _word); + break; + case ScalarValueKind.FirstLane: + { + if (node.Operands.Length < 2) throw new RefusedShape("malformed_first_lane"); + if (!_contexts.TryGetValue((run.Context, node), out var context)) + _contexts.Add((run.Context, node), context = new Context(node.Operands[1])); + var body = new List(); + var operand = Emit(node.Operands[0], body, new Run(context), path); + // Its own evaluator starts empty every time the value is evaluated. + foreach (var forgotten in context.Slots) block.Add(Expression.Assign(Known(forgotten), Expression.Constant(false))); + block.AddRange(body); + if (operand is null) return false; + block.Add(Expression.Assign(Value(slot), operand)); + block.Add(Expression.Assign(Known(slot), Expression.Constant(true))); + return true; + } + case ScalarValueKind.Select: + { + if (node.Operands.Length != 3) throw new RefusedShape("malformed_select"); + var operands = new Expression[3]; + for (var index = 0; index < operands.Length; index++) + { + if (Emit(node.Operands[index], block, run, path) is not { } operand) return false; + operands[index] = operand; + } + + block.Add(Expression.Assign(Value(slot), Expression.Condition( + Expression.NotEqual(operands[0], Expression.Constant(0UL)), operands[1], operands[2]))); + block.Add(Expression.Assign(Known(slot), Expression.Constant(true))); + return true; + } + case ScalarValueKind.Operation: + { + // Every operand is evaluated; the semantics use the first four. + var operands = new Expression[4]; + for (var index = 0; index < node.Operands.Length; index++) + { + if (Emit(node.Operands[index], block, run, path) is not { } operand) return false; + if (index < operands.Length) operands[index] = operand; + } + + for (var index = node.Operands.Length; index < operands.Length; index++) operands[index] = Expression.Constant(0UL); + call = Expression.Call(EvaluateOperation, Expression.Constant(node.Operation), + operands[0], operands[1], operands[2], operands[3], _word); + break; + } + default: + { + // The interpreter and the compiled evaluator disagree on these malformed reads; neither occurs in a built graph. + var buffer = node.Kind == ScalarValueKind.ScalarBufferWord; + if (node.MemoryIndex < 0 || node.Operands.Length < 2 || + (buffer && node.Operands[0].Operands.Length is >= 2 and not 4)) + throw new RefusedShape("malformed_read"); + var handle = node.Operands[0]; + if (node.MemoryIndex >= plan.Memory.Count || handle.Operands.Length < 2) + { + block.Add(Fail()); + return false; + } + + var operands = new Expression[buffer ? 4 : 3]; + ScalarValue[] sources = buffer + ? [handle.Operands[0], handle.Operands[1], node.Operands[1], handle.Operands[2], handle.Operands[3]] + : [handle.Operands[0], handle.Operands[1], node.Operands[1]]; + for (var index = 0; index < sources.Length; index++) + { + if (Emit(sources[index], block, run, path) is not { } operand) return false; + if (index < operands.Length) operands[index] = operand; + } + + call = Expression.Call(ReadWordMethod, _state, Expression.Constant(node.Kind), operands[0], operands[1], + operands[2], buffer ? operands[3] : Expression.Constant(0UL), + Expression.Constant((long)(int)plan.Memory[node.MemoryIndex].Offset), + Expression.Constant(RuntimeValueEvaluator.IsAbsoluteAddress(node.Kind, handle)), + Expression.Constant(node, typeof(ScalarValue)), _word); + if (run.Context == _planContext && _groups.TryGetValue(node, out var group)) + { + // The group's read may make this word known; otherwise it is read alone. + block.Add(Expression.Call(ReadGroupMethod, _state, Expression.Constant(group), operands[0], operands[1])); + block.Add(Expression.IfThen(Expression.Not(Known(slot)), Expression.Block(typeof(void), + Expression.IfThen(Expression.Not(call), Fail()), + Expression.Assign(Value(slot), _word), + Expression.Assign(Known(slot), Expression.Constant(true))))); + return true; + } + + break; + } + } + + block.Add(Expression.IfThen(Expression.Not(call), Fail())); + block.Add(Expression.Assign(Value(slot), _word)); + block.Add(Expression.Assign(Known(slot), Expression.Constant(true))); + return true; + } + } +} diff --git a/src/SharpEmu.ShaderCompiler/Resources/CompiledResourceTransaction.cs b/src/SharpEmu.ShaderCompiler/Resources/CompiledResourceTransaction.cs index 67d107a25..0b23c61b6 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/CompiledResourceTransaction.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/CompiledResourceTransaction.cs @@ -256,7 +256,7 @@ void GroupReads(List statements) } } - private static void SetTablePhase(ResourceRuntimeInputs inputs, bool table) => inputs.TablePhase?.Invoke(table); + internal static void SetTablePhase(ResourceRuntimeInputs inputs, bool table) => inputs.TablePhase?.Invoke(table); private static bool ReadGroup(ResourceRuntimeInputs inputs, bool clean, ulong low, ulong high, long relative, int count, out ReadGroupWords values, ShaderResourcePlan plan, ScalarValue[] nodes) @@ -292,7 +292,7 @@ private static bool ReadGroup(ResourceRuntimeInputs inputs, bool clean, ulong lo private static uint ReadGroupWord(ref ReadGroupWords words, int index) => words[index]; - private static bool ReadUserData(ResourceRuntimeInputs inputs, ulong index, out ulong value) + internal static bool ReadUserData(ResourceRuntimeInputs inputs, ulong index, out ulong value) { value = 0; if (index >= (ulong)inputs.UserData.Count) return false; @@ -300,7 +300,7 @@ private static bool ReadUserData(ResourceRuntimeInputs inputs, ulong index, out return true; } - private static bool ReadWord(ResourceRuntimeInputs inputs, bool clean, ScalarValueKind kind, ulong low, ulong high, + internal static bool ReadWord(ResourceRuntimeInputs inputs, bool clean, ScalarValueKind kind, ulong low, ulong high, ulong offset, ulong records, long immediate, bool absolute, out ulong value, ShaderResourcePlan plan, ScalarValue node) { value = 0; diff --git a/src/SharpEmu.ShaderCompiler/Resources/DeviceAddressRangePlanner.cs b/src/SharpEmu.ShaderCompiler/Resources/DeviceAddressRangePlanner.cs index 45f7d8415..e4be4ff4d 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/DeviceAddressRangePlanner.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/DeviceAddressRangePlanner.cs @@ -22,6 +22,8 @@ public sealed record DeviceAddressRangePlan( DeviceAddressUnboundedReason UnboundedReason = DeviceAddressUnboundedReason.None) { public ulong Extent => Bounded && EndByte > FirstByte ? (ulong)(EndByte - FirstByte) : 0; + // Scalar dword loads mask the effective address down to a dword in the emitter. + public bool AlignScalarReads { get; init; } } public enum DeviceAddressUnboundedReason @@ -111,7 +113,8 @@ public static IReadOnlyList Plan(ShaderResourcePlan plan slot = handles.Count; hashSlots.Add(slot); handles.Add(handle); - ranges.Add(new DeviceAddressRangePlan((uint)slot, handle.Operands[0], handle.Operands[1], [], false, true, long.MaxValue, long.MinValue, false)); + ranges.Add(new DeviceAddressRangePlan((uint)slot, handle.Operands[0], handle.Operands[1], [], false, true, long.MaxValue, long.MinValue, false) + { AlignScalarReads = true }); } // The immediate offset is signed; the span keeps the lowest and highest byte. @@ -123,6 +126,7 @@ public static IReadOnlyList Plan(ShaderResourcePlan plan { MemoryIndices = [.. ranges[slot].MemoryIndices, index], Written = ranges[slot].Written || written, + AlignScalarReads = ranges[slot].AlignScalarReads && memory.Kind == MemoryResourceKind.ScalarAddress && !written, Bounded = ranges[slot].Bounded && reason == DeviceAddressUnboundedReason.None, UnboundedReason = ranges[slot].UnboundedReason != DeviceAddressUnboundedReason.None ? ranges[slot].UnboundedReason : reason, FirstByte = Math.Min(ranges[slot].FirstByte, firstByte), @@ -367,9 +371,23 @@ private static DeviceAddressUnboundedReason UnboundedReasonOf(ShaderResourcePlan }; } + internal const string MissingFunctionDescriptor = "The shader function buffer has no descriptor."; + internal const string UnresolvedFunctionBuffer = "The shader function buffer range cannot be resolved."; + internal const string SwizzledFunctionBuffer = "The shader function uses an unsupported swizzled buffer."; + internal const string WrappingFunctionBuffer = "The shader function buffer range wraps the guest address space."; + // Evaluates the planned ranges for one draw. A bounded range spans its lowest byte to // its extent; an unbounded one starts at the lowest immediate and takes the cap. public static DeviceAddressRange[] Evaluate(ShaderResourcePlan plan, ResourceRuntimeInputs inputs) + { + var ranges = CompiledDeviceAddressRanges.Configured == CompiledDeviceAddressRanges.Mode.Off + ? EvaluateInterpreted(plan, inputs) + : CompiledDeviceAddressRanges.Serve(plan, inputs); + return plan.DeviceRecordCounts?.Append(plan, inputs, ranges) ?? ranges; + } + + // One evaluator for every range and then the function V#s; the reference of CompiledDeviceAddressRanges. + internal static DeviceAddressRange[] EvaluateInterpreted(ShaderResourcePlan plan, ResourceRuntimeInputs inputs) { var ranges = plan.DeviceAddressRanges; var result = new DeviceAddressRange[ranges.Count]; @@ -381,20 +399,7 @@ public static DeviceAddressRange[] Evaluate(ShaderResourcePlan plan, ResourceRun uint low = 0; uint high = 0; var planned = range.Plannable && evaluator.Evaluate(range.BaseLow, out low) && evaluator.Evaluate(range.BaseHigh, out high); - var handleBase = (low | ((ulong)high << 32)) & AddressMask; - var firstByte = range.Bounded ? range.FirstByte : Math.Min(range.FirstByte, 0); - var baseAddress = planned ? unchecked(handleBase + (ulong)firstByte) & AddressMask : 0; - var size = range.Bounded ? range.Extent : MaxRangeBytes; - if (range.Bounded) - { - BoundedEvaluations.Increment(); - } - else - { - UnboundedEvaluations[(int)range.UnboundedReason].Increment(); - } - - result[index] = new DeviceAddressRange(range.Handle, baseAddress, planned ? size : 0, planned, range.Written); + result[index] = EvaluateRange(range, planned, low, high); } if (plan.Graph.Program.FunctionBufferAccesses.Count == 0) return result; @@ -405,7 +410,7 @@ public static DeviceAddressRange[] Evaluate(ShaderResourcePlan plan, ResourceRun if (!memory.DeviceDescriptor || !plan.Graph.Program.FunctionBufferAccesses.Contains(memory.Pc)) continue; if (!plan.Memory.TryGetIndex(memory.Pc, memory.ComponentIndex, out var memoryIndex) || plan.Accesses[memoryIndex]?.Handle is not { Kind: ScalarValueKind.BufferHandle, Operands.Length: 4 } handle) - throw new ResourcePlanException("The shader function buffer has no descriptor."); + throw new ResourcePlanException(MissingFunctionDescriptor); var words = new uint[4]; var resolved = true; for (var component = 0; component < 4 && resolved; component++) @@ -414,20 +419,45 @@ public static DeviceAddressRange[] Evaluate(ShaderResourcePlan plan, ResourceRun { // A V# of a callee linked with run-time arguments: the host resolves it for each record (CallRecordCallee). if (plan.CallRecordCallees.Count != 0) continue; - throw new ResourcePlanException("The shader function buffer range cannot be resolved."); + throw new ResourcePlanException(UnresolvedFunctionBuffer); } var address = words[0] | ((ulong)(words[1] & 0xFFFF) << 32); if ((words[1] & 0x80000000) != 0) - throw new ResourcePlanException("The shader function uses an unsupported swizzled buffer."); + throw new ResourcePlanException(SwizzledFunctionBuffer); var stride = (words[1] >> 16) & 0x3FFF; var size = (ulong)words[2] * Math.Max(stride, 1u); var written = memory.Access is MemoryAccess.Write or MemoryAccess.Atomic; if (size == 0) continue; if (size > AddressMask - address + 1) - throw new ResourcePlanException("The shader function buffer range wraps the guest address space."); + throw new ResourcePlanException(WrappingFunctionBuffer); if (seen.Add((address, size, written))) functionRanges.Add(new((uint)functionRanges.Count, address, size, true, written)); } return functionRanges.ToArray(); } + + // Shared by interpreted and compiled evaluators. Widen a scalar read's residency range down to the exact + // first dword the GPU can touch; aligned reads retain their original extent (e.g. six bounds words = 24 bytes). + internal static DeviceAddressRange EvaluateRange(DeviceAddressRangePlan range, bool planned, uint low, uint high) + { + var handleBase = (low | ((ulong)high << 32)) & AddressMask; + var firstByte = range.Bounded ? range.FirstByte : Math.Min(range.FirstByte, 0); + var baseAddress = planned ? unchecked(handleBase + (ulong)firstByte) & AddressMask : 0; + var size = range.Bounded ? range.Extent : MaxRangeBytes; + if (range.Bounded) + { + BoundedEvaluations.Increment(); + } + else + { + UnboundedEvaluations[(int)range.UnboundedReason].Increment(); + } + + if (planned && range.AlignScalarReads) + { + size += baseAddress & 3; + baseAddress &= ~3ul; + } + return new DeviceAddressRange(range.Handle, baseAddress, planned ? size : 0, planned, range.Written); + } } diff --git a/src/SharpEmu.ShaderCompiler/Resources/DeviceCountProofWorker.cs b/src/SharpEmu.ShaderCompiler/Resources/DeviceCountProofWorker.cs new file mode 100644 index 000000000..13fae7dfa --- /dev/null +++ b/src/SharpEmu.ShaderCompiler/Resources/DeviceCountProofWorker.cs @@ -0,0 +1,30 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections.Concurrent; + +namespace SharpEmu.ShaderCompiler.Resources; + +// One worker across plans. A dispatch never waits for admission or completion; it keeps the exact count path. +internal sealed class DeviceCountProofWorker +{ + private static readonly Lazy Instance = new(() => new()); + private readonly BlockingCollection _jobs = new(16); + + private DeviceCountProofWorker() + { + new Thread(Run) { IsBackground = true, Name = "Device count proofs" }.Start(); + } + + internal static bool TryQueue(Action job) => Instance.Value._jobs.TryAdd(job); + + private void Run() + { + foreach (var job in _jobs.GetConsumingEnumerable()) + { + try { job(); } + // Failed optional analysis leaves the cached refusal and ordinary count path intact. + catch (Exception exception) when (exception is not OutOfMemoryException) { } + } + } +} diff --git a/src/SharpEmu.ShaderCompiler/Resources/DeviceRecordCountPlan.cs b/src/SharpEmu.ShaderCompiler/Resources/DeviceRecordCountPlan.cs new file mode 100644 index 000000000..230f18f12 --- /dev/null +++ b/src/SharpEmu.ShaderCompiler/Resources/DeviceRecordCountPlan.cs @@ -0,0 +1,222 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.ShaderCompiler.Resources; + +// A raw buffer whose base/format are dispatch inputs and whose count is loaded by the GPU. +// The shader retains the actual count. Only residency can use a count-independent upper bound. +public sealed class DeviceRecordCountPlan +{ + // SHARPEMU_DEVICE_RECORD_COUNTS=0 plans no such buffer. + public static bool Enabled { get; } = Environment.GetEnvironmentVariable("SHARPEMU_DEVICE_RECORD_COUNTS") != "0"; + public const uint CacheIdentity = 0x44524301; + private readonly Dictionary _handles; + private readonly HashSet _skipCounts; + private readonly HashSet _pcs; + private readonly object _gate = new(); + private sealed class ProofEntry(uint[] userData, DispatchBufferFootprint.Dispatch dispatch) + { + public uint[] UserData { get; } = userData; + public DispatchBufferFootprint.Dispatch Dispatch { get; } = dispatch; + public Dictionary? Spans { get; set; } + } + private readonly ProofEntry?[] _proofs = new ProofEntry[32]; + private uint[] _inputWords = []; + private long _proofRevision; + internal long ProofRevision => Volatile.Read(ref _proofRevision); + // Tests can control completion without timing races. Production always uses the bounded worker. + internal Func QueueProof { get; set; } = DeviceCountProofWorker.TryQueue; + + internal long MaterializationRevision(ResourceRuntimeInputs inputs) + { + lock (_gate) + { + if (inputs.ComputeState is { DeviceCountProof: true, Dispatch: { } dispatch }) + { + foreach (var entry in _proofs) + { + if (entry?.Spans is not { } spans || entry.Dispatch != dispatch || + entry.UserData.Length != inputs.UserData.Count) continue; + var matches = true; + for (var index = 0; index < entry.UserData.Length; index++) + if (entry.UserData[index] != inputs.UserData[index]) { matches = false; break; } + if (matches) return Mapped(spans, inputs) ? _proofRevision : -_proofRevision; + } + // Eviction by pending/refused shapes need not publish a new proof. A previously proved + // materialization must still stop serving until this exact input is proved and mapped again. + return -_proofRevision; + } + return _proofRevision; + } + } + + private static bool Mapped(Dictionary spans, ResourceRuntimeInputs inputs) + { + foreach (var span in spans.Values) + if (inputs.IsRangeMapped?.Invoke(span.Base, span.Size) != true) return false; + return true; + } + + private DeviceRecordCountPlan(ScalarValueGraph graph, Dictionary handles) + { + _handles = handles; + _skipCounts = handles.Values.ToHashSet(); + _pcs = handles.Keys.Select(index => graph.Memory[index].Pc).ToHashSet(); + } + + public bool Contains(int memoryIndex) => _handles.ContainsKey(memoryIndex); + public bool SkipCount(ScalarValue handle) => _skipCounts.Contains(handle); + + // The alternate ordinary plan handles descriptor modes the device raw-buffer lowering does not support. + // This reads only expressions proven independent of guest memory during Create. + public bool SupportsDescriptors(ShaderResourcePlan plan, ResourceRuntimeInputs inputs) + { + using var scratch = RuntimeEvaluationScratch.Rent(); + var evaluator = new RuntimeValueEvaluator(scratch, plan, inputs); + foreach (var handle in _handles.Values) + if (!evaluator.Evaluate(handle.Operands[1], out var high) || !evaluator.Evaluate(handle.Operands[3], out var format) || + (high & 0x80000000) != 0 || (format & (1u << 23)) != 0) return false; + return true; + } + + public static DeviceRecordCountPlan? Create(ScalarValueGraph graph, ShaderStage stage) + { + if (stage != ShaderStage.Compute || graph.CallArgumentRegisters != 0 || graph.Program.IsFusedProgram || + Gen5ShaderCallLinker.IsLinked(graph.Program) || graph.Program.Instructions.Count > 2048 || + graph.Program.Instructions.Any(instruction => instruction.Opcode is "SSetpcB64" or "SSwappcB64" or "SRfeB64")) + return null; + var handles = new Dictionary(); + for (var index = 0; index < graph.Accesses.Length; index++) + { + var memory = graph.Memory[index]; + if (memory.Kind != MemoryResourceKind.Buffer || memory.Typed || memory.Formatted || + memory.Access is not (MemoryAccess.Read or MemoryAccess.Write) || + !(memory.Opcode.StartsWith("BufferLoadDword", StringComparison.Ordinal) || + memory.Opcode.StartsWith("BufferStoreDword", StringComparison.Ordinal)) || + graph.Accesses[index]?.Handle is not { Kind: ScalarValueKind.BufferHandle, Operands.Length: 4 } handle || + (graph.ResolveInvariantPhi(handle.Operands[2]) ?? handle.Operands[2]) is not { Kind: ScalarValueKind.ScalarBufferWord } count || + !MemoryFree(graph, handle.Operands[0], []) || !MemoryFree(graph, handle.Operands[1], []) || !MemoryFree(graph, handle.Operands[3], []) || + count.Operands.Length != 2 || !count.Operands[1].IsConstant || + !count.Operands[0].Operands.All(value => MemoryFree(graph, value, []))) continue; + handles.Add(index, handle); + } + return handles.Count == 0 ? null : new(graph, handles); + } + + private static bool MemoryFree(ScalarValueGraph graph, ScalarValue value, HashSet visiting) + { + // Unmodified inputs and counts may cross loop headers. Resolve only proven invariant phis; + // a varying count/base still refuses admission and follows the ordinary plan. + value = graph.ResolveInvariantPhi(value) ?? value; + if (value.IsConstant || value.Kind is ScalarValueKind.UserData or ScalarValueKind.ShaderBase) return true; + if (value.Kind != ScalarValueKind.Operation || !RuntimeValueValidator.IsUniformOperation(value.Operation) || + !visiting.Add(value)) return false; + var result = value.Operands.All(operand => MemoryFree(graph, operand, visiting)); + visiting.Remove(value); + return result; + } + + internal DeviceAddressRange[] Append(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, DeviceAddressRange[] ordinary) + { + Dictionary? spans = null; + if (inputs.ComputeState is { HasPartialWorkgroups: false, DeviceCountProof: true, Dispatch: { } dispatch }) + { + // Indexing marks every input in the materialization cache's dependency recorder, even on a proof-cache hit. + lock (_gate) + { + if (_inputWords.Length != inputs.UserData.Count) _inputWords = new uint[inputs.UserData.Count]; + for (var index = 0; index < inputs.UserData.Count; index++) + _inputWords[index] = inputs.UserData[index]; + bool Matches(ProofEntry? entry) => entry is not null && entry.Dispatch == dispatch && + _inputWords.AsSpan().SequenceEqual(entry.UserData); + var cached = _proofs[0]; + if (!Matches(cached)) + { + cached = null; + for (var index = 1; index < _proofs.Length; index++) + { + var entry = _proofs[index]; + if (!Matches(entry)) continue; + cached = entry; + Array.Copy(_proofs, 0, _proofs, 1, index); + _proofs[0] = entry; + break; + } + } + if (cached is null) + { + // A bounded LRU retains alternating dispatch shapes and refusals. It stores only mathematics; + // current mappings and the actual count fallback are still checked below on every evaluation. + var userData = (uint[])_inputWords.Clone(); + cached = new(userData, dispatch); + Array.Copy(_proofs, 0, _proofs, 1, _proofs.Length - 1); + _proofs[0] = cached; + var pending = cached; + // The closure owns only immutable analysis inputs, never readers, mappings or GPU state. + var program = plan.Graph.Program; + var userDataBase = plan.Graph.UserDataBase; + if (!QueueProof(() => PrepareProof(program, userDataBase, pending))) + { + _proofs[0] = null; // Queue pressure is temporary: retry on a later dispatch. + // The cached fallback must retry admission too, even when its count word stays unchanged. + Interlocked.Increment(ref _proofRevision); + } + } + spans = cached.Spans; + } + } + // Use one eligibility state for all selected ranges. Materialization-cache hits check it too, + // including unmap/remap changes after an immutable mathematical proof was published. + if (spans is not null && !Mapped(spans, inputs)) spans = null; + var result = new List(ordinary); + using var scratch = RuntimeEvaluationScratch.Rent(); + var evaluator = new RuntimeValueEvaluator(scratch, plan, inputs); + var seen = new HashSet<(ulong Base, ulong Size, bool Written)>(); + foreach (var (index, handle) in _handles) + { + if (!evaluator.Evaluate(handle.Operands[0], out var low) || !evaluator.Evaluate(handle.Operands[1], out var high) || + !evaluator.Evaluate(handle.Operands[3], out var format)) + throw new ResourcePlanException("The device-count buffer address cannot be resolved."); + var address = low | ((ulong)(high & 0xFFFF) << 32); + if ((high & 0x80000000) != 0 || (format & (1u << 23)) != 0) + throw new ResourcePlanException("The device-count buffer uses unsupported swizzling or thread indices."); + ulong size; + var memory = plan.Memory[index]; + if (spans is not null && !spans.ContainsKey(memory.Pc)) // All paths proved inactive. + { + continue; + } + if (spans is not null && spans.TryGetValue(memory.Pc, out var span) && span.Base == address && + inputs.IsRangeMapped?.Invoke(address, span.Size) == true) + { + size = span.Size; + } + else + { + // Same device-descriptor shader, exact original residency and synchronization when the proof refuses. + if (!evaluator.Evaluate(handle.Operands[2], out var count)) + throw new ResourcePlanException("The device-count buffer fallback count cannot be resolved."); + size = (ulong)count * Math.Max((high >> 16) & 0x3FFF, 1u); + } + if (size == 0) continue; + if (size > 0x1_0000_0000_0000ul - address) + throw new ResourcePlanException("The device-count buffer wraps the guest address space."); + var written = memory.Access == MemoryAccess.Write; + if (seen.Add((address, size, written))) result.Add(new((uint)result.Count, address, size, true, written)); + } + return result.ToArray(); + } + + private void PrepareProof(Gen5ShaderProgram program, uint userDataBase, ProofEntry pending) + { + var proved = DispatchBufferFootprint.TryEvaluate(program, pending.UserData, userDataBase, + pending.Dispatch, _pcs, out var spans); + lock (_gate) + { + if (!proved || !_proofs.Contains(pending)) return; + pending.Spans = spans; + // Previously cached exact-count snapshots must discover the new proof on their next use. + Interlocked.Increment(ref _proofRevision); + } + } +} diff --git a/src/SharpEmu.ShaderCompiler/Resources/DispatchBufferFootprint.Word.cs b/src/SharpEmu.ShaderCompiler/Resources/DispatchBufferFootprint.Word.cs new file mode 100644 index 000000000..20760aeb5 --- /dev/null +++ b/src/SharpEmu.ShaderCompiler/Resources/DispatchBufferFootprint.Word.cs @@ -0,0 +1,72 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.ShaderCompiler.Resources; + +public static partial class DispatchBufferFootprint +{ + private readonly record struct Word(uint Min, uint Max) + { + public static Word Unknown => new(0, uint.MaxValue); + public static Word Of(uint value) => new(value, value); + public bool Exact => Min == Max; + public Word Join(Word other) => new(Math.Min(Min, other.Min), Math.Max(Max, other.Max)); + public Word Not() => new(uint.MaxValue - Max, uint.MaxValue - Min); + + public static Word Binary(string operation, Word a, Word b) + { + if (a.Exact && b.Exact) + { + var x = a.Min; var y = b.Min; + return Of(operation switch + { + "add" => unchecked(x + y), "sub" => unchecked(x - y), "mul" => unchecked(x * y), + "hi" => (uint)((ulong)x * y >> 32), "and" => x & y, "or" => x | y, "xor" => x ^ y, + "shl" => x << (int)(y & 31), "shr" => x >> (int)(y & 31), + _ => throw new ArgumentOutOfRangeException(nameof(operation)), + }); + } + switch (operation) + { + case "add" when (ulong)a.Max + b.Max <= uint.MaxValue: return new(a.Min + b.Min, a.Max + b.Max); + case "sub" when a.Min >= b.Max: return new(a.Min - b.Max, a.Max - b.Min); + case "mul" when (ulong)a.Max * b.Max <= uint.MaxValue: return new(a.Min * b.Min, a.Max * b.Max); + case "hi": return new((uint)((ulong)a.Min * b.Min >> 32), (uint)((ulong)a.Max * b.Max >> 32)); + case "and": return new(0, Math.Min(a.Max, b.Max)); + case "or": case "xor": + var top = Math.Max(a.Max, b.Max); + top |= top >> 1; top |= top >> 2; top |= top >> 4; top |= top >> 8; top |= top >> 16; + return new(0, top); + case "shr" when b.Exact: return new(a.Min >> (int)(b.Min & 31), a.Max >> (int)(b.Min & 31)); + case "shl" when b.Exact && (ulong)a.Max << (int)(b.Min & 31) <= uint.MaxValue: + return new(a.Min << (int)(b.Min & 31), a.Max << (int)(b.Min & 31)); + default: return Unknown; + } + } + + public static Word Compare(string operation, Word a, Word b) + { + switch (operation) + { + case "eq": + if (a.Max < b.Min || b.Max < a.Min) return Of(0); + if (a.Exact && a == b) return Of(1); + break; + case "ne": + var equal = Compare("eq", a, b); + return equal.Exact ? Of(1 - equal.Min) : equal; + case "lt": + if (a.Max < b.Min) return Of(1); + if (a.Min >= b.Max) return Of(0); + break; + case "le": + if (a.Max <= b.Min) return Of(1); + if (a.Min > b.Max) return Of(0); + break; + case "gt": return Compare("lt", b, a); + case "ge": return Compare("le", b, a); + } + return new(0, 1); + } + } +} diff --git a/src/SharpEmu.ShaderCompiler/Resources/DispatchBufferFootprint.cs b/src/SharpEmu.ShaderCompiler/Resources/DispatchBufferFootprint.cs new file mode 100644 index 000000000..2f2871af7 --- /dev/null +++ b/src/SharpEmu.ShaderCompiler/Resources/DispatchBufferFootprint.cs @@ -0,0 +1,389 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.ShaderCompiler.Resources; + +// Abstract execution of address calculations, never execution of guest memory. Loaded data is +// unknown. The result includes every path and lane, including paths disabled by a device count. +// Refusing a program or exhausting the analysis budget leaves its ordinary host count read intact. +public static partial class DispatchBufferFootprint +{ + public readonly record struct Span(ulong Base, ulong Size); + public sealed record Dispatch(uint GroupsX, uint GroupsY, uint GroupsZ, + uint ThreadsX, uint ThreadsY, uint ThreadsZ, uint WaveSize, int ThreadIdCount, + Gen5ComputeSystemRegisters Registers); + + public static bool TryEvaluate(Gen5ShaderProgram program, IReadOnlyList userData, uint userDataBase, + Dispatch dispatch, IReadOnlySet accesses, out Dictionary spans) + { + spans = []; + if (program.IsFusedProgram || program.FunctionBufferAccesses.Count != 0 || + dispatch.GroupsX == 0 || dispatch.GroupsX > 256 || dispatch.GroupsY != 1 || dispatch.GroupsZ != 1 || + dispatch.ThreadsX == 0 || dispatch.ThreadsX > 1024 || dispatch.ThreadsY != 1 || dispatch.ThreadsZ != 1 || + dispatch.WaveSize is not (32 or 64) || dispatch.ThreadIdCount != 1 || + dispatch.Registers.ThreadGroupSizeRegister.HasValue || userDataBase + (ulong)userData.Count > 106 || + program.Instructions.Count == 0 || program.Instructions.Count > 2048) + return false; + + var instructions = program.Instructions.ToDictionary(instruction => instruction.Pc); + var steps = 0; + for (uint group = 0; group < dispatch.GroupsX; group++) + { + var groupSteps = 0; + var initial = new State(program.Instructions[0].Pc) { FullHigh = dispatch.WaveSize == 64 ? uint.MaxValue : 0 }; + for (var index = 0; index < userData.Count; index++) initial.S[userDataBase + index] = Word.Of(userData[index]); + void SystemRegister(uint? register, uint value) + { + if (register is < 106) initial.S[register.Value] = Word.Of(value); + } + SystemRegister(dispatch.Registers.WorkGroupXRegister, group); + SystemRegister(dispatch.Registers.WorkGroupYRegister, 0); + SystemRegister(dispatch.Registers.WorkGroupZRegister, 0); + initial.S[126] = Word.Of(uint.MaxValue); + initial.S[127] = Word.Of(dispatch.WaveSize == 64 ? uint.MaxValue : 0); + initial.V[0] = new(0, dispatch.ThreadsX - 1); + var pending = new Stack(); + var visited = new HashSet(); + void Queue(State state) + { + if (visited.Add(state)) pending.Push(state.Copy()); + } + Queue(initial); + while (pending.TryPop(out var state)) + { + while (true) + { + // Groups have independent state. Bound each group and the entire background job separately. + if (++steps > 1_048_576 || ++groupSteps > 256_000) return false; + if (visited.Count > 4096) return false; + if (!instructions.TryGetValue(state.Pc, out var instruction)) return false; + var next = instruction.Pc + (uint)instruction.Words.Count * 4; + var opcode = instruction.Opcode; + if (opcode == "SEndpgm") break; + if (opcode is "SBranch" or "SCbranchScc0" or "SCbranchScc1" or "SCbranchExecz" or "SCbranchExecnz") + { + var condition = opcode == "SBranch" ? Word.Of(1) : opcode.Contains("Scc", StringComparison.Ordinal) + ? state.Scc : state.Active switch { 0 => Word.Of(0), 1 => Word.Of(1), _ => new Word(0, 1) }; + var want = opcode is "SCbranchScc0" or "SCbranchExecz" ? 0u : 1u; + var target = unchecked(instruction.Pc + 4 + (uint)((short)instruction.Words[0] * 4)); + if (condition.Min <= want && condition.Max >= want) + { + var taken = state.Copy(); + taken.Pc = target; + if (opcode == "SCbranchExecz") taken.S[126] = taken.S[127] = Word.Of(0); + Queue(taken); + } + if (!condition.Exact || condition.Min != want) + { + state.Pc = next; + Queue(state); + } + // Both successors use the same deduplication. Continuing the fallthrough inline + // repeated entire loops when earlier arithmetic alternatives had already converged. + break; + } + else if (opcode is "SNop" or "SInstPrefetch" or "SWaitcnt" or "SBarrier") { } + else if (instruction.Control is Gen5ScalarMemoryControl) + { + foreach (var destination in instruction.Destinations) state.Write(destination, Word.Unknown, vectorMasked: false); + } + else if (instruction.Control is Gen5BufferMemoryControl buffer) + { + if (accesses.Contains(instruction.Pc) && state.Active != 0) + { + if (!TrySpan(state, instruction, buffer, out var span)) return false; + if (spans.TryGetValue(instruction.Pc, out var previous)) + { + if (previous.Base != span.Base) return false; + span = span with { Size = Math.Max(span.Size, previous.Size) }; + } + spans[instruction.Pc] = span; + } + foreach (var destination in instruction.Destinations) state.Write(destination, Word.Unknown); + } + else if (instruction.Control is Gen5DataShareControl { Gds: false }) + { + foreach (var destination in instruction.Destinations) state.Write(destination, Word.Unknown); + } + else if (instruction.Encoding is Gen5ShaderEncoding.Sop1 or Gen5ShaderEncoding.Sop2 or Gen5ShaderEncoding.Sopc) + { + if (!Scalar(state, instruction)) return false; + } + else if (instruction.Encoding is Gen5ShaderEncoding.Vop1 or Gen5ShaderEncoding.Vop2 or Gen5ShaderEncoding.Vop3 or Gen5ShaderEncoding.Vopc) + { + if (!Vector(state, instruction, next, Queue)) return false; + } + else return false; + state.Pc = next; + } + } + } + // A selected access can be unreachable for these inputs; its empty span needs no residency. + return true; + } + + private static bool TrySpan(State state, Gen5ShaderInstruction instruction, Gen5BufferMemoryControl buffer, out Span span) + { + span = default; + if (buffer.Typed || buffer.DwordCount is 0 or > 4 || buffer.OffsetBytes < 0 || + buffer.VectorAddress > (buffer.IndexEnabled && buffer.OffsetEnabled ? 254u : 255u) || + !(instruction.Opcode.StartsWith("BufferLoadDword", StringComparison.Ordinal) || + instruction.Opcode.StartsWith("BufferStoreDword", StringComparison.Ordinal)) || buffer.ScalarResource > 124) + return false; + var low = state.S[buffer.ScalarResource]; + var high = state.S[buffer.ScalarResource + 1]; + var format = state.S[buffer.ScalarResource + 3]; + if (!low.Exact || !high.Exact || !format.Exact || (high.Min & 0x80000000) != 0 || (format.Min & (1u << 23)) != 0) + return false; + var index = buffer.IndexEnabled ? state.V[buffer.VectorAddress] : Word.Of(0); + var offset = buffer.OffsetEnabled ? state.V[buffer.VectorAddress + (buffer.IndexEnabled ? 1u : 0u)] : Word.Of(0); + var scalar = instruction.Sources.Count > 2 ? state.Read(instruction.Sources[2]) : Word.Of(0); + var stride = (high.Min >> 16) & 0x3FFF; + var size = (ulong)index.Max * stride + offset.Max + scalar.Max + (uint)buffer.OffsetBytes + buffer.DwordCount * 4; + // No modulo-address inference and no guessed cap: outside the analysis budget the caller reads the true count. + var address = low.Min | ((ulong)(high.Min & 0xFFFF) << 32); + if (size > DeviceAddressRangePlanner.MaxRangeBytes || size > 0x1_0000_0000_0000ul - address) return false; + span = new(address, size); + return true; + } + + private static bool Scalar(State state, Gen5ShaderInstruction instruction) + { + var opcode = instruction.Opcode; + var a = instruction.Sources.Count > 0 ? state.Read(instruction.Sources[0]) : Word.Unknown; + var b = instruction.Sources.Count > 1 ? state.Read(instruction.Sources[1]) : Word.Unknown; + if (instruction.Encoding == Gen5ShaderEncoding.Sopc) + { + var comparison = opcode switch + { + "SCmpEqU32" => "eq", "SCmpLgU32" => "ne", "SCmpLtU32" => "lt", + "SCmpLeU32" => "le", "SCmpGtU32" => "gt", "SCmpGeU32" => "ge", _ => null, + }; + if (comparison is null) return false; + state.Scc = Word.Compare(comparison, a, b); + return true; + } + if (instruction.Destinations is not [{ Kind: Gen5OperandKind.ScalarRegister } destination] || destination.Value >= 127) + return false; + var width = opcode.EndsWith("B64", StringComparison.Ordinal) ? 2 : 1; + var oldCondition = state.Scc; + // Read every source before writing an overlapping pair. + var ah = instruction.Sources.Count > 0 ? state.High(instruction.Sources[0]) : Word.Unknown; + var bh = instruction.Sources.Count > 1 ? state.High(instruction.Sources[1]) : Word.Unknown; + for (var component = 0; component < width; component++) + { + var left = component == 0 ? a : ah; + var right = component == 0 ? b : bh; + Word result; + switch (opcode) + { + case "SMovB32": case "SMovB64": result = left; break; + case "SNotB32": case "SNotB64": result = left.Not(); break; + case "SCselectB32": case "SCselectB64": + result = oldCondition.Exact ? (oldCondition.Min == 0 ? right : left) : left.Join(right); break; + case "SBitset1B32": result = Word.Binary("or", state.S[destination.Value], Word.Binary("shl", Word.Of(1), left)); break; + case "SLshl1AddU32": result = Word.Binary("add", Word.Binary("shl", left, Word.Of(1)), right); break; + default: + var operation = opcode switch + { + "SLshlB32" => "shl", "SLshrB32" => "shr", "SAddI32" or "SAddU32" => "add", + "SSubI32" or "SSubU32" => "sub", "SMulI32" => "mul", "SMulHiU32" => "hi", + "SAndB32" or "SAndB64" or "SAndn2B64" => "and", "SOrB32" or "SOrB64" or "SNorB64" => "or", + "SXorB32" or "SXorB64" => "xor", _ => null, + }; + if (operation is null) return false; + result = Word.Binary(operation, left, opcode == "SAndn2B64" ? right.Not() : right); + if (opcode == "SNorB64") result = result.Not(); + break; + } + state.S[destination.Value + component] = result; + } + // Instructions that leave SCC unchanged must preserve a preceding comparison. + if (opcode is not ("SMovB32" or "SMovB64" or "SCselectB32" or "SCselectB64" or "SMulI32" or "SMulHiU32" or "SBitset1B32")) + state.Scc = new(0, 1); + return true; + } + + private static bool Vector(State state, Gen5ShaderInstruction instruction, uint next, Action queue) + { + var opcode = instruction.Opcode; + if (opcode.StartsWith("VCmp", StringComparison.Ordinal)) + { + if (opcode.StartsWith("VCmpx", StringComparison.Ordinal)) + { + // GFX10 CMPX writes EXEC, not VCC. A comparison cannot activate an inactive lane. + if (state.Active != 0) state.S[126] = state.S[127] = Word.Unknown; + } + else + { + var destination = instruction.Control switch + { + Gen5SdwaControl { ScalarDestination: { } register } => register, + Gen5Vop3Control { ScalarDestination: { } register } => register, + _ => 106u, + }; + if (destination >= 127) return false; + state.S[destination] = state.S[destination + 1] = Word.Unknown; + } + return true; + } + if (instruction.Destinations.Count != 1) return false; + var dest = instruction.Destinations[0]; + var a = instruction.Sources.Count > 0 ? state.Read(instruction.Sources[0]) : Word.Unknown; + var b = instruction.Sources.Count > 1 ? state.Read(instruction.Sources[1]) : Word.Unknown; + var c = instruction.Sources.Count > 2 ? state.Read(instruction.Sources[2]) : Word.Unknown; + var plain = instruction.Control is null or Gen5Vop3Control + { AbsoluteMask: 0, NegateMask: 0, OutputModifier: 0, Clamp: false, OperandSelect: 0 }; + if (!plain) + { + // Modifiers/permutations are not interpreted. Poison the full destination, including SDWA preserve bits. + if (dest.Kind != Gen5OperandKind.VectorRegister) return false; + state.Write(dest, Word.Unknown); + if (opcode == "VAddI32") state.S[106] = state.S[107] = Word.Unknown; + if (instruction.Control is Gen5Vop3Control { ScalarDestination: { } poisonScalar }) + { + if (poisonScalar >= 127) return false; + state.S[poisonScalar] = state.S[poisonScalar + 1] = Word.Unknown; + } + return true; + } + if (opcode == "VReadfirstlaneB32") + { + // Undefined when no lane executes. Unknown also covers the implementation's inactive-lane behavior. + state.Write(dest, state.Active == 0 ? Word.Unknown : a, vectorMasked: false); + return true; + } + if (dest.Kind != Gen5OperandKind.VectorRegister) return false; + Word result; + switch (opcode) + { + case "VMovB32": result = a; break; + case "VCndmaskB32": result = a.Join(b); break; + case "VAndB32": result = Word.Binary("and", a, b); break; + case "VXorB32": result = Word.Binary("xor", a, b); break; + case "VAddI32": case "VAddU32": result = Word.Binary("add", a, b); break; + case "VLshlrevB32": result = Word.Binary("shl", b, a); break; + case "VLshrrevB32": result = Word.Binary("shr", b, a); break; + case "VLshlAddU32": result = Word.Binary("add", Word.Binary("shl", a, b), c); break; + case "VLshlOrU32": result = Word.Binary("or", Word.Binary("shl", a, b), c); break; + case "VCvtF32U32": case "VRcpIflagF32": case "VMulF32": case "VCvtU32F32": + if (!FloatResults(opcode, a, b, out var first, out var last)) return false; + // Retain correlation through integer reciprocal/division sequences. An interval here would lose it. + for (var bits = first; bits < last; bits++) + { + var alternative = state.Copy(); + alternative.Write(dest, Word.Of(bits)); + alternative.Pc = next; + queue(alternative); + } + result = Word.Of(last); + break; + default: return false; + } + state.Write(dest, result); + // VOP2 integer carry and VOP3B pair outputs must not leave old masks behind. + if (instruction.Control is Gen5Vop3Control { ScalarDestination: { } scalar }) + { + if (scalar >= 127) return false; + state.S[scalar] = state.S[scalar + 1] = Word.Unknown; + } + else if (opcode == "VAddI32") state.S[106] = state.S[107] = Word.Unknown; + return true; + } + + private static bool FloatResults(string opcode, Word a, Word b, out uint first, out uint last) + { + first = last = 0; + if (!a.Exact) return false; + if (opcode == "VCvtU32F32") + { + var value = BitConverter.UInt32BitsToSingle(a.Min); + first = last = float.IsNaN(value) || value <= 0 ? 0 : value >= 4294967296d ? uint.MaxValue : (uint)value; + return true; + } + if (opcode == "VCvtF32U32") + { + // Exact integer conversion needs no floating-point rounding-mode assumptions. + var converted = (float)a.Min; + if ((double)converted != a.Min) return false; + first = last = BitConverter.SingleToUInt32Bits(converted); + return true; + } + var left = BitConverter.UInt32BitsToSingle(a.Min); + if (!float.IsNormal(left) || left <= 0) return false; + double exact; + uint radius; + if (opcode == "VRcpIflagF32") + { + if (left < Math.ScaleB(1, -126) || left > Math.ScaleB(1, 126)) return false; + exact = 1d / left; + // Vulkan OpFDiv permits 2.5 ULP. Eight adjacent representations also cover a binade boundary. + radius = 8; + } + else + { + if (!b.Exact) return false; + var right = BitConverter.UInt32BitsToSingle(b.Min); + if (!float.IsNormal(right) || right <= 0) return false; + exact = (double)left * right; + radius = 1; // Both directed and nearest rounding of the exact 48-bit product. + } + var center = BitConverter.SingleToUInt32Bits((float)exact); + if (center < 0x00800000 + radius || center >= 0x7F800000 - radius) return false; + first = center - radius; + last = center + radius; + return true; + } + + private sealed class State(uint pc) : IEquatable + { + public uint Pc = pc; + public Word[] S = Enumerable.Repeat(Word.Unknown, 128).ToArray(); + public Word[] V = Enumerable.Repeat(Word.Unknown, 256).ToArray(); + public Word Scc = new(0, 1); + public uint FullHigh; + public int Active => S[126].Max == 0 && S[127].Max == 0 ? 0 : + S[126].Exact && S[126].Min == uint.MaxValue && S[127].Exact && S[127].Min == FullHigh ? 1 : 2; + public State Copy() + { + var copy = (State)MemberwiseClone(); + copy.S = (Word[])S.Clone(); copy.V = (Word[])V.Clone(); + return copy; + } + public Word Read(Gen5Operand operand) => operand.Kind switch + { + Gen5OperandKind.ScalarRegister when operand.Value < 128 => S[operand.Value], + Gen5OperandKind.VectorRegister when operand.Value < 256 => V[operand.Value], + Gen5OperandKind.LiteralConstant => Word.Of(operand.Value), + Gen5OperandKind.EncodedConstant when Gen5InlineConstants.TryDecode(operand.Value, out var value) => Word.Of(value), + _ => Word.Unknown, + }; + public Word High(Gen5Operand operand) => operand.Kind switch + { + Gen5OperandKind.ScalarRegister when operand.Value < 127 => S[operand.Value + 1], + Gen5OperandKind.EncodedConstant when operand.Value is >= 193 and <= 208 => Word.Of(uint.MaxValue), + Gen5OperandKind.EncodedConstant when Gen5InlineConstants.IsAperture(operand.Value) => Word.Of((uint)(Gen5InlineConstants.DecodeAperture64(operand.Value) >> 32)), + Gen5OperandKind.EncodedConstant or Gen5OperandKind.LiteralConstant => Word.Of(0), + _ => Word.Unknown, + }; + public void Write(Gen5Operand destination, Word value, bool vectorMasked = true) + { + if (destination.Kind == Gen5OperandKind.ScalarRegister && destination.Value < 128) S[destination.Value] = value; + else if (destination.Kind == Gen5OperandKind.VectorRegister && destination.Value < 256) + { + if (!vectorMasked || Active == 1) V[destination.Value] = value; + else if (Active == 2) V[destination.Value] = V[destination.Value].Join(value); + } + } + public bool Equals(State? other) => other is not null && Pc == other.Pc && Scc == other.Scc && + S.AsSpan().SequenceEqual(other.S) && V.AsSpan().SequenceEqual(other.V); + public override bool Equals(object? other) => other is State state && Equals(state); + public override int GetHashCode() + { + var hash = new HashCode(); hash.Add(Pc); hash.Add(Scc); + foreach (var word in S) hash.Add(word); + foreach (var word in V) hash.Add(word); + return hash.ToHashCode(); + } + } +} diff --git a/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs b/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs index 28dec61a6..d9eaa1c13 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs @@ -547,11 +547,8 @@ private DeviceAddressRange RangeOf(DeviceAddressRangePlan range, int index, ulon var low = _rangeLow[index]; var high = _rangeHigh[index]; var plannedRange = low >= 0 && valid[low] && valid[high]; - var handleBase = plannedRange ? ((uint)values[low] | ((ulong)(uint)values[high] << 32)) & AddressMask : 0; - var firstByte = range.Bounded ? range.FirstByte : Math.Min(range.FirstByte, 0); - var baseAddress = plannedRange ? unchecked(handleBase + (ulong)firstByte) & AddressMask : 0; - var size = range.Bounded ? range.Extent : DeviceAddressRangePlanner.MaxRangeBytes; - return new DeviceAddressRange(range.Handle, baseAddress, plannedRange ? size : 0, plannedRange, range.Written); + return DeviceAddressRangePlanner.EvaluateRange(range, plannedRange, + plannedRange ? (uint)values[low] : 0, plannedRange ? (uint)values[high] : 0); } private bool Run(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, int additionalTableWords, Scratch scratch, bool[] activeSources, diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceBranchBlock.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceBranchBlock.cs index 2dd09548e..f8a449a4d 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceBranchBlock.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceBranchBlock.cs @@ -7,10 +7,20 @@ namespace SharpEmu.ShaderCompiler.Resources; public sealed record ResourceBranchBlock(ScalarValue? Condition, int[] Successors, uint[] Sources) { + // SHARPEMU_BRANCHES_WITH_WRITES (on by default; =0 turns it off): a shader that writes memory keeps its blocks too + // when every write goes through a static buffer descriptor or to LDS or scratch; each dispatch checks those + // buffers' records against the words its predicates read (ResourceBranchWriteGuard). Tests set the override. + private static readonly bool WritesConfigured = Environment.GetEnvironmentVariable("SHARPEMU_BRANCHES_WITH_WRITES") != "0"; + [ThreadStatic] internal static bool? WritesOverride; + internal static bool WritesAllowed => WritesOverride ?? WritesConfigured; + + internal static bool Writes(ShaderResourcePlan plan) => + plan.Memory.Entries.Any(access => access.Access is MemoryAccess.Write or MemoryAccess.Atomic); + internal static IReadOnlyList Build(ShaderResourcePlan plan, Func rewrite) { // A shader write can change a predicate through an alias or a later loop iteration. - if (plan.Memory.Entries.Any(access => access.Access is MemoryAccess.Write or MemoryAccess.Atomic)) return []; + if (Writes(plan) && WrittenBuffers(plan) is null) return []; var instructions = plan.Graph.Program.Instructions; if (instructions.Any(instruction => instruction.Opcode is "SSetpcB64" or "SSwappcB64" or "SRfeB64" or "SCbranchJoin" or "SCbranchIFork" or "SCbranchGFork")) return []; @@ -71,4 +81,23 @@ internal static IReadOnlyList Build(ShaderResourcePlan plan return hasCondition ? blocks : []; } + + // The static buffers a shader writes through, when writes are allowed and every write and atomic goes through one of + // them or to LDS or scratch, which no scalar load reads; otherwise null. + internal static uint[]? WrittenBuffers(ShaderResourcePlan plan) + { + if (!WritesAllowed) return null; + var buffers = new SortedSet(); + foreach (var access in plan.Memory.Entries) + { + if (access.Access is not (MemoryAccess.Write or MemoryAccess.Atomic) || + access.Kind is MemoryResourceKind.LocalDataShare or MemoryResourceKind.Scratch) continue; + if (access.Kind != MemoryResourceKind.Buffer || access.DeviceDescriptor || + access.BufferDescriptor is not { Provenance: BufferDescriptorProvenance.Static } descriptor || + descriptor.StaticResource >= plan.Info.Buffers.Count) return null; + buffers.Add(descriptor.StaticResource); + } + + return [.. buffers]; + } } diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceBranchWriteGuard.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceBranchWriteGuard.cs new file mode 100644 index 000000000..289c4e5b8 --- /dev/null +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceBranchWriteGuard.cs @@ -0,0 +1,73 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.ShaderCompiler.Resources; + +// SHARPEMU_BRANCHES_WITH_WRITES (on by default, =0 off): the branch selection of a plan that writes memory +// (ResourceBranchBlock.WrittenBuffers), including one that writes only LDS or scratch. Its predicates are read through +// a clean reader that keeps their addresses, and the selection stands only when no written buffer can reach one of +// them: each buffer's records, 256 bytes wider on each side, cover none of those words. A written descriptor the clean +// reader cannot read, or one that swizzles or adds the thread id, keeps every source active, as with the switch off. +public sealed class ResourceBranchWriteGuard : IDisposable +{ + private const ulong Margin = 256; + + private readonly ShaderResourcePlan _plan; + private readonly GuestWordReader _clean; + private readonly List _reads = []; + private readonly RuntimeEvaluationScratch _scratch = RuntimeEvaluationScratch.Rent(); + + internal ResourceBranchWriteGuard(ShaderResourcePlan plan, ResourceRuntimeInputs inputs) + { + _plan = plan; + _clean = inputs.ReadCleanMemory!; + Evaluator = new RuntimeValueEvaluator(_scratch, plan, new ResourceRuntimeInputs + { + UserData = inputs.UserData, ShaderBase = inputs.ShaderBase, ReadMemory = Record, ReadCleanMemory = Record, + ComputeState = inputs.ComputeState, IsRangeMapped = inputs.IsRangeMapped, ReadsClean = true, + }); + } + + // Evaluates the predicates as the selection's clean evaluator does. + internal RuntimeValueEvaluator Evaluator { get; } + + private bool Record(ulong address, out uint word) + { + if (!_clean(address, out word)) return false; + _reads.Add(address); + return true; + } + + // Whether the selection made through Evaluator stands for this dispatch. + internal bool Holds() + { + var predicateReads = _reads.Count; + Span words = stackalloc uint[4]; + foreach (var buffer in _plan.ResourceBranchWrites) + { + var source = _plan.DescriptorSources[(int)_plan.Info.Buffers[(int)buffer].Source]; + if (source.DwordCount != 4) return false; + for (var index = 0; index < 4; index++) + { + if (!Evaluator.Evaluate(source.Dwords[index], out words[index])) return false; + } + + // A descriptor that is not a buffer is bound as null (ResourceMaterializer.BuildSpecialization): nothing is written. + if ((words[3] >> 30) != 0) continue; + if ((words[1] >> 31) != 0 || ((words[3] >> 23) & 1) != 0) return false; + var stride = (words[1] >> 16) & 0x3FFFu; + var size = stride == 0 ? words[2] : (ulong)stride * words[2]; + var start = words[0] | ((ulong)(words[1] & 0xFFFF) << 32); + var low = start > Margin ? start - Margin : 0; + var high = start + size + Margin; + for (var index = 0; index < predicateReads; index++) + { + if (_reads[index] + sizeof(uint) > low && _reads[index] < high) return false; + } + } + + return true; + } + + public void Dispose() => _scratch.Dispose(); +} diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializationCache.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializationCache.cs index e996f983e..7890b7193 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializationCache.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializationCache.cs @@ -292,6 +292,7 @@ public ResourceSnapshot PatchMemoryBases(ResourceSnapshot snapshot, List<(int Bu FlattenedResourceTable = table ?? snapshot.FlattenedResourceTable, UserData = snapshot.UserData, DeviceAddressRanges = snapshot.DeviceAddressRanges, + Heaps = snapshot.Heaps, }; } @@ -508,6 +509,7 @@ public ResourceSnapshot Apply(ResourceSnapshot snapshot, IReadOnlyList use FlattenedResourceTable = snapshot.FlattenedResourceTable, UserData = snapshot.UserData, DeviceAddressRanges = snapshot.DeviceAddressRanges, + Heaps = snapshot.Heaps, Origin = snapshot.Origin, }; } @@ -1158,6 +1160,8 @@ private bool MaterializeCore( out ResourceMaterializationFailure failure, ref MaterializationTiming timing) { + if (plan.DeviceRecordCounts is { } counts && inputs.ComputeState is { } compute) + inputs = inputs.WithComputeState(compute with { DeviceCountProofRevision = counts.MaterializationRevision(inputs) }); // A frontend image conversion can depend on GPU attachments or detile guest // texels. Unchanged descriptor bytes do not prove that its result is current. if (plan.NormalizeImageDescriptor is not null && plan.Info.Images.Count != 0 && plan.ImageNormalizationVersion is null) @@ -1310,6 +1314,8 @@ private bool MaterializeCore( refreshed.Next = cached; CountDiagnostic(Diagnostic.RefreshOlderVariant); } + // Learning history may still own this replaced entry, but not its variant chain. + variant.Next = null; Store(key, refreshed); _outcome = MaterializeOutcome.TableRefresh; TableRefreshes++; @@ -1374,6 +1380,7 @@ private bool MaterializeCore( ReadsClean = inputs.ReadsClean, ComputeState = inputs.ComputeState, TablePhase = recorder.TablePhase, + IsRangeMapped = inputs.IsRangeMapped, }; if (!ResourceMaterializer.Materialize(plan, recording, ref snapshot, ref specialization, out failure)) return false; @@ -1496,6 +1503,7 @@ private bool TryRefreshTable(ulong key, Entry cached, ShaderResourcePlan plan, R ReadResidentMemory = recorder.WrapResident(inputs.ReadResidentMemory), ReadsClean = inputs.ReadsClean, ComputeState = inputs.ComputeState, + IsRangeMapped = inputs.IsRangeMapped, }; var cachedTable = cached.Snapshot.FlattenedResourceTable; ReadingTable = true; @@ -1555,6 +1563,7 @@ private bool TryRefreshTable(ulong key, Entry cached, ShaderResourcePlan plan, R FlattenedResourceTable = table, UserData = previous.UserData, DeviceAddressRanges = previous.DeviceAddressRanges, + Heaps = previous.Heaps, }, Specialization = cached.Specialization, Next = cached.Next, @@ -1729,6 +1738,7 @@ private static ResourceSnapshot WithCurrentUserData(ResourceSnapshot cached, IRe FlattenedResourceTable = cached.FlattenedResourceTable, UserData = current, DeviceAddressRanges = cached.DeviceAddressRanges, + Heaps = cached.Heaps, Origin = cached.Origin, }; } @@ -2050,6 +2060,7 @@ private bool TryRebaseRefresh(Entry entry, ShaderResourcePlan plan, ResourceRunt FlattenedResourceTable = table, UserData = patched.UserData, DeviceAddressRanges = patched.DeviceAddressRanges, + Heaps = patched.Heaps, }; patches = found; return true; @@ -2077,6 +2088,7 @@ private bool TryRebaseRefresh(Entry entry, ShaderResourcePlan plan, ResourceRunt ReadResidentMemory = recorder.WrapResident(inputs.ReadResidentMemory), ReadsClean = inputs.ReadsClean, ComputeState = inputs.ComputeState, + IsRangeMapped = inputs.IsRangeMapped, }; var cachedTable = entry.Snapshot.FlattenedResourceTable; ReadingTable = true; @@ -2117,6 +2129,7 @@ private bool TryRebaseRefresh(Entry entry, ShaderResourcePlan plan, ResourceRunt FlattenedResourceTable = table, UserData = patched.UserData, DeviceAddressRanges = patched.DeviceAddressRanges, + Heaps = patched.Heaps, }; } finally diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializationProfile.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializationProfile.cs index 01a398a6a..c3dbaebfc 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializationProfile.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializationProfile.cs @@ -13,7 +13,7 @@ public enum Phase SourceEvaluation, BranchSelection, DescriptorPrefetch, DescriptorEvaluation, TablePrefetch, TableEvaluation, CompiledEvaluation, CompiledTableEvaluation, SpecializationGuardHit, CompiledOutputAllocation, CompiledBody, CompiledWordRead, CompiledGroupRead, - ReadRecording, ConsumerLookup, ConsumerGraph, Count + ReadRecording, ConsumerLookup, ConsumerGraph, CompiledBranchEvaluation, Count } public static readonly bool Enabled = IsEnabled( diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.SpecializationGuard.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.SpecializationGuard.cs index 3f3feb1a5..b01fb249d 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.SpecializationGuard.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.SpecializationGuard.cs @@ -8,15 +8,18 @@ public static partial class ResourceMaterializer // A published guard owns its data. Callers receive a separate specialization. internal sealed class SpecializationGuard { - internal uint[][] Buffers = []; + internal bool StableImageBindings; + internal uint[] Buffers = []; internal uint[][] Images = []; internal uint[][] Samplers = []; internal int[] SamplerSources = []; internal ResourceSpecialization Specialization = new(); } + // The V# bits a buffer's specialization depends on: its type and, when formatted, its format and destination selects. + // The stride is read at run time; the other addressing fields do not shape the module. private static uint BufferGuardFlags(ShaderResourcePlan plan, int index) => - 0xC0E00000u | (plan.Info.Buffers[index].Formatted ? 0x7FFFFu : 0u); + 0xC0000000u | (plan.Info.Buffers[index].Formatted ? 0x7FFFFu : 0u); private static SpecializationGuard? CaptureGuard(ShaderResourcePlan plan, MaterializedSnapshot snapshot) { @@ -29,7 +32,8 @@ private static uint BufferGuardFlags(ShaderResourcePlan plan, int index) => snapshot.Buffers.Any(words => words.Length != 4 || words[3] >> 30 != 0)) return null; return new SpecializationGuard { - Buffers = snapshot.Buffers.Select((words, index) => new[] { words[1] & 0xBFFF0000u, words[3] & BufferGuardFlags(plan, index) }).ToArray(), + StableImageBindings = plan.StableImageBindings, + Buffers = snapshot.Buffers.Select((words, index) => words[3] & BufferGuardFlags(plan, index)).ToArray(), Images = snapshot.Images.Select(words => words.ToArray()).ToArray(), Samplers = snapshot.Samplers.Select(words => words.ToArray()).ToArray(), }; @@ -38,13 +42,13 @@ private static uint BufferGuardFlags(ShaderResourcePlan plan, int index) => private static bool MatchesGuard(ShaderResourcePlan plan, MaterializedSnapshot snapshot, SpecializationGuard guard, bool checkSamplers = true) { - if (snapshot.Buffers.Length != guard.Buffers.Length || snapshot.Images.Length != guard.Images.Length || + if (plan.StableImageBindings != guard.StableImageBindings || + snapshot.Buffers.Length != guard.Buffers.Length || snapshot.Images.Length != guard.Images.Length || snapshot.IndirectImages.Count != 0 || snapshot.BufferCandidateTables.Count != 0) return false; for (var index = 0; index < guard.Buffers.Length; index++) { var words = snapshot.Buffers[index]; - if (words.Length != 4 || (words[1] & 0xBFFF0000u) != guard.Buffers[index][0] || - (words[3] & BufferGuardFlags(plan, index)) != guard.Buffers[index][1]) return false; + if (words.Length != 4 || (words[3] & BufferGuardFlags(plan, index)) != guard.Buffers[index]) return false; } for (var index = 0; index < guard.Images.Length; index++) if (!snapshot.Images[index].AsSpan().SequenceEqual(guard.Images[index])) return false; diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs index e1849afab..d8c7e7974 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs @@ -49,6 +49,7 @@ private sealed class MaterializedSnapshot public uint[] UserData = []; public List IndirectImages = []; public List BufferCandidateTables = []; + public BindlessHeapDescriptor[] Heaps = []; } // One bounded runtime V# table resolved for this draw: the distinct candidate descriptors @@ -145,6 +146,7 @@ public static bool Materialize( FlattenedResourceTable = nextSnapshot.FlattenedTable, UserData = nextSnapshot.UserData, DeviceAddressRanges = ranges, + Heaps = nextSnapshot.Heaps, }; specialization = nextSpecialization; failure = ResourceMaterializationFailure.None; @@ -345,8 +347,16 @@ private static bool SameUnlessStatistics(ReadOnlySpan key, ReadOnlySpan - plan.IndirectImages.Count == 0 && plan.BufferCandidateTables.Count == 0 && plan.MaterializationProgram is not null; + plan.IndirectImages.Count == 0 && plan.BufferCandidateTables.Count == 0 && plan.HeapRecordSources.Count == 0 && + !ExtendsPlannedRanges(plan) && plan.MaterializationProgram is not null; + + // DeviceAddressRangePlanner.Evaluate adds the ranges of the shader function buffers and of the device record counts + // after the planned ones; a materialization program evaluates the planned ranges only. + private static bool ExtendsPlannedRanges(ShaderResourcePlan plan) => + plan.Graph.Program.FunctionBufferAccesses.Count != 0 || plan.DeviceRecordCounts is not null; // Materializes every draw from the plan's program: no cached snapshot to prove. The // specialization is a function of descriptor words only, so equal words reuse it. @@ -798,8 +808,8 @@ private static bool MaterializeSnapshot(ShaderResourcePlan plan, ResourceRuntime if (program is not null && program.TryRun(plan, inputs, additionalTableWords, out values, out table, out var programRanges, out activeSources)) { _programRuns.Increment(); - ProgramCheck?.Invoke(plan, inputs, values, table, programRanges); - ranges = programRanges; + ranges = ExtendsPlannedRanges(plan) ? DeviceAddressRangePlanner.Evaluate(plan, inputs) : programRanges; + ProgramCheck?.Invoke(plan, inputs, values, table, ranges); } else { @@ -952,6 +962,30 @@ private static bool MaterializeSnapshot(ShaderResourcePlan plan, ResourceRuntime snapshot.BufferCandidateTables.Add(candidateTable); } + // The heap V#s the bindless heap records are read from, for the host's descriptor set 1. + if (plan.HeapRecordSources.Count != 0) + { + var heapSources = new uint[plan.HeapRecordSources.Count]; + for (var index = 0; index < heapSources.Length; index++) + heapSources[index] = plan.HeapRecordSources[index].Source; + if (!RuntimeValueEvaluator.EvaluateSources(plan, heapSources, inputs, [], evaluateTable: false, out var heaps, out _) || + heaps.Count != heapSources.Length) + { + return false; + } + + snapshot.Heaps = new BindlessHeapDescriptor[heaps.Count]; + for (var index = 0; index < heaps.Count; index++) + { + if (heaps[index].DwordCount != 4) + { + return false; + } + + snapshot.Heaps[index] = BindlessHeapDescriptor.FromWords(plan.HeapRecordSources[index].Sampler, heaps[index].Dwords); + } + } + snapshot.UserData = inputs.UserData.ToArray(); return true; } @@ -1239,7 +1273,7 @@ GuestImageFormat.ImageType2DArray or // other field of the record) is not something it can sample, so a shared selector reads it as null. private static bool SamplesAs(ReadOnlySpan descriptor, ImageResource image) { - var dimension = DescriptorDimension(descriptor, image.Dimension); + var dimension = DescriptorDimension(descriptor, image); return dimension == image.Dimension || image.Dimension is ImageDimension.Dim2D or ImageDimension.Dim2DArray && dimension is ImageDimension.Dim2D or ImageDimension.Dim2DArray; @@ -1261,8 +1295,8 @@ private static bool UsableImageCandidate(ReadOnlySpan candidate, bool r128 !NullImageDescriptor(candidate) && ValidImageDescriptor(candidate, r128) && ReservedImageBitsClear(candidate) && GuestImageFormat.SampledNumericClass(GuestImageFormat.FormatOf(candidate)) != ImageNumericClass.Unsupported; - // A call record's image the host can give a float view without a conversion in the shader: a valid sampled T# of a - // float format. A freed T# (0xFEFEFEFE words) fails the reserved-bit check. + // A bindless heap record the host can give a float view without a conversion in the shader: a valid sampled T# of a + // float format. A freed record (0xFEFEFEFE words) fails the reserved-bit check. public static bool IsFloatHeapImage(ReadOnlySpan words) { if (words.Length < 8 || !UsableImageCandidate(words, r128: false)) @@ -1670,8 +1704,17 @@ private static int MappingCapacity(IndirectImageTable table) => // ---- specialization ---- - private static ImageDimension DescriptorDimension(ReadOnlySpan descriptor, ImageDimension requested) + // A sampled image an array instruction reads (its dimension, a cube one's too, is Dim2DArray) is compiled as an array + // whatever its T# holds: a 2D texture or a null descriptor is bound as a one-layer array view, whose layer the + // sampler clamps to its only one, as the hardware clamps the slice to the T#'s layers. The address operands are + // those of an array read either way, so the LOD or mip after the slice is read where the instruction puts it, and a + // pixel shader that reads both kinds of texture through one instruction compiles once. + private static bool SampledArrayRead(ImageResource image) => + image.ResourceClass != ImageResourceClass.Storage && image.Dimension == ImageDimension.Dim2DArray; + + private static ImageDimension DescriptorDimension(ReadOnlySpan descriptor, ImageResource image) { + var requested = image.Dimension; var isArray = requested is ImageDimension.Dim1DArray or ImageDimension.Dim2DArray or ImageDimension.Dim2DMsaaArray; return GuestImageFormat.ImageTypeOf(descriptor) switch { @@ -1681,7 +1724,7 @@ private static ImageDimension DescriptorDimension(ReadOnlySpan descriptor, GuestImageFormat.ImageTypeCube => ImageDimension.Dim2DArray, GuestImageFormat.ImageType2DArray => isArray ? ImageDimension.Dim2DArray : ImageDimension.Dim2D, GuestImageFormat.ImageType2DMsaaArray => isArray ? ImageDimension.Dim2DMsaaArray : ImageDimension.Dim2DMsaa, - GuestImageFormat.ImageType2D => ImageDimension.Dim2D, + GuestImageFormat.ImageType2D => SampledArrayRead(image) ? ImageDimension.Dim2DArray : ImageDimension.Dim2D, GuestImageFormat.ImageType2DMsaa => ImageDimension.Dim2DMsaa, _ => ImageDimension.Unknown, }; @@ -1815,24 +1858,8 @@ private static bool BuildSpecialization( Array.Clear(words); } - var stride = (words[1] >> 16) & 0x3FFF; - var swizzleEnabled = (words[1] >> 31) != 0; - var indexStride = (words[3] >> 21) & 0x3; - var addThreadId = (words[3] >> 23) & 0x1; - var packedStride = stride | ((swizzleEnabled ? 1u : 0u) << 14) | (indexStride << 16) | (addThreadId << 20); - var swizzle = stride != 0 && ((packedStride >> 14) & 1) != 0; - if (stride == 0) - { - packedStride &= ~((1u << 14) | (3u << 16)); - } - else if (!swizzle) - { - packedStride &= ~(3u << 16); - } - var formatted = info.Buffers[index].Formatted; buffers.Add(new BufferSpecialization( - packedStride, formatted ? (words[3] >> 12) & 0x7F : DescriptorConstants.InvalidFormat, formatted ? words[3] & 0xFFF : DescriptorConstants.IdentityDestinationSelect)); } @@ -1872,6 +1899,18 @@ private static bool BuildSpecialization( continue; } + if (index < info.Images.Count && plan.DescriptorSources[(int)baseImage.Source].Heap is { } heap) + { + // A heap image has no descriptor before the shader picks its record: the instruction names its class. + images[index] = image with + { + NumericClass = ImageNumericClass.Float, + Dimension = baseImage.Dimension, + Cube = heap.Cube, + }; + continue; + } + if (NullImageDescriptor(descriptor)) { images[index] = image with @@ -1882,13 +1921,13 @@ private static bool BuildSpecialization( NumericClass = baseImage.Atomic64 ? ImageNumericClass.Uint64 : baseImage.Atomic ? baseImage.NumericClass : ImageNumericClass.Float, - Dimension = ImageDimension.Dim2D, + Dimension = SampledArrayRead(baseImage) ? ImageDimension.Dim2DArray : ImageDimension.Dim2D, Cube = false, }; continue; } - var dimension = DescriptorDimension(descriptor, baseImage.Dimension); + var dimension = DescriptorDimension(descriptor, baseImage); if (dimension == ImageDimension.Unknown) { return Fail( @@ -1918,7 +1957,12 @@ private static bool BuildSpecialization( MipStatistics = RecordMipStatistics && plan.Stage == ShaderStage.Pixel && !storage && ((descriptor[5] >> 25) & 1) != 0, }; var conversionFormat = ImageConversionFormat(format); - var shaderSwizzle = storage || conversionFormat != GuestImageFormat.Invalid ? descriptor[3] & 0xFFF : image.ShaderSwizzle; + // A storage image with no conversion format takes its select from shader data (RuntimeImageSwizzle), so the + // module keeps the identity select for every select bound. + var runtimeSwizzle = storage && conversionFormat == GuestImageFormat.Invalid && info.UsesRuntimeImageSwizzles && + image.IndirectRoot == DescriptorConstants.NoIndex; + var shaderSwizzle = runtimeSwizzle ? DescriptorConstants.IdentityImageSwizzle + : storage || conversionFormat != GuestImageFormat.Invalid ? descriptor[3] & 0xFFF : image.ShaderSwizzle; var rawSintStorage = storage && format == GuestImageFormat.Format32Sint && baseImage.Written && !baseImage.Read && !baseImage.Atomic; var numericClass = GuestImageFormat.SampledNumericClass(format); if (storage) @@ -1946,7 +1990,7 @@ private static bool BuildSpecialization( images[index] = image with { NumericClass = ImageNumericClass.Float, - Dimension = ImageDimension.Dim2D, + Dimension = SampledArrayRead(baseImage) ? ImageDimension.Dim2DArray : ImageDimension.Dim2D, Cube = false, }; continue; @@ -2127,22 +2171,7 @@ private static bool BuildSpecialization( } snapshot.Buffers[bufferCursor + candidate] = words; - var stride = (words[1] >> 16) & 0x3FFF; - var swizzleEnabled = (words[1] >> 31) != 0; - var indexStride = (words[3] >> 21) & 0x3; - var addThreadId = (words[3] >> 23) & 0x1; - var packedStride = stride | ((swizzleEnabled ? 1u : 0u) << 14) | (indexStride << 16) | (addThreadId << 20); - var swizzle = stride != 0 && ((packedStride >> 14) & 1) != 0; - if (stride == 0) - { - packedStride &= ~((1u << 14) | (3u << 16)); - } - else if (!swizzle) - { - packedStride &= ~(3u << 16); - } - - buffers.Add(new BufferSpecialization(packedStride, (words[3] >> 12) & 0x7F, words[3] & 0xFFF)); + buffers.Add(new BufferSpecialization((words[3] >> 12) & 0x7F, words[3] & 0xFFF)); } var mappingOffset = (uint)mappingCursor; @@ -2166,10 +2195,11 @@ private static bool BuildSpecialization( specialization = new ResourceSpecialization { BaseBufferCount = baseBufferCount, + StableImageBindings = plan.StableImageBindings, Buffers = buffers, Images = images, BufferCandidateTables = candidateTables, - ImageDescriptorGroups = DescriptorBindingAliases.Group(snapshot.Images, images), + ImageDescriptorGroups = plan.StableImageBindings ? [] : DescriptorBindingAliases.Group(snapshot.Images, images), SamplerDescriptorGroups = DescriptorBindingAliases.Group(snapshot.Samplers.Take(info.Samplers.Count).ToArray()), }; specializedSnapshot = snapshot; @@ -2229,6 +2259,9 @@ private static bool BuildSamplerPlan(ShaderResourceInfo info, IReadOnlyList specialization.Images.Count) { throw new ResourcePlanException( @@ -2239,7 +2272,6 @@ public static SpecializedResourceInfo ApplyTo(ShaderResourcePlan plan, ResourceS var info = source.Clone(); for (var index = 0; index < info.Buffers.Count; index++) { - info.Buffers[index].PackedStride = specialization.Buffers[index].PackedStride; info.Buffers[index].DescriptorFormat = specialization.Buffers[index].DescriptorFormat; info.Buffers[index].DescriptorSwizzle = specialization.Buffers[index].DescriptorSwizzle; } @@ -2252,7 +2284,6 @@ public static SpecializedResourceInfo ApplyTo(ShaderResourcePlan plan, ResourceS { Source = DescriptorConstants.NoIndex, Read = true, - PackedStride = specialized.PackedStride, DescriptorFormat = specialized.DescriptorFormat, DescriptorSwizzle = specialized.DescriptorSwizzle, }); diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceRuntimeInputs.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceRuntimeInputs.cs index d59e4e335..db57ffc8f 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceRuntimeInputs.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceRuntimeInputs.cs @@ -17,6 +17,8 @@ public sealed class ResourceRuntimeInputs public GuestWordReader? ReadMemory { get; init; } public GuestWordReader? ReadCleanMemory { get; init; } public ComputeSelectorState? ComputeState { get; init; } + // Metadata-only mapping query. It must not read the buffer or wait for GPU writes. + public Func? IsRangeMapped { get; init; } public Action>? TraceImageCandidate { get; init; } // Told true before the flattened table's words are evaluated and false after, so a reader @@ -27,6 +29,13 @@ public sealed class ResourceRuntimeInputs public bool ReadsClean { get; init; } + internal ResourceRuntimeInputs WithComputeState(ComputeSelectorState state) => new() + { + UserData = UserData, ShaderBase = ShaderBase, ReadMemory = ReadMemory, ReadCleanMemory = ReadCleanMemory, + ComputeState = state, IsRangeMapped = IsRangeMapped, TraceImageCandidate = TraceImageCandidate, + TablePhase = TablePhase, ReadResidentMemory = ReadResidentMemory, ReadsClean = ReadsClean, + }; + public ResourceRuntimeInputs WithReader(GuestWordReader? reader) => new() { UserData = UserData, @@ -34,6 +43,7 @@ public sealed class ResourceRuntimeInputs ReadMemory = reader, ReadCleanMemory = ReadCleanMemory, ComputeState = ComputeState, + IsRangeMapped = IsRangeMapped, TraceImageCandidate = TraceImageCandidate, TablePhase = TablePhase, ReadResidentMemory = ReadResidentMemory, @@ -71,6 +81,7 @@ public ResourceRuntimeInputs WithCallArguments(uint userDataBase, IReadOnlyList< ReadMemory = ReadMemory, ReadCleanMemory = ReadCleanMemory, ComputeState = ComputeState, + IsRangeMapped = IsRangeMapped, TraceImageCandidate = TraceImageCandidate, TablePhase = TablePhase, ReadResidentMemory = ReadResidentMemory, @@ -80,4 +91,9 @@ public ResourceRuntimeInputs WithCallArguments(uint userDataBase, IReadOnlyList< } public readonly record struct ComputeSelectorState(uint WaveSize, uint ThreadsX, uint ThreadsY, uint ThreadsZ, - bool HasPartialWorkgroups, uint LocalDataShareDwords, int LocalInvocationIdComponents); + bool HasPartialWorkgroups, uint LocalDataShareDwords, int LocalInvocationIdComponents) +{ + public DispatchBufferFootprint.Dispatch? Dispatch { get; init; } + public bool DeviceCountProof { get; init; } + internal long DeviceCountProofRevision { get; init; } +} diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceSnapshot.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceSnapshot.cs index 539706a36..259e4f0bb 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceSnapshot.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceSnapshot.cs @@ -21,6 +21,9 @@ public sealed class ResourceSnapshot public uint[]? MipStatistics { get; init; } public object? Origin { get; set; } + // The heap V#s the draw's bindless heap records are read from, one per heap. + public BindlessHeapDescriptor[] Heaps { get; init; } = []; + public static uint MipStatisticsOf(uint word5, uint word6) => (word6 & MipStatisticsSlotWordMask) | ((word5 & MipStatisticsEnableWordMask) != 0 ? MipStatisticsEnabled : 0u); } diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceSpecialization.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceSpecialization.cs index e56d1f81c..9518d5121 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceSpecialization.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceSpecialization.cs @@ -6,7 +6,8 @@ namespace SharpEmu.ShaderCompiler.Resources; -public readonly record struct BufferSpecialization(uint PackedStride, uint DescriptorFormat, uint DescriptorSwizzle); +// A buffer's stride is not part of its specialization; an indexed access reads it from the binding's V# at run time. +public readonly record struct BufferSpecialization(uint DescriptorFormat, uint DescriptorSwizzle); // The module-affecting layout of one bounded runtime V# table. Candidate descriptors // themselves are appended to Buffers; this names their contiguous run and the flattened @@ -36,6 +37,7 @@ public sealed class ResourceSpecialization : IEquatable { // The plan's base buffer count; Buffers beyond it are materialized candidates. public int BaseBufferCount { get; init; } + public bool StableImageBindings { get; init; } public List Buffers { get; init; } = []; public List Images { get; init; } = []; public List BufferCandidateTables { get; init; } = []; @@ -43,7 +45,8 @@ public sealed class ResourceSpecialization : IEquatable public List SamplerDescriptorGroups { get; init; } = []; public bool Equals(ResourceSpecialization? other) => - ReferenceEquals(this, other) || other is not null && BaseBufferCount == other.BaseBufferCount && Buffers.SequenceEqual(other.Buffers) && + ReferenceEquals(this, other) || other is not null && StableImageBindings == other.StableImageBindings && + BaseBufferCount == other.BaseBufferCount && Buffers.SequenceEqual(other.Buffers) && Images.SequenceEqual(other.Images) && BufferCandidateTables.SequenceEqual(other.BufferCandidateTables) && ImageDescriptorGroups.SequenceEqual(other.ImageDescriptorGroups) && SamplerDescriptorGroups.SequenceEqual(other.SamplerDescriptorGroups); @@ -54,6 +57,7 @@ public override int GetHashCode() { var hash = new HashCode(); hash.Add(BaseBufferCount); + hash.Add(StableImageBindings); foreach (var buffer in Buffers) { hash.Add(buffer); @@ -77,6 +81,7 @@ public override int GetHashCode() public ResourceSpecialization Clone() => new() { BaseBufferCount = BaseBufferCount, + StableImageBindings = StableImageBindings, Buffers = [.. Buffers], Images = [.. Images], BufferCandidateTables = [.. BufferCandidateTables], @@ -88,7 +93,7 @@ public override int GetHashCode() public static ResourceSpecialization Default(ShaderResourceInfo info) => new() { BaseBufferCount = info.Buffers.Count, - Buffers = info.Buffers.Select(_ => new BufferSpecialization(0, DescriptorConstants.InvalidFormat, DescriptorConstants.IdentityDestinationSelect)).ToList(), + Buffers = info.Buffers.Select(_ => new BufferSpecialization(DescriptorConstants.InvalidFormat, DescriptorConstants.IdentityDestinationSelect)).ToList(), Images = info.Images.Select(image => new ImageSpecialization( image.NumericClass == ImageNumericClass.Unsupported ? (image.Atomic64 ? ImageNumericClass.Uint64 : image.Atomic ? ImageNumericClass.Uint : ImageNumericClass.Float) diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceTableReadPlanner.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceTableReadPlanner.cs index cb0e72b38..d9c11fb66 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceTableReadPlanner.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceTableReadPlanner.cs @@ -13,6 +13,8 @@ public sealed class ResourceTableReadPlanner private readonly ScalarValueGraph _graph; private readonly ShaderStage _stage; private readonly ulong _hash; + private readonly bool _scalarDataOnDevice; + private readonly DeviceRecordCountPlan? _deviceRecordCounts; private readonly List _reads = []; private readonly List _dynamicReads = []; private readonly HashSet _dynamicReadSet = []; @@ -23,11 +25,16 @@ public sealed class ResourceTableReadPlanner private readonly HashSet _visited = []; private readonly Dictionary _replacements = []; - private ResourceTableReadPlanner(ScalarValueGraph graph, ShaderStage stage, ulong hash) + private ResourceTableReadPlanner(ScalarValueGraph graph, ShaderStage stage, ulong hash, bool scalarDataOnDevice, + DeviceRecordCountPlan? deviceRecordCounts) { _graph = graph; _stage = stage; _hash = hash; + _deviceRecordCounts = deviceRecordCounts; + _scalarDataOnDevice = scalarDataOnDevice && stage == ShaderStage.Compute && graph.CallArgumentRegisters == 0 && + !Gen5ShaderCallLinker.IsLinked(graph.Program) && + !graph.Program.Instructions.Any(instruction => instruction.Opcode is "SSetpcB64" or "SSwappcB64" or "SRfeB64"); } public sealed record Result( @@ -36,8 +43,9 @@ public sealed record Result( IReadOnlyDictionary Replacements, IReadOnlyDictionary FlattenedSlotByMemoryIndex); - public static Result Plan(ScalarValueGraph graph, ShaderStage stage, ulong hash) => - new ResourceTableReadPlanner(graph, stage, hash).Run(); + public static Result Plan(ScalarValueGraph graph, ShaderStage stage, ulong hash, bool scalarDataOnDevice = false, + DeviceRecordCountPlan? deviceRecordCounts = null) => + new ResourceTableReadPlanner(graph, stage, hash, scalarDataOnDevice, deviceRecordCounts).Run(); private Result Run() { @@ -60,9 +68,10 @@ private Result Run() { if (access?.Handle is { } handle) { - foreach (var dword in handle.Operands) + for (var component = 0; component < handle.Operands.Length; component++) { - Collect(dword, 0); + if (component != 2 || _deviceRecordCounts?.SkipCount(handle) != true) + Collect(handle.Operands[component], 0); } } @@ -76,12 +85,16 @@ private Result Run() } var validatorReadCount = _reads.Count; + var hostValues = _scalarDataOnDevice ? HostConsumerValues() : null; foreach (var access in _graph.Accesses) { if (access?.Read is { Kind: ScalarValueKind.ScalarAddressWord } read && IsRawRead(read) && read.Operands[1].IsConstant && new RuntimeValueValidator(_graph, _graph.UserDataBase, _graph.UserDataCount, validatorReadCount).Validate(read)) { + // Leave data-only reads in the shader. The existing scalar-address lowering and bounded + // DeviceAddressRangePlanner path own residency and producer visibility for these exact bytes. + if (hostValues is not null && CanReadOnDevice(read, hostValues)) continue; Collect(read, _graph.Memory[read.MemoryIndex].Pc); } } @@ -90,6 +103,53 @@ private Result Run() return new Result(_reads, _dynamicReads, _replacements, _flattenedSlotByMemoryIndex); } + private HashSet HostConsumerValues() + { + var values = new HashSet(_visited); // All descriptor/address/sampler ancestors already collected. + void Visit(ScalarValue? value) + { + if (value is null || !values.Add(value)) return; + foreach (var operand in value.Operands) Visit(operand); + } + foreach (var access in _graph.Accesses) + { + // Range bounds and resource activation can be evaluated by the host too. + Visit(access?.Offset); + Visit(access?.Active); + } + foreach (var condition in _graph.BranchConditions.Values) Visit(condition); + foreach (var argument in _graph.CallRecordArguments.Values) + { + Visit(argument.Low); + Visit(argument.High); + } + return values; + } + + private bool CanReadOnDevice(ScalarValue read, HashSet hostValues) + { + if (hostValues.Contains(read)) return false; + var memory = _graph.Memory[read.MemoryIndex]; + if (memory.Kind != MemoryResourceKind.ScalarAddress || memory.Access != MemoryAccess.Read || + memory.DataBits != 32 || memory.DataDwords != 1 || + read.Operands[1].ConstantU32 != 0 || + memory.Offset > DeviceAddressRangePlanner.MaxRangeBytes - sizeof(uint) || + read.Operands[0] is not { Kind: ScalarValueKind.AddressHandle, Operands.Length: 2 } handle) + return false; + // A pointer loaded from memory would reintroduce host reads to plan residency. Admit only an address + // computed entirely from immutable dispatch inputs; no first-lane, loop, memory, or descriptor chain. + bool MemoryFree(ScalarValue value, HashSet visiting) + { + if (value.IsConstant || value.Kind is ScalarValueKind.UserData or ScalarValueKind.ShaderBase) return true; + if (value.Kind != ScalarValueKind.Operation || !RuntimeValueValidator.IsUniformOperation(value.Operation) || + !visiting.Add(value)) return false; + var valid = value.Operands.All(operand => MemoryFree(operand, visiting)); + visiting.Remove(value); + return valid; + } + return handle.Operands.All(value => MemoryFree(value, [])); + } + private void Fail(uint pc, string message) => throw new ResourcePlanException( $"shader resource-table planning failed: hash=0x{_hash:X16} stage={_stage} pc=0x{pc:X8} {message}"); diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceTracker.DirectImages.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceTracker.DirectImages.cs index b8417eaf8..22cde1522 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceTracker.DirectImages.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceTracker.DirectImages.cs @@ -163,8 +163,7 @@ private bool HasOnlyImageConsumers(MemoryAccessInfo memory, ScalarValue handle) if (!allowedImage && (ReadsScalar(instruction, destination.Value) || (instruction.Encoding == Gen5ShaderEncoding.Sopk && instruction.Opcode is "SAddkI32" or "SMulkI32" && instruction.Destinations.Contains(destination)))) return false; - overwritten = instruction.Destinations.Any(target => target.Kind == Gen5OperandKind.ScalarRegister && - (target == destination || (instruction.DestinationWidth > 1 && target.Value + 1 == destination.Value))) || + overwritten = WritesScalar(instruction, destination) || instruction.Control is Gen5Vop3Control { ScalarDestination: { } scalarDestination } && destination.Value >= scalarDestination && destination.Value - scalarDestination < 2 || instruction.Control is Gen5SdwaControl { ScalarDestination: { } compareDestination } && @@ -178,12 +177,32 @@ private bool HasOnlyImageConsumers(MemoryAccessInfo memory, ScalarValue handle) return true; } + // Loops, not closures: the consumer walk asks these of every instruction it passes. + private static bool WritesScalar(Gen5ShaderInstruction instruction, Gen5Operand destination) + { + var targets = instruction.Destinations; + for (var index = 0; index < targets.Count; index++) + { + var target = targets[index]; + if (target.Kind == Gen5OperandKind.ScalarRegister && + (target == destination || (instruction.DestinationWidth > 1 && target.Value + 1 == destination.Value))) + return true; + } + + return false; + } + private static bool ReadsScalar(Gen5ShaderInstruction instruction, uint register) { bool InRange(uint first, uint width) => register >= first && register - first < width; var width = instruction.Opcode.Contains("64", StringComparison.Ordinal) ? 2u : 1u; - if (instruction.Sources.Any(source => source.Kind == Gen5OperandKind.ScalarRegister && InRange(source.Value, width))) - return true; + var sources = instruction.Sources; + for (var index = 0; index < sources.Count; index++) + { + if (sources[index].Kind == Gen5OperandKind.ScalarRegister && InRange(sources[index].Value, width)) + return true; + } + return instruction.Control switch { Gen5ImageControl image => InRange(image.ScalarResource, 8) || InRange(image.ScalarSampler, 4), diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceTracker.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceTracker.cs index d9b931cad..64301f3e3 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceTracker.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceTracker.cs @@ -22,12 +22,16 @@ public sealed partial class ResourceTracker private readonly List _bufferCandidateTables = []; private readonly Dictionary> _uses; private readonly Dictionary> _readsByMemory = []; + private readonly bool _bindlessNullDescriptors; + private readonly SortedSet _nullBindlessPcs = new(); + private readonly bool _bindlessHeap; private readonly bool _callRecordsEnabled; - private readonly List _callRecords = []; + private readonly List _heapRecords = []; + private readonly List _callRecords = []; - // An image or sampler a linked callee reads through its record: its descriptor source with the call record selector, and - // the scalar reads of its dwords, which the shader skips when only image instructions use them. - private sealed class CallRecordPlan + // An image or sampler read from a bindless heap: its descriptor source with the heap selector, and the scalar reads + // of its dwords, which the shader skips when only image instructions use them. + private sealed class HeapRecordPlan { public ScalarValue Handle = null!; public uint Source; @@ -55,11 +59,15 @@ public sealed record Result( IReadOnlyList IndirectImages, IReadOnlySet IndirectReads, IReadOnlyList BufferCandidateTables, + IReadOnlyList NullBindlessDescriptorPcs, + IReadOnlyList HeapRecords, IReadOnlyList CallRecords); - private ResourceTracker(ShaderResourcePlan plan, bool callRecords) + private ResourceTracker(ShaderResourcePlan plan, bool bindlessNullDescriptors, bool bindlessHeap, bool callRecords) { _plan = plan; + _bindlessNullDescriptors = bindlessNullDescriptors; + _bindlessHeap = bindlessHeap; _callRecordsEnabled = callRecords; _graph = plan.Graph; var roots = new List(); @@ -102,13 +110,19 @@ private ResourceTracker(ShaderResourcePlan plan, bool callRecords) } } + // With bindlessNullDescriptors, an image or sampler descriptor read at an index the host cannot evaluate reads as + // null instead of rejecting the program. With bindlessHeap, such a descriptor read from one heap V# is a heap + // record that the shader reads through descriptor set 1 (see BindlessHeap). // With callRecords, the images and samplers a callee linked with run-time arguments reads through its record are call // records (see CallRecordSelector), which descriptor set 1 holds. - public static Result Track(ShaderResourcePlan plan, bool callRecords = false) => new ResourceTracker(plan, callRecords).Run(); + public static Result Track(ShaderResourcePlan plan, bool bindlessNullDescriptors = false, bool bindlessHeap = false, + bool callRecords = false) => + new ResourceTracker(plan, bindlessNullDescriptors, bindlessHeap, callRecords).Run(); private Result Run() { PlanIndirectImages(); + PlanHeapRecords(); PlanCallRecords(); for (var index = 0; index < _plan.Memory.Count; index++) { @@ -155,6 +169,32 @@ private Result Run() } } + var heapAccesses = new List(); + foreach (var plan in _heapRecords) + { + if (plan.SuppressMemoryReads) + { + foreach (var index in plan.Memory) + { + _plan.Memory[index].PlanningOnly = true; + } + + foreach (var read in plan.Reads) + { + indirectReads.Add(read); + } + } + + for (var index = 0; index < _plan.Accesses.Length; index++) + { + if (_plan.Memory[index].Kind == MemoryResourceKind.Image && _plan.Accesses[index] is { } access && + ReferenceEquals(plan.Sampler ? access.SamplerHandle : access.Handle, plan.Handle)) + { + heapAccesses.Add(new HeapRecordAccess(index, plan.Source, plan.Sampler)); + } + } + } + var callAccesses = new List(); foreach (var plan in _callRecords) { @@ -181,7 +221,8 @@ private Result Run() } } - return new Result(_sources, _info, indirectAccesses, indirectReads, _bufferCandidateTables, callAccesses); + return new Result(_sources, _info, indirectAccesses, indirectReads, _bufferCandidateTables, [.. _nullBindlessPcs], + heapAccesses, callAccesses); } private ResourcePlanException Failure(uint pc, string reason) => @@ -257,6 +298,35 @@ private static bool HasLaneChosenValue(ScalarValue value) return false; } + // A bindless descriptor: a heap entry read at an index the host cannot evaluate (a material id, a per-instance + // value or a lane's key), or a value one lane chose. It has no value when the draw is bound. + private bool IsReadAtRuntimeIndex(ScalarValue value) + { + var seen = new HashSet(); + var pending = new Stack(); + pending.Push(value); + while (pending.TryPop(out var current)) + { + if (!seen.Add(current)) + { + continue; + } + + if (current.Kind is ScalarValueKind.ScalarBufferWord or ScalarValueKind.ScalarAddressWord or ScalarValueKind.FirstLane && + !_plan.ValidateRuntimeValue(current)) + { + return true; + } + + foreach (var operand in current.Operands) + { + pending.Push(operand); + } + } + + return false; + } + private bool HasUndefinedOrigin(ScalarValue value, string opcodePrefix) { var seen = new HashSet(); @@ -439,7 +509,7 @@ private uint InternSource(DescriptorSource source) { var current = _sources[candidate]; if (current.DwordCount != source.DwordCount || !Equals(current.IndirectImage, source.IndirectImage) || - !Equals(current.CallRecord, source.CallRecord)) + !Equals(current.Heap, source.Heap) || !Equals(current.CallRecord, source.CallRecord)) { continue; } @@ -634,7 +704,17 @@ private uint GetHandleSource( (expected == ScalarValueKind.ImageHandle && _plan.Stage != ShaderStage.Compute && source.Dwords.Any(HasLaneChosenValue)) || (expected == ScalarValueKind.SamplerHandle && source.Dwords.All(dword => dword.IsUndefined))); - if (dynamicImageFallback) + // Opted in, any image or sampler read from a heap at an index the host cannot evaluate reads as null too, + // in every stage, so the work that uses it still runs. + var bindlessFallback = !dynamicImageFallback && _bindlessNullDescriptors && + expected is (ScalarValueKind.ImageHandle or ScalarValueKind.SamplerHandle) && + source.Dwords.Any(IsReadAtRuntimeIndex); + if (bindlessFallback) + { + _nullBindlessPcs.Add(pc); + } + + if (dynamicImageFallback || bindlessFallback) { source = new DescriptorSource { @@ -814,44 +894,17 @@ private bool IsRuntimeDerivable(ScalarValue value, HashSet visiting private static bool HasRuntimeReadKind(ScalarValue value, ScalarValueKind kind) => HasRuntimeReadKind(value, kind, []); - private static bool HasRuntimeReadKind(ScalarValue value, ScalarValueKind kind, HashSet visiting) - { - if (!visiting.Add(value)) - { - return false; - } - - try - { - return value.Kind == kind || value.Operands.Any(operand => HasRuntimeReadKind(operand, kind, visiting)); - } - finally - { - visiting.Remove(value); - } - } - - private static bool HasRuntimeRead(ScalarValue value, HashSet visiting) - { - if (!visiting.Add(value)) - { - return false; - } - - try - { - if (value.Kind is ScalarValueKind.ScalarAddressWord or ScalarValueKind.ScalarBufferWord) - { - return true; - } + // Both searches keep every node they have seen. The search ends at the first match, so a node seen before was + // either explored without one or lies on the current path. Walking it again for every path that reaches it took + // exponential time on the phis of a shader with many branches. + private static bool HasRuntimeReadKind(ScalarValue value, ScalarValueKind kind, HashSet seen) => + seen.Add(value) && + (value.Kind == kind || value.Operands.Any(operand => HasRuntimeReadKind(operand, kind, seen))); - return value.Operands.Any(operand => HasRuntimeRead(operand, visiting)); - } - finally - { - visiting.Remove(value); - } - } + private static bool HasRuntimeRead(ScalarValue value, HashSet seen) => + seen.Add(value) && + (value.Kind is ScalarValueKind.ScalarAddressWord or ScalarValueKind.ScalarBufferWord || + value.Operands.Any(operand => HasRuntimeRead(operand, seen))); // ---- dense tables ---- @@ -1021,7 +1074,7 @@ private void Collect(int index) return; } - if (isBuffer && _graph.Program.FunctionBufferAccesses.Contains(memory.Pc)) + if (isBuffer && (_graph.Program.FunctionBufferAccesses.Contains(memory.Pc) || _plan.DeviceRecordCounts?.Contains(index) == true)) { if (access?.Handle is not { Kind: ScalarValueKind.BufferHandle, Operands.Length: 4 }) throw Failure(memory.Pc, "linked function buffer has no descriptor handle"); @@ -1041,7 +1094,7 @@ private void Collect(int index) throw Failure(memory.Pc, "memory operation has no resource handle"); } - if (memory.PlanningOnly || IsIndirectPlanningMemory(index) || IsCallRecordPlanningMemory(index)) + if (memory.PlanningOnly || IsIndirectPlanningMemory(index) || IsHeapPlanningMemory(index)) { return; } @@ -1107,6 +1160,8 @@ private void Collect(int index) { Provenance = BufferDescriptorProvenance.Runtime, }; + // Each candidate is a binding, whose stride an indexed access reads from shader data. + _info.UsesIndexedBuffers |= memory.IndexEnabled; return; } @@ -1167,6 +1222,9 @@ private void Collect(int index) Provenance = BufferDescriptorProvenance.Static, StaticResource = resource, }; + // An indexed access through a binding reads the binding's stride from shader data. A V# read on the device + // (the returns above) carries its own stride. + _info.UsesIndexedBuffers |= memory.IndexEnabled; AddMemoryPatch(index, resource, 0, false, memory.Pc); return; } @@ -1223,7 +1281,8 @@ private void Collect(int index) } else { - imageSource = CallRecordFor(access.Handle, sampler: false)?.Source ?? + imageSource = HeapRecordFor(access.Handle, sampler: false)?.Source ?? + CallRecordFor(access.Handle, sampler: false)?.Source ?? GetHandleSource(access.Handle, ScalarValueKind.ImageHandle, 8, memory.Pc); } @@ -1242,7 +1301,8 @@ private void Collect(int index) } var sampleAdjust = (memory.ImageSampleFlags & ImageSampleFlags.Adjust) != 0; - var samplerSource = CallRecordFor(access.SamplerHandle, sampler: true)?.Source ?? + var samplerSource = HeapRecordFor(access.SamplerHandle, sampler: true)?.Source ?? + CallRecordFor(access.SamplerHandle, sampler: true)?.Source ?? GetHandleSource(access.SamplerHandle, ScalarValueKind.SamplerHandle, 4, memory.Pc, sampler: true, sampleAdjust); sampler = AddSampler(samplerSource, memory.Pc); if (sampler == DescriptorConstants.NoIndex) @@ -1289,12 +1349,28 @@ private void LinkImageAliases() } } - // ---- call records ---- + // ---- bindless heap records ---- + + private HeapRecordPlan? HeapRecordFor(ScalarValue? handle, bool sampler) + { + foreach (var plan in _heapRecords) + { + if (plan.Sampler == sampler && ReferenceEquals(plan.Handle, handle)) + { + return plan; + } + } + + return null; + } - private bool IsCallRecordPlanningMemory(int index) => + private bool IsHeapPlanningMemory(int index) => + _heapRecords.Any(plan => plan.SuppressMemoryReads && plan.Memory.Contains(index)) || _callRecords.Any(plan => plan.SuppressMemoryReads && plan.Memory.Contains(index)); - private CallRecordPlan? CallRecordFor(ScalarValue? handle, bool sampler) + // ---- call records ---- + + private HeapRecordPlan? CallRecordFor(ScalarValue? handle, bool sampler) { foreach (var plan in _callRecords) { @@ -1307,7 +1383,8 @@ private bool IsCallRecordPlanningMemory(int index) => return null; } - // A sampled image or sampler whose dwords a linked callee reads through its record's run-time argument (consecutive scalar reads at immediate offsets from the pair its call entry kept) is a call record: the host + // With the bindless heap, a sampled image or sampler whose dwords a linked callee reads through its record's run-time + // argument (consecutive scalar reads at immediate offsets from the pair its call entry kept) is a call record: the host // resolves it for every record of the dispatch's tables, and the shader picks its record's at run time. private void PlanCallRecords() { @@ -1325,12 +1402,13 @@ private void PlanCallRecords() continue; } - if (access.Handle is { } image && !_indirectImages.Any(plan => ReferenceEquals(plan.Handle, image))) + if (access.Handle is { } image && !_indirectImages.Any(plan => ReferenceEquals(plan.Handle, image)) && + HeapRecordFor(image, sampler: false) is null) { TryPlanCallRecord(image, sampler: false, memory.Pc); } - if (memory.NeedsSampler && access.SamplerHandle is { } samplerHandle) + if (memory.NeedsSampler && access.SamplerHandle is { } samplerHandle && HeapRecordFor(samplerHandle, sampler: true) is null) { TryPlanCallRecord(samplerHandle, sampler: true, memory.Pc); } @@ -1395,7 +1473,7 @@ private void TryPlanCallRecord(ScalarValue handle, bool sampler, uint pc) Cube = !sampler && instruction?.Control is Gen5ImageControl { Dimension: 3 }, }, }); - _callRecords.Add(new CallRecordPlan + _callRecords.Add(new HeapRecordPlan { Handle = handle, Source = source, @@ -1422,6 +1500,104 @@ private bool IsCallRecordArgument(ScalarValue address) return false; } + // With the heap set, a sampled image or sampler whose dwords are read from one heap V# at an offset the host cannot + // evaluate becomes a heap record. A descriptor another plan reads keeps that plan. + private void PlanHeapRecords() + { + if (!_bindlessHeap) + { + return; + } + + for (var index = 0; index < _plan.Memory.Count; index++) + { + var memory = _plan.Memory[index]; + if (memory.Kind != MemoryResourceKind.Image || memory.ImageClass != ImageResourceClass.Sampled || + _plan.Accesses[index] is not { } access) + { + continue; + } + + if (access.Handle is { } image && !_indirectImages.Any(plan => ReferenceEquals(plan.Handle, image))) + { + TryPlanHeapRecord(image, sampler: false, memory.Pc); + } + + if (memory.NeedsSampler && access.SamplerHandle is { } samplerHandle) + { + TryPlanHeapRecord(samplerHandle, sampler: true, memory.Pc); + } + } + } + + private void TryPlanHeapRecord(ScalarValue handle, bool sampler, uint pc) + { + var width = sampler ? 4 : 8; + var expected = sampler ? ScalarValueKind.SamplerHandle : ScalarValueKind.ImageHandle; + if (handle.Kind != expected || handle.Operands.Length != width || HeapRecordFor(handle, sampler) is not null) + { + return; + } + + var reads = handle.Operands.Select(Invariant).ToArray(); + var first = ScalarReadMemory(reads[0], out _); + if (first is null) + { + return; + } + + var heapHandle = reads[0].Operands[0]; + var offset = reads[0].Operands[1]; + if (heapHandle.Kind != ScalarValueKind.BufferHandle || _plan.ValidateRuntimeValue(offset)) + { + return; + } + + // A sampler's words still load: the image instructions read them as a sampler, which the consumer check does not allow. + var memoryIndices = new int[width]; + var suppress = !sampler; + for (var dword = 0; dword < width; dword++) + { + var read = reads[dword]; + var memory = ScalarReadMemory(read, out var memoryIndex); + if (memory is null || memory.Offset != first.Offset + (uint)dword * sizeof(uint) || + !_graph.Equivalent(read.Operands[0], heapHandle) || !_graph.Equivalent(read.Operands[1], offset)) + { + return; + } + + memoryIndices[dword] = memoryIndex; + suppress = suppress && MemoryIndexBelongsTo(memoryIndex, read) && UsesOnly(read, [handle]) && + HasOnlyImageConsumers(memory, handle); + } + + var heapSource = InternRuntimeSource(heapHandle, pc); + if (heapSource == DescriptorConstants.NoIndex) + { + return; + } + + var instruction = _graph.Program.Instructions.FirstOrDefault(candidate => candidate.Pc == pc); + var source = InternSource(new DescriptorSource + { + Dwords = Enumerable.Repeat(_graph.Constant(0u), width).ToArray(), + Heap = new HeapRecordSelector(heapSource, memoryIndices[0], first.Offset, (uint)width * sizeof(uint)) + { + Cube = !sampler && instruction?.Control is Gen5ImageControl { Dimension: 3 }, + }, + }); + _heapRecords.Add(new HeapRecordPlan + { + Handle = handle, + Source = source, + Sampler = sampler, + SuppressMemoryReads = suppress, + Memory = memoryIndices, + Reads = reads, + }); + _info.UsesBindlessHeap = true; + } + // ---- indirect images ---- private bool IsIndirectPlanningMemory(int index) => diff --git a/src/SharpEmu.ShaderCompiler/Resources/RuntimeEvaluationScratch.cs b/src/SharpEmu.ShaderCompiler/Resources/RuntimeEvaluationScratch.cs index 79d533188..7984e6cf7 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/RuntimeEvaluationScratch.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/RuntimeEvaluationScratch.cs @@ -81,6 +81,18 @@ internal int Begin(int index, out ulong result) internal bool Contains(int index) => _stamps[index] == _generation; + internal bool TryGet(int index, out ulong result) + { + if (_stamps[index] == _generation) + { + result = _values[index]; + return true; + } + + result = 0; + return false; + } + internal void Store(int index, ulong value) { _values[index] = value; diff --git a/src/SharpEmu.ShaderCompiler/Resources/RuntimeImageSwizzle.cs b/src/SharpEmu.ShaderCompiler/Resources/RuntimeImageSwizzle.cs new file mode 100644 index 000000000..99e749fe5 --- /dev/null +++ b/src/SharpEmu.ShaderCompiler/Resources/RuntimeImageSwizzle.cs @@ -0,0 +1,150 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System; +using System.Collections.Generic; + +namespace SharpEmu.ShaderCompiler.Resources; + +// SHARPEMU_RUNTIME_IMAGE_SWIZZLE (on by default; =0 off): the destination select of a storage image (T# word 3, bits 0-11) +// is shader data instead of part of the module. Of a storage image with no conversion format, only a store reads the +// select: it puts each logical component in the physical channel the select names first (the other channels store zero, +// Gen5ShaderTranslator.GetImageStoreSourceIndex); its loads return the channels as stored. So the specialization keeps the +// identity select, the layout carries a store channel map per written image (BindingLayout.StorageImageSwizzlesDword), the +// descriptor path writes the maps from the bound T#s, and a store picks its channels by the map. Dispatches of one program +// over images whose selects differ share one module. +public static class RuntimeImageSwizzle +{ + public static bool Enabled { get; } = Environment.GetEnvironmentVariable("SHARPEMU_RUNTIME_IMAGE_SWIZZLE") != "0"; + + // An image whose stores take their channel map from shader data: a storage image bound through its own T#, not an indirect + // table's, with no conversion format. Heap and call-record images keep the identity select. + public static bool Serves(ImageResource image) => + image.ResourceClass == ImageResourceClass.Storage && image.ConversionFormat == DescriptorConstants.InvalidFormat && + image.IndirectRoot == DescriptorConstants.NoIndex; + + // The store channel map of a destination select: per physical channel (3 bits, X first) the logical component whose selector + // names it first (0-3), or 4 when none does and the channel stores zero. Each code is kept xor its channel, so the identity + // select's map, and an unwritten slot, is zero. + public static uint StoreChannelMap(uint destinationSelect) + { + var map = 0u; + for (var channel = 0u; channel < 4; channel++) + { + var source = 4u; + for (var component = 0u; component < 4; component++) + { + if (((destinationSelect >> (int)(component * 3)) & 7u) == 4u + channel) + { + source = component; + break; + } + } + + map |= (source ^ channel) << (int)(channel * 3); + } + + return map; + } + + // The slot of an image's store channel map: its rank among the written images whose select is shader data, or -1 + // for any other image. + public static int Slot(IReadOnlyList images, int index) + { + if ((uint)index >= (uint)images.Count || !TakesMap(images[index])) + { + return -1; + } + + var slot = 0; + for (var other = 0; other < index; other++) + { + slot += TakesMap(images[other]) ? 1 : 0; + } + + return slot; + } + + public static uint SlotCount(IReadOnlyList images) + { + var count = 0u; + foreach (var image in images) + { + count += TakesMap(image) ? 1u : 0u; + } + + return count; + } + + // Each written image's map in its slot, two to a dword: from its materialized T#, the identity for a null or absent + // descriptor (the select the module would have kept for it). + public static void WriteStoreMaps(uint[] shaderData, BindingLayout layout, IReadOnlyList images, + IReadOnlyList descriptors) + { + if (layout.StorageImageSwizzleCount == 0) + { + return; + } + + var first = (int)layout.StorageImageSwizzlesDword; + Array.Clear(shaderData, first, (int)(layout.StorageImageSwizzleCount + 1) / 2); + var slot = 0u; + for (var index = 0; index < images.Count; index++) + { + if (!TakesMap(images[index])) + { + continue; + } + + if (slot < layout.StorageImageSwizzleCount) + { + var map = StoreChannelMap(DestinationSelect(index < descriptors.Count ? descriptors[index] : null)); + shaderData[first + (int)(slot / 2)] |= map << (int)(slot % 2 * 16); + } + + slot++; + } + + if (slot != layout.StorageImageSwizzleCount) + { + throw new InvalidOperationException( + $"The store channel maps do not match the layout: images={slot} layout={layout.StorageImageSwizzleCount}."); + } + } + + private static bool TakesMap(ImageResource image) => image.Written && Serves(image); + + private static uint DestinationSelect(uint[]? words) => + words is { Length: >= 8 } && (words[0] != 0 || (words[1] & 0xFF) != 0) + ? words[3] & 0xFFF + : DescriptorConstants.IdentityImageSwizzle; + + // A recorded specialization (a prewarm record written with the selects baked in) with the select of every image + // whose select is shader data set to the identity, as the materializer keeps it; the same instance when nothing + // changes. + public static ResourceSpecialization Canonical(ShaderResourcePlan plan, ResourceSpecialization specialization) + { + if (!plan.Info.UsesRuntimeImageSwizzles) + { + return specialization; + } + + ResourceSpecialization? canonical = null; + var count = Math.Min(plan.Info.Images.Count, specialization.Images.Count); + for (var index = 0; index < count; index++) + { + var image = specialization.Images[index]; + if (plan.Info.Images[index].ResourceClass != ImageResourceClass.Storage || + image.ConversionFormat != DescriptorConstants.InvalidFormat || image.IndirectRoot != DescriptorConstants.NoIndex || + image.ShaderSwizzle == DescriptorConstants.IdentityImageSwizzle) + { + continue; + } + + canonical ??= specialization.Clone(); + canonical.Images[index] = image with { ShaderSwizzle = DescriptorConstants.IdentityImageSwizzle }; + } + + return canonical ?? specialization; + } +} diff --git a/src/SharpEmu.ShaderCompiler/Resources/RuntimeValueEvaluator.cs b/src/SharpEmu.ShaderCompiler/Resources/RuntimeValueEvaluator.cs index 562d83d8e..6e615f9c1 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/RuntimeValueEvaluator.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/RuntimeValueEvaluator.cs @@ -7,7 +7,7 @@ namespace SharpEmu.ShaderCompiler.Resources; // Evaluates graph values against one draw's inputs. Results are memoised so values // shared by several descriptors and flattened reads are computed once. -public sealed class RuntimeValueEvaluator +public sealed class RuntimeValueEvaluator : IEvaluatedValues { private const ulong AddressMask = 0x0000_FFFF_FFFF_FFFFul; @@ -297,8 +297,9 @@ internal static RawAddress ResolveRawAddress(ScalarValueKind kind, ulong baseAdd var size = stride == 0 ? (ulong)(uint)records : (ulong)stride * (uint)records; if (aligned > size || size - aligned < sizeof(uint)) { - // An unbound (empty) V# reads as zero; overrunning a bound buffer stays a failure. - return (uint)records == 0 || offset >= 0x8000_0000u ? RawAddress.Zero : RawAddress.Failed; + // The GPU does not read a dword past the V#'s records (scalar memory bounds checking): it reads as zero, as + // every dword of an unbound (empty) V# does. + return RawAddress.Zero; } address = ((baseAddress & ~3ul) + byteOffset) & ~3ul; @@ -371,6 +372,20 @@ internal bool IsEvaluated(ScalarValue value) => _compiled is not null && _compiled.TryGetIndex(value, out var index) ? _compiledValues.Contains(index) : _cache.TryGetValue(value, out _); + // A value this evaluator already holds, without evaluating it. + bool IEvaluatedValues.TryGetEvaluated(ScalarValue value, out ulong result) + { + if (value.IsConstant) + { + result = value.Payload; + return true; + } + + return _compiled is not null && _compiled.TryGetIndex(value, out var index) + ? _compiledValues.TryGet(index, out result) + : _cache.TryGetValue(value, out result); + } + internal void Seed(ScalarValue value, ulong result) { if (_compiled is not null && _compiled.TryGetIndex(value, out var index)) _compiledValues.Store(index, result); @@ -493,10 +508,22 @@ internal static bool EvaluateSources( // A failed transaction must not replay guest reads through the fallback evaluator. return transaction.Evaluate(inputs, additionalTableWords, out results, out table); } - ResourceMaterializationCache.RecordEvaluationPath(plan, - plan.ResourceBranches.Count != 0 ? "fallback_branches" : - plan.IndirectImages.Count != 0 ? "fallback_indirect_images" : - plan.BufferCandidateTables.Count != 0 ? "fallback_buffer_candidates" : "fallback_other_or_unavailable"); + // A branch plan's selected sources: its compiled branch transaction (on by default, SHARPEMU_COMPILED_BRANCHES). + var branchMode = evaluateTable && plan.ResourceBranches.Count != 0 && ReferenceEquals(sources, plan.MaterializationSources) && + ReferenceEquals(cleanFlatSlots, plan.CleanFlatSlots) ? BranchMode : CompiledBranchMode.Off; + var branches = branchMode != CompiledBranchMode.Off ? plan.CompiledBranches : null; + if (branches is not null) + { + ResourceMaterializationCache.RecordEvaluationPath(plan, "compiled_branches"); + } + else + { + ResourceMaterializationCache.RecordEvaluationPath(plan, + plan.ResourceBranches.Count != 0 ? "fallback_branches" : + plan.IndirectImages.Count != 0 ? "fallback_indirect_images" : + plan.BufferCandidateTables.Count != 0 ? "fallback_buffer_candidates" : "fallback_other_or_unavailable"); + } + var anyClean = false; foreach (var clean in cleanFlatSlots) { @@ -517,6 +544,24 @@ internal static bool EvaluateSources( using var branchProfile = ResourceMaterializationProfile.Measure(ResourceMaterializationProfile.Phase.BranchSelection); activeSources = EvaluateActiveSources(plan, inputs, cleanEvaluator, cleanScratch); } + + if (branches is not null) + { + BranchesServedOnThread++; + return branches.Evaluate(inputs, additionalTableWords, activeSources, cleanEvaluator, out results, out table); + } + + return EvaluateSelected(plan, sources, inputs, cleanFlatSlots, evaluateTable, activeSources, evaluator, + cleanEvaluator, additionalTableWords, out results, out table); + } + + // The fallback after its selection: the active sources' words, then the table, through the two memoised evaluators. + private static bool EvaluateSelected(ShaderResourcePlan plan, IReadOnlyList sources, ResourceRuntimeInputs inputs, + IReadOnlyList cleanFlatSlots, bool evaluateTable, bool[] activeSources, RuntimeValueEvaluator evaluator, + RuntimeValueEvaluator cleanEvaluator, int additionalTableWords, out List results, out uint[] table) + { + results = []; + table = []; var evaluated = new List(sources.Count); using (ResourceMaterializationProfile.Measure(ResourceMaterializationProfile.Phase.DescriptorPrefetch)) RawReadPrefetch.PrefetchSources(plan, sources, activeSources, evaluator); @@ -595,6 +640,10 @@ private static bool[] EvaluateActiveSources(ShaderResourcePlan plan, ResourceRun foreach (var block in plan.ResourceBranches) foreach (var source in block.Sources) activeSources[source] = false; + // A plan that writes memory reads its predicates through a guard that keeps their addresses. + using var guard = plan.ResourceBranchesWithWrites && inputs.ReadCleanMemory is not null + ? new ResourceBranchWriteGuard(plan, inputs) : null; + var predicates = guard?.Evaluator ?? cleanEvaluator; var visited = scratch.PrepareBranches(plan.ResourceBranches.Count); var pending = scratch.PendingBranches; pending.Push(0); @@ -605,12 +654,13 @@ private static bool[] EvaluateActiveSources(ShaderResourcePlan plan, ResourceRun var block = plan.ResourceBranches[blockIndex]; foreach (var source in block.Sources) activeSources[source] = true; // An unreadable predicate keeps both paths; never use the general reader to choose one. - if (block.Condition is { } condition && inputs.ReadCleanMemory is not null && cleanEvaluator.Evaluate(condition, out var value)) + if (block.Condition is { } condition && inputs.ReadCleanMemory is not null && predicates.Evaluate(condition, out var value)) pending.Push(block.Successors[value != 0 ? 0 : 1]); else foreach (var successor in block.Successors) pending.Push(successor); } + if (guard is not null && !guard.Holds()) Array.Fill(activeSources, true); ResourceMaterializationProfile.RecordActivity(activeSources); return activeSources; } @@ -629,4 +679,23 @@ public static bool EvaluateDescriptorSource(ShaderResourcePlan plan, uint source public static bool FlattenResourceTable(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, out uint[] table) => EvaluateSources(plan, [], inputs, [], evaluateTable: true, out _, out table); + + // ---- compiled branch transactions ---- + + // A branch plan's selected sources are evaluated with its CompiledBranchTransaction, on by default; + // SHARPEMU_COMPILED_BRANCHES=0, or any value but 1, turns it off. + internal enum CompiledBranchMode { Off, On } + + private static readonly CompiledBranchMode ConfiguredBranchMode = + Environment.GetEnvironmentVariable("SHARPEMU_COMPILED_BRANCHES") switch + { + null or "" or "1" => CompiledBranchMode.On, + _ => CompiledBranchMode.Off, + }; + + // Tests: a mode for the calling thread, and the calls the compiled form served on it. + [ThreadStatic] internal static CompiledBranchMode? BranchModeOverride; + [ThreadStatic] internal static int BranchesServedOnThread; + + internal static CompiledBranchMode BranchMode => BranchModeOverride ?? ConfiguredBranchMode; } diff --git a/src/SharpEmu.ShaderCompiler/Resources/RuntimeValueValidator.cs b/src/SharpEmu.ShaderCompiler/Resources/RuntimeValueValidator.cs index 8fc5672ac..6a4072af2 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/RuntimeValueValidator.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/RuntimeValueValidator.cs @@ -14,7 +14,12 @@ public sealed class RuntimeValueValidator private readonly uint _userDataCount; private readonly int _tableReadCount; private readonly ScalarValue? _activeMask; - private readonly HashSet _visiting = []; + // The nodes on the path from the root, by depth, and the results already proved. A result is kept only when its + // walk went back to no node above it on the path: the cycle cut there could make it depend on the path. Walking + // every path through a web of selects or phis instead took exponential time. + private readonly Dictionary _path = []; + private readonly Dictionary _known = []; + private int _lowestReentry = int.MaxValue; // Set when a failure traces back to a phi that isn't loop-invariant (e.g. a // hash-table/linear-probe bindless lookup): the value genuinely has no single @@ -68,19 +73,35 @@ public bool Validate(ScalarValue value) return true; } - if (!_visiting.Add(value)) + if (_known.TryGetValue(value, out var known)) { + return known; + } + + if (_path.TryGetValue(value, out var reentry)) + { + _lowestReentry = Math.Min(_lowestReentry, reentry); return false; } + var depth = _path.Count; + var outerReentry = _lowestReentry; + _lowestReentry = int.MaxValue; + _path.Add(value, depth); try { var result = ValidateNode(value); + if (_lowestReentry >= depth) + { + _known.Add(value, result); + } + return result; } finally { - _visiting.Remove(value); + _path.Remove(value); + _lowestReentry = Math.Min(outerReentry, _lowestReentry); } } diff --git a/src/SharpEmu.ShaderCompiler/Resources/ScalarDataReadPolicy.cs b/src/SharpEmu.ShaderCompiler/Resources/ScalarDataReadPolicy.cs new file mode 100644 index 000000000..7ebbd404d --- /dev/null +++ b/src/SharpEmu.ShaderCompiler/Resources/ScalarDataReadPolicy.cs @@ -0,0 +1,13 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.ShaderCompiler.Resources; + +// Startup policy: changes resource planning and emitted shader code, never a per-dispatch value substitution. +// Compute programs read bounded scalar data that only the shader consumes on the GPU instead of through the flattened +// table; SHARPEMU_GPU_SCALAR_DATA=0 flattens those reads on the host. +public static class ScalarDataReadPolicy +{ + public static bool Enabled { get; } = Environment.GetEnvironmentVariable("SHARPEMU_GPU_SCALAR_DATA") != "0"; + public const uint CacheIdentity = 0x53445201; +} diff --git a/src/SharpEmu.ShaderCompiler/Resources/ScalarGraphDiskCache.cs b/src/SharpEmu.ShaderCompiler/Resources/ScalarGraphDiskCache.cs index 98a96fca4..d3b0b6b8f 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ScalarGraphDiskCache.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ScalarGraphDiskCache.cs @@ -1,26 +1,47 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using System.IO.Compression; using System.Security.Cryptography; using System.Text; using System.Text.Json; namespace SharpEmu.ShaderCompiler.Resources; +// The running game's folder for the scalar graph disk cache: the presenter names it beside the game's pipeline cache. +public static class ShaderAnalysisCache +{ + public static void UseGameFolder(string folder) => ScalarGraphDiskCache.UseGameFolder(folder); +} + internal static class ScalarGraphDiskCache { - private const int Version = 4; + // 5: zlib-compressed entries. + private const int Version = 5; private const int MaxEntryBytes = 32 * 1024 * 1024; - private const long MaxCacheBytes = 256L * 1024 * 1024; - private static readonly string CachePath = Environment.GetEnvironmentVariable("SHARPEMU_SHADER_ANALYSIS_CACHE_PATH") ?? - Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SharpEmu", "shader-analysis"); + // Each game keeps its own cache, up to 8 GiB of compressed entries, trimmed by last use. One small folder shared by + // every game and trimmed by write time cannot hold one game's graphs: a game's opening and half an hour of play can + // build hundreds of megabytes of them, and play keeps adding graphs. A warm graph takes about a third off planning. + private const long MaxCacheBytes = 8L * 1024 * 1024 * 1024; + // A trim that passes the cap stops at this size, so the writes after it do not each list and trim the folder again. + private const long TrimTargetBytes = MaxCacheBytes / 10 * 9; + // SHARPEMU_SHADER_ANALYSIS_CACHE_PATH names the folder ("0" turns the cache off). Otherwise it is the running game's + // folder (UseGameFolder), kept like its pipeline binaries and prewarm list, so no game trims another's graphs; until a + // game names its folder the cache is off. + private static readonly string? CachePath = + Environment.GetEnvironmentVariable("SHARPEMU_SHADER_ANALYSIS_CACHE_PATH") is { Length: > 0 } configured ? configured : null; + private static volatile string? _gameFolder; + + internal static void UseGameFolder(string folder) => _gameFolder = folder; private static readonly bool Trace = Environment.GetEnvironmentVariable("SHARPEMU_PROFILE_SHADER_PLANNING") == "1"; private static readonly object WriteLock = new(); + // Each folder's size as last listed plus what this process wrote since (under WriteLock). + private static readonly Dictionary CountedBytes = new(StringComparer.OrdinalIgnoreCase); internal static ScalarValueGraph Build(Gen5ShaderProgram program, uint userDataBase, uint userDataCount, IReadOnlySet? fixedFunctionVertexLoads, uint waveSize, string? cachePath = null, ulong excludedUserDataRegisters = 0, int dynamicUserData = -1) { - var directory = cachePath ?? CachePath; + var directory = cachePath ?? CachePath ?? _gameFolder ?? "0"; if (directory == "0") return ScalarValueGraph.Build(program, userDataBase, userDataCount, fixedFunctionVertexLoads, waveSize, excludedUserDataRegisters, dynamicUserData); var key = Key(program, userDataBase, userDataCount, fixedFunctionVertexLoads, waveSize, excludedUserDataRegisters, dynamicUserData); var path = Path.Combine(directory, key + ".graph"); @@ -35,9 +56,10 @@ internal static ScalarValueGraph Build(Gen5ShaderProgram program, uint userDataB file.ReadExactly(bytes); if (CryptographicOperations.FixedTimeEquals(digest, SHA256.HashData(bytes))) { - using var reader = new BinaryReader(new MemoryStream(bytes, false)); + using var reader = new BinaryReader(Inflate(bytes)); if (reader.ReadString() != key) throw new InvalidDataException("Graph cache key mismatch."); var cached = ScalarValueGraph.ReadSnapshot(reader, program, userDataBase, userDataCount, fixedFunctionVertexLoads, waveSize, excludedUserDataRegisters, dynamicUserData); + MarkUsed(path); if (Trace) Console.Error.WriteLine($"[SHADER_ANALYSIS_CACHE] hit key={key} bytes={bytes.Length}"); return cached; } @@ -56,20 +78,25 @@ internal static ScalarValueGraph Build(Gen5ShaderProgram program, uint userDataB } if (stream.Length <= MaxEntryBytes - 32) { - var bytes = stream.GetBuffer().AsSpan(0, (int)stream.Length); + using var compressed = new MemoryStream(); + using (var zlib = new ZLibStream(compressed, CompressionLevel.Fastest, leaveOpen: true)) + { + zlib.Write(stream.GetBuffer(), 0, (int)stream.Length); + } + + var bytes = compressed.GetBuffer().AsSpan(0, (int)compressed.Length); lock (WriteLock) { Directory.CreateDirectory(directory); // Keep a bounded cache across compiler versions too. No live // analysis objects or guest memory are retained by the cache. - var entries = new DirectoryInfo(directory).GetFiles("*.graph").OrderBy(f => f.LastWriteTimeUtc).ToArray(); - var total = entries.Sum(f => f.Length) + stream.Length + 32; - foreach (var entry in entries) + var entryBytes = compressed.Length + 32; + if (!CountedBytes.TryGetValue(directory, out var counted) || counted + entryBytes > MaxCacheBytes) { - if (total <= MaxCacheBytes) break; - total -= entry.Length; - entry.Delete(); + counted = Trim(directory, entryBytes, MaxCacheBytes, TrimTargetBytes); } + + CountedBytes[directory] = counted + entryBytes; var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { @@ -122,6 +149,55 @@ internal static string Key(Gen5ShaderProgram program, uint userDataBase, uint us return Convert.ToHexString(SHA256.HashData(stream.GetBuffer().AsSpan(0, (int)stream.Length))); } + // An entry's snapshot, inflated (at most MaxEntryBytes; the reader needs a seekable stream). + private static MemoryStream Inflate(byte[] compressed) + { + var inflated = new MemoryStream(); + using (var zlib = new ZLibStream(new MemoryStream(compressed, false), CompressionMode.Decompress)) + { + var buffer = new byte[81920]; + int read; + while ((read = zlib.Read(buffer, 0, buffer.Length)) > 0) + { + if (inflated.Length + read > MaxEntryBytes) throw new InvalidDataException("Graph cache entry too large."); + inflated.Write(buffer, 0, read); + } + } + + inflated.Position = 0; + return inflated; + } + + // A hit marks its entry used: Trim drops the entries used longest ago, not the ones written longest ago. + private static void MarkUsed(string path) + { + try + { + File.SetLastAccessTimeUtc(path, DateTime.UtcNow); + } + catch (Exception error) when (IsCacheFailure(error)) { } + } + + // Lists the folder; when an entry of entryBytes would take it past capBytes, deletes the entries used longest ago until + // it fits within targetBytes. Returns the bytes that remain. + internal static long Trim(string directory, long entryBytes, long capBytes, long targetBytes) + { + var entries = new DirectoryInfo(directory).GetFiles("*.graph"); + var total = entries.Sum(static entry => entry.Length); + if (total + entryBytes <= capBytes) return total; + foreach (var entry in entries.OrderBy(LastUse)) + { + if (total + entryBytes <= targetBytes) break; + total -= entry.Length; + entry.Delete(); + } + + return total; + } + + private static DateTime LastUse(FileInfo entry) => + entry.LastAccessTimeUtc > entry.LastWriteTimeUtc ? entry.LastAccessTimeUtc : entry.LastWriteTimeUtc; + private static bool IsCacheFailure(Exception error) => error is IOException or UnauthorizedAccessException or InvalidDataException or ArgumentException or OverflowException; } diff --git a/src/SharpEmu.ShaderCompiler/Resources/ScalarValueGraph.Builder.cs b/src/SharpEmu.ShaderCompiler/Resources/ScalarValueGraph.Builder.cs index 12d24a1b6..bc57aa25b 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ScalarValueGraph.Builder.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ScalarValueGraph.Builder.cs @@ -272,7 +272,8 @@ private RegisterState MergePredecessors(int block) foreach (var key in laneKeys) { - var value = MergeSlot(block, RegisterState.LaneSlot(key.Register, key.Lane), visited, pending, (state, _) => state.Lanes[key]); + var value = MergeSlot(block, RegisterState.LaneSlot(key.Register, key.Lane), visited, pending, + static (state, slot) => state.Lanes[RegisterState.LaneOfSlot(slot)]); if (!value.IsUndefined) { merged.Lanes[key] = value; @@ -287,7 +288,8 @@ private RegisterState MergePredecessors(int block) foreach (var key in maskKeys) { - var value = MergeSlot(block, RegisterState.MaskSlot(key), visited, pending, (state, _) => state.ThreadBits[key]); + var value = MergeSlot(block, RegisterState.MaskSlot(key), visited, pending, + static (state, slot) => state.ThreadBits[RegisterState.MaskOfSlot(slot)]); if (!value.IsUndefined) { merged.ThreadBits[key] = value; @@ -1998,6 +2000,12 @@ public void Reset() public static int MaskSlot(uint register) => 32768 + (int)register; + // The keys back from their slots (a lane key is always below 64), so a merge reads them with a static lambda + // instead of a closure per key. + public static (uint Register, uint Lane) LaneOfSlot(int slot) => ((uint)(slot - 8192) / 64, (uint)(slot - 8192) % 64); + + public static uint MaskOfSlot(int slot) => (uint)(slot - 32768); + public ScalarValue Read(uint register) => register < ScalarRegisterCount ? Scalars[register] : _graph.Undefined(ScalarValueType.U32); diff --git a/src/SharpEmu.ShaderCompiler/Resources/ShaderResourceInfo.cs b/src/SharpEmu.ShaderCompiler/Resources/ShaderResourceInfo.cs index 631332422..52d6853b7 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ShaderResourceInfo.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ShaderResourceInfo.cs @@ -47,7 +47,6 @@ public sealed class BufferResource public uint Source { get; set; } public uint FirstUsePc { get; set; } public uint MaxByteExtent { get; set; } - public uint PackedStride { get; set; } public uint DescriptorFormat { get; set; } = DescriptorConstants.InvalidFormat; public uint DescriptorSwizzle { get; set; } = DescriptorConstants.IdentityDestinationSelect; public uint ImageAlias { get; set; } = DescriptorConstants.NoIndex; @@ -198,6 +197,14 @@ public sealed class ShaderResourceInfo // chose it): it binds DescriptorBindingKind.DeviceAddressFallback. public bool UsesDeviceAddressFallback { get; set; } + // Some access indexes a buffer binding (idxen): the layout carries every buffer binding's V# stride as shader data + // (BindingLayout.BufferStridesDword), which the access multiplies the index by. + public bool UsesIndexedBuffers { get; set; } + + // Storage images take their destination select from shader data (RuntimeImageSwizzle); the layout carries the store + // channel map of each written one (BindingLayout.StorageImageSwizzlesDword). + public bool UsesRuntimeImageSwizzles { get; set; } + public ShaderResourceInfo Clone() => new() { Buffers = Buffers.Select(buffer => buffer.Clone()).ToList(), @@ -218,6 +225,8 @@ public sealed class ShaderResourceInfo UsesCallRecords = UsesCallRecords, UsesCallMarks = UsesCallMarks, UsesDeviceAddressFallback = UsesDeviceAddressFallback, + UsesIndexedBuffers = UsesIndexedBuffers, + UsesRuntimeImageSwizzles = UsesRuntimeImageSwizzles, }; } @@ -259,6 +268,7 @@ public sealed class DescriptorSource public ScalarValue[] Dwords { get; init; } = []; public uint DwordCount => (uint)Dwords.Length; public IndirectImageSelector? IndirectImage { get; init; } + public HeapRecordSelector? Heap { get; init; } public CallRecordSelector? CallRecord { get; init; } } diff --git a/src/SharpEmu.ShaderCompiler/Resources/ShaderResourcePlan.CompiledRanges.cs b/src/SharpEmu.ShaderCompiler/Resources/ShaderResourcePlan.CompiledRanges.cs new file mode 100644 index 000000000..d1cbc524d --- /dev/null +++ b/src/SharpEmu.ShaderCompiler/Resources/ShaderResourcePlan.CompiledRanges.cs @@ -0,0 +1,22 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.ShaderCompiler.Resources; + +public sealed partial class ShaderResourcePlan +{ + // The compiled device-address ranges (CompiledDeviceAddressRanges), published with the compiled evaluator. + private CompiledDeviceAddressRanges? _compiledRanges; + + internal CompiledDeviceAddressRanges? CompiledRanges + { + get + { + _ = CompiledEvaluator; + return Volatile.Read(ref _compiledEvaluatorState) == 2 ? _compiledRanges : null; + } + } + + // Runs under the compile gate before the compiled state is published; it never throws. + private void CompileRangesNow() => _compiledRanges = CompiledDeviceAddressRanges.TryBuild(this); +} diff --git a/src/SharpEmu.ShaderCompiler/Resources/ShaderResourcePlan.cs b/src/SharpEmu.ShaderCompiler/Resources/ShaderResourcePlan.cs index bc8b57259..b9b524f33 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ShaderResourcePlan.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ShaderResourcePlan.cs @@ -19,7 +19,7 @@ public sealed record IndirectImageAccess(int MemoryIndex, ScalarValue Key, uint // The immutable resource analysis of one program: graph, descriptor sources, flattened // reads and dense tables. Built once, materialised per draw, free of any draw's user data. -public sealed class ShaderResourcePlan +public sealed partial class ShaderResourcePlan { private ShaderResourcePlan(ScalarValueGraph graph, ShaderStage stage, ulong hash) { @@ -45,6 +45,10 @@ private ShaderResourcePlan(ScalarValueGraph graph, ShaderStage stage, ulong hash public IReadOnlyList DescriptorSources { get; private set; } = []; public IReadOnlyList MaterializationSources { get; private set; } = []; public IReadOnlyList ResourceBranches { get; private set; } = []; + // Whether a plan with ResourceBranches writes memory, and the static buffers it writes through, which may be none + // when it writes only LDS or scratch (ResourceBranchWriteGuard). + public bool ResourceBranchesWithWrites { get; private set; } + public IReadOnlyList ResourceBranchWrites { get; private set; } = []; public IReadOnlyList TableReads { get; private set; } = []; public IReadOnlyDictionary FlattenedSlotByMemoryIndex { get; private set; } = new Dictionary(); public IReadOnlyList DynamicReads { get; private set; } = []; @@ -54,11 +58,14 @@ private ShaderResourcePlan(ScalarValueGraph graph, ShaderStage stage, ulong hash public bool RequiresSpecializationMemory { get; private set; } public ShaderResourceInfo Info { get; private set; } = new(); + public bool StableImageBindings { get; private set; } + internal RawReadPrefetchPlan? RawReadPrefetch { get; set; } private readonly object _compileGate = new(); private CompiledResourceEvaluator? _compiledEvaluator; private CompiledResourceTransaction? _compiledTransaction; private CompiledResourceTransaction? _compiledTableTransaction; + private CompiledBranchTransaction? _compiledBranches; internal ResourceMaterializer.SpecializationGuard? SpecializationGuard; private int _compiledEvaluatorState; @@ -97,6 +104,7 @@ internal CompiledResourceEvaluator? CompiledEvaluator lock (_compileGate) { if (Volatile.Read(ref _compiledEvaluatorState) == 2) return _compiledEvaluator; + CompileRangesNow(); CompiledResourceEvaluator? compiled; try { @@ -125,6 +133,15 @@ internal CompiledResourceEvaluator? CompiledEvaluator _compiledTableTransaction = null; } + try + { + _compiledBranches = CompiledBranchTransaction.Build(this); + } + catch (Exception exception) when (exception is not OutOfMemoryException) + { + _compiledBranches = null; + } + _compiledEvaluator = compiled; Volatile.Write(ref _compiledEvaluatorState, 2); return compiled; @@ -149,9 +166,24 @@ internal CompiledResourceTransaction? CompiledTableTransaction } } + // The compiled form of a branch plan's selected sources (CompiledBranchTransaction); null for other plans and + // until the SRT compiler has built it. + internal CompiledBranchTransaction? CompiledBranches + { + get + { + _ = CompiledEvaluator; + return Volatile.Read(ref _compiledEvaluatorState) == 2 ? _compiledBranches : null; + } + } + // The handles each memory access reads, after flattened reads were replaced. public MemoryAccessBinding?[] Accesses { get; private set; } = []; + // The image accesses whose image or sampler is a bindless heap record, and the heap V#s they read. + public IReadOnlyList HeapRecords { get; private set; } = []; + public IReadOnlyList HeapRecordSources { get; private set; } = []; + // The image accesses whose image or sampler a linked callee's call record holds, and what each callee reads through its // records' arguments besides them (by its slot among the program's call targets; empty unless linked with run-time // arguments). @@ -163,11 +195,16 @@ internal CompiledResourceTransaction? CompiledTableTransaction public IReadOnlyDictionary CallRecordArguments { get; private set; } = new Dictionary(); + // The accesses whose bindless image or sampler descriptor reads as null. + public IReadOnlyList NullBindlessDescriptorPcs { get; private set; } = []; + public static ShaderResourcePlan Extract(Gen5ShaderProgram program, ShaderStage stage, ulong hash, uint userDataBase, uint userDataCount, IReadOnlySet? fixedFunctionVertexLoads = null, Action? beforeResourceTracking = null, uint waveSize = 64, - bool callRecords = false, bool callMarks = false, int dynamicUserData = -1, - BufferDescriptorNormalizer? normalizeBufferDescriptor = null, - ImageDescriptorNormalizer? normalizeImageDescriptor = null, Func? imageNormalizationVersion = null) + bool bindlessNullDescriptors = false, bool bindlessHeap = false, bool callRecords = false, bool callMarks = false, + int dynamicUserData = -1, BufferDescriptorNormalizer? normalizeBufferDescriptor = null, + ImageDescriptorNormalizer? normalizeImageDescriptor = null, Func? imageNormalizationVersion = null, + StableImageDescriptorLimits stableImageLimits = default, bool? scalarDataOnDevice = null, + bool? deviceRecordCounts = null, bool? runtimeImageSwizzles = null) { // Mesh system inputs are not uniform user data, even when a GS pointer occupies s0:s1. var graph = ScalarGraphDiskCache.Build(program, userDataBase, userDataCount, fixedFunctionVertexLoads, waveSize, @@ -178,7 +215,8 @@ public static ShaderResourcePlan Extract(Gen5ShaderProgram program, ShaderStage NormalizeImageDescriptor = normalizeImageDescriptor, ImageNormalizationVersion = imageNormalizationVersion, }; - var reads = ResourceTableReadPlanner.Plan(graph, stage, hash); + plan.DeviceRecordCounts = (deviceRecordCounts ?? DeviceRecordCountPlan.Enabled) ? DeviceRecordCountPlan.Create(graph, stage) : null; + var reads = ResourceTableReadPlanner.Plan(graph, stage, hash, scalarDataOnDevice ?? ScalarDataReadPolicy.Enabled, plan.DeviceRecordCounts); var memo = new Dictionary(); ScalarValue Rewrite(ScalarValue value) => graph.Substitute(value, reads.Replacements, memo); ScalarValue RewriteRead(ScalarValue read) @@ -215,10 +253,16 @@ ScalarValue RewriteRead(ScalarValue read) // Diagnostics observe rewritten values before descriptor validation. beforeResourceTracking?.Invoke(plan); - var tracked = ResourceTracker.Track(plan, callRecords); + var tracked = ResourceTracker.Track(plan, bindlessNullDescriptors, bindlessHeap, callRecords); plan.DescriptorSources = tracked.Sources; plan.Info = tracked.Info; + plan.NullBindlessDescriptorPcs = tracked.NullBindlessDescriptorPcs; + plan.HeapRecords = tracked.HeapRecords; plan.CallRecords = tracked.CallRecords; + plan.HeapRecordSources = tracked.HeapRecords + .Select(record => new HeapRecordSource(plan.DescriptorSources[(int)record.Source].Heap!.HeapSource, record.Sampler)) + .Distinct() + .ToList(); if (program.Instructions.Any(instruction => instruction.Control is ShaderCallFaultControl)) plan.Info.UsesDeviceAddresses = true; // A program with shader calls, or a compute program with many device-address dwords (CompactMemoryAccessPolicy), @@ -228,6 +272,8 @@ ScalarValue RewriteRead(ScalarValue read) plan.Info.UsesDeviceAddressFallback = true; if (callMarks && program.Instructions.Any(static instruction => instruction.Control is ShaderCallFaultControl { ReturnPc: not null })) plan.Info.UsesCallMarks = true; + // Storage image selects as shader data (RuntimeImageSwizzle, SHARPEMU_RUNTIME_IMAGE_SWIZZLE unless the caller says). + plan.Info.UsesRuntimeImageSwizzles = runtimeImageSwizzles ?? RuntimeImageSwizzle.Enabled; plan.IndirectImages = tracked.IndirectImages; plan.BufferCandidateTables = tracked.BufferCandidateTables; plan.DynamicReads = plan.DynamicReads.Where(read => !tracked.IndirectReads.Contains(read)).ToList(); @@ -285,6 +331,8 @@ ScalarValue RewriteRead(ScalarValue read) plan.CleanFlatSlots = cleanSlots; plan.ResourceBranches = ResourceBranchBlock.Build(plan, Rewrite); + plan.ResourceBranchesWithWrites = plan.ResourceBranches.Count != 0 && ResourceBranchBlock.Writes(plan); + plan.ResourceBranchWrites = plan.ResourceBranchesWithWrites ? ResourceBranchBlock.WrittenBuffers(plan) ?? [] : []; plan.DeviceAddressRanges = DeviceAddressRangePlanner.Plan(plan); plan.CallRecordCallees = CallRecordPlanner.Plan(plan); @@ -300,10 +348,12 @@ ScalarValue RewriteRead(ScalarValue read) } plan.WrittenRangeSlotByHandle = writtenSlots; + plan.StableImageBindings = stableImageLimits.Fits(plan); return plan; } public const int WrittenRangeDwordCount = 3; + public DeviceRecordCountPlan? DeviceRecordCounts { get; private set; } // Planned after tracking; optional, and never a reason for the plan to fail. public IReadOnlyList DeviceAddressRanges { get; private set; } = []; diff --git a/src/SharpEmu.ShaderCompiler/Resources/StableImageDescriptorLimits.cs b/src/SharpEmu.ShaderCompiler/Resources/StableImageDescriptorLimits.cs new file mode 100644 index 000000000..d55393eb6 --- /dev/null +++ b/src/SharpEmu.ShaderCompiler/Resources/StableImageDescriptorLimits.cs @@ -0,0 +1,40 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.ShaderCompiler.Resources; + +// Zero limits preserve compact bindings. Admission depends only on the immutable plan and host +// limits, never on descriptor equality or the current image formats. Samplers still coalesce. +public readonly record struct StableImageDescriptorLimits( + uint SampledImages, uint StorageImages, uint Samplers, uint StorageBuffers, uint Resources) +{ + internal bool Fits(ShaderResourcePlan plan) + { + var info = plan.Info; + // The caller passes the stage's own budget: graphics stages share a set when a pipeline is built whole + // (ShaderDescriptorLimits.GraphicsImageLimits). Linked, heap and candidate layouts need a separate + // bound on their full demand; dynamic storage images can add a descriptor for every mip. + if (Resources == 0 || info.Images.Count == 0 || + plan.RequiresSpecializationMemory || plan.IndirectImages.Count != 0 || plan.BufferCandidateTables.Count != 0 || + info.UsesBindlessHeap || info.UsesCallRecords || info.UsesCallMarks || + Gen5ShaderCallLinker.IsLinked(plan.Graph.Program) || + plan.Graph.Program.Instructions.Any(instruction => instruction.Opcode is "SSwappcB64" or "SCallB64") || + plan.DescriptorSources.Any(source => source.IndirectImage is not null) || + info.Images.Any(image => image.IndirectRoot != DescriptorConstants.NoIndex || + image.MipMode != ImageMipMode.None || image.MipCount != 1 || + image.ResourceClass is not (ImageResourceClass.Sampled or ImageResourceClass.Storage))) + return false; + + ulong sampled = (ulong)info.Images.Count(image => image.ResourceClass == ImageResourceClass.Sampled); + ulong storage = (ulong)info.Images.Count - sampled; + // Point-filter copies and then depth-compare copies can each double the sampler count. + ulong samplers = (ulong)info.Samplers.Count * 4; + // Reserve all optional ordinary helpers: flattened table, shader data and mip statistics. + ulong buffers = (ulong)info.Buffers.Count + 3; + if (info.UsesDeviceAddresses) buffers += 2; // Page table and fault buffer. + if (info.UsesDeviceAddressFallback) buffers++; + if (BindingLayout.UsesGlobalDataShare(plan.Graph.Program)) buffers++; + return sampled <= SampledImages && storage <= StorageImages && samplers <= Samplers && + buffers <= StorageBuffers && sampled + storage + buffers <= Resources; + } +} diff --git a/src/SharpEmu.ShaderCompiler/ShaderCompileRequest.cs b/src/SharpEmu.ShaderCompiler/ShaderCompileRequest.cs index f277af770..6569f2ba6 100644 --- a/src/SharpEmu.ShaderCompiler/ShaderCompileRequest.cs +++ b/src/SharpEmu.ShaderCompiler/ShaderCompileRequest.cs @@ -72,7 +72,10 @@ public readonly record struct MeshShaderConfiguration( bool InputTriangleStrip = false, uint DeviceSubgroupLaneCount = 0, bool InputPointList = false, - bool InputLineList = false) + bool InputLineList = false, + // The task stage of an automatic draw launches the groups and passes the draw parameters in + // its payload (SpirvMeshTask), in place of the shader data. + bool TaskLaunched = false) { public static uint[] ParameterLocations(Gen5ShaderProgram program, int requiredOutputCount) => program.Instructions.Select(instruction => instruction.Control).OfType() @@ -123,10 +126,22 @@ public ShaderCompileRequest(ShaderResourcePlan plan, SpecializedResourceInfo res FlattenedSlotByMemoryIndex = new Dictionary(plan.FlattenedSlotByMemoryIndex); FlattenedTableReservedWords = (uint)plan.FlattenedTableReservedCount; + var heapImages = new Dictionary(); + var heapSamplers = new Dictionary(); + foreach (var record in plan.HeapRecords) + { + var heap = plan.DescriptorSources[(int)record.Source].Heap!; + (record.Sampler ? heapSamplers : heapImages)[record.MemoryIndex] = + new HeapRecordUse(heap.KeyMemoryIndex, heap.Immediate, heap.RecordBytes); + } + + HeapImageByMemoryIndex = heapImages; + HeapSamplerByMemoryIndex = heapSamplers; (CallRecordImageByMemoryIndex, CallRecordSamplerByMemoryIndex, CallRecordCallees) = PlanCallRecordFields(plan, resources); - IndirectKeyMemoryIndices = plan.IndirectImages.Select(access => access.Key.MemoryIndex).ToHashSet(); + var heapKeys = heapImages.Values.Concat(heapSamplers.Values).Select(use => use.KeyMemoryIndex).ToList(); + IndirectKeyMemoryIndices = plan.IndirectImages.Select(access => access.Key.MemoryIndex).Concat(heapKeys).ToHashSet(); IndirectOffsetKeyMemoryIndices = plan.IndirectImages.Where(access => access.KeyIsAddressOffset) - .Select(access => access.Key.MemoryIndex).ToHashSet(); + .Select(access => access.Key.MemoryIndex).Concat(heapKeys).ToHashSet(); IndirectRootByMemoryIndex = plan.IndirectImages.ToDictionary(access => access.MemoryIndex, access => access.Key.MemoryIndex); var writtenSlots = new Dictionary(); @@ -205,8 +220,13 @@ public ShaderCompileRequest WithProgram(Gen5ShaderProgram program) public IReadOnlySet IndirectOffsetKeyMemoryIndices { get; } - // The program reads call records through descriptor set 1 (BindlessHeap). - public bool UsesBindlessHeap => CallRecordImageByMemoryIndex.Count != 0 || CallRecordSamplerByMemoryIndex.Count != 0; + // Image accesses whose image or sampler is a bindless heap record: memory index → how the record is read. + public IReadOnlyDictionary HeapImageByMemoryIndex { get; } + + public IReadOnlyDictionary HeapSamplerByMemoryIndex { get; } + + public bool UsesBindlessHeap => HeapImageByMemoryIndex.Count != 0 || HeapSamplerByMemoryIndex.Count != 0 || + CallRecordImageByMemoryIndex.Count != 0 || CallRecordSamplerByMemoryIndex.Count != 0; // Image accesses whose image or sampler a call record holds: memory index → its field and set-1 array. public IReadOnlyDictionary CallRecordImageByMemoryIndex { get; } @@ -292,16 +312,38 @@ [.. uses.Where(use => use.Callee == callee).Select(use => use.Field).Distinct() public bool MipStatisticsSubgroupReduction { get; init; } + // The host subgroup of this stage is one guest wave32 and has arithmetic operations: wave32 MIN/MAX scans then + // become subgroup reductions (Gen5SpirvTranslator.WaveReductions). + public bool SubgroupArithmetic { get; init; } + // The device supports 64-bit integer atomics on workgroup memory // (VkPhysicalDeviceFeatures.shaderSharedInt64Atomics). When set, the LDS // 64-bit atomics are emitted as real 64-bit atomics instead of a pair of // 32-bit ones, which is not atomic as a pair. public bool SupportsSharedInt64Atomics { get; init; } + // The device supports 64-bit integer atomics on storage buffers (shaderBufferInt64Atomics). When set, an + // aligned X2 buffer atomic (SWAP, AND, OR) is one 64-bit atomic, as on the GPU; as two 32-bit atomics another + // thread group can read one half of a pair from one update and the other half from another. + public bool SupportsBufferInt64Atomics { get; init; } + // The device supports 64-bit integer atomics on images (shaderImageInt64Atomics). Without // it a program that uses an atomic on a 64-bit texel is rejected at compile time. public bool SupportsImageInt64Atomics { get; init; } + + // The device has a shader-readable device clock (shaderDeviceClock), which S_MEMTIME and + // S_MEMREALTIME read. + public bool SupportsShaderDeviceClock { get; init; } public bool ShaderSignedZeroInfNanPreserveFloat32Supported { get; init; } + + // The device bounds every storage buffer access by its descriptor's range and reads zero past it (robustBufferAccess2), + // so a guest buffer load needs no bounds check of its own. + public bool RobustBufferAccess2 { get; init; } + + // The device has 16-bit floats (shaderFloat16) and float controls that can give them alone round-to-nearest-even, kept + // denormals and kept signed zero, infinity and NaN, so an f16 value widens and narrows with OpFConvert as the guest + // converts it. + public bool NativeFloat16Conversions { get; init; } public Gen5ComputeSystemRegisters? ComputeSystemRegisters { get; init; } public IReadOnlyList PixelOutputs { get; init; } = []; diff --git a/tests/SharpEmu.Libs.Tests/Agc/AgcDrawIndex2Tests.cs b/tests/SharpEmu.Libs.Tests/Agc/AgcDrawIndex2Tests.cs index 01ab2ff7c..75b88c650 100644 --- a/tests/SharpEmu.Libs.Tests/Agc/AgcDrawIndex2Tests.cs +++ b/tests/SharpEmu.Libs.Tests/Agc/AgcDrawIndex2Tests.cs @@ -22,8 +22,11 @@ public sealed class AgcDrawIndex2Tests [Theory] [InlineData(0u, 0u, 0UL, 0x280u, 0x280u, 2u, 3)] [InlineData(1u, 0u, 0UL, 0x280u, 0x280u, 2u, 0)] - [InlineData(1u, 1u, 0x60180707UL, 0x010C010Fu, 0x0800010Fu, 0x22u, 1)] - [InlineData(1u, 5u, 0x160180707UL, 0x010C010Fu, 0x0800010Fu, 2u, 3)] + [InlineData(1u, 1u, 0x60180707UL, 0x0000010Fu, 0x0000010Fu, 0x22u, 1)] + [InlineData(1u, 5u, 0x160180707UL, 0x0000010Fu, 0x0000010Fu, 2u, 3)] + [InlineData(0u, 0u, 0x5C000008UL, 0x00A80280u, 0x08000280u, 2u, 3)] + [InlineData(0u, 0u, 0x5C000018UL, 0x00000280u, 0x00000280u, 2u, 3)] + [InlineData(0u, 0u, 0x60180705UL | 0x0F000008UL, 0x011B010Fu, 0x0800010Fu, 0x22u, 3)] public void IndexedMultiDrawPreservesCountAddressStrideAndModifier( uint countFromMemory, uint memoryCount, ulong modifier, uint vertexLocations, uint instanceLocation, uint initiator, int expectedDraws) @@ -71,6 +74,56 @@ public void IndexedMultiDrawPreservesCountAddressStrideAndModifier( Assert.Equal((uint)(7 + draw), runner.Host.IndexedDraws[draw].IndexCount); Assert.Equal(2u, runner.Host.IndexedDraws[draw].InstanceCount); } + + // The CP writes each draw's ordinal to the draw index register. + if ((instanceLocation & (1u << 27)) != 0) + { + Assert.Equal((uint)expectedDraws - 1, runner.Interpreter.Registers.Shader[vertexLocations >> 16]); + } + } + + [Theory] + [InlineData(0u, 0u, 3)] + [InlineData(1u, 2u, 2)] + public void NonIndexedMultiDrawWritesItsPacketAndDrawsEachRecord(uint countFromMemory, uint memoryCount, int expectedDraws) + { + var memory = new FakeCpuMemory(BaseAddress, 0x1000); + var context = new CpuContext(memory, Generation.Gen5); + var commandBufferAddress = BaseAddress + 0x80; + var stackAddress = BaseAddress + 0x500; + WriteUInt64(memory, commandBufferAddress + 0x10, CommandAddress); + WriteUInt64(memory, commandBufferAddress + 0x18, CommandAddress + 40); + WriteUInt64(memory, stackAddress + 8, 0); + context[CpuRegister.Rdi] = commandBufferAddress; + context[CpuRegister.Rsi] = 16; + context[CpuRegister.Rdx] = countFromMemory; + context[CpuRegister.Rcx] = 3; + context[CpuRegister.R8] = StreamRunner.LabelAddress; + context[CpuRegister.R9] = 32; + context[CpuRegister.Rsp] = stackAddress; + AgcExports.DcbDrawIndirectMulti(context); + Assert.Equal(CommandAddress, context[CpuRegister.Rax]); + Span bytes = stackalloc byte[40]; + Assert.True(memory.TryRead(CommandAddress, bytes)); + var packet = new uint[10]; + for (var index = 0; index < packet.Length; index++) + packet[index] = BinaryPrimitives.ReadUInt32LittleEndian(bytes[(index * 4)..]); + Assert.Equal(new uint[] { PacketHeader.Make(10, PacketOpcode.DrawIndirectMulti), + 16, 0x280, 0x280, countFromMemory << 30, 3, + StreamRunner.Low(StreamRunner.LabelAddress), StreamRunner.High(StreamRunner.LabelAddress), 32, 2 }, packet); + + var runner = new StreamRunner(); + runner.Host.WriteDword(StreamRunner.LabelAddress, memoryCount); + for (var draw = 0u; draw < 3; draw++) + runner.Host.WriteWords(StreamRunner.DataAddress + 16 + draw * 32, new uint[] { 7 + draw, 2, 0, 0 }); + Assert.Equal(SubmissionProgress.Complete, runner.Run( + StreamRunner.Packet(PacketOpcode.SetBase, 1, StreamRunner.Low(StreamRunner.DataAddress), StreamRunner.High(StreamRunner.DataAddress)), packet)); + Assert.Equal(expectedDraws, runner.Host.AutoDraws.Count); + for (var draw = 0; draw < expectedDraws; draw++) + { + Assert.Equal((uint)(7 + draw), runner.Host.AutoDraws[draw].VertexCount); + Assert.Equal(2u, runner.Host.AutoDraws[draw].InstanceCount); + } } [Theory] @@ -80,6 +133,7 @@ public void IndexedMultiDrawPreservesCountAddressStrideAndModifier( [InlineData(0x60180705UL, 0x10Fu, 0x10Fu, 0x22u)] [InlineData(0xA0180605UL, 0x10Fu, 0x10Fu, 2u)] [InlineData(0x40180605UL, 0x8Fu, 0x8Fu, 2u)] + [InlineData(0x40180615UL, 0x280u, 0x280u, 2u)] public void DrawIndirectEncodesTheModifierBeforeInterpretation( ulong drawModifier, uint firstVertexRegister, uint firstInstanceRegister, uint drawInitiator) { @@ -111,14 +165,24 @@ public void DrawIndirectEncodesTheModifierBeforeInterpretation( StreamRunner.Packet(PacketOpcode.SetBase, 1, StreamRunner.Low(StreamRunner.DataAddress), StreamRunner.High(StreamRunner.DataAddress)), packet)); var draw = Assert.Single(runner.Host.AutoDraws); - Assert.Equal((9u, 3u, 1u, 2u), (draw.VertexCount, draw.InstanceCount, draw.FirstVertex, draw.FirstInstance)); + // A start the packet names a register for reaches the shader there (the start instance is written last), and + // the draw counts from 0. + var named = firstVertexRegister != 0x280u; + Assert.Equal((9u, 3u, named ? 0u : 1u, named ? 0u : 2u), (draw.VertexCount, draw.InstanceCount, draw.FirstVertex, draw.FirstInstance)); + if (named) + { + Assert.Equal(2u, runner.Interpreter.Registers.Shader[firstInstanceRegister]); + } } [Theory] [InlineData(0x40000000UL, 0x280u, 0x280u, 2u)] [InlineData(0x40000100UL, 0x280u, 0x280u, 0x22u)] [InlineData(0x140000100UL, 0x280u, 0x280u, 2u)] - [InlineData(0x60180707UL, 0x010C010Fu, 0x0800010Fu, 0x22u)] + [InlineData(0x60180707UL, 0x0000010Fu, 0x0000010Fu, 0x22u)] + [InlineData(0x5C000008UL, 0x00000280u, 0x00000280u, 2u)] + [InlineData(0x60180715UL, 0x00000280u, 0x00000280u, 0x22u)] + [InlineData(0x40180605UL | 0x0F000008UL, 0x0000008Fu, 0x0000008Fu, 2u)] public void IndexedIndirectDrawEncodesTheModifierBeforeInterpretation( ulong modifier, uint vertexLocations, uint instanceLocation, uint initiator) { @@ -151,8 +215,15 @@ public void IndexedIndirectDrawEncodesTheModifierBeforeInterpretation( Assert.Equal(7u, draw.IndexCount); Assert.Equal(2u, draw.InstanceCount); Assert.Equal(StreamRunner.DataAddress + 6, draw.IndexAddress); - Assert.Equal(4, draw.BaseVertex); - Assert.Equal(5u, draw.FirstInstance); + var named = (vertexLocations & 0xFFFFu) != 0x280u; + Assert.Equal(named ? 0 : 4, draw.BaseVertex); + Assert.Equal(named ? 0u : 5u, draw.FirstInstance); + if (named) + { + Assert.Equal(5u, runner.Interpreter.Registers.Shader[instanceLocation & 0xFFFFu]); + } + + Assert.Equal(0u, vertexLocations >> 16); } [Theory] diff --git a/tests/SharpEmu.Libs.Tests/Agc/AgcPacketWritesTests.cs b/tests/SharpEmu.Libs.Tests/Agc/AgcPacketWritesTests.cs new file mode 100644 index 000000000..3cba692d3 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Agc/AgcPacketWritesTests.cs @@ -0,0 +1,374 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.HLE; +using SharpEmu.Libs.Agc; +using Xunit; + +namespace SharpEmu.Libs.Tests.Agc; + +// AgcPacketWrites: marker emission keeps the ordinary write order, including write failures. +// The read optimizations have their own cases. +public sealed class AgcPacketWritesTests +{ + private const ulong BaseAddress = 0x2_4000_0000; + private const ulong CommandBufferAddress = BaseAddress + 0x100; + private const ulong PacketAddress = BaseAddress + 0x400; + private const ulong ValuesAddress = BaseAddress + 0x18000; + private const ulong StackAddress = BaseAddress + 0x20000; + private const ulong RoomyCursorDown = BaseAddress + 0x14000; + private const int MemorySize = 0x30000; + + private static T With(bool atOnce, Func action) + { + var saved = AgcPacketWrites.OverrideForTests; + AgcPacketWrites.OverrideForTests = atOnce; + try + { + return action(); + } + finally + { + AgcPacketWrites.OverrideForTests = saved; + } + } + + private sealed record Emitted(int Result, ulong Rax, ulong Cursor, byte[] Bytes, int Reads, int Writes, int Copies); + + private static void AssertSame(Emitted original, Emitted atOnce) + { + Assert.Equal(original.Result, atOnce.Result); + Assert.Equal(original.Rax, atOnce.Rax); + Assert.Equal(original.Cursor, atOnce.Cursor); + Assert.Equal(original.Bytes, atOnce.Bytes); + } + + private static Emitted PushMarker(bool atOnce, byte[] name, ulong nameAddress, int memorySize = MemorySize, ulong failedWrite = 0) + { + var memory = new CountingMemory(memorySize); + WriteUInt64(memory, CommandBufferAddress + 0x10, PacketAddress); + WriteUInt64(memory, CommandBufferAddress + 0x18, RoomyCursorDown); + Assert.True(memory.TryWrite(nameAddress, name)); + memory.FailedWriteAddress = failedWrite; + memory.ResetCounts(); + var ctx = new CpuContext(memory, Generation.Gen5) + { + [CpuRegister.Rdi] = CommandBufferAddress, + [CpuRegister.Rsi] = nameAddress, + }; + var result = With(atOnce, () => AgcExports.DcbPushMarker(ctx)); + var (reads, writes, copies) = (memory.ReadCalls, memory.WriteCalls, memory.CopyCalls); + memory.FailedWriteAddress = 0; + var bytes = new byte[4200]; + Assert.True(memory.TryRead(PacketAddress, bytes)); + return new Emitted(result, ctx[CpuRegister.Rax], ReadUInt64(memory, CommandBufferAddress + 0x10), bytes, reads, writes, copies); + } + + private static byte[] Name(int length, bool terminated = true) + { + var name = new byte[length + (terminated ? 1 : 0)]; + for (var index = 0; index < length; index++) + name[index] = (byte)('a' + index % 26); + return name; + } + + [Theory] + [InlineData(0)] + [InlineData(3)] + [InlineData(4)] + [InlineData(70)] + [InlineData(4094)] + public void APushMarkerKeepsOrdinaryEmissionWhenPacketWritesAreEnabled(int length) + { + var original = PushMarker(false, Name(length), ValuesAddress); + var atOnce = PushMarker(true, Name(length), ValuesAddress); + + AssertSame(original, atOnce); + Assert.Equal(PacketAddress, atOnce.Rax); + // Name reads may differ; packet allocation and every write keep their ordinary order. + Assert.Equal(original.Writes, atOnce.Writes); + } + + [Theory] + [InlineData(10)] + [InlineData(100)] + public void ANameEndingAtTheEndOfReadableMemoryReadsTheSame(int length) + { + // The name and its terminator end at the last readable byte, so a 64-byte chunk past it cannot be read. + var name = Name(length); + var nameAddress = BaseAddress + MemorySize - (ulong)name.Length; + var original = PushMarker(false, name, nameAddress); + var atOnce = PushMarker(true, name, nameAddress); + + AssertSame(original, atOnce); + Assert.Equal(PacketAddress, atOnce.Rax); + } + + [Fact] + public void ANameWithoutATerminatorFailsTheSame() + { + var unterminated = Name(40, terminated: false); + var original = PushMarker(false, unterminated, BaseAddress + MemorySize - 40); + var atOnce = PushMarker(true, unterminated, BaseAddress + MemorySize - 40); + var tooLong = PushMarker(true, Name(4095), ValuesAddress); + + AssertSame(original, atOnce); + Assert.Equal(0UL, atOnce.Rax); + Assert.Equal(PacketAddress, atOnce.Cursor); + Assert.Equal(0UL, tooLong.Rax); + } + + [Fact] + public void AMarkerWhoseCursorCannotMoveFailsAsTheOriginalPathDoes() + { + var original = PushMarker(false, Name(20), ValuesAddress, failedWrite: CommandBufferAddress + 0x10); + var atOnce = PushMarker(true, Name(20), ValuesAddress, failedWrite: CommandBufferAddress + 0x10); + + AssertSame(original, atOnce); + Assert.Equal(0UL, atOnce.Rax); + Assert.Equal(PacketAddress, atOnce.Cursor); + } + + [Fact] + public void AMarkerWhosePacketCannotBeWrittenKeepsTheOriginalPath() + { + // Ordinary header/name-word writes stop at the same failing address, without a speculative block or rollback. + var original = PushMarker(false, Name(20), ValuesAddress, failedWrite: PacketAddress + 12); + var atOnce = PushMarker(true, Name(20), ValuesAddress, failedWrite: PacketAddress + 12); + + AssertSame(original, atOnce); + Assert.Equal(0UL, atOnce.Rax); + } + + private static (int Result, ulong Rax, byte[] Packet, int Reads) Release(bool atOnce, ulong stackAddress) + { + var memory = new CountingMemory(); + WriteUInt64(memory, CommandBufferAddress + 0x10, PacketAddress); + WriteUInt64(memory, CommandBufferAddress + 0x18, RoomyCursorDown); + ulong[] arguments = [2, 0x1122_3344_5566_7788UL, 0, 0, 5, 0xFFFF_FFFF]; + for (var index = 0; index < arguments.Length; index++) + { + var at = stackAddress + 8 + (ulong)index * 8; + if (at + 8 <= BaseAddress + MemorySize) + WriteUInt64(memory, at, arguments[index]); + } + var ctx = new CpuContext(memory, Generation.Gen5) + { + [CpuRegister.Rdi] = CommandBufferAddress, + [CpuRegister.R9] = BaseAddress + 0xC08, + [CpuRegister.Rsp] = stackAddress, + }; + memory.ResetCounts(); + var result = With(atOnce, () => AgcExports.CbReleaseMem(ctx)); + var reads = memory.ReadCalls; + var packet = new byte[64]; + Assert.True(memory.TryRead(PacketAddress, packet)); + return (result, ctx[CpuRegister.Rax], packet, reads); + } + + [Fact] + public void AReleaseReadsItsSixStackWordsInOneRead() + { + var original = Release(atOnce: false, StackAddress); + var atOnce = Release(atOnce: true, StackAddress); + + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, original.Result); + Assert.Equal(PacketAddress, original.Rax); + Assert.Equal((original.Result, original.Rax), (atOnce.Result, atOnce.Rax)); + Assert.Equal(original.Packet, atOnce.Packet); + Assert.Equal(original.Reads - 5, atOnce.Reads); + } + + [Theory] + [InlineData(0x1000)] + [InlineData(8)] + public void AReleaseWhoseStackWordsCannotAllBeReadFailsAsTheOriginalPathDoes(int pastEnd) + { + // The last stack word, or every one, lies past readable memory. + var stackAddress = BaseAddress + MemorySize - 56 + (ulong)pastEnd; + var original = Release(atOnce: false, stackAddress); + var atOnce = Release(atOnce: true, stackAddress); + + Assert.Equal(0UL, original.Rax); + Assert.Equal((original.Result, original.Rax), (atOnce.Result, atOnce.Rax)); + Assert.Equal(original.Packet, atOnce.Packet); + } + + private sealed record OrderedEmission( + int Result, + ulong Rax, + ulong Cursor, + byte[] Bytes, + ulong[] CursorUpdates, + int RefusedRollbacks); + + private static OrderedEmission EmitWithCursorHistory(bool atOnce, bool marker, ulong failedPacketByte) + { + var memory = new CursorHistoryMemory(failedPacketByte); + WriteUInt64(memory, CommandBufferAddress + 0x10, PacketAddress); + WriteUInt64(memory, CommandBufferAddress + 0x18, RoomyCursorDown); + var sentinel = new byte[96]; + Array.Fill(sentinel, (byte)0xCD); + Assert.True(memory.TryWrite(PacketAddress, sentinel)); + + if (marker) + { + Assert.True(memory.TryWrite(ValuesAddress, Name(20))); + } + else + { + WriteUInt32(memory, ValuesAddress, 0x1234_0000); + WriteUInt32(memory, ValuesAddress + 4, 0x1234_0001); + WriteUInt32(memory, ValuesAddress + 8, 0x1234_0002); + } + + var ctx = new CpuContext(memory, Generation.Gen5) + { + [CpuRegister.Rdi] = CommandBufferAddress, + [CpuRegister.Rsi] = marker ? ValuesAddress : 0x40, + [CpuRegister.Rdx] = ValuesAddress, + [CpuRegister.Rcx] = 3, + }; + + memory.Arm(); + var result = With(atOnce, () => marker + ? AgcExports.DcbPushMarker(ctx) + : AgcExports.CbSetShRegisterRangeDirect(ctx)); + memory.Disarm(); + + var bytes = new byte[96]; + Assert.True(memory.TryRead(PacketAddress, bytes)); + return new OrderedEmission(result, ctx[CpuRegister.Rax], + ReadUInt64(memory, CommandBufferAddress + 0x10), bytes, + memory.CursorUpdates.ToArray(), memory.RefusedRollbacks); + } + + private static void AssertSameOrderedEmission(OrderedEmission original, OrderedEmission candidate) + { + Assert.Equal(original.Result, candidate.Result); + Assert.Equal(original.Rax, candidate.Rax); + Assert.Equal(original.Cursor, candidate.Cursor); + Assert.Equal(original.Bytes, candidate.Bytes); + Assert.Equal(original.CursorUpdates, candidate.CursorUpdates); + Assert.Equal(original.RefusedRollbacks, candidate.RefusedRollbacks); + } + + [Fact] + public void AMarkerWriteFailureDoesNotRetryFromAnUnrestoredCursor() + { + var original = EmitWithCursorHistory(atOnce: false, marker: true, failedPacketByte: PacketAddress + 20); + var candidate = EmitWithCursorHistory(atOnce: true, marker: true, failedPacketByte: PacketAddress + 20); + + Assert.Equal(0UL, original.Rax); + Assert.Equal(PacketAddress + 28, original.Cursor); + Assert.Equal(new[] { PacketAddress + 28 }, original.CursorUpdates); + Assert.Equal(0, original.RefusedRollbacks); + AssertSameOrderedEmission(original, candidate); + } + + private sealed class CursorHistoryMemory(ulong failedPacketByte) : ICpuMemory + { + private readonly FakeCpuMemory _memory = new(BaseAddress, MemorySize); + private bool _armed; + private bool _cursorAdvanced; + public System.Collections.Generic.List CursorUpdates { get; } = new(); + public int RefusedRollbacks { get; private set; } + + public void Arm() => _armed = true; + public void Disarm() => _armed = false; + + public bool TryRead(ulong address, Span destination) => _memory.TryRead(address, destination); + + public bool TryWrite(ulong address, ReadOnlySpan source) + { + if (_armed && address == CommandBufferAddress + 0x10 && source.Length == sizeof(ulong)) + { + var next = BinaryPrimitives.ReadUInt64LittleEndian(source); + if (_cursorAdvanced && next == PacketAddress) + { + RefusedRollbacks++; + return false; + } + + if (!_memory.TryWrite(address, source)) + return false; + + CursorUpdates.Add(next); + _cursorAdvanced |= next != PacketAddress; + return true; + } + + if (_armed && failedPacketByte != 0 && + failedPacketByte >= address && failedPacketByte - address < (ulong)source.Length) + { + return false; + } + + return _memory.TryWrite(address, source); + } + + public bool TryCopy(ulong destinationAddress, ulong sourceAddress, ulong length) + { + var bytes = new byte[checked((int)length)]; + return TryRead(sourceAddress, bytes) && TryWrite(destinationAddress, bytes); + } + } + + private sealed class CountingMemory(int size = MemorySize) : ICpuMemory + { + private readonly FakeCpuMemory _memory = new(BaseAddress, size); + public ulong FailedReadAddress { get; set; } + public ulong FailedWriteAddress { get; set; } + public int CopyCalls { get; private set; } + public int ReadCalls { get; private set; } + public int WriteCalls { get; private set; } + + public void ResetCounts() => (ReadCalls, WriteCalls, CopyCalls) = (0, 0, 0); + + private static bool Includes(ulong address, ulong length, ulong target) => + target != 0 && target >= address && target - address < length; + + public bool TryRead(ulong address, Span destination) + { + ReadCalls++; + return !Includes(address, (ulong)destination.Length, FailedReadAddress) && _memory.TryRead(address, destination); + } + + public bool TryWrite(ulong address, ReadOnlySpan source) + { + WriteCalls++; + return !Includes(address, (ulong)source.Length, FailedWriteAddress) && _memory.TryWrite(address, source); + } + + public bool TryCopy(ulong destinationAddress, ulong sourceAddress, ulong length) + { + CopyCalls++; + if (Includes(sourceAddress, length, FailedReadAddress) || Includes(destinationAddress, length, FailedWriteAddress)) + return false; + var bytes = new byte[checked((int)length)]; + return _memory.TryRead(sourceAddress, bytes) && _memory.TryWrite(destinationAddress, bytes); + } + } + + private static ulong ReadUInt64(ICpuMemory memory, ulong address) + { + Span buffer = stackalloc byte[sizeof(ulong)]; + Assert.True(memory.TryRead(address, buffer)); + return BinaryPrimitives.ReadUInt64LittleEndian(buffer); + } + + private static void WriteUInt32(ICpuMemory memory, ulong address, uint value) + { + Span buffer = stackalloc byte[sizeof(uint)]; + BinaryPrimitives.WriteUInt32LittleEndian(buffer, value); + Assert.True(memory.TryWrite(address, buffer)); + } + + private static void WriteUInt64(ICpuMemory memory, ulong address, ulong value) + { + Span buffer = stackalloc byte[sizeof(ulong)]; + BinaryPrimitives.WriteUInt64LittleEndian(buffer, value); + Assert.True(memory.TryWrite(address, buffer)); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Agc/Gen5ShaderAtomicDecodeTests.cs b/tests/SharpEmu.Libs.Tests/Agc/Gen5ShaderAtomicDecodeTests.cs index 8a1bc30ac..16819451c 100644 --- a/tests/SharpEmu.Libs.Tests/Agc/Gen5ShaderAtomicDecodeTests.cs +++ b/tests/SharpEmu.Libs.Tests/Agc/Gen5ShaderAtomicDecodeTests.cs @@ -73,6 +73,21 @@ public void BufferAtomicOrX2_UsesTwoDataRegisters() instruction.Destinations); } + [Fact] + public void BufferAtomicAndX2_UsesTwoDataRegisters() + { + // BUFFER_ATOMIC_AND_X2 v[0:1], off, s[8:11], 0 offset:0x18, as the PSR opacity-override shaders encode it. + var instruction = DecodeSingle(0xE1640018, 0x80020000); + + Assert.Equal("BufferAtomicAndX2", instruction.Opcode); + var control = Assert.IsType(instruction.Control); + Assert.Equal(2u, control.DwordCount); + Assert.Equal(0u, control.VectorData); + Assert.Equal(8u, control.ScalarResource); + Assert.Equal(0x18, control.OffsetBytes); + Assert.False(control.Glc); + } + [Fact] public void BufferAtomicSwapX2_UsesTwoDataRegisters() { diff --git a/tests/SharpEmu.Libs.Tests/Agc/Gen5StorageImageSwizzleCacheTests.cs b/tests/SharpEmu.Libs.Tests/Agc/Gen5StorageImageSwizzleCacheTests.cs index 6ec574a24..1cb25d273 100644 --- a/tests/SharpEmu.Libs.Tests/Agc/Gen5StorageImageSwizzleCacheTests.cs +++ b/tests/SharpEmu.Libs.Tests/Agc/Gen5StorageImageSwizzleCacheTests.cs @@ -15,18 +15,32 @@ public sealed class Gen5StorageImageSwizzleCacheTests [InlineData("ImageStoreMip")] public void SpecializationSeparatesStorageImageSwizzles(string opcode) { - var identity = CreateSpecialization(Gen5ShaderTranslator.IdentityImageDstSelect, opcode); - var rotated = CreateSpecialization(0x9F5u, opcode); + var identity = CreateSpecialization(Gen5ShaderTranslator.IdentityImageDstSelect, opcode, runtimeImageSwizzles: false); + var rotated = CreateSpecialization(0x9F5u, opcode, runtimeImageSwizzles: false); Assert.NotEqual(identity, rotated); Assert.Equal(Gen5ShaderTranslator.IdentityImageDstSelect, Assert.Single(identity.Images).ShaderSwizzle); Assert.Equal(0x9F5u, Assert.Single(rotated.Images).ShaderSwizzle); } - private static ResourceSpecialization CreateSpecialization(uint destinationSelect, string opcode) + // With the select as shader data, the specialization keeps the identity select for every select. + [Theory] + [InlineData("ImageStore")] + [InlineData("ImageStoreMip")] + [InlineData("ImageLoad")] + public void RuntimeSwizzleSpecializationKeepsTheIdentitySelect(string opcode) + { + var identity = CreateSpecialization(Gen5ShaderTranslator.IdentityImageDstSelect, opcode, runtimeImageSwizzles: true); + var rotated = CreateSpecialization(0x9F5u, opcode, runtimeImageSwizzles: true); + Assert.Equal(identity, rotated); + Assert.Equal(Gen5ShaderTranslator.IdentityImageDstSelect, Assert.Single(rotated.Images).ShaderSwizzle); + } + + private static ResourceSpecialization CreateSpecialization(uint destinationSelect, string opcode, bool runtimeImageSwizzles) { var program = ResourceTestProgram.Program( ResourceTestProgram.Image(0, opcode, resourceRegister: 8), ResourceTestProgram.EndProgram(8)); - var plan = ResourceTestProgram.Extract(program, userDataCount: 16); + var plan = ShaderResourcePlan.Extract(program, ShaderStage.Compute, ResourceTestProgram.Hash, 0, 16, + runtimeImageSwizzles: runtimeImageSwizzles); var userData = new uint[16]; userData[8] = 0x20; userData[9] = 71u << 20; diff --git a/tests/SharpEmu.Libs.Tests/Ampr/AmprCommandQueueTests.cs b/tests/SharpEmu.Libs.Tests/Ampr/AmprCommandQueueTests.cs new file mode 100644 index 000000000..675ebd5dd --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Ampr/AmprCommandQueueTests.cs @@ -0,0 +1,168 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using SharpEmu.Libs.Ampr; +using SharpEmu.Libs.Kernel; +using Xunit; + +namespace SharpEmu.Libs.Tests.Ampr; + +[Collection("AmprFileRegistry")] +public sealed class AmprCommandQueueTests +{ + private const ulong MemoryBase = 0x3_0000_0000; + private const ulong Label = MemoryBase + 0x800; + private const ulong Output = MemoryBase + 0x808; + private const ulong SecondOutput = MemoryBase + 0x810; + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + + [Fact] + public void ABufferWhoseWaitsAreMetRunsBeforeTheSubmitReturns() + { + var context = CreateContext(); + Assert.True(context.TryWriteUInt64(Label, 5)); + var buffer = Build(context, 0, [Wait(Label, 5), Write(Output, 7)]); + + var submission = Submit(context, buffer, AmprExports.AmprEngine.Apr, 0x7101); + + Assert.True(submission.CompletedInline); + Assert.Equal(7UL, Read(context, Output)); + } + + [Fact] + public void ABufferThatReachesAnUnmetWaitFinishesOnItsQueue() + { + var context = CreateContext(); + var buffer = Build(context, 0, [Wait(Label, 1), Write(Output, 9)]); + + var submission = Submit(context, buffer, AmprExports.AmprEngine.Apr, 0x7102); + + Assert.False(submission.IsCompleted); + Assert.Equal(0UL, Read(context, Output)); + Assert.True(context.TryWriteUInt64(Label, 1)); + Assert.True(submission.Wait(Timeout)); + Assert.False(submission.CompletedInline); + Assert.Equal(9UL, Read(context, Output)); + } + + [Fact] + public void ALaterBufferOfTheSameQueueRunsAfterTheOneThatWaits() + { + var context = CreateContext(); + var first = Build(context, 0, [Wait(Label, 1), Write(Output, 1)]); + var second = Build(context, 1, [Write(Output, 2)]); + + var waiting = Submit(context, first, AmprExports.AmprEngine.Apr, 0x7103); + var queued = Submit(context, second, AmprExports.AmprEngine.Apr, 0x7103); + + Assert.False(queued.IsCompleted); + Assert.Equal(0UL, Read(context, Output)); + Assert.True(context.TryWriteUInt64(Label, 1)); + Assert.True(waiting.Wait(Timeout)); + Assert.True(queued.Wait(Timeout)); + Assert.Equal(2UL, Read(context, Output)); + } + + // Reads wait for the AMM work that maps their destination, so neither another engine nor another priority + // queues behind them. + [Fact] + public void AWaitingBufferHoldsUpOnlyItsOwnQueue() + { + var context = CreateContext(); + var waiting = Submit(context, Build(context, 0, [Wait(Label, 1), Write(Output, 1)]), AmprExports.AmprEngine.Apr, 0x7104); + + var otherEngine = Submit(context, Build(context, 1, [Write(SecondOutput, 3)]), AmprExports.AmprEngine.Amm, 0x7104); + Assert.True(otherEngine.CompletedInline); + Assert.Equal(3UL, Read(context, SecondOutput)); + + var otherPriority = Submit(context, Build(context, 2, [Write(SecondOutput, 4)]), AmprExports.AmprEngine.Apr, 0x7105); + Assert.True(otherPriority.CompletedInline); + Assert.Equal(4UL, Read(context, SecondOutput)); + + Assert.False(waiting.IsCompleted); + Assert.True(context.TryWriteUInt64(Label, 1)); + Assert.True(waiting.Wait(Timeout)); + } + + [Fact] + public void WaitingForASubmissionReturnsItsResultOnceTheBufferFinishes() + { + const ulong resultAddress = MemoryBase + 0x900; + const ulong submissionIdAddress = MemoryBase + 0x910; + var context = CreateContext(); + var buffer = Build(context, 0, [Wait(Label, 1), Write(Output, 5)]); + Assert.True(context.TryWriteUInt64(resultAddress, ulong.MaxValue)); + + context[CpuRegister.Rdi] = buffer; + context[CpuRegister.Rsi] = 0x7106; + context[CpuRegister.Rdx] = resultAddress; + context[CpuRegister.Rcx] = submissionIdAddress; + Assert.Equal(0, KernelAprCompatExports.KernelAprSubmitCommandBufferAndGetResult(context)); + Assert.Equal(ulong.MaxValue, Read(context, resultAddress)); + Assert.True(context.TryReadUInt32(submissionIdAddress, out var submissionId)); + + var release = Task.Run(async () => + { + await Task.Delay(50); + Assert.True(context.TryWriteUInt64(Label, 1)); + }); + var waiter = new CpuContext(context.Memory, Generation.Gen5); + waiter[CpuRegister.Rdi] = submissionId; + Assert.Equal(0, KernelAprCompatExports.KernelAprWaitCommandBuffer(waiter)); + release.Wait(Timeout); + + Assert.Equal(5UL, Read(context, Output)); + Assert.Equal(0UL, Read(context, resultAddress)); + } + + private static CpuContext CreateContext() => + new(new FakeCpuMemory(MemoryBase, 0x1000), Generation.Gen5); + + private static AmprExports.AmprSubmission Submit(CpuContext context, ulong buffer, AmprExports.AmprEngine engine, uint priority) + { + Assert.Equal(0, AmprExports.SubmitCommandBuffer(context, buffer, engine, priority, null, out var submission)); + return submission!; + } + + private static Action Wait(ulong address, ulong reference) => (context, buffer) => + { + context[CpuRegister.Rdi] = buffer; + context[CpuRegister.Rsi] = address; + context[CpuRegister.Rdx] = reference; + context[CpuRegister.Rcx] = 0; + context[CpuRegister.R8] = 0; + Assert.Equal(0, AmprExports.CommandBufferWaitOnAddress(context)); + }; + + private static Action Write(ulong address, ulong value) => (context, buffer) => + { + context[CpuRegister.Rdi] = buffer; + context[CpuRegister.Rsi] = address; + context[CpuRegister.Rdx] = value; + Assert.Equal(0, AmprExports.CommandBufferWriteAddress0400(context)); + }; + + // Command buffer objects sit at 0x100 + 0x40 * slot, their records at 0x200 + 0x100 * slot. + private static ulong Build(CpuContext context, uint slot, Action[] commands) + { + var buffer = MemoryBase + 0x100 + 0x40UL * slot; + context[CpuRegister.Rdi] = buffer; + context[CpuRegister.Rsi] = MemoryBase + 0x200 + 0x100UL * slot; + context[CpuRegister.Rdx] = 0x100; + Assert.Equal(0, AmprExports.CommandBufferConstructor(context)); + Assert.Equal(0, AmprExports.CommandBufferSetBuffer(context)); + foreach (var command in commands) + { + command(context, buffer); + } + + return buffer; + } + + private static ulong Read(CpuContext context, ulong address) + { + Assert.True(context.TryReadUInt64(address, out var value)); + return value; + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferAsyncReadbackTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferAsyncReadbackTests.cs index 10887cc4d..e2a4495b9 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferAsyncReadbackTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferAsyncReadbackTests.cs @@ -16,8 +16,11 @@ public sealed class GuestBufferAsyncReadbackTests(HeadlessVulkanFixture fixture) { private readonly HeadlessVulkan? _vulkan = fixture.Vulkan; - private static void Attach(CacheHarness harness, HeadlessVulkan vulkan) => + private static void Attach(CacheHarness harness, HeadlessVulkan vulkan, bool eagerReadbacks = true) + { harness.Cache.AsyncReadback = new VulkanAsyncReadback(vulkan.DeviceInfo, harness.Scheduler, vulkan.Queue, vulkan.QueueFamily); + harness.Cache.EagerReadbacksEnabled = eagerReadbacks; + } private static void Detach(CacheHarness harness) => harness.Worker.Run(() => { @@ -146,6 +149,31 @@ public void AHotWindowIsReadAheadAfterTheNextGpuWrite() harness.Shutdown(); } + // Eager readbacks are off by default: a GPU write into a hot window starts none, and the next read still lands the + // newest bytes through its own download. + [Fact] + public void AHotWindowIsNotReadAheadUnlessEagerReadbacksAreEnabled() + { + if (_vulkan is null || !GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + using var fatal = new FatalScope(); + Assert.False(harness.Cache.EagerReadbacksEnabled); + Attach(harness, _vulkan, eagerReadbacks: false); + var address = harness.MapBacked(0x10000, ReadWrite); + GpuWrite(harness, address, 0x01010101); + QueueRead(harness, address); + + GpuWrite(harness, address, 0x02020202); + SubmitBatch(harness); + Assert.Equal(0, harness.Cache.EagerReadbacksStarted); + QueueRead(harness, address); + + Assert.False(harness.Cache.HasGpuDirtyBytes(address, 0x100)); + Assert.Equal(0x02020202u, BitConverter.ToUInt32(harness.Read(address + 0x40, 4))); + Detach(harness); + harness.Shutdown(); + } + [Fact] public void AReadAheadOverwrittenBeforeItsReadIsNeverApplied() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferBdaRegistrationTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferBdaRegistrationTests.cs new file mode 100644 index 000000000..25bebd6d7 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferBdaRegistrationTests.cs @@ -0,0 +1,62 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE.GpuMemory; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.Libs.Tests.Gpu.Vulkan; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Images.ImageCacheTestSupport; + +namespace SharpEmu.Libs.Tests.Gpu.Buffers; + +[Collection(SchedulingStateCollection.Name)] +public sealed class GuestBufferBdaRegistrationTests : IClassFixture +{ + private readonly HeadlessVulkan? _vulkan; + + public GuestBufferBdaRegistrationTests(HeadlessVulkanFixture fixture) => _vulkan = fixture.Vulkan; + + // FindBuffer is the admission path used by BdaFaultProcessor's completion callback. + // It creates an owner and publishes its address, without uploading guest bytes. + // The next PrepareBda must upload it even with the same mappings and no CPU write. + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(true, true)] + public void NewDeviceAddressOwnerReceivesFirstUpload(bool regionAlreadyExists, bool registerAfterFirstPreparation) + { + if (!GatePrerequisites.Ready(_vulkan)) return; + Assert.Equal(0UL, GuestGpuMemoryHook.TraceAddress); + using var harness = new CacheHarness(_vulkan); + const ulong size = 0x10000; + var address = harness.MapBacked(size, ReadWrite); + var expected = Enumerable.Range(0, (int)size).Select(index => (byte)(37 + index * 13)).ToArray(); + harness.Write(address, expected); + var spans = new List { new(address, size) }; + var mapping = SharpEmu.Libs.Gpu.Buffers.GuestBufferCache.MappingKey(spans); + + var buffer = harness.Worker.Run(() => + { + if (regionAlreadyExists) + Assert.True(harness.Cache.HasCpuDirtyPages(address, size)); + + if (registerAfterFirstPreparation) + harness.Cache.PrepareBda(spans, mapping); + + var owner = harness.Cache.GetBuffer(harness.Cache.FindBuffer(address, size)); + Assert.True(harness.Cache.IsRegionRegistered(address, size)); + harness.Cache.PrepareBda(spans, mapping); + + // Query only after the preparation under test. Before registration, this query + // would create a missing tracker region and itself advance CpuDirtyEpoch. + Assert.False(harness.Cache.HasCpuDirtyPages(address, size)); + Assert.False(harness.Cache.HasGpuDirtyPages(address, size)); + return owner; + }); + + Assert.Equal(expected, harness.ReadBack(buffer, buffer.Offset(address), size)); + harness.Shutdown(); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferCacheTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferCacheTests.cs index 4ceeaf253..79b94c2a6 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferCacheTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferCacheTests.cs @@ -367,6 +367,43 @@ public void UploadSourcePacksRangesAndSurvivesUntilGpuCompletion(bool useTempora harness.Shutdown(); } + // An upload of ParallelSweepCopyBytes or more copies with the parallel copy's helpers, into the ring or a temporary source. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ALargeUploadCopiesTheSameBytesInParallel(bool useTemporaryBuffer) + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + const int length = 0x60000; + var address = harness.MapBacked(0x100000, ReadWrite); + var pattern = new byte[length]; + for (var index = 0; index < length; index++) pattern[index] = (byte)(index * 7 + index / 4096); + harness.Write(address, pattern); + harness.Write(address + 0x80000, pattern); + harness.Worker.Run(() => + { + using var staging = new GpuRingBuffer(_vulkan.DeviceInfo, harness.Scheduler, + GpuBufferUsage.Upload, useTemporaryBuffer ? 8UL : 2UL * length); + using var parallel = new ParallelGuestCopy(harness.Memory, 3); + var uploader = new GuestBufferUploader(_vulkan.DeviceInfo, harness.Scheduler, harness.Memory, staging, parallel); + BufferCopy[] regions = [new(0, 0, length), new(length, 0x80000, length)]; + var source = uploader.PrepareSource(address, regions, 2 * length, address, 0x80000 + length); + Assert.NotNull(source); + Assert.Equal(useTemporaryBuffer, !ReferenceEquals(staging, source)); + using var download = new GpuBuffer(_vulkan.DeviceInfo, harness.Scheduler, + GpuBufferUsage.Download, 0, GpuBuffer.AllFlags, 2 * length); + download.CopyFrom(harness.Scheduler.Current, source, regions[0].SrcOffset, 0, 2 * length, + AccessFlags.HostWriteBit, AccessFlags.None, + AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit, AccessFlags.HostReadBit); + harness.Scheduler.Finish(); + download.Invalidate(0, 2 * length); + Assert.Equal(pattern, download.Mapped[..length].ToArray()); + Assert.Equal(pattern, download.Mapped[length..(2 * length)].ToArray()); + }); + harness.Shutdown(); + } + [Fact] public void EmptyUploadDoesNotReserveStagingBytes() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferManagedCopyReadbackTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferManagedCopyReadbackTests.cs new file mode 100644 index 000000000..1b6f7518f --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferManagedCopyReadbackTests.cs @@ -0,0 +1,148 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.HLE.GpuMemory; +using SharpEmu.Libs.Gpu.Vulkan; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.Libs.Tests.Gpu.Vulkan; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Images.ImageCacheTestSupport; + +namespace SharpEmu.Libs.Tests.Gpu.Buffers; + +// Orders an intervening GPU claim at the new admission boundary. GPU recovery happens +// before any CPU reservation, and the real TryCopy/TryWrite performs the payload copy. +[Collection(SchedulingStateCollection.Name)] +public sealed class GuestBufferManagedCopyReadbackTests(HeadlessVulkanFixture fixture) + : IClassFixture +{ + private readonly HeadlessVulkan? _vulkan = fixture.Vulkan; + private const ulong WindowBytes = 512 * 1024; + private const int PointerCount = 52; + private const int PayloadBytes = PointerCount * sizeof(ulong); + private const uint NeighbourGpuValue = 0xCAFEF00D; + + // The read-only variants exercise the landed-notification behavior that already + // works. The written variants expose a newer CPU copy hidden by broad GPU ownership. + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public void ManagedCopySurvivesAnUploadBetweenPremarkAndBackingCopy(bool writtenUpload, bool asynchronous) => + RunManagedWriteRace(writtenUpload, asynchronous, useCopy: true); + + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public void ManagedWriteSurvivesAnUploadBetweenPremarkAndBackingCopy(bool writtenUpload, bool asynchronous) => + RunManagedWriteRace(writtenUpload, asynchronous, useCopy: false); + + private void RunManagedWriteRace(bool writtenUpload, bool asynchronous, bool useCopy) + { + if (_vulkan is null || !GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + using var fatal = new FatalScope(); + Assert.Null(GuestGpuMemoryHook.Current); + + var mapping = harness.MapBacked(2 * WindowBytes, ReadWrite); + var window = (mapping + WindowBytes - 1) & ~(WindowBytes - 1); + var destination = window + 0x1A680; + var neighbour = window + 0x18000; + var source = harness.MapBacked(0x10000, ReadWrite); + var oldBytes = Pointers(0x0000001000000000UL); + var newBytes = Pointers(0x0000002000000000UL); + // Synthetic stale payload; this is not a capture of the game's bad writer. + BinaryPrimitives.WriteUInt64LittleEndian(oldBytes.AsSpan(20 * sizeof(ulong)), 0x3F800000UL); + harness.Write(destination, oldBytes); + harness.Write(source, newBytes); + harness.Worker.Run(() => + { + // A persistent resident buffer exists before the CPU premark. + _ = harness.Cache.ObtainBuffer(window, WindowBytes, isWritten: false); + harness.Scheduler.Finish(); + if (asynchronous) + harness.Cache.AsyncReadback = new VulkanAsyncReadback( + _vulkan.DeviceInfo, harness.Scheduler, _vulkan.Queue, _vulkan.QueueFamily); + harness.Cache.EagerReadbacksEnabled = false; + }); + + var attempts = 0; + var reservations = 0; + harness.Gpu.BeforeManagedWriteReservationForTest = retry => + { + attempts++; + if (retry != 0) return; + harness.Worker.Run(() => + { + _ = harness.Cache.ObtainBuffer(window, WindowBytes, isWritten: writtenUpload); + // Actual GPU output is on another page of the readback window. + // The pointer array itself is not written by this command. + var (target, offset) = harness.Cache.ObtainBuffer(neighbour, sizeof(uint), isWritten: true); + target.Fill(offset, sizeof(uint), NeighbourGpuValue); + }); + Assert.Equal(writtenUpload, harness.Cache.HasGpuDirtyBytes(destination, PayloadBytes)); + }; + harness.Gpu.ManagedWriteReservedForTest = () => reservations++; + GuestGpuMemoryHook.Attach(harness.Gpu); + try + { + // The written case must retry premark and recover the intervening GPU claim + // BEFORE copying. The read-only control needs only its landed re-dirty. + var before = harness.Cache.PendingReadbacksApplied; + var copied = useCopy ? harness.Memory.TryCopy(destination, source, PayloadBytes) + : harness.Memory.TryWrite(destination, newBytes); + Assert.True(copied); + Assert.Equal(writtenUpload ? 2 : 1, attempts); + Assert.Equal(1, reservations); + Assert.True(harness.Cache.HasCpuDirtyPages(destination, PayloadBytes)); + Assert.False(harness.Cache.HasGpuDirtyBytes(destination, PayloadBytes)); + Assert.Equal(newBytes, ReadBacking(harness, destination, PayloadBytes)); + + Assert.True(harness.Cache.TrySynchronizeCpuRead(neighbour, sizeof(uint))); + if (asynchronous) + Assert.True(harness.Cache.PendingReadbacksApplied > before, + "This variant must exercise asynchronous landing; SHARPEMU_ASYNC_GUEST_READBACK must not be 0."); + Assert.Equal(NeighbourGpuValue, + BinaryPrimitives.ReadUInt32LittleEndian(ReadBacking(harness, neighbour, sizeof(uint)))); + + // The CPU copy was newer than the upload. Downloading the neighbour + // must preserve it, including the cell carrying the synthetic stale bits. + Assert.Equal(newBytes, ReadBacking(harness, destination, PayloadBytes)); + } + finally + { + GuestGpuMemoryHook.Attach(null); + harness.Gpu.BeforeManagedWriteReservationForTest = null; + harness.Gpu.ManagedWriteReservedForTest = null; + harness.Worker.Run(() => + { + harness.Cache.Shutdown(); + harness.Cache.AsyncReadback?.Dispose(); + harness.Cache.AsyncReadback = null; + }); + harness.Shutdown(); + } + } + + private static byte[] Pointers(ulong first) + { + var result = new byte[PayloadBytes]; + for (var index = 0; index < PointerCount; index++) + BinaryPrimitives.WriteUInt64LittleEndian(result.AsSpan(index * sizeof(ulong)), first + (ulong)index * 0x100); + return result; + } + + private static byte[] ReadBacking(CacheHarness harness, ulong address, int count) + { + // Inspect publication without triggering another managed readback. + var result = new byte[count]; + Assert.True(harness.Memory.TryReadBacking(address, result)); + return result; + } + +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferManagedWriteAdmissionTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferManagedWriteAdmissionTests.cs new file mode 100644 index 000000000..a012a464a --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferManagedWriteAdmissionTests.cs @@ -0,0 +1,144 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE.GpuMemory; +using SharpEmu.Libs.Gpu.Vulkan; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.Libs.Tests.Gpu.Vulkan; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Images.ImageCacheTestSupport; + +namespace SharpEmu.Libs.Tests.Gpu.Buffers; + +[Collection(SchedulingStateCollection.Name)] +public sealed class GuestBufferManagedWriteAdmissionTests(HeadlessVulkanFixture fixture) + : IClassFixture +{ + private readonly HeadlessVulkan? _vulkan = fixture.Vulkan; + private static readonly TimeSpan Deadline = TimeSpan.FromSeconds(10); + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task PremarkCanReadBackBeforeReservationAndGpuClaimWaitsForCopy(bool asynchronous) + { + if (_vulkan is null || !GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + Assert.Null(GuestGpuMemoryHook.Current); + const ulong size = 0x8000; + var destination = harness.MapBacked(0x10000, ReadWrite); + var source = harness.MapBacked(0x10000, ReadWrite); + var expected = Enumerable.Repeat((byte)0x79, (int)size).ToArray(); + harness.Write(source, expected); + harness.Worker.Run(() => + { + var (buffer, offset) = harness.Cache.ObtainBuffer(destination, size, isWritten: true); + buffer.Fill(offset, size, 0x11111111); + harness.Cache.EagerReadbacksEnabled = false; + if (asynchronous) + harness.Cache.AsyncReadback = new VulkanAsyncReadback( + _vulkan.DeviceInfo, harness.Scheduler, _vulkan.Queue, _vulkan.QueueFamily); + }); + Assert.True(harness.Cache.HasGpuDirtyBytes(destination, size)); + var premarkReturned = Signal(); + var reserved = Signal(); + var gpuBlocked = Signal(); + var gpuAdmitted = Signal(); + using var releaseCopy = new ManualResetEventSlim(); + harness.Gpu.BeforeManagedWriteReservationForTest = _ => + { + Assert.False(harness.Cache.HasGpuDirtyBytes(destination, size)); + premarkReturned.TrySetResult(true); + }; + harness.Gpu.ManagedWriteReservedForTest = () => + { + reserved.TrySetResult(true); + if (!releaseCopy.Wait(Deadline)) throw new TimeoutException("The test did not release the CPU copy."); + }; + harness.Gpu.Pages.ManagedWrites.GpuClaimWaitingForTest = () => gpuBlocked.TrySetResult(true); + GuestGpuMemoryHook.Attach(harness.Gpu); + Task? cpu = null; + Task? gpu = null; + try + { + var readbacksBefore = harness.Cache.PendingReadbacksApplied; + cpu = Task.Run(() => harness.Memory.TryCopy(destination, source, size)); + await reserved.Task.WaitAsync(Deadline); + Assert.True(premarkReturned.Task.IsCompletedSuccessfully); + if (asynchronous) + Assert.True(harness.Cache.PendingReadbacksApplied > readbacksBefore, + "The premark must exercise the async path; SHARPEMU_ASYNC_GUEST_READBACK must not be 0."); + + gpu = Task.Run(() => harness.Worker.Run(() => + { + _ = harness.Cache.ObtainBuffer(destination, size, isWritten: true); + gpuAdmitted.TrySetResult(true); + })); + await gpuBlocked.Task.WaitAsync(Deadline); + Assert.False(cpu.IsCompleted); + Assert.False(gpuAdmitted.Task.IsCompleted); + releaseCopy.Set(); + Assert.True(await cpu.WaitAsync(Deadline)); + await gpu.WaitAsync(Deadline); + Assert.True(gpuAdmitted.Task.IsCompletedSuccessfully); + Assert.True(harness.Cache.TrySynchronizeCpuRead(destination, size)); + var actual = new byte[(int)size]; + Assert.True(harness.Memory.TryReadBacking(destination, actual)); + Assert.Equal(expected, actual); + } + finally + { + releaseCopy.Set(); + try + { + if (cpu != null) await cpu.WaitAsync(Deadline); + if (gpu != null) await gpu.WaitAsync(Deadline); + } + finally + { + GuestGpuMemoryHook.Attach(null); + harness.Gpu.BeforeManagedWriteReservationForTest = null; + harness.Gpu.ManagedWriteReservedForTest = null; + harness.Gpu.Pages.ManagedWrites.GpuClaimWaitingForTest = null; + harness.Worker.Run(() => + { + harness.Cache.Shutdown(); + harness.Cache.AsyncReadback?.Dispose(); + harness.Cache.AsyncReadback = null; + }); + harness.Shutdown(); + } + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void MixedBackingCopyReleasesOuterReservationBeforeStagedWrites(bool sourceBacked) + { + if (_vulkan is null || !GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + Assert.Null(GuestGpuMemoryHook.Current); + const ulong size = 0x10020; + var source = sourceBacked ? harness.MapBacked(0x20000, ReadWrite) : harness.MapPrivate(0x20000); + var destination = sourceBacked ? harness.MapPrivate(0x20000) : harness.MapBacked(0x20000, ReadWrite); + var expected = Enumerable.Range(0, (int)size).Select(index => (byte)(index * 19 + 7)).ToArray(); + GuestGpuMemoryHook.Attach(harness.Gpu); + try + { + Assert.True(harness.Memory.TryWrite(source, expected)); + Assert.True(harness.Memory.TryCopy(destination, source, size)); + var actual = new byte[(int)size]; + Assert.True(harness.Memory.TryRead(destination, actual)); + Assert.Equal(expected, actual); + } + finally + { + GuestGpuMemoryHook.Attach(null); + } + harness.Shutdown(); + } + + private static TaskCompletionSource Signal() => new(TaskCreationOptions.RunContinuationsAsynchronously); +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferObtainMemoTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferObtainMemoTests.cs new file mode 100644 index 000000000..845496f3a --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferObtainMemoTests.cs @@ -0,0 +1,271 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Reflection; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.Libs.Tests.Gpu.Vulkan; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Images.ImageCacheTestSupport; + +namespace SharpEmu.Libs.Tests.Gpu.Buffers; + +// Read obtains served from the memo of persistent buffers, the reads it must leave to the full path, and its switch. +[Collection(SchedulingStateCollection.Name)] +public sealed class GuestBufferObtainMemoTests(HeadlessVulkanFixture fixture) : IClassFixture +{ + private const ulong Page = GuestBufferCache.CachingPageSize; + private const ulong Size = 2 * Page; + + private readonly HeadlessVulkan? _vulkan = fixture.Vulkan; + + private static byte[] Bytes(ulong length, byte seed) => Enumerable.Range(0, (int)length).Select(index => (byte)(seed + index * 13)).ToArray(); + + private static (GpuBuffer Buffer, ulong Offset) Read(CacheHarness harness, ulong address, bool texel = false) => + harness.Cache.ObtainBuffer(address, Size, isWritten: false, isTexelBuffer: texel, allowStream: false); + + [Fact] + public void RepeatedCleanReadsAreServed_AndACpuWriteTakesTheFullPathAgain() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + harness.Cache.ObtainMemoUse = GuestBufferCache.ObtainMemoMode.On; + var address = harness.MapBacked(0x10000, ReadWrite); + harness.Write(address, Bytes(Size, 1)); + harness.Worker.Run(() => + { + var first = Read(harness, address); + Assert.Equal(0, harness.Cache.ObtainMemoHits); + var second = Read(harness, address); + Assert.Equal(1, harness.Cache.ObtainMemoHits); + Assert.Same(first.Buffer, second.Buffer); + Assert.Equal(first.Offset, second.Offset); + }); + + // An unmap reaches the cache the same way: its pages turn CPU-dirty. + var latest = Bytes(Size, 99); + Assert.True(harness.Store.MarkCpuWrite(address, Size)); + harness.Write(address, latest); + var current = harness.Worker.Run(() => + { + var read = Read(harness, address); + Assert.Equal(1, harness.Cache.ObtainMemoHits); + _ = Read(harness, address); + Assert.Equal(2, harness.Cache.ObtainMemoHits); + return read; + }); + Assert.Equal(latest, harness.ReadBack(current.Buffer, current.Offset, Size)); + harness.Shutdown(); + } + + [Fact] + public void TwoRangesOfOneSetAreBothServed() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + harness.Cache.ObtainMemoUse = GuestBufferCache.ObtainMemoMode.On; + var address = harness.MapBacked(0x40000, ReadWrite); + var first = address; + var second = 0UL; + // A second range of the same size in the same set, a page clear of the first so neither buffer merges the other. + for (var offset = Size + Page; offset + Size <= 0x40000; offset += 0x10) + { + if (GuestBufferCache.ObtainMemoSet(address + offset, Size) == GuestBufferCache.ObtainMemoSet(first, Size)) + { + second = address + offset; + break; + } + } + + Assert.NotEqual(0UL, second); + harness.Worker.Run(() => + { + for (var round = 0; round < 3; round++) + { + _ = Read(harness, first); + _ = Read(harness, second); + } + + Assert.Equal(4, harness.Cache.ObtainMemoHits); + }); + harness.Shutdown(); + } + + [Fact] + public void ACleanTexelReadOverAnImageIsServed_AndStillTakesTheImageBytes() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + harness.Cache.ObtainMemoUse = GuestBufferCache.ObtainMemoMode.On; + var address = harness.MapBacked(0x10000, ReadWrite); + harness.Write(address, Bytes(Size, 5)); + var images = new ImageOverEveryRange(); + harness.Cache.ImageCache = images; + harness.Worker.Run(() => + { + var first = Read(harness, address, texel: true); + var second = Read(harness, address, texel: true); + Assert.Equal(1, harness.Cache.ObtainMemoHits); + Assert.Same(first.Buffer, second.Buffer); + }); + Assert.Equal(2, images.Synchronizations); + harness.Shutdown(); + } + + [Fact] + public void AnOwnerMergedIntoALargerBufferIsNotServed() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + harness.Cache.ObtainMemoUse = GuestBufferCache.ObtainMemoMode.On; + var address = harness.MapBacked(0x10000, ReadWrite); + var range = address + Page; + var expected = Bytes(Size, 7); + harness.Write(range, expected); + var current = harness.Worker.Run(() => + { + var first = Read(harness, range); + _ = harness.Cache.FindBuffer(address, 0x8000); + var second = Read(harness, range); + Assert.Equal(0, harness.Cache.ObtainMemoHits); + Assert.NotSame(first.Buffer, second.Buffer); + _ = Read(harness, range); + Assert.Equal(1, harness.Cache.ObtainMemoHits); + return second; + }); + Assert.Equal(expected, harness.ReadBack(current.Buffer, current.Offset, Size)); + harness.Shutdown(); + } + + // A written obtain of the range is not served and leaves the memo for the reads after it. + [Fact] + public void AWrittenObtainTakesTheFullPath() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + harness.Cache.ObtainMemoUse = GuestBufferCache.ObtainMemoMode.On; + var address = harness.MapBacked(0x10000, ReadWrite); + harness.Worker.Run(() => + { + var read = Read(harness, address); + var written = harness.Cache.ObtainBuffer(address, Size, isWritten: true); + Assert.Equal(0, harness.Cache.ObtainMemoHits); + Assert.Same(read.Buffer, written.Buffer); + Assert.True(harness.Cache.HasGpuDirtyBytes(address, Size)); + _ = Read(harness, address); + Assert.Equal(1, harness.Cache.ObtainMemoHits); + }); + harness.Shutdown(); + } + + [Fact] + public void OffServesNoRead() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + harness.Cache.ObtainMemoUse = GuestBufferCache.ObtainMemoMode.Off; + var address = harness.MapBacked(0x10000, ReadWrite); + harness.Worker.Run(() => + { + var first = Read(harness, address); + var second = Read(harness, address); + Assert.Same(first.Buffer, second.Buffer); + Assert.Equal(0, harness.Cache.ObtainMemoHits); + Assert.Equal(0, harness.Cache.ObtainMemoVerifications); + }); + harness.Shutdown(); + } + + [Fact] + public void VerifyComparesEveryReadItWouldServeAndServesNone() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + harness.Cache.ObtainMemoUse = GuestBufferCache.ObtainMemoMode.Verify; + var address = harness.MapBacked(0x10000, ReadWrite); + harness.Worker.Run(() => + { + for (var use = 0; use < 4; use++) + { + _ = Read(harness, address); + } + + Assert.Equal(0, harness.Cache.ObtainMemoHits); + Assert.Equal(3, harness.Cache.ObtainMemoVerifications); + Assert.Equal(0, harness.Cache.ObtainMemoMismatches); + }); + harness.Shutdown(); + } + + // A remembered answer that differs from the full path's is counted, and the full path's answer is bound. + [Fact] + public void VerifyCountsAnAnswerTheFullPathDoesNotGive() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + harness.Cache.ObtainMemoUse = GuestBufferCache.ObtainMemoMode.Verify; + var address = harness.MapBacked(0x10000, ReadWrite); + harness.Worker.Run(() => + { + var first = Read(harness, address); + ShiftRememberedOffset(harness.Cache, address, Size, 0x100); + var second = Read(harness, address); + Assert.Equal(first.Offset, second.Offset); + Assert.Equal(1, harness.Cache.ObtainMemoVerifications); + Assert.Equal(1, harness.Cache.ObtainMemoMismatches); + }); + harness.Shutdown(); + } + + private static void ShiftRememberedOffset(GuestBufferCache cache, ulong address, ulong size, ulong shift) + { + var memos = (Array)typeof(GuestBufferCache).GetField("_obtainMemos", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(cache)!; + var set = GuestBufferCache.ObtainMemoSet(address, size); + for (var way = set; way < set + 2; way++) + { + var memo = memos.GetValue(way)!; + var type = memo.GetType(); + if ((ulong)type.GetProperty("Address")!.GetValue(memo)! != address || type.GetProperty("Buffer")!.GetValue(memo) is null) + { + continue; + } + + memos.SetValue(Activator.CreateInstance(type, address, size, type.GetProperty("Identifier")!.GetValue(memo), + (ulong)type.GetProperty("Offset")!.GetValue(memo)! + shift, type.GetProperty("Buffer")!.GetValue(memo)), way); + return; + } + + Assert.Fail("The range is not remembered."); + } + + // Every range may hold image bytes, and none needs a copy: counts the texel synchronizations asked of it. + private sealed class ImageOverEveryRange : IGuestImageCache + { + public int Synchronizations; + + public ImageRegionInfo QueryRegion(ulong address, ulong size) => default; + + public bool ClearMetadata(ulong address) => false; + + public bool OverlapsDccMetadata(ulong address, ulong size) => false; + + public void InvalidateMemory(ulong address, ulong size) + { + } + + public void InvalidateMemoryFromGpu(ulong address, ulong size) + { + } + + public bool TrySynchronizeBufferFromImage(GpuBuffer buffer, ulong address, ulong size) + { + Synchronizations++; + return false; + } + + public bool MayHaveImageBytes(ulong address, ulong size) => true; + + public bool TryClearImageFromBuffer(ulong address, ulong size, uint packedClear) => false; + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferUnmappedPageTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferUnmappedPageTests.cs new file mode 100644 index 000000000..8d26f4bac --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/GuestBufferUnmappedPageTests.cs @@ -0,0 +1,84 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using SharpEmu.Libs.Gpu.Buffers; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Buffers; + +// A buffer upload reads pages the guest has no mapping for as zero; a mapped page that cannot be read is a failure. +public sealed class GuestBufferUnmappedPageTests +{ + private const ulong Base = 0x10000; + + // Four 4 KiB pages filled with 0xAB; the pages in `unmapped` have no mapping, the ones in `unreadable` are mapped + // but refuse reads. + private sealed class PagedMemory(ulong[] unmapped, ulong[]? unreadable = null) : ICpuMemory + { + private bool Mapped(ulong address, ulong size) + { + for (var page = address & ~0xFFFUL; page < address + size; page += 0x1000) + { + if (page < Base || page >= Base + 0x4000 || unmapped.Contains(page)) + return false; + } + + return true; + } + + public bool CanRead(ulong address, ulong size) => size != 0 && Mapped(address, size); + + public bool TryRead(ulong virtualAddress, Span destination) + { + if (!Mapped(virtualAddress, (ulong)destination.Length)) + return false; + for (var page = virtualAddress & ~0xFFFUL; page < virtualAddress + (ulong)destination.Length; page += 0x1000) + { + if (unreadable?.Contains(page) == true) + return false; + } + + destination.Fill(0xAB); + return true; + } + + public bool TryWrite(ulong virtualAddress, ReadOnlySpan source) => false; + } + + [Fact] + public void UnmappedPagesReadAsZeroAndMappedPagesKeepTheirBytes() + { + var memory = new PagedMemory([Base + 0x1000, Base + 0x2000]); + var destination = new byte[0x3000]; + destination.AsSpan().Fill(0xCD); + + Assert.True(GuestBufferUploader.TryReadMappedPages(memory, Base + 0x800, destination, out var unmapped)); + + Assert.Equal(0x2000UL, unmapped); + Assert.All(destination.AsSpan(0, 0x800).ToArray(), value => Assert.Equal(0xAB, value)); + Assert.All(destination.AsSpan(0x800, 0x2000).ToArray(), value => Assert.Equal(0, value)); + Assert.All(destination.AsSpan(0x2800, 0x800).ToArray(), value => Assert.Equal(0xAB, value)); + } + + [Fact] + public void AMappedPageThatCannotBeReadIsAFailure() + { + var memory = new PagedMemory([Base + 0x1000], unreadable: [Base + 0x2000]); + var destination = new byte[0x3000]; + + Assert.False(GuestBufferUploader.TryReadMappedPages(memory, Base, destination, out _)); + } + + [Fact] + public void AFullyMappedRangeReadsWithoutUnmappedBytes() + { + var memory = new PagedMemory([]); + var destination = new byte[0x1800]; + + Assert.True(GuestBufferUploader.TryReadMappedPages(memory, Base + 0x400, destination, out var unmapped)); + + Assert.Equal(0UL, unmapped); + Assert.All(destination, value => Assert.Equal(0xAB, value)); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Buffers/UploadPieceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/UploadPieceTests.cs new file mode 100644 index 000000000..8c50014c3 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/UploadPieceTests.cs @@ -0,0 +1,53 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Buffers; +using Silk.NET.Vulkan; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Buffers; + +public sealed class UploadPieceTests +{ + [Fact] + public void ACopyLargerThanAPieceIsSplitAcrossPieces() + { + var pieces = GuestBufferCache.SplitUploadPieces([new BufferCopy(0, 100, 5)], 2); + + Assert.Equal(3, pieces.Count); + AssertCopies(pieces[0], (0, 100, 2)); + AssertCopies(pieces[1], (0, 102, 2)); + AssertCopies(pieces[2], (0, 104, 1)); + } + + [Fact] + public void CopiesThatCrossAPieceBoundaryRestartTheirSourceOffsets() + { + var pieces = GuestBufferCache.SplitUploadPieces([new BufferCopy(0, 0, 3), new BufferCopy(3, 10, 3)], 4); + + Assert.Equal(2, pieces.Count); + AssertCopies(pieces[0], (0, 0, 3), (3, 10, 1)); + AssertCopies(pieces[1], (0, 11, 2)); + } + + [Fact] + public void AnExactMultipleLeavesNoEmptyPiece() + { + var pieces = GuestBufferCache.SplitUploadPieces([new BufferCopy(0, 8, 4)], 2); + + Assert.Equal(2, pieces.Count); + AssertCopies(pieces[0], (0, 8, 2)); + AssertCopies(pieces[1], (0, 10, 2)); + } + + private static void AssertCopies(List piece, params (ulong Source, ulong Destination, ulong Size)[] expected) + { + Assert.Equal(expected.Length, piece.Count); + for (var index = 0; index < expected.Length; index++) + { + Assert.Equal(expected[index].Source, piece[index].SrcOffset); + Assert.Equal(expected[index].Destination, piece[index].DstOffset); + Assert.Equal(expected[index].Size, piece[index].Size); + } + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamQueueTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamQueueTests.cs index fe0d63c7d..7a2211d6b 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamQueueTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamQueueTests.cs @@ -334,6 +334,67 @@ public void BlockedHead_IsRequeuedAndRetriedWithoutStoppingOtherQueues() Assert.Equal(1UL, queue.BlockedRetries); } + [Theory] + [InlineData(0, true)] + [InlineData(1, true)] + [InlineData(2, true)] + [InlineData(0, false)] + [InlineData(1, false)] + [InlineData(2, false)] + public void RetryNotificationDuringWaitRead_IsRetainedAndRechecksPredicate(int notification, bool labelReady) + { + var (host, queue) = NewQueue(); + host.WriteDword(Label, 0); + Enqueue(host, queue, Graphics, 1, WaitEqual(Label, 1), CreateInstanceCountPacket(9)); + host.AfterWaitOperandRead = address => + { + Assert.Equal(Label, address); + host.AfterWaitOperandRead = null; + if (labelReady) host.WriteDword(Label, 1); + switch (notification) + { + case 0: queue.NotifyCompletedGpuTick(1); break; + case 1: queue.RetryBlocked(); break; + case 2: queue.NotifyPublicationCompleted(); break; + default: throw new ArgumentOutOfRangeException(nameof(notification)); + } + }; + + // The current read still contains zero. Only the next attempt can observe the update. + Assert.Equal(SliceResult.BlockedWithoutProgress, queue.ProcessOne()); + Assert.Equal(0, queue.BlockedQueueCount); + Assert.True(queue.HasUnblockedPending); + Assert.Equal(labelReady ? SliceResult.Completed : SliceResult.BlockedWithoutProgress, queue.ProcessOne()); + Assert.Equal(2, host.OperandReads.Count(address => address == Label)); + if (labelReady) + { + Assert.Equal(9u, queue.GetInterpreter(0).InstanceCount); + Assert.Equal(SliceResult.NoWork, queue.ProcessOne()); + } + else + { + // A wake is not permission to skip WAIT_REG_MEM or busy-retry indefinitely. + Assert.Equal(1, queue.BlockedQueueCount); + Assert.Equal(SliceResult.AllBlocked, queue.ProcessOne()); + Assert.NotEqual(9u, queue.GetInterpreter(0).InstanceCount); + } + } + + [Fact] + public void RepeatedGpuTickDuringWaitRead_DoesNotCreateAnotherRetry() + { + var (host, queue) = NewQueue(); + queue.NotifyCompletedGpuTick(1); + host.WriteDword(Label, 0); + Enqueue(host, queue, Graphics, 1, WaitEqual(Label, 1)); + host.AfterWaitOperandRead = _ => queue.NotifyCompletedGpuTick(1); + + Assert.Equal(SliceResult.BlockedWithoutProgress, queue.ProcessOne()); + Assert.Equal(1, queue.BlockedQueueCount); + Assert.False(queue.HasUnblockedPending); + Assert.Equal(SliceResult.AllBlocked, queue.ProcessOne()); + } + [Fact] public void CompletedGpuTick_RetriesBlockedWaitWithoutTheTimeout() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs index 77caca020..ef75f538b 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs @@ -90,6 +90,9 @@ public void TraceWritersOf(string subject, ulong address, ulong size) => public List AutoDraws { get; } = new(); + // Runs at every draw, while the interpreter's registers hold the draw's state. + public Action? OnDraw { get; set; } + public Queue PendingCommands { get; } = new(); public int PendingCommandRuns { get; private set; } @@ -120,6 +123,16 @@ public bool TryReadGuestOperand(ulong address, Span destination) return TryReadGuest(address, destination); } + // Deterministically inject a completion after the predicate bytes were copied, before requeue. + public Action? AfterWaitOperandRead { get; set; } + + public bool TryReadGuestWaitOperand(ulong address, Span destination) + { + var read = TryReadGuestOperand(address, destination); + AfterWaitOperandRead?.Invoke(address); + return read; + } + public bool TryReadGuest(ulong address, Span destination) { GuestReads.Add(address); @@ -230,12 +243,14 @@ public bool IsFlipDone(int handle, int index) public void DrawIndexed(ulong submitId, in DrawIndexedArguments arguments) { IndexedDraws.Add(arguments); + OnDraw?.Invoke(); Calls.Add($"draw_indexed {submitId} {arguments.IndexCount}"); } public void DrawAuto(ulong submitId, in DrawAutoArguments arguments) { AutoDraws.Add(arguments); + OnDraw?.Invoke(); Calls.Add($"draw_auto {submitId} {arguments.VertexCount}"); } @@ -246,6 +261,8 @@ public void DispatchDirect(ulong submitId, uint groupsX, uint groupsY, uint grou public bool ResolvesIndirectDispatchOnGpu { get; set; } + public bool ResolvesIndirectThreadDispatchOnGpu { get; set; } + public bool ResolvesIndirectDrawOnGpu { get; set; } public void OnQueueReset(int queueId) => Calls.Add($"queue_reset {queueId}"); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/EndOfPipeSoftWaitTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/EndOfPipeSoftWaitTests.cs new file mode 100644 index 000000000..2483d316a --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/EndOfPipeSoftWaitTests.cs @@ -0,0 +1,427 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Diagnostics; +using SharpEmu.Libs.Gpu.GpuCommands; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.GpuCommands; + +// SHARPEMU_END_OF_PIPE_SOFT_WAITS: a wait met by another queue's ordinary end-of-pipe label suspends like an unmet wait +// while that release has not completed on the GPU and another head may run, and passes unchanged otherwise. +[Collection(CommandStreamQueueStateCollection.Name)] +public sealed class EndOfPipeSoftWaitTests +{ + private const ulong Label = StreamRunner.LabelAddress; + private const ulong Graphics = StreamRunner.CommandAddress; + private const ulong ComputeA = StreamRunner.DataAddress; + private const ulong ComputeB = StreamRunner.DataAddress + 0x800; + private const ulong Nested = StreamRunner.TableAddress; + private const uint FirstCompute = 0x20; + + private static uint[] Release32(ulong label, uint value) => + StreamRunner.Packet(PacketOpcode.ReleaseMemory, 0x28u | (5u << 8), 1u << 29, + StreamRunner.Low(label), StreamRunner.High(label), value, 0, 0); + + private static uint[] Release64(ulong label, ulong value) => + StreamRunner.Packet(PacketOpcode.ReleaseMemory, 0x28u | (5u << 8), 2u << 29, + StreamRunner.Low(label), StreamRunner.High(label), StreamRunner.Low(value), StreamRunner.High(value), 0); + + private static uint[] ReleaseInterrupt32(ulong label, uint value) => + StreamRunner.Packet(PacketOpcode.ReleaseMemory, 0x28u | (5u << 8), (2u << 24) | (1u << 29), + StreamRunner.Low(label), StreamRunner.High(label), value, 0, 0); + + private static uint[] Wait32(uint function, ulong address, uint reference, uint mask = 0xFFFF_FFFFu) => + StreamRunner.Packet(PacketOpcode.WaitRegisterMemory, function | 0x10u, + StreamRunner.Low(address), StreamRunner.High(address), reference, mask, 0); + + private static uint[] Wait64(uint function, ulong address, ulong reference, ulong mask = ulong.MaxValue) => + StreamRunner.Packet(PacketOpcode.WaitRegisterMemory64, function | 0x10u, + StreamRunner.Low(address), StreamRunner.High(address), StreamRunner.Low(reference), StreamRunner.High(reference), + StreamRunner.Low(mask), StreamRunner.High(mask), 0); + + private static uint[] Draw(uint vertices) => StreamRunner.Packet(PacketOpcode.DrawIndexAuto, vertices, 0); + + private static uint[] Instances(uint count) => StreamRunner.Packet(PacketOpcode.NumInstances, count); + + private static uint[] IndirectBuffer(ulong address, uint dwords) => + StreamRunner.Packet(PacketOpcode.IndirectBuffer, StreamRunner.Low(address), StreamRunner.High(address) & 0xFFFF, dwords); + + private sealed record Setup(RecordingCommandStreamHost Host, CommandStreamQueue Queue, EndOfPipeLandings Landings); + + private static Setup NewQueue(long capTicks = long.MaxValue, bool soft = true) + { + var host = new RecordingCommandStreamHost(); + var queue = new CommandStreamQueue(host); + var landings = new EndOfPipeLandings { CapTicks = capTicks }; + // Set either way: unless SHARPEMU_END_OF_PIPE_SOFT_WAITS=0, the queue starts with its own registry. + queue.Landings = soft ? landings : null; + return new Setup(host, queue, landings); + } + + private static void Graphics0(Setup setup, ulong submission, params uint[][] packets) + { + var words = StreamRunner.Concat(packets); + setup.Host.WriteWords(Graphics, words); + setup.Queue.EnqueueGraphics(Graphics, (uint)words.Length, submission, null); + } + + private static void Compute(Setup setup, uint queue, ulong address, ulong submission, params uint[][] packets) + { + var words = StreamRunner.Concat(packets); + setup.Host.WriteWords(address, words); + setup.Queue.EnqueueCompute(queue, address, (uint)words.Length, submission, null); + } + + // The releasing compute queue runs first, so its label is in memory and its landing is not complete. + private static EndOfPipeLanding Published(Setup setup, params uint[][] release) + { + Compute(setup, FirstCompute, ComputeA, 1, release); + Assert.Equal(SliceResult.Completed, setup.Queue.ProcessOne()); + return Assert.IsType(setup.Host.EndOfPipeWrites[^1].Landing); + } + + // After the release, queue 1 (the releasing compute queue) gets another head behind the graphics head in the + // round-robin order, so the graphics wait runs while another head may run. + private static void OtherWork(Setup setup) => Compute(setup, FirstCompute, ComputeB, 2, Instances(5)); + + private static int Draws(Setup setup) => setup.Host.Calls.Count(call => call.StartsWith("draw_auto", StringComparison.Ordinal)); + + private static void RunUntilIdle(Setup setup) + { + for (var slices = 0; slices < 16; slices++) + { + if (setup.Queue.ProcessOne() is SliceResult.NoWork) return; + } + + Assert.Fail("The queue did not go idle."); + } + + [Fact] + public void MetWaitYieldsToAnotherHeadThenRunsOnceWhenNoneIsLeft() + { + var setup = NewQueue(); + var landing = Published(setup, Release32(Label, 1)); + Graphics0(setup, 3, Wait32(3, Label, 1), Draw(7)); + OtherWork(setup); + + Assert.Equal(SliceResult.BlockedWithoutProgress, setup.Queue.ProcessOne()); + Assert.Equal(0, Draws(setup)); + // A soft wait is not a blocked wait: the batch policy keeps its own rule. + Assert.Equal(0, setup.Queue.BlockedQueueCount); + + Assert.Equal(SliceResult.Completed, setup.Queue.ProcessOne()); + Assert.Equal(5u, setup.Queue.GetInterpreter(1).InstanceCount); + Assert.Equal(0, Draws(setup)); + + Assert.Equal(SliceResult.Completed, setup.Queue.ProcessOne()); + Assert.Equal(1, Draws(setup)); + Assert.Equal(EndOfPipeLandings.Release.Idle, landing.ReleasedBy); + Assert.Equal(SliceResult.NoWork, setup.Queue.ProcessOne()); + Assert.Equal(1, Draws(setup)); + } + + [Fact] + public void SoftWaitPassesOnceItsReleaseCompletesOnTheGpu() + { + var setup = NewQueue(); + setup.Host.EndOfPipeRecorded = write => write.Landing?.Recorded(7); + var landing = Published(setup, Release32(Label, 1)); + Graphics0(setup, 3, Wait32(3, Label, 1), Draw(7)); + OtherWork(setup); + Assert.Equal(SliceResult.BlockedWithoutProgress, setup.Queue.ProcessOne()); + + setup.Queue.NotifyCompletedGpuTick(7); + RunUntilIdle(setup); + + Assert.Equal(1, Draws(setup)); + Assert.Equal(EndOfPipeLandings.Release.Complete, landing.ReleasedBy); + } + + [Fact] + public void WithoutAnotherHeadTheMetWaitPassesAtOnce() + { + var setup = NewQueue(); + var landing = Published(setup, Release32(Label, 1)); + Graphics0(setup, 3, Wait32(3, Label, 1), Draw(7)); + + Assert.Equal(SliceResult.Completed, setup.Queue.ProcessOne()); + Assert.Equal(1, Draws(setup)); + Assert.Equal(EndOfPipeLandings.Release.Idle, landing.ReleasedBy); + } + + [Fact] + public void SwitchOffKeepsTheOriginalOrder() + { + var setup = NewQueue(soft: false); + Compute(setup, FirstCompute, ComputeA, 1, Release32(Label, 1)); + Assert.Equal(SliceResult.Completed, setup.Queue.ProcessOne()); + Assert.Null(setup.Host.EndOfPipeWrites[^1].Landing); + Graphics0(setup, 3, Wait32(3, Label, 1), Draw(7)); + OtherWork(setup); + + // The graphics head runs first, as without the switch, and the other head after it. + Assert.Equal(SliceResult.Completed, setup.Queue.ProcessOne()); + Assert.Equal(1, Draws(setup)); + Assert.NotEqual(5u, setup.Queue.GetInterpreter(1).InstanceCount); + } + + [Theory] + [InlineData(5u, 0xFFFF_FFFFu, 1u)] // greater-or-equal + [InlineData(3u, 0x0000_FFFFu, 1u)] // partial mask + public void OnlyFullMaskEqualityWaitsAreAdmitted(uint function, uint mask, uint reference) + { + var setup = NewQueue(); + var landing = Published(setup, Release32(Label, 1)); + Graphics0(setup, 3, Wait32(function, Label, reference, mask), Draw(7)); + OtherWork(setup); + + Assert.Equal(SliceResult.Completed, setup.Queue.ProcessOne()); + Assert.Equal(1, Draws(setup)); + Assert.Null(landing.ReleasedBy); + } + + [Fact] + public void AWaitOfAnotherWidthIsNotAdmitted() + { + var setup = NewQueue(); + var landing = Published(setup, Release32(Label, 1)); + setup.Host.WriteDword(Label + 4, 0); + Graphics0(setup, 3, Wait64(3, Label, 1), Draw(7)); + OtherWork(setup); + + Assert.Equal(SliceResult.Completed, setup.Queue.ProcessOne()); + Assert.Equal(1, Draws(setup)); + Assert.Null(landing.ReleasedBy); + } + + [Fact] + public void A64BitReleaseIsAdmittedForA64BitEqualityWait() + { + var setup = NewQueue(); + var landing = Published(setup, Release64(Label, 0x1_0000_0002)); + Graphics0(setup, 3, Wait64(3, Label, 0x1_0000_0002), Draw(7)); + OtherWork(setup); + + Assert.Equal(SliceResult.BlockedWithoutProgress, setup.Queue.ProcessOne()); + RunUntilIdle(setup); + Assert.Equal(1, Draws(setup)); + Assert.Equal(EndOfPipeLandings.Release.Idle, landing.ReleasedBy); + } + + [Fact] + public void InterruptLabelsAndDeferredLabelsTakeNoHint() + { + var setup = NewQueue(); + Compute(setup, FirstCompute, ComputeA, 1, ReleaseInterrupt32(Label, 1)); + Assert.Equal(SliceResult.Completed, setup.Queue.ProcessOne()); + Assert.Null(setup.Host.EndOfPipeWrites[^1].Landing); + Graphics0(setup, 3, Wait32(3, Label, 1), Draw(7)); + OtherWork(setup); + Assert.Equal(SliceResult.Completed, setup.Queue.ProcessOne()); + Assert.Equal(1, Draws(setup)); + + // A deferred label replaces the address's hint. + var deferredSetup = NewQueue(); + Published(deferredSetup, Release32(Label, 1)); + deferredSetup.Host.DeferredEndOfPipe = (_, _) => true; + Compute(deferredSetup, FirstCompute, ComputeB, 2, Release32(Label, 1)); + Assert.Equal(SliceResult.Completed, deferredSetup.Queue.ProcessOne()); + deferredSetup.Host.DeferredEndOfPipe = null; + Graphics0(deferredSetup, 3, Wait32(3, Label, 1), Draw(7)); + Compute(deferredSetup, FirstCompute, ComputeA, 4, Instances(5)); + Assert.Equal(SliceResult.Completed, deferredSetup.Queue.ProcessOne()); + Assert.Equal(1, Draws(deferredSetup)); + } + + // A wait met through a deferred label's overlay value is not a met label in guest memory: no soft wait. + [Fact] + public void AWaitMetThroughADeferredLabelTakesNoSoftWait() + { + var setup = NewQueue(); + var landing = Published(setup, Release32(Label, 1)); + setup.Host.DeferredLabelRead = (int _, ulong _, ulong _, out bool deferred, out ulong value) => + { + deferred = true; + value = 1; + return true; + }; + Graphics0(setup, 3, Wait32(3, Label, 1), Draw(7)); + OtherWork(setup); + + Assert.Equal(SliceResult.Completed, setup.Queue.ProcessOne()); + Assert.Equal(1, Draws(setup)); + Assert.Null(landing.ReleasedBy); + } + + [Fact] + public void AQueuesOwnReleaseIsNoHint() + { + var setup = NewQueue(); + Compute(setup, FirstCompute + 1, ComputeB, 2, Instances(5)); + Graphics0(setup, 3, Release32(Label, 1), Wait32(3, Label, 1), Draw(7)); + + Assert.Equal(SliceResult.Completed, setup.Queue.ProcessOne()); + Assert.Equal(1, Draws(setup)); + } + + [Fact] + public void ANewerReleaseReplacesTheHintAndAnOldTickDoesNotCompleteIt() + { + var setup = NewQueue(); + var older = Published(setup, Release32(Label, 1)); + var newer = Published(setup, Release32(Label, 2)); + older.Recorded(5); + setup.Queue.NotifyCompletedGpuTick(5); + Graphics0(setup, 3, Wait32(3, Label, 2), Draw(7)); + OtherWork(setup); + + Assert.Equal(SliceResult.BlockedWithoutProgress, setup.Queue.ProcessOne()); + Assert.Equal(0, Draws(setup)); + RunUntilIdle(setup); + Assert.Equal(EndOfPipeLandings.Release.Idle, newer.ReleasedBy); + Assert.Null(older.ReleasedBy); + } + + [Fact] + public void TheDeadlineHoldsAcrossRetriesAndAUsedReleaseIsNotArmedAgain() + { + var setup = NewQueue(capTicks: Stopwatch.Frequency / 1000); + var landing = Published(setup, Release32(Label, 1)); + Graphics0(setup, 3, Wait32(3, Label, 1), Draw(7), Wait32(3, Label, 1), Draw(8)); + // Two other submissions on queue 1: the first runs while the wait is deferred, the second is still queued at the + // deadline, so only the deadline lets the wait pass then. + OtherWork(setup); + Compute(setup, FirstCompute, ComputeA, 4, Instances(6)); + + Assert.Equal(SliceResult.BlockedWithoutProgress, setup.Queue.ProcessOne()); + var until = Stopwatch.GetTimestamp() + Stopwatch.Frequency / 500; + while (Stopwatch.GetTimestamp() < until) Thread.SpinWait(100); + + RunUntilIdle(setup); + Assert.Equal(EndOfPipeLandings.Release.Cap, landing.ReleasedBy); + // The second wait met the same, used release: it ran without a second soft wait. + Assert.Equal(2, Draws(setup)); + } + + [Fact] + public void AControlBarrierCutoffAndShutdownLeaveNoSoftWait() + { + var barrier = NewQueue(); + var landing = Published(barrier, Release32(Label, 1)); + Graphics0(barrier, 3, Wait32(3, Label, 1), Draw(7)); + OtherWork(barrier); + Assert.True(barrier.Queue.TryEnqueueControlBarrier(static () => { }, static () => { })); + RunUntilIdle(barrier); + Assert.Equal(1, Draws(barrier)); + Assert.Equal(EndOfPipeLandings.Release.Idle, landing.ReleasedBy); + + var shutdown = NewQueue(); + var stopped = Published(shutdown, Release32(Label, 1)); + Graphics0(shutdown, 3, Wait32(3, Label, 1), Draw(7)); + OtherWork(shutdown); + Assert.Equal(SliceResult.BlockedWithoutProgress, shutdown.Queue.ProcessOne()); + shutdown.Queue.StopAccepting(); + RunUntilIdle(shutdown); + Assert.Equal(1, Draws(shutdown)); + Assert.Equal(EndOfPipeLandings.Release.Idle, stopped.ReleasedBy); + } + + [Fact] + public void ANestedSoftWaitResumesInsideItsBufferAndEveryPacketRunsOnce() + { + var setup = NewQueue(); + var landing = Published(setup, Release32(Label, 1)); + var nested = StreamRunner.Concat(Wait32(3, Label, 1), Draw(9)); + setup.Host.WriteWords(Nested, nested); + Graphics0(setup, 3, Instances(2), IndirectBuffer(Nested, (uint)nested.Length), Draw(7)); + OtherWork(setup); + + // The prefix before the wait made progress, so the slice ends with the usual flush. + Assert.Equal(SliceResult.Progressed, setup.Queue.ProcessOne()); + Assert.Equal("flush", setup.Host.Calls[^1]); + Assert.Equal(0, Draws(setup)); + + RunUntilIdle(setup); + Assert.Equal(new[] { "9", "7" }, + setup.Host.Calls.Where(call => call.StartsWith("draw_auto", StringComparison.Ordinal)).Select(call => call.Split(' ')[^1]).ToArray()); + Assert.Equal(EndOfPipeLandings.Release.Idle, landing.ReleasedBy); + } + + // The guest's wait passed once; a later change of the label (another release to it) must not turn it back into an unmet + // wait. The retry resumes only the soft delay. + [Fact] + public void ALaterLabelChangeDoesNotUndoAPassedWait() + { + var setup = NewQueue(); + var landing = Published(setup, Release32(Label, 1)); + Graphics0(setup, 3, Wait32(3, Label, 1), Draw(7)); + Compute(setup, FirstCompute, ComputeB, 2, Release32(Label, 2)); + + Assert.Equal(SliceResult.BlockedWithoutProgress, setup.Queue.ProcessOne()); + Assert.Equal(SliceResult.Completed, setup.Queue.ProcessOne()); + Assert.Equal(2u, setup.Host.ReadDword(Label)); + + Assert.Equal(SliceResult.Completed, setup.Queue.ProcessOne()); + Assert.Equal(1, Draws(setup)); + Assert.Equal(EndOfPipeLandings.Release.Idle, landing.ReleasedBy); + } + + // A dropped submission's soft wait ends when the queue runs another submission, even one at the same packet address: + // that packet's wait is evaluated afresh (here it is unmet and blocks as usual). + [Fact] + public void ADroppedSoftWaitDoesNotCarryToALaterSubmissionAtTheSamePacket() + { + var setup = NewQueue(); + var landing = Published(setup, Release32(Label, 1)); + Graphics0(setup, 3, Wait32(3, Label, 1), Draw(7)); + OtherWork(setup); + Assert.Equal(SliceResult.BlockedWithoutProgress, setup.Queue.ProcessOne()); + + setup.Queue.DiscardAll(); + Graphics0(setup, 4, Wait32(3, Label, 3), Draw(8)); + + Assert.Equal(SliceResult.BlockedWithoutProgress, setup.Queue.ProcessOne()); + Assert.Equal(0, Draws(setup)); + Assert.Equal(1, setup.Queue.BlockedQueueCount); + Assert.True(landing.Consumed); + Assert.Null(landing.ReleasedBy); + } + + // When every remaining head waits softly, one of them runs on (its wait passes) rather than the queue idling. + [Fact] + public void WhenEveryHeadWaitsSoftlyOneRunsOn() + { + var setup = NewQueue(); + var first = Published(setup, Release32(Label, 1)); + Compute(setup, FirstCompute + 1, ComputeB, 2, Release32(Label + 0x10, 1)); + Assert.Equal(SliceResult.Completed, setup.Queue.ProcessOne()); + var second = Assert.IsType(setup.Host.EndOfPipeWrites[^1].Landing); + Graphics0(setup, 3, Wait32(3, Label, 1), Draw(7)); + Compute(setup, FirstCompute, ComputeA, 4, Wait32(3, Label + 0x10, 1), Instances(5)); + Compute(setup, FirstCompute + 1, ComputeB + 0x200, 5, Instances(6)); + + Assert.Equal(SliceResult.BlockedWithoutProgress, setup.Queue.ProcessOne()); + Assert.Equal(SliceResult.BlockedWithoutProgress, setup.Queue.ProcessOne()); + Assert.Equal(SliceResult.Completed, setup.Queue.ProcessOne()); + Assert.Equal(6u, setup.Queue.GetInterpreter(2).InstanceCount); + + RunUntilIdle(setup); + Assert.Equal(1, Draws(setup)); + Assert.Equal(5u, setup.Queue.GetInterpreter(1).InstanceCount); + Assert.Equal(EndOfPipeLandings.Release.Idle, first.ReleasedBy); + Assert.Equal(EndOfPipeLandings.Release.Idle, second.ReleasedBy); + } + + [Fact] + public void AnUnmetWaitIsStillBlocked() + { + var setup = NewQueue(); + Published(setup, Release32(Label, 1)); + Graphics0(setup, 3, Wait32(3, Label, 2), Draw(7)); + OtherWork(setup); + + Assert.Equal(SliceResult.BlockedWithoutProgress, setup.Queue.ProcessOne()); + Assert.Equal(1, setup.Queue.BlockedQueueCount); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/GpuCommandInterpreterDrawTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/GpuCommandInterpreterDrawTests.cs index fabc00f0a..b3e2cd0e8 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/GpuCommandInterpreterDrawTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/GpuCommandInterpreterDrawTests.cs @@ -127,6 +127,105 @@ public void IndirectDraws_ReadArgumentsFromMemoryAndKeepTheInstanceCount() Assert.Contains("arguments base is zero", new StreamRunner().RunExpectingFatal(StreamRunner.Packet(PacketOpcode.DrawIndirect, 0, 0, 0, 2)).Message); } + // The CP writes the start vertex or base vertex and the start instance to the registers the packet names (0x280 + // names none); the shader adds them to its vertex and instance ids, so the draw counts those from 0. + [Fact] + public void IndirectDraws_WriteTheRegistersThePacketNames() + { + var runner = new StreamRunner(); + runner.Host.ResolvesIndirectDrawOnGpu = true; + runner.Host.WriteWords(Arguments, new uint[] { 9, 3, 1, 2 }); + runner.Host.WriteWords(Arguments + 16, new uint[] { 50, 2, 4, 7, 5 }); + var seen = new List<(uint BaseVertex, uint StartInstance)>(); + runner.Host.OnDraw = () => seen.Add((runner.Interpreter.Registers.Shader[0xA9], runner.Interpreter.Registers.Shader[0xA8])); + + runner.Run( + SetBase(Arguments, dispatch: false), + StreamRunner.Packet(PacketOpcode.IndexBase, StreamRunner.Low(Indices), StreamRunner.High(Indices)), + StreamRunner.Packet(PacketOpcode.IndexType, 0), + StreamRunner.Packet(PacketOpcode.IndexBufferSize, 40), + StreamRunner.Packet(PacketOpcode.DrawIndirect, 0, 0xA9, 0xA8, 2), + StreamRunner.Packet(PacketOpcode.DrawIndexIndirect, 16, 0xA9, 0xA8, 0x22), + StreamRunner.Packet(PacketOpcode.DrawIndexIndirect, 16, 0x280, 0xA8, 0x22)); + + Assert.Equal(new[] { (1u, 2u), (7u, 5u), (7u, 5u) }, seen); + var auto = Assert.Single(runner.Host.AutoDraws); + Assert.Equal((9u, 3u, 0u, 0u), (auto.VertexCount, auto.InstanceCount, auto.FirstVertex, auto.FirstInstance)); + // The registers need the arguments, so they are read here although the host could leave them on the GPU. + Assert.All(runner.Host.IndexedDraws, draw => Assert.Equal(0ul, draw.IndirectArgumentsAddress)); + Assert.Equal((Indices + 8, 0, 0u), (runner.Host.IndexedDraws[0].IndexAddress, runner.Host.IndexedDraws[0].BaseVertex, runner.Host.IndexedDraws[0].FirstInstance)); + // A base the packet names no register for still reaches the draw. + Assert.Equal((7, 0u), (runner.Host.IndexedDraws[1].BaseVertex, runner.Host.IndexedDraws[1].FirstInstance)); + // The draw says which values are in registers. + Assert.Equal((true, true), (auto.FirstVertexInRegister, auto.FirstInstanceInRegister)); + Assert.Equal((true, true), (runner.Host.IndexedDraws[0].BaseVertexInRegister, runner.Host.IndexedDraws[0].FirstInstanceInRegister)); + Assert.Equal((false, true), (runner.Host.IndexedDraws[1].BaseVertexInRegister, runner.Host.IndexedDraws[1].FirstInstanceInRegister)); + } + + [Fact] + public void IndirectMulti_WritesTheDrawIndexWhenEnabled() + { + var runner = new StreamRunner(); + runner.Host.WriteWords(Arguments, new uint[] { 1, 1, 0, 3, 2, 1, 0, 4 }); + var seen = new List<(uint StartInstance, uint DrawIndex)>(); + runner.Host.OnDraw = () => seen.Add((runner.Interpreter.Registers.Shader[0xA8], runner.Interpreter.Registers.Shader[0xAA])); + + runner.Run( + SetBase(Arguments, dispatch: false), + StreamRunner.Packet(PacketOpcode.DrawIndirectMulti, 0, 0xAAu << 16 | 0x280, 0xA8u | 1u << 27, 0, 2, 0, 0, 16, 2)); + + Assert.Equal(new[] { (3u, 0u), (4u, 1u) }, seen); + Assert.Equal(new uint[] { 1, 2 }, runner.Host.AutoDraws.Select(draw => draw.VertexCount)); + Assert.All(runner.Host.AutoDraws, draw => Assert.Equal(0u, draw.FirstInstance)); + } + + // The draw index is the draw's ordinal, so a packet that names only it leaves the arguments on the GPU. + [Fact] + public void IndexedIndirectMulti_KeepsArgumentsOnTheGpuWhenOnlyTheDrawIndexIsNamed() + { + var runner = new StreamRunner(); + runner.Host.ResolvesIndirectDrawOnGpu = true; + var seen = new List(); + runner.Host.OnDraw = () => seen.Add(runner.Interpreter.Registers.Shader[0xA8]); + + runner.Run( + SetBase(Arguments, dispatch: false), + StreamRunner.Packet(PacketOpcode.IndexBase, StreamRunner.Low(Indices), StreamRunner.High(Indices)), + StreamRunner.Packet(PacketOpcode.IndexType, 0), + StreamRunner.Packet(PacketOpcode.IndexBufferSize, 40), + StreamRunner.Packet(PacketOpcode.DrawIndexIndirectMulti, 16, 0xA8u << 16 | 0x280, 0x280u | 1u << 27, 0, 2, 0, 0, 32, 2)); + + Assert.Equal(new uint[] { 0, 1 }, seen); + Assert.Equal(new[] { Arguments + 16, Arguments + 48 }, runner.Host.IndexedDraws.Select(draw => draw.IndirectArgumentsAddress)); + Assert.DoesNotContain(runner.Host.GuestReads, address => address >= Arguments && address < Arguments + 80); + } + + // A start instance in the vertex program's live user data leaves the arguments on the GPU as a draw index does, so the + // draws never wait for the GPU work that wrote them. + [Fact] + public void IndirectMulti_KeepsArgumentsOnTheGpuWhenTheStartInstanceIsInLiveUserData() + { + var runner = new StreamRunner(); + runner.Host.ResolvesIndirectDrawOnGpu = true; + const uint gs0 = ShaderRegisterOffset.SpiShaderUserDataGs0; + + runner.Run( + StreamRunner.Packet(PacketOpcode.SetShaderRegister, ShaderRegisterOffset.SpiShaderPgmRsrc2Gs, 4u << 1), + SetBase(Arguments, dispatch: false), + StreamRunner.Packet(PacketOpcode.IndexBase, StreamRunner.Low(Indices), StreamRunner.High(Indices)), + StreamRunner.Packet(PacketOpcode.IndexType, 0), + StreamRunner.Packet(PacketOpcode.IndexBufferSize, 40), + StreamRunner.Packet(PacketOpcode.DrawIndexIndirectMulti, 16, (gs0 + 3) << 16 | 0x280, (gs0 + 2) | 1u << 27, 0, 2, 0, 0, 32, 2), + StreamRunner.Packet(PacketOpcode.DrawIndirectMulti, 0, 0x280, gs0 + 1, 0, 2, 0, 0, 16, 2)); + + Assert.Equal(new[] { Arguments + 16, Arguments + 48 }, runner.Host.IndexedDraws.Select(draw => draw.IndirectArgumentsAddress)); + Assert.All(runner.Host.IndexedDraws, draw => Assert.Equal((2, false), (draw.StartInstanceUserData, draw.FirstInstanceInRegister))); + Assert.Equal(new[] { Arguments, Arguments + 16 }, runner.Host.AutoDraws.Select(draw => draw.IndirectArgumentsAddress)); + Assert.All(runner.Host.AutoDraws, draw => Assert.Equal((1, false), (draw.StartInstanceUserData, draw.FirstInstanceInRegister))); + Assert.Equal(1u, runner.Interpreter.Registers.Shader[gs0 + 3]); + Assert.DoesNotContain(runner.Host.GuestReads, address => address >= Arguments && address < Arguments + 80); + } + [Fact] public void IndexedIndirectDraws_LeaveArgumentsOnTheGpuWhenTheHostCan() { @@ -158,6 +257,27 @@ public void IndexedIndirectDraws_LeaveArgumentsOnTheGpuWhenTheHostCan() Assert.Equal(40u, runner.Host.IndexedDraws[1].IndexCount); } + // A non-indexed indirect draw that names no register leaves its arguments on the GPU too. + [Fact] + public void AutoIndirectDraws_LeaveArgumentsOnTheGpuWhenTheHostCan() + { + var runner = new StreamRunner(); + runner.Host.ResolvesIndirectDrawOnGpu = true; + runner.Host.WriteWords(Arguments, new uint[] { 9, 3, 1, 2 }); + + runner.Run( + SetBase(Arguments, dispatch: false), + StreamRunner.Packet(PacketOpcode.DrawIndirect, 0, 0x280, 0, 2)); + + var auto = Assert.Single(runner.Host.AutoDraws); + Assert.Equal((Arguments, DrawOffsetSource.IndirectArguments), (auto.IndirectArgumentsAddress, auto.OffsetSource)); + Assert.DoesNotContain(runner.Host.GuestReads, address => address >= Arguments && address < Arguments + 16); + + // A later draw that inherits the instance count reads it then. + runner.Run(StreamRunner.Packet(PacketOpcode.DrawIndexAuto, 5, 0)); + Assert.Equal(3u, runner.Host.AutoDraws[1].InstanceCount); + } + [Fact] public void UnsizedIndexedIndirectDraws_LearnTheIndexRangeBeforeUsingTheGpu() { @@ -199,6 +319,10 @@ public void IndirectMulti_LoopsOverTheStrideAndTheCountAddress() Assert.Contains("stride is smaller", runner.RunExpectingFatal(StreamRunner.Packet(PacketOpcode.DrawIndirectMulti, 0, 0, 0, 0, 1, 0, 0, 8, 2)).Message); } + // A start instance in one of the vertex program's live user data registers stays the draw's first instance: the draw + // names that user data (the program stores its base instance there), the register is not written, and the host can + // keep the arguments on the GPU. A named base vertex still reads the arguments here, and a start instance in a + // register the program does not load is written as the CP would. [Fact] public void IndirectDraws_NameTheLiveUserRegisterOfTheirStartInstance() { @@ -220,11 +344,21 @@ public void IndirectDraws_NameTheLiveUserRegisterOfTheirStartInstance() StreamRunner.Packet(PacketOpcode.IndexType, 2), StreamRunner.Packet(PacketOpcode.DrawIndexIndirect, 16, 0x280, gs0 + 1, 0x22)); - Assert.Equal(0, Assert.Single(runner.Host.AutoDraws).StartInstanceUserData); + var auto = Assert.Single(runner.Host.AutoDraws); + Assert.Equal((0ul, 0u, true), (auto.IndirectArgumentsAddress, auto.FirstVertex, auto.FirstVertexInRegister)); + Assert.Equal((2u, false, 0), (auto.FirstInstance, auto.FirstInstanceInRegister, auto.StartInstanceUserData)); Assert.Equal(3, runner.Host.IndexedDraws.Count); - Assert.Equal((Arguments + 16, 2), (runner.Host.IndexedDraws[0].IndirectArgumentsAddress, runner.Host.IndexedDraws[0].StartInstanceUserData)); - Assert.Equal((Arguments + 16, -1), (runner.Host.IndexedDraws[1].IndirectArgumentsAddress, runner.Host.IndexedDraws[1].StartInstanceUserData)); - Assert.Equal((0ul, 1, 1u), (runner.Host.IndexedDraws[2].IndirectArgumentsAddress, runner.Host.IndexedDraws[2].StartInstanceUserData, runner.Host.IndexedDraws[2].FirstInstance)); + var indexed = runner.Host.IndexedDraws; + Assert.Equal((Arguments + 16, 0u, false, 2), + (indexed[0].IndirectArgumentsAddress, indexed[0].FirstInstance, indexed[0].FirstInstanceInRegister, indexed[0].StartInstanceUserData)); + Assert.Equal((0ul, 0u, true, -1), + (indexed[1].IndirectArgumentsAddress, indexed[1].FirstInstance, indexed[1].FirstInstanceInRegister, indexed[1].StartInstanceUserData)); + // Byte indices have no GPU index range, so the arguments are read; the start instance still goes to the draw. + Assert.Equal((0ul, 1u, false, 1), + (indexed[2].IndirectArgumentsAddress, indexed[2].FirstInstance, indexed[2].FirstInstanceInRegister, indexed[2].StartInstanceUserData)); + var shader = runner.Interpreter.Registers.Shader; + Assert.False(shader.ContainsKey(gs0) || shader.ContainsKey(gs0 + 1) || shader.ContainsKey(gs0 + 2)); + Assert.Equal((1u, 1u), (shader[gs0 + 3], shader[gs0 + 9])); } [Fact] @@ -246,7 +380,8 @@ public void Dispatches_DirectAndBothIndirectEncodings() // A host that dispatches indirectly on the GPU gets the arguments address without the // counts, so the interpreter never waits for a GPU readback of them. Thread-unit - // dispatches (initiator bit 5) still read them to convert threads into groups. + // dispatches (initiator bit 5) still read them to convert threads into groups, unless + // the host converts them on the GPU too. [Fact] public void IndirectDispatches_LeaveWorkgroupCountsOnTheGpuWhenTheHostCan() { @@ -267,6 +402,16 @@ public void IndirectDispatches_LeaveWorkgroupCountsOnTheGpuWhenTheHostCan() SetBase(Arguments, dispatch: true), StreamRunner.Packet(PacketOpcode.DispatchIndirect, 0, 0x61)); Assert.Equal(new[] { $"dispatch 0 4 5 6 61 @{Arguments:X}" }, runner.Host.Calls); + + var threads = new StreamRunner(); + threads.Host.ResolvesIndirectDispatchOnGpu = true; + threads.Host.ResolvesIndirectThreadDispatchOnGpu = true; + threads.Host.WriteWords(Arguments, new uint[] { 4, 5, 6 }); + threads.Run( + SetBase(Arguments, dispatch: true), + StreamRunner.Packet(PacketOpcode.DispatchIndirect, 0, 0x61)); + Assert.Equal(new[] { $"dispatch 0 0 0 0 61 @{Arguments:X}" }, threads.Host.Calls); + Assert.DoesNotContain(Arguments, threads.Host.GuestReads); } [Fact] diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/Registers/ContextIdentityTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/Registers/ContextIdentityTests.cs new file mode 100644 index 000000000..ad878db91 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/Registers/ContextIdentityTests.cs @@ -0,0 +1,49 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.GpuCommands.Registers; +using Xunit; +using static SharpEmu.Libs.Gpu.GpuCommands.Registers.ContextRegisterOffset; + +namespace SharpEmu.Libs.Tests.Gpu.GpuCommands.Registers; + +// The direct executor path can receive live banks. Retaining a bare Context reference +// does not create a read-only snapshot or establish the producer's COW obligation. +public sealed class ContextIdentityTests +{ + private static RegisterBanks NewBanks() => + new(static message => new InvalidOperationException(message)); + + private static void WriteMask(RegisterBanks banks, uint value) => + RegisterWriteTable.WriteContextEntry(banks, CbTargetMask, value, 0); + + [Fact] + public void RetainingALiveContextReferenceDoesNotMakeIdentityAContentProof() + { + var banks = NewBanks(); + WriteMask(banks, 0xFu); + var remembered = banks.Context; + var rememberedMask = remembered.RenderTargetMask; + + WriteMask(banks, 3u); + + Assert.Same(remembered, banks.Context); + Assert.NotEqual(rememberedMask, banks.Context.RenderTargetMask); + Assert.Equal(3u, remembered.RenderTargetMask); + } + + [Fact] + public void RetainingASnapshotEstablishesTheProducerCopyObligation() + { + var banks = NewBanks(); + WriteMask(banks, 0xFu); + var snapshot = banks.Snapshot(); + var remembered = snapshot.Context; + + WriteMask(banks, 3u); + + Assert.NotSame(remembered, banks.Context); + Assert.Equal(0xFu, remembered.RenderTargetMask); + Assert.Equal(3u, banks.Context.RenderTargetMask); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/CachedImageTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/CachedImageTests.cs index e94602727..c49978b92 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Images/CachedImageTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/CachedImageTests.cs @@ -45,6 +45,38 @@ internal static ImageDescription Volume(uint width, uint height, uint depth) return description; } + // A depth target's device-local allocation can fail with ErrorOutOfDeviceMemory although its requirements also + // allow system memory. Device-local types come first; when they are exhausted the image takes another allowed type + // and keeps its contents; only when no type can be allocated is it fatal. + [Fact] + public void ExhaustedDeviceLocalMemory_PlacesTheImageInAnotherAllowedType() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new ImageTestHarness(_vulkan); + using var fatal = new FatalScope(); + var device = harness.Device; + var description = Color2D(16, 16); + var bytes = new byte[16 * 16 * 4]; + new System.Random(7).NextBytes(bytes); + try + { + device.SimulateExhaustedMemoryType = index => (device.GetMemoryTypeFlags(index) & MemoryPropertyFlags.DeviceLocalBit) != 0; + var image = harness.CreateImage(description); + Assert.True(image.Backing.Exists); + var copies = ImageTestHarness.WholeImageCopies(description, (ulong)bytes.Length); + harness.UploadImage(image, bytes, copies); + Assert.Equal(bytes, harness.ReadImage(image, copies, (ulong)bytes.Length)); + + device.SimulateExhaustedMemoryType = static _ => true; + var failure = Assert.Throws(() => harness.CreateImage(description)); + Assert.Contains("ErrorOutOfDeviceMemory", failure.Message); + } + finally + { + device.SimulateExhaustedMemoryType = null; + } + } + [Fact] public void CalculateRowsPerCopy_LimitsRowsToTheStagingCapacity() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.Depth.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.Depth.cs index 4ed0bcab4..b16ad3469 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.Depth.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.Depth.cs @@ -227,6 +227,32 @@ public void BufferSynchronization_CopiesFittingMipsVolumesAndWholeDepthOnly() harness.Shutdown(); } + // Only an image that starts at the buffer's address is synchronized into it: one that starts two 1 MiB owner pages into a + // larger buffer is not taken for that buffer, and is for a buffer at its own address. + [Fact] + public void BufferSynchronization_TakesOnlyTheImageAtTheBuffersAddress() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + const ulong page = 0x100000; + var address = harness.MapBacked(3 * page, ReadWrite); + var later = address + 2 * page; + harness.Write(later, Bytes(0x11223344u)); + var request = LinearRequest(later, 4, Format.R32Uint, GuestPixelFormat.Bits32UInt, GuestImageType.Color2D, new Extent3D(1, 1, 1), 1, 4, 1); + var imageIdentifier = harness.Acquire(ref request); + harness.MarkGpuWritten(imageIdentifier); + harness.Worker.Run(() => + { + using var whole = new GpuBuffer(harness.Vulkan.DeviceInfo, harness.Scheduler, GpuBufferUsage.DeviceLocal, address, GpuBuffer.AllFlags, 3 * page); + using var own = new GpuBuffer(harness.Vulkan.DeviceInfo, harness.Scheduler, GpuBufferUsage.DeviceLocal, later, GpuBuffer.AllFlags, page); + Assert.False(harness.Images.TrySynchronizeBufferFromImage(whole, address, 3 * page)); + Assert.True(harness.Images.TrySynchronizeBufferFromImage(own, later, page)); + Assert.Equal(0x11223344u, BitConverter.ToUInt32(harness.CopyFromDevice(own.Handle, 0, 4))); + harness.Scheduler.Finish(); + }); + harness.Shutdown(); + } + // A tiled array's mip layout ends before its tile plan does: each level spans its size times the layer count from // its offset in the first slice, while every 64 KiB slice holds a whole chain with the base level last. A buffer // over the whole image takes every tile; a buffer that ends inside the last tile keeps the guest bytes. diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.HeapHold.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.HeapHold.cs new file mode 100644 index 000000000..a837d98d0 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.HeapHold.cs @@ -0,0 +1,55 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Images; +using SharpEmu.Libs.Tests.Gpu.Buffers; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Images.ImageCacheTestSupport; + +namespace SharpEmu.Libs.Tests.Gpu.Images; + +public sealed partial class GuestImageCacheTests +{ + // An image deleted while the bindless heap names its view keeps its memory through completed ticks and is freed + // after the tick in which the heap lets go of it; an image the heap does not name is freed after its tick. + [Fact] + public void HeapHeldImage_IsFreedOnlyAfterTheHeapLetsGo() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var address = harness.MapBacked(4 * 65536, ReadWrite); + var heldRequest = GrowthRequest(address, 1, GuestTileMode.Linear); + var plainRequest = GrowthRequest(address + 2 * 65536, 1, GuestTileMode.Linear); + var heldId = harness.Acquire(ref heldRequest); + var plainId = harness.Acquire(ref plainRequest); + var held = harness.Image(heldId); + var plain = harness.Image(plainId); + var changes = 0; + held.HeapChanged = _ => changes++; + + harness.Worker.Run(() => + { + harness.Images.DeleteImageForTest(heldId); + harness.Images.DeleteImageForTest(plainId); + }); + harness.Finish(); + + Assert.Equal(1, changes); + Assert.False(held.Registered); + Assert.True(held.Backing.Exists); + Assert.NotNull(held.DeferredErase); + Assert.False(plain.Backing.Exists); + Assert.Null(plain.DeferredErase); + + // What the heap does when it rewrites the image's last element. + held.HeapChanged = null; + var erase = held.DeferredErase!; + held.DeferredErase = null; + harness.Worker.Run(erase); + Assert.True(held.Backing.Exists); + harness.Finish(); + Assert.False(held.Backing.Exists); + _vulkan.AssertNoValidationMessages(); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.ImageTypes.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.ImageTypes.cs index f7797aab5..66b13cfbd 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.ImageTypes.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.ImageTypes.cs @@ -59,7 +59,7 @@ public void ImageTypeReplacementPreservesLayersOutsideTheRequestedRange(bool sta [InlineData(false, true, 2u)] [InlineData(true, false, 2u)] [InlineData(true, true, 2u)] - public void SingletonImageTypeReplacementPreservesContentsAndRetiresTheOldBacking( + public void SingletonImageTypeChangePreservesContentsAndRetiresOnlyAGpuWrittenBacking( bool startWithTwoDimensions, bool gpuModified, uint layers) { if (!GatePrerequisites.Ready(_vulkan)) return; @@ -85,8 +85,9 @@ public void SingletonImageTypeReplacementPreservesContentsAndRetiresTheOldBackin var destinationIdentifier = harness.Acquire(ref destination); var destinationImage = harness.Image(destinationIdentifier); Assert.NotEqual(sourceIdentifier, destinationIdentifier); - Assert.False(sourceImage.Registered); - Assert.True(sourceImage.Binding.NeedsRebind); + // Guest contents keep the image of the other type beside the new one; GPU-written contents move into it. + Assert.Equal(!gpuModified, sourceImage.Registered); + Assert.Equal(gpuModified, sourceImage.Binding.NeedsRebind); Assert.NotEqual(0ul, sourceImage.Backing.Handle.Handle); Assert.Equal(startWithTwoDimensions ? ImageType.Type1D : ImageType.Type2D, destinationImage.Backing.ImageType); Assert.True(destinationImage.SupportsViewType(destination.View)); @@ -96,12 +97,13 @@ public void SingletonImageTypeReplacementPreservesContentsAndRetiresTheOldBackin var expected = Enumerable.Range(0, (int)layers) .Select(layer => gpuModified ? deviceValue : guestValue + (uint)layer).ToArray(); Assert.Equal(Bytes(expected), harness.ReadImageBytes(destinationImage)); - Assert.Equal(0ul, sourceImage.Backing.Handle.Handle); + Assert.Equal(gpuModified, sourceImage.Backing.Handle.Handle == 0); for (uint layer = 0; layer < layers; layer++) Assert.Equal(Bytes(guestValue + layer), harness.Read(address + layer * sliceSize, sizeof(uint))); var restoredIdentifier = harness.Acquire(ref source); Assert.NotEqual(destinationIdentifier, restoredIdentifier); + Assert.Equal(!gpuModified, restoredIdentifier == sourceIdentifier); Assert.Equal(Bytes(expected), harness.ReadImageBytes(harness.Image(restoredIdentifier))); harness.Shutdown(); } @@ -133,6 +135,67 @@ public void SingletonImageTypeReplacementUsesTheCurrentBufferContents(bool start harness.Shutdown(); } + // A texture the guest reads both as 1D and as 2D keeps one image of each type instead of replacing one with the other + // on every lookup. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ASingleRowTextureReadAsBothTypesKeepsOneImageOfEach(bool startWithTwoDimensions) + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var address = harness.MapBacked(0x10000, ReadWrite); + harness.Write(address, Bytes(0x10203040u)); + var first = SingletonRequest(address, 1, startWithTwoDimensions); + var second = SingletonRequest(address, 1, !startWithTwoDimensions); + var firstIdentifier = harness.Acquire(ref first); + var secondIdentifier = harness.Acquire(ref second); + Assert.NotEqual(firstIdentifier, secondIdentifier); + for (var round = 0; round < 3; round++) + { + first = SingletonRequest(address, 1, startWithTwoDimensions); + second = SingletonRequest(address, 1, !startWithTwoDimensions); + Assert.Equal(firstIdentifier, harness.Acquire(ref first)); + Assert.Equal(secondIdentifier, harness.Acquire(ref second)); + } + + Assert.True(harness.Image(firstIdentifier).Registered); + Assert.True(harness.Image(secondIdentifier).Registered); + Assert.Equal(Bytes(0x10203040u), harness.ReadImageBytes(harness.Image(firstIdentifier))); + Assert.Equal(Bytes(0x10203040u), harness.ReadImageBytes(harness.Image(secondIdentifier))); + harness.Shutdown(); + } + + // Once one twin is GPU-written, the other holds stale contents: its next lookup retires it and grows the written image + // into its type. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AGpuWriteToOneSingleRowTwinRetiresTheOther(bool writeTwoDimensions) + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var address = harness.MapBacked(0x10000, ReadWrite); + harness.Write(address, Bytes(0x10203040u)); + var written = SingletonRequest(address, 1, writeTwoDimensions); + var other = SingletonRequest(address, 1, !writeTwoDimensions); + var otherIdentifier = harness.Acquire(ref other); + var writtenIdentifier = harness.Acquire(ref written); + var otherImage = harness.Image(otherIdentifier); + var writtenImage = harness.Image(writtenIdentifier); + Assert.Same(writtenImage, otherImage.DimensionTwin); + writtenImage.MarkGpuModified(); + Assert.True(otherImage.DimensionTwinStale); + + other = SingletonRequest(address, 1, !writeTwoDimensions); + var refreshedIdentifier = harness.Acquire(ref other); + Assert.NotEqual(otherIdentifier, refreshedIdentifier); + Assert.False(otherImage.Registered); + Assert.True(harness.Image(refreshedIdentifier).IsGpuModified); + Assert.True(harness.Image(refreshedIdentifier).SupportsViewType(other.View)); + harness.Shutdown(); + } + [Fact] public void SingletonVolumeKeepsItsCompatibleTwoDimensionalView() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/ImageTestHarness.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/ImageTestHarness.cs index f1b77c4fa..75d42ce61 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Images/ImageTestHarness.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/ImageTestHarness.cs @@ -134,13 +134,15 @@ internal static class GatePrerequisites public static bool DeviceRequired => Environment.GetEnvironmentVariable(RequireDeviceVariable) == "1"; - public static bool Ready([NotNullWhen(true)] HeadlessVulkan? vulkan, bool sampleRateShading = false, bool samplerAnisotropy = false, bool referenceSpirv = false, bool shaderInt64 = false) + public static bool Ready([NotNullWhen(true)] HeadlessVulkan? vulkan, bool sampleRateShading = false, bool samplerAnisotropy = false, bool referenceSpirv = false, bool shaderInt64 = false, + bool robustBufferAccess2 = false) { var missing = vulkan is null ? "a Vulkan device" : sampleRateShading && !vulkan.SampleRateShading ? "the sampleRateShading device feature" : samplerAnisotropy && !vulkan.SamplerAnisotropy ? "the samplerAnisotropy device feature" : referenceSpirv && !vulkan.SupportsSpirv16 ? "a Vulkan 1.3 device for the SPIR-V 1.6 reference modules" : shaderInt64 && !vulkan.ShaderInt64 ? "the shaderInt64 device feature" + : robustBufferAccess2 && !vulkan.RobustBufferAccess2 ? "the robustBufferAccess2 device feature" : null; if (missing is null) { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/ReadbackLandingTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/ReadbackLandingTests.cs new file mode 100644 index 000000000..0e2cf0083 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/ReadbackLandingTests.cs @@ -0,0 +1,70 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using SharpEmu.HLE.Host; +using SharpEmu.Libs.Gpu.Images; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Images; + +public sealed class ReadbackLandingTests +{ + [Theory] + [InlineData(false)] + [InlineData(true)] + public void LandingKeepsThePageACpuStoreCovered(bool sameAsReadback) + { + var backing = new ArrayBackedSpace(); + const ulong address = ArrayBackedSpace.Base; + var queued = new ReadbackLandings(); + var landing = queued.Queue(address, backing.Bytes.AsSpan(0, 3 * 4096)); + var payload = Enumerable.Repeat((byte)0x66, 3 * 4096).ToArray(); + var cpu = sameAsReadback ? (byte)0x66 : (byte)0x77; + queued.NoteGuestStore(address + 4096, 4096); + backing.Bytes.AsSpan(4096, 4096).Fill(cpu); + + Assert.True(landing.TryLand(backing, payload)); + + Assert.All(backing.Bytes.Take(4096), value => Assert.Equal((byte)0x66, value)); + Assert.All(backing.Bytes.Skip(4096).Take(4096), value => Assert.Equal(cpu, value)); + Assert.All(backing.Bytes.Skip(8192).Take(4096), value => Assert.Equal((byte)0x66, value)); + Assert.Empty(queued.Pending); + } + + [Fact] + public void LandingKeepsTheRunsBeforeARefusedWrite() + { + var inner = new ArrayBackedSpace(); + const ulong address = ArrayBackedSpace.Base; + var backing = new RefuseWriteBacking(inner, address + 8192); + var queued = new ReadbackLandings(); + var landing = queued.Queue(address, inner.Bytes.AsSpan(0, 3 * 4096)); + queued.NoteGuestStore(address + 4096, 4096); + inner.Bytes.AsSpan(4096, 4096).Fill(0x77); + var payload = Enumerable.Repeat((byte)0x66, 3 * 4096).ToArray(); + + Assert.False(landing.TryLand(backing, payload)); + + Assert.All(inner.Bytes.Take(4096), value => Assert.Equal((byte)0x66, value)); + Assert.All(inner.Bytes.Skip(4096).Take(4096), value => Assert.Equal((byte)0x77, value)); + Assert.All(inner.Bytes.Skip(8192).Take(4096), value => Assert.Equal((byte)0, value)); + Assert.Empty(queued.Pending); + } + + private sealed class RefuseWriteBacking(IGuestBackedSpace inner, ulong refused) : IGuestBackedSpace + { + public bool TryHoldRange(ulong address, ulong size) => inner.TryHoldRange(address, size); + public bool TryHoldRangeAtOrAbove(ulong start, ulong size, ulong alignment, out ulong address) => + inner.TryHoldRangeAtOrAbove(start, size, alignment, out address); + public bool TryMapBacked(ulong address, ulong size, ulong offset, GuestPageProtection protection, out HostViewFailure failure) => + inner.TryMapBacked(address, size, offset, protection, out failure); + public bool TryUnmapBacked(ulong address, ulong size) => inner.TryUnmapBacked(address, size); + public bool TryClearBacking(ulong offset, ulong size) => inner.TryClearBacking(offset, size); + public bool IsBackedView(ulong address) => inner.IsBackedView(address); + public bool IsBackedRange(ulong address, ulong size) => inner.IsBackedRange(address, size); + public bool TryReadBacking(ulong address, Span bytes) => inner.TryReadBacking(address, bytes); + public bool TryWriteBacking(ulong address, ReadOnlySpan bytes) => + address != refused && inner.TryWriteBacking(address, bytes); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/ViewFormatRulesTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/ViewFormatRulesTests.cs index a09d17078..5d0d93677 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Images/ViewFormatRulesTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/ViewFormatRulesTests.cs @@ -77,6 +77,7 @@ public void DepthViews_AcceptOnlyTheReplicatedSwizzles() var replicated = ViewFormatRules.PackDestinationSelect(4, 4, 4, 4); Assert.True(ViewFormatRules.IsSupportedSampledDepthView(Format.D32Sfloat, Format.R32Sfloat, replicated)); Assert.True(ViewFormatRules.IsSupportedSampledDepthView(Format.D16Unorm, Format.R16Unorm, ViewFormatRules.PackDestinationSelect(4, 0, 0, 1))); + Assert.True(ViewFormatRules.IsSupportedSampledDepthView(Format.D16Unorm, Format.R16Unorm, ViewFormatRules.PackDestinationSelect(4, 4, 4, 1))); Assert.False(ViewFormatRules.IsSupportedSampledDepthView(Format.D32Sfloat, Format.R32Sfloat, ViewFormatRules.PackDestinationSelect(4, 5, 6, 7))); Assert.False(ViewFormatRules.IsSupportedSampledDepthView(Format.R32Sfloat, Format.R32Sfloat, replicated)); Assert.Equal(replicated, ViewFormatRules.SelectSampledDepthView(Format.D32SfloatS8Uint, Format.R32Uint, replicated)); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/CallTableScanTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/CallTableScanTests.cs new file mode 100644 index 000000000..8a377fd9b --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/CallTableScanTests.cs @@ -0,0 +1,429 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; +using Mode = SharpEmu.Libs.Gpu.Pipelines.ShaderCallLibrary.TableScanMode; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +// The one-pass table read (ShaderCallLibrary.TableScan.cs): on the same memory it returns the library the original read +// returns (ShaderCallLibraryMemo.Difference) and throws the original's exceptions. +public sealed class CallTableScanTests +{ + private const ulong TableA = 0x10_0000_0000; + private const ulong TableB = 0x20_0000_0000; + private const ulong Code = 0x200000; + + // Site 1 reads table A (records selected by s20), site 2 calls the pair user data s4..s7 hold, site 3 reads table B + // (records selected by s21). + private static Gen5ShaderProgram ThreeSites() => Program( + Sop2(0, "SLshlB32", 20, Gen5Operand.Scalar(20), Operand(4)), + ScalarBufferLoad(4, 0, 16, 4, dynamicOffsetRegister: 20), + Vop1(12, "VMovB32", 111, Operand(0)), + new(16, Gen5ShaderEncoding.Sopp, "SWaitcnt", [0xBF8C0000], [], [], null), + MoveScalarRegister(20, 14, 16), MoveScalarRegister(24, 15, 17), + MoveScalarRegister(28, 16, 18), MoveScalarRegister(32, 17, 19), + Sop1(36, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + MoveScalarRegister(40, 14, 4), MoveScalarRegister(44, 15, 5), + MoveScalarRegister(48, 16, 6), MoveScalarRegister(52, 17, 7), + Vop1(56, "VMovB32", 5, Operand(0)), + Sop1(60, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + Sop2(64, "SLshlB32", 21, Gen5Operand.Scalar(21), Operand(4)), + ScalarBufferLoad(68, 8, 24, 4, dynamicOffsetRegister: 21), + Vop1(76, "VMovB32", 111, Operand(0)), + new(80, Gen5ShaderEncoding.Sopp, "SWaitcnt", [0xBF8C0000], [], [], null), + MoveScalarRegister(84, 14, 24), MoveScalarRegister(88, 15, 25), + MoveScalarRegister(92, 16, 26), MoveScalarRegister(96, 17, 27), + Sop1(100, "SSwappcB64", 14, Gen5Operand.Scalar(14)), EndProgram(104)); + + // One site reading the record at a fixed offset. + private static Gen5ShaderProgram FixedRecord(int offset) => Program( + ScalarBufferLoad(0, 0, 16, 4, immediateOffset: offset), + Vop1(8, "VMovB32", 111, Operand(0)), + new(12, Gen5ShaderEncoding.Sopp, "SWaitcnt", [0xBF8C0000], [], [], null), + MoveScalarRegister(16, 14, 16), MoveScalarRegister(20, 15, 17), + MoveScalarRegister(24, 16, 18), MoveScalarRegister(28, 17, 19), + Sop1(32, "SSwappcB64", 14, Gen5Operand.Scalar(14)), EndProgram(36)); + + private static MemoryAccessTable Access(params uint[] loadPcs) + { + var access = new MemoryAccessTable(); + for (var index = 0; index < loadPcs.Length; index++) + access.Add(new() { Pc = loadPcs[index], Kind = MemoryResourceKind.ScalarBuffer, Resource = (uint)index }); + return access; + } + + private static uint[] Descriptor(ulong address, int records) => + [unchecked((uint)address), (uint)(address >> 32) | (16u << 16), (uint)records, 0]; + + // Guest memory: the tables, the callees' code (callee n at Code + n * 0x100, 1 + n % 5 nops then a return) and + // addresses whose code cannot be read; a flaky address fails its first function read of each read pass. + private sealed class Guest + { + public readonly Dictionary Tables = new(); + public readonly HashSet Unreadable = []; + public ulong Flaky = ulong.MaxValue; + public bool FlakyFailed; + public int Callees = 12; + public bool TablesCopy = true; + + public bool ReadWord(ulong address, out uint word) + { + word = 0; + foreach (var (start, bytes) in Tables) + { + if (address >= start && address - start + 4 <= (ulong)bytes.Length) + { + word = BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan((int)(address - start))); + return true; + } + } + + if (address < Code || address >= Code + (ulong)Callees * 0x100) return false; + var function = address - (address - Code) % 0x100; + if (Unreadable.Contains(function)) return false; + if (function == Flaky && !FlakyFailed) + { + FlakyFailed = true; + return false; + } + + var callee = (int)((function - Code) / 0x100); + var index = (int)((address - function) / 4); + var nops = 1 + callee % 5; + word = index < nops ? 0xBF800000 : index == nops ? 0xBE80200E : 0; + return index <= nops; + } + + public bool ReadBytes(ulong address, Span destination, bool clean) + { + if (!TablesCopy) return false; + foreach (var (start, bytes) in Tables) + { + if (address >= start && address - start + (ulong)destination.Length <= (ulong)bytes.Length) + { + bytes.AsSpan((int)(address - start), destination.Length).CopyTo(destination); + return true; + } + } + + return false; + } + } + + private static ShaderCallLibrary Read(Mode mode, Gen5ShaderProgram caller, MemoryAccessTable access, ResourceSnapshot snapshot, + Guest guest, ShaderFunctionCache? functions, ShaderCallLibraryMemo? memo) + { + ShaderCallLibrary.TableScanOverride = mode; + try + { + guest.FlakyFailed = false; + return ShaderCallLibrary.Read(caller, access, snapshot, guest.ReadWord, functions, runtimeArguments: true, userDataBase: 0, + readBytes: guest.ReadBytes, memo: memo); + } + finally + { + ShaderCallLibrary.TableScanOverride = null; + } + } + + private static Exception? Throws(Mode mode, Gen5ShaderProgram caller, MemoryAccessTable access, ResourceSnapshot snapshot, + Guest guest, ShaderFunctionCache? functions = null) + { + try + { + Read(mode, caller, access, snapshot, guest, functions, null); + return null; + } + catch (InvalidOperationException exception) + { + return exception; + } + } + + // ShaderCallLibraryMemo.Difference without program identity, for reads with their own function caches. + private static void SameShape(ShaderCallLibrary expected, ShaderCallLibrary actual) + { + static string Shape(ShaderCallSite site) => $"{site.Pc}:{site.AddressRegister}:{site.ArgumentRegister}:{site.ReturnAddress}:" + + string.Join(",", site.Targets.Select(static target => $"{target.Address:X}/{target.Argument:X}/{target.Program.Instructions.Count}")); + Assert.Equal(expected.Identity, actual.Identity); + Assert.Equal(expected.LayoutIdentity, actual.LayoutIdentity); + Assert.Equal(expected.Bodies, actual.Bodies); + Assert.Equal(expected.Records, actual.Records); + Assert.Equal(expected.Calls.Select(Shape), actual.Calls.Select(Shape)); + Assert.Equal(expected.CurrentCodeHashes.Keys, actual.CurrentCodeHashes.Keys); + Assert.Equal(expected.CodeHashes.Keys.Order(), actual.CodeHashes.Keys.Order()); + Assert.Equal(expected.CurrentSites.Keys.Order(), actual.CurrentSites.Keys.Order()); + foreach (var (address, sites) in expected.CurrentSites) Assert.True(sites.SetEquals(actual.CurrentSites[address])); + } + + private static void Record(byte[] table, int index, ulong target, ulong argument) + { + BinaryPrimitives.WriteUInt64LittleEndian(table.AsSpan(index * 16), target); + BinaryPrimitives.WriteUInt64LittleEndian(table.AsSpan(index * 16 + 8), argument); + } + + // Random tables: most records zero, the rest naming twelve callees (two of them unreadable) with arguments from a small + // pool, so records repeat within and across tables; user data names one of them. + private static (Guest Guest, ResourceSnapshot Snapshot) RandomTables(int seed, int recordsA, int recordsB) + { + var random = new System.Random(seed); + var guest = new Guest(); + guest.Unreadable.Add(Code + 3 * 0x100); + guest.Unreadable.Add(Code + 7 * 0x100); + var a = new byte[recordsA * 16]; + var b = new byte[recordsB * 16]; + foreach (var table in new[] { a, b }) + { + for (var index = 0; index < table.Length / 16; index++) + { + if (random.Next(10) < 7) continue; + Record(table, index, Code + (ulong)random.Next(guest.Callees) * 0x100, 0x5000ul + (ulong)random.Next(20) * 0x40); + } + } + + guest.Tables[TableA] = a; + guest.Tables[TableB] = b; + var user = Code + (ulong)random.Next(guest.Callees) * 0x100; + if (guest.Unreadable.Contains(user)) user += 0x100; + var snapshot = new ResourceSnapshot + { + Buffers = [Descriptor(TableA, recordsA), Descriptor(TableB, recordsB)], + UserData = [0, 0, 0, 0, (uint)user, (uint)(user >> 32), 0x7000, 0x12], + }; + return (guest, snapshot); + } + + [Theory] + [InlineData(1, 7, 3)] + [InlineData(2, 64, 64)] + [InlineData(3, 333, 1)] + [InlineData(4, 2049, 517)] + [InlineData(5, 40000, 9)] + [InlineData(6, 1, 40000)] + public void TheScanReturnsTheOriginalsLibrary(int seed, int recordsA, int recordsB) + { + var caller = ThreeSites(); + var access = Access(4, 68); + var (guest, snapshot) = RandomTables(seed, recordsA, recordsB); + foreach (var copy in new[] { true, false }) + { + guest.TablesCopy = copy; + var functions = new ShaderFunctionCache(guest.ReadBytes); + var original = Read(Mode.Off, caller, access, snapshot, guest, functions, null); + var scanned = Read(Mode.On, caller, access, snapshot, guest, functions, null); + Assert.Null(ShaderCallLibraryMemo.Difference(scanned, original)); + Assert.Equal(3, original.Calls.Count); + Assert.NotEmpty(original.Records); + + // With call-library reuse, a scan that derives the topology and one that reuses it. + var memo = new ShaderCallLibraryMemo(active: true); + var first = Read(Mode.On, caller, access, snapshot, guest, functions, memo); + var reused = Read(Mode.On, caller, access, snapshot, guest, functions, memo); + Assert.Null(ShaderCallLibraryMemo.Difference(first, original)); + Assert.Null(ShaderCallLibraryMemo.Difference(reused, original)); + Assert.Equal(1, memo.Counted("TopologyHit")); + } + } + + // A record's order and the site that first names a callee decide the records and current code hashes: the same records + // in another order give the original's other order. + [Fact] + public void RecordsKeepTheOriginalsOrderAcrossSites() + { + var caller = ThreeSites(); + var access = Access(4, 68); + var guest = new Guest(); + var a = new byte[8 * 16]; + var b = new byte[8 * 16]; + Record(a, 5, Code + 0x200, 0x5040); + Record(a, 1, Code + 0x100, 0x5000); + Record(a, 6, Code + 0x100, 0x5000); + Record(b, 0, Code + 0x200, 0x5040); + Record(b, 2, Code + 0x400, 0x5000); + Record(b, 7, Code + 0x100, 0x6000); + guest.Tables[TableA] = a; + guest.Tables[TableB] = b; + var snapshot = new ResourceSnapshot + { + Buffers = [Descriptor(TableA, 8), Descriptor(TableB, 8)], + UserData = [0, 0, 0, 0, (uint)(Code + 0x500), 0, 0x7000, 0], + }; + var functions = new ShaderFunctionCache(guest.ReadBytes); + var original = Read(Mode.Off, caller, access, snapshot, guest, functions, null); + var scanned = Read(Mode.On, caller, access, snapshot, guest, functions, null); + Assert.Null(ShaderCallLibraryMemo.Difference(scanned, original)); + Assert.Equal(new (ulong, ulong)[] + { + (Code + 0x100, 0x5000), (Code + 0x200, 0x5040), (Code + 0x500, 0x7000), (Code + 0x400, 0x5000), (Code + 0x100, 0x6000), + }, scanned.Records); + Assert.Equal(new[] { Code + 0x100, Code + 0x200, Code + 0x500, Code + 0x400 }, scanned.CurrentCodeHashes.Keys); + Assert.Equal(new uint[] { 36, 100 }, scanned.CurrentSites[Code + 0x100].Order()); + } + + // A table record whose function cannot be read leaves out every later table record naming it, also after a user-data + // site reads that function; the user-data site keeps it. + [Fact] + public void AFunctionATableCouldNotReadStaysOutOfLaterTables() + { + var caller = ThreeSites(); + var access = Access(4, 68); + var guest = new Guest { Flaky = Code + 0x200 }; + var a = new byte[4 * 16]; + var b = new byte[4 * 16]; + Record(a, 0, Code + 0x200, 0x5000); + Record(a, 1, Code + 0x100, 0x5000); + Record(b, 0, Code + 0x200, 0x6000); + Record(b, 1, Code + 0x100, 0x6000); + guest.Tables[TableA] = a; + guest.Tables[TableB] = b; + var snapshot = new ResourceSnapshot + { + Buffers = [Descriptor(TableA, 4), Descriptor(TableB, 4)], + UserData = [0, 0, 0, 0, (uint)(Code + 0x200), 0, 0x7000, 0], + }; + var original = Read(Mode.Off, caller, access, snapshot, guest, new ShaderFunctionCache(guest.ReadBytes), null); + var scanned = Read(Mode.On, caller, access, snapshot, guest, new ShaderFunctionCache(guest.ReadBytes), null); + SameShape(original, scanned); + Assert.Contains((Code + 0x200, 0x7000ul), scanned.Records); + Assert.DoesNotContain((Code + 0x200, 0x5000ul), scanned.Records); + Assert.DoesNotContain((Code + 0x200, 0x6000ul), scanned.Records); + } + + // Every refusal and failure throws the original's exception. + [Fact] + public void FailuresThrowTheOriginalsExceptions() + { + static void Same(Exception? original, Exception? scanned) + { + Assert.NotNull(original); + Assert.NotNull(scanned); + Assert.Equal(original!.GetType(), scanned!.GetType()); + Assert.Equal(original.Message, scanned.Message); + } + + var caller = ThreeSites(); + var access = Access(4, 68); + var (guest, snapshot) = RandomTables(9, 100, 100); + + // A user-data function that cannot be read. + var unreadable = new ResourceSnapshot { Buffers = snapshot.Buffers, UserData = [0, 0, 0, 0, (uint)(Code + 3 * 0x100), 0, 0x7000, 0] }; + Same(Throws(Mode.Off, caller, access, unreadable, guest), Throws(Mode.On, caller, access, unreadable, guest)); + Assert.IsType(Throws(Mode.On, caller, access, unreadable, guest)); + + // A table the host can read only in part. + var partial = new Guest { TablesCopy = false }; + partial.Tables[TableA] = new byte[64 * 16]; + partial.Tables[TableB] = new byte[16]; + var past = new ResourceSnapshot { Buffers = [Descriptor(TableA, 64), Descriptor(TableB, 8)], UserData = snapshot.UserData }; + Same(Throws(Mode.Off, caller, access, past, partial), Throws(Mode.On, caller, access, past, partial)); + + // An unsupported layout, a table past 16 MiB, no buffer for a load. + var swizzled = new ResourceSnapshot + { + Buffers = [[unchecked((uint)TableA), (uint)(TableA >> 32) | (16u << 16) | 0x80000000u, 100, 0], Descriptor(TableB, 100)], + UserData = snapshot.UserData, + }; + Same(Throws(Mode.Off, caller, access, swizzled, guest), Throws(Mode.On, caller, access, swizzled, guest)); + var huge = new ResourceSnapshot { Buffers = [Descriptor(TableA, (16 << 20) / 16 + 1), Descriptor(TableB, 100)], UserData = snapshot.UserData }; + Same(Throws(Mode.Off, caller, access, huge, guest), Throws(Mode.On, caller, access, huge, guest)); + var noBuffer = new ResourceSnapshot { Buffers = [Descriptor(TableA, 100)], UserData = snapshot.UserData }; + Same(Throws(Mode.Off, caller, access, noBuffer, guest), Throws(Mode.On, caller, access, noBuffer, guest)); + + // A fixed record past the table's end. + var fixedCaller = FixedRecord(64 * 16); + var fixedAccess = Access(0); + var small = new ResourceSnapshot { Buffers = [Descriptor(TableA, 64)], UserData = snapshot.UserData }; + Same(Throws(Mode.Off, fixedCaller, fixedAccess, small, guest), Throws(Mode.On, fixedCaller, fixedAccess, small, guest)); + } + + // A fixed record, an empty table and a zero user-data target. + [Theory] + [InlineData(0)] + [InlineData(16)] + [InlineData(1024)] + public void FixedRecordsEmptyTablesAndNullTargets(int offset) + { + var (guest, snapshot) = RandomTables(11, 200, 0); + Record(guest.Tables[TableA], offset / 16, Code + 0x100, 0x5100); + var fixedCaller = FixedRecord(offset); + var fixedSnapshot = new ResourceSnapshot { Buffers = [Descriptor(TableA, 200)], UserData = snapshot.UserData }; + var functions = new ShaderFunctionCache(guest.ReadBytes); + Assert.Null(ShaderCallLibraryMemo.Difference( + Read(Mode.On, fixedCaller, Access(0), fixedSnapshot, guest, functions, null), + Read(Mode.Off, fixedCaller, Access(0), fixedSnapshot, guest, functions, null))); + + var empty = new ResourceSnapshot + { + Buffers = [Descriptor(TableA, 200), Descriptor(TableB, 0)], + UserData = [0, 0, 0, 0, 0, 0, 0x7000, 0], + }; + var caller = ThreeSites(); + var original = Read(Mode.Off, caller, Access(4, 68), empty, guest, functions, null); + Assert.Null(ShaderCallLibraryMemo.Difference(Read(Mode.On, caller, Access(4, 68), empty, guest, functions, null), original)); + Assert.Empty(original.Calls[1].Targets); + Assert.Empty(original.Calls[2].Targets); + } + + // The scan reads each function once per read, as the original does, and allocates a small part of the original's + // bytes for a large table. + [Fact] + public void TheScanReadsFunctionsOnceAndAllocatesLess() + { + var caller = ThreeSites(); + var access = Access(4, 68); + var (guest, snapshot) = RandomTables(17, 60000, 16); + var random = new System.Random(17); + for (var index = 0; index < 60000; index += 3) + { + var callee = random.Next(guest.Callees); + if (callee is 3 or 7) callee++; + Record(guest.Tables[TableA], index, Code + (ulong)callee * 0x100, 0x100000ul + (ulong)index * 0x40); + } + + var functions = new ShaderFunctionCache(guest.ReadBytes); + Read(Mode.Off, caller, access, snapshot, guest, functions, null); + Read(Mode.On, caller, access, snapshot, guest, functions, null); + var before = GC.GetAllocatedBytesForCurrentThread(); + Read(Mode.Off, caller, access, snapshot, guest, functions, null); + var original = GC.GetAllocatedBytesForCurrentThread() - before; + before = GC.GetAllocatedBytesForCurrentThread(); + Read(Mode.On, caller, access, snapshot, guest, functions, null); + var scanned = GC.GetAllocatedBytesForCurrentThread() - before; + Assert.True(scanned * 4 < original, $"scanned {scanned} bytes, original {original}"); + + var reads = new Dictionary(); + bool Counting(ulong address, out uint word) + { + if (address >= Code && address < Code + 0x10000 && (address - Code) % 0x100 == 0) + reads[address] = reads.GetValueOrDefault(address) + 1; + return guest.ReadWord(address, out word); + } + + ShaderCallLibrary.TableScanOverride = Mode.On; + try + { + ShaderCallLibrary.Read(caller, access, snapshot, Counting, null, runtimeArguments: true, userDataBase: 0, + readBytes: guest.ReadBytes); + } + finally + { + ShaderCallLibrary.TableScanOverride = null; + } + + Assert.All(reads.Values, count => Assert.Equal(1, count)); + Assert.Equal(guest.Callees, reads.Count); + } + + [Fact] + public void TheScanIsOnUnlessConfigured() + { + if (Environment.GetEnvironmentVariable("SHARPEMU_CALL_TABLE_SCAN") is not null) return; + Assert.Equal(Mode.On, ShaderCallLibrary.TableScan); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ComputeRejectionPolicyTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ComputeRejectionPolicyTests.cs index 5b2502f7c..719cf0bad 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ComputeRejectionPolicyTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ComputeRejectionPolicyTests.cs @@ -14,6 +14,9 @@ namespace SharpEmu.Libs.Tests.Gpu.Pipelines; public sealed class ComputeRejectionPolicyTests { private const string Variable = "SHARPEMU_STRICT_COMPUTE"; + // The rejected plans below read an image descriptor at an index the host cannot evaluate. Null bindless descriptors, + // on by default, would read it as null instead, so these tests turn them off. + private const string BindlessNullVariable = "SHARPEMU_BINDLESS_NULL"; private const ulong CodeAddress = PipelineTestGuest.MemoryBase + 0x1000; private const ulong HeaderAddress = PipelineTestGuest.MemoryBase + 0x8000; @@ -57,9 +60,11 @@ public void UnsupportedShaderCallsRespectTheRejectionPolicy(bool strict) public void ComputeRejectionUsesTheConfiguredPolicy(string? value, bool rejectPlan) { var previous = Environment.GetEnvironmentVariable(Variable); + var previousBindlessNull = Environment.GetEnvironmentVariable(BindlessNullVariable); try { Environment.SetEnvironmentVariable(Variable, value); + Environment.SetEnvironmentVariable(BindlessNullVariable, "0"); using var fatal = new FatalScope(); var guest = new PipelineTestGuest(); guest.RegisterProgram(CodeAddress, HeaderAddress, rejectPlan @@ -92,6 +97,37 @@ public void ComputeRejectionUsesTheConfiguredPolicy(string? value, bool rejectPl finally { Environment.SetEnvironmentVariable(Variable, previous); + Environment.SetEnvironmentVariable(BindlessNullVariable, previousBindlessNull); + } + } + + // Planning a large program takes seconds, so a rejected program is not planned again: the second lookup reads code + // that would now plan, and still gets the first rejection. + [Fact] + public void ARejectedPlanIsNotPlannedAgain() + { + var previousBindlessNull = Environment.GetEnvironmentVariable(BindlessNullVariable); + try + { + Environment.SetEnvironmentVariable(BindlessNullVariable, "0"); + using var fatal = new FatalScope(); + var guest = new PipelineTestGuest(); + guest.RegisterProgram(CodeAddress, HeaderAddress, [0x7E100500, 0xF42C0402, 0x10000000, 0xF0000108, 0x00040000, 0xBF810000]); + var source = guest.Source(CodeAddress, ShaderStage.Compute, []); + var cursor = 0u; + Assert.False(guest.Programs.TryGetProgram(source, PipelineTestGuest.ComputeOptions(32), false, ref cursor, + out _, out _, out var first)); + Assert.Contains("resource plan is invalid", first); + + guest.WriteWords(CodeAddress, 0xBF810000, 0xBF810000, 0xBF810000, 0xBF810000, 0xBF810000, 0xBF810000); + Assert.False(guest.Programs.TryGetProgram(source, PipelineTestGuest.ComputeOptions(32), false, ref cursor, + out _, out _, out var second)); + Assert.Equal(first, second); + Assert.Empty(guest.Compiler.Requests); + } + finally + { + Environment.SetEnvironmentVariable(BindlessNullVariable, previousBindlessNull); } } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ImageBindingTestProgram.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ImageBindingTestProgram.cs new file mode 100644 index 000000000..942166ff3 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ImageBindingTestProgram.cs @@ -0,0 +1,37 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +internal static class ImageBindingTestProgram +{ + public static readonly StableImageDescriptorLimits Limits = new(16, 0, 4, 3, 19); + public static readonly uint[][] Partitions = + [ + [0, 1, 2, 1, 2, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2], + [0, 1, 1, 1, 4, 1, 1, 1, 8, 8, 8, 8, 8, 8, 8, 8], + ]; + + public static uint[] Code() + { + // One sampler from +512, then sixteen image descriptors at +32*i. + var words = new List { 0xF4080600, 0xFA000200 }; + for (uint index = 0; index < 16; index++) + { + words.AddRange([0xF40C0400, 0xFA000000 | (index * 32), // s_load_dwordx8 s[16:23], s[0:1] + 0xF09C0F08, 0x00C40400]); // image_sample_lz v[4:7], v[0:1], s[16:23], s[24:27], 2D + } + words.Add(0xBF810000); + return [.. words]; + } + + public static void WriteDescriptors(PipelineTestGuest guest, ulong address, uint[] partition) + { + for (var index = 0; index < 16; index++) + guest.WriteWords(address + (ulong)index * 32, + 0x20u + partition[index], 77u << 20, 3u | (3u << 14), 0xFACu | (9u << 28), 0, 0, 0, 0); + guest.WriteWords(address + 512, 0, 0, 0, 0); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/LinkedShaderPrewarmTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/LinkedShaderPrewarmTests.cs new file mode 100644 index 000000000..18ab6b75d --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/LinkedShaderPrewarmTests.cs @@ -0,0 +1,96 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.ShaderCompiler; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +public sealed class LinkedShaderPrewarmTests +{ + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(true, true)] + public void RestoresCapturedCodeCallOrderAndModes(bool runtimeRecords, bool callMarks) + { + const ulong callerAddress = 0x1000, functionAddress = 0x2000; + uint[] words = [0xBF800000, 0xBE80200E]; + var function = ShaderFunctionReader.Read(functionAddress, (ulong address, out uint word) => + { + var offset = address - functionAddress; + word = offset < 8 ? words[(int)(offset / 4)] : 0; + return offset < 8; + }); + Assert.True(function.Complete, function.Error); + var caller = new Gen5ShaderProgram(callerAddress, + [ + new(0, Gen5ShaderEncoding.Sop1, "SSwappcB64", [0xBE8E210E], [Gen5Operand.Scalar(14)], [Gen5Operand.Scalar(14)], null), + new(4, Gen5ShaderEncoding.Sopp, "SEndpgm", [0xBF810000], [], [], null), + ]); + var site = new ShaderCallSite(0, 14, 16, 14, callerAddress + 4, + [new(functionAddress, 0x3000, function.Program), new(functionAddress, 0x4000, function.Program)]); + var library = new ShaderCallLibrary("test", [site], "test", [0x3000, 0x4000]) + { + CodeRuns = new() { [functionAddress] = function.Runs }, + }; + var expected = Gen5ShaderCallLinker.Link(caller, library.Calls, runtimeRecords); + var captured = LinkedShaderPrewarm.Capture(library, runtimeRecords, callMarks, bindlessHeap: false); + Assert.Single(captured.Functions); + // The library's backing bytes may be reused later; the record must keep the exact earlier code. + function.Runs[0].Bytes[0] ^= 1; + var restored = Read(Write(captured)); + Assert.Equal(runtimeRecords, restored.RuntimeRecords); + Assert.Equal(callMarks, restored.CallMarks); + Assert.False(restored.BindlessHeap); + Assert.Equal(new ulong[] { 0x3000, 0x4000 }, restored.Sites[0].Targets.Select(target => target.Argument)); + var actual = restored.Link(caller); + Assert.Equal(expected.Instructions.Select(instruction => instruction.Opcode), actual.Instructions.Select(instruction => instruction.Opcode)); + Assert.Equal(expected.Instructions.Select(instruction => instruction.Control), actual.Instructions.Select(instruction => instruction.Control)); + Assert.Equal(expected.Instructions.SelectMany(instruction => instruction.Words), actual.Instructions.SelectMany(instruction => instruction.Words)); + } + + [Fact] + public void CapturePreservesTheLibrarySiteOrder() + { + var first = new ShaderCallSite(8, 14, 16, 14, 0x100CUL, []); + var second = new ShaderCallSite(0, 14, 16, 14, 0x1004UL, []); + var library = new ShaderCallLibrary("test", [first, second], "test", []); + var restored = Read(Write(LinkedShaderPrewarm.Capture(library, false, false, false))); + Assert.Equal(new uint[] { 8, 0 }, restored.Sites.Select(site => site.Pc)); + } + + [Theory] + [InlineData(-1)] + [InlineData(int.MaxValue)] + public void RejectsImpossibleFunctionCountsBeforeAllocation(int count) + { + var bytes = Write(new LinkedShaderPrewarm(false, false, false, [], [])); + BinaryPrimitives.WriteInt32LittleEndian(bytes.AsSpan(3), count); + Assert.Throws(() => Read(bytes)); + } + + [Fact] + public void RejectsACallWhoseCodeIsMissing() + { + var record = new LinkedShaderPrewarm(false, false, false, [], + [new(0, 14, 16, 14, 0x1004, [new(0x2000, 0x3000)])]); + Assert.Throws(() => Read(Write(record))); + } + + private static byte[] Write(LinkedShaderPrewarm record) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + record.Write(writer); + return stream.ToArray(); + } + + private static LinkedShaderPrewarm Read(byte[] bytes) + { + using var reader = new BinaryReader(new MemoryStream(bytes)); + return LinkedShaderPrewarm.Read(reader); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/MeshDrawPlannerTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/MeshDrawPlannerTests.cs index 731a7b1f5..1767736f2 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/MeshDrawPlannerTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/MeshDrawPlannerTests.cs @@ -138,6 +138,48 @@ public void FusedGeometry_KeepsTriangleAssemblyAndProvokingVertex(bool triangleS Assert.Equal(triangleStrip, plan.Geometry.InputTriangleStrip); } + // A mesh-style primitive shader: one input point per subgroup, 32 output vertices, VGT_GS_MAX_VERT_OUT 32 and + // 48 output primitives (a 4x3 grid of cells, four triangles around each cell centre). + [Theory] + [InlineData(0u, 30u, 32u)] + [InlineData(48u, 48u, 64u)] + [InlineData(16u, 30u, 32u)] + public void PrimitiveAmplificationSizesTheOutputAndTheLanes(uint amplification, uint primitives, uint threads) + { + var banks = MeshStyleBanks(amplification); + var plan = Assert.IsType(Create(banks)); + Assert.True(plan.Geometry.InputPointList); + Assert.Equal(1u, plan.Geometry.InputPrimitiveCountPerWorkgroup); + Assert.Equal(32u, plan.Geometry.OutputVertexCapacity); + Assert.Equal(primitives, plan.Geometry.OutputPrimitiveCapacity); + Assert.Equal(threads, plan.Geometry.ThreadsPerGroup); + } + + [Theory] + [InlineData("invocations")] + [InlineData("primitives")] + public void PrimitiveAmplificationBeyondTheDeviceKeepsTheStripPlan(string limit) + { + var limits = limit == "invocations" ? Limits with { MaxInvocations = 32, MaxWorkGroupSizeX = 32 } + : Limits with { OutputPrimitiveCapacity = 40 }; + var plan = Assert.IsType(Create(MeshStyleBanks(48), limits)); + Assert.Equal(30u, plan.Geometry.OutputPrimitiveCapacity); + Assert.Equal(32u, plan.Geometry.ThreadsPerGroup); + } + + private static RegisterBanks MeshStyleBanks(uint amplification) + { + var banks = Banks(); + banks.Context.ShaderStages = 0x20u | 1u << 22; + banks.Context.ShaderInterface.MaxOutputPerSubgroup = 32; + banks.Context.ShaderInterface.GeometryMaxVerticesOut = 32; + banks.Context.ShaderInterface.PrimitiveShaderSubgroupControl = amplification; + banks.UserConfig.PrimitiveType = 1; + banks.UserConfig.GeometryEngineControl.PrimitiveGroupSize = 1; + banks.UserConfig.GeometryEngineControl.VertexGroupSize = 1; + return banks; + } + private static MeshDrawPlan? Create(RegisterBanks banks, MeshShaderLimits? limits = null, uint subgroup = 32) => MeshDrawPlanner.Create(banks.Shader.Vertex, banks.Context.ShaderInterface, banks.Context, banks.UserConfig, limits ?? Limits, subgroup); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PendingPassSkipTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PendingPassSkipTests.cs new file mode 100644 index 000000000..0b72c5040 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PendingPassSkipTests.cs @@ -0,0 +1,311 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +// While the newest program of a runtime-record caller compiles, the caller's older ready program serves. With SkipPendingPass a +// dispatch whose resolution selects the permutation still compiling polls that compile and, while it compiles, serves the +// fallback without the newest program's record ranges and stage resources; what each dispatch serves, and the fallback it +// reports, must not change. +[Collection(SchedulingStateCollection.Name)] +public sealed class PendingPassSkipTests : IDisposable +{ + private const ulong Caller = PipelineTestGuest.MemoryBase + 0x1000; + private const ulong Header = PipelineTestGuest.MemoryBase + 0x8000; + private const ulong Table = PipelineTestGuest.MemoryBase + 0x10000; + private const ulong Callee = PipelineTestGuest.MemoryBase + 0x20000; + private readonly string _directory = Path.Combine(Path.GetTempPath(), "SharpEmuTests", Guid.NewGuid().ToString("N")); + private long _lastEarlySkips; + private long _lastCallDispatchReuses; + + private sealed record Dispatch(ulong Served, LinkedCompileFallback? Fallback); + + private sealed record Poll(int Dispatch, ulong Program, ShaderStageResources Stage); + + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public void CurrentDispatchContinuationPreservesFallbackSelectionAndPipelinePolling(bool early, bool middle) + { + var (ordinary, ordinaryPolls, _) = Run(skip: true, middle: middle, early: early); + Assert.Equal(0, _lastCallDispatchReuses); + var (continued, continuedPolls, _) = Run(skip: true, middle: middle, early: early, reuseDispatch: true); + Assert.True(_lastCallDispatchReuses > 0); + Assert.Equal(ordinary.Select(Served), continued.Select(Served)); + Assert.Equal(ordinaryPolls.Select(poll => (poll.Dispatch, poll.Program)), + continuedPolls.Select(poll => (poll.Dispatch, poll.Program))); + } + + [Fact] + public void CurrentDispatchContinuationReadsTheNextDispatchsChangedRecords() + { + using var fatal = new FatalScope(); + var guest = new PipelineTestGuest(CompileSpirv); + guest.Host.RuntimeCallRecordsSupported = true; + // Two fixed-offset call sites: the first stays ready and reads the changed argument, while the second + // introduces new code whose pipeline stays pending. Merely growing this fixed-offset table adds no call site. + guest.RegisterProgram(Caller, Header, + [0xF4280400, 125u << 25, 0xBF8C0000, 0xBE8E0310, 0xBE8F0311, 0xBE900312, 0xBE910313, 0xBE8E210E, + 0xF4280400, (125u << 25) | 16, 0xBF8C0000, 0xBE8E0310, 0xBE8F0311, 0xBE900312, 0xBE910313, 0xBE8E210E, 0xBF810000]); + guest.WriteWords(Callee, 0xBF800000, 0xBE80200E); + const ulong secondCallee = Callee + 0x100; + guest.WriteWords(secondCallee, 0xBF800001, 0xBE80200E); + guest.WriteWords(Table, unchecked((uint)Callee), (uint)(Callee >> 32), 0x3000, 0, + unchecked((uint)Callee), (uint)(Callee >> 32), 0x6000, 0); + UseIsolatedCallUnion(guest, false, false, [28, 60]); + guest.Programs.ReuseCallDispatch = true; + guest.Programs.SkipPendingPass = true; + guest.Programs.SkipPendingPassEarly = true; + var ready = new HashSet(); + guest.Programs.TryComputePipeline = (program, _, _) => ready.Contains(program.Id); + (ulong Handle, ShaderStageResources Stage) Resolve(uint count) + { + var cursor = 0u; + var program = guest.Programs.GetOrCompile(guest.Source(Caller, ShaderStage.Compute, + PipelineTestGuest.BufferDescriptor(Table, 16, count, 0)), PipelineTestGuest.ComputeOptions(32), + ref cursor, out var stage); + return (program.Id, stage); + } + ready.Add(Resolve(2).Handle); + Assert.Null(Resolve(2).Stage.CompileFallback); + guest.WriteWords(Table, unchecked((uint)Callee), (uint)(Callee >> 32), 0x4000, 0, + unchecked((uint)secondCallee), (uint)(secondCallee >> 32), 0x6000, 0); + var first = Resolve(2); + Assert.NotNull(first.Stage.CompileFallback); + Assert.Contains((Callee, 0x4000ul), first.Stage.CallRecords!); + guest.WriteWords(Table + 8, 0x5000, 0); + var second = Resolve(2); + Assert.NotNull(second.Stage.CompileFallback); + Assert.Contains((Callee, 0x5000ul), second.Stage.CallRecords!); + Assert.DoesNotContain((Callee, 0x4000ul), second.Stage.CallRecords!); + Assert.Contains((Callee, 0x4000ul), first.Stage.CallRecords!); + Assert.True(guest.Programs.CallDispatchReuses >= 2); + } + + [Fact] + public void ThePendingNewestProgramIsPolledWhileTheSameProgramsServe() + { + var (resolved, resolvedPolls, resolvedSkips) = Run(skip: false); + var (polled, polledPolls, polledSkips) = Run(skip: true); + + // 0: the first program compiles; 1: it is ready and serves; 2: new callee code links a newer program whose pipeline + // compiles, and the first serves as its fallback; 3: the newer one still compiles; 4: it is ready and serves. + Assert.Equal(5, resolved.Count); + Assert.Null(resolved[1].Fallback); + Assert.NotNull(resolved[2].Fallback); + Assert.Equal(resolved[1].Served, resolved[2].Served); + Assert.Equal("pipeline", resolved[2].Fallback!.Reason); + Assert.Equal(Served(resolved[2]), Served(resolved[3])); + Assert.Null(resolved[4].Fallback); + Assert.NotEqual(resolved[1].Served, resolved[4].Served); + + // The same programs serve, with the same fallbacks, in both modes. + Assert.Equal(resolved.Select(Served), polled.Select(Served)); + Assert.Equal(0, resolvedSkips); + Assert.Equal(1, polledSkips); + + // Dispatch 3 polls the newer program's compile once in both modes. Without the skip, the stage step polls with the + // stage resources it made; with the skip, the dispatch polls with the ones dispatch 2 made and makes none. With the + // skip, dispatch 4 polls twice: before its record ranges (the compile is ready, so it resolves on) and in the stage step. + var newer = resolved[4].Served; + var resolvedNewer = resolvedPolls.Where(poll => poll.Program == newer).ToArray(); + var polledNewer = polledPolls.Where(poll => poll.Program == newer).ToArray(); + Assert.Equal([2, 3, 4], resolvedNewer.Select(static poll => poll.Dispatch)); + Assert.Equal([2, 3, 4, 4], polledNewer.Select(static poll => poll.Dispatch)); + var resolvedAt3 = Assert.Single(resolvedNewer, static poll => poll.Dispatch == 3); + var polledAt3 = Assert.Single(polledNewer, static poll => poll.Dispatch == 3); + // Stage resources are a value; their snapshot is the instance one materialization made. + Assert.NotSame(Assert.Single(resolvedNewer, static poll => poll.Dispatch == 2).Stage.Resources, resolvedAt3.Stage.Resources); + Assert.Same(Assert.Single(polledNewer, static poll => poll.Dispatch == 2).Stage.Resources, polledAt3.Stage.Resources); + } + + // SHARPEMU_PENDING_PASS_EARLY: with one permutation, the one still compiling, the poll runs before the newest program's + // targets and materialization; the same programs and fallbacks serve, and the skipped dispatch makes no stage resources. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void TheEarlySkipServesTheSameProgramsAndMaterializesNothingForThePendingProgram(bool middle) + { + var (resolved, _, _) = Run(skip: false, middle: middle); + var (early, earlyPolls, earlySkips) = Run(skip: true, middle: middle, early: true); + + Assert.Equal(resolved.Select(Served), early.Select(Served)); + Assert.Equal(1, earlySkips); + Assert.Equal(1, _lastEarlySkips); + if (!middle) + { + var newer = resolved[4].Served; + var polled = earlyPolls.Where(poll => poll.Program == newer).ToArray(); + Assert.Equal([2, 3, 4, 4], polled.Select(static poll => poll.Dispatch)); + Assert.Same(Assert.Single(polled, static poll => poll.Dispatch == 2).Stage.Resources, + Assert.Single(polled, static poll => poll.Dispatch == 3).Stage.Resources); + } + } + + // The poll can promote an older compile that finished meanwhile: that program serves in both modes, not the + // fallback the caller had before the poll. + [Fact] + public void AMiddleCompileThatFinishesDuringThePollServesInBothModes() + { + var (resolved, _, resolvedSkips) = Run(skip: false, middle: true); + var (polled, _, polledSkips) = Run(skip: true, middle: true); + + // 0: the first program compiles; 1: it is ready and serves; 2: a second program compiles while the first serves; + // 3: a third (the newest) compiles too; 4: the second finished, so it serves while the newest still compiles. + Assert.Equal(5, resolved.Count); + Assert.Equal(resolved[1].Served, resolved[3].Served); + Assert.NotEqual(resolved[1].Served, resolved[4].Served); + Assert.Equal(2, resolved[3].Fallback!.RequestedGeneration - resolved[3].Fallback!.ServedGeneration); + Assert.Equal(1, resolved[4].Fallback!.RequestedGeneration - resolved[4].Fallback!.ServedGeneration); + Assert.Equal(resolved.Select(Served), polled.Select(Served)); + Assert.Equal(0, resolvedSkips); + Assert.Equal(1, polledSkips); + } + + // The shortcut follows the stage step's own selection: the first permutation whose push-data start and specialization + // match. Only when that is the pending one does it serve the fallback; a ready alternate, or none, takes the full path. + [Fact] + public void OnlyThePermutationTheStageStepWouldSelectCountsAsPending() + { + var plain = new ResourceSpecialization(); + var imaged = new ResourceSpecialization(); + imaged.Images.Add(new ImageSpecialization(ImageNumericClass.Float, ImageDimension.Dim2D, 1, 0, 0, uint.MaxValue, 0, 0, false)); + var other = new ResourceSpecialization(); + other.Images.Add(new ImageSpecialization(ImageNumericClass.Uint, ImageDimension.Dim2D, 1, 0, 0, uint.MaxValue, 0, 0, false)); + var first = Permutation(1, plain); + var second = Permutation(2, imaged); + List permutations = [first, second]; + + Assert.True(ShaderProgramCache.PendingPermutationServes(permutations, second.Handle, 0, imaged)); + // The current specialization selects the other permutation, which may be ready: the stage step decides. + Assert.False(ShaderProgramCache.PendingPermutationServes(permutations, second.Handle, 0, plain)); + // No permutation matches: the stage step compiles one. + Assert.False(ShaderProgramCache.PendingPermutationServes(permutations, second.Handle, 0, other)); + // The first match wins, as in the stage step's loop. + var duplicate = Permutation(3, imaged); + Assert.False(ShaderProgramCache.PendingPermutationServes([first, second, duplicate], duplicate.Handle, 0, imaged)); + Assert.True(ShaderProgramCache.Selects(second, 0, imaged)); + Assert.False(ShaderProgramCache.Selects(second, 0, plain)); + + // Push data: a permutation whose shader data (four dwords) starts at dword 0 serves only a dispatch whose cursor is 0; + // one compiled for a cursor of 8 serves only that cursor. + var atZero = Permutation(4, imaged, new BindingLayout { PushDataStartDword = 0, CallTargetCount = 2 }); + var atEight = Permutation(5, imaged, new BindingLayout { PushDataStartDword = 8, CallTargetCount = 2 }); + Assert.Equal(4u, atZero.Bindings.ShaderDataDwordCount); + Assert.True(ShaderProgramCache.Selects(atZero, 0, imaged)); + Assert.False(ShaderProgramCache.Selects(atZero, 8, imaged)); + Assert.False(ShaderProgramCache.Selects(atZero, 30, imaged)); + Assert.False(ShaderProgramCache.PendingPermutationServes([atZero], atZero.Handle, 8, imaged)); + Assert.True(ShaderProgramCache.PendingPermutationServes([atZero, atEight], atEight.Handle, 8, imaged)); + Assert.False(ShaderProgramCache.PendingPermutationServes([atZero, atEight], atEight.Handle, 0, imaged)); + } + + private static ProgramPermutation Permutation(ulong id, ResourceSpecialization specialization, BindingLayout? bindings = null) => new() + { + Specialization = specialization, + Program = new ShaderProgramInfo + { + Stage = ShaderStageKind.Compute, Hash = id, Images = [], Bindings = bindings ?? new BindingLayout(), + }, + Handle = new ShaderProgram(id), + }; + + // Generations count across caches, so a fallback is compared by its libraries, its reason and how many generations it lags. + private static (ulong, string?, string?, string?, long?) Served(Dispatch dispatch) => + (dispatch.Served, dispatch.Fallback?.RequestedLibrary, dispatch.Fallback?.ServedLibrary, dispatch.Fallback?.Reason, + dispatch.Fallback?.RequestedGeneration - dispatch.Fallback?.ServedGeneration); + + // Without middle: five dispatches; the second program becomes ready before the last. With middle: a third program links at + // dispatch 3, and the second (not the newest) becomes ready before dispatch 4. + private (List Dispatches, List Polls, long Skips) Run(bool skip, bool middle = false, bool early = false, + bool reuseDispatch = false) + { + using var fatal = new FatalScope(); + var guest = new PipelineTestGuest(CompileSpirv); + guest.Host.RuntimeCallRecordsSupported = true; + guest.RegisterProgram(Caller, Header, + [0xF4280400, 125u << 25, 0xBF8C0000, 0xBE8E0310, 0xBE8F0311, 0xBE900312, 0xBE910313, 0xBE8E210E, 0xBF810000]); + guest.WriteWords(Callee, 0xBF800000, 0xBE80200E); + const ulong argument = 0x3000; + guest.WriteWords(Table, unchecked((uint)Callee), (uint)(Callee >> 32), unchecked((uint)argument), (uint)(argument >> 32)); + UseIsolatedCallUnion(guest, skip, middle); + guest.Programs.SkipPendingPass = skip; + guest.Programs.SkipPendingPassEarly = early; + guest.Programs.ReuseCallDispatch = reuseDispatch; + + var dispatches = new List(); + var polls = new List(); + var ready = new HashSet(); + guest.Programs.TryComputePipeline = (program, stage, _) => + { + polls.Add(new Poll(dispatches.Count, program.Id, stage)); + return ready.Contains(program.Id); + }; + + dispatches.Add(Next(guest)); + ready.Add(dispatches[0].Served); + dispatches.Add(Next(guest)); + guest.WriteWords(Callee, 0xBF800001, 0xBE80200E); + dispatches.Add(Next(guest)); + var second = polls.First(poll => poll.Dispatch == 2 && poll.Program != dispatches[0].Served).Program; + if (middle) + { + guest.WriteWords(Callee, 0xBF800002, 0xBE80200E); + } + + dispatches.Add(Next(guest)); + ready.Add(second); + dispatches.Add(Next(guest)); + _lastEarlySkips = guest.Programs.PendingPassEarlySkips; + _lastCallDispatchReuses = guest.Programs.CallDispatchReuses; + return (dispatches, polls, guest.Programs.PendingPassSkips); + } + + private static Dispatch Next(PipelineTestGuest guest) + { + var cursor = 0u; + var program = guest.Programs.GetOrCompile(guest.Source(Caller, ShaderStage.Compute, PipelineTestGuest.BufferDescriptor(Table, 16, 1, 0)), + PipelineTestGuest.ComputeOptions(32), ref cursor, out var stage); + return new Dispatch(program.Id, stage.CompileFallback); + } + + // Runtime linking loads the callees kept for the caller before its first link; each run keeps them under this test's + // directory, so no run reads or writes the user's shader cache or another run's union. + private void UseIsolatedCallUnion(PipelineTestGuest guest, bool skip, bool middle, uint[]? callSites = null) + { + var path = Path.Combine(_directory, $"callees-{skip}-{middle}.bin"); + var decoded = ShaderFunctionReader.Read(Callee, guest.Host.TryReadGuestWord); + Assert.True(decoded.Complete, decoded.Error); + var source = guest.Source(Caller, ShaderStage.Compute, PipelineTestGuest.BufferDescriptor(Table, 16, 1, 0)); + var callee = new UnitedCallee(new ShaderCallTarget(Callee, 0, decoded.Program), + System.Security.Cryptography.SHA256.HashData(decoded.Bytes), decoded.Runs); + // The single-site caller's s_swappc is word 7 (pc 28); the record freshness test uses two sites. + new ShaderCallUnionStore(path).Save(ShaderStage.Compute, source.Hash, + (callSites ?? [28]).ToDictionary(static pc => pc, _ => new[] { callee })); + var field = typeof(ShaderProgramCache).GetField("_callUnionStore", + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); + Assert.NotNull(field); + field.SetValue(guest.Programs, new ShaderCallUnionStore(path)); + } + + private static byte[] CompileSpirv(ShaderCompileRequest request) + { + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + return shader.Spirv; + } + + public void Dispose() + { + if (Directory.Exists(_directory)) Directory.Delete(_directory, recursive: true); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PipelineTestSupport.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PipelineTestSupport.cs index e8ef2c81c..876cd627d 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PipelineTestSupport.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PipelineTestSupport.cs @@ -28,7 +28,7 @@ internal sealed class FakeCompiledShader(ShaderCompileRequest request, byte[]? s } // Counts modules and pipelines; every guest read comes straight from the fake memory. -internal sealed class FakePipelineHost(ICpuMemory memory) : IShaderPipelineHost +internal class FakePipelineHost(ICpuMemory memory) : IShaderPipelineHost { private ulong _nextHandle = 1; @@ -53,12 +53,18 @@ public uint[] NormalizeImageDescriptor(IShaderFrontend frontend, ReadOnlySpan 32; + public StableImageDescriptorLimits ComputeImageDescriptorLimits { get; set; } + + public StableImageDescriptorLimits GraphicsImageDescriptorLimits { get; set; } + public bool ComputeWave64Supported => true; public bool GraphicsSubgroupOperationsEnabled => true; public bool SharedInt64AtomicsEnabled => false; + public bool RuntimeCallRecordsSupported { get; set; } + public bool CallMarksSupported { get; set; } public long CallMarkSnapshots { get; set; } @@ -79,6 +85,10 @@ public uint[] NormalizeImageDescriptor(IShaderFrontend frontend, ReadOnlySpan RecordedVertexPrograms { get; } = new(); + + public void VertexProgramRecorded(ulong module, ulong prewarmIdentity) => RecordedVertexPrograms.Add((module, prewarmIdentity)); + public RenderHostLimits Limits => new(16384, 16384, 16384, 16384); public bool TryResolveColorOutput(uint dataFormat, uint numberType, uint componentSwap, out Gen5PixelOutputKind outputKind, out Gen5ColorComponentMapping componentMapping) @@ -186,6 +196,31 @@ public bool TryCreateComputePipeline(ComputePipelineDescription description, out handle = CreateComputePipeline(description); return true; } + + // How many requests for graphics pipelines report "still compiling" before one is handed over, and the description + // each request named. + public int PendingGraphicsCompiles { get; set; } + + public List GraphicsPipelineRequests { get; } = new(); + + public bool TryCreateGraphicsPipeline(GraphicsPipelineDescription description, out PipelineHandle handle) + { + GraphicsPipelineRequests.Add(description); + handle = default; + if (PendingGraphicsCompiles > 0) + { + PendingGraphicsCompiles--; + return false; + } + + handle = CreateGraphicsPipeline(description); + return true; + } + + // The descriptions a caller waited for, outside the pipeline cache's lock. + public List GraphicsPipelineWaits { get; } = new(); + + public void WaitForGraphicsPipeline(GraphicsPipelineDescription description) => GraphicsPipelineWaits.Add(description); } // Remembers every request; compiles nothing unless a module factory was given. diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PixelPrewarmTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PixelPrewarmTests.cs new file mode 100644 index 000000000..6799d65c6 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PixelPrewarmTests.cs @@ -0,0 +1,147 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using SharpEmu.Libs.Gpu.Images; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +// Pixel programs recorded in the prewarm list beside the compute ones, and translated again from the record. +public sealed class PixelPrewarmTests : IDisposable +{ + private const ulong CodeAddress = PipelineTestGuest.MemoryBase + 0x1_0000; + private const ulong HeaderAddress = PipelineTestGuest.MemoryBase + 0x8000; + private const ulong BufferAddress = PipelineTestGuest.MemoryBase + 0x4_0000; + + private readonly string _directory = Path.Combine(Path.GetTempPath(), "SharpEmuTests", Guid.NewGuid().ToString("N")); + + public void Dispose() + { + if (Directory.Exists(_directory)) + { + Directory.Delete(_directory, recursive: true); + } + } + + private ShaderPrewarmList Open() => ShaderPrewarmList.Open(_directory) ?? throw new InvalidOperationException("The list did not open."); + + private static byte[] Compile(ShaderCompileRequest request) + { + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + return shader.Spirv; + } + + private static StageCompileOptions PixelOptions(bool ieeeMode) => new() + { + PixelInfo = new PixelInputInfo { InputCount = 1, IeeeMode = ieeeMode }, + PixelOutputs = [new Gen5PixelOutputBinding(0, 0, Gen5PixelOutputKind.Float)], + PixelInputEnable = 0x2, + PixelInputAddress = 0x2, + }; + + [Fact] + public void APixelRecordRoundTripsWithEveryField() + { + var code = new ShaderCodeCapture + { + Hash = 0x1234_5678_9ABC_DEF0, CodeSize = 12, Address = CodeAddress, Generation = Generation.Gen5, + Ranges = [new CodeRange(CodeAddress, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])], + }; + var info = new PixelInputInfo + { + InputCount = 3, + SystemInputBase = 5, + CustomInterpolationMask = 0x6, + PerspectiveCenterRegister = 2, + InterpolatorSettings = Enumerable.Range(0, PixelInputInfo.InterpolatorCount).Select(index => (uint)(index * 7 + 1)).ToArray(), + TargetOutputModes = [1, 2, 3, 4, 5, 6, 7, 8], + TargetExportFormats = [8, 7, 6, 5, 4, 3, 2, 1], + TargetExportMappings = Enumerable.Range(0, PixelInputInfo.TargetCount).Select(index => new ColorComponentMap((byte)(0xE4 ^ index))).ToArray(), + IeeeMode = true, + ScratchDwords = 9, + PositionX = true, + PositionW = true, + FrontFace = true, + KillEnable = true, + DepthExportEnable = true, + SampleShading = true, + EarlyDepth = true, + ExecuteOnNoop = true, + }; + var record = new PixelPrewarmRecord + { + Hash = code.Hash, + CodeSize = code.CodeSize, + Address = code.Address, + UserDataBase = 4, + UserDataCount = 16, + PushDataCursor = 3, + Info = info, + Outputs = + [ + new Gen5PixelOutputBinding(0, 0, Gen5PixelOutputKind.Float), + new Gen5PixelOutputBinding(1, 2, Gen5PixelOutputKind.Uint, new Gen5ColorComponentMapping(0x1B)) + { + DualSourceAlpha = true, ExportTarget = 3, Index = 1, ExportFormat = Gen5PixelExportFormat.Uint16, + }, + ], + InputEnable = 0x22, + InputAddress = 0x23, + Specialization = new ResourceSpecialization { BaseBufferCount = 1, Buffers = [new BufferSpecialization(4, 0xFAC)] }, + }; + + using (var list = Open()) + { + list.RecordPixel(code, record); + list.RecordPixel(code, record); + } + + using var reloaded = Open(); + Assert.Equal(0, reloaded.LoadedComputeCount); + var (loaded, loadedCode, _) = Assert.IsType(Assert.Single(reloaded.LoadedGraphicsPrewarm())); + Assert.Equal(ShaderPrewarmList.Identity(record), ShaderPrewarmList.Identity(loaded)); + Assert.Equal(code.Ranges[0].Bytes, Assert.Single(loadedCode.Ranges).Bytes); + Assert.Equal(info.InterpolatorSettings, loaded.Info.InterpolatorSettings); + Assert.True(loaded.Info.IeeeMode && loaded.Info.ExecuteOnNoop && !loaded.Info.PositionY); + Assert.Equal(new uint[] { 0, 3 }, loaded.Outputs.Select(output => output.ExportTarget)); + Assert.Equal(Gen5PixelExportFormat.Uint16, loaded.Outputs[1].ExportFormat); + Assert.Equal((byte)0x1B, loaded.Outputs[1].ComponentMapping.Packed); + Assert.Equal(new BufferSpecialization(4, 0xFAC), Assert.Single(loaded.Specialization.Buffers)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ARecordedPixelProgramTranslatesToTheSameSpirvAfterReload(bool ieeeMode) + { + byte[] runtime; + IShaderPipelineHost host; + using (var list = Open()) + { + var guest = new PipelineTestGuest(Compile); + guest.Host.ShaderPrewarm = list; + guest.RegisterProgram(CodeAddress, HeaderAddress, PipelineTestGuest.FormatLoadProgram); + var userData = PipelineTestGuest.BufferDescriptor(BufferAddress, 4, 64, BufferDescriptorWords.Format32UInt); + var cursor = 0u; + guest.Programs.GetOrCompile(guest.Source(CodeAddress, ShaderStage.Pixel, userData), PixelOptions(ieeeMode), ref cursor, out _); + host = guest.Host; + runtime = Assert.Single(guest.Compiler.Shaders).Spirv; + } + + using var reloaded = Open(); + Assert.Equal(0, reloaded.LoadedComputeCount); + var (record, code, _) = Assert.IsType(Assert.Single(reloaded.LoadedGraphicsPrewarm())); + Assert.Equal(ieeeMode, record.Info.IeeeMode); + Assert.NotEmpty(record.Specialization.Buffers); + var compiler = new FakeShaderCompiler(Compile); + Assert.True(ShaderProgramCache.TryCompilePixelPrewarm(record, code, compiler, host, out var compiled, out var layout, out var error), error); + Assert.NotNull(layout); + Assert.Equal(runtime, Assert.IsType(compiled).Spirv); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ProgramInputDependenciesTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ProgramInputDependenciesTests.cs new file mode 100644 index 000000000..5b61ac15f --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ProgramInputDependenciesTests.cs @@ -0,0 +1,139 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.HLE; +using SharpEmu.Libs.Gpu.GpuCommands.Registers; +using SharpEmu.Libs.Gpu.Images; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Rendering.RenderExecutorFixtures; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +// Cross-draw reuse must prove more than a shader's addresses or its code identity. +[Collection(SchedulingStateCollection.Name)] +public sealed class ProgramInputDependenciesTests : IDisposable +{ + private const ulong MemoryBase = 0x1_0000_0000; + private const ulong Code = MemoryBase + 0x100; + private const ulong Semantics = MemoryBase + 0x200; + private const ulong UserBlock = MemoryBase + 0x300; + private const ulong DirectOffsets = MemoryBase + 0x400; + private readonly FatalScope _fatal = new(); + private readonly FakeCpuMemory _memory = new(MemoryBase, 0x1000); + private readonly CpuContext _context; + + public ProgramInputDependenciesTests() => _context = new CpuContext(_memory, Generation.Gen5); + public void Dispose() => _fatal.Dispose(); + + private static RegisteredShader Shader() => new(Code, MemoryBase, 16, 0, UserBlock, Semantics, 1, 0, 0); + + private PixelInputInfo ResolvePixel(RegisterBanks banks, RegisteredShader shader) + { + var mappings = new ColorComponentMap[PixelInputInfo.TargetCount]; + Array.Fill(mappings, ColorComponentMap.Identity); + return PixelStageInputResolver.Resolve(_context, shader, banks.Context.ShaderInterface, + new byte[PixelInputInfo.TargetCount], mappings, 1); + } + + private static uint[] StaticKey(PixelInputInfo info) + { + var key = new List(); + StageStaticKey.Build(info, key); + return key.ToArray(); + } + + private void Write32(ulong address, uint value) + { + Span bytes = stackalloc byte[4]; + BinaryPrimitives.WriteUInt32LittleEndian(bytes, value); + Assert.True(_memory.TryWrite(address, bytes)); + } + + private void Write16(ulong address, ushort value) + { + Span bytes = stackalloc byte[2]; + BinaryPrimitives.WriteUInt16LittleEndian(bytes, value); + Assert.True(_memory.TryWrite(address, bytes)); + } + + private ulong CodeIdentity(RegisteredShader shader) => + ShaderIdentity.Compute(_memory, shader.CodeAddress, shader.CodeRanges, "test"); + + [Theory] + [InlineData("interpolator")] + [InlineData("system-inputs")] + [InlineData("export-format")] + public void EqualShaderAddressesDoNotProveEqualPixelStaticKeys(string changedField) + { + var live = Banks(); + var before = live.Snapshot(); + var changed = live.ShaderInterfaceForWrite; + switch (changedField) + { + case "interpolator": + changed.PixelInterpolatorWritten = 1; + changed.PixelInterpolatorSettings[0] = 7; + break; + case "system-inputs": + changed.PixelInputEnable = changed.PixelInputAddress = 2; + break; + case "export-format": + changed.TargetOutputModes[0] = 2; + break; + default: + throw new ArgumentOutOfRangeException(nameof(changedField)); + } + var after = live.Snapshot(); + Assert.Equal(before.Shader.Vertex.ExportAddress, after.Shader.Vertex.ExportAddress); + Assert.Equal(before.Shader.Pixel.Address, after.Shader.Pixel.Address); + Assert.NotSame(before.Context.ShaderInterface, after.Context.ShaderInterface); + + var shader = Shader(); + var first = ResolvePixel(before, shader); + var second = ResolvePixel(after, shader); + Assert.False(StaticKey(first).SequenceEqual(StaticKey(second))); + } + + [Fact] + public void SameShaderAndCodeIdentityDoNotProveEqualPixelSemantics() + { + var banks = Banks(); + var shader = Shader(); + var identity = CodeIdentity(shader); + var before = ResolvePixel(banks, shader); + Write32(Semantics, 1u << 24); // Custom full-precision interpolation. + var after = ResolvePixel(banks, shader); + + Assert.Equal(identity, CodeIdentity(shader)); + Assert.Equal(0u, before.CustomInterpolationMask); + Assert.Equal(1u, after.CustomInterpolationMask); + Assert.False(StaticKey(before).SequenceEqual(StaticKey(after))); + } + + [Fact] + public void SameShaderAndCodeIdentityDoNotProveEqualVertexTableRegisters() + { + var shader = Shader(); + Write32(UserBlock, unchecked((uint)DirectOffsets)); + Write32(UserBlock + 4, (uint)(DirectOffsets >> 32)); + Write16(UserBlock + 0x2C, 11); + for (uint type = 0; type < 11; type++) Write16(DirectOffsets + type * 2, 0xFFFF); + Write16(DirectOffsets + 8 * 2, 10); + Write16(DirectOffsets + 10 * 2, 8); + Write32(Semantics, 1u << 16); + var identity = CodeIdentity(shader); + Assert.True(VertexInputResolver.TryReadTables(_context, shader, 32, out var before, out var firstError), firstError); + + Write16(DirectOffsets + 8 * 2, 12); + Assert.True(VertexInputResolver.TryReadTables(_context, shader, 32, out var after, out var secondError), secondError); + + Assert.Equal(identity, CodeIdentity(shader)); + Assert.Equal(10, before.VertexBufferRegister); + Assert.Equal(12, after.VertexBufferRegister); + Assert.Equal(before.InputSemantics, after.InputSemantics); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCallLibraryMemoTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCallLibraryMemoTests.cs new file mode 100644 index 000000000..bfa6c41d5 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCallLibraryMemoTests.cs @@ -0,0 +1,335 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +// Call-library reuse (ShaderCallLibraryMemo): every reused result equals what the original read derives from the same +// memory with the same function cache, and the counters show which reuse served it. +public sealed class ShaderCallLibraryMemoTests +{ + private const ulong Table = 0x1000; + private const int MaxCallees = 192; + + // A run-time-record caller: one site whose 16-byte records it selects by a dynamic offset. + private static Gen5ShaderProgram Caller() => Program( + Sop2(0, "SLshlB32", 20, Gen5Operand.Scalar(20), Operand(4)), + ScalarBufferLoad(4, 0, 16, 4, dynamicOffsetRegister: 20), + Vop1(12, "VMovB32", 111, Operand(0)), + new(16, Gen5ShaderEncoding.Sopp, "SWaitcnt", [0xBF8C0000], [], [], null), + MoveScalarRegister(20, 14, 16), MoveScalarRegister(24, 15, 17), + MoveScalarRegister(28, 16, 18), MoveScalarRegister(32, 17, 19), + Sop1(36, "SSwappcB64", 14, Gen5Operand.Scalar(14)), EndProgram(40)); + + private static MemoryAccessTable Access() + { + var access = new MemoryAccessTable(); + access.Add(new() { Pc = 4, Kind = MemoryResourceKind.ScalarBuffer, Resource = 0 }); + return access; + } + + private static ResourceSnapshot Snapshot(int records) => new() { Buffers = [[(uint)Table, 16u << 16, (uint)records, 0]] }; + + private sealed class Guest + { + // 0x200000: s_nop 0; s_setpc_b64 s[14:15]. 0x300000: another body. 0x400000: the code of 0x200000 at another address. + public readonly Dictionary Words = new() + { + [0x200000] = 0xBF800000, [0x200004] = 0xBE80200E, + [0x300000] = 0xBF800000, [0x300004] = 0xBF800000, [0x300008] = 0xBE80200E, + [0x400000] = 0xBF800000, [0x400004] = 0xBE80200E, + }; + + public void Records(ulong table, params (ulong Target, ulong Argument)[] records) + { + for (var index = 0; index < records.Length; index++) + { + var address = table + (ulong)index * 16; + Words[address] = (uint)records[index].Target; + Words[address + 4] = (uint)(records[index].Target >> 32); + Words[address + 8] = (uint)records[index].Argument; + Words[address + 12] = (uint)(records[index].Argument >> 32); + } + } + + public void Records(params (ulong Target, ulong Argument)[] records) => Records(Table, records); + + public bool Read(ulong address, out uint word) => Words.TryGetValue(address, out word); + } + + private sealed class Reader(int records, bool active = true) + { + public readonly Gen5ShaderProgram Caller = ShaderCallLibraryMemoTests.Caller(); + public readonly MemoryAccessTable Access = ShaderCallLibraryMemoTests.Access(); + public readonly ShaderFunctionCache Functions = new(null); + public readonly ShaderCallLibraryMemo Memo = new(active: active); + public readonly Guest Guest = new(); + public int Records = records; + + public ShaderCallLibrary Reuse() => Memo.Read(Caller, Access, Snapshot(Records), Guest.Read, Functions, runtimeArguments: true, + userDataBase: 0, readBytes: null); + + // The original read of the same memory with the same function cache. + public ShaderCallLibrary Original() => ShaderCallLibrary.Read(Caller, Access, Snapshot(Records), Guest.Read, Functions, + runtimeArguments: true); + } + + private static void SameAsOriginal(Reader reader, ShaderCallLibrary reused) => + Assert.Null(ShaderCallLibraryMemo.Difference(reused, reader.Original())); + + // The same tables again: the tables are read again and the topology of the first read serves. + [Fact] + public void RepeatedTablesReuseTheTopology() + { + var reader = new Reader(2); + reader.Guest.Records((0x200000, 0x5000), (0x300000, 0x5100)); + var first = reader.Reuse(); + var second = reader.Reuse(); + Assert.Equal(1, reader.Memo.Counted("TopologyMiss")); + Assert.Equal(1, reader.Memo.Counted("TopologyHit")); + Assert.Same(first.Topology, second.Topology); + Assert.Equal(first.Records, second.Records); + SameAsOriginal(reader, second); + } + + // Changed arguments in another order: the records are fresh, while the sites, slots and identity come from the topology + // of the first read. + [Fact] + public void ReorderedRecordsWithChangedArgumentsReuseTheTopologyWithFreshRecords() + { + var reader = new Reader(3); + reader.Guest.Records((0x200000, 0x5000), (0x300000, 0x5100), (0x200000, 0x5200)); + var first = reader.Reuse(); + reader.Guest.Records((0x300000, 0x6100), (0x200000, 0x6000), (0x200000, 0x6200)); + var second = reader.Reuse(); + Assert.Equal(1, reader.Memo.Counted("TopologyHit")); + Assert.Equal(first.LayoutIdentity, second.LayoutIdentity); + Assert.Equal(new (ulong, ulong)[] { (0x300000, 0x6100), (0x200000, 0x6000), (0x200000, 0x6200) }, second.Records); + SameAsOriginal(reader, second); + } + + // A duplicated record counts once, in its first position; a record whose target is null is not collected (the same + // callees: the topology serves); a table with fewer records naming fewer callees is another topology. + [Fact] + public void DuplicatedAndRemovedRecordsKeepTheOriginalCollection() + { + var reader = new Reader(3); + reader.Guest.Records((0x200000, 0x5000), (0x200000, 0x5000), (0x300000, 0x5100)); + var duplicated = reader.Reuse(); + Assert.Equal(new (ulong, ulong)[] { (0x200000, 0x5000), (0x300000, 0x5100) }, duplicated.Records); + SameAsOriginal(reader, duplicated); + + reader.Guest.Records((0x200000, 0x5000), (0, 0), (0x300000, 0x5100)); + var removed = reader.Reuse(); + Assert.Equal(new (ulong, ulong)[] { (0x200000, 0x5000), (0x300000, 0x5100) }, removed.Records); + SameAsOriginal(reader, removed); + + reader.Records = 2; + var shorter = reader.Reuse(); + Assert.Equal(new (ulong, ulong)[] { (0x200000, 0x5000) }, shorter.Records); + SameAsOriginal(reader, shorter); + Assert.Equal(1, reader.Memo.Counted("TopologyHit")); + Assert.Equal(2, reader.Memo.Counted("TopologyMiss")); + } + + // New code at an address the library names is a new function-cache result: the topology is not reused, and the site + // links the new program. + [Fact] + public void ChangedCodeAtAReusedAddressIsNotReused() + { + var reader = new Reader(2); + reader.Guest.Records((0x200000, 0x5000), (0x300000, 0x5100)); + var first = reader.Reuse(); + reader.Guest.Words[0x200000] = 0xBF800001; + var second = reader.Reuse(); + Assert.Equal(0, reader.Memo.Counted("TopologyHit")); + Assert.Equal(2, reader.Memo.Counted("TopologyMiss")); + Assert.NotEqual(first.LayoutIdentity, second.LayoutIdentity); + SameAsOriginal(reader, second); + } + + // The same code at another address is another topology (the slots name addresses). + [Fact] + public void ACalleeAtAnotherAddressIsAnotherTopology() + { + var reader = new Reader(2); + reader.Guest.Records((0x200000, 0x5000), (0x300000, 0x5100)); + reader.Reuse(); + reader.Guest.Records((0x400000, 0x5000), (0x300000, 0x5100)); + var relocated = reader.Reuse(); + Assert.Equal(0, reader.Memo.Counted("TopologyHit")); + Assert.Contains(relocated.Calls[0].Targets, target => target.Address == 0x400000); + SameAsOriginal(reader, relocated); + } + + // A record whose function cannot be read is left out; the same table again reuses the topology. + [Fact] + public void AnUnreadableTargetIsLeftOutAndTheTopologyIsReused() + { + var reader = new Reader(2); + reader.Guest.Records((0x200000, 0x5000), (0x900000, 0x5100)); + var first = reader.Reuse(); + Assert.Equal(new (ulong, ulong)[] { (0x200000, 0x5000) }, first.Records); + SameAsOriginal(reader, first); + var again = reader.Reuse(); + Assert.Equal(1, reader.Memo.Counted("TopologyHit")); + SameAsOriginal(reader, again); + } + + // A table the host cannot read in full is refused as the original read refuses it, with no topology step; once + // readable again, the topology serves. + [Theory] + [InlineData(0ul)] + [InlineData(4ul)] + [InlineData(16ul)] + [InlineData(28ul)] + public void ATableThatBecomesUnreadableKeepsTheOriginalRefusal(ulong missingOffset) + { + var reader = new Reader(2); + reader.Guest.Records((0x200000, 0x5000), (0x300000, 0x5100)); + reader.Reuse(); + reader.Guest.Words.Remove(Table + missingOffset); + + var original = Assert.Throws(() => reader.Original()); + var reused = Assert.Throws(() => reader.Reuse()); + Assert.Equal(original.Message, reused.Message); + Assert.Equal(0, reader.Memo.Counted("TopologyHit")); + Assert.Equal(1, reader.Memo.Counted("TopologyMiss")); + + reader.Guest.Records((0x200000, 0x5000), (0x300000, 0x5100)); + var restored = reader.Reuse(); + Assert.Equal(1, reader.Memo.Counted("TopologyHit")); + SameAsOriginal(reader, restored); + } + + // Two sites, each selecting its records from its own table: a changed first table and a hole in the second is refused + // as the original read refuses it; with the hole restored both tables are read in their order and the topology serves. + [Fact] + public void ASecondTableWithAHoleKeepsTheOriginalRefusal() + { + const ulong second = 0x2000; + var caller = Program( + Sop2(0, "SLshlB32", 20, Gen5Operand.Scalar(20), Operand(4)), + ScalarBufferLoad(4, 0, 16, 4, dynamicOffsetRegister: 20), + Vop1(12, "VMovB32", 111, Operand(0)), + new(16, Gen5ShaderEncoding.Sopp, "SWaitcnt", [0xBF8C0000], [], [], null), + MoveScalarRegister(20, 14, 16), MoveScalarRegister(24, 15, 17), + MoveScalarRegister(28, 16, 18), MoveScalarRegister(32, 17, 19), + Sop1(36, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + Sop2(40, "SLshlB32", 21, Gen5Operand.Scalar(21), Operand(4)), + ScalarBufferLoad(44, 4, 16, 4, dynamicOffsetRegister: 21), + new(52, Gen5ShaderEncoding.Sopp, "SWaitcnt", [0xBF8C0000], [], [], null), + MoveScalarRegister(56, 14, 16), MoveScalarRegister(60, 15, 17), + MoveScalarRegister(64, 16, 18), MoveScalarRegister(68, 17, 19), + Sop1(72, "SSwappcB64", 14, Gen5Operand.Scalar(14)), EndProgram(76)); + var access = new MemoryAccessTable(); + access.Add(new() { Pc = 4, Kind = MemoryResourceKind.ScalarBuffer, Resource = 0 }); + access.Add(new() { Pc = 44, Kind = MemoryResourceKind.ScalarBuffer, Resource = 1 }); + var snapshot = new ResourceSnapshot { Buffers = [[(uint)Table, 16u << 16, 2, 0], [(uint)second, 16u << 16, 2, 0]] }; + var guest = new Guest(); + var functions = new ShaderFunctionCache(null); + var memo = new ShaderCallLibraryMemo(active: true); + ShaderCallLibrary Reuse() => memo.Read(caller, access, snapshot, guest.Read, functions, runtimeArguments: true, userDataBase: 0, + readBytes: null); + ShaderCallLibrary Original() => ShaderCallLibrary.Read(caller, access, snapshot, guest.Read, functions, runtimeArguments: true); + + guest.Records(Table, (0x200000, 0x5000), (0x300000, 0x5100)); + guest.Records(second, (0x300000, 0x7000), (0x200000, 0x7100)); + var first = Reuse(); + Assert.Equal(2, first.Calls.Count); + Assert.Null(ShaderCallLibraryMemo.Difference(first, Original())); + + guest.Records(Table, (0x200000, 0x6000), (0x300000, 0x6100)); + guest.Words.Remove(second + 20); + var original = Assert.Throws(Original); + var reused = Assert.Throws(Reuse); + Assert.Equal(original.Message, reused.Message); + Assert.Equal(0, memo.Counted("TopologyHit")); + + guest.Records(second, (0x300000, 0x7000), (0x200000, 0x7200)); + var restored = Reuse(); + Assert.Equal(1, memo.Counted("TopologyHit")); + Assert.Null(ShaderCallLibraryMemo.Difference(restored, Original())); + Assert.Contains((0x200000ul, 0x7200ul), restored.Records); + } + + // Unite keeps a call that changed nothing by the input's topology and the union's version: a later read with other + // records reuses it with its own records, and the union stays as the original call leaves it. + [Fact] + public void UniteAndSiteCalleesAreReusedWithTheCurrentRecords() + { + var reader = new Reader(2); + var union = new Dictionary>(); + reader.Guest.Records((0x200000, 0x5000), (0x300000, 0x5100)); + var first = reader.Reuse(); + reader.Memo.Unite(first, reader.Caller.Address, union, MaxCallees); + Assert.Equal(1, reader.Memo.Counted("UniteChanged")); + var united = reader.Memo.Unite(first, reader.Caller.Address, union, MaxCallees); + Assert.Equal(0, reader.Memo.Counted("UniteHit")); + + reader.Guest.Records((0x300000, 0x6100), (0x200000, 0x6000)); + var second = reader.Reuse(); + var reused = reader.Memo.Unite(second, reader.Caller.Address, union, MaxCallees); + Assert.Equal(1, reader.Memo.Counted("UniteHit")); + var copy = union.ToDictionary(static site => site.Key, static site => new Dictionary(site.Value)); + var direct = second.Unite(reader.Caller.Address, copy, MaxCallees, out var changed); + Assert.False(changed); + Assert.Null(ShaderCallLibraryMemo.Difference(reused, direct)); + Assert.Equal(second.Records, reused.Records); + + var chosen = union.ToDictionary(static site => site.Key, static site => site.Value); + var firstChoice = reader.Memo.WithSiteCallees(united, reader.Caller.Address, chosen); + Assert.Null(ShaderCallLibraryMemo.Difference(firstChoice, united.WithSiteCallees(reader.Caller.Address, chosen))); + var reusedChoice = reader.Memo.WithSiteCallees(reused, reader.Caller.Address, chosen); + Assert.Equal(1, reader.Memo.Counted("SitesHit")); + Assert.Null(ShaderCallLibraryMemo.Difference(reusedChoice, reused.WithSiteCallees(reader.Caller.Address, chosen))); + } + + // With reuse off, a read is the original read: counted as Off and without a topology token. + [Fact] + public void AnInactiveMemoReadsAsTheOriginal() + { + var reader = new Reader(2, active: false); + reader.Guest.Records((0x200000, 0x5000), (0x300000, 0x5100)); + var read = reader.Reuse(); + Assert.Null(read.Topology); + Assert.Equal(1, reader.Memo.Counted("Off")); + Assert.Equal(0, reader.Memo.Counted("TopologyMiss")); + SameAsOriginal(reader, read); + } + + // An un-tokened library (the original read's) must invalidate a previously kept Unite result. + [Fact] + public void AnUntokenedUnionChangeInvalidatesAnEarlierKeptResult() + { + var reader = new Reader(2); + var union = new Dictionary>(); + reader.Guest.Records((0x200000, 0x5000), (0x300000, 0x5100)); + var first = reader.Reuse(); + reader.Memo.Unite(first, reader.Caller.Address, union, MaxCallees); + reader.Memo.Unite(first, reader.Caller.Address, union, MaxCallees); + + reader.Guest.Records((0x400000, 0x6000), (0x300000, 0x6100)); + var untokened = reader.Original(); + Assert.Null(untokened.Topology); + reader.Memo.Unite(untokened, reader.Caller.Address, union, MaxCallees); + Assert.Equal(1, reader.Memo.Counted("UniteUntokened")); + Assert.Contains(0x400000ul, Assert.Single(union).Value.Keys); + Assert.DoesNotContain(0x200000ul, Assert.Single(union).Value.Keys); + + reader.Guest.Records((0x200000, 0x5000), (0x300000, 0x5100)); + var current = reader.Reuse(); + var expectedUnion = union.ToDictionary(static site => site.Key, + static site => new Dictionary(site.Value)); + var expected = current.Unite(reader.Caller.Address, expectedUnion, MaxCallees); + var actual = reader.Memo.Unite(current, reader.Caller.Address, union, MaxCallees); + Assert.Equal(0, reader.Memo.Counted("UniteHit")); + Assert.Null(ShaderCallLibraryMemo.Difference(actual, expected)); + Assert.Equal(Assert.Single(expectedUnion).Value.Keys.Order(), Assert.Single(union).Value.Keys.Order()); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCallLibraryTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCallLibraryTests.cs index f614a3a10..ae440f87e 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCallLibraryTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCallLibraryTests.cs @@ -1,6 +1,7 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using System.Buffers.Binary; using SharpEmu.Libs.Gpu.Pipelines; using SharpEmu.ShaderCompiler; using SharpEmu.ShaderCompiler.Resources; @@ -109,6 +110,252 @@ ShaderCallLibrary Read() => ShaderCallLibrary.Read(caller, memory, snapshot, Assert.All(targets, target => Assert.Same(targets[0].Program, target.Program)); } + // A ray tracer's hit table reserves far more records than one frame fills: 360,000 records of 16 bytes, copied at once. + // Records past the filled ones can name functions the game has since unloaded. With run-time arguments such a record is + // left out and the tables' other callees still link; a table past 16 MiB is refused. + [Fact] + public void RuntimeArguments_ReadALargeHitTableAndLeaveOutUnreadableFunctions() + { + const int Records = 360000; + const ulong TableAddress = 0x10_0000_0000; + var caller = Program( + Sop2(0, "SLshlB32", 20, Gen5Operand.Scalar(20), Operand(4)), + ScalarBufferLoad(4, 0, 16, 4, dynamicOffsetRegister: 20), + Vop1(12, "VMovB32", 111, Operand(0)), + new(16, Gen5ShaderEncoding.Sopp, "SWaitcnt", [0xBF8C0000], [], [], null), + MoveScalarRegister(20, 14, 16), MoveScalarRegister(24, 15, 17), + MoveScalarRegister(28, 16, 18), MoveScalarRegister(32, 17, 19), + Sop1(36, "SSwappcB64", 14, Gen5Operand.Scalar(14)), EndProgram(40)); + var memory = new MemoryAccessTable(); + memory.Add(new() { Pc = 4, Kind = MemoryResourceKind.ScalarBuffer, Resource = 0 }); + ResourceSnapshot Snapshot(uint records) => + new() { Buffers = [[unchecked((uint)TableAddress), (uint)(TableAddress >> 32) | (16u << 16), records, 0]] }; + var table = new byte[Records * 16]; + void Record(int index, ulong target, ulong argument) + { + BinaryPrimitives.WriteUInt64LittleEndian(table.AsSpan(index * 16), target); + BinaryPrimitives.WriteUInt64LittleEndian(table.AsSpan(index * 16 + 8), argument); + } + + Record(0, 0x200000, 0x5000); + Record(1, 0x300000, 0x5100); + Record(4095, 0x200000, 0x5200); + Record(Records - 1, 0x900000, 0x6000); + var code = new Dictionary + { + [0x200000] = 0xBF800000, [0x200004] = 0xBE80200E, + [0x300000] = 0xBF800000, [0x300004] = 0xBF800000, [0x300008] = 0xBE80200E, + }; + var tableWordReads = 0; + bool ReadWord(ulong address, out uint word) + { + if (address >= TableAddress && address - TableAddress < (ulong)table.Length) + { + tableWordReads++; + word = BinaryPrimitives.ReadUInt32LittleEndian(table.AsSpan((int)(address - TableAddress))); + return true; + } + + return code.TryGetValue(address, out word); + } + + bool ReadBytes(ulong address, Span destination, bool clean) + { + if (address < TableAddress || address - TableAddress + (ulong)destination.Length > (ulong)table.Length) return false; + table.AsSpan((int)(address - TableAddress), destination.Length).CopyTo(destination); + return true; + } + + var library = ShaderCallLibrary.Read(caller, memory, Snapshot(Records), ReadWord, runtimeArguments: true, readBytes: ReadBytes); + Assert.Equal(0, tableWordReads); + var site = Assert.Single(library.Calls); + Assert.Equal(new ulong[] { 0x200000, 0x300000 }, site.Targets.Select(static target => target.Address).Order()); + Assert.Equal(new (ulong, ulong)[] { (0x200000, 0x5000), (0x200000, 0x5200), (0x300000, 0x5100) }, + library.Records.Select(static record => (record.Target, record.Argument)).Order()); + + // A copy per record reads tables of up to 64 KiB; past 16 MiB a table is refused in either mode. + Assert.Throws(() => + ShaderCallLibrary.Read(caller, memory, Snapshot(Records), ReadWord, readBytes: ReadBytes)); + Assert.Throws(() => + ShaderCallLibrary.Read(caller, memory, Snapshot((16u << 20) / 16 + 1), ReadWord, runtimeArguments: true, readBytes: ReadBytes)); + } + + // A callee the linker cannot copy (here one that calls another function) is left out of a run-time-argument program at + // every site, and the tables' other callees still link; a copy per record has no such fallback. + [Fact] + public void RuntimeArguments_LinkLeavesOutACalleeTheLinkerCannotCopy() + { + var caller = Program( + Sop2(0, "SLshlB32", 20, Gen5Operand.Scalar(20), Operand(4)), + ScalarBufferLoad(4, 0, 16, 4, dynamicOffsetRegister: 20), + Vop1(12, "VMovB32", 111, Operand(0)), + new(16, Gen5ShaderEncoding.Sopp, "SWaitcnt", [0xBF8C0000], [], [], null), + MoveScalarRegister(20, 14, 16), MoveScalarRegister(24, 15, 17), + MoveScalarRegister(28, 16, 18), MoveScalarRegister(32, 17, 19), + Sop1(36, "SSwappcB64", 14, Gen5Operand.Scalar(14)), EndProgram(40)); + var memory = new MemoryAccessTable(); + memory.Add(new() { Pc = 4, Kind = MemoryResourceKind.ScalarBuffer, Resource = 0 }); + var snapshot = new ResourceSnapshot { Buffers = [[0x1000, 16u << 16, 3, 0]] }; + var words = new Dictionary + { + // 0x200000: s_nop 0; s_setpc_b64 s[14:15]. 0x300000: s_swappc_b64 s[16:17], s[18:19] before its return. + [0x200000] = 0xBF800000, [0x200004] = 0xBE80200E, + [0x300000] = 0xBE902112, [0x300004] = 0xBE80200E, + }; + (ulong Target, ulong Argument)[] records = [(0x200000, 0x5000), (0x300000, 0x5100), (0x200000, 0x5200)]; + for (var record = 0; record < records.Length; record++) + { + var address = 0x1000ul + (ulong)record * 16; + words[address] = (uint)records[record].Target; + words[address + 4] = 0; + words[address + 8] = (uint)records[record].Argument; + words[address + 12] = 0; + } + + var library = ShaderCallLibrary.Read(caller, memory, snapshot, (ulong address, out uint word) => words.TryGetValue(address, out word), + runtimeArguments: true); + var leftOut = new List(); + var linked = ShaderCallLibrary.LinkLeavingOutUnlinkable(caller, ref library, leftOut.Add); + Assert.Equal(0x300000ul, Assert.Single(leftOut).Target.Address); + Assert.Equal([0x200000ul], Gen5ShaderCallLinker.CallTargets(linked)); + Assert.Equal([0x200000ul], Assert.Single(library.Calls).Targets.Select(static target => target.Address)); + Assert.Throws(() => Gen5ShaderCallLinker.Link(caller, + ShaderCallLibrary.Read(caller, memory, snapshot, (ulong address, out uint word) => words.TryGetValue(address, out word)).Calls)); + } + + // A record buffer is at most 4 GiB and inside the address space the device-address cache maps. A record's buffer + // field can hold material constants instead (0.015f = 0x3C75C28F), which describe a buffer about 16 TiB long. + [Theory] + [InlineData(0x10A013F510ul, 0x1000ul, true)] + [InlineData(0x3C75C28Ful, 0xFC0430A3D71ul, false)] + [InlineData(0x1000ul, (1ul << 32) + 1, false)] + [InlineData((1ul << 40) - 0x1000, 0x1000ul, true)] + [InlineData((1ul << 40) - 0x1000, 0x2000ul, false)] + [InlineData(1ul << 44, 0x10ul, false)] + public void RecordBuffers_StayInsideTheDeviceAddressSpace(ulong address, ulong size, bool describes) => + Assert.Equal(describes, ShaderProgramCache.DescribesRecordBuffer(address, size)); + + // A buffer is made resident. Words that describe no buffer (hit materials can hold text and floats there) are not: + // a read-only buffer keeps its record, whose call runs; a written one leaves the record out. + [Theory] + [InlineData(0x10A013F510ul, 0x1000ul, false, (int)ShaderProgramCache.RecordBuffer.Resident)] + [InlineData(0x10A013F510ul, 0x1000ul, true, (int)ShaderProgramCache.RecordBuffer.Resident)] + [InlineData(0x2F7372657463ul, 0x110B21D0AEA2ul, false, (int)ShaderProgramCache.RecordBuffer.NotResident)] + [InlineData(0x2F7372657463ul, 0x110B21D0AEA2ul, true, (int)ShaderProgramCache.RecordBuffer.LeaveRecordOut)] + [InlineData(0ul, 0x1000ul, true, (int)ShaderProgramCache.RecordBuffer.NotResident)] + [InlineData(0x10A013F510ul, 0ul, true, (int)ShaderProgramCache.RecordBuffer.NotResident)] + public void RecordBuffers_ReadOnlyKeepTheRecordAndWrittenLeaveItOut(ulong address, ulong size, bool written, int expected) => + Assert.Equal((ShaderProgramCache.RecordBuffer)expected, ShaderProgramCache.ClassifyRecordBuffer(address, size, written)); + + // A caller may pass its function pointer and argument in user data: the call registers are copied from user-data + // registers nothing wrote before, and the target and argument come from the dispatch's user data. Another argument + // is another library, but the same layout, so it links to the same program. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void UserDataFunctionPointersLink(bool userDataOverwritten) + { + var caller = Program( + userDataOverwritten ? MoveScalarRegister(0, 2, 40) : Vop1(0, "VMovB32", 1, Operand(0)), + MoveScalarRegister(4, 14, 0), MoveScalarRegister(8, 15, 1), + MoveScalarRegister(12, 16, 2), MoveScalarRegister(16, 17, 3), + Vop1(20, "VMovB32", 5, Operand(0)), + Sop1(24, "SSwappcB64", 14, Gen5Operand.Scalar(14)), EndProgram(28)); + var snapshot = new ResourceSnapshot { UserData = [0x200000, 0x11, 0x5000, 0x12] }; + var words = new Dictionary { [0x11_0020_0000] = 0xBF800000, [0x11_0020_0004] = 0xBE80200E }; + ShaderCallLibrary Read() => ShaderCallLibrary.Read(caller, new MemoryAccessTable(), snapshot, + (ulong address, out uint word) => words.TryGetValue(address, out word)); + if (userDataOverwritten) + { + Assert.Throws(Read); + return; + } + + var call = Assert.Single(Read().Calls); + Assert.Equal((14u, 16u), (call.AddressRegister, call.ArgumentRegister)); + var target = Assert.Single(call.Targets); + Assert.Equal((0x11_0020_0000ul, 0x12_0000_5000ul), (target.Address, target.Argument)); + Assert.Equal("SSetpcB64", target.Program.Instructions[^1].Opcode); + var other = ShaderCallLibrary.Read(caller, new MemoryAccessTable(), new ResourceSnapshot { UserData = [0x200000, 0x11, 0x6000, 0x12] }, + (ulong address, out uint word) => words.TryGetValue(address, out word)); + Assert.NotEqual(Read().Identity, other.Identity); + Assert.Equal(Read().LayoutIdentity, other.LayoutIdentity); + } + + // The call registers may reach user data through copies: the caller saves the argument pair at entry, overwrites + // the call registers with another call, and copies the second target and the saved pair back for this call. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void UserDataFunctionPointersLinkThroughCopies(bool savedPairOverwritten) + { + var caller = Program( + Sop1(0, "SMovB64", 84, Gen5Operand.Scalar(14)), + savedPairOverwritten ? Sop2(4, "SAddU32", 85, Gen5Operand.Scalar(85), Gen5Operand.Scalar(0)) : Vop1(4, "VMovB32", 1, Operand(0)), + MoveScalarRegister(8, 14, 8), MoveScalarRegister(12, 15, 9), MoveScalarRegister(16, 16, 10), MoveScalarRegister(20, 17, 11), + Sop1(24, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + MoveScalarRegister(28, 14, 12), MoveScalarRegister(32, 15, 13), MoveScalarRegister(36, 16, 84), MoveScalarRegister(40, 17, 85), + Sop1(44, "SSwappcB64", 14, Gen5Operand.Scalar(14)), EndProgram(48)); + var snapshot = new ResourceSnapshot + { + UserData = [0, 0, 0, 0, 0, 0, 0, 0, 0x200000, 0x11, 0x5000, 0x12, 0x200100, 0x11, 0x6000, 0x12], + }; + var words = new Dictionary + { + [0x11_0020_0000] = 0xBF800000, [0x11_0020_0004] = 0xBE80200E, + [0x11_0020_0100] = 0xBF800000, [0x11_0020_0104] = 0xBE80200E, + }; + ShaderCallLibrary Read() => ShaderCallLibrary.Read(caller, new MemoryAccessTable(), snapshot, + (ulong address, out uint word) => words.TryGetValue(address, out word)); + if (savedPairOverwritten) + { + Assert.Throws(Read); + return; + } + + var calls = Read().Calls; + Assert.Equal(2, calls.Count); + var first = Assert.Single(calls[0].Targets); + Assert.Equal((0x11_0020_0000ul, 0x12_0000_5000ul), (first.Address, first.Argument)); + var second = Assert.Single(calls[1].Targets); + Assert.Equal((0x11_0020_0100ul, 0x12_0000_6000ul), (second.Address, second.Argument)); + } + + // A caller's call sites are planned once from its code, and each read takes its dispatch's user data and address: a + // copy at another address returns to its own address, and a dispatch whose user data cannot hold both pairs is + // planned again and refused. + [Fact] + public void CallSitePlansReadEachDispatchsUserDataAndAddress() + { + var caller = Program( + Vop1(0, "VMovB32", 1, Operand(0)), + MoveScalarRegister(4, 14, 0), MoveScalarRegister(8, 15, 1), + MoveScalarRegister(12, 16, 2), MoveScalarRegister(16, 17, 3), + Vop1(20, "VMovB32", 5, Operand(0)), + Sop1(24, "SSwappcB64", 14, Gen5Operand.Scalar(14)), EndProgram(28)); + var words = new Dictionary + { + [0x11_0020_0000] = 0xBF800000, [0x11_0020_0004] = 0xBE80200E, + [0x11_0020_0100] = 0xBF800000, [0x11_0020_0104] = 0xBE80200E, + }; + ShaderCallSite Read(Gen5ShaderProgram program, uint[] userData) => Assert.Single(ShaderCallLibrary.Read(program, + new MemoryAccessTable(), new ResourceSnapshot { UserData = userData }, + (ulong address, out uint word) => words.TryGetValue(address, out word)).Calls); + + var first = Assert.Single(Read(caller, [0x200000, 0x11, 0x5000, 0x12]).Targets); + Assert.Equal((0x11_0020_0000ul, 0x12_0000_5000ul), (first.Address, first.Argument)); + var second = Assert.Single(Read(caller, [0x200100, 0x11, 0x6000, 0x12]).Targets); + Assert.Equal((0x11_0020_0100ul, 0x12_0000_6000ul), (second.Address, second.Argument)); + + var moved = caller with { Address = caller.Address + 0x1000 }; + Assert.Equal(Read(caller, [0x200000, 0x11, 0x5000, 0x12]).ReturnAddress + 0x1000, + Read(moved, [0x200000, 0x11, 0x5000, 0x12]).ReturnAddress); + + Assert.Throws(() => Read(caller, [0x200000, 0x11])); + Assert.Throws(() => Read(caller, [0x200000, 0x11])); + Assert.Single(Read(caller, [0x200000, 0x11, 0x5000, 0x12]).Targets); + } + // A site linked with run-time records holds each callee once, so its table may hold more records than a site linked // per record. [Theory] diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCallSiteCacheRegressionTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCallSiteCacheRegressionTests.cs new file mode 100644 index 000000000..e4f01803d --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCallSiteCacheRegressionTests.cs @@ -0,0 +1,155 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +public sealed class ShaderCallSiteCacheRegressionTests +{ + private static Gen5ShaderProgram UserDataCaller() => Program( + MoveScalarRegister(0, 14, 8), MoveScalarRegister(4, 15, 9), + MoveScalarRegister(8, 16, 10), MoveScalarRegister(12, 17, 11), + Sop1(16, "SSwappcB64", 14, Gen5Operand.Scalar(14)), EndProgram(20)); + + [Fact] + public void CachedSites_ReadCurrentArgumentsAndCalleeCode() + { + var caller = UserDataCaller(); + var words = new Dictionary + { + [0x2000] = 0xBF800000, [0x2004] = 0xBE80200E, + [0x4000] = 0xBF800000, [0x4004] = 0xBE80200E, + }; + var functions = new ShaderFunctionCache(null); + ShaderCallLibrary Read(uint target, uint argument) => ShaderCallLibrary.Read( + caller, new MemoryAccessTable(), new ResourceSnapshot { UserData = [target, 0, argument, 0] }, + (ulong address, out uint word) => words.TryGetValue(address, out word), functions, + runtimeArguments: true, userDataBase: 8); + + var first = Read(0x2000, 0x3000); + var changedArgument = Read(0x2000, 0x5000); + Assert.Equal(first.LayoutIdentity, changedArgument.LayoutIdentity); + Assert.Equal((0x2000ul, 0x5000ul), Assert.Single(changedArgument.Records)); + words[0x2000] = 0xBF800001; + var changedCode = Read(0x2000, 0x5000); + Assert.False(first.CurrentCodeHashes[0x2000].SequenceEqual(changedCode.CurrentCodeHashes[0x2000])); + Assert.NotEqual(first.LayoutIdentity, changedCode.LayoutIdentity); + Assert.Equal((0x4000ul, 0x6000ul), Assert.Single(Read(0x4000, 0x6000).Records)); + } + + [Fact] + public void CachedSites_RecheckUserDataBaseWithTheSameCount() + { + var caller = UserDataCaller(); + ShaderCallLibrary Read(uint first, uint[] data) => ShaderCallLibrary.Read(caller, new MemoryAccessTable(), + new ResourceSnapshot { UserData = data }, (ulong address, out uint word) => { word = 0; return false; }, + userDataBase: first); + + for (var repetition = 0; repetition < 2; repetition++) + { + Assert.Empty(Assert.Single(Read(8, [0, 0, 123, 0]).Calls).Targets); + Assert.Throws(() => Read(9, [0, 0, 123, 0])); + Assert.Empty(Assert.Single(Read(8, [0, 0, 456, 0]).Calls).Targets); + } + } + + [Fact] + public void CachedTableSites_ReadCurrentTableAndResourceMapping() + { + var caller = Program( + ScalarBufferLoad(0, 4, 14, 2, immediateOffset: 0), + ScalarBufferLoad(8, 4, 16, 2, immediateOffset: 8), + new(16, Gen5ShaderEncoding.Sopp, "SWaitcnt", [0xBF8C0000], [], [], null), + Sop1(20, "SSwappcB64", 14, Gen5Operand.Scalar(14)), EndProgram(24)); + var words = new Dictionary + { + [0x1000] = 0x2000, [0x1004] = 0, [0x1008] = 0x3000, [0x100C] = 0, + [0x3000] = 0x2000, [0x3004] = 0, [0x3008] = 0x5000, [0x300C] = 0, + [0x2000] = 0xBF800000, [0x2004] = 0xBE80200E, + }; + var snapshot = new ResourceSnapshot { Buffers = [[0x1000, 16u << 16, 1, 0], [0x3000, 16u << 16, 1, 0]] }; + ShaderCallLibrary Read(uint resource) + { + var memory = new MemoryAccessTable(); + memory.Add(new() { Pc = 0, Kind = MemoryResourceKind.ScalarBuffer, Resource = resource }); + return ShaderCallLibrary.Read(caller, memory, snapshot, + (ulong address, out uint word) => words.TryGetValue(address, out word)); + } + + Assert.Equal(0x3000ul, Assert.Single(Assert.Single(Read(0).Calls).Targets).Argument); + Assert.Equal(0x5000ul, Assert.Single(Assert.Single(Read(1).Calls).Targets).Argument); + words[0x3008] = 0x6000; + Assert.Equal(0x6000ul, Assert.Single(Assert.Single(Read(1).Calls).Targets).Argument); + words.Remove(0x300C); + Assert.Throws(() => Read(1)); + } + + [Fact] + public void CachedSites_DoNotFollowAnOldInstructionList() + { + var caller = UserDataCaller(); + var changed = caller with + { + Instructions = caller.Instructions.Select(instruction => instruction.Pc == 16 + ? instruction with { AddressOffset = 0x1_0000_0010ul } : instruction).ToArray(), + }; + var snapshot = new ResourceSnapshot { UserData = [0, 0, 0, 0] }; + ShaderCallLibrary Read(Gen5ShaderProgram selected) => ShaderCallLibrary.Read(selected, new MemoryAccessTable(), snapshot, + (ulong address, out uint word) => { word = 0; return false; }, userDataBase: 8); + + Assert.Equal(20ul, Assert.Single(Read(caller).Calls).ReturnAddress); + Assert.Equal(0x1_0000_0014ul, Assert.Single(Read(changed).Calls).ReturnAddress); + var changedSource = caller with + { + Instructions = caller.Instructions.Select(instruction => instruction.Pc == 0 + ? MoveScalarRegister(0, 14, 9) : instruction).ToArray(), + }; + Assert.Throws(() => Read(changedSource)); + Assert.Equal(20ul, Assert.Single(Read(caller).Calls).ReturnAddress); + } + + [Fact] + public void CachedRefusal_DoesNotReorderEarlierGuestReads() + { + var caller = Program( + MoveScalarRegister(0, 14, 8), MoveScalarRegister(4, 15, 9), + MoveScalarRegister(8, 16, 10), MoveScalarRegister(12, 17, 11), + Sop1(16, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + new(20, Gen5ShaderEncoding.Sop1, "SSwappcB64", [0], [], [], null), EndProgram(24)); + for (var repetition = 0; repetition < 2; repetition++) + { + var reads = new List(); + var error = Assert.Throws(() => ShaderCallLibrary.Read(caller, new MemoryAccessTable(), + new ResourceSnapshot { UserData = [0x2000, 0, 0x3000, 0] }, + (ulong address, out uint word) => + { + reads.Add(address); + word = address == 0x2000 ? 0xBF800000u : 0xBE80200Eu; + return address is 0x2000 or 0x2004; + }, userDataBase: 8)); + + Assert.Contains(0x2000ul, reads); + Assert.Equal("The shader call does not use a supported table record.", error.Message); + } + } + + [Fact] + public void ConcurrentReaders_KeepTheirOwnRangeAndRefusal() + { + var caller = UserDataCaller(); + Parallel.For(0, 64, index => + { + var valid = (index & 1) == 0; + ShaderCallLibrary Read() => ShaderCallLibrary.Read(caller, new MemoryAccessTable(), + new ResourceSnapshot { UserData = [0, 0, 0, 0] }, + (ulong address, out uint word) => { word = 0; return false; }, userDataBase: valid ? 8u : 9u); + if (valid) Assert.Empty(Assert.Single(Read().Calls).Targets); + else Assert.Throws(Read); + }); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCallUnionStoreTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCallUnionStoreTests.cs new file mode 100644 index 000000000..25dd2b0d3 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCallUnionStoreTests.cs @@ -0,0 +1,62 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Security.Cryptography; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +public sealed class ShaderCallUnionStoreTests +{ + private const ulong Caller = 0xC0FFEE, FunctionAddress = 0x2000, OtherAddress = 0x3000; + + // A recorded library is the one a session links first when its callees, site by site, are the ones a session kept, + // as the next session's store reads them back. + [Fact] + public void ARecordedLibraryIsTheKeptOneOnlyWhenItsSiteCalleesMatch() + { + var directory = Path.Combine(Path.GetTempPath(), $"sharpemu-callees-{Guid.NewGuid():N}"); + var path = Path.Combine(directory, "callees.bin"); + try + { + new ShaderCallUnionStore(path).Save(ShaderStage.Compute, Caller, + new Dictionary { [0] = [Callee(FunctionAddress)], [8] = [] }); + var store = new ShaderCallUnionStore(path); + + Assert.True(store.KeepsCalleesOf(ShaderStage.Compute, Caller, Library((0, FunctionAddress)))); + Assert.False(store.KeepsCalleesOf(ShaderStage.Compute, Caller, Library((0, OtherAddress)))); + Assert.False(store.KeepsCalleesOf(ShaderStage.Compute, Caller, Library((0, FunctionAddress), (8, FunctionAddress)))); + Assert.False(store.KeepsCalleesOf(ShaderStage.Compute, Caller + 1, Library((0, FunctionAddress)))); + Assert.False(store.KeepsCalleesOf(ShaderStage.Pixel, Caller, Library((0, FunctionAddress)))); + } + finally + { + if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true); + } + } + + private static UnitedCallee Callee(ulong address) + { + uint[] words = [0xBF800000, 0xBE80200E]; + var function = ShaderFunctionReader.Read(address, (ulong wordAddress, out uint word) => + { + var offset = wordAddress - address; + word = offset < 8 ? words[(int)(offset / 4)] : 0; + return offset < 8; + }); + Assert.True(function.Complete, function.Error); + return new UnitedCallee(new ShaderCallTarget(address, 0, function.Program), SHA256.HashData(function.Bytes), function.Runs); + } + + private static LinkedShaderPrewarm Library(params (uint Pc, ulong Target)[] calls) + { + var functions = calls.Select(static call => call.Target).Distinct() + .Select(static address => new LinkedPrewarmFunction(address, [new CodeRange(address, new byte[8])])).ToArray(); + var sites = calls.GroupBy(static call => call.Pc).Select(static site => new LinkedPrewarmSite(site.Key, 14, 16, 14, + Caller + site.Key + 4, [.. site.Select(static call => new LinkedPrewarmTarget(call.Target, 0))])).ToArray(); + return new LinkedShaderPrewarm(true, false, false, functions, sites); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCalleeTiersTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCalleeTiersTests.cs index 31258bfd1..0bc7a9191 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCalleeTiersTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCalleeTiersTests.cs @@ -143,4 +143,69 @@ public void A_new_choice_waits_for_the_calls_to_settle() third.Observe(Named((First, FirstCode), (Second, SecondCode)), Caller, host); Assert.Equal([First, Second], third.Choose(union, fallbackGeneration: 1, snapshots: 167)[0x40].Keys.Order()); } + + private static Dictionary> Sites(params (uint Pc, UnitedCallee Callee)[] entries) + { + var sites = new Dictionary>(); + foreach (var (pc, callee) in entries) + { + if (!sites.TryGetValue(pc, out var callees)) sites[pc] = callees = []; + callees[callee.Target.Address] = callee; + } + + return sites; + } + + // A body already called at one site that the tables also name at another site moves the choice like a call: otherwise + // the ready program keeps no target at the new site, and its calls there return at once. + [Fact] + public void A_called_body_named_at_another_site_moves_the_choice() + { + var tiers = new ShaderCalleeTiers(Sites((0x40, Callee(First, FirstCode)))); + tiers.LinkedGeneration = 3; + var union = Sites((0x40, Callee(First, FirstCode)), (0x80, Callee(First, FirstCode))); + Assert.False(tiers.Choose(union, 3, 10).ContainsKey(0x80)); + Assert.False(tiers.Choose(union, 3, 10 + ShaderCalleeTiers.Settle - 1).ContainsKey(0x80)); + var chosen = tiers.Choose(union, 3, 10 + ShaderCalleeTiers.Settle); + Assert.Equal([First], chosen[0x40].Keys); + Assert.Equal([First], chosen[0x80].Keys); + Assert.Null(tiers.LinkedGeneration); + } + + // The scan runs again once the program cache reports a union change after a scan that found every called body chosen. + [Fact] + public void A_union_that_later_names_a_called_body_at_a_new_site_moves_the_choice() + { + var tiers = new ShaderCalleeTiers(Sites((0x40, Callee(First, FirstCode)))); + tiers.LinkedGeneration = 3; + var union = Sites((0x40, Callee(First, FirstCode))); + for (var snapshots = 10; snapshots < 10 + 2 * ShaderCalleeTiers.Settle; snapshots++) + { + Assert.Equal([0x40u], tiers.Choose(union, 3, snapshots).Keys); + } + + Assert.Equal(3, tiers.LinkedGeneration); + union[0x80] = new() { [First] = Callee(First, FirstCode) }; + tiers.NoteUnionChanged(); + Assert.False(tiers.Choose(union, 3, 40).ContainsKey(0x80)); + Assert.Equal([First], tiers.Choose(union, 3, 40 + ShaderCalleeTiers.Settle)[0x80].Keys); + } + + // A site whose body only moved to another address keeps its slot (CurrentTargets serves the address that holds the code), + // so it does not move the choice; neither does a body nobody called. + [Fact] + public void A_moved_body_or_an_uncalled_body_at_a_new_site_keeps_the_choice() + { + var tiers = new ShaderCalleeTiers(Sites((0x40, Callee(First, FirstCode)))); + tiers.LinkedGeneration = 3; + var union = Sites((0x40, Callee(Second, FirstCode)), (0x80, Callee(Second + 0x10000, SecondCode))); + for (var snapshots = 10; snapshots < 10 + 2 * ShaderCalleeTiers.Settle; snapshots++) + { + var chosen = tiers.Choose(union, 3, snapshots); + Assert.Equal([First], chosen[0x40].Keys); + Assert.False(chosen.ContainsKey(0x80)); + } + + Assert.Equal(3, tiers.LinkedGeneration); + } } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderDescriptorLimitsTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderDescriptorLimitsTests.cs index 6ad83de49..455821730 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderDescriptorLimitsTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderDescriptorLimitsTests.cs @@ -9,6 +9,50 @@ namespace SharpEmu.Libs.Tests.Gpu.Pipelines; public sealed unsafe class ShaderDescriptorLimitsTests { + [Fact] + public void StableComputeBudgetUsesPerStagePerSetAndPoolLimits() + { + var limits = new PhysicalDeviceLimits + { + MaxPerStageDescriptorSampledImages = 16, MaxDescriptorSetSampledImages = 32, + MaxPerStageDescriptorStorageImages = 32, MaxDescriptorSetStorageImages = 8, + MaxPerStageDescriptorSamplers = uint.MaxValue, MaxDescriptorSetSamplers = uint.MaxValue, + MaxPerStageDescriptorStorageBuffers = uint.MaxValue, MaxDescriptorSetStorageBuffers = uint.MaxValue, + MaxPerStageResources = 27, + }; + var budget = ShaderDescriptorLimits.ComputeImageLimits(limits); + Assert.Equal(16u, budget.SampledImages); + Assert.Equal(8u, budget.StorageImages); + Assert.Equal(DescriptorHeap.PoolCapacity.Samplers, budget.Samplers); + Assert.Equal(DescriptorHeap.PoolCapacity.StorageBuffers, budget.StorageBuffers); + Assert.Equal(27u, budget.Resources); + limits.MaxPerStageDescriptorSampledImages = limits.MaxDescriptorSetSampledImages = uint.MaxValue; + limits.MaxPerStageDescriptorStorageImages = limits.MaxDescriptorSetStorageImages = uint.MaxValue; + budget = ShaderDescriptorLimits.ComputeImageLimits(limits); + Assert.Equal(DescriptorHeap.PoolCapacity.SampledImages, budget.SampledImages); + Assert.Equal(DescriptorHeap.PoolCapacity.StorageImages, budget.StorageImages); + } + + // The two stages of a pipeline built whole share one set and one pool, so each takes half of both. + [Fact] + public void StableGraphicsBudgetHalvesTheSetAndPoolLimits() + { + var limits = new PhysicalDeviceLimits + { + MaxPerStageDescriptorSampledImages = 16, MaxDescriptorSetSampledImages = 24, + MaxPerStageDescriptorStorageImages = 4, MaxDescriptorSetStorageImages = 64, + MaxPerStageDescriptorSamplers = uint.MaxValue, MaxDescriptorSetSamplers = uint.MaxValue, + MaxPerStageDescriptorStorageBuffers = uint.MaxValue, MaxDescriptorSetStorageBuffers = uint.MaxValue, + MaxPerStageResources = 27, + }; + var budget = ShaderDescriptorLimits.GraphicsImageLimits(limits); + Assert.Equal(12u, budget.SampledImages); + Assert.Equal(4u, budget.StorageImages); + Assert.Equal(DescriptorHeap.PoolCapacity.Samplers / 2, budget.Samplers); + Assert.Equal(DescriptorHeap.PoolCapacity.StorageBuffers / 2, budget.StorageBuffers); + Assert.Equal(27u, budget.Resources); + } + [Fact] public void CountsPhysicalDescriptorsAcrossBindingsAndStages() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderFunctionReaderTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderFunctionReaderTests.cs index 3547b2b4b..028d21ca1 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderFunctionReaderTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderFunctionReaderTests.cs @@ -114,4 +114,22 @@ bool Read(ulong address, out uint word) readable = true; Assert.True(cache.Read(0x10000, Read).Complete); } + + // Words that do not decode (a stale table record naming other data) are decoded again only once they change. + [Fact] + public void FunctionCache_KeepsAFailedDecodeUntilItsWordsChange() + { + var code = new Dictionary { [0x10000] = 0x7A005800 }; + bool Read(ulong address, out uint word) => code.TryGetValue(address, out word); + var cache = new ShaderFunctionCache(null); + + var first = cache.Read(0x10000, Read); + Assert.False(first.Complete); + Assert.DoesNotContain("read-failed", first.Error); + Assert.Same(first, cache.Read(0x10000, Read)); + + code[0x10000] = 0xBE80200E; + var changed = cache.Read(0x10000, Read); + Assert.True(changed.Complete, changed.Error); + } } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheTests.cs index 5fb7dbd8e..3f8e7bd32 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheTests.cs @@ -584,6 +584,26 @@ public void GraphicsPipelines_AreCachedByTheirKey() Assert.Equal(2, cache.GraphicsPipelineCount); } + [Fact] + public void GraphicsPipelines_StillCompiling_AreWaitedForOutsideTheCacheLock() + { + var guest = new PipelineTestGuest(); + guest.Host.PendingGraphicsCompiles = 2; + var cache = new ShaderPipelineCache(guest.Context, guest.Host, guest.Compiler, guest.Registry); + var host = new RecordingRenderHost(); + var executor = new RenderExecutor(host, new CachingProvider(cache)); + + executor.DrawAuto(1, Banks(), Auto(3)); + + // The draw is not left out: it waited twice for the compile it started, then took the pipeline. + Assert.Single(host.Calls, call => call.StartsWith("draw ", StringComparison.Ordinal)); + Assert.Single(guest.Host.GraphicsPipelines); + Assert.Equal(3, guest.Host.GraphicsPipelineRequests.Count); + Assert.Equal(2, guest.Host.GraphicsPipelineWaits.Count); + Assert.All(guest.Host.GraphicsPipelineWaits, wait => Assert.Same(guest.Host.GraphicsPipelineRequests[0], wait)); + Assert.Equal(1, cache.GraphicsPipelineCount); + } + // Programs from the fixtures, pipelines from the real cache over the fake host. private sealed class CachingProvider(ShaderPipelineCache cache) : IShaderPipelineProvider { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPlanningDumpTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPlanningDumpTests.cs index 02ae0124e..83a21e24c 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPlanningDumpTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPlanningDumpTests.cs @@ -18,7 +18,7 @@ public sealed class ShaderPlanningDumpTests public void RejectedPlanPreservesDiagnosticsOnlyWhenTheGateAndAddressMatch(string enabled, bool addressMatches, bool expectFiles, bool blockedDirectory) { var directory = Directory.CreateTempSubdirectory("shader-planning-test-").FullName; - var names = new[] { "SHARPEMU_DUMP_SPIRV", "SHARPEMU_DUMP_SPIRV_ADDRESS", "SHARPEMU_SHADER_SPIRV_DUMP_DIR" }; + var names = new[] { "SHARPEMU_DUMP_SPIRV", "SHARPEMU_DUMP_SPIRV_ADDRESS", "SHARPEMU_SHADER_SPIRV_DUMP_DIR", "SHARPEMU_BINDLESS_NULL" }; var previous = names.Select(Environment.GetEnvironmentVariable).ToArray(); try { @@ -28,6 +28,8 @@ public void RejectedPlanPreservesDiagnosticsOnlyWhenTheGateAndAddressMatch(strin var outputDirectory = Path.Combine(directory, "output"); if (blockedDirectory) File.WriteAllText(outputDirectory, "This file prevents directory creation."); Environment.SetEnvironmentVariable(names[2], outputDirectory); + // Null bindless descriptors off: the image descriptor below then rejects the plan. + Environment.SetEnvironmentVariable(names[3], "0"); using var fatalScope = new FatalScope(); var guest = new PipelineTestGuest(); // A lane-derived offset reads an image descriptor without a material-table selector. diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPrewarmExtensionTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPrewarmExtensionTests.cs new file mode 100644 index 000000000..3c71732ab --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPrewarmExtensionTests.cs @@ -0,0 +1,273 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.IO.Hashing; +using SharpEmu.HLE; +using SharpEmu.Libs.Gpu.Images; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +// The prewarm list's side file: record kinds an earlier build cannot read (pixel programs, linked compile outcomes). +public sealed class ShaderPrewarmExtensionTests : IDisposable +{ + private const ulong CodeAddress = PipelineTestGuest.MemoryBase + 0x1_0000; + private const int MainHeaderBytes = 3 * sizeof(uint); + private const int ExtensionHeaderBytes = 2 * sizeof(uint); + + private readonly string _directory = Path.Combine(Path.GetTempPath(), "SharpEmuTests", Guid.NewGuid().ToString("N")); + + public void Dispose() + { + if (Directory.Exists(_directory)) + { + Directory.Delete(_directory, recursive: true); + } + } + + private ShaderPrewarmList Open() => ShaderPrewarmList.Open(_directory) ?? throw new InvalidOperationException("The list did not open."); + + private string MainPath => Path.Combine(_directory, ShaderPrewarmList.FileName); + + private string ExtensionPath => Path.Combine(_directory, ShaderPrewarmList.ExtensionFileName); + + private static (ShaderCodeCapture Code, PixelPrewarmRecord Record) Pixel() + { + var code = new ShaderCodeCapture + { + Hash = 0x0BAD_F00D_1234_5678, CodeSize = 8, Address = CodeAddress, Generation = Generation.Gen5, + Ranges = [new CodeRange(CodeAddress, [1, 2, 3, 4, 5, 6, 7, 8])], + }; + var record = new PixelPrewarmRecord + { + Hash = code.Hash, + CodeSize = code.CodeSize, + Address = code.Address, + UserDataBase = 0, + UserDataCount = 4, + PushDataCursor = 0, + Info = new PixelInputInfo { InputCount = 1 }, + Outputs = [new Gen5PixelOutputBinding(0, 0, Gen5PixelOutputKind.Float)], + InputEnable = 0x2, + InputAddress = 0x2, + Specialization = new ResourceSpecialization(), + }; + return (code, record); + } + + // A record as the list frames it: length, checksum, then the kind byte and the payload. + private static byte[] Frame(byte kind, byte[] payload) + { + var body = new byte[1 + payload.Length]; + body[0] = kind; + payload.CopyTo(body, 1); + var record = new byte[sizeof(uint) + sizeof(ulong) + body.Length]; + BitConverter.TryWriteBytes(record.AsSpan(0, sizeof(uint)), (uint)body.Length); + BitConverter.TryWriteBytes(record.AsSpan(sizeof(uint), sizeof(ulong)), XxHash3.HashToUInt64(body)); + body.CopyTo(record, sizeof(uint) + sizeof(ulong)); + return record; + } + + [Fact] + public void PixelRecordsGoToTheSideFile_SoAnEarlierBuildKeepsTheWholeMainList() + { + var (code, record) = Pixel(); + using (var list = Open()) + { + list.RecordPixel(code, record); + } + + // An earlier build reads the main list only; it holds nothing it would stop at and cut. + Assert.Equal(MainHeaderBytes, new FileInfo(MainPath).Length); + Assert.True(new FileInfo(ExtensionPath).Length > ExtensionHeaderBytes); + using var reloaded = Open(); + var (loaded, loadedCode, _) = Assert.IsType(Assert.Single(reloaded.LoadedGraphicsPrewarm())); + Assert.Equal(ShaderPrewarmList.Identity(record), ShaderPrewarmList.Identity(loaded)); + Assert.Equal(code.Ranges[0].Bytes, Assert.Single(loadedCode.Ranges).Bytes); + } + + // A side file of another version is not loaded: version 2 changed the image binding policy graphics records + // translate under, and version 3 ends pixel and pre-rasterization records with their first use. + [Fact] + public void ASideFileOfAnotherVersionStartsEmpty() + { + var (code, record) = Pixel(); + using (var list = Open()) + { + list.RecordPixel(code, record); + list.RecordLinkedCompile(0x1234, slow: true, milliseconds: 90_000); + } + + var bytes = File.ReadAllBytes(ExtensionPath); + BitConverter.TryWriteBytes(bytes.AsSpan(sizeof(uint), sizeof(uint)), 1u); + File.WriteAllBytes(ExtensionPath, bytes); + using (var reloaded = Open()) + { + Assert.Empty(reloaded.LoadedGraphicsPrewarm()); + Assert.False(reloaded.IsSlowLinkedCompile(0x1234)); + } + + Assert.Equal(ExtensionHeaderBytes, new FileInfo(ExtensionPath).Length); + Assert.Equal(3u, BitConverter.ToUInt32(File.ReadAllBytes(ExtensionPath), sizeof(uint))); + } + + [Fact] + public void LinkedCompileOutcomesPersist_AndTheLastOneWins() + { + const ulong slow = 0xE6D7_6D24_F59F_8015; + const ulong other = 0xC4DF_2A00_067E_0666; + using (var list = Open()) + { + Assert.False(list.IsSlowLinkedCompile(slow)); + list.RecordLinkedCompile(slow, slow: true, 61_000); + Assert.True(list.IsSlowLinkedCompile(slow)); + } + + var length = new FileInfo(ExtensionPath).Length; + using (var list = Open()) + { + Assert.True(list.IsSlowLinkedCompile(slow)); + // Nothing new to record: the same outcome again, and fast for a program never recorded slow. + list.RecordLinkedCompile(slow, slow: true, 70_000); + list.RecordLinkedCompile(other, slow: false, 3_000); + } + + Assert.Equal(length, new FileInfo(ExtensionPath).Length); + using (var list = Open()) + { + Assert.False(list.IsSlowLinkedCompile(other)); + list.RecordLinkedCompile(slow, slow: false, 1_200); + Assert.False(list.IsSlowLinkedCompile(slow)); + } + + using var reloaded = Open(); + Assert.False(reloaded.IsSlowLinkedCompile(slow)); + } + + [Fact] + public void AnUnknownSideFileRecordIsSkippedAndKept() + { + const ulong first = 0x29BE_8047_C4E8_6AFE; + const ulong second = 0xFC05_37B7_278D_B60C; + using (var list = Open()) + { + list.RecordLinkedCompile(first, slow: true, 90_000); + } + + // A later build's record kind, then this build's own record after it. + var unknown = Frame(0x7F, [9, 8, 7, 6, 5]); + using (var file = new FileStream(ExtensionPath, FileMode.Append, FileAccess.Write)) + { + file.Write(unknown); + } + + var withUnknown = new FileInfo(ExtensionPath).Length; + using (var list = Open()) + { + Assert.True(list.IsSlowLinkedCompile(first)); + list.RecordLinkedCompile(second, slow: true, 120_000); + } + + Assert.True(new FileInfo(ExtensionPath).Length > withUnknown); + using (var reloaded = Open()) + { + Assert.True(reloaded.IsSlowLinkedCompile(first)); + Assert.True(reloaded.IsSlowLinkedCompile(second)); + } + + var bytes = File.ReadAllBytes(ExtensionPath); + Assert.True(bytes.AsSpan().IndexOf(unknown) > 0); + } + + [Fact] + public void ATornSideFileRecordEndsTheLoadAndIsCut() + { + const ulong first = 0x6573_0DAB_35E2_83F7; + const ulong torn = 0x1111_2222_3333_4444; + using (var list = Open()) + { + list.RecordLinkedCompile(first, slow: true, 75_000); + } + + var intact = new FileInfo(ExtensionPath).Length; + using (var list = Open()) + { + list.RecordLinkedCompile(torn, slow: true, 75_000); + } + + using (var file = new FileStream(ExtensionPath, FileMode.Open, FileAccess.ReadWrite)) + { + file.SetLength(file.Length - 3); + } + + using var reloaded = Open(); + Assert.True(reloaded.IsSlowLinkedCompile(first)); + Assert.False(reloaded.IsSlowLinkedCompile(torn)); + Assert.Equal(intact, new FileInfo(ExtensionPath).Length); + } + + [Fact] + public void TheSideFileKeepsItsOwnProgress() + { + using var list = Open(); + list.AppendProgress("stamp", new ulong[] { 1, 2 }, extension: true); + list.AppendProgress("stamp", new ulong[] { 3 }); + + // The compute prewarm clears its own progress only. + list.ClearProgress(); + Assert.Empty(list.ReadProgress("stamp")); + Assert.Equal(new HashSet { 1, 2 }, list.ReadProgress("stamp", extension: true)); + } + + [Fact] + public void PixelRecordsInTheMainFileOfAListWithoutSideFileStillLoad() + { + var (code, record) = Pixel(); + using (var list = Open()) + { + list.RecordPixel(code, record); + } + + // Move the side file's records to the end of the main list, where a list written without a side file keeps + // them, and cut the first use from each pixel record. + var extension = File.ReadAllBytes(ExtensionPath); + using (var main = new FileStream(MainPath, FileMode.Append, FileAccess.Write)) + { + main.Write(WithoutFirstUse(extension.AsSpan(ExtensionHeaderBytes))); + } + + File.Delete(ExtensionPath); + using var reloaded = Open(); + var (loaded, _, _) = Assert.IsType(Assert.Single(reloaded.LoadedGraphicsPrewarm())); + Assert.Equal(ShaderPrewarmList.Identity(record), ShaderPrewarmList.Identity(loaded)); + } + + // Records (length, checksum, kind and payload each) with the first use cut from every pixel record's payload. + private static byte[] WithoutFirstUse(ReadOnlySpan records) + { + const byte pixelKind = 3; + const int headerBytes = sizeof(uint) + sizeof(ulong); + using var output = new MemoryStream(); + while (records.Length >= headerBytes) + { + var length = (int)BitConverter.ToUInt32(records); + var body = records.Slice(headerBytes, length).ToArray(); + if (body[0] == pixelKind) + { + body = body[..^sizeof(float)]; + } + + output.Write(BitConverter.GetBytes((uint)body.Length)); + output.Write(BitConverter.GetBytes(XxHash3.HashToUInt64(body))); + output.Write(body); + records = records[(headerBytes + length)..]; + } + + return output.ToArray(); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPrewarmLinkedReplayTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPrewarmLinkedReplayTests.cs new file mode 100644 index 000000000..26a05e388 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPrewarmLinkedReplayTests.cs @@ -0,0 +1,254 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +// The prewarm record must describe the program that was actually compiled, including linked +// callees. The round-trip cases use the real translator and compare payload and layout as well as structure. +[Collection(SchedulingStateCollection.Name)] +public sealed class ShaderPrewarmLinkedReplayTests : IDisposable +{ + private const ulong Caller = PipelineTestGuest.MemoryBase + 0x1000; + private const ulong Header = PipelineTestGuest.MemoryBase + 0x8000; + private const ulong Table = PipelineTestGuest.MemoryBase + 0x10000; + private const ulong Callee = PipelineTestGuest.MemoryBase + 0x20000; + private readonly string _directory = Path.Combine(Path.GetTempPath(), "SharpEmuTests", Guid.NewGuid().ToString("N")); + + [Theory] + [InlineData(false)] + [InlineData(true)] + [InlineData(true, true)] + public void RecordedProgramRestoresItsLinkedCallEntries(bool linked, bool imageCallee = false) + { + using var fatal = new FatalScope(); + ShaderCompileRequest runtime; + byte[] runtimeSpirv; + using (var list = Open()) + { + var guest = CreateGuest(list, linked, imageCallee); + Compile(guest, linked); + runtime = Assert.Single(guest.Compiler.Requests); + runtimeSpirv = Assert.Single(guest.Compiler.Shaders).Spirv; + Assert.DoesNotContain(runtime.Program.Instructions, instruction => instruction.Opcode == "SSwappcB64"); + Assert.Equal(linked ? 1 : 0, CallEntries(runtime).Length); + if (imageCallee) Assert.NotEmpty(runtime.Resources.Info.Images); + } + + using var restored = Open(); + var (record, code) = Assert.Single(restored.LoadedComputes()); + var compiler = new FakeShaderCompiler(CompileSpirv); + Assert.True(ShaderProgramCache.TryCompilePrewarm(record, code, compiler, false, true, false, + out var compiled, out var layout, out var error), error); + Assert.NotNull(compiled); + Assert.NotNull(layout); + Assert.Equal(runtimeSpirv, Assert.IsType(compiled).Spirv); + Assert.Equal(runtime.Bindings, layout); + Assert.Equal(runtime.Bindings.AllocationCursor, layout.AllocationCursor); + var replay = Assert.Single(compiler.Requests); + Assert.DoesNotContain(replay.Program.Instructions, instruction => instruction.Opcode == "SSwappcB64"); + Assert.Equal(CallEntries(runtime), CallEntries(replay)); + Assert.Equal(runtime.Program.Instructions.Select(instruction => instruction.Opcode).ToArray(), + replay.Program.Instructions.Select(instruction => instruction.Opcode).ToArray()); + } + + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + [InlineData(false, true, true)] + [InlineData(true, true, true)] + public void RuntimeRecordModesRoundTripThroughRecordingAndTheTranslator(bool callMarks, bool withCallee, bool gpuThreadCounts = false) + { + using var fatal = new FatalScope(); + ShaderCompileRequest runtime; + byte[] runtimeSpirv; + using (var list = Open()) + { + var guest = CreateGuest(list, linked: true); + guest.Host.RuntimeCallRecordsSupported = true; + guest.Host.CallMarksSupported = callMarks; + UseIsolatedCallUnion(guest, withCallee); + Compile(guest, linked: true, gpuThreadCounts: gpuThreadCounts); + runtime = Assert.Single(guest.Compiler.Requests); + runtimeSpirv = Assert.Single(guest.Compiler.Shaders).Spirv; + Assert.Equal(withCallee ? 1 : 0, CallEntries(runtime).Length); + Assert.All(runtime.Program.Instructions.Select(instruction => instruction.Control) + .OfType(), entry => Assert.True(entry.RuntimeArgument)); + var fault = Assert.Single(runtime.Program.Instructions.Select(instruction => instruction.Control) + .OfType()); + Assert.NotNull(fault.ReturnPc); + Assert.Equal(callMarks, runtime.Resources.Info.UsesCallMarks); + Assert.Equal(callMarks, runtime.Bindings.Find(DescriptorBindingKind.CallMarks) is not null); + Assert.Equal(gpuThreadCounts, runtime.Bindings.UsesDispatchThreadLimits); + if (gpuThreadCounts) + { + Assert.False(runtime.Bindings.UsesPushData); + Assert.NotNull(runtime.Bindings.Find(DescriptorBindingKind.ShaderData)); + } + } + + using var restored = Open(); + var (record, code) = Assert.Single(restored.LoadedComputes()); + Assert.NotNull(record.Linked); + Assert.True(record.Linked.RuntimeRecords); + Assert.Equal(gpuThreadCounts, record.Info.IndirectThreadCounts); + Assert.Equal(gpuThreadCounts, record.Info.DispatchThreadDimensions); + Assert.Equal(gpuThreadCounts ? PushData.DwordCount : 0u, record.PushDataCursor); + Assert.Equal(callMarks, record.Linked.CallMarks); + Assert.Equal(withCallee ? 1 : 0, record.Linked.Functions.Length); + Assert.Single(record.Linked.Sites); + Assert.Equal(withCallee ? 1 : 0, record.Linked.Sites[0].Targets.Length); + var compiler = new FakeShaderCompiler(CompileSpirv); + Assert.True(ShaderProgramCache.TryCompilePrewarm(record, code, compiler, false, true, false, + out var compiled, out var layout, out var error), error); + Assert.Equal(runtimeSpirv, Assert.IsType(compiled).Spirv); + Assert.Equal(runtime.Bindings, layout); + var replay = Assert.Single(compiler.Requests); + Assert.Equal(runtime.Resources.Info.UsesCallMarks, replay.Resources.Info.UsesCallMarks); + Assert.Equal(runtime.Program.Instructions.Select(instruction => instruction.Control), + replay.Program.Instructions.Select(instruction => instruction.Control)); + } + + private void UseIsolatedCallUnion(PipelineTestGuest guest, bool withCallee) + { + // Runtime linking loads kept callees before its first compile. Inject a store under this test's directory, + // so this regression never reads or writes the user's shader cache and needs no process-wide environment edits. + var path = Path.Combine(_directory, "callees.bin"); + if (withCallee) + { + var decoded = ShaderFunctionReader.Read(Callee, guest.Host.TryReadGuestWord); + Assert.True(decoded.Complete, decoded.Error); + var source = guest.Source(Caller, ShaderStage.Compute, PipelineTestGuest.BufferDescriptor(Table, 16, 1, 0)); + var callee = new UnitedCallee(new ShaderCallTarget(Callee, 0, decoded.Program), + System.Security.Cryptography.SHA256.HashData(decoded.Bytes), decoded.Runs); + // The fixture's s_swappc is word7 (pc28); its return is Caller+32. + new ShaderCallUnionStore(path).Save(ShaderStage.Compute, source.Hash, new() { [28] = [callee] }); + } + var field = typeof(ShaderProgramCache).GetField("_callUnionStore", + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); + Assert.NotNull(field); + field.SetValue(guest.Programs, new ShaderCallUnionStore(path)); + } + + [Fact] + public void DifferentLinkedCalleeCodeDoesNotCollapseToOnePrewarmRecord() + { + using var fatal = new FatalScope(); + using (var list = Open()) + { + var guest = CreateGuest(list, linked: true); + var first = Compile(guest, linked: true); + // This existing linked-cache fixture changes code without changing descriptors or the caller. + guest.WriteWords(Callee, 0xBF800001, 0xBE80200E); + var second = Compile(guest, linked: true); + Assert.NotEqual(first, second); + Assert.Equal(2, guest.Compiler.Requests.Count); + Assert.All(guest.Compiler.Requests, request => Assert.Single(CallEntries(request))); + } + + using var restored = Open(); + var records = restored.LoadedComputes(); + Assert.Equal(2, records.Count); + Assert.Equal(2, records.Select(item => ShaderPrewarmList.Identity(item.Record)).Distinct().Count()); + } + + private static PipelineTestGuest CreateGuest(ShaderPrewarmList list, bool linked, bool imageCallee = false) + { + var guest = new PipelineTestGuest(CompileSpirv); + guest.Host.ShaderPrewarm = list; + guest.RegisterProgram(Caller, Header, linked + ? [0xF4280400, 125u << 25, 0xBF8C0000, 0xBE8E0310, 0xBE8F0311, + 0xBE900312, 0xBE910313, 0xBE8E210E, 0xBF810000] + : PipelineTestGuest.EndProgram); + var argument = imageCallee ? PipelineTestGuest.MemoryBase + 0x30000 : 0x3000UL; + if (imageCallee) + { + // Copy the record argument s[16:17] to the descriptor-table base s[0:1]; preserve return s[14:15]. + guest.WriteWords(Callee, [0xBE800410, .. ImageBindingTestProgram.Code()[..^1], 0xBE80200E]); + ImageBindingTestProgram.WriteDescriptors(guest, argument, ImageBindingTestProgram.Partitions[0]); + } + else guest.WriteWords(Callee, 0xBF800000, 0xBE80200E); + guest.WriteWords(Table, unchecked((uint)Callee), (uint)(Callee >> 32), unchecked((uint)argument), (uint)(argument >> 32)); + return guest; + } + + [Fact] + public void LinkedReplayStillRejectsAnInvalidIndirectRoot() + { + using var fatal = new FatalScope(); + using (var list = Open()) Compile(CreateGuest(list, linked: true), linked: true); + using var restored = Open(); + var (record, code) = Assert.Single(restored.LoadedComputes()); + Assert.NotNull(record.Linked); + record.Specialization.Images.Add(new ImageSpecialization( + ImageNumericClass.Float, ImageDimension.Dim2D, 1, 0, 0, uint.MaxValue, 0, 0, false)); + var compiler = new FakeShaderCompiler(); + Assert.False(ShaderProgramCache.TryCompilePrewarm(record, code, compiler, false, true, false, + out _, out _, out var error)); + Assert.Contains("invalid indirect root", error); + Assert.Empty(compiler.Requests); + } + + [Fact] + public void GlobalCacheStampDoesNotCertifyLinkedCaches() + { + using var fatal = new FatalScope(); + using (var list = Open()) Compile(CreateGuest(list, linked: true), linked: true); + using var restored = Open(); + Assert.True(restored.HasLinkedComputes); + var stamp = restored.CoverageStamp("test-build"); + byte[] cache = [1, 2, 3]; + restored.WriteStamp(ShaderPrewarmList.CacheStamp(stamp, cache)); + var presenter = typeof(SharpEmu.Libs.VideoOut.VulkanVideoPresenter) + .GetNestedType("Presenter", System.Reflection.BindingFlags.NonPublic)!; + var skip = presenter.GetMethod("CanSkipShaderPrewarm", + System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic)!; + Assert.False((bool)skip.Invoke(null, [restored, stamp, cache])!); + } + + private static ShaderProgram Compile(PipelineTestGuest guest, bool linked, bool gpuThreadCounts = false) + { + // Match ShaderPipelineCache: GPU-written limits must live outside push constants. + var cursor = gpuThreadCounts ? PushData.DwordCount : 0u; + var userData = linked ? PipelineTestGuest.BufferDescriptor(Table, 16, 1, 0) : Array.Empty(); + var options = gpuThreadCounts ? new StageCompileOptions + { + ComputeInfo = new ComputeInputInfo + { + ThreadsX = 32, ThreadsY = 1, ThreadsZ = 1, WaveSize = 32, GroupIdX = true, ThreadIdCount = 1, + DispatchThreadDimensions = true, IndirectThreadCounts = true, + }, + } : PipelineTestGuest.ComputeOptions(32); + var program = guest.Programs.GetOrCompile(guest.Source(Caller, ShaderStage.Compute, userData), + options, ref cursor, out var stage); + Assert.Equal(gpuThreadCounts, stage.GpuThreadLimits); + return program; + } + + private static byte[] CompileSpirv(ShaderCompileRequest request) + { + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + return shader.Spirv; + } + + private static ulong[] CallEntries(ShaderCompileRequest request) => request.Program.Instructions + .Select(instruction => instruction.Control).OfType() + .Select(entry => entry.ReturnAddress).ToArray(); + + private ShaderPrewarmList Open() => ShaderPrewarmList.Open(_directory) + ?? throw new InvalidOperationException("The synthetic prewarm list did not open."); + + public void Dispose() + { + if (Directory.Exists(_directory)) Directory.Delete(_directory, recursive: true); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPrewarmListTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPrewarmListTests.cs index 3f632a4e8..1b8e1a847 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPrewarmListTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPrewarmListTests.cs @@ -53,6 +53,41 @@ private static (IShaderPipelineHost Host, byte[] Spirv) CompileAtRuntime(ShaderP return (guest.Host, Assert.Single(guest.Compiler.Shaders).Spirv); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ImageBindingPolicyRoundTripsAndPrewarmRejectsTheOtherHostPolicy(bool stable) + { + var limits = stable ? ImageBindingTestProgram.Limits : default; + byte[] runtime; + using (var list = Open()) + { + var guest = new PipelineTestGuest(Compile); + guest.Host.ShaderPrewarm = list; + guest.Host.ComputeImageDescriptorLimits = limits; + guest.RegisterProgram(CodeAddress, HeaderAddress, ImageBindingTestProgram.Code()); + ImageBindingTestProgram.WriteDescriptors(guest, BufferAddress, ImageBindingTestProgram.Partitions[0]); + var cursor = 0u; + guest.Programs.GetOrCompile(guest.Source(CodeAddress, ShaderStage.Compute, + [unchecked((uint)BufferAddress), (uint)(BufferAddress >> 32)]), + PipelineTestGuest.ComputeOptions(), ref cursor, out _); + runtime = Assert.Single(guest.Compiler.Shaders).Spirv; + } + using var reloaded = Open(); + var (record, code) = Assert.Single(reloaded.LoadedComputes()); + Assert.Equal(stable, record.Specialization.StableImageBindings); + Assert.Equal(stable, record.Specialization.Clone().StableImageBindings); + var compiler = new FakeShaderCompiler(Compile); + Assert.True(ShaderProgramCache.TryCompilePrewarm(record, code, compiler, false, true, false, + out var compiled, out _, out var error, stableImageLimits: limits), error); + Assert.Equal(runtime, Assert.IsType(compiled).Spirv); + var rejected = new FakeShaderCompiler(Compile); + Assert.False(ShaderProgramCache.TryCompilePrewarm(record, code, rejected, false, true, false, + out _, out _, out error, stableImageLimits: stable ? default : ImageBindingTestProgram.Limits)); + Assert.Contains("image binding policy", error); + Assert.Empty(rejected.Requests); + } + private ShaderPrewarmList Open() => ShaderPrewarmList.Open(_directory) ?? throw new InvalidOperationException("The list did not open."); [Theory] @@ -88,8 +123,12 @@ public void ARecordedComputeProgramCompilesToTheSameSpirvAfterReload(bool ieeeMo Assert.Equal(runtime, Assert.IsType(compiled).Spirv); } - [Fact] - public void OlderFormatRecordsAreRejectedBeforeAppending() + [Theory] + [InlineData(1u)] + [InlineData(3u)] + [InlineData(4u)] + [InlineData(5u)] + public void OlderFormatRecordsAreRejectedBeforeAppending(uint version) { using (var list = Open()) CompileAtRuntime(list, BufferDescriptorWords.Format32UInt); @@ -97,7 +136,7 @@ public void OlderFormatRecordsAreRejectedBeforeAppending() using (var stream = new FileStream(path, FileMode.Open, FileAccess.Write)) { stream.Position = sizeof(uint); - stream.Write(BitConverter.GetBytes(1u)); + stream.Write(BitConverter.GetBytes(version)); } using (var list = Open()) { @@ -125,6 +164,161 @@ public void TheSameCompileIsRecordedOnceAndAnotherSpecializationAddsARecord() Assert.Same(loaded[0].Code.Ranges, loaded[1].Code.Ranges); } + // Compute records run by the earliest time into a session at which one used them, and a later session that uses a + // record sooner moves it up. + [Fact] + public void ComputeRecordsRunByTheirEarliestUse() + { + using (var list = Open()) + { + list.SessionClock = () => 10; + CompileAtRuntime(list, BufferDescriptorWords.Format32UInt); + list.SessionClock = () => 50; + CompileAtRuntime(list, BufferDescriptorWords.Format32x4UInt); + } + + using (var list = Open()) + { + Assert.Equal([BufferDescriptorWords.Format32UInt, BufferDescriptorWords.Format32x4UInt], Formats(list)); + list.SessionClock = () => 5; + CompileAtRuntime(list, BufferDescriptorWords.Format32x4UInt); + list.SessionClock = () => 30; + CompileAtRuntime(list, BufferDescriptorWords.Format32UInt); + } + + using var reloaded = Open(); + Assert.Equal([BufferDescriptorWords.Format32x4UInt, BufferDescriptorWords.Format32UInt], Formats(reloaded)); + } + + // A main list without first uses keeps list order. + [Fact] + public void ComputeRecordsWithoutFirstUsesKeepListOrder() + { + using (var list = Open()) + { + list.SessionClock = () => 50; + CompileAtRuntime(list, BufferDescriptorWords.Format32UInt); + list.SessionClock = () => 10; + CompileAtRuntime(list, BufferDescriptorWords.Format32x4UInt); + } + + File.Delete(Path.Combine(_directory, ShaderPrewarmList.ExtensionFileName)); + using var reloaded = Open(); + Assert.Equal([BufferDescriptorWords.Format32UInt, BufferDescriptorWords.Format32x4UInt], Formats(reloaded)); + } + + // A record whose compile takes long runs by the time it must start, its first use minus its longest recorded + // compile; a compile of under a second is not recorded, and a shorter one leaves the longer. + [Fact] + public void ALongCompileRunsByTheTimeItMustStart() + { + using (var list = Open()) + { + list.SessionClock = () => 10; + CompileAtRuntime(list, BufferDescriptorWords.Format32UInt); + list.SessionClock = () => 50; + CompileAtRuntime(list, BufferDescriptorWords.Format32x4UInt); + } + + using (var list = Open()) + { + var (first, second) = (list.LoadedComputes()[0].Record, list.LoadedComputes()[1].Record); + list.RecordComputeCost(second, 30); + Assert.Equal([BufferDescriptorWords.Format32UInt, BufferDescriptorWords.Format32x4UInt], Formats(list)); + // The second must start by 9.8 s, before the first's 10 s; a recorded half second would move the first to 9.5 s. + list.RecordComputeCost(first, 0.5f); + list.RecordComputeCost(second, 40.2f); + Assert.Equal([BufferDescriptorWords.Format32x4UInt, BufferDescriptorWords.Format32UInt], Formats(list)); + // A shorter compile leaves the longer: 50 - 20 = 30 s would put the second after the first again. + list.RecordComputeCost(second, 20); + Assert.Equal([BufferDescriptorWords.Format32x4UInt, BufferDescriptorWords.Format32UInt], Formats(list)); + } + + using var reloaded = Open(); + Assert.Equal([BufferDescriptorWords.Format32x4UInt, BufferDescriptorWords.Format32UInt], Formats(reloaded)); + // Scheduled by these starts: 50 - 40.2 for the second record, the first one's first use for the first. + Assert.Equal(new[] { 50f - 40.2f, 10f }, reloaded.LoadedComputeStarts().Select(static item => item.StartBy)); + } + + // A schema fingerprint that changes discards every recorded main list and graphics list and every pixel and vertex + // record, so it may only change with a deliberate format change. These are the values the recorded lists carry. + [Fact] + public void TheSchemaFingerprintsKeepTheValuesOfTheRecordedLists() + { + Assert.Equal(0x24DB2A98u, ShaderPrewarmList.SchemaFingerprint); + Assert.Equal(0x31C0D60Du, ShaderPrewarmList.PixelSchemaFingerprint); + Assert.Equal(0x31C5863Bu, ShaderPrewarmList.VertexSchemaFingerprint); + Assert.Equal(0xD15F4A8Du, ShaderPrewarmList.GraphicsSchemaFingerprint); + } + + private sealed class SchemaSample + { + public List Buffers { get; init; } = []; + public uint? Optional { get; init; } + public (ulong Address, uint SizeBytes)[] Ranges { get; init; } = []; + public uint Plain { get; init; } + } + + // Generic types are named without the assemblies of their arguments, whose versions change with every release and + // runtime, so the fingerprints stay those of the recorded lists. + [Fact] + public void TheSchemaTextNamesGenericTypesWithoutAssemblies() + { + Assert.Equal( + "SharpEmu.Libs.Tests.Gpu.Pipelines.ShaderPrewarmListTests+SchemaSample{" + + "System.Collections.Generic.List`1[SharpEmu.ShaderCompiler.Resources.BufferSpecialization] Buffers;" + + "System.Nullable`1[System.UInt32] Optional;" + + "System.UInt32 Plain;" + + "System.ValueTuple`2[System.UInt64,System.UInt32][] Ranges;}", + ShaderPrewarmList.SchemaText(typeof(SchemaSample))); + } + + // Records that differ only in a buffer's stride word, which the loader skips, load as one record. + [Fact] + public void RecordsThatDifferOnlyInAnOldBufferStrideLoadAsOne() + { + using (var list = Open()) + { + CompileAtRuntime(list, BufferDescriptorWords.Format32UInt); + } + + var path = Path.Combine(_directory, ShaderPrewarmList.FileName); + var compute = MainListBodies(File.ReadAllBytes(path)).Single(static body => body[0] == 2); + // The buffer's stride field (written as 0), then its descriptor format. + byte[] field = [0, 0, 0, 0, .. BitConverter.GetBytes(BufferDescriptorWords.Format32UInt)]; + var at = compute.AsSpan().IndexOf(field); + Assert.True(at > 0); + Assert.Equal(-1, compute.AsSpan(at + 1).IndexOf(field)); + using (var file = File.Open(path, FileMode.Append)) + { + foreach (var stride in new uint[] { 16, 32 }) + { + var old = (byte[])compute.Clone(); + BitConverter.TryWriteBytes(old.AsSpan(at), stride); + file.Write(BitConverter.GetBytes((uint)old.Length)); + file.Write(BitConverter.GetBytes(System.IO.Hashing.XxHash3.HashToUInt64(old))); + file.Write(old); + } + } + + using var reloaded = Open(); + Assert.Single(reloaded.LoadedComputes()); + } + + // Each record of a main list: its kind, then its payload. + private static IEnumerable MainListBodies(byte[] data) + { + for (var offset = 12; data.Length - offset >= 13;) + { + var length = BitConverter.ToInt32(data, offset); + yield return data.AsSpan(offset + 12, length).ToArray(); + offset += 12 + length; + } + } + + private static uint[] Formats(ShaderPrewarmList list) => + [.. list.LoadedComputes().Select(item => item.Record.Specialization.Buffers[0].DescriptorFormat)]; + [Fact] public void ATruncatedLastRecordIsDroppedAndTheListKeepsAppending() { @@ -180,8 +374,9 @@ public void ReloadKeepsSeparateContinuationsAtTheSameEntryAddress() using var reloaded = Open(); var records = reloaded.LoadedComputes(); Assert.Equal(3, records.Count); + // The order follows each record's first use; the continuations are what this checks. Assert.Equal(new ulong[] { 0, 0x100, 0x1_0000_0000 }, - records.Select(entry => entry.Record.ContinuationAddressOffset)); + records.Select(entry => entry.Record.ContinuationAddressOffset).Order()); foreach (var (record, code) in records) Assert.Equal(record.ContinuationAddressOffset, code.Fused is { } fused ? unchecked(fused.ContinuationAddress - code.Address) : 0); @@ -197,6 +392,27 @@ public void TheStampMatchesOnlyTheTextLastWritten() Assert.False(list.IsStampCurrent("build-b")); } + [Fact] + public void DeviceCountPlanRoundTripsBesideOrdinaryPrewarmRecords() + { + using (var list = Open()) CompileAtRuntime(list, BufferDescriptorWords.Format32UInt); + using (var list = Open()) + { + var (ordinary, code) = Assert.Single(list.LoadedComputes()); + Assert.False(ordinary.DeviceRecordCounts); + list.RecordCompute(code, new ComputePrewarmRecord + { + Hash = ordinary.Hash, CodeSize = ordinary.CodeSize, Address = ordinary.Address, + UserDataBase = ordinary.UserDataBase, UserDataCount = ordinary.UserDataCount, + PushDataCursor = ordinary.PushDataCursor, Info = ordinary.Info, SystemRegisters = ordinary.SystemRegisters, + Specialization = ordinary.Specialization, DeviceRecordCounts = true, + }); + } + using var reloaded = Open(); + // The second session's record runs first by its earlier use; the two records are what this checks. + Assert.Equal(new[] { false, true }, reloaded.LoadedComputes().Select(entry => entry.Record.DeviceRecordCounts).Order()); + } + [Fact] public void Coverage_UsesLoadedRecordsAndDoesNotCertifyConcurrentAppends() { @@ -285,6 +501,71 @@ public void ARecordIdentityDependsOnItsSpecialization() Assert.Equal(identities[0], ShaderPrewarmList.Identity(reloaded.LoadedComputes()[0].Record)); } + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + public void RecordedSpecializationPreservesAliasesAndMipStatistics(int changedField) + { + using (var list = Open()) + CompileAtRuntime(list, BufferDescriptorWords.Format32UInt); + + ResourceSpecialization expected; + ulong baselineIdentity; + ulong changedIdentity; + using (var list = Open()) + { + var (seed, code) = Assert.Single(list.LoadedComputes()); + var baseline = seed.Specialization.Clone(); + var image = new ImageSpecialization(ImageNumericClass.Float, ImageDimension.Dim2D, + 1, 0, DescriptorConstants.IdentityDestinationSelect, DescriptorConstants.NoIndex, 0, 0, false); + baseline.Images.Add(image); + baseline.Images.Add(image); + expected = changedField == 3 ? new ResourceSpecialization + { + BaseBufferCount = baseline.BaseBufferCount, Buffers = [.. baseline.Buffers], + Images = [.. baseline.Images], StableImageBindings = true, + } : baseline.Clone(); + switch (changedField) + { + case 0: expected.ImageDescriptorGroups.AddRange([0u, 0u]); break; + case 1: expected.SamplerDescriptorGroups.AddRange([0u, 0u]); break; + case 2: expected.Images[0] = expected.Images[0] with { MipStatistics = true }; break; + } + + ComputePrewarmRecord WithSpecialization(ResourceSpecialization specialization) => new() + { + Hash = seed.Hash, + CodeSize = seed.CodeSize, + Address = seed.Address, + ContinuationAddressOffset = seed.ContinuationAddressOffset, + UserDataBase = seed.UserDataBase, + UserDataCount = seed.UserDataCount, + PushDataCursor = seed.PushDataCursor, + Info = seed.Info, + SystemRegisters = seed.SystemRegisters, + Specialization = specialization, + }; + + var first = WithSpecialization(baseline); + var second = WithSpecialization(expected); + baselineIdentity = ShaderPrewarmList.Identity(first); + changedIdentity = ShaderPrewarmList.Identity(second); + Assert.NotEqual(baselineIdentity, changedIdentity); + list.RecordCompute(code, first); + list.RecordCompute(code, second); + list.RecordCompute(code, second); + } + + using var reloaded = Open(); + var loaded = reloaded.LoadedComputes(); + Assert.Equal(3, loaded.Count); // Seed plus the two distinct variants; duplicate remains deduplicated. + Assert.Contains(loaded, item => ShaderPrewarmList.Identity(item.Record) == baselineIdentity); + var restored = Assert.Single(loaded, item => ShaderPrewarmList.Identity(item.Record) == changedIdentity); + Assert.True(expected.Equals(restored.Record.Specialization)); + } + [Fact] public void RecordedReadsReplayAsMergedRanges() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderProgramCacheTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderProgramCacheTests.cs index a61c4ab06..fe8c90c36 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderProgramCacheTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderProgramCacheTests.cs @@ -92,6 +92,55 @@ public void EmbeddedFetchIsReplacedBeforeTheProgramRequestsResourceTables() Assert.Equal("SNop", request.Program.Instructions[0].Opcode); } + [Theory] + [InlineData(16u, 1)] + [InlineData(15u, 2)] + public void ImageAliasPartitionsReuseOnePermutationWhenUncoalescedDemandFits(uint imageLimit, int permutations) + { + _guest.Host.ComputeImageDescriptorLimits = ImageBindingTestProgram.Limits with { SampledImages = imageLimit }; + _guest.RegisterProgram(CodeA, HeaderA, ImageBindingTestProgram.Code()); + var ids = new List(); + foreach (var partition in ImageBindingTestProgram.Partitions) + { + ImageBindingTestProgram.WriteDescriptors(_guest, DataBase, partition); + var cursor = 0u; + var program = Compile(CodeA, [unchecked((uint)DataBase), (uint)(DataBase >> 32)], ref cursor, out var stage); + ids.Add(program.Id); + Assert.Equal(16, stage.Resources.Images.Length); + } + Assert.Equal(permutations, ids.Distinct().Count()); + Assert.Equal(permutations, Assert.Single(_guest.Programs.Entries).Permutations.Count); + Assert.Equal(permutations, _guest.Compiler.Requests.Count); + Assert.Equal(permutations, _guest.Host.Modules.Count); + } + + // A pixel program's images bind one per slot as a compute program's do, within the graphics budget; the compute + // budget does not admit it. + [Theory] + [InlineData(16u, 0u, 1)] + [InlineData(15u, 0u, 2)] + [InlineData(0u, 16u, 2)] + public void PixelImageAliasPartitionsReuseOnePermutationWhenTheGraphicsBudgetFits(uint graphicsLimit, uint computeLimit, + int permutations) + { + _guest.Host.GraphicsImageDescriptorLimits = ImageBindingTestProgram.Limits with { SampledImages = graphicsLimit }; + _guest.Host.ComputeImageDescriptorLimits = ImageBindingTestProgram.Limits with { SampledImages = computeLimit }; + _guest.RegisterProgram(CodeA, HeaderA, ImageBindingTestProgram.Code()); + var ids = new List(); + foreach (var partition in ImageBindingTestProgram.Partitions) + { + ImageBindingTestProgram.WriteDescriptors(_guest, DataBase, partition); + var cursor = 0u; + var program = _guest.Programs.GetOrCompile( + _guest.Source(CodeA, ShaderStage.Pixel, [unchecked((uint)DataBase), (uint)(DataBase >> 32)]), + new StageCompileOptions { PixelInfo = new PixelInputInfo(), PixelOutputs = [] }, ref cursor, out var stage); + ids.Add(program.Id); + Assert.Equal(16, stage.Resources.Images.Length); + } + Assert.Equal(permutations, ids.Distinct().Count()); + Assert.Equal(permutations, _guest.Compiler.Requests.Count); + } + private readonly FatalScope _fatal = new(); private readonly PipelineTestGuest _guest = new(); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/TranslationDiskCacheTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/TranslationDiskCacheTests.cs new file mode 100644 index 000000000..050be4e4f --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/TranslationDiskCacheTests.cs @@ -0,0 +1,186 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.IO.Compression; +using System.Security.Cryptography; +using System.Text; +using SharpEmu.Libs.Gpu; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Vulkan; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +[Collection(TranslationDiskCacheCollection.Name)] +public sealed class TranslationDiskCacheTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "SharpEmuTests", Guid.NewGuid().ToString("N")); + private readonly VulkanGuestGpuBackend _backend = new(); + + public TranslationDiskCacheTests() => TranslationDiskCache.UseGameFolder(_directory, "test-stamp"); + + public void Dispose() + { + TranslationDiskCache.UseGameFolder(null, null); + if (Directory.Exists(_directory)) + { + Directory.Delete(_directory, recursive: true); + } + } + + private static string Key(char digit) => new(digit, 64); + + [Theory] + [InlineData("SHARPEMU_TRANSLATION_CACHE", true)] + [InlineData("SHARPEMU_VK_PIPELINE_CACHE_PATH", true)] + [InlineData("SHARPEMU_SHADER_MODULE_DUMP", true)] + [InlineData("SHARPEMU_PROFILE_RENDER", true)] + [InlineData("sharpemu_log_agc", true)] + [InlineData("SHARPEMU_SHADER_OPTIMIZATIONS", false)] + [InlineData("SHARPEMU_BRANCHES_WITH_WRITES", false)] + public void PathsDumpsLogsAndProfilesStayOutOfTheKey(string name, bool ignored) => + Assert.Equal(ignored, TranslationDiskCache.IgnoredVariable(name)); + + [Theory] + [InlineData("SHARPEMU_CAPTURE_PIXEL_VGPR_ADDRESS", true)] + [InlineData("SHARPEMU_FORCE_TITLE_EARLY_COLOR", true)] + [InlineData("SHARPEMU_FORCE_PACKED_EXPORT_STORE_ONE", true)] + [InlineData("sharpemu_trace_packed_export_address", true)] + [InlineData("SHARPEMU_PREPARED_ADDRESS_RANGES", false)] + [InlineData("SHARPEMU_CRASH_CAPTURE", false)] + [InlineData("SHARPEMU_TRACE_MUTEX_ADDRESS", false)] + [InlineData("SHARPEMU_SHADER_OPTIMIZATIONS", false)] + public void OnlyTheTranslatorsAddressSwitchesPutTheAddressInTheKey(string name, bool selects) => + Assert.Equal(selects, TranslationDiskCache.AddressSelectsTranslation(name)); + + [Fact] + public void AStoredTranslationLoadsAsTheSameShader() + { + var shader = new VulkanCompiledGuestShader([1, 2, 3, 4]) { InputLocationMask = 0x5 }; + TranslationDiskCache.Store(Key('A'), shader); + + var loaded = TranslationDiskCache.TryLoad(Key('A'), _backend); + + Assert.NotNull(loaded); + Assert.Equal(shader.Payload, loaded.Payload); + Assert.Equal(0x5u, loaded.InputLocationMask); + } + + [Fact] + public void AnotherKeyOrADamagedEntryIsAMiss() + { + TranslationDiskCache.Store(Key('B'), new VulkanCompiledGuestShader([9, 8, 7, 6])); + Assert.Null(TranslationDiskCache.TryLoad(Key('C'), _backend)); + + var path = Path.Combine(TranslationDiskCache.Folder!, Key('B') + ".spvc"); + var bytes = File.ReadAllBytes(path); + bytes[^1] ^= 0xFF; + File.WriteAllBytes(path, bytes); + Assert.Null(TranslationDiskCache.TryLoad(Key('B'), _backend)); + } + + // A checksummed entry whose payload is shorter than its declared length is a miss. + [Theory] + [InlineData(1, 0)] + [InlineData(4, 3)] + [InlineData(64, 4)] + public void AChecksummedEntryWithAShortPayloadIsAMiss(int declaredLength, int actualLength) + { + var key = Key('D'); + WritePayloadEntry(key, declaredLength, Enumerable.Range(0, actualLength).Select(value => (byte)value).ToArray()); + + Assert.Null(TranslationDiskCache.TryLoad(key, _backend)); + } + + [Theory] + [InlineData(0, 0)] + [InlineData(4, 4)] + [InlineData(3, 4)] + public void ACompletePayloadKeepsItsExistingAdmissionContract(int declaredLength, int actualLength) + { + var key = Key('E'); + var payload = Enumerable.Range(0, actualLength).Select(value => (byte)value).ToArray(); + WritePayloadEntry(key, declaredLength, payload); + + var loaded = TranslationDiskCache.TryLoad(key, _backend); + + Assert.NotNull(loaded); + Assert.Equal(payload.Take(declaredLength).ToArray(), loaded.Payload); + Assert.Null(loaded.InputLocationMask); + } + + // A complete version-1 envelope with a valid checksum and compressed stream; the declared payload length varies + // independently of the bytes present. + private static void WritePayloadEntry(string key, int declaredLength, byte[] payload) + { + using var content = new MemoryStream(); + using (var writer = new BinaryWriter(content, Encoding.UTF8, leaveOpen: true)) + { + writer.Write(1); + writer.Write(key); + writer.Write(false); // No input location mask. + writer.Write(declaredLength); + writer.Write(payload); + } + + using var compressed = new MemoryStream(); + using (var zlib = new ZLibStream(compressed, CompressionLevel.Fastest, leaveOpen: true)) + { + zlib.Write(content.GetBuffer(), 0, (int)content.Length); + } + + var bytes = compressed.ToArray(); + File.WriteAllBytes(Path.Combine(TranslationDiskCache.Folder!, key + ".spvc"), [.. SHA256.HashData(bytes), .. bytes]); + } + + [Fact] + public void ABuildUsesItsOwnFolderAndKeepsOnlyTheNewestOtherBuild() + { + var game = Path.Combine(_directory, "game"); + Directory.CreateDirectory(game); + File.WriteAllBytes(Path.Combine(game, "flat.spvc"), [1]); + var now = DateTime.UtcNow; + foreach (var (name, hoursAgo) in new[] { ("old1", 30), ("old2", 20), ("old3", 10) }) + { + var build = Directory.CreateDirectory(Path.Combine(game, name)); + File.WriteAllBytes(Path.Combine(build.FullName, "entry.spvc"), [2]); + Directory.SetLastWriteTimeUtc(build.FullName, now.AddHours(-hoursAgo)); + } + + TranslationDiskCache.UseGameFolder(game, "another-stamp"); + + var current = TranslationDiskCache.Folder!; + Assert.Equal(game, Path.GetDirectoryName(current)); + Assert.True(Directory.Exists(current)); + Assert.True(Directory.Exists(Path.Combine(game, "old3"))); + Assert.False(Directory.Exists(Path.Combine(game, "old2"))); + Assert.False(Directory.Exists(Path.Combine(game, "old1"))); + Assert.False(File.Exists(Path.Combine(game, "flat.spvc"))); + } + + [Fact] + public void TrimDropsTheEntriesUsedLongestAgo() + { + Directory.CreateDirectory(_directory); + var now = DateTime.UtcNow; + foreach (var (name, hoursAgo) in new[] { ("a", 10), ("b", 9), ("c", 8), ("d", 7) }) + { + var path = Path.Combine(_directory, name + ".spvc"); + File.WriteAllBytes(path, new byte[100]); + File.SetLastWriteTimeUtc(path, now.AddHours(-hoursAgo)); + File.SetLastAccessTimeUtc(path, now.AddHours(-hoursAgo)); + } + + Assert.Equal(200, TranslationDiskCache.Trim(_directory, 100, 450, 300)); + Assert.False(File.Exists(Path.Combine(_directory, "a.spvc"))); + Assert.False(File.Exists(Path.Combine(_directory, "b.spvc"))); + Assert.True(File.Exists(Path.Combine(_directory, "d.spvc"))); + } +} + +// The cache's folder is process-wide: its tests run one at a time. +[CollectionDefinition(Name, DisableParallelization = true)] +public sealed class TranslationDiskCacheCollection +{ + public const string Name = "TranslationDiskCache"; +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/VertexPrewarmTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/VertexPrewarmTests.cs new file mode 100644 index 000000000..503632f91 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/VertexPrewarmTests.cs @@ -0,0 +1,392 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +// Vertex and mesh programs recorded in the prewarm side file with the pre-rasterization states their libraries were +// compiled with, and translated again from the record. +public sealed class VertexPrewarmTests : IDisposable +{ + private const ulong CodeAddress = PipelineTestGuest.MemoryBase + 0x1_0000; + private const ulong HeaderAddress = PipelineTestGuest.MemoryBase + 0x8000; + private const ulong DataBase = PipelineTestGuest.MemoryBase + 0x4_0000; + private const uint Format32x4Float = 77; + + // The attribute table load and the formatted fetch of attribute 0 that the embedded fetch replaces, then s_endpgm. + private static readonly uint[] EmbeddedFetchProgram = [0xF4080303, 0xFA000000, 0x02020B08, 0xE00C2000, 0x80030401, 0xBF810000]; + + private readonly string _directory = Path.Combine(Path.GetTempPath(), "SharpEmuTests", Guid.NewGuid().ToString("N")); + + public void Dispose() + { + if (Directory.Exists(_directory)) + { + Directory.Delete(_directory, recursive: true); + } + } + + private ShaderPrewarmList Open() => ShaderPrewarmList.Open(_directory) ?? throw new InvalidOperationException("The list did not open."); + + internal static byte[] Compile(ShaderCompileRequest request) + { + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + return shader.Spirv; + } + + private static ShaderCodeCapture Code(ulong hash, ulong continuationOffset = 0) => new() + { + Hash = hash, CodeSize = 12, Address = CodeAddress, Generation = Generation.Gen5, + Fused = continuationOffset == 0 + ? null + : new FusedCodeParts(HeaderAddress, CodeAddress + continuationOffset, HeaderAddress + 0x100), + Ranges = [new CodeRange(CodeAddress, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])], + }; + + private static VertexInputInfo EmbeddedFetchInfo(ulong buffer, uint stride, uint records) + { + var descriptor = PipelineTestGuest.BufferDescriptor(buffer, stride, records, Format32x4Float); + return new VertexInputInfo + { + FetchEmbedded = true, + FetchAttributeRegister = 4, + FetchBufferRegister = 6, + Attributes = [new VertexAttributeResource(new(descriptor[0], descriptor[1], descriptor[2], descriptor[3]), 4, 4, 0, 0, 0, 0)], + Buffers = [new VertexInputBuffer(buffer, stride, records)], + }; + } + + private static VertexPrewarmRecord VertexRecord(ShaderCodeCapture code, VertexInputInfo info) => new() + { + Hash = code.Hash, + CodeSize = code.CodeSize, + Address = code.Address, + UserDataBase = 0, + UserDataCount = 8, + PushDataCursor = 0, + VertexInfo = info, + RequiredVertexOutputCount = 2, + Specialization = new ResourceSpecialization(), + }; + + private static VertexPrewarmRecord MeshRecord(ShaderCodeCapture code) => new() + { + Mesh = true, + Hash = code.Hash, + CodeSize = code.CodeSize, + Address = code.Address, + ContinuationAddressOffset = 0x40, + UserDataBase = 2, + UserDataCount = 12, + PushDataCursor = 5, + MeshInfo = new MeshDrawConfiguration + { + Geometry = new GuestGeometryConfiguration + { + ThreadsPerGroup = 128, InputTriangleStrip = true, InputPrimitiveCountPerWorkgroup = 64, + InputVertexCountPerWorkgroup = 192, OutputVertexCapacity = 256, OutputPrimitiveCapacity = 128, ProvokingVertex = 2, + WaveSize = 32, IeeeMode = true, ScratchDwords = 7, LocalDataShareDwords = 1024, PositionExportControl = 3, + ClipSpace = new ClipSpaceTransform(true, 0.5f, -0.5f, 0.25f, 0.75f, 960, 540), + }, + Execution = new MeshExecutionLimits + { + DeviceSubgroupLaneCount = 32, MaxGroupCountX = 65535, MaxGroupCountY = 65535, MaxGroupTotalCount = 4194304, + }, + }, + RequiredVertexOutputCount = 4, + MeshOutputLocationMask = 0x13, + Specialization = new ResourceSpecialization { BaseBufferCount = 1, Buffers = [new BufferSpecialization(4, 0xFAC)] }, + DeviceRecordCounts = true, + }; + + private static PixelPrewarmRecord PixelRecord(ShaderCodeCapture code, uint userDataBase) => new() + { + Hash = code.Hash, + CodeSize = code.CodeSize, + Address = code.Address, + UserDataBase = userDataBase, + UserDataCount = 4, + PushDataCursor = 0, + Info = new PixelInputInfo { InputCount = 1 }, + Outputs = [new Gen5PixelOutputBinding(0, 0, Gen5PixelOutputKind.Float)], + InputEnable = 0x2, + InputAddress = 0x2, + Specialization = new ResourceSpecialization(), + }; + + [Fact] + public void AVertexRecordLeavesOutBufferAddressesAndRecordCounts() + { + var code = Code(0x1111); + var identity = ShaderPrewarmList.Identity(VertexRecord(code, EmbeddedFetchInfo(DataBase, 16, 4))); + Assert.Equal(identity, ShaderPrewarmList.Identity(VertexRecord(code, EmbeddedFetchInfo(DataBase + 0x1_0001_2340, 16, 900)))); + Assert.NotEqual(identity, ShaderPrewarmList.Identity(VertexRecord(code, EmbeddedFetchInfo(DataBase, 32, 4)))); + } + + // The same program met at another code address is one record. + [Fact] + public void ProgramsMetAtAnotherCodeAddressAreOneRecord() + { + var code = Code(0x1111); + var moved = new ShaderCodeCapture + { + Hash = code.Hash, CodeSize = code.CodeSize, Address = CodeAddress + 0x2000, Generation = Generation.Gen5, + Ranges = [new CodeRange(CodeAddress + 0x2000, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])], + }; + var pixel = PixelRecord(code, 1); + var movedPixel = PixelRecord(moved, 1); + var vertex = VertexRecord(code, EmbeddedFetchInfo(DataBase, 16, 4)); + var movedVertex = VertexRecord(moved, EmbeddedFetchInfo(DataBase, 16, 4)); + Assert.Equal(ShaderPrewarmList.Identity(pixel), ShaderPrewarmList.Identity(movedPixel)); + Assert.Equal(ShaderPrewarmList.Identity(vertex), ShaderPrewarmList.Identity(movedVertex)); + var state = new PreRasterizationState(0, 2, 1, false, false, true, false); + using (var list = Open()) + { + list.RecordPixel(code, pixel); + list.RecordPixel(moved, movedPixel); + list.RecordPreRasterization(list.RecordVertex(code, vertex), state); + Assert.Equal(list.RecordVertex(code, vertex), list.RecordVertex(moved, movedVertex)); + } + + using var reloaded = Open(); + Assert.Equal(1, reloaded.LoadedPixelCount); + var items = reloaded.LoadedGraphicsPrewarm(); + Assert.Equal(2, items.Count); + Assert.Equal(CodeAddress, Assert.IsType(items[0]).Record.Address); + Assert.Equal(CodeAddress, Assert.IsType(items[1]).Program.Address); + } + + // Items run by the time into their sessions at which they were first met, so a state a later session adds runs + // before the earlier session's later records instead of after all of them. + [Fact] + public void ALaterSessionsRecordsRunWhereThatSessionFirstMetThem() + { + var pixelCode = Code(0x1111); + var vertexCode = Code(0x2222); + var vertex = VertexRecord(vertexCode, EmbeddedFetchInfo(DataBase, 16, 4)); + var state = new PreRasterizationState(0, 2, 1, false, false, true, false); + using (var list = Open()) + { + list.SessionClock = () => 10; + list.RecordPixel(pixelCode, PixelRecord(pixelCode, 1)); + list.SessionClock = () => 100; + list.RecordPixel(pixelCode, PixelRecord(pixelCode, 2)); + } + + using (var list = Open()) + { + list.SessionClock = () => 50; + list.RecordPreRasterization(list.RecordVertex(vertexCode, vertex), state); + } + + using var reloaded = Open(); + Assert.Collection(reloaded.LoadedGraphicsPrewarm(), + item => Assert.Equal(1u, Assert.IsType(item).Record.UserDataBase), + item => Assert.Equal(state, Assert.IsType(item).State), + item => Assert.Equal(2u, Assert.IsType(item).Record.UserDataBase)); + // The prewarm pool schedules the items by their first uses. + Assert.Equal(new[] { 10f, 50f, 100f }, reloaded.LoadedGraphicsPrewarm().Select(static item => item.FirstUse)); + } + + [Fact] + public void PixelProgramsAndPreRasterizationStatesLoadInTheOrderTheyWereRecorded() + { + var pixelCode = Code(0x1111); + var vertexCode = Code(0x2222); + var meshCode = Code(0x3333, continuationOffset: 0x40); + var vertex = VertexRecord(vertexCode, EmbeddedFetchInfo(DataBase, 16, 4)); + var mesh = MeshRecord(meshCode); + var first = new PreRasterizationState(0, 2, 1, true, false, true, false); + var second = new PreRasterizationState(2, 0, 0, false, true, false, true); + using (var list = Open()) + { + list.RecordPixel(pixelCode, PixelRecord(pixelCode, 1)); + var vertexIdentity = list.RecordVertex(vertexCode, vertex); + list.RecordPreRasterization(vertexIdentity, first); + list.RecordPixel(pixelCode, PixelRecord(pixelCode, 2)); + var meshIdentity = list.RecordVertex(meshCode, mesh); + list.RecordPreRasterization(meshIdentity, second); + list.RecordPreRasterization(vertexIdentity, first); + // A state of a program the file does not hold is kept but left out of the prewarm. + list.RecordPreRasterization(0xDEAD, first); + Assert.Equal(vertexIdentity, list.RecordVertex(vertexCode, vertex)); + Assert.Equal(ShaderPrewarmList.Identity(mesh), meshIdentity); + } + + using var reloaded = Open(); + Assert.Equal(3, reloaded.LoadedPreRasterizationCount); + Assert.Collection(reloaded.LoadedGraphicsPrewarm(), + item => Assert.Equal(1u, Assert.IsType(item).Record.UserDataBase), + item => + { + var part = Assert.IsType(item); + Assert.Equal(first, part.State); + Assert.Equal(ShaderPrewarmList.Identity(vertex), ShaderPrewarmList.Identity(part.Program)); + var attribute = Assert.Single(part.Program.VertexInfo!.Attributes); + Assert.Equal(0u, attribute.Descriptor.Word0); + Assert.Equal(16u, attribute.Descriptor.Stride); + Assert.Equal(Format32x4Float, attribute.Descriptor.Format); + Assert.Equal(vertexCode.Ranges[0].Bytes, Assert.Single(part.Code.Ranges).Bytes); + }, + item => Assert.Equal(2u, Assert.IsType(item).Record.UserDataBase), + item => + { + var part = Assert.IsType(item); + Assert.Equal(second, part.State); + Assert.True(part.Program.Mesh); + Assert.Equal(mesh.MeshInfo, part.Program.MeshInfo); + Assert.Equal(mesh.MeshOutputLocationMask, part.Program.MeshOutputLocationMask); + Assert.Equal(0x40ul, part.Program.ContinuationAddressOffset); + Assert.True(part.Program.DeviceRecordCounts); + Assert.Equal(new BufferSpecialization(4, 0xFAC), Assert.Single(part.Program.Specialization.Buffers)); + Assert.Equal(ShaderPrewarmList.Identity(mesh), ShaderPrewarmList.Identity(part.Program)); + }); + } + + // The embedded fetch vertex program compiled by a program cache that records into the list, as a session's does: its + // prewarm identity, the session's SPIR-V and the host it compiled for. + internal static (ulong Identity, byte[] Spirv, IShaderPipelineHost Host) RecordEmbeddedFetchProgram(ShaderPrewarmList list) + { + var guest = new PipelineTestGuest(Compile); + guest.Host.ShaderPrewarm = list; + guest.RegisterProgram(CodeAddress, HeaderAddress, EmbeddedFetchProgram); + var cursor = 0u; + guest.Programs.GetOrCompile(guest.Source(CodeAddress, ShaderStage.Vertex, new uint[8]), + new StageCompileOptions { VertexInfo = EmbeddedFetchInfo(DataBase, 16, 4) }, ref cursor, out _); + var (_, identity) = Assert.Single(guest.Host.RecordedVertexPrograms); + return (identity, Assert.Single(guest.Compiler.Shaders).Spirv, guest.Host); + } + + [Fact] + public void ARecordedVertexProgramTranslatesToTheSameSpirvAfterReload() + { + byte[] runtime; + IShaderPipelineHost host; + var state = new PreRasterizationState(0, 0, 0, false, false, true, false); + using (var list = Open()) + { + (var identity, runtime, host) = RecordEmbeddedFetchProgram(list); + list.RecordPreRasterization(identity, state); + } + + using var reloaded = Open(); + var part = Assert.IsType(Assert.Single(reloaded.LoadedGraphicsPrewarm())); + Assert.Equal(state, part.State); + var compiler = new FakeShaderCompiler(Compile); + Assert.True(ShaderProgramCache.TryCompileVertexPrewarm(part.Program, part.Code, compiler, host, out var compiled, out var layout, + out var task, out var error), error); + Assert.Null(task); + Assert.NotNull(layout); + Assert.Single(Assert.IsType(compiled).Request.VertexInputs); + Assert.Equal(runtime, Assert.IsType(compiled).Spirv); + } + + // A vertex program compiled after pixel stages that end at different push cursors is one translation, whose push + // data takes the top of the range above every one of them; after a pixel stage its data does not fit beside, it + // reads the shader data block. The program reads a V# from user data, so it has shader data to place. + [Fact] + public void AVertexProgramIsOneTranslationForEveryPixelStageBeforeIt() + { + var guest = new PipelineTestGuest(Compile); + guest.RegisterProgram(CodeAddress, HeaderAddress, PipelineTestGuest.FormatLoadProgram); + var userData = PipelineTestGuest.BufferDescriptor(DataBase, 16, 4, Format32x4Float); + var options = new StageCompileOptions { VertexInfo = new VertexInputInfo() }; + var ids = new List(); + BindingLayout? first = null; + var pixelEnds = new List { 0 }; + for (var index = 0; index < pixelEnds.Count; index++) + { + var pixelEnd = pixelEnds[index]; + var cursor = pixelEnd; + var handle = guest.Programs.GetOrCompile(guest.Source(CodeAddress, ShaderStage.Vertex, userData), options, ref cursor, + out var stage); + ids.Add(handle.Id); + var layout = stage.Program!.Bindings!; + if (first is null) + { + // The last cursors the data fits above: the middle of the room and its end. + first = layout; + Assert.True(layout.ShaderDataDwordCount is > 0 and < PushData.DwordCount, $"data={layout.ShaderDataDwordCount}"); + pixelEnds.Add((PushData.DwordCount - layout.ShaderDataDwordCount) / 2); + pixelEnds.Add(PushData.DwordCount - layout.ShaderDataDwordCount); + } + + Assert.True(layout.UsesPushData, $"cursor={pixelEnd} data={layout.ShaderDataDwordCount} start={layout.PushDataStartDword}"); + Assert.Equal(PushData.DwordCount - layout.ShaderDataDwordCount, layout.PushDataStartDword); + Assert.True(layout.PushDataStartDword >= pixelEnd); + Assert.Equal(PushData.DwordCount, cursor); + } + + Assert.Equal(3, ids.Count); + Assert.All(ids, id => Assert.Equal(ids[0], id)); + Assert.Single(guest.Compiler.Shaders); + + var late = PushData.DwordCount - first!.ShaderDataDwordCount + 1; + var lateHandle = guest.Programs.GetOrCompile(guest.Source(CodeAddress, ShaderStage.Vertex, userData), options, ref late, + out var lateStage); + Assert.NotEqual(ids[0], lateHandle.Id); + Assert.False(lateStage.Program!.Bindings!.UsesPushData); + Assert.Equal(2, guest.Compiler.Shaders.Count); + } + + internal static readonly MeshShaderLimits TaskMeshLimits = new(128, 256, 256, 28672, 65535, 65535, 1u << 22, 128, 32768, 49152, + 1, 1, 128); + + // A task-launched mesh program (s_endpgm) compiled by a program cache that records into the list, as a session's does: its + // prewarm identity, the task launch of its program and the host it compiled for. + internal static (ulong Identity, MeshTaskLaunchInfo? Task, IShaderPipelineHost Host) RecordTaskLaunchedMeshProgram( + ShaderPrewarmList list) + { + var guest = new PipelineTestGuest(Compile); + guest.Host.ShaderPrewarm = list; + guest.Host.MeshShadersSupported = true; + guest.Host.MeshLimits = TaskMeshLimits; + guest.RegisterProgram(CodeAddress, HeaderAddress, PipelineTestGuest.EndProgram); + var options = new StageCompileOptions + { + MeshInfo = new MeshDrawConfiguration + { + Execution = new MeshExecutionLimits { DeviceSubgroupLaneCount = 32 }, + Geometry = new GuestGeometryConfiguration + { + WaveSize = 32, ThreadsPerGroup = 32, OutputVertexCapacity = 3, OutputPrimitiveCapacity = 1, + InputPrimitiveCountPerWorkgroup = 4, InputVertexCountPerWorkgroup = 3, InputPointList = true, TaskLaunched = true, + }, + }, + }; + var cursor = 0u; + guest.Programs.GetOrCompile(guest.Source(CodeAddress, ShaderStage.Mesh, []), options, ref cursor, out var stage); + var (_, identity) = Assert.Single(guest.Host.RecordedVertexPrograms); + return (identity, stage.Program!.MeshTask, guest.Host); + } + + // A task-launched mesh program is recorded as any other mesh program, and translated again from its record it takes + // the task launch its session's pipelines specialize the generic task stage with. + [Fact] + public void ATaskLaunchedMeshProgramIsRecordedWithItsSessionsTaskLaunch() + { + var state = new PreRasterizationState(0, 0, 0, false, false, true, false); + MeshTaskLaunchInfo? runtime; + IShaderPipelineHost host; + using (var list = Open()) + { + (var identity, runtime, host) = RecordTaskLaunchedMeshProgram(list); + list.RecordPreRasterization(identity, state); + } + + Assert.Equal(new MeshTaskLaunchInfo(4, true), runtime); + using var reloaded = Open(); + var part = Assert.IsType(Assert.Single(reloaded.LoadedGraphicsPrewarm())); + Assert.True(ShaderProgramCache.TryCompileVertexPrewarm(part.Program, part.Code, new FakeShaderCompiler(Compile), host, + out var compiled, out _, out var task, out var error), error); + Assert.NotNull(compiled); + Assert.Equal(runtime, task); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs index 0a573b4a2..21e82b5c0 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs @@ -23,9 +23,9 @@ public sealed class DispatchChainTests : IDisposable public void Dispose() => _fatal.Dispose(); - private static BufferResourceInfo Written => new(false, true, false, false, false, 4, 0); + private static BufferResourceInfo Written => new(false, true, false, false, false, 4); - private static BufferResourceInfo Read => new(true, false, false, false, false, 4, 0); + private static BufferResourceInfo Read => new(true, false, false, false, false, 4); private void Dispatch(ulong submitId, BufferResourceInfo[] buffers, uint[][] descriptors) { @@ -35,6 +35,57 @@ private void Dispatch(ulong submitId, BufferResourceInfo[] buffers, uint[][] des private int HazardBarriers => _host.Calls.Count(call => call == "write_hazard_barrier"); + [Theory] + [InlineData(false)] + [InlineData(true)] + public void RuntimeCalleeAccessesKeepTheBarrierOnEitherSideOfTheChain(bool calleeFirst) + { + var caller = new ShaderProgramInfo + { + Stage = ShaderStageKind.Compute, + Buffers = [Written], + UsesDeviceAddresses = true, + CallRecordCallees = [new CallRecordCallee([], [], 16)], + }; + var hidden = new ShaderStageResources(caller, new ResourceSnapshot + { + Buffers = [BufferDescriptor(BufferB, 4, 16)], + // A nonempty ordinary range list must not hide the missing callee accesses. + DeviceAddressRanges = [new(1, BufferB, 64, true, true)], + }) + { + CallRecords = [(0x1000, BufferA)], + }; + DispatchWithHiddenAccesses(hidden, calleeFirst); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void BindlessImageAccessesKeepTheBarrierOnEitherSideOfTheChain(bool heapFirst) + { + // The heap may read an image written by a previous dispatch, or write an image + // the next dispatch reads. Neither image is in the caller's explicit image list. + var caller = new ShaderProgramInfo + { + Stage = ShaderStageKind.Compute, + Buffers = [Written], + Bindings = new BindingLayout { UsesBindlessHeap = true }, + }; + DispatchWithHiddenAccesses(Stage(caller, [BufferDescriptor(BufferB, 4, 16)]), heapFirst); + } + + private void DispatchWithHiddenAccesses(ShaderStageResources hidden, bool hiddenFirst) + { + var ordinary = Stage(Program(ShaderStageKind.Compute, buffers: [Written]), [BufferDescriptor(BufferA, 4, 16)]); + _pipelines.Compute = ComputeProgram(hiddenFirst ? hidden : ordinary); + _executor.Dispatch(1, Banks(), 1, 1, 1, 0x41); + _pipelines.Compute = ComputeProgram(hiddenFirst ? ordinary : hidden); + _executor.Dispatch(2, Banks(), 1, 1, 1, 0x41); + + Assert.Equal(2, HazardBarriers); + } + [Fact] public void DisjointDispatchesShareOneHazardBarrierAndDeferTheirAccessBarriers() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/EmbeddedVertexOffsetTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/EmbeddedVertexOffsetTests.cs index e597dce4b..0505e85b6 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/EmbeddedVertexOffsetTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/EmbeddedVertexOffsetTests.cs @@ -3,6 +3,7 @@ using SharpEmu.Libs.Gpu.GpuCommands; using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Tests.Gpu.GpuCommands; using SharpEmu.Libs.Tests.Gpu.Scheduling; using Xunit; using static SharpEmu.Libs.Tests.Gpu.Rendering.RenderExecutorFixtures; @@ -118,4 +119,80 @@ public void InstanceOffset_ComesFromItsOwnRegisterAndKeepsTheVertexOffset() Assert.Equal(8, RenderExecutor.ResolveVertexOffset(0, input)); Assert.Equal(3u, RenderExecutor.ResolveInstanceOffset(input)); } + + // A vertex program whose fetch adds s20 to its vertex index and s21 to its instance index. + private static VertexInputInfo OffsetRegisterInput(uint vertexOffset, uint instanceOffset, bool fetchEmbedded) + { + var userData = new uint[14]; + userData[20 - UserDataBase] = vertexOffset; + userData[21 - UserDataBase] = instanceOffset; + var program = Program(ShaderStageKind.Vertex, userDataBase: UserDataBase, vertexOffsetScalar: 20, instanceOffsetScalar: 21); + return new VertexInputInfo + { + Buffers = [new VertexInputBuffer(VertexBase, 16, 64)], + Attributes = [Attribute(0, 0, 4)], + FetchEmbedded = fetchEmbedded, + Stage = new ShaderStageResources(program, new ResourceSnapshot { UserData = userData }, VertexShader), + }; + } + + // The packet names 0xA9 for the base vertex and 0xA8 for the start instance (0x280 names none); the arguments hold 8 + // and 3. A named value reaches the program in its register, and a fetch the host replaced reads it from there; a program + // that fetches itself adds it in its own code, so its draw counts from 0. Values the packet names no register for stay in + // the draw's arguments. + [Theory] + [InlineData(true, true, true, "draw_indexed 3 1 0 8 3")] + [InlineData(false, true, true, "draw 3 1 8 3")] + [InlineData(true, false, true, "draw_indexed 3 1 0 0 0")] + [InlineData(false, false, true, "draw 3 1 0 0")] + [InlineData(true, true, false, "draw_indexed 3 1 0 8 3")] + [InlineData(false, true, false, "draw 3 1 8 3")] + public void IndirectDraw_OffsetsInNamedRegistersReachAReplacedFetch(bool indexed, bool fetchEmbedded, bool namesRegisters, string expected) + { + using var fatal = new FatalScope(); + var runner = new StreamRunner(); + runner.Host.WriteWords(StreamRunner.TableAddress, indexed ? new uint[] { 3, 1, 0, 8, 3 } : new uint[] { 3, 1, 8, 3 }); + var vertexRegister = namesRegisters ? 0xA9u : 0x280u; + var instanceRegister = namesRegisters ? 0xA8u : 0x280u; + var setBase = StreamRunner.Packet(PacketOpcode.SetBase, 1, StreamRunner.Low(StreamRunner.TableAddress), StreamRunner.High(StreamRunner.TableAddress)); + if (indexed) + { + runner.Run( + setBase, + StreamRunner.Packet(PacketOpcode.IndexBase, StreamRunner.Low(StreamRunner.DataAddress), StreamRunner.High(StreamRunner.DataAddress)), + StreamRunner.Packet(PacketOpcode.IndexType, 0), + StreamRunner.Packet(PacketOpcode.IndexBufferSize, 40), + StreamRunner.Packet(PacketOpcode.DrawIndexIndirect, 0, vertexRegister, instanceRegister, 0x22)); + } + else + { + runner.Run(setBase, StreamRunner.Packet(PacketOpcode.DrawIndirect, 0, vertexRegister, instanceRegister, 2)); + } + + // The program's s20 and s21 are the registers the packet named, or hold unrelated values when it named none. + var input = namesRegisters + ? OffsetRegisterInput(runner.Interpreter.Registers.Shader[0xA9], runner.Interpreter.Registers.Shader[0xA8], fetchEmbedded) + : OffsetRegisterInput(5, 7, fetchEmbedded); + var host = new RecordingRenderHost(); + var defaults = Programs(); + var provider = new FakePipelineProvider + { + Graphics = new GraphicsPrograms + { + Vertex = defaults.Vertex, Pixel = defaults.Pixel, + VertexInput = input, PixelInput = defaults.PixelInput, + }, + }; + var executor = new RenderExecutor(host, provider); + if (indexed) + { + executor.DrawIndexed(1, Banks(), Assert.Single(runner.Host.IndexedDraws) with { IndexAddress = IndexBase }); + } + else + { + executor.DrawAuto(1, Banks(), Assert.Single(runner.Host.AutoDraws)); + } + + Assert.Contains(expected, host.Calls); + } } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/LinkedModuleWaitTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/LinkedModuleWaitTests.cs new file mode 100644 index 000000000..fa271ac14 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/LinkedModuleWaitTests.cs @@ -0,0 +1,51 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Diagnostics; +using SharpEmu.Libs.Gpu.Rendering; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Rendering; + +public sealed class LinkedModuleWaitTests +{ + [Fact] + public void A_module_that_compiles_within_the_bound_is_waited_for() + { + var compile = Task.Delay(50); + Assert.True(RenderExecutor.WaitForLinkedModule(() => compile.IsCompleted, () => compile, Stopwatch.Frequency * 5)); + } + + [Fact] + public void A_module_still_compiling_at_the_bound_is_left_to_the_skip() + { + var compile = new TaskCompletionSource().Task; + var started = Stopwatch.GetTimestamp(); + Assert.False(RenderExecutor.WaitForLinkedModule(() => false, () => compile, Stopwatch.Frequency / 20)); + Assert.True(Stopwatch.GetElapsedTime(started) < TimeSpan.FromSeconds(2)); + } + + [Fact] + public void Without_a_completion_the_wait_polls_until_ready() + { + var polls = 0; + Assert.True(RenderExecutor.WaitForLinkedModule(() => ++polls >= 3, () => null, Stopwatch.Frequency * 5)); + Assert.Equal(3, polls); + } + + [Fact] + public void A_completed_compile_whose_pipeline_is_not_ready_polls_with_sleeps() + { + var polls = 0; + Assert.False(RenderExecutor.WaitForLinkedModule(() => { polls++; return false; }, () => Task.CompletedTask, Stopwatch.Frequency / 20)); + // About one poll per millisecond of the 50 ms bound, not a spin. + Assert.InRange(polls, 1, 200); + } + + [Fact] + public void A_failed_compile_ends_the_wait_without_throwing() + { + var compile = Task.FromException(new InvalidOperationException("compile failed")); + Assert.False(RenderExecutor.WaitForLinkedModule(() => false, () => compile, Stopwatch.Frequency / 20)); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorAdaptationTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorAdaptationTests.cs index 282245a6d..fb743719c 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorAdaptationTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorAdaptationTests.cs @@ -1,6 +1,7 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using SharpEmu.Libs.Gpu.GpuCommands; using SharpEmu.Libs.Gpu.GpuCommands.Registers; using SharpEmu.Libs.Gpu.Images; using SharpEmu.Libs.Gpu.Rendering; @@ -178,6 +179,55 @@ public void MetadataClearQuad_WithAnImageInThePixelProgram_Draws() Assert.Contains(_host.Calls, call => call.StartsWith("draw 4", StringComparison.Ordinal)); } + private const ulong IndirectArguments = RecordingRenderHost.MemoryBase + 0x60_0000; + + private DrawAutoArguments IndirectAuto(uint count) + { + var bytes = new byte[16]; + BitConverter.TryWriteBytes(bytes.AsSpan(0), count); + BitConverter.TryWriteBytes(bytes.AsSpan(4), 1u); + _host.WriteGuest(IndirectArguments, bytes); + return Auto(0, source: DrawOffsetSource.IndirectArguments) with { IndirectArgumentsAddress = IndirectArguments }; + } + + // An indirect strip whose state may make it a metadata clear quad reads its count and positions on the CPU and is + // dropped as a direct one is. + [Fact] + public void IndirectMetadataClearQuad_ReadsItsCountOnTheCpuAndIsDropped() + { + var banks = MetadataQuadBanks(); + _executor.DrawAuto(1, banks, IndirectAuto(4)); + + Assert.DoesNotContain(_host.Calls, call => call.StartsWith("draw", StringComparison.Ordinal)); + Assert.Equal(1 + 4, _host.GuestReads); + } + + // The same state with another count draws what it read, and a strip whose state cannot be a metadata clear quad (here + // an ordinary blend, or no DCC) lets the GPU read its arguments. + [Theory] + [InlineData(6u, false, true, "draw 6")] + [InlineData(4u, true, true, "draw_indirect")] + [InlineData(4u, false, false, "draw_indirect")] + public void IndirectStrip_ReadsItsCountOnlyWhenItMayBeAMetadataClearQuad(uint count, bool ordinaryBlend, bool dcc, string expected) + { + var banks = MetadataQuadBanks(); + if (ordinaryBlend) + { + banks.Context.BlendControls[0] = new BlendRegisters { Enable = true, ColorSourceFactor = 4, ColorDestinationFactor = 5 }; + } + + if (!dcc) + { + var words = banks.Context.ColorTargets[0]; + banks.Context.ColorTargets[0] = words with { Info = words.Info & ~DccEnabledBit }; + } + + _executor.DrawAuto(1, banks, IndirectAuto(count)); + + Assert.Contains(_host.Calls, call => call.StartsWith(expected, StringComparison.Ordinal)); + Assert.Equal(expected == "draw_indirect" ? 0 : 1, _host.GuestReads); + } + private RegisterBanks TargetlessBanks() { var banks = Banks(); @@ -230,7 +280,7 @@ public void TargetlessDrawThatWritesAStorageImage_IsNeverRetained() public void TargetlessDrawWithImagesAndBufferWrites_IsNeverRetained(bool vertexWrites, bool atomic) { _host.RetainTargetlessDraws = true; - var written = new BufferResourceInfo(false, true, atomic, false, false, 4, 0); + var written = new BufferResourceInfo(false, true, atomic, false, false, 4); var vertex = Stage(Program(ShaderStageKind.Vertex, buffers: vertexWrites ? [written] : []), buffers: vertexWrites ? [BufferDescriptor(VertexBase, 4, 16)] : []); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorComputeTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorComputeTests.cs index 117917a8b..f46837277 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorComputeTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorComputeTests.cs @@ -106,6 +106,8 @@ public async Task PendingPipeline_WaitsWithoutPolling() [Fact] public void LinkedProgram_SkipsItsDispatchWhileTheModuleCompiles() { + // With no linked compile wait, the dispatch is skipped at once. + _executor.LinkedCompileWait = 0; var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); _pipelines.PendingComputeCompletion = completion.Task; var program = new ShaderProgramInfo { Stage = ShaderStageKind.Compute, Hash = 0x1234, Bindings = new BindingLayout { CallTargetCount = 1 } }; @@ -122,8 +124,135 @@ public void LinkedProgram_SkipsItsDispatchWhileTheModuleCompiles() AssertDispatched(4, 2, 1); } - private static BufferResourceInfo ClearResource(bool read = false, bool formatted = true, bool written = true, uint maxByteExtent = 16, uint packedStride = 16) => - new(read, written, false, formatted, false, maxByteExtent, packedStride); + [Fact] + public void LinkedProgram_WaitsForAModuleThatCompilesWithinTheBound() + { + _executor.LinkedCompileWait = System.Diagnostics.Stopwatch.Frequency * 5; + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _pipelines.PendingComputeCompletion = completion.Task; + var program = new ShaderProgramInfo { Stage = ShaderStageKind.Compute, Hash = 0x1235, Bindings = new BindingLayout { CallTargetCount = 1 } }; + _pipelines.Compute = ComputeProgram(Stage(program)); + _ = Task.Run(async () => + { + await Task.Delay(50); + completion.SetResult(); + }); + _executor.Dispatch(5, Banks(), 4, 2, 1, 0x41); + AssertDispatched(4, 2, 1); + } + + [Fact] + public void LinkedProgram_WhoseCompileOutlastsTheBoundIsSkippedWithoutAnotherWait() + { + _executor.LinkedCompileWait = System.Diagnostics.Stopwatch.Frequency / 20; + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _pipelines.PendingComputeCompletion = completion.Task; + var program = new ShaderProgramInfo { Stage = ShaderStageKind.Compute, Hash = 0x1236, Bindings = new BindingLayout { CallTargetCount = 1 } }; + _pipelines.Compute = ComputeProgram(Stage(program)); + _executor.Dispatch(5, Banks(), 4, 2, 1, 0x41); + AssertNotDispatched(); + var attempts = _pipelines.ComputePipelineAttempts; + Assert.True(attempts > 1); + + _executor.Dispatch(6, Banks(), 4, 2, 1, 0x41); + AssertNotDispatched(); + Assert.Equal(attempts + 1, _pipelines.ComputePipelineAttempts); + + completion.SetResult(); + _executor.Dispatch(7, Banks(), 4, 2, 1, 0x41); + AssertDispatched(4, 2, 1); + } + + [Fact] + public void LinkedProgram_KnownToCompileForMinutes_WaitsOnlyTheShortBound() + { + // A session recorded the program slow, so the 5 s bound is not spent on a compile that outlasts it. + _executor.LinkedCompileWait = System.Diagnostics.Stopwatch.Frequency * 5; + _executor.KnownSlowLinkedCompileWait = System.Diagnostics.Stopwatch.Frequency / 20; + _pipelines.PendingComputeCompletion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously).Task; + var program = new ShaderProgramInfo { Stage = ShaderStageKind.Compute, Hash = 0x1237, Bindings = new BindingLayout { CallTargetCount = 1 } }; + _pipelines.SlowLinkedPrograms.Add(program.Hash); + _pipelines.Compute = ComputeProgram(Stage(program)); + _executor.SlowLinkedCompileRecordTicks = System.Diagnostics.Stopwatch.Frequency / 10; + var started = System.Diagnostics.Stopwatch.GetTimestamp(); + _executor.Dispatch(5, Banks(), 4, 2, 1, 0x41); + AssertNotDispatched(); + Assert.True(System.Diagnostics.Stopwatch.GetElapsedTime(started) < TimeSpan.FromSeconds(2)); + + // Still compiling past the record threshold: already known, so nothing new is recorded. + Thread.Sleep(150); + _executor.Dispatch(6, Banks(), 4, 2, 1, 0x41); + AssertNotDispatched(); + Assert.Empty(_pipelines.RecordedLinkedCompiles); + } + + [Fact] + public void LinkedProgram_KnownSlowButReadyWithinTheShortBound_IsDispatched() + { + // A module created from stored data is ready within the short bound: the dispatch runs and nothing is recorded. + _executor.LinkedCompileWait = System.Diagnostics.Stopwatch.Frequency * 5; + _executor.KnownSlowLinkedCompileWait = System.Diagnostics.Stopwatch.Frequency * 2; + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _pipelines.PendingComputeCompletion = completion.Task; + var program = new ShaderProgramInfo { Stage = ShaderStageKind.Compute, Hash = 0x1238, Bindings = new BindingLayout { CallTargetCount = 1 } }; + _pipelines.SlowLinkedPrograms.Add(program.Hash); + _pipelines.Compute = ComputeProgram(Stage(program)); + _ = Task.Run(async () => + { + await Task.Delay(20); + completion.SetResult(); + }); + _executor.Dispatch(5, Banks(), 4, 2, 1, 0x41); + AssertDispatched(4, 2, 1); + Assert.Empty(_pipelines.RecordedLinkedCompiles); + } + + [Fact] + public void LinkedProgram_StillCompilingAfterTheRecordThreshold_IsRecordedSlowOnce() + { + _executor.LinkedCompileWait = System.Diagnostics.Stopwatch.Frequency / 50; + _executor.SlowLinkedCompileRecordTicks = System.Diagnostics.Stopwatch.Frequency / 10; + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _pipelines.PendingComputeCompletion = completion.Task; + var program = new ShaderProgramInfo { Stage = ShaderStageKind.Compute, Hash = 0x1239, Bindings = new BindingLayout { CallTargetCount = 1 } }; + _pipelines.Compute = ComputeProgram(Stage(program)); + _executor.Dispatch(5, Banks(), 4, 2, 1, 0x41); + AssertNotDispatched(); + Assert.Empty(_pipelines.RecordedLinkedCompiles); + + Thread.Sleep(150); + _executor.Dispatch(6, Banks(), 4, 2, 1, 0x41); + _executor.Dispatch(7, Banks(), 4, 2, 1, 0x41); + AssertNotDispatched(); + Assert.Equal(new[] { (program.Hash, true) }, _pipelines.RecordedLinkedCompiles); + + completion.SetResult(); + _executor.Dispatch(8, Banks(), 4, 2, 1, 0x41); + AssertDispatched(4, 2, 1); + Assert.Single(_pipelines.RecordedLinkedCompiles); + } + + [Fact] + public void LinkedProgram_KnownSlowWhoseCompileEndsWithinTheNormalBound_IsRecordedFastAgain() + { + _executor.LinkedCompileWait = System.Diagnostics.Stopwatch.Frequency * 5; + _executor.KnownSlowLinkedCompileWait = System.Diagnostics.Stopwatch.Frequency / 50; + var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _pipelines.PendingComputeCompletion = completion.Task; + var program = new ShaderProgramInfo { Stage = ShaderStageKind.Compute, Hash = 0x123A, Bindings = new BindingLayout { CallTargetCount = 1 } }; + _pipelines.SlowLinkedPrograms.Add(program.Hash); + _pipelines.Compute = ComputeProgram(Stage(program)); + _executor.Dispatch(5, Banks(), 4, 2, 1, 0x41); + AssertNotDispatched(); + + completion.SetResult(); + _executor.Dispatch(6, Banks(), 4, 2, 1, 0x41); + AssertDispatched(4, 2, 1); + Assert.Equal(new[] { (program.Hash, false) }, _pipelines.RecordedLinkedCompiles); + } + + private static BufferResourceInfo ClearResource(bool read = false, bool formatted = true, bool written = true, uint maxByteExtent = 16) => + new(read, written, false, formatted, false, maxByteExtent); private static uint[] ClearUserData(uint[] descriptor, uint value, uint last = ClearValue) => [descriptor[0], descriptor[1], descriptor[2], descriptor[3], value, value, value, last]; @@ -242,7 +371,7 @@ public void ThreadDimensionInitiator_WithNoThreads_IsSkippedBeforeTheProgramLook [Fact] public void StorageWrites_InsertTheHazardBarrierBeforeThePipelineBind() { - var written = new BufferResourceInfo(false, true, false, false, false, 4, 0); + var written = new BufferResourceInfo(false, true, false, false, false, 4); _pipelines.Compute = ComputeProgram(Stage(Program(ShaderStageKind.Compute, buffers: [written]), buffers: [BufferDescriptor(VertexBase, 4, 16)])); _executor.Dispatch(1, Banks(), 1, 1, 1, 0x41); Assert.True(_host.Calls.IndexOf("write_hazard_barrier") < _host.Calls.IndexOf("bind_pipeline Compute C1")); @@ -335,8 +464,8 @@ private void ConfigureLoadedValueFill(uint records, ulong valueAddress, uint val var source = BufferDescriptor(valueAddress, 0, 1); var program = Program(ShaderStageKind.Compute, buffers: [ - new BufferResourceInfo(Read: true, Written: false, Atomic: false, Formatted: false, Scalar: true, MaxByteExtent: 4, PackedStride: 0), - ClearResource(maxByteExtent: 4, packedStride: 4), + new BufferResourceInfo(Read: true, Written: false, Atomic: false, Formatted: false, Scalar: true, MaxByteExtent: 4), + ClearResource(maxByteExtent: 4), ]); _pipelines.Compute = ComputeProgram(Stage(program, buffers: [source, target], userData: [.. target, .. source])); } @@ -384,10 +513,10 @@ public void PartialDispatch_RefusesTheClearAndRunsTheDispatch() { "read-modify-write", ClearResource(read: true), BufferDescriptor(MetadataAddress, 16, 256) }, { "unformatted", ClearResource(formatted: false), BufferDescriptor(MetadataAddress, 16, 256) }, { "narrow extent", ClearResource(maxByteExtent: 4), BufferDescriptor(MetadataAddress, 16, 256) }, - { "stride mismatch", ClearResource(packedStride: 8), BufferDescriptor(MetadataAddress, 8, 256) }, + { "stride mismatch", ClearResource(), BufferDescriptor(MetadataAddress, 8, 256) }, { "other format", ClearResource(), BufferDescriptor(MetadataAddress, 16, 256, format: 10) }, - { "swizzled", ClearResource(packedStride: 16 | (1u << 14)), BufferDescriptor(MetadataAddress, 16, 256, swizzle: true) }, - { "thread id added", ClearResource(packedStride: 16 | (1u << 20)), BufferDescriptor(MetadataAddress, 16, 256, addThreadId: true) }, + { "swizzled", ClearResource(), BufferDescriptor(MetadataAddress, 16, 256, swizzle: true) }, + { "thread id added", ClearResource(), BufferDescriptor(MetadataAddress, 16, 256, addThreadId: true) }, }; [Theory] @@ -447,7 +576,7 @@ public void MetadataClear_ConsumesAWrittenBufferOverClearableMetadata() { _host.MetadataAddresses.Add(MetadataAddress); _host.ClearableMetadata.Add(MetadataAddress); - var written = new BufferResourceInfo(false, true, false, false, false, 4, 0); + var written = new BufferResourceInfo(false, true, false, false, false, 4); _pipelines.Compute = ComputeProgram(Stage(Program(ShaderStageKind.Compute, buffers: [written]), buffers: [BufferDescriptor(MetadataAddress, 4, 16)])); _executor.Dispatch(1, Banks(), 4, 1, 1, 0x41); @@ -461,7 +590,7 @@ public void MetadataClear_RefusesAReadModifyWriteKernelOverMetadata() { _host.MetadataAddresses.Add(MetadataAddress); _host.ClearableMetadata.Add(MetadataAddress); - var readWrite = new BufferResourceInfo(true, true, false, false, false, 4, 0); + var readWrite = new BufferResourceInfo(true, true, false, false, false, 4); _pipelines.Compute = ComputeProgram(Stage(Program(ShaderStageKind.Compute, buffers: [readWrite]), buffers: [BufferDescriptor(MetadataAddress, 4, 16)])); _executor.Dispatch(1, Banks(), 4, 1, 1, 0x41); @@ -473,7 +602,7 @@ public void MetadataClear_RefusesAReadModifyWriteKernelOverMetadata() public void MetadataClear_RefusesAProgramWithBitwiseExclusiveOr() { _host.ClearableMetadata.Add(MetadataAddress); - var written = new BufferResourceInfo(false, true, false, false, false, 4, 0); + var written = new BufferResourceInfo(false, true, false, false, false, 4); _pipelines.Compute = ComputeProgram(Stage(Program(ShaderStageKind.Compute, buffers: [written], exclusiveOr: true), buffers: [BufferDescriptor(MetadataAddress, 4, 16)])); _executor.Dispatch(1, Banks(), 4, 1, 1, 0x41); @@ -484,7 +613,7 @@ public void MetadataClear_RefusesAProgramWithBitwiseExclusiveOr() [Fact] public void MetadataClear_WithAMismatchedBufferCountIsFatal() { - var written = new BufferResourceInfo(false, true, false, false, false, 4, 0); + var written = new BufferResourceInfo(false, true, false, false, false, 4); _pipelines.Compute = ComputeProgram(Stage(Program(ShaderStageKind.Compute, buffers: [written]))); var fatal = Assert.Throws(() => _executor.Dispatch(1, Banks(), 4, 1, 1, 0x41)); Assert.Contains("descriptors=0 program=1", fatal.Message); @@ -493,7 +622,7 @@ public void MetadataClear_WithAMismatchedBufferCountIsFatal() [Fact] public void ShortBufferDescriptor_IsFatal() { - var written = new BufferResourceInfo(false, true, false, false, false, 4, 0); + var written = new BufferResourceInfo(false, true, false, false, false, 4); _pipelines.Compute = ComputeProgram(Stage(Program(ShaderStageKind.Compute, buffers: [written]), buffers: [[1, 2]])); var fatal = Assert.Throws(() => _executor.Dispatch(1, Banks(), 4, 1, 1, 0x41)); Assert.Contains("index=0 words=2", fatal.Message); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorDrawTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorDrawTests.cs index c06c759a2..0070c1ad5 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorDrawTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorDrawTests.cs @@ -143,6 +143,58 @@ public void ADrawAfterATwoTargetDrawBindsOnlyItsOwnTarget() private const ulong IndirectArguments = RecordingRenderHost.MemoryBase + 0x60_0000; + // A GPU-culled automatic draw of a mesh program reads its counts on the GPU; without the + // indirect mesh command it reads them here and draws from them. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void AutoIndirectMeshDrawReadsItsArgumentsOnTheGpu(bool gpuIndirect) + { + _host.SupportsIndirectMeshDraw = gpuIndirect; + _pipelines.MeshShadersSupported = true; + _pipelines.Graphics = new GraphicsPrograms + { + Vertex = new ShaderProgram(0x11), Pixel = new ShaderProgram(0x22), + VertexInput = new VertexInputInfo { Stage = Stage(Program(ShaderStageKind.Mesh)) }, + PixelInput = new PixelInputInfo { Stage = Stage(Program(ShaderStageKind.Pixel)) }, + MeshInput = new MeshDrawConfiguration + { + Geometry = new GuestGeometryConfiguration { InputPrimitiveCountPerWorkgroup = 1, InputPointList = true }, + Execution = new MeshExecutionLimits + { + MaxGroupCountX = 65535, MaxGroupCountY = 65535, MaxGroupTotalCount = 65535, + }, + }, + }; + MeshDrawParameters? parameters = null; + _host.PreparationFailure = stage => + { + if (stage.Program?.Stage == ShaderStageKind.Mesh) parameters = stage.MeshDraw; + return null; + }; + var banks = Banks(primitiveType: 1, withDepth: true); + banks.Context.ShaderStages = 0x2030u; + WriteIndirectArguments(6, 2, 4, 5); + + _executor.DrawAuto(1, banks, Auto(0, source: DrawOffsetSource.IndirectArguments) with { IndirectArgumentsAddress = IndirectArguments }); + + if (gpuIndirect) + { + Assert.Equal(0, _host.GuestReads); + var request = _host.IndirectMeshRequest!.Value; + Assert.True(request.Automatic); + Assert.Equal((IndirectArguments, true, 1u), (request.ArgumentsAddress, request.PointList, request.PrimitivesPerGroup)); + Assert.Equal(new MeshDrawParameters(0, 0, 0, uint.MaxValue, 0x9000), parameters); + AssertOrder("preparation_begin", "acquire_indirect_mesh", "prepare_bindings", + "prepare_indirect_mesh", "draw_indirect_mesh", "dispose_indirect_mesh", "preparation_end"); + return; + } + + Assert.Null(_host.IndirectMeshRequest); + Assert.Equal(new MeshDrawParameters(6, 4, 5, 0, 0), parameters); + AssertOrder("preparation_begin", "prepare_bindings", "draw_mesh 6 2 1", "preparation_end"); + } + private void WriteIndirectArguments(params uint[] words) { var bytes = new byte[words.Length * 4]; @@ -171,6 +223,27 @@ public void IndirectIndexedDraw_LetsTheGpuReadTheArguments() Assert.DoesNotContain(_host.Calls, c => c.StartsWith("draw_indexed ", StringComparison.Ordinal)); } + // A GPU-culled automatic draw reads its four arguments on the GPU, so nothing here waits for the culling pass. So does a + // triangle strip whose state cannot make it a metadata clear quad (RenderExecutorAdaptationTests). + [Theory] + [InlineData(false)] + [InlineData(true)] + public void IndirectAutoDraw_LetsTheGpuReadTheArguments(bool strip) + { + WriteIndirectArguments(6, 2, 4, 3); + var arguments = Auto(0, source: DrawOffsetSource.IndirectArguments) with { IndirectArgumentsAddress = IndirectArguments }; + _executor.DrawAuto(7, strip ? Banks(PrimitiveTriangleStrip) : Banks(), arguments); + + Assert.Equal(0, _host.GuestReads); + AssertOrder( + "obtain 100600000 10 written=False", + "begin_rendering", + "bind_pipeline Graphics A1", + "draw_indirect", + "reset_bindings"); + Assert.DoesNotContain(_host.Calls, c => c.StartsWith("draw ", StringComparison.Ordinal)); + } + [Fact] public void IndirectIndexedStrip_ReadsTheArgumentsOnTheCpu() { @@ -249,9 +322,8 @@ public void MeshAutoDraw_RecordsMeshGroupsAndDrawParameters(ulong geometryAddres if (totalLimit < (triangleStrip ? 8u : 4u)) { - var error = Assert.Throws(() => - _executor.DrawAuto(1, banks, Auto(30, instances: 2, firstVertex: 5))); - Assert.Contains("total=8/7", error.Message); + // A draw over the device group limits is left out, as the GPU preparation leaves out an indirect one. + _executor.DrawAuto(1, banks, Auto(30, instances: 2, firstVertex: 5)); Assert.DoesNotContain(_host.Calls, call => call.StartsWith("draw_mesh", StringComparison.Ordinal)); return; } @@ -1153,7 +1225,7 @@ public void DynamicState_FollowsAViewportWrite() [Fact] public void ShaderBufferWrites_EndRenderingAndBarrierAfterTheDraw() { - var written = new BufferResourceInfo(false, true, false, false, false, 4, 0); + var written = new BufferResourceInfo(false, true, false, false, false, 4); var descriptor = BufferDescriptor(VertexBase, 4, 16); _pipelines.Graphics = Programs( vertexStage: Stage(Program(ShaderStageKind.Vertex, buffers: [written]), buffers: [descriptor]), @@ -1166,7 +1238,7 @@ public void ShaderBufferWrites_EndRenderingAndBarrierAfterTheDraw() [Fact] public void ShaderBufferWrites_WithoutAnAddressOrFootprintNeedNoBarrier() { - var written = new BufferResourceInfo(false, true, false, false, false, 4, 0); + var written = new BufferResourceInfo(false, true, false, false, false, 4); _pipelines.Graphics = Programs(vertexStage: Stage(Program(ShaderStageKind.Vertex, buffers: [written]), buffers: [BufferDescriptor(0, 4, 16)])); _executor.DrawIndexed(1, Banks(), Indexed(3)); Assert.DoesNotContain(_host.Calls, c => c.StartsWith("write_barrier", StringComparison.Ordinal)); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorPendingWritesTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorPendingWritesTests.cs index 5b03a56fa..58b60de6a 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorPendingWritesTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorPendingWritesTests.cs @@ -63,7 +63,7 @@ public bool TryDecode(CpuContext context, RegisteredShader shader, out Gen5Shade public void Dispose() => _fatal.Dispose(); - private static BufferResourceInfo Written => new(false, true, false, false, false, 4, 0); + private static BufferResourceInfo Written => new(false, true, false, false, false, 4); [Fact] public void ADrawMarksItsTargetAndItsWrittenBufferUntilTheRecorderFinishesIt() diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorStateTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorStateTests.cs index e5173c973..937e3dc6b 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorStateTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorStateTests.cs @@ -688,7 +688,7 @@ public void Preparation_SpansEveryResourceOperationAndRefusesARingWrap() [Fact] public void Preparation_CoversTheBufferWriteBarrier() { - var written = new BufferResourceInfo(false, true, false, false, false, 4, 0); + var written = new BufferResourceInfo(false, true, false, false, false, 4); _pipelines.Graphics = Programs(vertexStage: Stage(Program(ShaderStageKind.Vertex, buffers: [written]), buffers: [BufferDescriptor(VertexBase, 4, 16)])); _executor.DrawIndexed(1, Banks(), Indexed(3)); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs index dd9c64348..f5f05e722 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs @@ -370,6 +370,9 @@ public void DrawIndexed(uint indexCount, uint instanceCount, uint firstIndex, in public void DrawIndexedIndirect(BufferBinding arguments) => Calls.Add($"draw_indexed_indirect {arguments.Handle:X}:{arguments.Offset:X}"); + public void DrawIndirect(BufferBinding arguments) => + Calls.Add($"draw_indirect {arguments.Handle:X}:{arguments.Offset:X}"); + public void DrawMeshTasks(uint groupCountX, uint groupCountY, uint groupCountZ) => Calls.Add($"draw_mesh {groupCountX} {groupCountY} {groupCountZ}"); @@ -590,6 +593,13 @@ public PipelineHandle CreateComputePipeline(ComputeInputInfo input, ShaderProgra return PendingComputeCompletion; } + public HashSet SlowLinkedPrograms { get; } = []; + public List<(ulong Hash, bool Slow)> RecordedLinkedCompiles { get; } = []; + + public bool IsSlowLinkedCompile(ulong hash) => SlowLinkedPrograms.Contains(hash); + + public void RecordLinkedCompile(ulong hash, bool slow, long milliseconds) => RecordedLinkedCompiles.Add((hash, slow)); + public bool TryCreateComputePipeline(ComputeInputInfo input, ShaderProgram program, out PipelineHandle handle) { ComputePipelineAttempts++; diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ResolvedCommandReplayTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ResolvedCommandReplayTests.cs index d5593f2e0..aaaf95793 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ResolvedCommandReplayTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ResolvedCommandReplayTests.cs @@ -34,7 +34,7 @@ private static (RecordingRenderHost Host, FakePipelineProvider Pipelines) Arrang var pipelines = new FakePipelineProvider { Graphics = Programs(vertexBuffers: [new VertexInputBuffer(VertexBase, 16, 4)]), - Compute = ComputeProgram(Stage(Program(ShaderStageKind.Compute, buffers: [new BufferResourceInfo(false, true, false, false, false, 4, 0)]), + Compute = ComputeProgram(Stage(Program(ShaderStageKind.Compute, buffers: [new BufferResourceInfo(false, true, false, false, false, 4)]), buffers: [BufferDescriptor(VertexBase, 4, 16)])), }; return (new RecordingRenderHost(), pipelines); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Scheduling/PendingGuestPublicationTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Scheduling/PendingGuestPublicationTests.cs index af6a8a616..69fccbbb1 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Scheduling/PendingGuestPublicationTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Scheduling/PendingGuestPublicationTests.cs @@ -91,6 +91,26 @@ public void CommandProcessorReadsPartOfDeferredLabelButNotPendingDump() Assert.False(pending.TryOverlayLabels(0x2004, bytes, out _)); } + // A held write is visible to command-processor reads at once, which keep their order after it when it belongs to + // another queue; a CPU read (no queue) and any read over a pending dump still wait. + [Fact] + public void CommandProcessorReadsHeldWriteButCpuReadsWait() + { + var pending = new PendingGuestPublications(); + var held = pending.AddWrite(1, 0x1000, 4, [0x44, 0x33, 0x22, 0x11]); + var bytes = new byte[4]; + Assert.True(pending.TryOverlayLabels(0, 0x1000, bytes, out var covered, out var foreign)); + Assert.Equal(0xF, covered); + Assert.Equal(0x1122_3344u, System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(bytes)); + Assert.Same(held, foreign); + Assert.True(pending.TryOverlayLabels(1, 0x1002, new byte[4], out covered, out foreign)); + Assert.Equal(0x3, covered); + Assert.Null(foreign); + Assert.False(pending.TryOverlayLabels(0x1000, new byte[4], out _)); + pending.Add(2, 0x1000, 8); + Assert.False(pending.TryOverlayLabels(0, 0x1000, new byte[4], out _, out _)); + } + [Fact] public void PageIndexFindsEntryAcrossPagesUntilPublished() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Scheduling/PresenterSubmissionTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Scheduling/PresenterSubmissionTests.cs index 257d7ae2a..6b3e13e6c 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Scheduling/PresenterSubmissionTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Scheduling/PresenterSubmissionTests.cs @@ -195,6 +195,73 @@ public void ClosedPortFrame_IsRemovedBeforeCheckingTheNextFramesGpuTick() } } + [Fact] + public void AcquireTimeout_DiscardsTheTakenOlderFlipAndReopensItsBuffer() + { + var context = new CpuContext(new FakeCpuMemory(0x10000, 0x1000), Generation.Gen5); + var handle = VideoOutExports.VideoOutOpen(context); + Assert.True(handle > 0); + const BindingFlags staticMembers = BindingFlags.Static | BindingFlags.NonPublic; + var queue = typeof(VulkanVideoPresenter).GetField("_pendingGuestImagePresentations", staticMembers)!.GetValue(null)!; + var presentationType = queue.GetType().GenericTypeArguments[0]; + var enqueue = queue.GetType().GetMethod("Enqueue")!; + var clear = queue.GetType().GetMethod("Clear")!; + var presenter = RuntimeHelpers.GetUninitializedObject(PresenterType); + var commands = new CommandStreamQueue((ICommandStreamHost)presenter); + Set(presenter, "_commandStream", commands); + Assert.Empty((IEnumerable)queue); + try + { + // Register display buffers 0 and 1 without starting a native presenter. + var ports = (IDictionary)typeof(VideoOutExports).GetField("_ports", staticMembers)!.GetValue(null)!; + var port = ports[handle]!; + var slots = (Array)port.GetType().GetProperty("BufferSlots")!.GetValue(port)!; + foreach (var index in new[] { 0, 1 }) + { + var slot = slots.GetValue(index)!; + slot.GetType().GetProperty("GroupIndex")!.SetValue(slot, 0); + } + + // An older flip on buffer 0 and a newer one on buffer 1, neither paced by the display clock. + Assert.Equal(0, VideoOutExports.TryReserveFlipRequest(handle, 0, 0, 0, false, out var olderRequest)); + Assert.Equal(0, VideoOutExports.TryReserveFlipRequest(handle, 1, 0, 0, false, out var newerRequest)); + foreach (var (sequence, requestId) in new[] { (1L, olderRequest), (2L, newerRequest) }) + { + var frame = Activator.CreateInstance(presentationType)!; + presentationType.GetProperty("Sequence")!.SetValue(frame, sequence); + presentationType.GetProperty("FlipRequestId")!.SetValue(frame, requestId); + enqueue.Invoke(queue, new[] { frame }); + } + + // The render loop takes the older frame, then gets no swapchain image within the acquire timeout. + var take = PresenterType.GetMethod("TryTakePresentation", InstanceMembers)!; + var arguments = new object?[] { null }; + Assert.True((bool)take.Invoke(presenter, arguments)!); + var taken = arguments[0]!; + Assert.Equal(olderRequest, presentationType.GetProperty("FlipRequestId")!.GetValue(taken)); + Assert.False(VideoOutExports.IsFlipDone(handle, 0)); + var retries = (long)commands.BlockedRetries; + + Invoke(presenter, "DropPresentationAfterAcquireTimeout", taken, 0, false, null); + + Assert.Equal(VideoOutExports.FlipOutcome.Discarded, VideoOutExports.GetFlipOutcomeForTests(olderRequest)); + Assert.True(VideoOutExports.IsFlipDone(handle, 0)); + Assert.Equal(retries + 1, (long)commands.BlockedRetries); + + // Only the taken frame is dropped: the newer flip still waits for the presenter. + Assert.Equal(VideoOutExports.FlipOutcome.Pending, VideoOutExports.GetFlipOutcomeForTests(newerRequest)); + Assert.False(VideoOutExports.IsFlipDone(handle, 1)); + var remaining = Assert.Single(((IEnumerable)queue).Cast()); + Assert.Equal(newerRequest, presentationType.GetProperty("FlipRequestId")!.GetValue(remaining)); + } + finally + { + clear.Invoke(queue, null); + context[CpuRegister.Rdi] = (ulong)handle; + VideoOutExports.VideoOutClose(context); + } + } + [Fact] public void ImageUploadProfile_AddsBytesAndSeparatesPreparationCosts() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Scheduling/PublicationGapTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Scheduling/PublicationGapTests.cs new file mode 100644 index 000000000..928f1bf09 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Scheduling/PublicationGapTests.cs @@ -0,0 +1,99 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Scheduling; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Scheduling; + +[Collection(SchedulingStateCollection.Name)] +public sealed class PublicationGapTests +{ + private static PendingGuestPublications Create() + { + var pending = new PendingGuestPublications { ReusePublicationGaps = true }; + pending.Register(pending.Add(1, 0x1000, 0x10), 1); + pending.Register(pending.Add(1, 0x2000, 0x10), 2); + return pending; + } + + [Fact] + public void GapServesDifferentRangesAndHonorsItsExactEdges() + { + var pending = Create(); + Assert.False(pending.HasOverlap(0x1500, 4, includeLabels: false)); + Assert.False(pending.HasOverlap(0x1010, 0xFF0, includeLabels: false)); + Assert.True(pending.HasOverlap(0x100F, 1, includeLabels: false)); + Assert.Equal(2UL, pending.OverlapTick(0x1FFF, 2, includeLabels: false)); + } + + [Fact] + public void AddingAndPublishingDumpInvalidateTheSnapshot() + { + var pending = Create(); + Assert.False(pending.HasOverlap(0x1500, 4, includeLabels: false)); + var inserted = pending.Add(2, 0x1500, 4); + pending.Register(inserted, 9); + Assert.True(pending.HasOverlap(0x1500, 4, includeLabels: false)); + Assert.Equal(9UL, pending.OverlapTick(0x1500, 4, includeLabels: false)); + pending.Publish(inserted, () => { }); + Assert.False(pending.HasOverlap(0x1500, 4, includeLabels: false)); + } + + [Fact] + public void SkippedGpuSlotAndPublishingEntryCannotProveAGap() + { + var pending = Create(); + var entry = pending.Add(1, 0x1500, 4); + pending.Register(entry, 8); + entry.GpuSlot = 0; + Assert.False(pending.HasOverlap(0x1500, 4, includeLabels: false, skipGpuSlots: true)); + entry.GpuSlot = -1; // Same array, mutable eligibility changed. + Assert.Equal(8UL, pending.OverlapTick(0x1500, 4, includeLabels: false, skipGpuSlots: true)); + entry.Publishing = true; + Assert.Equal(0UL, pending.OverlapTick(0x1500, 4, includeLabels: false)); + entry.Publishing = false; + Assert.Equal(8UL, pending.OverlapTick(0x1500, 4, includeLabels: false)); + } + + [Fact] + public void FailureIsNotHiddenByACachedGap() + { + var pending = Create(); + Assert.False(pending.HasOverlap(0x1500, 4, includeLabels: false)); + pending.Fail(new Exception("publication failed")); + Assert.Throws(() => pending.HasOverlap(0x1500, 4, includeLabels: false)); + Assert.Throws(() => pending.OverlapTick(0x1500, 4, includeLabels: false)); + } + + [Fact] + public void OtherOwnersAndThreadsDoNotBorrowTheGap() + { + var pending = Create(); + Assert.False(pending.HasOverlap(0x1500, 4, includeLabels: false)); + var other = Create(); + other.Register(other.Add(2, 0x1500, 4), 7); + Assert.True(other.HasOverlap(0x1500, 4, includeLabels: false)); + var threadResult = true; + var thread = new Thread(() => threadResult = pending.HasOverlap(0x2500, 4, includeLabels: false)); + thread.Start(); + thread.Join(); + Assert.False(threadResult); + Assert.False(pending.HasOverlap(0x1700, 4, includeLabels: false)); + Assert.True(pending.HasOverlap(0x2000, 1, includeLabels: false)); + } + + [Fact] + public void DisabledModeAndInvalidRangesKeepReferenceBehavior() + { + var pending = Create(); + pending.ReusePublicationGaps = false; + Assert.False(pending.HasOverlap(0x1500, 4, includeLabels: false)); + Assert.False(pending.HasOverlap(0x1500, 4, includeLabels: false)); + Assert.False(pending.HasOverlap(ulong.MaxValue, 4, includeLabels: false)); + Assert.False(pending.HasOverlap(0x1000, 0, includeLabels: false)); + pending.ReusePublicationGaps = true; + Assert.False(pending.HasOverlap(0x2500, ulong.MaxValue - 0x2500, includeLabels: false)); + Assert.False(pending.HasOverlap(ulong.MaxValue - 1, 1, includeLabels: false)); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/BiasedStorageBufferDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/BiasedStorageBufferDeviceTests.cs index 14d71f2c1..0ee799af3 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/BiasedStorageBufferDeviceTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/BiasedStorageBufferDeviceTests.cs @@ -17,11 +17,14 @@ namespace SharpEmu.Libs.Tests.Gpu.Vulkan; // adds the two bytes to its byte addresses (the buffer's byte bias). public sealed class BiasedStorageBufferDeviceTests(HeadlessVulkanFixture fixture) : IClassFixture { + // The view ends on a whole dword: the last partial one when the buffer holds it, else the one before it, which the + // shader's ArrayLength leaves out as well. Under four bytes there is no whole dword, and the view keeps its bytes. [Theory] [InlineData(6ul, 64ul, 8ul)] [InlineData(8ul, 64ul, 8ul)] - [InlineData(6ul, 7ul, 6ul)] + [InlineData(6ul, 7ul, 4ul)] [InlineData(5ul, 64ul, 8ul)] + [InlineData(2ul, 3ul, 2ul)] public void TheViewEndsOnADwordInsideTheBuffer(ulong bytes, ulong available, ulong expected) => Assert.Equal(expected, VulkanVideoPresenter.StorageBufferViewRange(bytes, available, uint.MaxValue)); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/BufferAtomicRangeDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/BufferAtomicRangeDeviceTests.cs index 6d304a6f0..8d047a16e 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/BufferAtomicRangeDeviceTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/BufferAtomicRangeDeviceTests.cs @@ -57,6 +57,56 @@ public void ReturningAtomicOutOfRangeReturnsZero() harness.AssertNoValidationMessages(); } + // BUFFER_ATOMIC_SWAP_X2 and OR_X2 move the whole pair at once. 1024 lanes swap {lane, lane ^ K} through one slot, then + // read it with OR_X2 0: every pair a lane gets back was written whole, and each value comes back exactly once. + [Fact] + public void X2AtomicsNeverTearThePair() + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan) || !vulkan.SupportsBufferInt64Atomics) return; + const int lanes = 1024, reads = 8192, slot = 16384; + const uint key = 0xA5A5A5A5, initial = 0xFFFFFFFF; + var program = Program( + Vop2(0, "VLshlrevB32", 1, Operand(3), Gen5Operand.Vector(0)), + Vop1(8, "VMovB32", 2, Gen5Operand.Vector(0)), + Vop2(16, "VXorB32", 3, Operand(key), Gen5Operand.Vector(0)), + MoveVector(24, 4, 0), + MoveVector(32, 5, 0), + // buffer_atomic_swap_x2 v[2:3], off, s[4:7], s12 glc, then buffer_atomic_or_x2 v[4:5], off, s[4:7], s12 glc. + Decode(0xE1404000, 0x0C010200) with { Pc = 40 }, + Decode(0xE1684000, 0x0C010400) with { Pc = 48 }, + // buffer_store_dwordx2 v[2:3], v1, s[4:7], 0 offen, and v[4:5] the same at s13. + Decode(0xE0741000, 0x80010201) with { Pc = 56 }, + Decode(0xE0741000, 0x0D010401) with { Pc = 64 }, + EndProgram(72)); + var (plan, resources, layout) = Prepare(program); + var request = new ShaderCompileRequest(plan, resources, layout) + { + LocalSizeX = lanes, ThreadCountX = lanes, WaveSize = 32, SupportsBufferInt64Atomics = true, + }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + using var harness = new ImageTestHarness(vulkan); + using var runner = new LayoutComputeRunner(harness, request, shader.Spirv); + var memory = new byte[slot + 8]; + BinaryPrimitives.WriteUInt32LittleEndian(memory.AsSpan(slot), initial); + BinaryPrimitives.WriteUInt32LittleEndian(memory.AsSpan(slot + 4), initial ^ key); + var buffer = runner.CreateBuffer(memory); + var registers = new uint[256]; + registers[6] = (uint)memory.Length; + registers[12] = slot; + registers[13] = reads; + harness.Run(() => runner.Dispatch(registers, + new Dictionary { [DescriptorBindingKind.Buffers] = [buffer] }, 1)); + var words = runner.ReadBack(buffer, 0, (ulong)memory.Length); + uint Low(int offset) => BinaryPrimitives.ReadUInt32LittleEndian(words.AsSpan(offset)); + uint High(int offset) => BinaryPrimitives.ReadUInt32LittleEndian(words.AsSpan(offset + 4)); + var pairs = Enumerable.Range(0, lanes).SelectMany(lane => new[] { lane * 8, reads + lane * 8 }).Append(slot); + Assert.All(pairs, offset => Assert.Equal(Low(offset) ^ key, High(offset))); + var returned = Enumerable.Range(0, lanes).Select(lane => Low(lane * 8)).Append(Low(slot)).Order(); + Assert.Equal(Enumerable.Range(0, lanes).Select(lane => (uint)lane).Append(initial).Order(), returned); + harness.AssertNoValidationMessages(); + } + private static Gen5ShaderInstruction Decode(uint first, uint second) { uint[] words = [first, second, 0xBF810000]; diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/BufferFormatWrapDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/BufferFormatWrapDeviceTests.cs new file mode 100644 index 000000000..41c93cede --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/BufferFormatWrapDeviceTests.cs @@ -0,0 +1,53 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.Libs.Tests.Gpu.Vulkan; + +// A formatted load reads component c from byte (elementAddress + 4c) in 32 bits. With the element at 2^32 - 4 (plus 0-3 +// bytes), Y, Z and W wrap to the view's first bytes; with only those selected the load reads them, aligned or not. +public sealed class BufferFormatWrapDeviceTests(HeadlessVulkanFixture fixture) : IClassFixture +{ + [Theory] + [InlineData(0u)] + [InlineData(1u)] + [InlineData(3u)] + public void ComponentsPastTheTopOfTheByteSpaceWrapToTheViewsStart(uint misalignment) + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan)) return; + var program = Program(MoveScalar(0, 126, 1), MoveScalar(4, 127, 0), + MoveVector(8, 0, 0xFFFF_FFFC + misalignment), + BufferAccess(16, "BufferLoadFormatXyzw", 8, dwords: 4, vectorData: 4, offsetEnabled: true), + BufferAccess(24, "BufferStoreDwordx4", 12, dwords: 4, vectorData: 4), EndProgram(32)); + var (plan, resources, layout) = Prepare(program); + // 32_32_32_32 UINT; x = Y, y = Z, z = W, w = 0. + resources.Info.Buffers[0].DescriptorFormat = 75; + resources.Info.Buffers[0].DescriptorSwizzle = 5 | (6 << 3) | (7 << 6); + var request = new ShaderCompileRequest(plan, resources, layout) { WaveSize = 64, LocalSizeX = 64 }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + using var harness = new ImageTestHarness(vulkan); + using var runner = new LayoutComputeRunner(harness, request, shader.Spirv); + var bytes = Enumerable.Range(0, 64).Select(index => (byte)index).ToArray(); + var input = runner.CreateBuffer(bytes); + var output = runner.CreateBuffer(16); + var registers = new uint[256]; + registers[10] = 64; + registers[14] = 16; + harness.Run(() => runner.Dispatch(registers, + new Dictionary { [DescriptorBindingKind.Buffers] = [input, output] }, 1)); + var actual = runner.ReadBack(output, 0, 16); + uint Bytes(uint first) => BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan((int)first)); + Assert.Equal([Bytes(misalignment), Bytes(misalignment + 4), Bytes(misalignment + 8), 0u], + Enumerable.Range(0, 4).Select(index => BinaryPrimitives.ReadUInt32LittleEndian(actual.AsSpan(index * 4))).ToArray()); + harness.AssertNoValidationMessages(); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/CompactDeviceRangeDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/CompactDeviceRangeDeviceTests.cs new file mode 100644 index 000000000..cde4572a9 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/CompactDeviceRangeDeviceTests.cs @@ -0,0 +1,146 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using Xunit.Abstractions; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.Libs.Tests.Gpu.Vulkan; + +// A linked program reads consecutive dwords through the page table as one range, which resolves its first and last dword +// only. S_LOAD_DWORDX8 starts 20 bytes before a page end, so dwords 0-4 lie in the first page and 5-7 in the next; +// BUFFER_LOAD_DWORDX4 through a run-time V# does the same per lane at 4-byte steps. With the next page mapped every dword +// reads its bytes; without it the dwords there read zero and its page is reported missing. With the inline range, through +// the shared load function (SharedDeviceLoads), and through one shared function per range (SharedDeviceRanges). +[Collection(SharedDeviceLoadState.Name)] +public sealed class CompactDeviceRangeDeviceTests(HeadlessVulkanFixture fixture, ITestOutputHelper output) : IClassFixture +{ + private const ulong PageSize = Gen5SpirvTranslator.DeviceAddressPageSize; + private const ulong GuestBase = 64 * PageSize; + private const ulong DataAddress = GuestBase + PageSize - 20; + private const ulong TableEntries = 4096; + private const uint ResultRegister = 4; + private const uint Lanes = 8; + private const uint ResultBytes = Lanes * 64; + + [Theory] + [InlineData(true, false, false)] + [InlineData(false, false, false)] + [InlineData(true, true, false)] + [InlineData(false, true, false)] + [InlineData(true, true, true)] + [InlineData(false, true, true)] + public void RangesAcrossAPageEndReadEachDwordFromItsPage(bool secondPageMapped, bool sharedLoads, bool sharedRanges) + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan, shaderInt64: true)) return; + var instructions = new List + { + MoveScalar(0, 14, 0x2000), MoveScalar(4, 15, 0), MoveScalar(8, 24, 1), + Sop1(12, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + Vop2(16, "VAddU32", 2, Operand((uint)GuestBase), Gen5Operand.Vector(0)), + ReadFirstLane(20, 12, 2), + MoveScalar(24, 13, (uint)(GuestBase >> 32)), + ScalarLoad(28, 12, 20, count: 4), + ScalarLoad(36, 12, 26, count: 2, immediateOffset: 16), + ScalarLoad(44, 26, 32, count: 8), + Vop2(52, "VLshlrevB32", 5, Operand(2), Gen5Operand.Vector(0)), + BufferAccess(56, "BufferLoadDwordx4", 20, dwords: 4, vectorData: 8, offsetEnabled: true, vectorAddress: 5), + }; + uint pc = 64; + for (uint register = 0; register < 8; register++, pc += 4) + { + instructions.Add(MoveVectorFromScalar(pc, 12 + register, 32 + register)); + } + + instructions.Add(Vop2(pc, "VLshlrevB32", 6, Operand(6), Gen5Operand.Vector(0))); + pc += 4; + for (uint part = 0; part < 3; part++, pc += 8) + { + instructions.Add(BufferAccess(pc, "BufferStoreDwordx4", ResultRegister, offset: (int)(part * 16), dwords: 4, + vectorData: 8 + part * 4, offsetEnabled: true, vectorAddress: 6)); + } + + instructions.Add(EndProgram(pc)); + var function = Program(Sop1(0, "SSetpcB64", 0, Gen5Operand.Scalar(14))); + var program = Gen5ShaderCallLinker.Link(Program(instructions.ToArray()), + [new(12, 14, 24, 14, 16, [new ShaderCallTarget(0x2000, 1, function)])]); + var (plan, resources, layout) = Prepare(program); + var request = new ShaderCompileRequest(plan, resources, layout) { LocalSizeX = Lanes, ThreadCountX = Lanes, ScratchDwords = 32 }; + var (previous, previousRanges) = (Gen5SpirvTranslator.SharedDeviceLoads, Gen5SpirvTranslator.SharedDeviceRanges); + Gen5SpirvShader shader; + string error; + try + { + Gen5SpirvTranslator.SharedDeviceLoads = sharedLoads; + Gen5SpirvTranslator.SharedDeviceRanges = sharedRanges; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out shader, out error), error); + } + finally + { + (Gen5SpirvTranslator.SharedDeviceLoads, Gen5SpirvTranslator.SharedDeviceRanges) = (previous, previousRanges); + } + + var first = ImageTestHarness.Pattern((int)PageSize, 41); + var second = ImageTestHarness.Pattern((int)PageSize, 42); + BinaryPrimitives.WriteUInt32LittleEndian(first.AsSpan(0), (uint)DataAddress); + BinaryPrimitives.WriteUInt32LittleEndian(first.AsSpan(4), (uint)(DataAddress >> 32)); + BinaryPrimitives.WriteUInt32LittleEndian(first.AsSpan(8), 0x10000); + BinaryPrimitives.WriteUInt32LittleEndian(first.AsSpan(12), 4 | (5 << 3) | (6 << 6) | (7 << 9) | (20u << 12)); + BinaryPrimitives.WriteUInt64LittleEndian(first.AsSpan(16), DataAddress); + using var harness = new ImageTestHarness(vulkan); + using var runner = new LayoutComputeRunner(harness, request, shader.Spirv); + var result = runner.CreateBuffer(ResultBytes); + var fault = runner.CreateBuffer(TableEntries / 8 + 64); + var pages = new List<(ulong, GpuBuffer, ulong)> { (GuestBase, runner.CreateBuffer(first, PageSize), 0) }; + if (secondPageMapped) pages.Add((GuestBase + PageSize, runner.CreateBuffer(second, PageSize), 0)); + var registers = new uint[256]; + registers[0] = (uint)GuestBase; + registers[1] = (uint)(GuestBase >> 32); + registers[ResultRegister + 2] = ResultBytes; + harness.Run(() => runner.Dispatch(registers, + new Dictionary + { + [DescriptorBindingKind.Buffers] = [result], + [DescriptorBindingKind.DeviceAddressPageTable] = [runner.CreatePageTable(TableEntries, pages)], + [DescriptorBindingKind.FaultBuffer] = [fault], + }, 1, flattenedTable: new uint[Math.Max(plan.FlattenedTableReservedCount, 1)], + callArguments: Gen5ShaderCallLinker.CallEntryArguments(program), callTargets: Gen5ShaderCallLinker.CallTargets(program))); + var stored = runner.ReadBack(result, 0, ResultBytes); + var faults = runner.ReadBack(fault, 0, fault.Size); + harness.AssertNoValidationMessages(); + + // The guest dword at a byte offset from DataAddress: from the first page, the second, or zero where unmapped. + uint Expected(int offset) + { + var address = (int)(PageSize - 20) + offset; + if (address + 4 <= (int)PageSize) return BinaryPrimitives.ReadUInt32LittleEndian(first.AsSpan(address)); + return secondPageMapped ? BinaryPrimitives.ReadUInt32LittleEndian(second.AsSpan(address - (int)PageSize)) : 0u; + } + + uint Stored(uint lane, uint dword) => BinaryPrimitives.ReadUInt32LittleEndian(stored.AsSpan((int)(lane * 64 + dword * 4))); + for (uint lane = 0; lane < Lanes; lane++) + { + for (uint dword = 0; dword < 4; dword++) + { + Assert.Equal(Expected((int)(lane * 4 + dword * 4)), Stored(lane, dword)); + } + + for (uint dword = 0; dword < 8; dword++) + { + Assert.Equal(Expected((int)(dword * 4)), Stored(lane, 4 + dword)); + } + } + + var pageIndex = (GuestBase + PageSize) >> Gen5SpirvTranslator.DeviceAddressPageBits; + var faultWord = BinaryPrimitives.ReadUInt32LittleEndian(faults.AsSpan((int)(pageIndex / 32) * 4)); + Assert.Equal(secondPageMapped ? 0u : 1u << (int)(pageIndex % 32), faultWord & (1u << (int)(pageIndex % 32))); + output.WriteLine($"Verified the page-end ranges (second page mapped: {secondPageMapped}) on {vulkan!.DeviceName}."); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/CpuKernelEvaluationDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/CpuKernelEvaluationDeviceTests.cs index e57822ca1..1d8cc1080 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/CpuKernelEvaluationDeviceTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/CpuKernelEvaluationDeviceTests.cs @@ -310,6 +310,7 @@ private static uint[] RunOnDevice(ImageTestHarness harness, LayoutComputeRunner var controlBuffer = runner.CreateBuffer(MemoryMarshal.AsBytes(control)); var bound = new List(); var ranges = new List(); + var strides = new List(); foreach (var buffer in request.Resources.Info.Buffers) { var register = BufferRegister(plan.Graph.Program, buffer.FirstUsePc); @@ -321,12 +322,14 @@ private static uint[] RunOnDevice(ImageTestHarness harness, LayoutComputeRunner }; bound.Add(gpu); ranges.Add(range); + strides.Add((userData[(int)register + 1] >> 16) & 0x3FFF); } var registers = new uint[256]; userData.CopyTo(registers, 0); harness.Run(() => runner.Dispatch(registers, new Dictionary { [DescriptorBindingKind.Buffers] = [.. bound] }, - groups, dispatchThreadLimits: [limit, 1, 1], bufferRanges: [.. ranges])); + groups, dispatchThreadLimits: [limit, 1, 1], bufferRanges: [.. ranges], + bufferStrides: request.Bindings.BufferStrideCount != 0 ? [.. strides] : null)); var bytes = runner.ReadBack(destinationBuffer, 0, DestinationRecords * sizeof(uint)); return MemoryMarshal.Cast(bytes).ToArray(); } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/DeferredExecGuardDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/DeferredExecGuardDeviceTests.cs new file mode 100644 index 000000000..e88fd64e1 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/DeferredExecGuardDeviceTests.cs @@ -0,0 +1,203 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Ir; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.Libs.Tests.Gpu.Vulkan; + +// Wave32 programs whose vector writes under a partial EXEC are merged once per EXEC region: every lane EXEC leaves +// out must still show its old value afterwards, and to any instruction that reads another lane inside the region. +public sealed class DeferredExecGuardDeviceTests(HeadlessVulkanFixture fixture) : IClassFixture +{ + private const uint Exec = 126; + private readonly List _instructions = []; + private uint _pc; + + private uint Add(Gen5ShaderInstruction instruction) + { + var pc = _pc; + _instructions.Add(instruction with { Pc = pc }); + _pc += 8; + return pc; + } + + private void Point(uint branchPc, uint targetPc) + { + var index = _instructions.FindIndex(instruction => instruction.Pc == branchPc); + var offset = (short)(((int)targetPc - (int)branchPc - 4) / 4); + _instructions[index] = _instructions[index] with { Words = [unchecked((uint)(ushort)offset)] }; + } + + // v2 = the thread's index in the 8 x 8 group: lanes 0-31 are the first wave, 32-63 the second. + private void Lane() + { + Add(Vop2(0, "VLshlrevB32", 2, Operand(3), Gen5Operand.Vector(1))); + Add(Vop2(0, "VAddI32", 2, Gen5Operand.Vector(0), Gen5Operand.Vector(2))); + } + + // waveSize 64: one wave of 64 lanes on a 32-lane host, which runs a lane-local program as two independent half waves. + private uint[] Run(uint waveSize = 32) + { + const uint threads = 64; + Add(Vop2(0, "VLshlrevB32", 5, Operand(2), Gen5Operand.Vector(2))); + Add(BufferAccess(0, "BufferStoreDword", 4, vectorData: 4, offsetEnabled: true, vectorAddress: 5)); + Add(EndProgram(0)); + var program = Program([.. _instructions]); + if (waveSize == 64) + { + Assert.True(Gen5WaveLaneLocalAnalysis.IsLaneLocal(program, new HashSet(), out var reason), reason); + } + + var (plan, resources, layout) = Prepare(program); + var request = new ShaderCompileRequest(plan, resources, layout) + { + LocalSizeX = 8, LocalSizeY = 8, ThreadCountX = 8, ThreadCountY = 8, WaveSize = waveSize, HostComputeSubgroup32 = true, + }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + Assert.NotNull(fixture.Vulkan); + using var harness = new ImageTestHarness(fixture.Vulkan); + using var runner = new LayoutComputeRunner(harness, request, shader.Spirv); + var output = runner.CreateBuffer(threads * 4); + var registers = new uint[256]; + registers[6] = threads * 4; + var buffers = new Dictionary { [DescriptorBindingKind.Buffers] = [output] }; + harness.Run(() => runner.Dispatch(registers, buffers, 1)); + var bytes = runner.ReadBack(output, 0, threads * 4); + harness.AssertNoValidationMessages(); + var lanes = new uint[threads]; + for (var lane = 0; lane < lanes.Length; lane++) + { + lanes[lane] = BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(lane * sizeof(uint))); + } + + return lanes; + } + + private bool Ready() => GatePrerequisites.Ready(fixture.Vulkan, shaderInt64: true); + + [Fact] + public void RepeatedWritesInOneRegion_LeaveTheInactiveLanesTheirOldValues() + { + if (!Ready()) return; + Lane(); + Add(MoveVector(0, 4, 7)); + Add(MoveVector(0, 3, 9)); + Add(Sop1(0, "SMovB32", 20, Gen5Operand.Scalar(Exec))); + Add(Vopc(0, "VCmpxLeU32", Operand(40), 2)); + Add(Vop2(0, "VAddU32", 4, Operand(64), Gen5Operand.Vector(2))); + Add(Vop2(0, "VAddU32", 4, Operand(1), Gen5Operand.Vector(4))); + Add(Vop2(0, "VAddU32", 3, Operand(2), Gen5Operand.Vector(4))); + Add(Vop2(0, "VAddU32", 4, Gen5Operand.Vector(3), Gen5Operand.Vector(4))); + Add(Sop1(0, "SMovB32", Exec, Gen5Operand.Scalar(20))); + Add(Vop2(0, "VLshlrevB32", 6, Operand(16), Gen5Operand.Vector(3))); + Add(Vop2(0, "VAddU32", 4, Gen5Operand.Vector(6), Gen5Operand.Vector(4))); + + var lanes = Run(); + for (uint lane = 0; lane < 64; lane++) + { + var expected = lane >= 40 ? 2 * lane + 132 + ((lane + 67) << 16) : 7u + (9u << 16); + Assert.Equal(expected, lanes[lane]); + } + } + + [Fact] + public void ALaneReadInsideARegion_SeesTheOldValueOfAnInactiveLane() + { + if (!Ready()) return; + Lane(); + Add(Vop2(0, "VAddU32", 4, Operand(100), Gen5Operand.Vector(2))); + Add(MoveVector(0, 7, 0)); + Add(Vop2(0, "VAndB32", 6, Operand(31), Gen5Operand.Vector(2))); + Add(Sop1(0, "SMovB32", 20, Gen5Operand.Scalar(Exec))); + Add(Vopc(0, "VCmpxLtU32", Operand(0), 6)); + Add(Vop2(0, "VAddU32", 4, Operand(1000), Gen5Operand.Vector(4))); + Add(ReadLane(0, 21, 4, 0)); + Add(MoveVectorFromScalar(0, 7, 21)); + Add(Sop1(0, "SMovB32", Exec, Gen5Operand.Scalar(20))); + Add(Vop2(0, "VLshlrevB32", 7, Operand(16), Gen5Operand.Vector(7))); + Add(Vop2(0, "VAddU32", 4, Gen5Operand.Vector(7), Gen5Operand.Vector(4))); + + var lanes = Run(); + for (uint lane = 0; lane < 64; lane++) + { + var firstOfWave = lane & ~31u; + var expected = (lane & 31) == 0 ? lane + 100 : lane + 1100 + ((firstOfWave + 100) << 16); + Assert.Equal(expected, lanes[lane]); + } + } + + [Fact] + public void ARegionSplitByABranch_StillKeepsTheInactiveLanes() + { + if (!Ready()) return; + Lane(); + Add(MoveVector(0, 4, 7)); + Add(Sop1(0, "SMovB32", 20, Gen5Operand.Scalar(Exec))); + Add(Vopc(0, "VCmpxLeU32", Operand(40), 2)); + Add(Vop2(0, "VAddU32", 4, Operand(64), Gen5Operand.Vector(2))); + var skip = Add(Branch(0, "SCbranchExecz", 0)); + Add(Vop2(0, "VAddU32", 4, Operand(1), Gen5Operand.Vector(4))); + var join = Add(Sop1(0, "SMovB32", Exec, Gen5Operand.Scalar(20))); + Point(skip, join); + + var lanes = Run(); + for (uint lane = 0; lane < 64; lane++) + { + Assert.Equal(lane >= 40 ? lane + 65 : 7u, lanes[lane]); + } + } + // The same regions in a wave64 program: its two halves each merge their own inactive lanes. + [Fact] + public void HalfWaves_RepeatedWritesInOneRegion_LeaveTheInactiveLanesTheirOldValues() + { + if (!Ready()) return; + Lane(); + Add(MoveVector(0, 4, 7)); + Add(MoveVector(0, 3, 9)); + Add(Sop1(0, "SMovB64", 20, Gen5Operand.Scalar(Exec))); + Add(Vopc(0, "VCmpxLeU32", Operand(40), 2)); + Add(Vop2(0, "VAddU32", 4, Operand(64), Gen5Operand.Vector(2))); + Add(Vop2(0, "VAddU32", 4, Operand(1), Gen5Operand.Vector(4))); + Add(Vop2(0, "VAddU32", 3, Operand(2), Gen5Operand.Vector(4))); + Add(Vop2(0, "VAddU32", 4, Gen5Operand.Vector(3), Gen5Operand.Vector(4))); + Add(Sop1(0, "SMovB64", Exec, Gen5Operand.Scalar(20))); + Add(Vop2(0, "VLshlrevB32", 6, Operand(16), Gen5Operand.Vector(3))); + Add(Vop2(0, "VAddU32", 4, Gen5Operand.Vector(6), Gen5Operand.Vector(4))); + + var lanes = Run(waveSize: 64); + for (uint lane = 0; lane < 64; lane++) + { + var expected = lane >= 40 ? 2 * lane + 132 + ((lane + 67) << 16) : 7u + (9u << 16); + Assert.Equal(expected, lanes[lane]); + } + } + + [Fact] + public void HalfWaves_ARegionSplitByABranch_StillKeepsTheInactiveLanes() + { + if (!Ready()) return; + Lane(); + Add(MoveVector(0, 4, 7)); + Add(Sop1(0, "SMovB64", 20, Gen5Operand.Scalar(Exec))); + Add(Vopc(0, "VCmpxLeU32", Operand(40), 2)); + Add(Vop2(0, "VAddU32", 4, Operand(64), Gen5Operand.Vector(2))); + var skip = Add(Branch(0, "SCbranchExecz", 0)); + Add(Vop2(0, "VAddU32", 4, Operand(1), Gen5Operand.Vector(4))); + var join = Add(Sop1(0, "SMovB64", Exec, Gen5Operand.Scalar(20))); + Point(skip, join); + + var lanes = Run(waveSize: 64); + for (uint lane = 0; lane < 64; lane++) + { + Assert.Equal(lane >= 40 ? lane + 65 : 7u, lanes[lane]); + } + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/DeviceAddressShaderTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/DeviceAddressShaderTests.cs index af00d0209..c6603a93b 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/DeviceAddressShaderTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/DeviceAddressShaderTests.cs @@ -159,6 +159,33 @@ public void LinkedCalls_FunctionReadsItsOwnProgramAddress(ulong function, ulong run.Finish(output, nameof(LinkedCalls_FunctionReadsItsOwnProgramAddress)); } + // The caller reads its program address with S_GETPC_B64 after a call, as a program does to address the constants placed + // after its code: it reads the shader base plus the instruction's offset in its own code, although the callee body linked + // before it moved the instruction. + [Fact] + public void LinkedCalls_CallerReadsItsOwnProgramAddressAfterACall() + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan, shaderInt64: true)) return; + const ulong shaderBase = 0x3_0040_0000; + var caller = Program(MoveScalar(0, 14, 0x2000), MoveScalar(4, 15, 0), MoveScalar(8, 16, 10), MoveScalar(12, 17, 0), + Sop1(16, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + Sop1(20, "SGetpcB64", 2, Gen5Operand.Scalar(0)), + Vop1(24, "VMovB32", 3, Gen5Operand.Scalar(2)), Vop1(28, "VMovB32", 4, Gen5Operand.Scalar(3)), + BufferAccess(32, "BufferStoreDwordx4", ResultRegister, dwords: 4, vectorData: 1), EndProgram(40)); + var function = Program(Vop1(0, "VMovB32", 1, Gen5Operand.Scalar(16)), Vop1(4, "VMovB32", 2, Operand(7)), + Sop1(8, "SSetpcB64", 0, Gen5Operand.Scalar(14))); + var linked = Gen5ShaderCallLinker.Link(caller, [new(16, 14, 16, 14, caller.Address + 20, [new(0x2000, 10, function)])]); + var run = new Run(vulkan, linked); + run.Dispatch(GuestBase, shaderBase: shaderBase); + Assert.Equal(10u, run.ResultWord(0)); + Assert.Equal(7u, run.ResultWord(4)); + Assert.Equal(unchecked((uint)(shaderBase + 24)), run.ResultWord(8)); + Assert.Equal((uint)(shaderBase >> 32), run.ResultWord(12)); + Assert.All(run.FaultWords(), word => Assert.Equal(0u, word)); + run.Finish(output, nameof(LinkedCalls_CallerReadsItsOwnProgramAddressAfterACall)); + } + // A partial wave: the lanes past the dispatch's thread count do not run, and the others run a call body whose comparison // is a wave operation over the running lanes. [Fact] @@ -522,6 +549,8 @@ public void DeviceRecordCount_ControlsIndexedStoreBounds(uint recordCount, uint Branch(76, "SCbranchScc1", -8), EndProgram(80)); var run = new Run(vulkan, program, threadCount: 8); + // The indexed store's V# is built on the device and carries its own stride; the layout carries none. + Assert.Equal(0u, run.Request.Bindings.BufferStrideCount); var data = new byte[64]; WriteWord(data, 0, recordCount); run.MapPage(GuestBase, data); @@ -905,6 +934,96 @@ public void RayIntersect_ABvhBasedAtZero_ReadsTheNodeItsPointerAddresses(bool ty run.Finish(output, nameof(RayIntersect_ABvhBasedAtZero_ReadsTheNodeItsPointerAddresses)); } + // A float32 box node takes two 64-byte units. In the last unit of a page its second unit, with the bounds of + // children 2 and 3, is on the next page, which can be another buffer; each unit is resolved on its own. With + // either page missing the node is not tested: every result dword is invalid. + [Theory] + [InlineData(true, true)] + [InlineData(true, false)] + [InlineData(false, true)] + public void RayIntersect_AFloat32BoxAcrossTwoPages_ReadsEachUnitFromItsPage(bool firstPageMapped, bool secondPageMapped) + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan, shaderInt64: true)) + { + return; + } + + const ulong NodeAddress = GuestBase + PageSize - 64; + uint[] children = [0x1000, 0x2000, 0x3000, 0x4000]; + // Child bounds as min xyz, max xyz. Children 0 and 2 contain the ray, 2 nearer; 1 and 3 lie beside it. + float[][] bounds = + [ + [0, 0, 5, 2, 2, 6], + [5, 5, 5, 6, 6, 6], + [0, 0, 2, 2, 2, 3], + [5, 5, 2, 6, 6, 3], + ]; + var first = new byte[(int)PageSize]; + var second = new byte[(int)PageSize]; + void WriteNodeWord(uint dword, uint value) + { + var offset = (int)(PageSize - 64) + (int)dword * 4; + if (offset < (int)PageSize) + WriteWord(first, offset, value); + else + WriteWord(second, offset - (int)PageSize, value); + } + + for (var child = 0u; child < 4; child++) + { + WriteNodeWord(child, children[child]); + for (var bound = 0u; bound < 6; bound++) + WriteNodeWord(4 + child * 6 + bound, BitConverter.SingleToUInt32Bits(bounds[child][bound])); + } + + // The ray starts at (1, 1, -10) and runs along +z: extent, origin, direction, inverse direction. The inverse + // direction's 1e30 stands in for an axis-parallel ray's infinity: this harness compiles without the + // SignedZeroInfNanPreserve mode the game enables, so the driver need not keep an infinity. + float[] ray = [1000f, 1f, 1f, -10f, 0f, 0f, 1f, 1e30f, 1e30f, 1f]; + var instructions = new List + { + MoveVector(0, OffsetRegister, 0), + GlobalMemory(8, "GlobalLoadDword", AddressLow, OffsetRegister, 20, 20), + MoveVector(16, 0, (uint)(NodeAddress >> 3) | 5), + }; + for (var index = 0; index < ray.Length; index++) + { + instructions.Add(MoveVector((uint)(24 + index * 8), (uint)(1 + index), BitConverter.SingleToUInt32Bits(ray[index]))); + } + + // A base of zero with box sorting, every node index valid and the BVH type in bits [127:124]. + instructions.Add(MoveScalar(104, 8, 0)); + instructions.Add(MoveScalar(112, 9, 0x8000_0000)); + instructions.Add(MoveScalar(120, 10, uint.MaxValue)); + instructions.Add(MoveScalar(128, 11, 0x8000_03FFu)); + instructions.Add(RayIntersect(136)); + instructions.Add(MoveVector(144, 11, 0)); + instructions.Add(BufferAccess(152, "BufferStoreDwordx4", ResultRegister, 0, 4, vectorData: 12, offsetEnabled: true, vectorAddress: 11)); + instructions.Add(EndProgram(160)); + var run = new Run(vulkan, Program([.. instructions])); + if (firstPageMapped) + { + run.MapPage(GuestBase, first); + } + + if (secondPageMapped) + { + run.MapPage(GuestBase + PageSize, second); + } + + run.Dispatch(GuestBase); + uint[] expected = firstPageMapped && secondPageMapped + ? [children[2], children[0], uint.MaxValue, uint.MaxValue] + : [uint.MaxValue, uint.MaxValue, uint.MaxValue, uint.MaxValue]; + for (var index = 0u; index < 4; index++) + { + Assert.Equal(expected[index], run.ResultWord(index * 4)); + } + + run.Finish(output, nameof(RayIntersect_AFloat32BoxAcrossTwoPages_ReadsEachUnitFromItsPage)); + } + // IMAGE_BVH_INTERSECT_RAY v[12:15], v[0:10], s[8:11]. private static Gen5ShaderInstruction RayIntersect(uint pc) { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/DeviceFormatStoreDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/DeviceFormatStoreDeviceTests.cs new file mode 100644 index 000000000..8efbe45f1 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/DeviceFormatStoreDeviceTests.cs @@ -0,0 +1,88 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using Xunit.Abstractions; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.Libs.Tests.Gpu.Vulkan; + +// A formatted store through a run-time V# branches on the V#'s format; the formats of one store shape share a branch. Each +// format must still store its own encoding: 8 (1), 8_8 (14) and 8_8_8_8 (56) UNORM share the X store's branch, 8 SNORM (2), +// 16 FLOAT (13) and 32 FLOAT (22) do not. Four lanes store 0.5, 1, -1 and NaN, one dword apart, into a page of 0xCC bytes; +// only each element's bytes change. +public sealed class DeviceFormatStoreDeviceTests(HeadlessVulkanFixture fixture, ITestOutputHelper output) : IClassFixture +{ + private const ulong PageSize = Gen5SpirvTranslator.DeviceAddressPageSize; + private const ulong GuestBase = 64 * PageSize; + private const ulong TableEntries = 4096; + private const int StoreOffset = 512; + private const int SourceOffset = 1024; + private static readonly uint[] Values = [0x3F000000, 0x3F800000, 0xBF800000, 0x7FC00000]; + + [Theory] + [InlineData(1u, new uint[] { 0x80, 0xFF, 0x00, 0x00 }, 1)] + [InlineData(14u, new uint[] { 0x80, 0xFF, 0x00, 0x00 }, 1)] + [InlineData(56u, new uint[] { 0x80, 0xFF, 0x00, 0x00 }, 1)] + [InlineData(2u, new uint[] { 0x40, 0x7F, 0x81, 0x00 }, 1)] + [InlineData(13u, new uint[] { 0x3800, 0x3C00, 0xBC00 }, 2)] + [InlineData(22u, new uint[] { 0x3F000000, 0x3F800000, 0xBF800000, 0x7FC00000 }, 4)] + public void FormatsStoreTheirOwnEncodingThroughARuntimeDescriptor(uint format, uint[] expected, int elementBytes) + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan, shaderInt64: true)) return; + var program = Program( + Vop2(0, "VAddU32", 2, Operand((uint)GuestBase), Gen5Operand.Vector(0)), + ReadFirstLane(4, 12, 2), + MoveScalar(8, 13, (uint)(GuestBase >> 32)), + ScalarLoad(12, 12, 20, count: 4), + Vop2(20, "VLshlrevB32", 5, Operand(2), Gen5Operand.Vector(0)), + GlobalMemory(24, "GlobalLoadDword", 0, 5, 8, 8, offset: SourceOffset), + BufferAccess(32, "BufferStoreFormatX", 20, dwords: 1, vectorData: 8, offsetEnabled: true, vectorAddress: 5), + EndProgram(40)); + var (plan, resources, layout) = Prepare(program); + var request = new ShaderCompileRequest(plan, resources, layout) { LocalSizeX = 4, ThreadCountX = 4, ScratchDwords = 32 }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + var page = Enumerable.Repeat((byte)0xCC, (int)PageSize).ToArray(); + BinaryPrimitives.WriteUInt32LittleEndian(page.AsSpan(0), (uint)GuestBase + StoreOffset); + BinaryPrimitives.WriteUInt32LittleEndian(page.AsSpan(4), (uint)(GuestBase >> 32)); + BinaryPrimitives.WriteUInt32LittleEndian(page.AsSpan(8), 0x1000); + BinaryPrimitives.WriteUInt32LittleEndian(page.AsSpan(12), 4 | (5 << 3) | (6 << 6) | (7 << 9) | (format << 12)); + for (var lane = 0; lane < Values.Length; lane++) + { + BinaryPrimitives.WriteUInt32LittleEndian(page.AsSpan(SourceOffset + lane * 4), Values[lane]); + } + + using var harness = new ImageTestHarness(vulkan); + using var runner = new LayoutComputeRunner(harness, request, shader.Spirv); + var pageBuffer = runner.CreateBuffer(page, PageSize); + var fault = runner.CreateBuffer(TableEntries / 8 + 64); + var table = runner.CreatePageTable(TableEntries, [(GuestBase, pageBuffer, 0ul)]); + var registers = new uint[256]; + registers[0] = (uint)GuestBase; + registers[1] = (uint)(GuestBase >> 32); + harness.Run(() => runner.Dispatch(registers, + new Dictionary + { + [DescriptorBindingKind.DeviceAddressPageTable] = [table], + [DescriptorBindingKind.FaultBuffer] = [fault], + }, 1, flattenedTable: new uint[Math.Max(plan.FlattenedTableReservedCount, 1)])); + var stored = runner.ReadBack(pageBuffer, 0, PageSize); + harness.AssertNoValidationMessages(); + for (var lane = 0; lane < expected.Length; lane++) + { + var dword = BinaryPrimitives.ReadUInt32LittleEndian(stored.AsSpan(StoreOffset + lane * 4)); + var elementMask = elementBytes == 4 ? uint.MaxValue : (1u << (elementBytes * 8)) - 1; + Assert.Equal(expected[lane], dword & elementMask); + Assert.Equal(0xCCCCCCCCu & ~elementMask, dword & ~elementMask); + } + + output.WriteLine($"Verified format {format} on {vulkan!.DeviceName}."); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/FlattenedReadReuseDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/FlattenedReadReuseDeviceTests.cs index d7fd73be1..f36bbf427 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/FlattenedReadReuseDeviceTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/FlattenedReadReuseDeviceTests.cs @@ -27,7 +27,9 @@ public void EquivalentReads_StoreBothResultsWithoutAPageTable(uint components, b return; } - var request = Request(FlattenedReadReuseTests.RepeatedReadProgram(components), userDataCount: 9, tableBlock: tableBlock); + // This fixture exercises the host-flattened table without a guest page table, independent of the process policy. + var request = Request(FlattenedReadReuseTests.RepeatedReadProgram(components), userDataCount: 9, scalarDataOnDevice: false, + tableBlock: tableBlock); Assert.Equal(tableBlock, request.Bindings.UsesTableBlock); Assert.False(request.Resources.Info.UsesDeviceAddresses); Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/Float16ArithmeticDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/Float16ArithmeticDeviceTests.cs index d5807ab8e..e9ba95b65 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/Float16ArithmeticDeviceTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/Float16ArithmeticDeviceTests.cs @@ -32,6 +32,10 @@ public void MinimumThreeUsesSelectedSourceHalves(uint first, uint second, uint t [InlineData(0x4000u, 0x4200u, 0x3C00u, 0x4700u)] [InlineData(0x3C01u, 0x3BFEu, 0xBC00u, 0x8010u)] [InlineData(0x0001u, 0x3C00u, 0x0001u, 0x0002u)] + // Results halfway between two subnormals round to the even one. + [InlineData(0x0001u, 0x3800u, 0x0001u, 0x0002u)] + [InlineData(0x03FFu, 0x3800u, 0x0000u, 0x0200u)] + [InlineData(0x8003u, 0x3800u, 0x8000u, 0x8002u)] public void FusedAddLiteralRoundsOnlyAfterAddition(uint first, uint second, uint literal, uint expected) => CheckResult("VFmaAkF16", first, expected, second, literal); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/FloatMinMaxLoweringDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/FloatMinMaxLoweringDeviceTests.cs new file mode 100644 index 000000000..8426d82e0 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/FloatMinMaxLoweringDeviceTests.cs @@ -0,0 +1,151 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.Libs.Tests.Gpu.Vulkan; + +// V_MIN, V_MAX, V_MIN3, V_MAX3 and V_MED3 give the same bits in a module that declares SignedZeroInfNanPreserve as in one +// that does not, over every ordered triple of a value set (NaN payloads of both signs, quiet and signaling, zeros, +// subnormals, infinities, normals); GLSL NMin and NMax did not (two NaNs, subnormals). A NaN operand gives the RDNA2 result +// (IEEE mode off): a NaN S0 gives S1, a NaN S1 gives S0, so two NaNs give S1. +public sealed class FloatMinMaxLoweringDeviceTests(HeadlessVulkanFixture fixture) : IClassFixture +{ + private const int RowBytes = 32; + private const uint Lanes = 1024; + + private static readonly uint[] Float32Values = + [ + 0x7FC0_0000, 0xFFC0_0000, 0x7FC0_0001, 0x7FFF_FFFF, 0xFFFF_FFFF, 0x7FD2_3456, + 0x7F80_0001, 0xFF80_0001, 0x7FA0_0000, 0xFFBF_FFFF, + 0x0000_0000, 0x8000_0000, 0x0000_0001, 0x807F_FFFF, + 0x7F80_0000, 0xFF80_0000, 0x3F80_0000, 0xBF80_0000, 0x0080_0000, 0x7F7F_FFFF, + ]; + + private static readonly uint[] Float16Values = + [ + 0x7E00, 0xFE00, 0x7E01, 0x7FFF, 0xFFFF, 0x7C01, 0xFC01, 0x7D00, + 0x0000, 0x8000, 0x0001, 0x83FF, 0x7C00, 0xFC00, 0x3C00, 0xBC00, 0x0400, 0x7BFF, + ]; + + [Fact] + public void Float32LoweringsAgreeAndFollowTheGuestNanRule() + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan)) return; + var program = Program( + Vop2(0, "VAddU32", 1, Gen5Operand.Scalar(8), Gen5Operand.Vector(0)), + Vop2(4, "VLshlrevB32", 7, Operand(5), Gen5Operand.Vector(1)), + BufferAccess(8, "BufferLoadDwordx3", 4, dwords: 3, vectorData: 8, offsetEnabled: true, vectorAddress: 7), + Vop2(16, "VMinF32", 11, Gen5Operand.Vector(8), Gen5Operand.Vector(9)), + Vop2(20, "VMaxF32", 12, Gen5Operand.Vector(8), Gen5Operand.Vector(9)), + Vop3(24, "VMin3F32", 13, Gen5Operand.Vector(8), Gen5Operand.Vector(9), Gen5Operand.Vector(10)), + Vop3(32, "VMax3F32", 14, Gen5Operand.Vector(8), Gen5Operand.Vector(9), Gen5Operand.Vector(10)), + Vop3(40, "VMed3F32", 15, Gen5Operand.Vector(8), Gen5Operand.Vector(9), Gen5Operand.Vector(10)), + BufferAccess(48, "BufferStoreDwordx4", 4, offset: 12, dwords: 4, vectorData: 11, offsetEnabled: true, vectorAddress: 7), + BufferAccess(56, "BufferStoreDword", 4, offset: 28, vectorData: 15, offsetEnabled: true, vectorAddress: 7), + EndProgram(64)); + var rows = Rows(Float32Values); + var bitTests = Run(vulkan, program, rows, preserveNan: false); + var preserving = Run(vulkan, program, rows, preserveNan: true); + var count = Float32Values.Length * Float32Values.Length * Float32Values.Length; + for (var row = 0; row < count; row++) + { + var (a, b, c) = (Word(rows, row, 0), Word(rows, row, 1), Word(rows, row, 2)); + for (var output = 0; output < 5; output++) + { + Assert.True(Word(bitTests, row, 3 + output) == Word(preserving, row, 3 + output), + $"output {output} of ({a:X8}, {b:X8}, {c:X8}): bit tests {Word(bitTests, row, 3 + output):X8}, " + + $"NaN-preserving {Word(preserving, row, 3 + output):X8}"); + } + + if (IsNan(a) || IsNan(b)) + { + Assert.Equal(Minimum(a, b), Word(preserving, row, 3)); + Assert.Equal(Maximum(a, b), Word(preserving, row, 4)); + } + } + } + + [Fact] + public void Float16LoweringsAgree() + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan)) return; + var program = Program( + Vop2(0, "VAddU32", 1, Gen5Operand.Scalar(8), Gen5Operand.Vector(0)), + Vop2(4, "VLshlrevB32", 7, Operand(5), Gen5Operand.Vector(1)), + BufferAccess(8, "BufferLoadDwordx3", 4, dwords: 3, vectorData: 8, offsetEnabled: true, vectorAddress: 7), + Vop2(16, "VMaxF16", 11, Gen5Operand.Vector(8), Gen5Operand.Vector(9)), + Vop3(20, "VMax3F16", 12, Gen5Operand.Vector(8), Gen5Operand.Vector(9), Gen5Operand.Vector(10)), + Vop3(28, "VMed3F16", 13, Gen5Operand.Vector(8), Gen5Operand.Vector(9), Gen5Operand.Vector(10)), + BufferAccess(36, "BufferStoreDwordx3", 4, offset: 12, dwords: 3, vectorData: 11, offsetEnabled: true, vectorAddress: 7), + EndProgram(44)); + var rows = Rows(Float16Values); + var bitTests = Run(vulkan, program, rows, preserveNan: false); + var preserving = Run(vulkan, program, rows, preserveNan: true); + Assert.Equal(bitTests, preserving); + } + + private static bool IsNan(uint bits) => (bits & 0x7FFF_FFFF) > 0x7F80_0000; + + private static uint Minimum(uint a, uint b) => IsNan(a) ? b : IsNan(b) ? a + : BitConverter.UInt32BitsToSingle(a) < BitConverter.UInt32BitsToSingle(b) ? a : b; + + private static uint Maximum(uint a, uint b) => IsNan(a) ? b : IsNan(b) ? a + : BitConverter.UInt32BitsToSingle(a) > BitConverter.UInt32BitsToSingle(b) ? a : b; + + private static uint Word(byte[] bytes, int row, int word) => + BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(row * RowBytes + word * sizeof(uint))); + + // Every ordered triple of the value set, one 32-byte row each (a, b, c, then the results), padded to whole dispatches. + private static byte[] Rows(uint[] values) + { + var count = values.Length * values.Length * values.Length; + var rows = new byte[(count + (int)Lanes - 1) / (int)Lanes * (int)Lanes * RowBytes]; + var row = 0; + foreach (var a in values) + foreach (var b in values) + foreach (var c in values) + { + BinaryPrimitives.WriteUInt32LittleEndian(rows.AsSpan(row * RowBytes), a); + BinaryPrimitives.WriteUInt32LittleEndian(rows.AsSpan(row * RowBytes + 4), b); + BinaryPrimitives.WriteUInt32LittleEndian(rows.AsSpan(row * RowBytes + 8), c); + row++; + } + + return rows; + } + + private static byte[] Run(HeadlessVulkan vulkan, Gen5ShaderProgram program, byte[] rows, bool preserveNan) + { + var (plan, resources, layout) = Prepare(program); + var request = new ShaderCompileRequest(plan, resources, layout) + { + LocalSizeX = Lanes, ThreadCountX = Lanes, WaveSize = 32, ShaderSignedZeroInfNanPreserveFloat32Supported = preserveNan, + }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + using var harness = new ImageTestHarness(vulkan); + using var runner = new LayoutComputeRunner(harness, request, shader.Spirv); + var buffer = runner.CreateBuffer(rows); + var registers = new uint[256]; + registers[6] = (uint)rows.Length; + for (uint first = 0; first < rows.Length / RowBytes; first += Lanes) + { + registers[8] = first; + harness.Run(() => runner.Dispatch(registers, + new Dictionary { [DescriptorBindingKind.Buffers] = [buffer] }, 1)); + } + + var result = runner.ReadBack(buffer, 0, (ulong)rows.Length); + harness.AssertNoValidationMessages(); + return result; + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/FloatNanSemanticsDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/FloatNanSemanticsDeviceTests.cs index 3c5345d64..6832b09ad 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/FloatNanSemanticsDeviceTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/FloatNanSemanticsDeviceTests.cs @@ -64,4 +64,60 @@ public void ConversionsAndMinMaxFollowTheGuestNanRules( Enumerable.Range(0, 4).Select(index => BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(index * sizeof(uint)))).ToArray()); harness.AssertNoValidationMessages(); } + + // v_cvt_u32_f32 for every sign and exponent with the 64 lowest and 64 highest mantissas: NaN and every negative value + // (-0 and negative NaN included) give zero, +Inf and values from 2^32 saturate, the rest truncate. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void UnsignedConversionFollowsTheGuestForEveryExponent(bool preserveNan) + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan, shaderInt64: true)) return; + const uint lanes = 1024; + var rows = new byte[512 * 128 * 8]; + for (var head = 0u; head < 512; head++) + for (var low = 0u; low < 128; low++) + { + var bits = (head << 23) | (low < 64 ? low : 0x7F_FFFF - (low - 64)); + BinaryPrimitives.WriteUInt32LittleEndian(rows.AsSpan((int)((head * 128 + low) * 8)), bits); + } + + var program = Program( + Vop2(0, "VAddU32", 1, Gen5Operand.Scalar(8), Gen5Operand.Vector(0)), + Vop2(4, "VLshlrevB32", 7, Operand(3), Gen5Operand.Vector(1)), + BufferAccess(8, "BufferLoadDword", 4, vectorData: 2, offsetEnabled: true, vectorAddress: 7), + Vop1(16, "VCvtU32F32", 3, Gen5Operand.Vector(2)), + BufferAccess(20, "BufferStoreDword", 4, offset: 4, vectorData: 3, offsetEnabled: true, vectorAddress: 7), + EndProgram(28)); + var (plan, resources, layout) = Prepare(program); + var request = new ShaderCompileRequest(plan, resources, layout) + { + LocalSizeX = lanes, ThreadCountX = lanes, WaveSize = 32, ShaderSignedZeroInfNanPreserveFloat32Supported = preserveNan, + }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + using var harness = new ImageTestHarness(vulkan); + using var runner = new LayoutComputeRunner(harness, request, shader.Spirv); + var buffer = runner.CreateBuffer(rows); + var registers = new uint[256]; + registers[6] = (uint)rows.Length; + for (uint first = 0; first < rows.Length / 8; first += lanes) + { + registers[8] = first; + harness.Run(() => runner.Dispatch(registers, + new Dictionary { [DescriptorBindingKind.Buffers] = [buffer] }, 1)); + } + + var result = runner.ReadBack(buffer, 0, (ulong)rows.Length); + for (var row = 0; row < rows.Length / 8; row++) + { + var bits = BinaryPrimitives.ReadUInt32LittleEndian(result.AsSpan(row * 8)); + var value = BitConverter.UInt32BitsToSingle(bits); + var expected = float.IsNaN(value) || bits >= 0x8000_0000 ? 0u : value >= 4294967296f ? uint.MaxValue : (uint)value; + Assert.True(expected == BinaryPrimitives.ReadUInt32LittleEndian(result.AsSpan(row * 8 + 4)), + $"0x{bits:X8} converted to 0x{BinaryPrimitives.ReadUInt32LittleEndian(result.AsSpan(row * 8 + 4)):X8}, not 0x{expected:X8}"); + } + + harness.AssertNoValidationMessages(); + } } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/FmaMixDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/FmaMixDeviceTests.cs index b83bd08af..ff354e4ec 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/FmaMixDeviceTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/FmaMixDeviceTests.cs @@ -63,6 +63,57 @@ public void InlineFloatRemainsFullPrecisionWithHalfSelection() new Gen5Vop3pControl(1, 1, 0, 0, false), 2f); } + // A half operand widens exactly: fma(h, 1, -0) returns every f16 value as its f32 value, the subnormals and signed + // zeros included, and a NaN as a NaN. Each dispatch widens 1,024 consecutive bit patterns, one per lane. + [Fact] + public void EveryHalfOperandWidensExactly() + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan)) return; + const uint lanes = 1024; + var (plan, resources, layout) = Prepare(Program([ + Vop2(0, "VAddU32", 1, Gen5Operand.Scalar(8), Gen5Operand.Vector(0)), + new Gen5ShaderInstruction(4, Gen5ShaderEncoding.Vop3p, "VFmaMixF32", [0u, 0u], + [Gen5Operand.Vector(1), Gen5Operand.Source(242), new(Gen5OperandKind.LiteralConstant, 0x8000_0000)], + [Gen5Operand.Vector(2)], new Gen5Vop3pControl(0, 1, 0, 0, false)), + Vop2(16, "VLshlrevB32", 3, Operand(2), Gen5Operand.Vector(0)), + BufferAccess(20, "BufferStoreDword", 4, vectorData: 2, offsetEnabled: true, vectorAddress: 3), + EndProgram(28), + ])); + var request = new ShaderCompileRequest(plan, resources, layout) + { + LocalSizeX = lanes, ThreadCountX = lanes, WaveSize = 32, + }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + using var harness = new ImageTestHarness(vulkan); + using var runner = new LayoutComputeRunner(harness, request, shader.Spirv); + var output = runner.CreateBuffer(lanes * sizeof(uint)); + var registers = new uint[256]; + registers[6] = lanes * sizeof(uint); + for (uint first = 0; first <= ushort.MaxValue; first += lanes) + { + registers[8] = first; + harness.Run(() => runner.Dispatch(registers, + new Dictionary { [DescriptorBindingKind.Buffers] = [output] }, 1)); + var widened = runner.ReadBack(output, 0, lanes * sizeof(uint)); + for (var lane = 0u; lane < lanes; lane++) + { + var half = BitConverter.UInt16BitsToHalf((ushort)(first + lane)); + var actual = BinaryPrimitives.ReadUInt32LittleEndian(widened.AsSpan((int)(lane * sizeof(uint)))); + if (Half.IsNaN(half)) + { + Assert.True(float.IsNaN(BitConverter.UInt32BitsToSingle(actual)), $"f16 0x{first + lane:X4} widened to 0x{actual:X8}"); + } + else + { + Assert.Equal(BitConverter.SingleToUInt32Bits((float)half), actual); + } + } + } + + harness.AssertNoValidationMessages(); + } + private void CheckResult(string opcode, Gen5Operand[] sources, Gen5Vop3pControl control, float expected) { var vulkan = fixture.Vulkan; diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/GcnComputeDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/GcnComputeDeviceTests.cs index 25d38dc2a..415467a77 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/GcnComputeDeviceTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/GcnComputeDeviceTests.cs @@ -170,7 +170,8 @@ public void ScatterCopyPreservesLargeOffsetsAndChecksTheBoundView( output.Fill(destinationWord * 4UL, 256, 0xCDCDCDCD); runner.Dispatch(userData, new Dictionary { [DescriptorBindingKind.Buffers] = [command, data, output] }, 1, - bufferRanges: [12, 256, (destinationWord + (ulong)boundWords) * 4]); + bufferRanges: [12, 256, (destinationWord + (ulong)boundWords) * 4], + bufferStrides: [.. snapshot.Buffers.Select(static words => (words[1] >> 16) & 0x3FFF)]); }); var actual = runner.ReadBack(output, destinationWord * 4UL, 256); for (var index = (int)boundWords; index < values.Length; index++) values[index] = 0xCDCDCDCD; diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/HeadlessVulkan.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/HeadlessVulkan.cs index f6b21b063..ce981e4dd 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/HeadlessVulkan.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/HeadlessVulkan.cs @@ -49,6 +49,7 @@ private HeadlessVulkan(Vk vk, Instance instance, PhysicalDevice physical, Device public bool SupportsFragmentShaderBarycentric { get; private init; } public bool SupportsFillRectangle { get; private init; } public bool SupportsMeshShaders { get; private init; } + public bool SupportsTaskShaders { get; private init; } public bool CanRequireComputeSubgroup32 { get; private init; } public uint SubgroupSize { @@ -61,6 +62,16 @@ public uint SubgroupSize } } public bool SupportsImageInt64Atomics { get; private init; } + public bool SupportsBufferInt64Atomics { get; private init; } + + // As on the presenter's device: a storage buffer access past its descriptor's range reads zero and writes nothing. + public bool RobustBufferAccess2 { get; private init; } + + // As on the presenter's device: shaderFloat16 is enabled and the 16-bit float controls of + // ShaderCompileRequest.NativeFloat16Conversions are available. + public bool NativeFloat16Conversions { get; private init; } + + public bool SupportsGraphicsPipelineLibrary { get; private init; } private static readonly string[] RenderingExtensionNames = [ @@ -344,6 +355,42 @@ private void RegisterDebugMessenger() vk.GetPhysicalDeviceFeatures2(physical, &query); } var imageAtomicInt64 = (bool)imageAtomicInt64Features.ShaderImageInt64Atomics; + const string robustness2Extension = "VK_EXT_robustness2"; + var robustness2Features = new PhysicalDeviceRobustness2FeaturesEXT { SType = StructureType.PhysicalDeviceRobustness2FeaturesExt }; + if (HasDeviceExtensions(vk, physical, [robustness2Extension])) + { + var query = new PhysicalDeviceFeatures2 { SType = StructureType.PhysicalDeviceFeatures2, PNext = &robustness2Features }; + vk.GetPhysicalDeviceFeatures2(physical, &query); + } + var atomicInt64Features = new PhysicalDeviceShaderAtomicInt64Features + { + SType = StructureType.PhysicalDeviceShaderAtomicInt64Features, + }; + var atomicInt64Query = new PhysicalDeviceFeatures2 { SType = StructureType.PhysicalDeviceFeatures2, PNext = &atomicInt64Features }; + vk.GetPhysicalDeviceFeatures2(physical, &atomicInt64Query); + var float16Features = new PhysicalDeviceShaderFloat16Int8Features { SType = StructureType.PhysicalDeviceShaderFloat16Int8Features }; + var float16Query = new PhysicalDeviceFeatures2 { SType = StructureType.PhysicalDeviceFeatures2, PNext = &float16Features }; + vk.GetPhysicalDeviceFeatures2(physical, &float16Query); + var floatControls = new PhysicalDeviceFloatControlsProperties { SType = StructureType.PhysicalDeviceFloatControlsProperties }; + var floatControlsQuery = new PhysicalDeviceProperties2 { SType = StructureType.PhysicalDeviceProperties2, PNext = &floatControls }; + vk.GetPhysicalDeviceProperties2(physical, &floatControlsQuery); + var nativeFloat16 = float16Features.ShaderFloat16 && floatControls.ShaderRoundingModeRtefloat16 && + floatControls.ShaderDenormPreserveFloat16 && floatControls.ShaderSignedZeroInfNanPreserveFloat16 && + floatControls.RoundingModeIndependence == ShaderFloatControlsIndependence.IndependenceAll && + floatControls.DenormBehaviorIndependence == ShaderFloatControlsIndependence.IndependenceAll; + const string pipelineLibraryExtension = "VK_KHR_pipeline_library"; + const string graphicsPipelineLibraryExtension = "VK_EXT_graphics_pipeline_library"; + var graphicsPipelineLibraryFeatures = new PhysicalDeviceGraphicsPipelineLibraryFeaturesEXT + { + SType = StructureType.PhysicalDeviceGraphicsPipelineLibraryFeaturesExt, + }; + if (HasDeviceExtensions(vk, physical, [pipelineLibraryExtension, graphicsPipelineLibraryExtension])) + { + var query = new PhysicalDeviceFeatures2 { SType = StructureType.PhysicalDeviceFeatures2, PNext = &graphicsPipelineLibraryFeatures }; + vk.GetPhysicalDeviceFeatures2(physical, &query); + } + + var graphicsPipelineLibrary = (bool)graphicsPipelineLibraryFeatures.GraphicsPipelineLibrary; var vulkan13Features = new PhysicalDeviceVulkan13Features { @@ -372,6 +419,7 @@ private void RegisterDebugMessenger() vk.GetPhysicalDeviceFeatures(physical, out var baseFeatures); var meshShaders = meshFeatures.MeshShader && vulkan13Features.ComputeFullSubgroups && dynamicRendering; + var taskShaders = meshShaders && meshFeatures.TaskShader; var sizeControlProperties = new PhysicalDeviceSubgroupSizeControlProperties { SType = StructureType.PhysicalDeviceSubgroupSizeControlProperties, @@ -424,6 +472,17 @@ private void RegisterDebugMessenger() barycentricFeatures.PNext = vulkan13Features.PNext; vulkan13Features.PNext = &barycentricFeatures; } + var bufferInt64Atomics = (bool)atomicInt64Features.ShaderBufferInt64Atomics && baseFeatures.ShaderInt64; + if (bufferInt64Atomics) + { + atomicInt64Features = new PhysicalDeviceShaderAtomicInt64Features + { + SType = StructureType.PhysicalDeviceShaderAtomicInt64Features, + ShaderBufferInt64Atomics = true, + PNext = vulkan13Features.PNext, + }; + vulkan13Features.PNext = &atomicInt64Features; + } imageAtomicInt64 &= baseFeatures.ShaderInt64; if (imageAtomicInt64) { @@ -431,6 +490,27 @@ private void RegisterDebugMessenger() imageAtomicInt64Features.PNext = vulkan13Features.PNext; vulkan13Features.PNext = &imageAtomicInt64Features; } + if (nativeFloat16) + { + float16Features = new PhysicalDeviceShaderFloat16Int8Features + { + SType = StructureType.PhysicalDeviceShaderFloat16Int8Features, + ShaderFloat16 = true, + PNext = vulkan13Features.PNext, + }; + vulkan13Features.PNext = &float16Features; + } + var robustBufferAccess2 = (bool)robustness2Features.RobustBufferAccess2 && baseFeatures.RobustBufferAccess; + if (robustBufferAccess2) + { + robustness2Features = new PhysicalDeviceRobustness2FeaturesEXT + { + SType = StructureType.PhysicalDeviceRobustness2FeaturesExt, + RobustBufferAccess2 = true, + PNext = vulkan13Features.PNext, + }; + vulkan13Features.PNext = &robustness2Features; + } var extensionNames = new List(); if (meshShaders) { @@ -438,12 +518,26 @@ private void RegisterDebugMessenger() { SType = StructureType.PhysicalDeviceMeshShaderFeaturesExt, MeshShader = true, + TaskShader = taskShaders, PNext = vulkan13Features.PNext, }; vulkan13Features.PNext = &meshFeatures; extensionNames.Add(meshExtension); } if (imageAtomicInt64) extensionNames.Add(imageAtomicInt64Extension); + if (robustBufferAccess2) extensionNames.Add(robustness2Extension); + if (graphicsPipelineLibrary) + { + graphicsPipelineLibraryFeatures = new PhysicalDeviceGraphicsPipelineLibraryFeaturesEXT + { + SType = StructureType.PhysicalDeviceGraphicsPipelineLibraryFeaturesExt, + GraphicsPipelineLibrary = true, + PNext = vulkan13Features.PNext, + }; + vulkan13Features.PNext = &graphicsPipelineLibraryFeatures; + extensionNames.Add(pipelineLibraryExtension); + extensionNames.Add(graphicsPipelineLibraryExtension); + } if (dynamicRendering) extensionNames.AddRange(RenderingExtensionNames); if (barycentric) extensionNames.Add(barycentricExtension); const string fillRectangleExtension = "VK_NV_fill_rectangle"; @@ -478,8 +572,13 @@ private void RegisterDebugMessenger() SupportsFragmentShaderBarycentric = barycentric, SupportsFillRectangle = fillRectangle, SupportsMeshShaders = meshShaders, + SupportsTaskShaders = taskShaders, CanRequireComputeSubgroup32 = computeSubgroup32, SupportsImageInt64Atomics = imageAtomicInt64, + SupportsBufferInt64Atomics = bufferInt64Atomics, + SupportsGraphicsPipelineLibrary = graphicsPipelineLibrary, + RobustBufferAccess2 = robustBufferAccess2, + NativeFloat16Conversions = nativeFloat16, }; if (validation) { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/LargeStorageBindingDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/LargeStorageBindingDeviceTests.cs new file mode 100644 index 000000000..cd93bc1ed --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/LargeStorageBindingDeviceTests.cs @@ -0,0 +1,73 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Silk.NET.Vulkan; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.Libs.Tests.Gpu.Vulkan; + +// A guest buffer can span more than 2 GiB (a geometry pool of 0xAB000000 bytes): the program reads a word near the start +// and one near the end of the binding. +public sealed unsafe class LargeStorageBindingDeviceTests(HeadlessVulkanFixture fixture) : IClassFixture +{ + private const uint NearOffset = 0x100; + private const uint NearValue = 0x11223344; + private const uint FarValue = 0x55667788; + + [Theory] + [InlineData(0x7FFF_0000UL)] + [InlineData(0x8001_0000UL)] + [InlineData(0xAB00_0000UL)] + public void LoadsReadBothEndsOfTheBinding(ulong range) + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan)) return; + if (vulkan.DeviceInfo.MaxStorageBufferRange < range) + { + Assert.False(GatePrerequisites.DeviceRequired && range < 0x8000_0000UL, "The device limits storage bindings below 2 GiB."); + return; + } + + var farOffset = (uint)(range - 0x100); + var program = Program( + MoveVector(0, 0, farOffset), + BufferAccess(8, "BufferLoadDword", 4, offset: (int)NearOffset, vectorData: 4), + BufferAccess(16, "BufferLoadDword", 4, offset: 0, vectorData: 5, offsetEnabled: true, vectorAddress: 0), + BufferAccess(24, "BufferStoreDword", 8, offset: 0, vectorData: 4), + BufferAccess(32, "BufferStoreDword", 8, offset: 4, vectorData: 5), + EndProgram(40)); + var (plan, resources, layout) = Prepare(program); + var request = new ShaderCompileRequest(plan, resources, layout) { LocalSizeX = 32, ThreadCountX = 32, WaveSize = 32 }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + using var harness = new ImageTestHarness(vulkan); + using var runner = new LayoutComputeRunner(harness, request, shader.Spirv); + using var pool = new GpuBuffer(harness.Device, harness.Scheduler, GpuBufferUsage.DeviceLocal, 0, GpuBuffer.AllFlags, range); + var result = runner.CreateBuffer(64); + var registers = new uint[256]; + registers[4] = 0x1000; registers[6] = (uint)range; + registers[8] = 0x2000; registers[10] = 64; + harness.Run(() => + { + var command = new CommandBuffer(harness.Scheduler.Current.Handle); + var near = NearValue; + var far = FarValue; + harness.Vk.CmdUpdateBuffer(command, pool.Handle, NearOffset, sizeof(uint), &near); + harness.Vk.CmdUpdateBuffer(command, pool.Handle, farOffset, sizeof(uint), &far); + runner.Dispatch(registers, + new Dictionary { [DescriptorBindingKind.Buffers] = [pool, result] }, 1, + bufferRanges: [range, 64]); + }); + + var words = runner.ReadBack(result, 0, 8); + Assert.Equal(NearValue, BinaryPrimitives.ReadUInt32LittleEndian(words)); + Assert.Equal(FarValue, BinaryPrimitives.ReadUInt32LittleEndian(words.AsSpan(4))); + harness.AssertNoValidationMessages(); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/LayoutComputeRunner.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/LayoutComputeRunner.cs index e7dc9964a..d7dc85197 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/LayoutComputeRunner.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/LayoutComputeRunner.cs @@ -219,6 +219,8 @@ public void Dispatch( uint[]? memoryOffsets = null, ulong[]? callArguments = null, ulong[]? callTargets = null, + uint[]? bufferStrides = null, + IReadOnlyList? imageDescriptors = null, uint[]? tessellationData = null) { var vk = _harness.Vk; @@ -256,6 +258,20 @@ public void Dispatch( shaderData[layout.MemoryOffsetDword + (uint)index / 4] |= (memoryOffsets[index] & 0xFF) << (index % 4 * 8); } + // The V# stride of each buffer binding, as BindBuffers writes it, for indexed buffer accesses. + if (layout.BufferStrideCount != 0) + { + if (bufferStrides?.Length != layout.BufferStrideCount) throw new InvalidOperationException("The dispatch requires its buffer strides."); + for (var index = 0; index < bufferStrides.Length; index++) + shaderData[layout.BufferStridesDword + (uint)index / 2] |= (bufferStrides[index] & 0x3FFF) << (index % 2 * 16); + } + + // Each written image's store channel map, as BindBuffers writes it from the bound T#s. + if (imageDescriptors is not null) + { + RuntimeImageSwizzle.WriteStoreMaps(shaderData, layout, _request.Resources.Info.Images, imageDescriptors); + } + if (layout.UsesDispatchThreadLimits) { if (dispatchThreadLimits is not { Length: 3 }) throw new InvalidOperationException("The dispatch requires three thread limits."); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/LayoutImageShaderTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/LayoutImageShaderTests.cs index f1f362f45..fd14eed01 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/LayoutImageShaderTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/LayoutImageShaderTests.cs @@ -147,12 +147,14 @@ private static ImageDescription Describe(ulong guestOffset, Format format, Guest private sealed class Run : IDisposable { - public Run(HeadlessVulkan vulkan, Gen5ShaderProgram program, uint[] registers, uint threadCount, bool imageInt64Atomics = false) + public Run(HeadlessVulkan vulkan, Gen5ShaderProgram program, uint[] registers, uint threadCount, bool imageInt64Atomics = false, + Func? specialize = null) { Plan = ShaderResourcePlan.Extract(program, ShaderStage.Compute, 0x5348_4152_5045_4D55, 0, 64); var snapshot = new ResourceSnapshot(); var specialization = new ResourceSpecialization(); Assert.True(ResourceMaterializer.Materialize(Plan, Inputs(registers), ref snapshot, ref specialization)); + specialization = specialize?.Invoke(specialization) ?? specialization; Snapshot = snapshot; Resources = ResourceMaterializer.ApplyTo(Plan, specialization); var layout = BindingLayout.Allocate( @@ -432,6 +434,53 @@ public void EqualDescriptorSourcesSampleThroughSharedBindings(bool distinctImage output.WriteLine($"Verified descriptor aliases on {vulkan.DeviceName}; validation={vulkan.ValidationEnabled}."); } + // The program above with one image and one sampler descriptor repeated, bound once (the draw's groups) or to each of its + // resources (a specialization without groups): both sample the same texel, and the shared sampler as well. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void RepeatedDescriptorsSampleTheSameBoundOnceOrToEachResource(bool bindingEach) + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan)) return; + var program = Program( + MoveVector(0, 0, 0x3F00_0000), MoveVector(4, 1, 0x3F00_0000), + Image(8, "ImageSampleLz", 16, 32, dmask: 1), + BufferAccess(16, "BufferStoreDword", ResultRegister, 0, vectorData: 4), + Image(24, "ImageSampleLz", 24, 36, dmask: 1), + BufferAccess(32, "BufferStoreDword", ResultRegister, 4, vectorData: 4), EndProgram(40)); + var registers = UserData(); + uint[] descriptor = [(uint)FirstImageAddress, Format32Float << 20, 0, 0xFAC | (ImageType2D << 28), 0, 0, 0, 0]; + descriptor.CopyTo(registers, 16); + descriptor.CopyTo(registers, 24); + using var run = new Run(vulkan, program, registers, 1, specialize: bindingEach ? WithoutGroups : null); + var imageClass = ImageDescriptorBinding.ForImage(run.Resources.Info.Images[0])!.Value; + Assert.Equal(bindingEach ? 2 : 1, run.Request.Bindings.Find(imageClass)!.Resources.Count); + Assert.Equal(bindingEach ? 2 : 1, run.Request.Bindings.Find(DescriptorBindingKind.Samplers)!.Resources.Count); + var image = run.Harness.CreateImage(Describe(0, Format.R32Sfloat, GuestPixelFormat.Bits32Float, 2, 1, 1)); + run.Harness.UploadImage(image, MemoryMarshal.AsBytes([0.25f, 0.75f]), ImageTestHarness.WholeImageCopies(image.Description, 0)); + var sampler = run.Runner.CreateSampler(Filter.Linear); + var views = new Dictionary { [0] = [SampledView(image)], [1] = [SampledView(image)] }; + run.Dispatch(run.BindImages(views, [sampler, sampler]), command => + image.Transition(AccessFlags.ShaderReadBit, null, command)); + + // Both resources sample the centre of the same two-texel image through the same linear sampler: the texels' mean. + Assert.Equal(BitConverter.SingleToUInt32Bits(0.5f), run.ResultWord(0)); + Assert.Equal(BitConverter.SingleToUInt32Bits(0.5f), run.ResultWord(1)); + run.Harness.AssertNoValidationMessages(); + output.WriteLine($"Verified repeated descriptors bound {(bindingEach ? "to each resource" : "once")} on {vulkan.DeviceName}."); + } + + // The specialization with no descriptor groups: every image and sampler resource its own binding. + private static ResourceSpecialization WithoutGroups(ResourceSpecialization specialization) => new() + { + BaseBufferCount = specialization.BaseBufferCount, + StableImageBindings = specialization.StableImageBindings, + Buffers = [.. specialization.Buffers], + Images = [.. specialization.Images], + BufferCandidateTables = [.. specialization.BufferCandidateTables], + }; + // Image 0 is plain, image 1 the indirect root, image 2 its candidate for key 1; a mip load // reads texel (0, 0) of mip 1 of two-level images. [Theory] @@ -572,7 +621,7 @@ public void DirectImageTableUsesCapturedOffset(uint mask, uint expected, bool sp [InlineData(0x80000000u, true, 91u)] [InlineData(1u, false, 91u)] [InlineData(0x80000000u, false, 37u)] - public void MixedImageDimensionsSelectTheirOwnBinding(uint mask, bool arrayFirst, uint expected) + public void MixedImageDimensionsReadTheirOwnTexture(uint mask, bool arrayFirst, uint expected) { var vulkan = fixture.Vulkan; if (!GatePrerequisites.Ready(vulkan)) return; @@ -585,7 +634,10 @@ public void MixedImageDimensionsSelectTheirOwnBinding(uint mask, bool arrayFirst var views = new DescriptorImageInfo[images.Length]; for (var index = 0; index < images.Length; index++) { - var array = request.Resources.Info.Images[index].Dimension == ImageDimension.Dim2DArray; + // The T# says what the texture holds; the module reads a 2D one, whose only layer it reads at slice 1, as a + // one-layer array. + var array = snapshot.Images[index][3] >> 28 == 13; + var arrayView = request.Resources.Info.Images[index].Dimension == ImageDimension.Dim2DArray; var description = Describe((ulong)index * 0x10000, Format.R32Uint, GuestPixelFormat.Bits32UInt, 1, 1, 1); description.Resources = new SubresourceCount(1, array ? 2u : 1u); images[index] = harness.CreateImage(description); @@ -596,7 +648,7 @@ public void MixedImageDimensionsSelectTheirOwnBinding(uint mask, bool arrayFirst ImageView = images[index].GetOrCreateView(ImageViewDescription.Default with { Format = Format.R32Uint, - Type = array ? ImageViewType.Type2DArray : ImageViewType.Type2D, + Type = arrayView ? ImageViewType.Type2DArray : ImageViewType.Type2D, LayerCount = description.Resources.Layers, }), ImageLayout = ImageLayout.General, diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/NativeFloat16ConversionDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/NativeFloat16ConversionDeviceTests.cs new file mode 100644 index 000000000..d59c7859e --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/NativeFloat16ConversionDeviceTests.cs @@ -0,0 +1,525 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.Numerics; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using Xunit.Abstractions; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.Libs.Tests.Gpu.Vulkan; + +// With NativeFloat16Conversions the f16 conversions are OpFConvert under the 16-bit float controls, and the f16 add, subtract, +// multiply, maximum and median are f16 ops. Each kernel runs translated both ways and must give the same bits: every f32 +// narrowed (all 2^32 patterns, as x * 1 + -0 through V_FMA_MIXLO_F16), every f16 widened (all 2^16, through V_FMA_MIX_F32 from +// either half, V_MAX_F16 and V_PK_MAX_F16), the f16 arithmetic over every ordered pair of halves (all 2^32) and, with its +// modifiers and constants, over every ordered triple of a value set. The narrowing and widening also match System.Half, and a +// NaN narrows to 0x7E00 with its sign. V_CVT_F16_F32 and V_CVT_F32_F16 (GLSL packing) keep their bits in a module that declares +// the float controls. +public sealed class NativeFloat16ConversionDeviceTests(HeadlessVulkanFixture fixture, ITestOutputHelper output) + : IClassFixture +{ + private const uint Lanes = 1024; + private const uint WorkGroupRegister = 9; + + private static readonly ushort[] Halves = + [ + 0x0000, 0x8000, 0x0001, 0x8001, 0x0002, 0x03FF, 0x83FF, 0x0400, 0x8400, 0x0401, + 0x1400, 0x2E66, 0x3555, 0xB555, 0x3800, 0x3BFF, 0x3C00, 0xBC00, 0x3C01, 0x4000, + 0x4200, 0x4900, 0x5640, 0x5BFF, 0x6BFF, 0x77FF, 0x7800, 0x7BFE, 0x7BFF, 0xFBFF, + 0x7C00, 0xFC00, 0x7E00, 0xFE00, 0x7C01, 0xFC01, 0x7FFF, 0x7D55, 0x0200, 0x8200, + ]; + + public static IEnumerable Parts() => Enumerable.Range(0, 16).Select(part => new object[] { (uint)part }); + + // 2^28 patterns per part, in 64 dispatches of 4,096 groups. A result word is the narrowed half (low) and V_CVT_F16_F32 (high). + [Theory] + [MemberData(nameof(Parts))] + public void EveryFloatNarrowsAsTheIntegerSequence(uint part) + { + if (!Ready()) return; + const uint groups = 4096, count = groups * Lanes; + using var pair = new KernelPair(fixture.Vulkan!, Kernel(1, + Mix("VFmaMixloF16", 10, [Gen5Operand.Vector(1), Gen5Operand.Source(242), new(Gen5OperandKind.LiteralConstant, 0x8000_0000)], + new Gen5Vop3pControl(0, 0, 0, 0, false)), + MoveVector(0, 11, 0), + Vop1(0, "VCvtF16F32", 11, Gen5Operand.Vector(1)), + Vop2(0, "VLshlrevB32", 11, Operand(16), Gen5Operand.Vector(11)), + Vop2(0, "VOrB32", 10, Gen5Operand.Vector(10), Gen5Operand.Vector(11))), new byte[count * 4], preserveNan: true); + long positiveNans = 0, negativeNans = 0, packDiffers = 0; + var wrong = new List(); + long integerWrong = 0, nativeWrong = 0, unequal = 0; + for (var dispatch = 0u; dispatch < 64; dispatch++) + { + var first = (part << 28) + dispatch * count; + pair.Dispatch(first, groups); + var (integer, native) = pair.Read(); + for (var index = 0; index < count; index++) + { + var bits = first + (uint)index; + var word = BinaryPrimitives.ReadUInt32LittleEndian(integer.AsSpan(index * 4)); + var nativeWord = BinaryPrimitives.ReadUInt32LittleEndian(native.AsSpan(index * 4)); + var value = BitConverter.UInt32BitsToSingle(bits); + // A NaN reaches the narrowing as the NaN the device's FMA returns, so either sign is right. + var nan = float.IsNaN(value); + var expected = nan ? word & 0xFFFF : BitConverter.HalfToUInt16Bits((Half)value); + var integerOk = nan ? expected is 0x7E00 or 0xFE00 : (word & 0xFFFF) == expected; + var nativeOk = (nativeWord & 0xFFFF) == expected; + if (integerOk && nativeOk && word == nativeWord) + { + if (nan && expected == 0x7E00) positiveNans++; + else if (nan) negativeNans++; + else if (word >> 16 != expected) packDiffers++; + continue; + } + + integerWrong += integerOk ? 0 : 1; + nativeWrong += nativeOk ? 0 : 1; + unequal += word == nativeWord ? 0 : 1; + if (wrong.Count < 12) + wrong.Add($"f32 0x{bits:X8}: expected 0x{expected:X4}, integer 0x{word:X8}, native 0x{nativeWord:X8}"); + } + } + + output.WriteLine($"part {part}: NaN results +{positiveNans} -{negativeNans}; " + + $"V_CVT_F16_F32 differs from the narrowing for {packDiffers} other inputs"); + Assert.True(wrong.Count == 0, $"integer wrong {integerWrong}, native wrong {nativeWrong}, unequal {unequal}:" + + Environment.NewLine + string.Join(Environment.NewLine, wrong)); + } + + // All 2^16 patterns in one dispatch: V_FMA_MIX_F32 (h * 1 + -0) from the low half and from the high half, V_MAX_F16 (h, h), + // V_PK_MAX_F16 with h in both halves, and V_CVT_F32_F16. + [Fact] + public void EveryHalfWidensAsTheIntegerSequence() + { + if (!Ready()) return; + const uint count = 1u << 16, words = 8; + using var pair = new KernelPair(fixture.Vulkan!, Kernel(words, + Vop2(0, "VLshlrevB32", 4, Operand(16), Gen5Operand.Vector(1)), + Vop2(0, "VOrB32", 5, Gen5Operand.Vector(1), Gen5Operand.Vector(4)), + Mix("VFmaMixF32", 10, [Gen5Operand.Vector(1), Gen5Operand.Source(242), new(Gen5OperandKind.LiteralConstant, 0x8000_0000)], + new Gen5Vop3pControl(0, 1, 0, 0, false)), + Mix("VFmaMixF32", 11, [Gen5Operand.Vector(4), Gen5Operand.Source(242), new(Gen5OperandKind.LiteralConstant, 0x8000_0000)], + new Gen5Vop3pControl(1, 1, 0, 0, false)), + Vop2(0, "VMaxF16", 12, Gen5Operand.Vector(1), Gen5Operand.Vector(1)), + Mix("VPkMaxF16", 13, [Gen5Operand.Vector(5), Gen5Operand.Vector(5)], new Gen5Vop3pControl(0, 3, 0, 0, false)), + Vop1(0, "VCvtF32F16", 14, Gen5Operand.Vector(1))), new byte[count * words * 4], preserveNan: true); + pair.Dispatch(0, count / Lanes); + var (integer, native) = pair.Read(); + AssertSame(integer, native, word => $"f16 0x{word / words:X4} result {word % words}"); + var payloadsKept = 0; + for (var bits = 0u; bits < count; bits++) + { + uint Word(int index) => BinaryPrimitives.ReadUInt32LittleEndian(integer.AsSpan((int)(bits * words + index) * 4)); + var half = BitConverter.UInt16BitsToHalf((ushort)bits); + var widened = BitConverter.SingleToUInt32Bits((float)half); + var narrowed = Half.IsNaN(half) ? (bits & 0x8000) | 0x7E00 : bits; + if (Half.IsNaN(half)) + { + Assert.True(float.IsNaN(BitConverter.UInt32BitsToSingle(Word(0))), $"f16 0x{bits:X4} widened to 0x{Word(0):X8}"); + if (Word(0) == (((bits & 0x8000) << 16) | 0x7F80_0000 | ((bits & 0x3FF) << 13))) payloadsKept++; + } + else + { + Assert.True(Word(0) == widened && Word(1) == widened, + $"f16 0x{bits:X4} widened to 0x{Word(0):X8} and 0x{Word(1):X8}, not 0x{widened:X8}"); + } + + Assert.True(Word(2) == narrowed && Word(3) == (narrowed | (narrowed << 16)), + $"f16 0x{bits:X4}: maximum 0x{Word(2):X8}, packed maximum 0x{Word(3):X8}"); + } + + output.WriteLine($"{payloadsKept} of 2048 NaN results of V_FMA_MIX_F32 keep the f16 payload"); + } + + // Every ordered triple (a, b, c) of the value set, one 64-byte row each: the inputs, then 13 results. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void HalfArithmeticKeepsItsBits(bool preserveNan) + { + if (!Ready()) return; + var program = Program(Numbered( + [ + Vop2(0, "VAddU32", 1, Gen5Operand.Scalar(8), Gen5Operand.Vector(0)), + Vop2(0, "VLshlrevB32", 7, Operand(6), Gen5Operand.Vector(1)), + BufferAccess(0, "BufferLoadDwordx3", 4, dwords: 3, vectorData: 8, offsetEnabled: true, vectorAddress: 7), + Vop2(0, "VLshlrevB32", 30, Operand(16), Gen5Operand.Vector(9)), + Vop2(0, "VOrB32", 30, Gen5Operand.Vector(8), Gen5Operand.Vector(30)), + Vop2(0, "VLshlrevB32", 31, Operand(16), Gen5Operand.Vector(8)), + Vop2(0, "VOrB32", 31, Gen5Operand.Vector(10), Gen5Operand.Vector(31)), + .. Enumerable.Range(11, 13).Select(register => MoveVector(0, (uint)register, 0)), + Vop2(0, "VAddF16", 11, Gen5Operand.Vector(8), Gen5Operand.Vector(9)), + Vop2(0, "VMulF16", 12, Gen5Operand.Vector(8), Gen5Operand.Vector(9)), + Vop3(0, "VFmaF16", 13, Gen5Operand.Vector(8), Gen5Operand.Vector(9), Gen5Operand.Vector(10)), + Vop1(0, "VRcpF16", 14, Gen5Operand.Vector(8)), + Vop1(0, "VSqrtF16", 15, Gen5Operand.Vector(8)), + Vop3(0, "VMax3F16", 16, Gen5Operand.Vector(8), Gen5Operand.Vector(9), Gen5Operand.Vector(10)), + Vop3(0, "VMed3F16", 17, Gen5Operand.Vector(8), Gen5Operand.Vector(9), Gen5Operand.Vector(10)), + Mix("VFmaMixloF16", 18, [Gen5Operand.Vector(8), Gen5Operand.Vector(9), Gen5Operand.Vector(10)], new Gen5Vop3pControl(0, 7, 0, 0, false)), + Mix("VFmaMixF32", 19, [Gen5Operand.Vector(8), Gen5Operand.Vector(9), Gen5Operand.Vector(10)], new Gen5Vop3pControl(0, 7, 0, 0, false)), + Mix("VPkAddF16", 20, [Gen5Operand.Vector(30), Gen5Operand.Vector(31)], new Gen5Vop3pControl(0, 3, 0, 0, false)), + Mix("VPkMulF16", 21, [Gen5Operand.Vector(30), Gen5Operand.Vector(31)], new Gen5Vop3pControl(0, 3, 0, 0, false)), + Mix("VPkFmaF16", 22, [Gen5Operand.Vector(30), Gen5Operand.Vector(31), Gen5Operand.Vector(30)], new Gen5Vop3pControl(0, 7, 0, 0, false)), + Vop2(0, "VMaxF16", 23, Gen5Operand.Vector(8), Gen5Operand.Vector(9)), + BufferAccess(0, "BufferStoreDwordx4", 4, offset: 12, dwords: 4, vectorData: 11, offsetEnabled: true, vectorAddress: 7), + BufferAccess(0, "BufferStoreDwordx4", 4, offset: 28, dwords: 4, vectorData: 15, offsetEnabled: true, vectorAddress: 7), + BufferAccess(0, "BufferStoreDwordx4", 4, offset: 44, dwords: 4, vectorData: 19, offsetEnabled: true, vectorAddress: 7), + BufferAccess(0, "BufferStoreDword", 4, offset: 60, vectorData: 23, offsetEnabled: true, vectorAddress: 7), + ])); + const int rowBytes = 64; + var count = Halves.Length * Halves.Length * Halves.Length; + var rows = new byte[(count + (int)Lanes - 1) / (int)Lanes * (int)Lanes * rowBytes]; + var row = 0; + foreach (var a in Halves) + foreach (var b in Halves) + foreach (var c in Halves) + { + BinaryPrimitives.WriteUInt32LittleEndian(rows.AsSpan(row * rowBytes), a); + BinaryPrimitives.WriteUInt32LittleEndian(rows.AsSpan(row * rowBytes + 4), b); + BinaryPrimitives.WriteUInt32LittleEndian(rows.AsSpan(row * rowBytes + 8), c); + row++; + } + + using var pair = new KernelPair(fixture.Vulkan!, program, rows, preserveNan); + for (var first = 0u; first < rows.Length / rowBytes; first += Lanes) + { + pair.Dispatch(first, 1); + } + + var (integer, native) = pair.Read(); + AssertSame(integer, native, word => + { + var index = word / (rowBytes / 4); + return index >= count ? $"padding row {index}" + : $"({Halves[index / (Halves.Length * Halves.Length)]:X4}, {Halves[index / Halves.Length % Halves.Length]:X4}, " + + $"{Halves[index % Halves.Length]:X4}) result {word % (rowBytes / 4) - 3}"; + }); + } + + // Every ordered pair of halves, 2^28 per part in 64 dispatches of 4,096 groups: a in the low half of v1 and b in the high + // half. The words are V_ADD_F16, V_SUB_F16, V_MUL_F16 and V_MAX_F16 of (a, b) (VOP3, b through op_sel), then V_PK_ADD_F16, + // V_PK_MUL_F16, V_PK_MAX_F16 and V_PK_MIN_F16 of the pairs (a, b) and (b, a). The 16 parts take several minutes on a + // desktop GPU, so they run only with SHARPEMU_TEST_EXHAUSTIVE_F16=1; HalfArithmeticModifiersKeepTheirBits always runs. + [Theory] + [MemberData(nameof(Parts))] + public void EveryHalfPairComputesAsTheFloatSequence(uint part) + { + if (Environment.GetEnvironmentVariable("SHARPEMU_TEST_EXHAUSTIVE_F16") != "1" || !Ready()) return; + const uint groups = 4096, count = groups * Lanes, words = 8; + string[] names = ["V_ADD_F16", "V_SUB_F16", "V_MUL_F16", "V_MAX_F16", "V_PK_ADD_F16", "V_PK_MUL_F16", "V_PK_MAX_F16", "V_PK_MIN_F16"]; + using var pair = new KernelPair(fixture.Vulkan!, Kernel(words, + [ + Vop2(0, "VLshlrevB32", 5, Operand(16), Gen5Operand.Vector(1)), + Vop2(0, "VLshrrevB32", 6, Operand(16), Gen5Operand.Vector(1)), + Vop2(0, "VOrB32", 4, Gen5Operand.Vector(5), Gen5Operand.Vector(6)), + .. new[] { "VAddF16", "VSubF16", "VMulF16", "VMaxF16" }.Select((opcode, index) => + Vop3With(opcode, 10 + (uint)index, Modifiers(select: 2), Gen5Operand.Vector(1), Gen5Operand.Vector(1))), + .. new[] { "VPkAddF16", "VPkMulF16", "VPkMaxF16", "VPkMinF16" }.Select((opcode, index) => + Mix(opcode, 14 + (uint)index, [Gen5Operand.Vector(1), Gen5Operand.Vector(4)], new Gen5Vop3pControl(0, 3, 0, 0, false))), + ]), new byte[count * words * 4], preserveNan: true); + var unequal = new long[words]; + var differences = new List(); + for (var dispatch = 0u; dispatch < 64; dispatch++) + { + var first = (part << 28) + dispatch * count; + pair.Dispatch(first, groups); + var (integer, native) = pair.Read(); + if (integer.AsSpan().SequenceEqual(native)) continue; + for (var word = 0; word < integer.Length / 4; word++) + { + var expected = BinaryPrimitives.ReadUInt32LittleEndian(integer.AsSpan(word * 4)); + var actual = BinaryPrimitives.ReadUInt32LittleEndian(native.AsSpan(word * 4)); + if (expected == actual) continue; + var bits = first + (uint)(word / words); + if (unequal[word % words]++ == 0 || differences.Count < 12) + differences.Add($"{names[word % words]} (0x{bits & 0xFFFF:X4}, 0x{bits >> 16:X4}): f32 forms 0x{expected:X8}, f16 0x{actual:X8}"); + } + } + + Assert.True(differences.Count == 0, $"unequal results {string.Join(", ", unequal.Select((n, i) => $"{names[i]} {n}"))}:" + + Environment.NewLine + string.Join(Environment.NewLine, differences)); + } + + // Every ordered triple (a, b, c) of the value set, one 256-byte row each: the inputs, then the f16 ops with abs, neg, clamp, + // op_sel and output modifiers and inline and literal constants, and the packed ops with op_sel, op_sel_hi, neg_lo, neg_hi, + // clamp and constants. Among them are the constants and modifiers that keep the f32 forms (1/(2 pi), NaN, omod). Without + // SignedZeroInfNanPreserve for 32 bits the f32 forms may fold x + -x, x - x, x * -0, x + 0 and an operand's negated copy + // (fast math), so those results depend on the code around them and are compared only with it. A maximum, minimum or + // median with a negated operand keeps the f32 forms, whose NaN result after a float negation has the sign the driver + // leaves it (Vulkan keeps no NaN bits: a driver may keep it for -b, -c and drop it for x, -x); a NaN lane of those + // is compared without its sign. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void HalfArithmeticModifiersKeepTheirBits(bool preserveNan) + { + if (!Ready()) return; + var a = Gen5Operand.Vector(8); + var b = Gen5Operand.Vector(9); + var c = Gen5Operand.Vector(10); + var ab = Gen5Operand.Vector(30); + var ca = Gen5Operand.Vector(31); + var bc = Gen5Operand.Vector(32); + Gen5Operand Literal(uint value) => new(Gen5OperandKind.LiteralConstant, value); + Gen5Vop3pControl Packed(uint select = 0, uint selectHigh = 3, uint negateLow = 0, uint negateHigh = 0, bool clamp = false) => + new(select, selectHigh, negateLow, negateHigh, clamp); + (string Name, Func Emit)[] cases = + [ + ("add a b", d => Vop2(0, "VAddF16", d, a, b)), + ("subrev a b", d => Vop2(0, "VSubrevF16", d, a, b)), + ("add -a |b|", d => Vop3With("VAddF16", d, Modifiers(absolute: 2, negate: 1), a, b)), + ("sub |a| -b clamp", d => Vop3With("VSubF16", d, Modifiers(absolute: 1, negate: 2, clamp: true), a, b)), + ("mul -a -b clamp", d => Vop3With("VMulF16", d, Modifiers(negate: 3, clamp: true), a, b)), + ("mul b a to the high half", d => Vop3With("VMulF16", d, Modifiers(select: 11), ab, ca)), + ("max -a |b|", d => Vop3With("VMaxF16", d, Modifiers(absolute: 2, negate: 1), a, b)), + ("max -a -b clamp", d => Vop3With("VMaxF16", d, Modifiers(negate: 3, clamp: true), a, b)), + ("max3 -a b |c|", d => Vop3With("VMax3F16", d, Modifiers(absolute: 4, negate: 1), a, b, c)), + ("med3 |a| -b c clamp", d => Vop3With("VMed3F16", d, Modifiers(absolute: 1, negate: 2, clamp: true), a, b, c)), + ("med3 b a -c", d => Vop3With("VMed3F16", d, Modifiers(negate: 4, select: 3), ab, ca, c)), + ("add a 1.0", d => Vop3With("VAddF16", d, Modifiers(), a, Gen5Operand.Source(242))), + ("mul a 1/(2 pi)", d => Vop3With("VMulF16", d, Modifiers(), a, Gen5Operand.Source(248))), + ("mul -a -0.5", d => Vop3With("VMulF16", d, Modifiers(negate: 1), a, Gen5Operand.Source(241))), + ("add 5 b", d => Vop3With("VAddF16", d, Modifiers(), Gen5Operand.Source(133), b)), + ("sub a 0x3555", d => Vop3With("VSubF16", d, Modifiers(), a, Literal(0x3555))), + ("max a NaN", d => Vop3With("VMaxF16", d, Modifiers(), a, Literal(0xFD55))), + ("mul a -0", d => Vop3With("VMulF16", d, Modifiers(), a, Literal(0x8000))), + ("add a -0", d => Vop3With("VAddF16", d, Modifiers(), a, Literal(0x8000))), + ("mul a 1.0", d => Vop3With("VMulF16", d, Modifiers(), a, Gen5Operand.Source(242))), + ("sub a b omod 2", d => Vop3With("VSubF16", d, Modifiers(outputModifier: 1), a, b)), + ("max a b", d => Vop2(0, "VMaxF16", d, a, b)), + ("mul c b", d => Vop2(0, "VMulF16", d, c, b)), + ("max3 a b c clamp to the high half", d => Vop3With("VMax3F16", d, Modifiers(clamp: true, select: 8), a, b, c)), + ("pk_add ab ca", d => Mix("VPkAddF16", d, [ab, ca], Packed())), + ("pk_add bb cc", d => Mix("VPkAddF16", d, [ab, ca], Packed(select: 1, selectHigh: 1))), + ("pk_mul -ab c-a", d => Mix("VPkMulF16", d, [ab, ca], Packed(negateLow: 1, negateHigh: 2))), + ("pk_mul aa bb clamp", d => Mix("VPkMulF16", d, [ab, bc], Packed(selectHigh: 0, clamp: true))), + ("pk_max -a-b -ca", d => Mix("VPkMaxF16", d, [ab, ca], Packed(negateLow: 3, negateHigh: 1))), + ("pk_min ab cb", d => Mix("VPkMinF16", d, [ab, bc], Packed(select: 2, selectHigh: 1))), + ("pk_max ca ab clamp", d => Mix("VPkMaxF16", d, [ca, ab], Packed(clamp: true))), + ("pk_add ab 1.0", d => Mix("VPkAddF16", d, [ab, Gen5Operand.Source(242)], Packed())), + ("pk_mul ab (0.5, -1)", d => Mix("VPkMulF16", d, [ab, Literal(0xBC00_3800)], Packed())), + ("pk_min ab -1 (NaN halves)", d => Mix("VPkMinF16", d, [ab, Gen5Operand.Source(193)], Packed())), + ("pk_add ab -ab", d => Mix("VPkAddF16", d, [ab, ab], Packed(negateLow: 2, negateHigh: 2))), + ("pk_mul ac cb", d => Mix("VPkMulF16", d, [ca, bc], Packed(select: 3, selectHigh: 0))), + ("pk_max ab -b-c", d => Mix("VPkMaxF16", d, [ab, bc], Packed(negateHigh: 3))), + ("pk_min -ab ca clamp", d => Mix("VPkMinF16", d, [ab, ca], Packed(negateLow: 1, clamp: true))), + ("add a -a", d => Vop3With("VAddF16", d, Modifiers(negate: 2), a, a)), + ("sub a a", d => Vop2(0, "VSubF16", d, a, a)), + ("subrev -a -a", d => Vop3With("VSubrevF16", d, Modifiers(negate: 3), a, a)), + ("max a -a", d => Vop3With("VMaxF16", d, Modifiers(negate: 2), a, a)), + ("pk_add -ab ab", d => Mix("VPkAddF16", d, [ab, ab], Packed(negateLow: 1, negateHigh: 1))), + ("pk_mul ab -ab", d => Mix("VPkMulF16", d, [ab, ab], Packed(negateLow: 2, negateHigh: 2))), + ("pk_add ab ab", d => Mix("VPkAddF16", d, [ab, ab], Packed())), + ("pk_max ab -ab", d => Mix("VPkMaxF16", d, [ab, ab], Packed(negateLow: 2, negateHigh: 2))), + ]; + string[] fastMath = ["mul a -0", "add a -0", "pk_add ab 1.0", "add a -a", "sub a a", "subrev -a -a", "max a -a", + "pk_add -ab ab", "pk_mul ab -ab", "pk_add ab ab", "pk_add ab -ab", "pk_max ab -ab"]; + string[] negatedSelection = ["max -a |b|", "max3 -a b |c|", "med3 b a -c", "pk_max -a-b -ca", "pk_max ab -b-c", + "max a -a", "pk_max ab -ab"]; + Assert.All(fastMath.Concat(negatedSelection), name => Assert.Contains(cases, test => test.Name == name)); + const uint first = 40; + var results = (uint)cases.Length; + var program = Program(Numbered( + [ + Vop2(0, "VAddU32", 1, Gen5Operand.Scalar(8), Gen5Operand.Vector(0)), + Vop2(0, "VLshlrevB32", 7, Operand(8), Gen5Operand.Vector(1)), + BufferAccess(0, "BufferLoadDwordx3", 4, dwords: 3, vectorData: 8, offsetEnabled: true, vectorAddress: 7), + Vop2(0, "VLshlrevB32", 30, Operand(16), b), + Vop2(0, "VOrB32", 30, a, ab), + Vop2(0, "VLshlrevB32", 31, Operand(16), a), + Vop2(0, "VOrB32", 31, c, ca), + Vop2(0, "VLshlrevB32", 32, Operand(16), c), + Vop2(0, "VOrB32", 32, b, bc), + .. Enumerable.Range((int)first, (int)(results + 3) / 4 * 4).Select(register => MoveVector(0, (uint)register, 0)), + .. cases.Select((test, index) => test.Emit(first + (uint)index)), + .. Enumerable.Range(0, (int)(results + 3) / 4).Select(store => BufferAccess(0, "BufferStoreDwordx4", 4, + offset: 16 + store * 16, dwords: 4, vectorData: first + (uint)store * 4, offsetEnabled: true, vectorAddress: 7)), + ])); + const int rowBytes = 256; + var count = Halves.Length * Halves.Length * Halves.Length; + var rows = new byte[(count + (int)Lanes - 1) / (int)Lanes * (int)Lanes * rowBytes]; + var row = 0; + foreach (var first16 in Halves) + foreach (var second in Halves) + foreach (var third in Halves) + { + BinaryPrimitives.WriteUInt32LittleEndian(rows.AsSpan(row * rowBytes), first16); + BinaryPrimitives.WriteUInt32LittleEndian(rows.AsSpan(row * rowBytes + 4), second); + BinaryPrimitives.WriteUInt32LittleEndian(rows.AsSpan(row * rowBytes + 8), third); + row++; + } + + using var pair = new KernelPair(fixture.Vulkan!, program, rows, preserveNan); + for (var start = 0u; start < rows.Length / rowBytes; start += Lanes) + { + pair.Dispatch(start, 1); + } + + var (integer, native) = pair.Read(); + var unequal = new int[cases.Length]; + var differences = new List(); + for (var index = 0; index < count; index++) + { + for (var result = 0; result < cases.Length; result++) + { + if (!preserveNan && fastMath.Contains(cases[result].Name)) continue; + var offset = index * rowBytes + 16 + result * 4; + var expected = BinaryPrimitives.ReadUInt32LittleEndian(integer.AsSpan(offset)); + var actual = BinaryPrimitives.ReadUInt32LittleEndian(native.AsSpan(offset)); + if (negatedSelection.Contains(cases[result].Name) && NanSignless(expected) == NanSignless(actual)) continue; + if (expected == actual || unequal[result]++ >= 3) continue; + differences.Add($"{cases[result].Name} ({Halves[index / (Halves.Length * Halves.Length)]:X4}, " + + $"{Halves[index / Halves.Length % Halves.Length]:X4}, {Halves[index % Halves.Length]:X4}): " + + $"f32 forms 0x{expected:X8}, f16 0x{actual:X8}"); + } + } + + Assert.True(differences.Count == 0, string.Join(", ", unequal.Select((n, i) => (n, i)).Where(c => c.n > 0) + .Select(c => $"{cases[c.i].Name}: {c.n}")) + Environment.NewLine + string.Join(Environment.NewLine, differences)); + } + + // A word with the sign bit of each NaN half cleared. + private static uint NanSignless(uint word) + { + foreach (var shift in new[] { 0, 16 }) + { + if (((word >> shift) & 0x7FFF) > 0x7C00) word &= ~(0x8000u << shift); + } + + return word; + } + + private static Gen5Vop3Control Modifiers( + uint absolute = 0, uint negate = 0, uint outputModifier = 0, bool clamp = false, uint select = 0) => + new(absolute, negate, outputModifier, clamp, select, null); + + private static Gen5ShaderInstruction Vop3With(string opcode, uint destination, Gen5Vop3Control control, params Gen5Operand[] sources) => + Vop3(0, opcode, destination, sources) with { Control = control }; + + private bool Ready() + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan)) return false; + if (vulkan.NativeFloat16Conversions) return true; + Assert.False(GatePrerequisites.DeviceRequired, "The device lacks shaderFloat16 or the 16-bit float controls."); + return false; + } + + private static Gen5ShaderInstruction Mix(string opcode, uint destination, Gen5Operand[] sources, Gen5Vop3pControl control) => + new(0, Gen5ShaderEncoding.Vop3p, opcode, [0u, 0u], sources, [Gen5Operand.Vector(destination)], control); + + // The instructions with consecutive addresses, then s_endpgm. + private static Gen5ShaderInstruction[] Numbered(params Gen5ShaderInstruction[] body) => + [.. body.Append(EndProgram(0)).Select((instruction, index) => instruction with { Pc = (uint)index * 8 })]; + + // v1 = s8 + the invocation's index in the dispatch (its work group in s9); the results v10.., cleared first, are stored as + // `words` (1, 2, 4 or 8) consecutive dwords per invocation. + private static Gen5ShaderProgram Kernel(uint words, params Gen5ShaderInstruction[] body) + { + var instructions = new List + { + Sop2(0, "SLshlB32", 10, Gen5Operand.Scalar(WorkGroupRegister), Operand(10)), + Vop2(0, "VAddU32", 2, Gen5Operand.Scalar(10), Gen5Operand.Vector(0)), + Vop2(0, "VAddU32", 1, Gen5Operand.Scalar(8), Gen5Operand.Vector(2)), + Vop2(0, "VLshlrevB32", 3, Operand(2 + (uint)BitOperations.Log2(words)), Gen5Operand.Vector(2)), + }; + instructions.AddRange(Enumerable.Range(10, (int)words).Select(register => MoveVector(0, (uint)register, 0))); + instructions.AddRange(body); + for (var word = 0u; word < words; word += 4) + { + var dwords = Math.Min(4, words - word); + instructions.Add(BufferAccess(0, dwords == 1 ? "BufferStoreDword" : $"BufferStoreDwordx{dwords}", 4, offset: (int)word * 4, + dwords: dwords, vectorData: 10 + word, offsetEnabled: true, vectorAddress: 3)); + } + + return Program(Numbered([.. instructions])); + } + + private static void AssertSame(byte[] integer, byte[] native, Func describe) + { + if (integer.AsSpan().SequenceEqual(native)) return; + var differences = new List(); + var count = 0; + for (var word = 0; word < integer.Length / 4; word++) + { + var expected = BinaryPrimitives.ReadUInt32LittleEndian(integer.AsSpan(word * 4)); + var actual = BinaryPrimitives.ReadUInt32LittleEndian(native.AsSpan(word * 4)); + if (expected == actual) continue; + if (count++ < 8) differences.Add($"{describe(word)}: integer conversions 0x{expected:X8}, native 0x{actual:X8}"); + } + + Assert.Fail($"{count} words differ, first:{Environment.NewLine}{string.Join(Environment.NewLine, differences)}"); + } + + // One kernel translated with the integer conversions and with the native ones, each with a copy of the buffer. + private sealed class KernelPair : IDisposable + { + private readonly ImageTestHarness _harness; + private readonly (LayoutComputeRunner Runner, GpuBuffer Buffer)[] _kernels; + private readonly uint _size; + + public KernelPair(HeadlessVulkan vulkan, Gen5ShaderProgram program, byte[] buffer, bool preserveNan) + { + _harness = new ImageTestHarness(vulkan); + _size = (uint)buffer.Length; + _kernels = [.. new[] { false, true }.Select(native => + { + var (plan, resources, layout) = Prepare(program, userDataCount: WorkGroupRegister); + var request = new ShaderCompileRequest(plan, resources, layout) + { + LocalSizeX = Lanes, WaveSize = 32, ShaderSignedZeroInfNanPreserveFloat32Supported = preserveNan, + ComputeSystemRegisters = new Gen5ComputeSystemRegisters(WorkGroupRegister, null, null, null), + NativeFloat16Conversions = native, + }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + Assert.Equal(native, DeclaresFloat16(shader.Spirv)); + var runner = new LayoutComputeRunner(_harness, request, shader.Spirv); + return (runner, runner.CreateBuffer(buffer)); + })]; + } + + public void Dispatch(uint first, uint groups) + { + var registers = new uint[256]; + registers[6] = _size; + registers[8] = first; + foreach (var (runner, buffer) in _kernels) + { + _harness.Run(() => runner.Dispatch(registers, + new Dictionary { [DescriptorBindingKind.Buffers] = [buffer] }, groups)); + } + } + + public (byte[] Integer, byte[] Native) Read() + { + var results = _kernels.Select(kernel => kernel.Runner.ReadBack(kernel.Buffer, 0, _size)).ToArray(); + _harness.AssertNoValidationMessages(); + return (results[0], results[1]); + } + + public void Dispose() + { + foreach (var (runner, _) in _kernels) runner.Dispose(); + _harness.Dispose(); + } + + private static bool DeclaresFloat16(byte[] spirv) + { + for (var offset = 20; offset < spirv.Length;) + { + var header = BinaryPrimitives.ReadUInt32LittleEndian(spirv.AsSpan(offset)); + if ((header & 0xFFFF) == (uint)SpirvOp.Capability && + BinaryPrimitives.ReadUInt32LittleEndian(spirv.AsSpan(offset + 4)) == (uint)SpirvCapability.Float16) return true; + offset += (int)(header >> 16) * 4; + } + + return false; + } + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/ReadFirstLaneWave32DeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/ReadFirstLaneWave32DeviceTests.cs new file mode 100644 index 000000000..6d2b9527e --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/ReadFirstLaneWave32DeviceTests.cs @@ -0,0 +1,67 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.Libs.Tests.Gpu.Vulkan; + +// V_READFIRSTLANE_B32 reads the first lane EXEC enables, and lane 0 when EXEC is empty (RDNA2 ISA 12.8). +public sealed class ReadFirstLaneWave32DeviceTests(HeadlessVulkanFixture fixture) : IClassFixture +{ + private const uint ThreadCount = 32; + private const uint Exec = 126; + + [Theory] + [InlineData(0u, 100u)] + [InlineData(7u, 107u)] + [InlineData(31u, 131u)] + [InlineData(32u, 100u)] + public void ReadsTheFirstActiveLaneAndLaneZeroWhenNoneIsActive(uint firstActiveLane, uint expected) + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan, shaderInt64: true)) return; + var instructions = new List(); + uint pc = 0; + void Add(Gen5ShaderInstruction instruction) + { + instructions.Add(instruction with { Pc = pc }); + pc += 8; + } + + Add(Vop2(0, "VAddU32", 3, Operand(100), Gen5Operand.Vector(0))); + Add(Vopc(0, "VCmpxLeU32", Operand(firstActiveLane), 0)); + Add(ReadFirstLane(0, 20, 3)); + Add(Sop1(0, "SMovB64", Exec, Gen5Operand.Source(193))); + Add(MoveVectorFromScalar(0, 4, 20)); + Add(Vop2(0, "VLshlrevB32", 5, Operand(2), Gen5Operand.Vector(0))); + Add(BufferAccess(0, "BufferStoreDword", 4, vectorData: 4, offsetEnabled: true, vectorAddress: 5)); + Add(EndProgram(0)); + var (plan, resources, layout) = Prepare(Program([.. instructions])); + var request = new ShaderCompileRequest(plan, resources, layout) + { + LocalSizeX = ThreadCount, ThreadCountX = ThreadCount, WaveSize = 32, + }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + using var harness = new ImageTestHarness(vulkan); + using var runner = new LayoutComputeRunner(harness, request, shader.Spirv); + var result = runner.CreateBuffer(ThreadCount * sizeof(uint)); + var registers = new uint[256]; + registers[6] = ThreadCount * sizeof(uint); + harness.Run(() => runner.Dispatch(registers, + new Dictionary { [DescriptorBindingKind.Buffers] = [result] }, 1)); + var actual = runner.ReadBack(result, 0, ThreadCount * sizeof(uint)); + for (var lane = 0; lane < ThreadCount; lane++) + { + Assert.Equal(expected, BinaryPrimitives.ReadUInt32LittleEndian(actual.AsSpan(lane * sizeof(uint)))); + } + + harness.AssertNoValidationMessages(); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/RobustBufferLoadDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/RobustBufferLoadDeviceTests.cs new file mode 100644 index 000000000..77d96a4a3 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/RobustBufferLoadDeviceTests.cs @@ -0,0 +1,120 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.Libs.Tests.Gpu.Vulkan; + +// With robustBufferAccess2 on the device a guest buffer load is a plain load (ShaderCompileRequest.RobustBufferAccess2). It +// must read what the bounds-checked load reads: the view's dwords, zero past the view though the buffer goes on, and zero +// at the top of the 32-bit byte space, where a dword index passes 2^30 (a byte offset past 4 GiB). +public sealed class RobustBufferLoadDeviceTests(HeadlessVulkanFixture fixture) : IClassFixture +{ + private const uint ViewBytes = 64; + private const int BufferDwords = 64; + private const uint Lanes = 32; + private const uint RowBytes = 32; + + // Lane i loads dword i (the view ends at dword 16) and the four dwords from byte 0xFFFFFF80 + 4i (dword indices + // 0x3FFFFFE0 + i to 0x3FFFFFE3 + i, past 2^30 for the last lanes). + [Fact] + public void VectorLoadsReadWhatBoundsCheckedLoadsRead() + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan, robustBufferAccess2: true)) return; + var program = Program( + Vop2(0, "VLshlrevB32", 1, Operand(2), Gen5Operand.Vector(0)), + BufferAccess(4, "BufferLoadDword", 4, vectorData: 2, offsetEnabled: true, vectorAddress: 1), + Vop2(12, "VAddU32", 3, new Gen5Operand(Gen5OperandKind.LiteralConstant, 0xFFFF_FF80), Gen5Operand.Vector(1)), + BufferAccess(20, "BufferLoadDwordx4", 4, dwords: 4, vectorData: 4, offsetEnabled: true, vectorAddress: 3), + Vop2(28, "VLshlrevB32", 8, Operand(5), Gen5Operand.Vector(0)), + BufferAccess(32, "BufferStoreDword", 8, vectorData: 2, offsetEnabled: true, vectorAddress: 8), + BufferAccess(40, "BufferStoreDwordx4", 8, offset: 4, dwords: 4, vectorData: 4, offsetEnabled: true, vectorAddress: 8), + EndProgram(48)); + + var robust = Run(vulkan, program, robust: true, Lanes, new uint[256]); + var bounded = Run(vulkan, program, robust: false, Lanes, new uint[256]); + + Assert.Equal(bounded, robust); + for (var lane = 0u; lane < Lanes; lane++) + { + Assert.Equal(lane < ViewBytes / 4 ? Word(lane) : 0u, Read(robust, lane, 0)); + for (var index = 1u; index <= 4; index++) + { + Assert.Equal(0u, Read(robust, lane, index)); + } + } + } + + // A scalar load with a dynamic offset: two dwords from byte 60 (the view's last dword, then the first past it) and + // sixteen from byte 0xFFFFFFFC (dword indices 0x3FFFFFFF to 0x4000000E). + [Fact] + public void ScalarLoadsReadWhatBoundsCheckedLoadsRead() + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan, robustBufferAccess2: true)) return; + var program = Program( + ScalarBufferLoad(0, 4, 20, count: 2, dynamicOffsetRegister: 16), + ScalarBufferLoad(8, 4, 24, count: 16, dynamicOffsetRegister: 17), + MoveVectorFromScalar(16, 2, 20), + MoveVectorFromScalar(20, 3, 21), + MoveVectorFromScalar(24, 4, 24), + MoveVectorFromScalar(28, 5, 25), + MoveVectorFromScalar(32, 6, 39), + BufferAccess(36, "BufferStoreDwordx4", 8, dwords: 4, vectorData: 2), + BufferAccess(44, "BufferStoreDword", 8, offset: 16, vectorData: 6), + EndProgram(52)); + var registers = new uint[256]; + registers[16] = 60; + registers[17] = 0xFFFF_FFFC; + + var robust = Run(vulkan, program, robust: true, 1, registers); + var bounded = Run(vulkan, program, robust: false, 1, registers); + + Assert.Equal(bounded, robust); + Assert.Equal([Word(15), 0u, 0u, 0u, 0u], Enumerable.Range(0, 5).Select(index => Read(robust, 0, (uint)index)).ToArray()); + } + + private static uint Word(uint index) => 0xA000_0000 | index; + + private static uint Read(byte[] rows, uint lane, uint word) => + BinaryPrimitives.ReadUInt32LittleEndian(rows.AsSpan((int)(lane * RowBytes + word * sizeof(uint)))); + + // The source buffer holds 64 dwords behind a 16-dword view; the result buffer has a row of 8 dwords per lane. + private static byte[] Run(HeadlessVulkan vulkan, Gen5ShaderProgram program, bool robust, uint lanes, uint[] registers) + { + var (plan, resources, layout) = Prepare(program); + var request = new ShaderCompileRequest(plan, resources, layout) + { + LocalSizeX = lanes, ThreadCountX = lanes, WaveSize = 32, RobustBufferAccess2 = robust, + }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + using var harness = new ImageTestHarness(vulkan); + using var runner = new LayoutComputeRunner(harness, request, shader.Spirv); + var words = new byte[BufferDwords * sizeof(uint)]; + for (var index = 0; index < BufferDwords; index++) + { + BinaryPrimitives.WriteUInt32LittleEndian(words.AsSpan(index * sizeof(uint)), Word((uint)index)); + } + + var source = runner.CreateBuffer(words); + var result = runner.CreateBuffer(Lanes * RowBytes); + registers[4] = 0x1000; + registers[6] = ViewBytes; + registers[8] = 0x2000; + registers[10] = Lanes * RowBytes; + harness.Run(() => runner.Dispatch(registers, + new Dictionary { [DescriptorBindingKind.Buffers] = [source, result] }, 1, + bufferRanges: [ViewBytes, Lanes * RowBytes])); + var rows = runner.ReadBack(result, 0, Lanes * RowBytes); + harness.AssertNoValidationMessages(); + return rows; + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/RuntimeBufferStrideDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/RuntimeBufferStrideDeviceTests.cs new file mode 100644 index 000000000..6c5ca6dd7 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/RuntimeBufferStrideDeviceTests.cs @@ -0,0 +1,52 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.Libs.Tests.Gpu.Vulkan; + +// An indexed buffer access multiplies its index by its binding's V# stride at run time, so one module serves every +// stride a game binds. +public sealed class RuntimeBufferStrideDeviceTests(HeadlessVulkanFixture fixture) : IClassFixture +{ + [Fact] + public void OneModuleLoadsTheIndexedElementOfEachStride() + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan)) return; + // v1 = 2; v4 = source[v1 * stride]; result[0] = v4. + var program = Program( + MoveVector(0, 1, 2), + BufferAccess(8, "BufferLoadDword", 4, offset: 0, vectorData: 4, indexEnabled: true, vectorAddress: 1), + BufferAccess(16, "BufferStoreDword", 8, offset: 0, vectorData: 4), + EndProgram(24)); + var input = new byte[64]; + BinaryPrimitives.WriteUInt32LittleEndian(input.AsSpan(2 * 4), 0xAAAA0004); + BinaryPrimitives.WriteUInt32LittleEndian(input.AsSpan(2 * 12), 0xBBBB000C); + var (plan, resources, layout) = Prepare(program); + Assert.Equal(2u, layout.BufferStrideCount); + var request = new ShaderCompileRequest(plan, resources, layout) { LocalSizeX = 32, ThreadCountX = 32, WaveSize = 32 }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + using var harness = new ImageTestHarness(vulkan!); + using var runner = new LayoutComputeRunner(harness, request, shader.Spirv); + var source = runner.CreateBuffer(input); + foreach (var (stride, expected) in new[] { (4u, 0xAAAA0004u), (12u, 0xBBBB000Cu) }) + { + var result = runner.CreateBuffer(64); + var registers = new uint[256]; + registers[4] = 0x1000; registers[5] = stride << 16; registers[6] = 4; + registers[8] = 0x2000; registers[10] = 64; + harness.Run(() => runner.Dispatch(registers, + new Dictionary { [DescriptorBindingKind.Buffers] = [source, result] }, 1, + bufferRanges: [64, 64], memoryOffsets: [0, 0], bufferStrides: [stride, 0])); + Assert.Equal(expected, BinaryPrimitives.ReadUInt32LittleEndian(runner.ReadBack(result, 0, 4))); + } + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/RuntimeImageSwizzleDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/RuntimeImageSwizzleDeviceTests.cs new file mode 100644 index 000000000..cd20003db --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/RuntimeImageSwizzleDeviceTests.cs @@ -0,0 +1,204 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE.GpuMemory; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Gpu.Images; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Silk.NET.Vulkan; +using Xunit; +using Xunit.Abstractions; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.Libs.Tests.Gpu.Vulkan; + +// A store through a storage image whose destination select is shader data writes, bit for bit, the texel a module with +// the select baked in writes: every permutation of XYZW and a sample of other selects, two dmasks, and common storage +// formats (8-bit unorm, 16-bit float with 32-bit and D16 data, 32-bit uint and float). One module serves every select. +public sealed class RuntimeImageSwizzleDeviceTests(HeadlessVulkanFixture fixture, ITestOutputHelper output) : IClassFixture +{ + private const uint ImageType2D = 9; + private const uint ResourceRegister = 8; + // X001, XYZ1, XXXX, 0000, 1111, ZYX0, XYXY. + private static readonly uint[] OtherSelects = [0x204, 0x3AC, 0x924, 0x000, 0x249, 0x12E, 0xB2C]; + + public static TheoryData Formats() => new() + { + { 56, Format.R8G8B8A8Unorm, GuestPixelFormat.Bits8_8_8_8UNorm, 4, false }, + { 71, Format.R16G16B16A16Sfloat, GuestPixelFormat.Bits16_16_16_16Float, 8, false }, + { 71, Format.R16G16B16A16Sfloat, GuestPixelFormat.Bits16_16_16_16Float, 8, true }, + { 75, Format.R32G32B32A32Uint, GuestPixelFormat.Bits32_32_32_32UInt, 16, false }, + { 77, Format.R32G32B32A32Sfloat, GuestPixelFormat.Bits32_32_32_32Float, 16, false }, + }; + + [Theory] + [MemberData(nameof(Formats))] + public void RuntimeSelectStoresWriteTheBakedTexelBitForBit(uint guestFormat, Format format, GuestPixelFormat pixelFormat, + uint texelBytes, bool d16) + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan)) + { + return; + } + + using var harness = new ImageTestHarness(vulkan!); + var selects = Permutations().Concat(OtherSelects).ToArray(); + var stores = 0; + foreach (var dmask in new[] { 0xFu, 0x5u }) + { + byte[]? shared = null; + foreach (var select in selects) + { + var baked = Store(harness, guestFormat, format, pixelFormat, texelBytes, d16, dmask, select, runtime: false); + var runtime = Store(harness, guestFormat, format, pixelFormat, texelBytes, d16, dmask, select, runtime: true); + Assert.Equal(baked.Texel, runtime.Texel); + Assert.NotEqual(baked.Spirv, runtime.Spirv); + shared ??= runtime.Spirv; + Assert.Equal(shared, runtime.Spirv); + stores++; + if (select == 0xF2E && dmask == 0xF) + { + // ZYXW: the X channel holds the third component. + Assert.Equal(Texel(guestFormat, d16, dmask, select)[..(int)(texelBytes / 4)], baked.Texel[..(int)(texelBytes / 4)]); + } + } + } + + harness.AssertNoValidationMessages(); + output.WriteLine($"Compared {stores} baked and runtime-select stores of format {guestFormat} (d16={d16}) on {vulkan!.DeviceName}."); + } + + // The 24 orderings of X, Y, Z and W. + private static IEnumerable Permutations() + { + foreach (var x in new uint[] { 4, 5, 6, 7 }) + foreach (var y in new uint[] { 4, 5, 6, 7 }) + foreach (var z in new uint[] { 4, 5, 6, 7 }) + foreach (var w in new uint[] { 4, 5, 6, 7 }) + { + if (new[] { x, y, z, w }.Distinct().Count() == 4) + { + yield return x | (y << 3) | (z << 6) | (w << 9); + } + } + } + + // The data registers' values: distinct per component, exact in the format. + private static uint[] Data(uint guestFormat, bool d16) + { + if (d16) + { + return [Half(1.5f) | (Half(2.5f) << 16), Half(3.5f) | (Half(4.5f) << 16)]; + } + + return guestFormat switch + { + 56 => [Bits(0.2f), Bits(0.4f), Bits(0.6f), Bits(0.8f)], + 75 => [0x1111_1111, 0x2222_2222, 0x3333_3333, 0x4444_4444], + _ => [Bits(1.5f), Bits(2.5f), Bits(3.5f), Bits(4.5f)], + }; + + static uint Bits(float value) => BitConverter.SingleToUInt32Bits(value); + static uint Half(float value) => BitConverter.HalfToUInt16Bits((Half)value); + } + + // The bytes of the texel a store of every component through select writes (the expectation for one known select). + private static byte[] Texel(uint guestFormat, bool d16, uint dmask, uint select) + { + var bytes = new List(); + float[] floats = guestFormat == 56 ? [0.2f, 0.4f, 0.6f, 0.8f] : [1.5f, 2.5f, 3.5f, 4.5f]; + uint[] uints = [0x1111_1111, 0x2222_2222, 0x3333_3333, 0x4444_4444]; + for (var channel = 0; channel < 4; channel++) + { + var component = Gen5ShaderTranslator.GetImageStoreSourceIndex(select, dmask, channel); + switch (guestFormat) + { + case 56: + bytes.Add(component < 0 ? (byte)0 : (byte)Math.Round(floats[component] * 255)); + break; + case 71: + var half = component < 0 ? (ushort)0 : BitConverter.HalfToUInt16Bits((Half)floats[component]); + bytes.AddRange(BitConverter.GetBytes(half)); + break; + case 75: + bytes.AddRange(BitConverter.GetBytes(component < 0 ? 0u : uints[component])); + break; + default: + bytes.AddRange(BitConverter.GetBytes(component < 0 ? 0f : floats[component])); + break; + } + } + + _ = d16; + return [.. bytes]; + } + + private static (byte[] Texel, byte[] Spirv) Store(ImageTestHarness harness, uint guestFormat, Format format, + GuestPixelFormat pixelFormat, uint texelBytes, bool d16, uint dmask, uint select, bool runtime) + { + // v1, v2 = (0, 0); the data registers from v4; one store of the dmask's components to texel (0, 0). + var instructions = new List { MoveVector(0, 1, 0), MoveVector(8, 2, 0) }; + var pc = 16u; + foreach (var (word, index) in Data(guestFormat, d16).Select((word, index) => (word, index))) + { + instructions.Add(MoveVector(pc, 4 + (uint)index, word)); + pc += 8; + } + + var control = new Gen5ImageControl(dmask, 1, [1, 2, 3], 4, ResourceRegister, 0, 1, false, Glc: false, Slc: false, A16: false, D16: d16); + instructions.Add(new Gen5ShaderInstruction(pc, Gen5ShaderEncoding.Mimg, "ImageStore", [0u, 0u], + [Gen5Operand.Vector(1), Gen5Operand.Scalar(ResourceRegister), Gen5Operand.Scalar(0)], [], control)); + instructions.Add(EndProgram(pc + 8)); + var program = Program([.. instructions]); + var userData = new uint[16]; + userData[ResourceRegister] = 0x1000; + userData[ResourceRegister + 1] = guestFormat << 20; + userData[ResourceRegister + 2] = 1 | (1 << 14); + userData[ResourceRegister + 3] = (ImageType2D << 28) | select; + var plan = ShaderResourcePlan.Extract(program, ShaderStage.Compute, Hash, 0, 16, runtimeImageSwizzles: runtime); + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + Assert.True(ResourceMaterializer.Materialize(plan, Inputs(userData), ref snapshot, ref specialization, out var failure), + failure.ToString()); + var resources = ResourceMaterializer.ApplyTo(plan, specialization); + var layout = BindingLayout.Allocate(resources.Info, BindingLayout.CollectUserDataRegisters(program, 0, 16), false, + ShaderCompileRequest.RequiresFlattenedTable(plan, resources), false); + Assert.Equal(runtime ? 1u : 0u, layout.StorageImageSwizzleCount); + var request = new ShaderCompileRequest(plan, resources, layout) { LocalSizeX = 1, ThreadCountX = 1 }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + + var description = ImageDescription.Create(); + description.Data = new GuestSpan(ArrayBackedSpace.Base, 2 * 2 * texelBytes * 2); + description.PixelFormat = format; + description.GuestFormat = pixelFormat; + description.Extent = new Extent3D(2, 2, 1); + description.Resources = new SubresourceCount(1, 1); + description.Pitch = 2; + description.BytesPerBlock = texelBytes; + var image = harness.CreateImage(description); + var copies = ImageTestHarness.WholeImageCopies(description, 0); + var size = ImageTestHarness.WholeImageBytes(description); + harness.UploadImage(image, Enumerable.Repeat((byte)0xA5, (int)size).ToArray(), copies); + using var runner = new LayoutComputeRunner(harness, request, shader.Spirv); + var view = new DescriptorImageInfo + { + ImageView = image.GetOrCreateView(ImageViewDescription.Default with { Format = format, Usage = ImageUsageFlags.StorageBit }), + ImageLayout = ImageLayout.General, + }; + var images = layout.Descriptors + .Where(binding => ImageDescriptorBinding.ResourceClass(binding.Kind) == ImageResourceClass.Storage) + .ToDictionary(binding => binding.Kind, binding => binding.Resources.Select(_ => view).ToArray()); + harness.Run(() => + { + image.Transition(AccessFlags.ShaderWriteBit, null, new CommandBuffer(harness.Scheduler.Current.Handle)); + runner.Dispatch(userData, new Dictionary(), 1, boundImages: images, + imageDescriptors: snapshot.Images); + }); + var texel = harness.ReadImage(image, copies, size)[..(int)texelBytes]; + return (texel, shader.Spirv); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/SharedDeviceLoadDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/SharedDeviceLoadDeviceTests.cs new file mode 100644 index 000000000..76443e78c --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/SharedDeviceLoadDeviceTests.cs @@ -0,0 +1,230 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using Xunit.Abstractions; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.Libs.Tests.Gpu.Vulkan; + +[CollectionDefinition(Name, DisableParallelization = true)] +public sealed class SharedDeviceLoadState +{ + // Tests that set Gen5SpirvTranslator.SharedDeviceLoads run alone: no other test translates while it differs. + public const string Name = "SharedDeviceLoads"; +} + +// A linked program's device dword loads compiled with the shared load function off and on +// (SharedDeviceLoads), run on the same pages and lanes; every result and fault word must match. The loads: +// S_LOAD_DWORDX4/X2/X8 through run-time addresses (one at the top of the 48-bit space, which wraps to page 0), +// S_BUFFER_LOAD_DWORDX8, BUFFER_LOAD_DWORDX4 and BUFFER_LOAD_FORMAT_XYZW through a run-time V#. Cases: all 128 unified +// formats; data inside one page, 20 bytes before a mapped and an unmapped second page, num_records inside the lanes, a base +// above the page table; 32 lanes at 7-byte steps. +[Collection(SharedDeviceLoadState.Name)] +public sealed class SharedDeviceLoadDeviceTests(HeadlessVulkanFixture fixture, ITestOutputHelper output) : IClassFixture +{ + private const ulong PageSize = Gen5SpirvTranslator.DeviceAddressPageSize; + private const ulong GuestBase = 64 * PageSize; + private const ulong TableEntries = 4096; + private const uint ResultRegister = 4; + private const uint Lanes = 32; + private const uint ResultBytes = Lanes * 128; + + [Fact] + public void DeviceLoadsMatchWithAndWithoutTheSharedFunction() + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan, shaderInt64: true)) return; + var program = LinkedProgram(); + var (previous, previousRanges) = (Gen5SpirvTranslator.SharedDeviceLoads, Gen5SpirvTranslator.SharedDeviceRanges); + Compiled before, after; + try + { + // One call per dword (the range functions off, whatever SHARPEMU_SHARED_DEVICE_RANGES says). + Gen5SpirvTranslator.SharedDeviceRanges = false; + Gen5SpirvTranslator.SharedDeviceLoads = false; + before = Compile(program); + Gen5SpirvTranslator.SharedDeviceLoads = true; + after = Compile(program); + } + finally + { + (Gen5SpirvTranslator.SharedDeviceLoads, Gen5SpirvTranslator.SharedDeviceRanges) = (previous, previousRanges); + } + + output.WriteLine($"module: {before.Spirv.Length} B -> {after.Spirv.Length} B"); + Assert.True(after.Spirv.Length < before.Spirv.Length, "the loads go through the shared function"); + Compare(vulkan!, before, after); + } + + // The same program with the shared function, its dword ranges one call per dword and one call per range. + [Fact] + public void DeviceRangesMatchWithAndWithoutTheRangeFunctions() + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan, shaderInt64: true)) return; + var program = LinkedProgram(); + var (previousLoads, previousRanges) = (Gen5SpirvTranslator.SharedDeviceLoads, Gen5SpirvTranslator.SharedDeviceRanges); + Compiled before, after; + try + { + Gen5SpirvTranslator.SharedDeviceLoads = true; + Gen5SpirvTranslator.SharedDeviceRanges = false; + before = Compile(program); + Gen5SpirvTranslator.SharedDeviceRanges = true; + after = Compile(program); + } + finally + { + (Gen5SpirvTranslator.SharedDeviceLoads, Gen5SpirvTranslator.SharedDeviceRanges) = (previousLoads, previousRanges); + } + + output.WriteLine($"module: {before.Spirv.Length} B -> {after.Spirv.Length} B"); + Assert.Contains("loadDeviceDwords8", System.Text.Encoding.ASCII.GetString(after.Spirv)); + Compare(vulkan!, before, after); + } + + private void Compare(HeadlessVulkan vulkan, Compiled before, Compiled after) + { + (ulong Base, uint Records, bool SecondPage)[] cases = + [ + (GuestBase + 512, 0x10000, true), + (GuestBase + PageSize - 20, 0x10000, true), + (GuestBase + PageSize - 20, 0x10000, false), + (GuestBase + 512, 150, true), + (0x0000_1000_0000_0000, 0x10000, true), + (0x0000_FFFF_FFFF_FFF0, 0x10000, true), + ]; + long dispatches = 0, words = 0, mismatches = 0, live = 0, faulted = 0; + using var harness = new ImageTestHarness(vulkan); + var first = ImageTestHarness.Pattern((int)PageSize, 31); + var second = ImageTestHarness.Pattern((int)PageSize, 32); + for (uint format = 0; format < 128; format++) + { + using var beforeRunner = new LayoutComputeRunner(harness, before.Request, before.Spirv); + using var afterRunner = new LayoutComputeRunner(harness, after.Request, after.Spirv); + foreach (var (dataBase, records, secondPage) in cases) + { + var page = (byte[])first.Clone(); + BinaryPrimitives.WriteUInt32LittleEndian(page.AsSpan(0), (uint)dataBase); + BinaryPrimitives.WriteUInt32LittleEndian(page.AsSpan(4), (uint)(dataBase >> 32) & 0xFFFF); + BinaryPrimitives.WriteUInt32LittleEndian(page.AsSpan(8), records); + BinaryPrimitives.WriteUInt32LittleEndian(page.AsSpan(12), 4 | (5 << 3) | (6 << 6) | (7 << 9) | (format << 12)); + BinaryPrimitives.WriteUInt64LittleEndian(page.AsSpan(16), dataBase); + var a = Run(harness, beforeRunner, before, page, secondPage ? second : null); + var b = Run(harness, afterRunner, after, page, secondPage ? second : null); + dispatches++; + for (var index = 0; index < a.Result.Length; index++) + { + words++; + if (a.Result[index] != b.Result[index]) mismatches++; + if (a.Result[index] != 0) live++; + } + + for (var index = 0; index < a.Faults.Length; index++) + { + if (a.Faults[index] != b.Faults[index]) mismatches++; + if (a.Faults[index] != 0) faulted++; + } + + if (mismatches != 0) + { + var at = Enumerable.Range(0, a.Result.Length).FirstOrDefault(index => a.Result[index] != b.Result[index]); + Assert.Fail($"format {format} base 0x{dataBase:X} records {records} second page {secondPage}: {mismatches} differences, " + + $"first result word {at}: {a.Result[at]:X8} vs {b.Result[at]:X8}"); + } + } + } + + harness.AssertNoValidationMessages(); + output.WriteLine($"{dispatches} dispatch pairs, {words} result words compared ({live} nonzero), {faulted} nonzero fault words, " + + $"{mismatches} mismatches on {vulkan!.DeviceName}"); + Assert.Equal(0, mismatches); + Assert.True(live > 0 && faulted > 0, "the cases read data and record faults"); + } + + private sealed record Compiled(ShaderResourcePlan Plan, ShaderCompileRequest Request, byte[] Spirv, ulong[] CallArguments, ulong[] CallTargets); + + private static Compiled Compile(Gen5ShaderProgram program) + { + var (plan, resources, layout) = Prepare(program); + var request = new ShaderCompileRequest(plan, resources, layout) { LocalSizeX = Lanes, ThreadCountX = Lanes, ScratchDwords = 32 }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + return new Compiled(plan, request, shader.Spirv, Gen5ShaderCallLinker.CallEntryArguments(program), Gen5ShaderCallLinker.CallTargets(program)); + } + + private static Gen5ShaderProgram LinkedProgram() + { + var instructions = new List + { + MoveScalar(0, 14, 0x2000), MoveScalar(4, 15, 0), MoveScalar(8, 24, 1), + Sop1(12, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + Vop2(16, "VAddU32", 2, Operand((uint)GuestBase), Gen5Operand.Vector(0)), + ReadFirstLane(20, 12, 2), + MoveScalar(24, 13, (uint)(GuestBase >> 32)), + ScalarLoad(28, 12, 20, count: 4), + ScalarLoad(36, 12, 26, count: 2, immediateOffset: 16), + ScalarLoad(44, 26, 32, count: 8), + ScalarBufferLoad(52, 20, 40, count: 8), + Vop2(60, "VMulU32U24", 5, Operand(7), Gen5Operand.Vector(0)), + BufferAccess(64, "BufferLoadDwordx4", 20, dwords: 4, vectorData: 8, offsetEnabled: true, vectorAddress: 5), + BufferAccess(72, "BufferLoadFormatXyzw", 20, dwords: 4, vectorData: 12, offsetEnabled: true, vectorAddress: 5), + }; + uint pc = 80; + for (uint register = 0; register < 16; register++, pc += 4) + { + instructions.Add(MoveVectorFromScalar(pc, 16 + register, 32 + register)); + } + + instructions.Add(Vop2(pc, "VLshlrevB32", 6, Operand(7), Gen5Operand.Vector(0))); + pc += 4; + for (uint part = 0; part < 6; part++, pc += 8) + { + instructions.Add(BufferAccess(pc, "BufferStoreDwordx4", ResultRegister, offset: (int)(part * 16), dwords: 4, + vectorData: 8 + part * 4, offsetEnabled: true, vectorAddress: 6)); + } + + instructions.Add(EndProgram(pc)); + var caller = Program(instructions.ToArray()); + var function = Program(Sop1(0, "SSetpcB64", 0, Gen5Operand.Scalar(14))); + var linked = Gen5ShaderCallLinker.Link(caller, [new(12, 14, 24, 14, 16, [new ShaderCallTarget(0x2000, 1, function)])]); + Assert.True(Gen5ShaderCallLinker.IsLinked(linked)); + return linked; + } + + private static (uint[] Result, uint[] Faults) Run(ImageTestHarness harness, LayoutComputeRunner runner, Compiled compiled, + byte[] firstPage, byte[]? secondPage) + { + var result = runner.CreateBuffer(ResultBytes); + var fault = runner.CreateBuffer(TableEntries / 8 + 64); + var pages = new List<(ulong, GpuBuffer, ulong)> { (GuestBase, runner.CreateBuffer(firstPage, PageSize), 0) }; + if (secondPage is not null) pages.Add((GuestBase + PageSize, runner.CreateBuffer(secondPage, PageSize), 0)); + var table = runner.CreatePageTable(TableEntries, pages); + var registers = new uint[256]; + registers[0] = (uint)GuestBase; + registers[1] = (uint)(GuestBase >> 32); + registers[ResultRegister + 2] = ResultBytes; + var bound = new Dictionary + { + [DescriptorBindingKind.Buffers] = [result], + [DescriptorBindingKind.DeviceAddressPageTable] = [table], + [DescriptorBindingKind.FaultBuffer] = [fault], + }; + harness.Run(() => runner.Dispatch(registers, bound, 1, flattenedTable: new uint[Math.Max(compiled.Plan.FlattenedTableReservedCount, 1)], + callArguments: compiled.CallArguments, callTargets: compiled.CallTargets)); + return (Words(runner.ReadBack(result, 0, ResultBytes)), Words(runner.ReadBack(fault, 0, fault.Size))); + } + + private static uint[] Words(byte[] bytes) + { + var words = new uint[bytes.Length / 4]; + for (var index = 0; index < words.Length; index++) words[index] = BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(index * 4)); + return words; + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/TessellationWaveDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/TessellationWaveDeviceTests.cs index 87306c0ec..e987888ad 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/TessellationWaveDeviceTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/TessellationWaveDeviceTests.cs @@ -165,7 +165,6 @@ public void MergedHullInputs_SplitPatchesNumberedAcrossInstances() data[Gen5TessellationData.FirstPatch] = 7; data[Gen5TessellationData.PatchCount] = 63; data[Gen5TessellationData.VertexOffset] = 11; - data[Gen5TessellationData.InstanceId] = 100; data[Gen5TessellationData.PatchesPerInstance] = 10; harness.Run(() => runner.Dispatch(scalar, new Dictionary { [DescriptorBindingKind.Buffers] = [buffer] }, 1, @@ -178,7 +177,7 @@ public void MergedHullInputs_SplitPatchesNumberedAcrossInstances() Assert.Equal((lane / 4) | ((lane % 4) << 8), Read(0)); Assert.Equal(patch % 10, Read(1)); Assert.Equal(patch % 10 * 4 + lane % 4 + 11, Read(2)); - Assert.Equal(100 + patch / 10, Read(3)); + Assert.Equal(patch / 10, Read(3)); } harness.AssertNoValidationMessages(); } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/Wave64HalfMaskDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/Wave64HalfMaskDeviceTests.cs index 2008680a5..04ef2d2eb 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/Wave64HalfMaskDeviceTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/Wave64HalfMaskDeviceTests.cs @@ -74,7 +74,7 @@ protected uint[] Run(uint localDataShareDwords = 0, uint sizeX = 8, uint sizeY = Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); if (HostSubgroup32 && laneLocal is { } oneLanePerInvocation) { - var halfWavesEnabled = Environment.GetEnvironmentVariable("SHARPEMU_WAVE64_LANE_LOCAL") == "1"; + var halfWavesEnabled = Environment.GetEnvironmentVariable("SHARPEMU_WAVE64_LANE_LOCAL") != "0"; Assert.Equal(oneLanePerInvocation && halfWavesEnabled ? sizeX : (threads + 63) / 64 * 32, LocalSizeX(shader.Spirv)); } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/WaveReductionDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/WaveReductionDeviceTests.cs new file mode 100644 index 000000000..dfc99f90b --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/WaveReductionDeviceTests.cs @@ -0,0 +1,316 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.Libs.Tests.Gpu.Vulkan; + +// DPP16 write rules and the wave32 row reductions of Gen5SpirvTranslator.WaveReductions, run on the device. +public sealed class WaveReductionDeviceTests(HeadlessVulkanFixture fixture) : IClassFixture +{ + private const uint EvenLanes = 0x5555_5555; + + // v4 starts at 1000 + lane, then V_MOV_B32 v4, v3 (v3 = lane + 1) runs with the DPP control under the EXEC mask. + [Theory] + [InlineData("InactiveSource", 0x111u, false, false, 15u, EvenLanes)] + [InlineData("InactiveSourceBoundControl", 0x111u, false, true, 15u, EvenLanes)] + [InlineData("InactiveSourceFetchInactive", 0x111u, true, false, 15u, EvenLanes)] + [InlineData("BankMask", 0xE4u, true, false, 0b0010u, uint.MaxValue)] + public void Dpp16_WritesFollowSourceValidityAndBanks(string name, uint control, bool fetchInactive, bool boundControl, uint bankMask, uint exec) + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan)) return; + var program = Build( + Vop2(0, "VAddI32", 3, Operand(1), Gen5Operand.Vector(0)), + Vop2(0, "VAddI32", 4, Operand(1000), Gen5Operand.Vector(0)), + MoveScalar(0, 126, exec), + Vop1(0, "VMovB32", 4, Gen5Operand.Vector(3)) with + { + Control = new Gen5DppControl(control, fetchInactive, boundControl, 0, 0, bankMask, 15), + }, + MoveScalar(0, 126, uint.MaxValue), + Vop2(0, "VLshlrevB32", 5, Operand(2), Gen5Operand.Vector(0)), + BufferAccess(0, "BufferStoreDword", 4, vectorData: 4, offsetEnabled: true, vectorAddress: 5)); + var actual = Run(vulkan, program, threads: 32, subgroupArithmetic: false, bytes: 128); + for (uint lane = 0; lane < 32; lane++) + { + var active = (exec >> (int)lane & 1) != 0; + var rowLane = lane & 15; + var source = name == "BankMask" ? lane : lane - 1; + var sourceValid = name == "BankMask" || rowLane != 0 && (fetchInactive || (exec >> (int)source & 1) != 0); + var bankEnabled = (bankMask >> (int)(lane >> 2 & 3) & 1) != 0; + var expected = !active || !bankEnabled ? 1000 + lane + : sourceValid ? source + 1 + : boundControl ? 0u + : 1000 + lane; + Assert.True(expected == Read(actual, lane), $"{name}: lane {lane} expected {expected}, got {Read(actual, lane)}"); + } + } + + // A guest scan: s80 copies the entry EXEC and drops lanes 19 and up, lanes outside s0 = EXEC & s80 take the + // identity, a DPP row_shr 1/2/4/8 scan runs, then lanes 15 and 31 are read and combined. A workgroup of fewer than 32 + // threads leaves host invocations missing from the subgroup. Each lane stores the two reads and the combined value. + [Theory] + [InlineData("VMaxU32", 32u)] + [InlineData("VMinU32", 32u)] + [InlineData("VOrB32", 32u)] + [InlineData("VAddU32", 32u)] + [InlineData("VMaxU32", 20u)] + [InlineData("VMinU32", 20u)] + [InlineData("VOrB32", 20u)] + [InlineData("VAddU32", 20u)] + [InlineData("VMaxU32", 12u)] + [InlineData("VMinU32", 12u)] + [InlineData("VOrB32", 12u)] + [InlineData("VAddU32", 12u)] + public void Wave32RowScan_ReadsEachRowOverTheLanesThatExist(string operation, uint threads) + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan)) return; + var actual = Run(vulkan, Build(ScanProgram(operation)), threads, subgroupArithmetic: true, bytes: 512); + var rowZero = Fold(operation, 0, threads); + var rowOne = Fold(operation, 1, threads); + var combined = Combine(operation, rowZero, rowOne); + for (uint lane = 0; lane < threads; lane++) + { + Assert.Equal(rowZero, Read(actual, lane * 4)); + Assert.Equal(rowOne, Read(actual, lane * 4 + 1)); + Assert.Equal(combined, Read(actual, lane * 4 + 2)); + } + + // A full subgroup gives the same values without the reduction. + if (threads == 32) + { + var scanned = Run(vulkan, Build(ScanProgram(operation)), threads, subgroupArithmetic: false, bytes: 512); + Assert.Equal(actual[..(32 * 16)], scanned[..(32 * 16)]); + } + } + + // Only the exact scan becomes a reduction. + [Theory] + [InlineData("Exact", 2)] + [InlineData("NoSubgroupArithmetic", 0)] + [InlineData("IdentityChanged", 0)] + [InlineData("ShiftOrder", 0)] + [InlineData("BoundControl", 0)] + [InlineData("OtherLane", 0)] + [InlineData("ExecNotSaved", 0)] + [InlineData("ScanSourceChanged", 0)] + [InlineData("MaskAllLanes", 0)] + [InlineData("MaskNotFromEntryCopy", 0)] + [InlineData("MaskInVcc", 0)] + [InlineData("EntryCopyOverwritten", 0)] + [InlineData("EntryCopyAfterExecWrite", 0)] + [InlineData("EntryCopyInOddRegister", 2)] + [InlineData("EntryCopyPairWrite", 0)] + [InlineData("MaskInOddRegister", 2)] + [InlineData("MaskPairWrite", 0)] + [InlineData("SavedSourceKept", 2)] + [InlineData("SavedSourcePairWrite", 0)] + public void Wave32RowScan_OnlyTheExactScanIsReduced(string variant, int reductions) + { + var instructions = ScanProgram( + "VMaxU32", + entry: variant is "EntryCopyInOddRegister" or "EntryCopyPairWrite" ? 81u : 80u, + mask: variant is "MaskInOddRegister" or "MaskPairWrite" ? 1u : 0u).ToList(); + int Find(string opcode, int skip = 0) => instructions.FindIndex(skip, instruction => instruction.Opcode == opcode); + var cndmask = Find("VCndmaskB32"); + var maskWrite = Find("SAndB32"); + switch (variant) + { + case "IdentityChanged": + instructions[cndmask] = instructions[cndmask] with { Sources = [Operand(5), .. instructions[cndmask].Sources.Skip(1)] }; + break; + case "ShiftOrder": + (instructions[cndmask + 1], instructions[cndmask + 2]) = (instructions[cndmask + 2], instructions[cndmask + 1]); + break; + case "BoundControl": + instructions[cndmask + 3] = instructions[cndmask + 3] with { Control = new Gen5DppControl(0x114, false, true, 0, 0, 15, 15) }; + break; + case "OtherLane": + var read = Find("VReadlaneB32"); + instructions[read] = ReadLane(0, 1, 2, 14); + break; + case "ExecNotSaved": + var saveexec = Find("SOrn2SaveexecB32"); + instructions[saveexec] = Sop1(0, "SOrn2SaveexecB32", 106, Gen5Operand.Scalar(80)); + break; + case "ScanSourceChanged": + instructions[cndmask + 2] = instructions[cndmask + 2] with { Sources = [Gen5Operand.Vector(1), Gen5Operand.Vector(2)] }; + break; + case "MaskAllLanes": + // A lane missing from the host subgroup would take value, not the identity, on the PS5. + instructions[maskWrite] = MoveScalar(0, 0, uint.MaxValue); + break; + case "MaskNotFromEntryCopy": + instructions[maskWrite] = Sop2(0, "SAndB32", 0, Gen5Operand.Scalar(126), Gen5Operand.Scalar(81)); + instructions.Insert(0, MoveScalar(0, 81, 0x7FFFF)); + break; + case "MaskInVcc": + instructions[cndmask] = Vop2(0, "VCndmaskB32", 2, Operand(0), Gen5Operand.Vector(1)); + break; + case "EntryCopyOverwritten": + instructions.Insert(maskWrite, Sop2(0, "SOrB32", 80, Gen5Operand.Scalar(80), Operand(1u << 25))); + break; + case "EntryCopyAfterExecWrite": + instructions.Insert(0, Sop2(0, "SAndB32", 126, Gen5Operand.Scalar(126), Operand(uint.MaxValue))); + break; + case "EntryCopyPairWrite": + // S_MOV_B64 s[80:81] names s80 only. + instructions.Insert(maskWrite, Sop1(0, "SMovB64", 80, Gen5Operand.Scalar(8))); + break; + case "MaskPairWrite": + // S_MOV_B64 s[0:1] names s0 only. + instructions.Insert(maskWrite + 1, Sop1(0, "SMovB64", 0, Gen5Operand.Scalar(8))); + break; + case "SavedSourceKept": + case "SavedSourcePairWrite": + // S_MOV_B32 exec_lo, s3 makes s3 hold EXEC; S_MOV_B64 s[2:3] names s2 only. + var savedAt = Find("SOrn2SaveexecB32"); + instructions[savedAt] = Sop1(0, "SOrn2SaveexecB32", 106, Gen5Operand.Scalar(3)); + instructions.InsertRange(savedAt, variant == "SavedSourceKept" + ? [MoveScalarRegister(0, 3, 126), MoveScalarRegister(0, 126, 3)] + : [MoveScalarRegister(0, 3, 126), MoveScalarRegister(0, 126, 3), Sop1(0, "SMovB64", 2, Gen5Operand.Scalar(8))]); + break; + } + + var (plan, resources, layout) = Prepare(Build([.. instructions])); + var request = new ShaderCompileRequest(plan, resources, layout) + { + LocalSizeX = 32, ThreadCountX = 32, WaveSize = 32, + SubgroupArithmetic = variant != "NoSubgroupArithmetic", + }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + Assert.Equal(reductions, CountOpcode(shader.Spirv, (ushort)SpirvOp.GroupNonUniformUMax)); + } + + // Each lane's value: 8 * lane + 100 (MAX, ADD), 1023 - 8 * lane (MIN), 1 << lane (OR). + private static uint Value(string operation, uint lane) => operation switch + { + "VMinU32" => 1023 - 8 * lane, + "VOrB32" => 1u << (int)lane, + _ => 8 * lane + 100, + }; + + private static uint Identity(string operation) => operation == "VMinU32" ? uint.MaxValue : 0u; + + private static uint Combine(string operation, uint left, uint right) => operation switch + { + "VMaxU32" => Math.Max(left, right), + "VMinU32" => Math.Min(left, right), + "VOrB32" => left | right, + _ => left + right, + }; + + // The operation over the lanes of a row that exist (below threads) and are in the scan mask (lanes 0 to 18). + private static uint Fold(string operation, uint row, uint threads) + { + var result = Identity(operation); + for (var lane = row * 16; lane < row * 16 + 16; lane++) + { + if (lane < threads && lane <= 18) result = Combine(operation, result, Value(operation, lane)); + } + + return result; + } + + private static Gen5ShaderInstruction[] ScanProgram(string operation, uint entry = 80, uint mask = 0) + { + var list = new List + { + MoveScalarRegister(0, entry, 126), + Sop2(0, "SAndn2B32", entry, Gen5Operand.Scalar(entry), Operand(0xFFF8_0000)), + operation switch + { + "VMinU32" => Vop2(0, "VLshlrevB32", 1, Operand(3), Gen5Operand.Vector(0)), + "VOrB32" => Vop2(0, "VLshlrevB32", 1, Gen5Operand.Vector(0), Operand(1)), + _ => Vop2(0, "VLshlrevB32", 1, Operand(3), Gen5Operand.Vector(0)), + }, + operation switch + { + "VMinU32" => Vop2(0, "VXorB32", 1, Operand(0x3FF), Gen5Operand.Vector(1)), + "VOrB32" => Nop(0), + _ => Vop2(0, "VAddI32", 1, Operand(100), Gen5Operand.Vector(1)), + }, + Sop2(0, "SAndB32", mask, Gen5Operand.Scalar(126), Gen5Operand.Scalar(entry)), + Sop1(0, "SOrn2SaveexecB32", 106, Gen5Operand.Scalar(126)), + Vop3(0, "VCndmaskB32", 2, Operand(Identity(operation)), Gen5Operand.Vector(1), Gen5Operand.Scalar(mask)), + }; + foreach (var shift in new uint[] { 1, 2, 4, 8 }) + list.Add(Vop2(0, operation, 2, Gen5Operand.Vector(2), Gen5Operand.Vector(2)) with + { + Control = new Gen5DppControl(0x110 + shift, false, false, 0, 0, 15, 15), + }); + list.Add(MoveScalarRegister(0, 126, 106)); + list.Add(ReadLane(0, 1, 2, 15)); + list.Add(ReadLane(0, 2, 2, 31)); + list.Add(Sop2(0, operation switch { "VMaxU32" => "SMaxU32", "VMinU32" => "SMinU32", "VOrB32" => "SOrB32", _ => "SAddU32" }, + 3, Gen5Operand.Scalar(1), Gen5Operand.Scalar(2))); + list.Add(Sopc(0, "SCmpGtU32", Gen5Operand.Scalar(3), Operand(0))); + list.Add(MoveVectorFromScalar(0, 4, 1)); + list.Add(MoveVectorFromScalar(0, 5, 2)); + list.Add(MoveVectorFromScalar(0, 6, 3)); + list.Add(Vop2(0, "VLshlrevB32", 7, Operand(4), Gen5Operand.Vector(0))); + list.Add(BufferAccess(0, "BufferStoreDword", 4, offset: 0, vectorData: 4, offsetEnabled: true, vectorAddress: 7)); + list.Add(BufferAccess(0, "BufferStoreDword", 4, offset: 4, vectorData: 5, offsetEnabled: true, vectorAddress: 7)); + list.Add(BufferAccess(0, "BufferStoreDword", 4, offset: 8, vectorData: 6, offsetEnabled: true, vectorAddress: 7)); + return [.. list]; + } + + private static Gen5ShaderProgram Build(params Gen5ShaderInstruction[] instructions) + { + var placed = new List(); + uint pc = 0; + foreach (var instruction in instructions.Append(EndProgram(0))) + { + placed.Add(instruction with { Pc = pc }); + pc += 8; + } + + return new Gen5ShaderProgram(0, [.. placed]); + } + + private static byte[] Run(HeadlessVulkan vulkan, Gen5ShaderProgram program, uint threads, bool subgroupArithmetic, int bytes) + { + var (plan, resources, layout) = Prepare(program); + var request = new ShaderCompileRequest(plan, resources, layout) + { + LocalSizeX = threads, LocalSizeY = 1, ThreadCountX = threads, ThreadCountY = 1, WaveSize = 32, + SubgroupArithmetic = subgroupArithmetic, + }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + using var harness = new ImageTestHarness(vulkan); + using var runner = new LayoutComputeRunner(harness, request, shader.Spirv); + var result = runner.CreateBuffer((ulong)bytes); + var registers = new uint[256]; + registers[6] = (uint)bytes; + harness.Run(() => runner.Dispatch(registers, + new Dictionary { [DescriptorBindingKind.Buffers] = [result] }, 1)); + var actual = runner.ReadBack(result, 0, (ulong)bytes); + harness.AssertNoValidationMessages(); + return actual; + } + + private static uint Read(byte[] data, uint word) => BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan((int)word * 4)); + + private static int CountOpcode(byte[] spirv, ushort opcode) + { + var count = 0; + for (var offset = 20; offset + 4 <= spirv.Length;) + { + var word = BinaryPrimitives.ReadUInt32LittleEndian(spirv.AsSpan(offset)); + if ((word & 0xFFFF) == opcode) count++; + offset += (int)(word >> 16) * 4; + if (word >> 16 == 0) break; + } + + return count; + } +} diff --git a/tests/SharpEmu.Libs.Tests/Kernel/KernelBackedMemoryTests.cs b/tests/SharpEmu.Libs.Tests/Kernel/KernelBackedMemoryTests.cs index 5771857d5..c903cf3cc 100644 --- a/tests/SharpEmu.Libs.Tests/Kernel/KernelBackedMemoryTests.cs +++ b/tests/SharpEmu.Libs.Tests/Kernel/KernelBackedMemoryTests.cs @@ -243,6 +243,29 @@ public void SparseImageReadZeroesUnresidentApertureRangesAndRejectsOutsideIt() } } + [Fact] + public void PrtWriteLandsOnlyInMappedSlices() + { + using var test = new BackedKernelMemory(); + var address = SharpEmu.Libs.Tests.Memory.HostViews.HostViewTestSupport.ProbeGuestAddress(test.Host, 0x10000); + test.Reserve(0x10000, address); + SetPrtAperture(test, address, 0x10000); + try + { + test.Allocate(0, 0x8000); + test.Map(0, 0x4000, address); + test.Map(0x4000, 0x4000, address + 0xC000); + var payload = Enumerable.Repeat((byte)0x66, 0x10000).ToArray(); + Assert.True(KernelMemoryCompatExports.TryWritePrtBacking(test.Memory, address, payload)); + var actual = new byte[0x10000]; + Assert.True(KernelMemoryCompatExports.TryReadPrtBacking(test.Memory, address, actual)); + Assert.All(actual.Take(0x4000), value => Assert.Equal((byte)0x66, value)); + Assert.All(actual.Skip(0x4000).Take(0x8000), value => Assert.Equal((byte)0, value)); + Assert.All(actual.Skip(0xC000), value => Assert.Equal((byte)0x66, value)); + } + finally { SetPrtAperture(test, address, 0); } + } + private static void SetPrtAperture(BackedKernelMemory test, ulong address, ulong size) { test.Context[CpuRegister.Rdi] = 0; diff --git a/tests/SharpEmu.Libs.Tests/Kernel/KernelRuntimeCompatExportsTests.cs b/tests/SharpEmu.Libs.Tests/Kernel/KernelRuntimeCompatExportsTests.cs index a3814eac8..029b550b8 100644 --- a/tests/SharpEmu.Libs.Tests/Kernel/KernelRuntimeCompatExportsTests.cs +++ b/tests/SharpEmu.Libs.Tests/Kernel/KernelRuntimeCompatExportsTests.cs @@ -562,6 +562,47 @@ public void ModuleRegistry_ExactPathDoesNotFallBackToMatchingFileName() } } + // The loader maps a module's own segments; the protection query reports them, so a title that adds flags to the + // current protection of its data starts from the real value. + [Fact] + public void QueryMemoryProtection_ReportsALoadedModuleSegment() + { + const ulong ModuleBase = 0x7F12_3400_0000; + var context = new CpuContext(new FakeCpuMemory(MemoryBase, 0x100), Generation.Gen5); + KernelModuleRegistry.Reset(); + try + { + var handle = KernelModuleRegistry.RegisterModule( + "/app0/main.elf", ModuleBase, 0x10_0000, ModuleBase, 0, 0, 0, 0, isMain: true); + KernelModuleRegistry.RegisterModuleSegments(handle, + [ + new(ModuleBase, ModuleBase + 0x8_0000, 0x4), + new(ModuleBase + 0x8_0000, ModuleBase + 0x10_0000, 0x3), + ]); + context[CpuRegister.Rdi] = ModuleBase + 0x9_2345; + context[CpuRegister.Rsi] = MemoryBase; + context[CpuRegister.Rdx] = MemoryBase + 0x8; + context[CpuRegister.Rcx] = MemoryBase + 0x10; + + Assert.Equal(0, KernelMemoryCompatExports.KernelQueryMemoryProtection(context)); + Assert.True(context.TryReadUInt64(MemoryBase, out var start)); + Assert.True(context.TryReadUInt64(MemoryBase + 0x8, out var end)); + Assert.True(context.TryReadUInt32(MemoryBase + 0x10, out var protection)); + Assert.Equal(ModuleBase + 0x8_0000, start); + Assert.Equal(ModuleBase + 0x10_0000 - 1, end); + Assert.Equal(3u, protection); + + context[CpuRegister.Rdi] = ModuleBase + 0x10_0000; + Assert.Equal( + (int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND, + KernelMemoryCompatExports.KernelQueryMemoryProtection(context)); + } + finally + { + KernelModuleRegistry.Reset(); + } + } + private static int GetMinutesWest() => unchecked((int)-TimeZoneInfo.Local.BaseUtcOffset.TotalMinutes); diff --git a/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/AvlSpanSetTests.cs b/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/AvlSpanSetTests.cs index 8b9931cf4..1e3ad7fd6 100644 --- a/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/AvlSpanSetTests.cs +++ b/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/AvlSpanSetTests.cs @@ -8,6 +8,49 @@ namespace SharpEmu.Libs.Tests.Memory.GpuMemory; public sealed class AvlSpanSetTests { + // A snapshot built from the last one's spans outside the changed extent holds exactly the set's spans, after single and + // batched changes, merges, splits and clears. + [Theory] + [InlineData(7, 4096)] + [InlineData(19, 1 << 20)] + public void SnapshotsAfterBatchedChangesHoldExactlyTheSpans(int seed, int space) + { + var expected = new SpanSet(); + var actual = new AvlSpanSet(); + var random = new System.Random(seed); + for (var round = 0; round < 4000; round++) + { + if (random.Next(400) == 0) + { + expected.Clear(); + actual.Clear(); + } + + for (var change = random.Next(1, 6); change > 0; change--) + { + var address = (ulong)random.Next(space); + var size = (ulong)random.Next(1, space / (random.Next(2) == 0 ? 512 : 16)); + if (random.Next(3) != 0) + { + expected.Add(address, size); + actual.Add(address, size); + } + else + { + expected.Remove(address, size); + actual.Remove(address, size); + } + } + + var want = expected.Snapshot(); + var got = actual.Snapshot(); + Assert.Equal(want.Starts.ToArray(), got.Starts.ToArray()); + Assert.Equal(want.Ends.ToArray(), got.Ends.ToArray()); + } + + Assert.True(actual.SplicedSnapshots > 3000, $"spliced {actual.SplicedSnapshots} of 4000 snapshots"); + } + [Theory] [InlineData(101, 4096)] [InlineData(202, 1048576)] diff --git a/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/GuestGpuManagedWriteLeaseTests.cs b/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/GuestGpuManagedWriteLeaseTests.cs new file mode 100644 index 000000000..9828d8e08 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/GuestGpuManagedWriteLeaseTests.cs @@ -0,0 +1,235 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using SharpEmu.HLE.GpuMemory; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using Xunit; + +namespace SharpEmu.Libs.Tests.Memory.GpuMemory; + +[Collection(GpuMemoryStateCollection.Name)] +public sealed class GuestGpuManagedWriteLeaseTests +{ + private sealed class Store : IGuestBufferStore + { + internal readonly List<(bool Landed, ulong Address, ulong Size)> Calls = []; + internal bool ThrowOnLanded; + internal bool GpuData = true; + internal readonly List<(ulong Address, ulong Size)> EmulatorWrites = []; + public bool MayHoldGpuData(ulong address, ulong size) => GpuData; + public bool NoteEmulatorWrite(ulong address, ulong size) + { + EmulatorWrites.Add((address, size)); + MarkCpuWriteLanded(address, size); + return true; + } + public bool MarkCpuWrite(ulong address, ulong size) + { + Calls.Add((false, address, size)); + return true; + } + public void MarkCpuWriteLanded(ulong address, ulong size) + { + Calls.Add((true, address, size)); + if (ThrowOnLanded) throw new InvalidOperationException("Synthetic landed notification failure."); + } + public bool DownloadToCpu(ulong address, ulong size) => true; + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void WriteAcrossUnregisteredGapNotifiesEveryMappedIntersection(bool closureFree) + { + var savedOverride = HostCallTrims.MarkClosureFreeOverrideForTests; + HostCallTrims.MarkClosureFreeOverrideForTests = closureFree; + try + { + using var memory = new GuestGpuMemory(new RecordingAddressSpace()); + var store = new Store(); + memory.AttachStores(store, null); + const GuestPageProtection access = GuestPageProtection.Read | GuestPageProtection.Write; + memory.Register(0x10000, 0x4000, access); + memory.Register(0x18000, 0x4000, access); + // Registration reports each span to the store; only the managed write's notifications are under test. + store.Calls.Clear(); + Assert.False(memory.Covers(0x12000, 0x8000)); + using (memory.BeginManagedWrite(0x12000, 0x8000)) { } + Assert.Equal(new (bool, ulong, ulong)[] + { + (false, 0x12000, 0x2000), (false, 0x18000, 0x2000), + (true, 0x12000, 0x2000), (true, 0x18000, 0x2000) + }, store.Calls); + } + finally + { + HostCallTrims.MarkClosureFreeOverrideForTests = savedOverride; + } + } + + // A write that overlaps no GPU span notifies no store, with the closure or without it. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void WriteOutsideEverySpanNotifiesNothing(bool closureFree) + { + var savedOverride = HostCallTrims.MarkClosureFreeOverrideForTests; + HostCallTrims.MarkClosureFreeOverrideForTests = closureFree; + try + { + using var memory = new GuestGpuMemory(new RecordingAddressSpace()); + var store = new Store(); + memory.AttachStores(store, null); + memory.Register(0x10000, 0x4000, GuestPageProtection.Read | GuestPageProtection.Write); + store.Calls.Clear(); + using (memory.BeginManagedWrite(0x20000, 0x100)) { } + using (memory.BeginManagedWrite(0x0F000, 0x1000)) { } + Assert.Empty(store.Calls); + } + finally + { + HostCallTrims.MarkClosureFreeOverrideForTests = savedOverride; + } + } + + // Compare allocation across complete BeginManagedWrite calls outside every span. + [Fact] + public void ClosureFreeMarksOutsideEverySpanAllocateLessThanTheClosure() + { + using var memory = new GuestGpuMemory(new RecordingAddressSpace()); + memory.AttachStores(new Store(), null); + memory.Register(0x10000, 0x4000, GuestPageProtection.Read | GuestPageProtection.Write); + + long Allocated(bool closureFree) + { + var savedOverride = HostCallTrims.MarkClosureFreeOverrideForTests; + HostCallTrims.MarkClosureFreeOverrideForTests = closureFree; + try + { + for (var warm = 0; warm < 16; warm++) + using (memory.BeginManagedWrite(0x20000, 8)) { } + var before = GC.GetAllocatedBytesForCurrentThread(); + for (var write = 0; write < 256; write++) + using (memory.BeginManagedWrite(0x20000, 8)) { } + return GC.GetAllocatedBytesForCurrentThread() - before; + } + finally + { + HostCallTrims.MarkClosureFreeOverrideForTests = savedOverride; + } + } + + var withClosure = Allocated(closureFree: false); + var closureFree = Allocated(closureFree: true); + // A whole-call allocation floor and difference; these assertions do not count individual objects. + Assert.True(withClosure >= 256 * 2 * 2 * 24, $"closure path allocated {withClosure} bytes"); + Assert.True(withClosure - closureFree >= 256 * 2 * 2 * 24, + $"closure path {withClosure} bytes, closure-free {closureFree} bytes"); + } + + // A write through one backing view: the stores take PrepareEmulatorWrite and NoteEmulatorWrite for every intersection. + [Fact] + public void EmulatorWriteAcrossUnregisteredGapNotifiesEveryMappedIntersection() + { + using var memory = new GuestGpuMemory(new RecordingAddressSpace()); + var store = new Store(); + memory.AttachStores(store, null); + const GuestPageProtection access = GuestPageProtection.Read | GuestPageProtection.Write; + memory.Register(0x10000, 0x4000, access); + memory.Register(0x18000, 0x4000, access); + store.Calls.Clear(); + using (memory.BeginManagedWrite(0x12000, 0x8000, emulatorWrite: true)) { } + Assert.Equal(new (bool, ulong, ulong)[] + { + (false, 0x12000, 0x2000), (false, 0x18000, 0x2000), + (true, 0x12000, 0x2000), (true, 0x18000, 0x2000) + }, store.Calls); + Assert.Equal(new (ulong, ulong)[] { (0x12000, 0x2000), (0x18000, 0x2000) }, store.EmulatorWrites); + } + + // A GPU claim between the premark and the reservation invalidates the attempt: the write recovers GPU data again before + // its bytes land, in a registered span and in a lazily backed range alike. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void EmulatorWriteRetriesRecoveryAfterAnInterveningGpuClaim(bool lazy) + { + using var memory = new GuestGpuMemory(new RecordingAddressSpace()); + var store = new Store { GpuData = false }; + memory.AttachStores(store, null); + if (lazy) memory.RegisterLazyRange(0x10000, 0x4000); + else memory.Register(0x10000, 0x4000, GuestPageProtection.Read | GuestPageProtection.Write); + store.Calls.Clear(); + var attempts = 0; + memory.BeforeManagedWriteReservationForTest = retry => + { + attempts++; + if (retry != 0) return; + using var claim = memory.Pages.ManagedWrites.BeginGpuClaim(0x10000, 16); + store.GpuData = true; + }; + using (memory.BeginManagedWrite(0x10000, 16, emulatorWrite: true)) + { + Assert.Equal(2, attempts); + Assert.Equal(new (bool, ulong, ulong)[] { (false, 0x10000, 16) }, store.Calls); + Assert.Empty(store.EmulatorWrites); + } + + Assert.Equal(new (bool, ulong, ulong)[] { (false, 0x10000, 16), (true, 0x10000, 16) }, store.Calls); + Assert.Equal(new (ulong, ulong)[] { (0x10000, 16) }, store.EmulatorWrites); + } + + // A write over a registered span and a lazily backed range marks both intersections. + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public void PartialWriteIncludesLazyAndRegisteredIntersections(bool emulatorWrite, bool closureFree) + { + var savedOverride = HostCallTrims.MarkClosureFreeOverrideForTests; + HostCallTrims.MarkClosureFreeOverrideForTests = closureFree; + try + { + using var memory = new GuestGpuMemory(new RecordingAddressSpace()); + var store = new Store(); + memory.AttachStores(store, null); + memory.Register(0x10000, 0x4000, GuestPageProtection.Read | GuestPageProtection.Write); + memory.RegisterLazyRange(0x18000, 0x4000); + store.Calls.Clear(); + using (memory.BeginManagedWrite(0x12000, 0x8000, emulatorWrite)) { } + Assert.Equal(new (bool, ulong, ulong)[] + { + (false, 0x12000, 0x2000), (false, 0x18000, 0x2000), + (true, 0x12000, 0x2000), (true, 0x18000, 0x2000) + }, store.Calls); + } + finally + { + HostCallTrims.MarkClosureFreeOverrideForTests = savedOverride; + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ReservedHookOrLandedExceptionReleasesAdmission(bool failLanded) + { + using var memory = new GuestGpuMemory(new RecordingAddressSpace()); + var store = new Store(); + memory.AttachStores(store, null); + memory.Register(0x10000, 0x4000, GuestPageProtection.Read | GuestPageProtection.Write); + // Registration reports the span to the store; arm the failure and count calls from the write on. + store.Calls.Clear(); + store.ThrowOnLanded = failLanded; + if (!failLanded) + memory.ManagedWriteReservedForTest = () => throw new InvalidOperationException("Synthetic reserved hook failure."); + Assert.Throws(() => + { + using var write = memory.BeginManagedWrite(0x10000, 16); + }); + using var claim = memory.Pages.ManagedWrites.BeginGpuClaim(0x10000, 16); + Assert.Equal(failLanded ? 2 : 1, store.Calls.Count); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/GuestPageTrackerTests.cs b/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/GuestPageTrackerTests.cs index 451f9124d..728f8ce21 100644 --- a/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/GuestPageTrackerTests.cs +++ b/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/GuestPageTrackerTests.cs @@ -229,6 +229,31 @@ public void CpuDirtySummaryFollowsEveryTransitionOfTheBlock() Release(address, Region); } + // The lock-free query over several blocks: clean blocks pass on their summary bits, a dirty page in any one block is + // found, and a block without a region (here the last block of the summary word below) is never known clean. + [NativePageProtectionFact] + public void LockFreeCpuDirtyQuerySpansBlocksAndSummaryWords() + { + var address = AllocateAligned(Region * 3, Region * 64); + _tracker.ForEachUploadRange(address, Region * 3, false, NoRange, NoUpload, preserveCpuWriteHotPages: false); + Assert.False(_tracker.MayHaveCpuDirtyPages(address, Region * 3)); + Assert.True(_tracker.MayHaveCpuDirtyPages(address - Region + Page, Region)); + + _tracker.MarkCpuDirtyPages(address + Region * 2 + Page * 7, 8); + Assert.True(_tracker.MayHaveCpuDirtyPages(address, Region * 3)); + Assert.False(_tracker.MayHaveCpuDirtyPages(address, Region * 2)); + Assert.False(_tracker.MayHaveCpuDirtyPages(address + Region * 2, Page * 7)); + Assert.True(_tracker.MayHaveCpuDirtyPages(address + Region, Region + Page * 8)); + + _tracker.ForEachUploadRange(address, Region * 3, false, NoRange, NoUpload, preserveCpuWriteHotPages: false); + _tracker.MarkCpuDirtyPages(address + 16, 8); + Assert.True(_tracker.MayHaveCpuDirtyPages(address, Region * 3)); + Assert.False(_tracker.MayHaveCpuDirtyPages(address + Page, Region * 3 - Page)); + + _tracker.UntrackMemory(address, Region * 3); + Release(address, Region * 3); + } + [NativePageProtectionFact] public void PossiblyCpuDirtyRangesSkipOnlyBlocksKnownClean() { diff --git a/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/GuestWriteReservationsTests.cs b/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/GuestWriteReservationsTests.cs new file mode 100644 index 000000000..2ced7044d --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/GuestWriteReservationsTests.cs @@ -0,0 +1,430 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE.GpuMemory; +using Xunit; + +namespace SharpEmu.Libs.Tests.Memory.GpuMemory; + +public sealed class GuestWriteReservationsTests +{ + private const ulong Address = 0x10000; + private static readonly TimeSpan Deadline = TimeSpan.FromSeconds(10); + + [Fact] + public void StaleCopiedTokenCannotReleaseOrReserveANewerAttempt() + { + var owner = new GuestWriteReservations(); + var old = owner.BeginCpuAttempt(Address, 16); + var copy = old; + old.Dispose(); + using var current = owner.BeginCpuAttempt(Address, 16); + copy.Dispose(); + Assert.True(copy.Released); + Assert.False(current.Released); + Assert.Throws(() => copy.TryReserve()); + Assert.True(current.TryReserve()); + copy.Dispose(); + Assert.Throws(() => owner.BeginGpuClaim(Address, 16)); + } + + [Fact] + public void InvalidatedTokenStaysInvalidUntilAFreshAttemptIsAdmitted() + { + var owner = new GuestWriteReservations(); + var attempt = owner.BeginCpuAttempt(Address, 16); + var copy = attempt; + using (owner.BeginGpuClaim(Address, 16)) { } + Assert.False(attempt.TryReserve()); + Assert.False(copy.TryReserve()); + copy.Dispose(); + Assert.True(attempt.Released); + using var fresh = owner.BeginCpuAttempt(Address, 16); + Assert.True(fresh.TryReserve()); + attempt.Dispose(); + Assert.False(fresh.Released); + } + + [Fact] + public void InterveningClaimForcesFreshPremarkEvenAfterClaimFinished() + { + var owner = new GuestWriteReservations(); + using (var attempt = owner.BeginCpuAttempt(Address, 16)) + { + using (owner.BeginGpuClaim(Address + 128, 16)) { } + Assert.False(attempt.TryReserve()); + } + using var fresh = owner.BeginCpuAttempt(Address, 16); + Assert.True(fresh.TryReserve()); + } + + [Fact] + public void UnrelatedPageClaimDoesNotInvalidateTheAttempt() + { + var owner = new GuestWriteReservations(); + using var attempt = owner.BeginCpuAttempt(Address, 16); + using (owner.BeginGpuClaim(Address + TrackerLayout.PageBytes, 16)) { } + Assert.True(attempt.TryReserve()); + } + + [Fact] + public async Task ReservationBlocksClaimUntilReleaseAndCoversTheWholePage() + { + var owner = new GuestWriteReservations(); + var blocked = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var reserved = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var releaseCpu = new ManualResetEventSlim(); + owner.GpuClaimWaitingForTest = () => blocked.TrySetResult(true); + var cpu = Task.Run(() => + { + using var attempt = owner.BeginCpuAttempt(Address + 7, 1); + Assert.True(attempt.TryReserve()); + reserved.TrySetResult(true); + if (!releaseCpu.Wait(Deadline)) throw new TimeoutException("The test did not release the CPU reservation."); + }); + await reserved.Task.WaitAsync(Deadline); + var admitted = false; + var gpu = Task.Run(() => + { + using var claim = owner.BeginGpuClaim(Address + 2048, 1); + admitted = true; + }); + try + { + await blocked.Task.WaitAsync(Deadline); + Assert.False(gpu.IsCompleted); + Assert.False(admitted); + } + finally + { + releaseCpu.Set(); + await cpu.WaitAsync(Deadline); + await gpu.WaitAsync(Deadline); + owner.GpuClaimWaitingForTest = null; + } + Assert.True(admitted); + } + + [Fact] + public async Task ActiveGpuClaimFinishesBeforeCpuPremarkCanBegin() + { + var owner = new GuestWriteReservations(); + using var release = new ManualResetEventSlim(); + var admitted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var cpuBlocked = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + owner.CpuAttemptWaitingForTest = () => cpuBlocked.TrySetResult(true); + var gpu = Task.Run(() => + { + using var claim = owner.BeginGpuClaim(Address, 64); + admitted.TrySetResult(true); + if (!release.Wait(Deadline)) throw new TimeoutException("The test did not release the GPU claim."); + }); + await admitted.Task.WaitAsync(Deadline); + var cpu = Task.Run(() => + { + using var attempt = owner.BeginCpuAttempt(Address, 64); + return attempt.TryReserve(); + }); + try + { + await cpuBlocked.Task.WaitAsync(Deadline); + Assert.False(cpu.IsCompleted); + release.Set(); + await gpu.WaitAsync(Deadline); + Assert.True(await cpu.WaitAsync(Deadline)); + } + finally + { + release.Set(); + await gpu.WaitAsync(Deadline); + await cpu.WaitAsync(Deadline); + } + } + + [Fact] + public void NestedPremarkAndOverlappingGpuWorkAreRejectedWhileReserved() + { + var owner = new GuestWriteReservations(); + using var attempt = owner.BeginCpuAttempt(Address, 16); + Assert.True(attempt.TryReserve()); + Assert.Throws(() => owner.BeginCpuAttempt(Address + 0x2000, 16)); + Assert.Throws(() => owner.BeginGpuClaim(Address, 16)); + } + + [Fact] + public void AbortedAttemptAndThrownCopyReleaseAdmission() + { + var owner = new GuestWriteReservations(); + using (owner.BeginCpuAttempt(Address, 16)) { } + Assert.Throws((Action)(() => + { + using var attempt = owner.BeginCpuAttempt(Address, 16); + Assert.True(attempt.TryReserve()); + throw new InvalidOperationException("Synthetic copy failure"); + })); + using var claim = owner.BeginGpuClaim(Address, 16); + } + + [Fact] + public void GpuOwnerCanPerformAReentrantManagedStore() + { + var owner = new GuestWriteReservations(); + using var claim = owner.BeginGpuClaim(Address, 16); + using var attempt = owner.BeginCpuAttempt(Address, 16); + Assert.True(attempt.TryReserve()); + } + + [Fact] + public async Task DisjointGpuOwnersCanEachPerformAReentrantManagedStore() + { + var owner = new GuestWriteReservations(); + using var startCpu = new ManualResetEventSlim(); + using var releaseCpu = new ManualResetEventSlim(); + var claims = Enumerable.Range(0, 2).Select(_ => + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)).ToArray(); + var reserved = Enumerable.Range(0, 2).Select(_ => + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)).ToArray(); + var workers = Enumerable.Range(0, 2).Select(index => Task.Run(() => + { + var address = Address + (ulong)index * TrackerLayout.PageBytes; + using var claim = owner.BeginGpuClaim(address, 16); + claims[index].TrySetResult(claim); + if (!startCpu.Wait(Deadline)) throw new TimeoutException("The test did not start the CPU premarks."); + using var attempt = owner.BeginCpuAttempt(address, 16); + Assert.True(attempt.TryReserve()); + reserved[index].TrySetResult(true); + if (!releaseCpu.Wait(Deadline)) throw new TimeoutException("The test did not release the CPU copies."); + })).ToArray(); + try + { + await Task.WhenAll(claims.Select(x => x.Task)).WaitAsync(Deadline); + startCpu.Set(); + await Task.WhenAll(reserved.Select(x => x.Task)).WaitAsync(Deadline); + } + finally + { + startCpu.Set(); + releaseCpu.Set(); + // Also unwind a broken global-gate implementation: neither task may retain + // its claim forever while waiting for the other task's unrelated claim. + foreach (var claim in claims) + if (claim.Task.IsCompletedSuccessfully) claim.Task.Result.Dispose(); + await Task.WhenAll(workers).WaitAsync(Deadline); + } + } + + // A write across two 2 MiB regions reserves on the locked path and still holds back an overlapping claim. + [Fact] + public async Task WriteAcrossRegionsBlocksAnOverlappingClaim() + { + var owner = new GuestWriteReservations(); + const ulong boundary = 0x400000; + var blocked = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + owner.GpuClaimWaitingForTest = () => blocked.TrySetResult(true); + var attempt = owner.BeginCpuAttempt(boundary - 16, 32); + Assert.True(attempt.TryReserve()); + var gpu = Task.Run(() => + { + using var claim = owner.BeginGpuClaim(boundary + 64, 16); + }); + await blocked.Task.WaitAsync(Deadline); + Assert.False(gpu.IsCompleted); + attempt.Dispose(); + await gpu.WaitAsync(Deadline); + owner.GpuClaimWaitingForTest = null; + } + + // More claims on other pages of the region than the claim history keeps invalidate the attempt: the history no + // longer shows whether one of them covered its pages. + [Fact] + public void ClaimsBeyondTheHistoryInvalidateAnAttemptConservatively() + { + var owner = new GuestWriteReservations(); + using (var attempt = owner.BeginCpuAttempt(Address, 16)) + { + for (var index = 0; index < 65; index++) + { + using (owner.BeginGpuClaim(Address + TrackerLayout.PageBytes * (ulong)(1 + index % 8), 16)) { } + } + Assert.False(attempt.TryReserve()); + } + using var fresh = owner.BeginCpuAttempt(Address, 16); + Assert.True(fresh.TryReserve()); + } + + // Writers on several threads and a claimer on another, over a few shared pages: an admitted claim never overlaps a + // reserved write, and a reserved write never overlaps an admitted claim. + [Fact] + public async Task ConcurrentWritersAndClaimsNeverOverlap() + { + var owner = new GuestWriteReservations(); + const int pages = 6; + var reserved = new int[pages]; + var claimed = new int[pages]; + var violations = 0; + var stop = DateTime.UtcNow + TimeSpan.FromSeconds(1.5); + var writers = Enumerable.Range(0, 4).Select(seed => Task.Run(() => + { + var random = new System.Random(seed); + while (DateTime.UtcNow < stop) + { + var page = random.Next(pages); + var address = Address + (ulong)page * TrackerLayout.PageBytes; + while (true) + { + using var attempt = owner.BeginCpuAttempt(address, 8); + if (!attempt.TryReserve()) continue; + Interlocked.Increment(ref reserved[page]); + if (Volatile.Read(ref claimed[page]) != 0) Interlocked.Increment(ref violations); + Thread.SpinWait(random.Next(50)); + Interlocked.Decrement(ref reserved[page]); + break; + } + } + })).ToArray(); + var claimer = Task.Run(() => + { + var random = new System.Random(99); + while (DateTime.UtcNow < stop) + { + var first = random.Next(pages); + var count = 1 + random.Next(pages - first); + using var claim = owner.BeginGpuClaim(Address + (ulong)first * TrackerLayout.PageBytes, (ulong)count * TrackerLayout.PageBytes); + for (var page = first; page < first + count; page++) + { + Interlocked.Increment(ref claimed[page]); + if (Volatile.Read(ref reserved[page]) != 0) Interlocked.Increment(ref violations); + } + Thread.SpinWait(random.Next(50)); + for (var page = first; page < first + count; page++) Interlocked.Decrement(ref claimed[page]); + } + }); + await Task.WhenAll(writers.Append(claimer)).WaitAsync(TimeSpan.FromSeconds(30)); + Assert.Equal(0, violations); + } + + // Writes on chunks that no claim has covered reserve in their threads' records and do not wait for each other. + [Fact] + public async Task WritesOnUnclaimedChunksDoNotExcludeEachOther() + { + var owner = new GuestWriteReservations(); + var reserved = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var release = new ManualResetEventSlim(); + var first = Task.Run(() => + { + using var attempt = owner.BeginCpuAttempt(Address, 16); + Assert.True(attempt.TryReserve()); + reserved.TrySetResult(true); + if (!release.Wait(Deadline)) throw new TimeoutException("The test did not release the first write."); + }); + try + { + await reserved.Task.WaitAsync(Deadline); + var second = await Task.Run(() => + { + using var attempt = owner.BeginCpuAttempt(Address + 8, 16); + return attempt.TryReserve(); + }).WaitAsync(Deadline); + Assert.True(second); + } + finally + { + release.Set(); + await first.WaitAsync(Deadline); + } + } + + // The claim that marks a chunk waits for a write recorded anywhere in the chunk, not only over its own pages: a later + // claim over the recorded pages finds the chunk marked and reads no records. + [Fact] + public async Task ClaimThatMarksAChunkWaitsForAWriteRecordedElsewhereInIt() + { + var owner = new GuestWriteReservations(); + var blocked = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var reserved = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var releaseCpu = new ManualResetEventSlim(); + owner.GpuClaimWaitingForTest = () => blocked.TrySetResult(true); + var cpu = Task.Run(() => + { + using var attempt = owner.BeginCpuAttempt(Address, 16); + Assert.True(attempt.TryReserve()); + reserved.TrySetResult(true); + if (!releaseCpu.Wait(Deadline)) throw new TimeoutException("The test did not release the CPU reservation."); + }); + await reserved.Task.WaitAsync(Deadline); + var admitted = false; + var gpu = Task.Run(() => + { + using var claim = owner.BeginGpuClaim(Address + 5 * TrackerLayout.PageBytes, 16); + admitted = true; + }); + try + { + await blocked.Task.WaitAsync(Deadline); + Assert.False(gpu.IsCompleted); + Assert.False(admitted); + } + finally + { + releaseCpu.Set(); + await cpu.WaitAsync(Deadline); + await gpu.WaitAsync(Deadline); + owner.GpuClaimWaitingForTest = null; + } + Assert.True(admitted); + } + + // A claimer marks a fresh chunk every 20 ms while writers reserve all over the chunks, so writes keep meeting a chunk + // as it is marked: an admitted claim never overlaps a reserved write, and a reserved write never overlaps an admitted + // claim. + [Fact] + public async Task ClaimsMarkingFreshChunksNeverOverlapReservedWrites() + { + var owner = new GuestWriteReservations(); + const int chunks = 64; + const ulong chunkBytes = 0x10000; + var reserved = new int[chunks]; + var claimed = new int[chunks]; + var violations = 0; + var stop = DateTime.UtcNow + TimeSpan.FromSeconds(1.5); + var writers = Enumerable.Range(0, 4).Select(seed => Task.Run(() => + { + var random = new System.Random(seed); + while (DateTime.UtcNow < stop) + { + var chunk = random.Next(chunks); + var address = Address + (ulong)chunk * chunkBytes + (ulong)random.Next(16) * TrackerLayout.PageBytes; + while (true) + { + using var attempt = owner.BeginCpuAttempt(address, 8); + if (!attempt.TryReserve()) continue; + Interlocked.Increment(ref reserved[chunk]); + if (Volatile.Read(ref claimed[chunk]) != 0) Interlocked.Increment(ref violations); + Thread.SpinWait(random.Next(50)); + Interlocked.Decrement(ref reserved[chunk]); + break; + } + } + })).ToArray(); + var claimer = Task.Run(() => + { + var random = new System.Random(99); + var clock = System.Diagnostics.Stopwatch.StartNew(); + var next = 0; + while (DateTime.UtcNow < stop) + { + int chunk; + if (next < chunks && clock.ElapsedMilliseconds >= next * 20L) chunk = next++; + else if (next > 0) chunk = random.Next(next); + else continue; + using var claim = owner.BeginGpuClaim(Address + (ulong)chunk * chunkBytes, chunkBytes); + Interlocked.Increment(ref claimed[chunk]); + if (Volatile.Read(ref reserved[chunk]) != 0) Interlocked.Increment(ref violations); + Thread.SpinWait(random.Next(50)); + Interlocked.Decrement(ref claimed[chunk]); + } + }); + await Task.WhenAll(writers.Append(claimer)).WaitAsync(TimeSpan.FromSeconds(30)); + Assert.Equal(0, violations); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/SpanSnapshotLastHitTests.cs b/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/SpanSnapshotLastHitTests.cs new file mode 100644 index 000000000..d00ebf04d --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/SpanSnapshotLastHitTests.cs @@ -0,0 +1,120 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE.GpuMemory; +using Xunit; + +namespace SharpEmu.Libs.Tests.Memory.GpuMemory; + +public sealed class SpanSnapshotLastHitTests +{ + [Fact] + public void Contains_RequiresFullRangeWithinTheCachedSpan() + { + var snapshot = new SpanSnapshot([0x1000, 0x4000], [0x2000, 0x5000]); + Assert.True(snapshot.ContainsWithLastHit(0x1100, 4)); + Assert.True(snapshot.ContainsWithLastHit(0x1800, 0x800)); + Assert.False(snapshot.ContainsWithLastHit(0x1800, 0x801)); + Assert.False(snapshot.ContainsWithLastHit(0x0FFF, 1)); + Assert.False(snapshot.ContainsWithLastHit(0x2000, 1)); + Assert.False(snapshot.ContainsWithLastHit(0x3000, 4)); + Assert.True(snapshot.ContainsWithLastHit(0x4000, 0x1000)); + Assert.True(snapshot.ContainsWithLastHit(0x1000, 0x1000)); + } + + [Fact] + public void Contains_UsesSnapshotIdentityAfterUnmappingAndRemapping() + { + var set = new SpanSet(); + set.Add(0x1000, 0x3000); + var original = set.Snapshot(); + Assert.True(original.ContainsWithLastHit(0x2000, 4)); + + set.Remove(0x2000, 0x1000); + var unmapped = set.Snapshot(); + Assert.False(unmapped.ContainsWithLastHit(0x2000, 4)); + Assert.True(unmapped.ContainsWithLastHit(0x3000, 4)); + Assert.True(original.ContainsWithLastHit(0x2000, 4)); + Assert.False(unmapped.ContainsWithLastHit(0x2000, 4)); + + set.Add(0x2000, 0x1000); + Assert.True(set.Snapshot().ContainsWithLastHit(0x2000, 4)); + Assert.False(SpanSnapshot.Empty.ContainsWithLastHit(0x2000, 4)); + } + + [Fact] + public void Contains_MatchesBinarySearchForBoundaryAndOverflowRequests() + { + ulong[] starts = [0x1000, 0x4000, ulong.MaxValue - 0x1000]; + ulong[] ends = [0x2000, 0x5000, ulong.MaxValue]; + var snapshot = new SpanSnapshot(starts, ends); + ulong[] addresses = [0, 0xFFF, 0x1000, 0x1FFF, 0x2000, 0x3000, 0x4000, 0x4FFF, + ulong.MaxValue - 0x1000, ulong.MaxValue - 1, ulong.MaxValue]; + ulong[] sizes = [0, 1, 4, 0x1000, ulong.MaxValue]; + for (var repetition = 0; repetition < 2; repetition++) + foreach (var address in addresses) + foreach (var size in sizes) + { + var index = Array.BinarySearch(starts, address); + if (index < 0) index = ~index - 1; + var expected = index >= 0 && ends[index] >= unchecked(address + size); + Assert.Equal(expected, snapshot.ContainsWithLastHit(address, size)); + } + } + + [Fact] + public void Contains_ConcurrentCallersCanCacheDifferentSnapshotsAndSpans() + { + var left = new SpanSnapshot([0x1000, 0x4000], [0x2000, 0x5000]); + var right = new SpanSnapshot([0x1000, 0x8000], [0x1800, 0x9000]); + Parallel.For(0, 64, worker => + { + for (var iteration = 0; iteration < 100; iteration++) + { + Assert.True(left.ContainsWithLastHit(0x1900, 4)); + Assert.False(right.ContainsWithLastHit(0x1900, 4)); + Assert.True(right.ContainsWithLastHit(0x8000, 4)); + Assert.False(left.ContainsWithLastHit(0x8000, 4)); + Assert.True(left.ContainsWithLastHit(worker % 2 == 0 ? 0x1000UL : 0x4000UL, 4)); + } + }); + } + + // Random spans and queries: the cached answer equals a linear scan of the snapshot's spans, while older snapshots' hits + // are still remembered on this thread. + [Fact] + public void Contains_MatchesALinearScanAcrossSuccessiveSnapshots() + { + var random = new System.Random(1234); + var set = new SpanSet(); + var older = new List(); + for (var round = 0; round < 40; round++) + { + for (var change = 0; change < 6; change++) + { + var address = (ulong)random.Next(0, 256) * 0x100; + var size = (ulong)random.Next(1, 32) * 0x100; + if (random.Next(3) == 0) set.Remove(address, size); + else set.Add(address, size); + } + + var snapshot = set.Snapshot(); + var spans = new List<(ulong Start, ulong End)>(); + set.ForEach((start, size) => spans.Add((start, start + size))); + older.Add(snapshot); + for (var query = 0; query < 400; query++) + { + var address = (ulong)random.Next(0, 0x11000); + var size = (ulong)random.Next(0, 0x2000); + var index = spans.FindLastIndex(span => span.Start <= address); + var expected = index >= 0 && spans[index].End >= address + size; + Assert.Equal(expected, snapshot.ContainsWithLastHit(address, size)); + if (query % 50 == 0) + { + // Warm another snapshot's hit on this thread between queries. + _ = older[random.Next(older.Count)].ContainsWithLastHit(address, 4); + } + } + } + } +} diff --git a/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/SpanSnapshotOverlapTests.cs b/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/SpanSnapshotOverlapTests.cs new file mode 100644 index 000000000..6704ecf48 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/SpanSnapshotOverlapTests.cs @@ -0,0 +1,29 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE.GpuMemory; +using Xunit; + +namespace SharpEmu.Libs.Tests.Memory.GpuMemory; + +public sealed class SpanSnapshotOverlapTests +{ + // The stateful walk visits the same parts in the same order as the closure walk. + [Fact] + public void TheStatefulWalkMatchesTheClosureWalk() + { + var snapshot = new SpanSnapshot([0x1000, 0x4000, 0x6000], [0x2000, 0x5000, 0x8000]); + ulong[] addresses = [0, 0xFFF, 0x1000, 0x1800, 0x1FFF, 0x2000, 0x3000, 0x3FFF, 0x4800, 0x5000, 0x5FFF, 0x7FFF, + 0x8000, 0x9000]; + ulong[] sizes = [1, 4, 0x800, 0x1000, 0x3000, 0x8000]; + foreach (var address in addresses) + foreach (var size in sizes) + { + var closure = new List<(ulong, ulong)>(); + snapshot.ForEachOverlap(address, size, (part, partSize) => closure.Add((part, partSize))); + var stateful = new List<(ulong, ulong)>(); + snapshot.ForEachOverlap(address, size, stateful, static (list, part, partSize) => list.Add((part, partSize))); + Assert.Equal(closure, stateful); + } + } +} diff --git a/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/PhysicalVirtualMemoryBackedTests.cs b/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/PhysicalVirtualMemoryBackedTests.cs index 78ae6dc7d..726e7cf1a 100644 --- a/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/PhysicalVirtualMemoryBackedTests.cs +++ b/tests/SharpEmu.Libs.Tests/Memory/GuestMemory/PhysicalVirtualMemoryBackedTests.cs @@ -370,8 +370,76 @@ public void ManagedWritesMarkTheGpuStoresAgainOnceTheBytesLand() } } - [Fact] - public void MixedCopyWithProtectedPrivateMemoryDoesNotUpgradeUnderTheReadLock() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void MixedCopyWithProtectedPrivateMemoryDoesNotUpgradeUnderTheReadLock(bool direct) + { + var saved = HostCallTrims.MixedCopyOverrideForTests; + HostCallTrims.MixedCopyOverrideForTests = direct; + try + { + MixedCopyWithProtectedPrivateMemory(); + } + finally + { + HostCallTrims.MixedCopyOverrideForTests = saved; + } + } + + // Copies between backed and private memory leave the same bytes and results with the direct copy as through + // staging: backed to private (whole and unaligned), private to backed, and a copy that runs past the backed mapping. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void MixedCopiesLeaveTheSameBytesDirectlyAsThroughStaging(bool direct) + { + if (!Supported) return; + var saved = HostCallTrims.MixedCopyOverrideForTests; + HostCallTrims.MixedCopyOverrideForTests = direct; + try + { + var host = HostViewMemory.Create(); + using var memory = new PhysicalVirtualMemory(viewHost: host, backingBytes: BackingSize); + var view = Hold(memory, host); + Assert.True(memory.TryMapBacked(view, Segment, 0, GuestPageProtection.Read | GuestPageProtection.Write, out _)); + var writable = MapPrivate(memory, host, 2 * Segment, ProgramHeaderFlags.Read | ProgramHeaderFlags.Write); + var pattern = new byte[Segment]; + for (var i = 0; i < pattern.Length; i++) pattern[i] = (byte)(i * 7 + 1); + Assert.True(memory.TryWrite(view, pattern)); + + Assert.True(memory.TryCopy(writable, view, Segment)); + Assert.Equal(pattern, Read(memory, writable, (int)Segment)); + Assert.True(memory.TryCopy(writable + Segment + 3, view + 5, 0x1001)); + Assert.Equal(pattern.AsSpan(5, 0x1001).ToArray(), Read(memory, writable + Segment + 3, 0x1001)); + + var inverted = new byte[0x2003]; + for (var i = 0; i < inverted.Length; i++) inverted[i] = (byte)~pattern[i]; + Assert.True(memory.TryWrite(writable + 0x100, inverted)); + Assert.True(memory.TryCopy(view + 0x11, writable + 0x100, (ulong)inverted.Length)); + Assert.Equal(inverted, Read(memory, view + 0x11, inverted.Length)); + + // Past the backed mapping: fails, and the destination keeps its bytes. + var sentinel = new byte[0x40]; + Array.Fill(sentinel, (byte)0x5A); + Assert.True(memory.TryWrite(writable + 0x3000, sentinel)); + Assert.False(memory.TryCopy(writable + 0x3000, view + Segment - 0x10, 0x40)); + Assert.Equal(sentinel, Read(memory, writable + 0x3000, sentinel.Length)); + } + finally + { + HostCallTrims.MixedCopyOverrideForTests = saved; + } + } + + private static byte[] Read(PhysicalVirtualMemory memory, ulong address, int length) + { + var bytes = new byte[length]; + Assert.True(memory.TryRead(address, bytes)); + return bytes; + } + + private void MixedCopyWithProtectedPrivateMemory() { if (!Supported) return; var host = HostViewMemory.Create(); diff --git a/tests/SharpEmu.Libs.Tests/Network/HttpExportsTests.cs b/tests/SharpEmu.Libs.Tests/Network/HttpExportsTests.cs new file mode 100644 index 000000000..30f70681b --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Network/HttpExportsTests.cs @@ -0,0 +1,67 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using SharpEmu.Libs.Network; +using Xunit; + +namespace SharpEmu.Libs.Tests.Network; + +public sealed class HttpExportsTests +{ + private const ulong MemoryBase = 0x1_0000_0000; + private const ulong ServerName = MemoryBase + 0x100; + private const ulong Scheme = MemoryBase + 0x140; + private const ulong RequestPath = MemoryBase + 0x180; + private const ulong HeaderName = MemoryBase + 0x1C0; + private const int InvalidId = unchecked((int)0x80431100); + private const int BeforeSend = unchecked((int)0x80431065); + private const int ResolverNoDns = unchecked((int)0x80436002); + private readonly FakeCpuMemory _memory = new(MemoryBase, 0x1000); + private readonly CpuContext _ctx; + + public HttpExportsTests() + { + _ctx = new CpuContext(_memory, Generation.Gen5); + _memory.WriteCString(ServerName, "example.invalid"); + _memory.WriteCString(Scheme, "https"); + _memory.WriteCString(RequestPath, "/upload"); + _memory.WriteCString(HeaderName, "Content-Type"); + } + + // A request is created as on a console; sending it fails without a network and leaves no response to read. + [Fact] + public void RequestsAreCreatedButNeverReachTheServer() + { + var context = Call(HttpExports.HttpInit, 1, 0, 0x10000); + var template = Call(HttpExports.HttpCreateTemplate, (ulong)context, 0, 1, 0); + var connection = Call(HttpExports.HttpCreateConnection, (ulong)template, ServerName, Scheme, 443, 1); + var request = Call(HttpExports.HttpCreateRequest, (ulong)connection, 1, RequestPath, 16); + Assert.NotEqual(template, connection); + Assert.NotEqual(connection, request); + + Assert.Equal(0, Call(HttpExports.HttpAddRequestHeader, (ulong)request, HeaderName, Scheme, 0)); + Assert.Equal(0, Call(HttpExports.HttpSetRequestContentLength, (ulong)request, 32)); + Assert.Equal(ResolverNoDns, Call(HttpExports.HttpSendRequest, (ulong)request, 0, 0)); + Assert.Equal(BeforeSend, Call(HttpExports.HttpGetStatusCode, (ulong)request, MemoryBase)); + Assert.Equal(BeforeSend, Call(HttpExports.HttpReadData, (ulong)request, MemoryBase, 16)); + + Assert.Equal(0, Call(HttpExports.HttpDeleteConnection, (ulong)connection)); + Assert.Equal(InvalidId, Call(HttpExports.HttpDeleteRequest, (ulong)request)); + Assert.Equal(InvalidId, Call(HttpExports.HttpCreateConnection, (ulong)connection, ServerName, Scheme, 443, 1)); + Assert.Equal(0, Call(HttpExports.HttpTerm, (ulong)context)); + } + + private int Call(Func export, params ulong[] arguments) + { + CpuRegister[] registers = [CpuRegister.Rdi, CpuRegister.Rsi, CpuRegister.Rdx, CpuRegister.Rcx, CpuRegister.R8]; + for (var index = 0; index < registers.Length; index++) + { + _ctx[registers[index]] = index < arguments.Length ? arguments[index] : 0; + } + + _ctx[CpuRegister.Rax] = 0; + var result = export(_ctx); + return result == 0 && _ctx[CpuRegister.Rax] != 0 ? unchecked((int)_ctx[CpuRegister.Rax]) : result; + } +} diff --git a/tests/SharpEmu.Libs.Tests/Np/NpEntitlementAccessExportsTests.cs b/tests/SharpEmu.Libs.Tests/Np/NpEntitlementAccessExportsTests.cs index 6288d9c59..45b3ff63b 100644 --- a/tests/SharpEmu.Libs.Tests/Np/NpEntitlementAccessExportsTests.cs +++ b/tests/SharpEmu.Libs.Tests/Np/NpEntitlementAccessExportsTests.cs @@ -35,6 +35,45 @@ public void GetGameTrialsFlagValidatesOutputMemory(ulong address, int expected) Assert.Equal(expected, NpEntitlementAccessExports.NpEntitlementAccessGetGameTrialsFlag(context)); } + // A unified entitlement request finishes at once, signed out, with no entitlements; a deleted request is gone. + [Fact] + public void UnifiedEntitlementListRequestFinishesSignedOutUntilDeleted() + { + const int SignedOut = unchecked((int)0x817D0014); + const int RequestNotFound = unchecked((int)0x817D0015); + var memory = new FakeCpuMemory(MemoryBase, 0x1_000); + var context = new CpuContext(memory, Generation.Gen5); + Assert.True(memory.TryWrite(MemoryBase, Enumerable.Repeat((byte)0xA5, 0x40).ToArray())); + context[CpuRegister.Rdi] = 0x1000_0000; + context[CpuRegister.Rsi] = 0; + context[CpuRegister.Rdx] = 0; + context[CpuRegister.Rcx] = 0; + context[CpuRegister.R8] = MemoryBase + 0x100; + context[CpuRegister.R9] = MemoryBase; + Assert.Equal(0, NpEntitlementAccessExports.NpEntitlementAccessRequestUnifiedEntitlementInfoList(context)); + Assert.True(context.TryReadUInt64(MemoryBase, out var requestId)); + Assert.NotEqual(0UL, requestId); + + context[CpuRegister.Rdi] = requestId; + context[CpuRegister.Rsi] = MemoryBase + 0x10; + context[CpuRegister.Rdx] = MemoryBase + 0x200; + context[CpuRegister.Rcx] = 4; + context[CpuRegister.R8] = MemoryBase + 0x14; + context[CpuRegister.R9] = MemoryBase + 0x18; + Assert.Equal(0, NpEntitlementAccessExports.NpEntitlementAccessPollUnifiedEntitlementInfoList(context)); + Span written = stackalloc byte[12]; + Assert.True(memory.TryRead(MemoryBase + 0x10, written)); + Assert.Equal(SignedOut, BinaryPrimitives.ReadInt32LittleEndian(written)); + Assert.Equal(0, BinaryPrimitives.ReadInt32LittleEndian(written[4..])); + Assert.Equal(0, BinaryPrimitives.ReadInt32LittleEndian(written[8..])); + + context[CpuRegister.Rdi] = requestId; + Assert.Equal(0, NpEntitlementAccessExports.NpEntitlementAccessDeleteRequest(context)); + context[CpuRegister.Rdi] = requestId; + context[CpuRegister.Rsi] = MemoryBase + 0x10; + Assert.Equal(RequestNotFound, NpEntitlementAccessExports.NpEntitlementAccessPollUnifiedEntitlementInfoList(context)); + } + [Theory] [InlineData("GHOST2APP0000000")] [InlineData("GHOST2BASE000000")] diff --git a/tests/SharpEmu.Libs.Tests/Pad/PadExportsTests.cs b/tests/SharpEmu.Libs.Tests/Pad/PadExportsTests.cs index 13d21f156..e228873bc 100644 --- a/tests/SharpEmu.Libs.Tests/Pad/PadExportsTests.cs +++ b/tests/SharpEmu.Libs.Tests/Pad/PadExportsTests.cs @@ -367,6 +367,31 @@ public void IsRemoteController_WritesOneFalseByte() Assert.Equal(0xA5, result[1]); } + [NativeX64Fact] + public void UnknownZBsgF0q8DIM_WritesZeroForAnOpenHandle() + { + const ulong valueAddress = Base + 0x100; + Assert.True(_memory.TryWrite(valueAddress, new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xA5 })); + _ctx[CpuRegister.Rdi] = 1; + _ctx[CpuRegister.Rsi] = valueAddress; + + Assert.Equal(0, PadExports.PadUnknownZBsgF0q8DIM(_ctx)); + Span value = stackalloc byte[5]; + Assert.True(_memory.TryRead(valueAddress, value)); + Assert.Equal(new byte[] { 0, 0, 0, 0, 0xA5 }, value.ToArray()); + } + + [NativeX64Theory] + [InlineData(2, Base + 0x100, InvalidHandle)] + [InlineData(1, 0ul, unchecked((int)0x80920001))] + [InlineData(1, Base + 0x1000, (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT)] + public void UnknownZBsgF0q8DIM_RejectsUnknownHandlesAndInvalidOutput(int handle, ulong address, int expected) + { + _ctx[CpuRegister.Rdi] = unchecked((ulong)handle); + _ctx[CpuRegister.Rsi] = address; + Assert.Equal(expected, PadExports.PadUnknownZBsgF0q8DIM(_ctx)); + } + [NativeX64Theory] [InlineData(0ul, unchecked((int)0x80920001))] [InlineData(Base + 0x1000, (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT)] diff --git a/tests/SharpEmu.Libs.Tests/PlayGo/PlayGoExportsTests.cs b/tests/SharpEmu.Libs.Tests/PlayGo/PlayGoExportsTests.cs index b8c22529b..4405a4ae4 100644 --- a/tests/SharpEmu.Libs.Tests/PlayGo/PlayGoExportsTests.cs +++ b/tests/SharpEmu.Libs.Tests/PlayGo/PlayGoExportsTests.cs @@ -142,6 +142,42 @@ public void GetLocus_UnparseableMetadata_RemainsPermissive(UnusableMetadataKind Assert.Equal(new byte[] { LocusLocalFast }, ReadLoci(1)); } + // A title that ships playgo-chunk.dat without playgo-chunkdefs.xml lists the chunks its header counts. + [Theory] + [InlineData(0x6F676C70u)] + [InlineData(0x78676C70u)] + public void GetChunkId_ChunkDatWithoutDefinitions_ListsTheHeaderChunks(uint magic) + { + var dat = new byte[0x40]; + BinaryPrimitives.WriteUInt32LittleEndian(dat, magic); + BinaryPrimitives.WriteUInt16LittleEndian(dat.AsSpan(0x08), 1); + BinaryPrimitives.WriteUInt16LittleEndian(dat.AsSpan(0x0A), 3); + BinaryPrimitives.WriteUInt32LittleEndian(dat.AsSpan(0x10), (uint)dat.Length); + var sceSys = Directory.CreateDirectory(Path.Combine(_app0Root, "sce_sys")); + File.WriteAllBytes(Path.Combine(sceSys.FullName, "playgo-chunk.dat"), dat); + var handle = InitializeAndOpen(); + + _ctx[CpuRegister.Rdi] = handle; + _ctx[CpuRegister.Rsi] = ChunkIdsAddress; + _ctx[CpuRegister.Rdx] = 16; + _ctx[CpuRegister.Rcx] = HandleAddress; + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, PlayGoExports.PlayGoGetChunkId(_ctx)); + Span written = stackalloc byte[sizeof(uint) + 3 * sizeof(ushort)]; + Assert.True(_memory.TryRead(HandleAddress, written[..sizeof(uint)])); + Assert.True(_memory.TryRead(ChunkIdsAddress, written[sizeof(uint)..])); + Assert.Equal(3u, BinaryPrimitives.ReadUInt32LittleEndian(written)); + Assert.Equal(new ushort[] { 0, 1, 2 }, new[] + { + BinaryPrimitives.ReadUInt16LittleEndian(written[4..]), + BinaryPrimitives.ReadUInt16LittleEndian(written[6..]), + BinaryPrimitives.ReadUInt16LittleEndian(written[8..]), + }); + + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, GetLocus(handle, [0, 1, 2])); + Assert.Equal(new byte[] { LocusLocalFast, LocusLocalFast, LocusLocalFast }, ReadLoci(3)); + Assert.Equal(BadChunkId, GetLocus(handle, [3])); + } + [Fact] public void GetLocus_FaultingChunkAndOutputPointers_ReturnMemoryFault() { diff --git a/tests/SharpEmu.Libs.Tests/SaveData/SaveDataExportsTests.cs b/tests/SharpEmu.Libs.Tests/SaveData/SaveDataExportsTests.cs index 003dae6c8..ba88623d0 100644 --- a/tests/SharpEmu.Libs.Tests/SaveData/SaveDataExportsTests.cs +++ b/tests/SharpEmu.Libs.Tests/SaveData/SaveDataExportsTests.cs @@ -219,6 +219,36 @@ public void SyncSaveDataMemory_PostsSyncEndEvent_DrainedOnce() Assert.Equal(NoEvent, SaveDataExports.SaveDataGetEventResult(Reg(rsi: EventOut))); } + // Titles mount as usual after "not found" or "no need to convert"; any other result is their save error path. + [Fact] + public void Convert_ReportsNotFoundThenNoNeedToConvert() + { + const int NoNeedConvert = unchecked((int)0x809F001E); + WriteAscii(SecondDirNamePtr, DirName); + Span convert = stackalloc byte[0x38]; + convert.Clear(); + BinaryPrimitives.WriteInt32LittleEndian(convert, UserId); + BinaryPrimitives.WriteUInt64LittleEndian(convert[0x08..], SecondDirNamePtr); + Assert.True(_memory.TryWrite(DeleteParam, convert)); + + Assert.Equal(NoEvent, SaveDataExports.SaveDataConvert(Reg(rdi: DeleteParam))); + Assert.Equal(0, Mount()); + Assert.Equal(NoNeedConvert, SaveDataExports.SaveDataConvert(Reg(rdi: DeleteParam))); + Assert.Equal(ParameterError, SaveDataExports.SaveDataConvert(Reg(rdi: 0))); + } + + [Fact] + public void Cancel_ReleasesAPreparedResourceAndRejectsAnUnknownOne() + { + const int ResourceInvalid = unchecked((int)0x809F001C); + var resource = SaveDataExports.SaveDataCreateTransactionResource(Reg(rdi: 0x1000)); + Assert.True(resource > 0); + + Assert.Equal(0, SaveDataExports.SaveDataCancel(Reg(rdi: (ulong)resource))); + Assert.Equal(0, SaveDataExports.SaveDataDeleteTransactionResource(Reg(rdi: (ulong)resource))); + Assert.Equal(ResourceInvalid, SaveDataExports.SaveDataCancel(Reg(rdi: (ulong)resource))); + } + [Fact] public void Mount_CreatesSlotDirectory_AndReportsMounted() { diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/BindlessHeapRunTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/BindlessHeapRunTests.cs new file mode 100644 index 000000000..2b7b3d6c1 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/BindlessHeapRunTests.cs @@ -0,0 +1,263 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.VideoOut; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +// Bindless heap revalidation reads sorted records in runs (VulkanVideoPresenter.HeapRecordRunEnd). +public sealed class BindlessHeapRunTests +{ + private const uint ImageBytes = BindlessHeap.ImageRecordBytes; + + [Fact] + public void ARunKeepsRepeatedAndNearbyRecordsAndEndsAtAGap() + { + var gapRecords = VulkanVideoPresenter.HeapRunGapBytes / ImageBytes; + uint[] indexes = [3, 3, 4, 4 + gapRecords + 1, 4 + gapRecords + 1 + gapRecords + 2]; + Assert.Equal(4, VulkanVideoPresenter.HeapRecordRunEnd(indexes, 0, ImageBytes, 49152)); + // 37 skips 32 records after 4 (the gap limit) and stays; 71 skips 33 after 37 and starts its own run. + Assert.Equal(4, VulkanVideoPresenter.HeapRecordRunEnd(indexes, 3, ImageBytes, 49152)); + Assert.Equal(5, VulkanVideoPresenter.HeapRecordRunEnd(indexes, 4, ImageBytes, 49152)); + } + + [Fact] + public void ARunEndsBeforeTheRecordsTheHeapHasNot() + { + uint[] indexes = [10, 11, 12, 13]; + Assert.Equal(2, VulkanVideoPresenter.HeapRecordRunEnd(indexes, 0, ImageBytes, 12)); + } + + [Fact] + public void ARunSpansAtMostTheRunLimit() + { + var limitRecords = VulkanVideoPresenter.HeapRunMaxBytes / ImageBytes; + var indexes = Enumerable.Range(0, (int)limitRecords + 5).Select(static index => (uint)index).ToArray(); + Assert.Equal((int)limitRecords, VulkanVideoPresenter.HeapRecordRunEnd(indexes, 0, ImageBytes, uint.MaxValue)); + } + + // Any sorted set of indexes splits into runs that cover it once each, and every run obeys the limits. + [Theory] + [InlineData(1, 16u)] + [InlineData(2, 32u)] + [InlineData(3, 16u)] + [InlineData(4, 32u)] + public void RunsPartitionSortedIndexesWithinTheLimits(int seed, uint recordBytes) + { + var random = new System.Random(seed); + var indexes = Enumerable.Range(0, 3000).Select(_ => (uint)random.Next(0, 49152)).Order().ToArray(); + var start = 0; + while (start < indexes.Length) + { + var end = VulkanVideoPresenter.HeapRecordRunEnd(indexes, start, recordBytes, 49152); + Assert.True(end > start); + Assert.True(((ulong)indexes[end - 1] - indexes[start] + 1) * recordBytes <= VulkanVideoPresenter.HeapRunMaxBytes); + for (var at = start + 1; at < end; at++) + { + Assert.True((ulong)(indexes[at] - indexes[at - 1]) * recordBytes <= VulkanVideoPresenter.HeapRunGapBytes + recordBytes); + } + + if (end < indexes.Length) + { + var next = indexes[end]; + Assert.True((ulong)(next - indexes[end - 1]) * recordBytes > VulkanVideoPresenter.HeapRunGapBytes + recordBytes || + ((ulong)next - indexes[start] + 1) * recordBytes > VulkanVideoPresenter.HeapRunMaxBytes); + } + + start = end; + } + } + + private const ulong MemoryBase = 0x10000; + + // Guest memory as a byte array from MemoryBase, and one heap in it; every visit is kept with its words. + private sealed class FakeHeap(byte[] memory, ulong heapBase, uint records, uint[] indexes, bool sampler) + : VulkanVideoPresenter.IHeapRunVisitor + { + public ulong Base = heapBase; + public uint Records = records; + public bool FailRunReads; + public int RunReads; + public int RecordReads; + public readonly List<(int Position, uint[] Words)> Visits = new(); + // Runs on each visit; true means the visit resolved. + public Func OnVisit = _ => false; + public readonly uint RecordBytes = sampler ? BindlessHeap.SamplerRecordBytes : BindlessHeap.ImageRecordBytes; + + public BindlessHeapDescriptor Heap(bool samplerHeap) => new(samplerHeap, Base, Records, RecordBytes); + + public bool TryRead(ulong address, Span destination) + { + RunReads++; + return !FailRunReads && Read(address, destination); + } + + public int ReadRecord(int position, Span words) + { + RecordReads++; + var index = indexes[position]; + var count = (int)(RecordBytes / sizeof(uint)); + return Base != 0 && index < Records && + Read(Base + (ulong)index * RecordBytes, System.Runtime.InteropServices.MemoryMarshal.AsBytes(words[..count])) ? count : 0; + } + + public bool Visit(int position, ReadOnlySpan words) + { + Visits.Add((position, words.ToArray())); + return OnVisit(position); + } + + // What one read of the record at index returns now. + public uint[] RecordWords(uint index) + { + var words = new uint[RecordBytes / sizeof(uint)]; + return Base != 0 && index < Records && + Read(Base + (ulong)index * RecordBytes, System.Runtime.InteropServices.MemoryMarshal.AsBytes(words.AsSpan())) ? words : []; + } + + private bool Read(ulong address, Span destination) + { + if (address < MemoryBase || address - MemoryBase + (ulong)destination.Length > (ulong)memory.Length) return false; + memory.AsSpan((int)(address - MemoryBase), destination.Length).CopyTo(destination); + return true; + } + } + + private static byte[] Pattern(int bytes, int seed) + { + var memory = new byte[bytes]; + new System.Random(seed).NextBytes(memory); + return memory; + } + + private static void Visit(FakeHeap heap, uint[] indexes, bool sampler, byte[] buffer) + { + Span scratch = stackalloc uint[8]; + VulkanVideoPresenter.VisitHeapRuns(ref heap, indexes, 0, indexes.Length, sampler, buffer, scratch); + } + + // Every entry is visited once, in order, with the words its own read returns, from far fewer reads. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void RunsVisitEveryEntryOnceInOrderWithItsRecordWords(bool sampler) + { + var memory = Pattern(0x40000, 7); + var random = new System.Random(3); + var indexes = Enumerable.Range(0, 600).Select(_ => (uint)random.Next(0, 4000)).Order().ToArray(); + var heap = new FakeHeap(memory, MemoryBase + 0x100, 4000, indexes, sampler); + Visit(heap, indexes, sampler, new byte[VulkanVideoPresenter.HeapRunMaxBytes]); + Assert.Equal(Enumerable.Range(0, indexes.Length), heap.Visits.Select(visit => visit.Position)); + for (var at = 0; at < indexes.Length; at++) + { + Assert.Equal(heap.RecordWords(indexes[at]), heap.Visits[at].Words); + } + + Assert.True(heap.RunReads < indexes.Length / 4); + Assert.Equal(0, heap.RecordReads); + } + + // A resolve may land bytes over later records of its run: the entries after it read them after it. + [Fact] + public void AResolveRereadsTheRestOfItsRun() + { + var memory = Pattern(0x10000, 11); + uint[] indexes = [0, 1, 2, 3]; + var heap = new FakeHeap(memory, MemoryBase, 64, indexes, sampler: false); + heap.OnVisit = position => + { + if (position != 1) return false; + memory.AsSpan((int)(2 * heap.RecordBytes), (int)heap.RecordBytes).Fill(0xAB); + return true; + }; + Visit(heap, indexes, sampler: false, new byte[VulkanVideoPresenter.HeapRunMaxBytes]); + Assert.Equal(4, heap.Visits.Count); + Assert.All(heap.Visits[2].Words, word => Assert.Equal(0xABABABABu, word)); + Assert.Equal(heap.RecordWords(3), heap.Visits[3].Words); + Assert.Equal(2, heap.RunReads); + } + + // A nested revalidation inside a resolve may reuse the run buffer: no entry after the resolve reads it as it was. + [Fact] + public void ARunBufferOverwrittenDuringAResolveIsReadAgain() + { + var memory = Pattern(0x10000, 13); + uint[] indexes = [4, 5, 6, 7]; + var buffer = new byte[VulkanVideoPresenter.HeapRunMaxBytes]; + var heap = new FakeHeap(memory, MemoryBase, 64, indexes, sampler: false); + heap.OnVisit = position => + { + if (position != 0) return false; + buffer.AsSpan().Fill(0x5A); + return true; + }; + Visit(heap, indexes, sampler: false, buffer); + for (var at = 0; at < indexes.Length; at++) + { + Assert.Equal(heap.RecordWords(indexes[at]), heap.Visits[at].Words); + } + } + + // A run that cannot be read is visited one record read at a time, each right before its visit. + [Fact] + public void AnUnreadableRunFallsBackToOneReadPerEntry() + { + var memory = Pattern(0x10000, 17); + uint[] indexes = [1, 2, 2, 9]; + var heap = new FakeHeap(memory, MemoryBase, 64, indexes, sampler: true) { FailRunReads = true }; + heap.OnVisit = position => + { + if (position != 1) return false; + memory.AsSpan((int)(9 * heap.RecordBytes), (int)heap.RecordBytes).Fill(0x11); + return true; + }; + Visit(heap, indexes, sampler: true, new byte[VulkanVideoPresenter.HeapRunMaxBytes]); + Assert.Equal(4, heap.RecordReads); + for (var at = 0; at < indexes.Length; at++) + { + Assert.Equal(heap.RecordWords(indexes[at]), heap.Visits[at].Words); + } + + Assert.All(heap.Visits[3].Words, word => Assert.Equal(0x11111111u, word)); + } + + // Records the heap does not hold, and every record of a heap at address zero, get no words. + [Fact] + public void RecordsPastTheHeapGetNoWords() + { + var memory = Pattern(0x10000, 19); + uint[] indexes = [1, 3, 5, 9]; + var heap = new FakeHeap(memory, MemoryBase, 4, indexes, sampler: false); + Visit(heap, indexes, sampler: false, new byte[VulkanVideoPresenter.HeapRunMaxBytes]); + Assert.Equal(heap.RecordWords(1), heap.Visits[0].Words); + Assert.Equal(heap.RecordWords(3), heap.Visits[1].Words); + Assert.Empty(heap.Visits[2].Words); + Assert.Empty(heap.Visits[3].Words); + + var unplaced = new FakeHeap(memory, 0, 64, indexes, sampler: false); + Visit(unplaced, indexes, sampler: false, new byte[VulkanVideoPresenter.HeapRunMaxBytes]); + Assert.All(unplaced.Visits, visit => Assert.Empty(visit.Words)); + Assert.Equal(0, unplaced.RunReads); + } + + // A resolve that moves the heap: the entries after it read their records at the new base. + [Fact] + public void AMovedHeapIsReadAtItsNewBaseAfterAResolve() + { + var memory = Pattern(0x20000, 23); + uint[] indexes = [0, 1, 2]; + var heap = new FakeHeap(memory, MemoryBase, 64, indexes, sampler: false); + heap.OnVisit = position => + { + if (position != 0) return false; + heap.Base = MemoryBase + 0x10000; + return true; + }; + Visit(heap, indexes, sampler: false, new byte[VulkanVideoPresenter.HeapRunMaxBytes]); + Assert.Equal(heap.RecordWords(1), heap.Visits[1].Words); + Assert.Equal(heap.RecordWords(2), heap.Visits[2].Words); + Assert.NotEqual(heap.Visits[1].Words, new FakeHeap(memory, MemoryBase, 64, indexes, sampler: false).RecordWords(1)); + } +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/CallRecordPreparationTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/CallRecordPreparationTests.cs new file mode 100644 index 000000000..f6f5cd23f --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/CallRecordPreparationTests.cs @@ -0,0 +1,130 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.Reflection; +using System.Runtime.CompilerServices; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.VideoOut; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +public class CallRecordPreparationTests +{ + // Off: the original preparation. The derived classes run every case with call record spans and with their verify. + internal virtual VulkanVideoPresenter.CallRecordSpanMode Mode => VulkanVideoPresenter.CallRecordSpanMode.Off; + + private const BindingFlags Members = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + private static readonly Type Presenter = typeof(VulkanVideoPresenter).GetNestedType("Presenter", BindingFlags.NonPublic)!; + private const ulong Target = 0x2000; + private const ulong Argument = 0x1000; + + // Exercise the actual row construction without creating a Vulkan device. Empty image/sampler fields make this a + // CPU-only preparation path, while the resulting words are the table the call-record shader search consumes. + private (uint[] Words, DeviceAddressRange[] Ranges) Prepare(FakeCpuMemory memory, CallRecordBuffer[] buffers, + params (ulong Target, ulong Argument)[] records) + { + VulkanVideoPresenter.CallRecordSpanOverride = Mode; + try + { + return PrepareIn(memory, buffers, records); + } + finally + { + VulkanVideoPresenter.CallRecordSpanOverride = null; + } + } + + private static (uint[] Words, DeviceAddressRange[] Ranges) PrepareIn(FakeCpuMemory memory, CallRecordBuffer[] buffers, + (ulong Target, ulong Argument)[] records) + { + var presenter = RuntimeHelpers.GetUninitializedObject(Presenter); + Presenter.GetField("_guestMemory", Members)!.SetValue(presenter, memory); + var program = new ShaderProgramInfo { CallRecordCallees = [new CallRecordCallee([], buffers, 64)] }; + var stage = new ShaderStageResources(program, new ResourceSnapshot()) { CallTargets = [Target], CallRecords = records }; + return ((uint[] Words, DeviceAddressRange[] Ranges))Presenter.GetMethod("PrepareCallRecords", Members)!.Invoke(presenter, [program, stage])!; + } + + private static void WriteDescriptor(FakeCpuMemory memory, ulong argument, ulong address, uint size) + { + Span bytes = stackalloc byte[16]; + BinaryPrimitives.WriteUInt32LittleEndian(bytes, (uint)address); + BinaryPrimitives.WriteUInt32LittleEndian(bytes[4..], (uint)(address >> 32)); + BinaryPrimitives.WriteUInt32LittleEndian(bytes[8..], size); + BinaryPrimitives.WriteUInt32LittleEndian(bytes[12..], 0); + Assert.True(memory.TryWrite(argument, bytes)); + } + + [Fact] + public void ARecordWithoutBufferFieldsKeepsItsKeyAndArgumentRange() + { + var memory = new FakeCpuMemory(Argument, 0x2000); + var result = Prepare(memory, [], (Target, Argument)); + Assert.Equal(1u, result.Words[0]); + Assert.Equal((uint)Argument, result.Words[1]); + Assert.Equal(0u, result.Words[2]); + Assert.Equal(0u, result.Words[3]); + Assert.Contains(result.Ranges, range => range.Base == Argument && range.Size == 64 && !range.Written); + } + + [Theory] + [InlineData(0x8000ul, 64u, false, true, true)] + [InlineData(0x8000ul, 64u, true, true, true)] + [InlineData(1ul << 40, 64u, false, true, false)] + [InlineData(1ul << 40, 64u, true, false, false)] + [InlineData(0ul, 64u, false, true, false)] + [InlineData(0ul, 64u, true, true, false)] + [InlineData(0x8000ul, 0u, false, true, false)] + [InlineData(0x8000ul, 0u, true, true, false)] + public void BufferPolicyControlsTheUploadedRowAndResidentRange(ulong address, uint size, bool written, + bool keep, bool resident) + { + var memory = new FakeCpuMemory(Argument, 0x2000); + WriteDescriptor(memory, Argument, address, size); + var result = Prepare(memory, [new CallRecordBuffer(0, written)], (Target, Argument)); + Assert.Equal(keep ? 1u : 0u, result.Words[0]); + if (!keep) + { + Assert.Empty(result.Ranges); + return; + } + + Assert.Equal((uint)Argument, result.Words[1]); + Assert.Equal(0u, result.Words[2]); + Assert.Equal(0u, result.Words[3]); + Assert.Contains(result.Ranges, range => range.Base == Argument && range.Size == 64 && !range.Written); + Assert.Equal(resident, result.Ranges.Any(range => range.Base == address && range.Size == size && range.Written == written)); + } + + [Fact] + public void AnInvalidWritableRecordDoesNotRemoveTheValidRecordBesideIt() + { + var memory = new FakeCpuMemory(Argument, 0x2000); + WriteDescriptor(memory, Argument, 0x8000, 64); + WriteDescriptor(memory, Argument + 0x100, 1ul << 40, 64); + var result = Prepare(memory, [new CallRecordBuffer(0, true)], + (Target, Argument + 0x100), (Target, Argument)); + Assert.Equal(1u, result.Words[0]); + Assert.Equal((uint)Argument, result.Words[1]); + Assert.Contains(result.Ranges, range => range.Base == 0x8000 && range.Written); + Assert.DoesNotContain(result.Ranges, range => range.Base == Argument + 0x100); + } + + [Fact] + public void AnUnreadableFieldPreservesTheExistingKeepRecordPolicy() + { + var memory = new FakeCpuMemory(Argument, 0x2000); + var result = Prepare(memory, [new CallRecordBuffer(0, true)], (Target, 0x5000)); + Assert.Equal(1u, result.Words[0]); + Assert.Equal(0x5000u, result.Words[1]); + Assert.Single(result.Ranges); + Assert.Equal(0x5000ul, result.Ranges[0].Base); + } +} + +public sealed class SpannedCallRecordPreparationTests : CallRecordPreparationTests +{ + internal override VulkanVideoPresenter.CallRecordSpanMode Mode => VulkanVideoPresenter.CallRecordSpanMode.On; +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/CallRecordSpanTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/CallRecordSpanTests.cs new file mode 100644 index 000000000..623f73b46 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/CallRecordSpanTests.cs @@ -0,0 +1,171 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.Reflection; +using System.Runtime.CompilerServices; +using SharpEmu.HLE; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.VideoOut; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using Mode = SharpEmu.Libs.VideoOut.VulkanVideoPresenter.CallRecordSpanMode; + +namespace SharpEmu.Libs.Tests.VideoOut; + +// Call record spans (VulkanVideoPresenter.CallRecordSpans.cs): on the same memory the preparation hands the bindless heap the +// same descriptor words in the same order, and writes the same words table and merged ranges, as the original; verify keeps +// the separate read and counts a difference. +public sealed class CallRecordSpanTests +{ + private const BindingFlags Members = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + private static readonly Type Presenter = typeof(VulkanVideoPresenter).GetNestedType("Presenter", BindingFlags.NonPublic)!; + private const ulong Base = 0x10000; + private const int Size = 0x10000; + + private sealed record Prepared(uint[] Words, DeviceAddressRange[] Ranges, List Elements); + + // The elements stand in for the bindless heap (which needs a device): each call is listed with its slot and words and + // gets the next number. + private static Prepared Prepare(Mode mode, ICpuMemory memory, CallRecordCallee[] callees, ulong[] targets, + (ulong Target, ulong Argument)[] records, DeviceAddressRange[]? stageRanges = null) + { + var elements = new List(); + VulkanVideoPresenter.CallRecordSpanOverride = mode; + VulkanVideoPresenter.CallRecordElementForTests = (slot, words) => + { + elements.Add($"{slot}:{string.Join(",", words)}"); + return (uint)elements.Count; + }; + try + { + var presenter = RuntimeHelpers.GetUninitializedObject(Presenter); + Presenter.GetField("_guestMemory", Members)!.SetValue(presenter, memory); + var program = new ShaderProgramInfo { CallRecordCallees = callees }; + var stage = new ShaderStageResources(program, new ResourceSnapshot()) + { + CallTargets = targets, + CallRecords = records, + CallRecordRanges = stageRanges, + }; + (uint[] Words, DeviceAddressRange[] Ranges) prepared; + try + { + prepared = ((uint[], DeviceAddressRange[]))Presenter.GetMethod("PrepareCallRecords", Members)!.Invoke(presenter, [program, stage])!; + } + catch (TargetInvocationException exception) when (exception.InnerException is not null) + { + throw exception.InnerException; + } + + return new(prepared.Words, prepared.Ranges, elements); + } + finally + { + VulkanVideoPresenter.CallRecordSpanOverride = null; + VulkanVideoPresenter.CallRecordElementForTests = null; + } + } + + private static void Same(Prepared expected, Prepared actual) + { + Assert.Equal(expected.Words, actual.Words); + Assert.Equal(expected.Ranges, actual.Ranges); + Assert.Equal(expected.Elements, actual.Elements); + } + + // Callees whose fields and V#s lie within one span, one whose span is too wide to read whole, one that reads nothing. + private static readonly CallRecordCallee[] Callees = + [ + new([new CallRecordField(0, false, 1), new CallRecordField(32, true, 7)], [new CallRecordBuffer(48, false)], 64), + new([], [new CallRecordBuffer(0, true), new CallRecordBuffer(16, false)], 32), + new([new CallRecordField(0x100, false, 2)], [new CallRecordBuffer(0, false)], 0), + new([new CallRecordField(0, false, 3)], [new CallRecordBuffer(0x300, false)], 16), + new([], [], 16), + ]; + + private static readonly ulong[] Targets = [0x2000, 0x3000, 0x4000, 0x5000, 0x6000]; + + private static void Descriptor(FakeCpuMemory memory, ulong at, ulong address, uint records, uint stride = 0) + { + Span bytes = stackalloc byte[16]; + BinaryPrimitives.WriteUInt32LittleEndian(bytes, (uint)address); + BinaryPrimitives.WriteUInt32LittleEndian(bytes[4..], (uint)(address >> 32) | stride << 16); + BinaryPrimitives.WriteUInt32LittleEndian(bytes[8..], records); + BinaryPrimitives.WriteUInt32LittleEndian(bytes[12..], 0); + memory.TryWrite(at, bytes); + } + + // Random memory with valid, null and invalid V#s, and records whose spans lie inside the region, cross its end or lie past + // it, with unknown targets and repeated arguments. + private static (FakeCpuMemory Memory, (ulong, ulong)[] Records) RandomRecords(int seed, int count) + { + var random = new System.Random(seed); + var memory = new FakeCpuMemory(Base, Size); + var noise = new byte[Size]; + random.NextBytes(noise); + memory.TryWrite(Base, noise); + var records = new List<(ulong, ulong)>(); + for (var index = 0; index < count; index++) + { + var argument = Base + (ulong)random.Next(0, Size + 0x400) / 16 * 16; + if (random.Next(4) == 0 && records.Count != 0) argument = records[random.Next(records.Count)].Item2; + var target = random.Next(12) == 0 ? 0x9000ul : Targets[random.Next(Targets.Length)]; + if (random.Next(3) == 0) + { + // A V# that describes a buffer at each of the callees' buffer immediates. + foreach (var immediate in new uint[] { 0, 16, 48, 0x300 }) + Descriptor(memory, argument + immediate, 0x8000 + (ulong)random.Next(0x1000) * 16, (uint)random.Next(1, 64), 16); + } + else if (random.Next(3) == 0) + { + // Null V#s, and a written one that describes no buffer. + Descriptor(memory, argument, 0, 0); + Descriptor(memory, argument + 16, 1ul << 40, 64); + } + + if (!records.Contains((target, argument))) records.Add((target, argument)); + } + + return (memory, [.. records]); + } + + [Theory] + [InlineData(1, 8)] + [InlineData(2, 64)] + [InlineData(3, 300)] + [InlineData(4, 2000)] + public void SpansPrepareWhatTheOriginalPrepares(int seed, int count) + { + var (memory, records) = RandomRecords(seed, count); + DeviceAddressRange[] stageRanges = [new(3, 0x8000, 0x40, true, false), new(4, 0x9000, 0x20, true, true)]; + var original = Prepare(Mode.Off, memory, Callees, Targets, records, stageRanges); + Same(original, Prepare(Mode.On, memory, Callees, Targets, records, stageRanges)); + Assert.NotEmpty(original.Elements); + Assert.True(original.Words[0] > 0); + } + + // A record whose span crosses the end of mapped memory is read field by field: the fields inside still read, and the + // ones past the end take the null element, as in the original. + [Fact] + public void ASpanPastMappedMemoryReadsFieldByField() + { + var memory = new FakeCpuMemory(Base, Size); + var argument = Base + Size - 40; + Descriptor(memory, argument + 16, 0x8000, 4, 16); + var records = new[] { (Targets[1], argument), (Targets[0], argument) }; + var original = Prepare(Mode.Off, memory, Callees, Targets, records); + var spanned = Prepare(Mode.On, memory, Callees, Targets, records); + Same(original, spanned); + Assert.Contains(spanned.Ranges, range => range.Base == 0x8000 && range.Size == 64); + Assert.Single(spanned.Elements); + Assert.Equal(BindlessHeap.CallRecordNullIndex, spanned.Words[^1]); + } + + [Fact] + public void SpansAreOnUnlessConfigured() + { + if (Environment.GetEnvironmentVariable("SHARPEMU_CALL_RECORD_SPANS") is not null) return; + Assert.Equal(Mode.On, VulkanVideoPresenter.CallRecordSpans); + } +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/DeferredSignalHarness.cs b/tests/SharpEmu.Libs.Tests/VideoOut/DeferredSignalHarness.cs index b6f855c46..915fe66bf 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/DeferredSignalHarness.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/DeferredSignalHarness.cs @@ -43,6 +43,14 @@ internal DeferredSignalHarness() internal void Set(string name, object value) => PresenterUnderTest.PresenterType .GetField(name, PresenterUnderTest.InstanceMembers)!.SetValue(Presenter, value); + internal object? Get(string name) => PresenterUnderTest.PresenterType + .GetField(name, PresenterUnderTest.InstanceMembers)!.GetValue(Presenter); + + // The presenter's label publication path, as a GPU completion runs it. + internal void PublishDeferredSignal(PendingGuestPublications.Entry entry) => PresenterUnderTest.PresenterType + .GetMethod("PublishDeferredSignal", PresenterUnderTest.InstanceMembers)! + .Invoke(Presenter, [entry, false, (Action)(static () => { })]); + internal PendingGuestPublications.Entry AddDump(ulong count = 37) { var entry = Pending.Add(0, StreamRunner.DataAddress, 8); diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/DeferredSignalPublicationTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/DeferredSignalPublicationTests.cs index f5092aaf1..46e210c86 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/DeferredSignalPublicationTests.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/DeferredSignalPublicationTests.cs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: GPL-2.0-or-later using SharpEmu.Libs.Gpu.GpuCommands; +using SharpEmu.Libs.Gpu.Scheduling; using SharpEmu.Libs.Tests.Gpu.GpuCommands; using SharpEmu.Libs.Tests.Gpu.Scheduling; using Xunit; @@ -233,20 +234,25 @@ private static void PublishAll(DeferredSignalHarness harness) harness.Scheduler.RunCompletedOperations(); } - [Fact] - public void WriteAfterForeignLabelWaitIsHeldUntilTheLabelPublishes() + [Theory] + [InlineData(true)] + [InlineData(false)] + public void WriteAfterForeignLabelWaitIsHeldUntilTheLabelPublishes(bool forward) { var (harness, graphics, compute) = CrossQueueWindow(); using var owner = harness; + harness.Pending.ForwardHeldWrites = forward; var flag = StreamRunner.LabelAddress + 0x200; Assert.Equal(SubmissionProgress.Complete, compute.Run( StreamRunner.Packet(PacketOpcode.WriteData, 0x00000500u, StreamRunner.Low(flag), StreamRunner.High(flag), 5))); Assert.Equal(0u, graphics.Host.ReadDword(flag)); Assert.True(harness.Pending.HasQueue(33)); - // A later wait on the held-back value must not read the old memory. + // A later wait on the held-back value never reads the old memory: it takes the held value, or without + // forwarding waits for the publication. The CPU reads the old memory until the publication either way. var wait = StreamRunner.Packet(PacketOpcode.WaitRegisterMemory, 0x13, StreamRunner.Low(flag), StreamRunner.High(flag), 5, uint.MaxValue, 0); - Assert.Equal(SubmissionProgress.Blocked, compute.Run(wait)); + Assert.Equal(forward ? SubmissionProgress.Complete : SubmissionProgress.Blocked, compute.Run(wait)); + Assert.Equal(0u, graphics.Host.ReadDword(flag)); PublishAll(harness); Assert.Equal(1u, graphics.Host.ReadDword(StreamRunner.LabelAddress)); Assert.Equal(5u, graphics.Host.ReadDword(flag)); @@ -255,6 +261,28 @@ public void WriteAfterForeignLabelWaitIsHeldUntilTheLabelPublishes() Assert.Equal(0, harness.Pending.Count); } + // Another queue takes a held write's value at once and keeps its own later write behind it: the CPU sees neither + // before the foreign label publishes, then both. + [Fact] + public void ForeignWaitTakesHeldWriteAndHoldsItsOwnWriteBehindIt() + { + var (harness, graphics, compute) = CrossQueueWindow(); + using var owner = harness; + var flag = StreamRunner.LabelAddress + 0x200; + var reply = StreamRunner.LabelAddress + 0x280; + Assert.Equal(SubmissionProgress.Complete, compute.Run( + StreamRunner.Packet(PacketOpcode.WriteData, 0x00000500u, StreamRunner.Low(flag), StreamRunner.High(flag), 5))); + Assert.Equal(SubmissionProgress.Complete, graphics.Run( + StreamRunner.Packet(PacketOpcode.WaitRegisterMemory, 0x13, StreamRunner.Low(flag), StreamRunner.High(flag), 5, uint.MaxValue, 0), + StreamRunner.Packet(PacketOpcode.WriteData, 0x00000500u, StreamRunner.Low(reply), StreamRunner.High(reply), 9))); + Assert.Equal(0u, graphics.Host.ReadDword(flag)); + Assert.Equal(0u, graphics.Host.ReadDword(reply)); + PublishAll(harness); + Assert.Equal(5u, graphics.Host.ReadDword(flag)); + Assert.Equal(9u, graphics.Host.ReadDword(reply)); + Assert.Equal(0, harness.Pending.Count); + } + [Fact] public void ReadModifyWriteAfterForeignLabelWaitSuspendsUntilTheLabelPublishes() { @@ -371,4 +399,67 @@ public void CompletionDuringSuspendCannotLoseWakeup() runner.Host.WriteDword(StreamRunner.LabelAddress, 7); Assert.Equal(SliceResult.Completed, harness.Queue.ProcessOne()); } + + // A deferred label of queue 1 with nothing else pending in that queue. + private static PendingGuestPublications.Entry ForeignLabel(DeferredSignalHarness harness) + { + var ordering = harness.Pending.AddOrdering(1); + var label = harness.Pending.AddAfterPending(1, 0x6000, 8, 9)!; + harness.Pending.Publish(ordering, static () => { }); + return label; + } + + // A cross-queue window whose foreign label publishes between MustHoldForCrossQueueOrder's window check and its wake + // arm. A later entry keeps the foreign queue pending, so the publication saw no armed wake and woke nobody; the method + // must not report a hold that nothing will wake. + [Fact] + public void ACrossQueueWindowCompletedBeforeTheArmIsNotHeld() + { + using var harness = new DeferredSignalHarness(); + var foreign = ForeignLabel(harness); + _ = harness.Pending.AddAfterPending(1, 0x6008, 4, 1); + harness.Set("_crossQueueWindows", new Dictionary { [0] = foreign }); + harness.Set("CrossQueueHoldCheckedForTest", (Action)(() => harness.PublishDeferredSignal(foreign))); + var held = ((ICommandStreamHost)harness.Presenter).MustHoldForCrossQueueOrder(0); + Assert.True(foreign.Completed); + Assert.True(harness.Pending.HasQueue(1)); + Assert.False(held); + } + + // A window whose foreign label is still pending holds the queue and arms the wake its publication will take. + [Fact] + public void APendingCrossQueueWindowHoldsAndArmsItsWake() + { + using var harness = new DeferredSignalHarness(); + var foreign = ForeignLabel(harness); + harness.Set("_crossQueueWindows", new Dictionary { [0] = foreign }); + Assert.True(((ICommandStreamHost)harness.Presenter).MustHoldForCrossQueueOrder(0)); + Assert.Equal(1, (int)harness.Get("_partialLabelReadBlocked")!); + } + + // A window whose foreign label already published holds nothing and arms nothing. + [Fact] + public void ACompletedCrossQueueWindowIsNotHeld() + { + using var harness = new DeferredSignalHarness(); + var foreign = ForeignLabel(harness); + harness.Set("_crossQueueWindows", new Dictionary { [0] = foreign }); + harness.PublishDeferredSignal(foreign); + Assert.False(((ICommandStreamHost)harness.Presenter).MustHoldForCrossQueueOrder(0)); + Assert.Equal(0, (int)harness.Get("_partialLabelReadBlocked")!); + } + + // A publication after the arm takes the armed wake, even while a later entry keeps its queue pending. + [Fact] + public void APublicationAfterTheArmTakesTheWake() + { + using var harness = new DeferredSignalHarness(); + var foreign = ForeignLabel(harness); + _ = harness.Pending.AddAfterPending(1, 0x6008, 4, 1); + harness.Set("_crossQueueWindows", new Dictionary { [0] = foreign }); + Assert.True(((ICommandStreamHost)harness.Presenter).MustHoldForCrossQueueOrder(0)); + harness.PublishDeferredSignal(foreign); + Assert.True(foreign.Completed); + Assert.Equal(0, (int)harness.Get("_partialLabelReadBlocked")!); + } } diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/DriverShaderCacheFolderTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/DriverShaderCacheFolderTests.cs new file mode 100644 index 000000000..1ee90a21f --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/DriverShaderCacheFolderTests.cs @@ -0,0 +1,25 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.VideoOut; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +public sealed class DriverShaderCacheFolderTests +{ + [Fact] + public void TheGameFolderIsGivenByDefaultUnlessSwitchedOffOrAPathIsSet() + { + Assert.Equal("cache/seed.bin.driver", DriverShaderCacheFolder.Resolve(null, null, "cache/seed.bin")); + Assert.Equal("cache/seed.bin.driver", DriverShaderCacheFolder.Resolve("1", "", "cache/seed.bin")); + Assert.Null(DriverShaderCacheFolder.Resolve("0", null, "cache/seed.bin")); + // A path the user or a runner set is kept. + Assert.Null(DriverShaderCacheFolder.Resolve(null, "elsewhere", "cache/seed.bin")); + } + + [Fact] + public void TheSwitchDoesNotChangeTranslationKeys() => + Assert.True(TranslationDiskCache.IgnoredVariable("SHARPEMU_DRIVER_CACHE_FOLDER")); +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/ForwardedWaitTransferTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/ForwardedWaitTransferTests.cs new file mode 100644 index 000000000..a6f7247e2 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/ForwardedWaitTransferTests.cs @@ -0,0 +1,69 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.GpuCommands; +using SharpEmu.Libs.Tests.Gpu.GpuCommands; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +[Collection(SchedulingStateCollection.Name)] +public sealed class ForwardedWaitTransferTests +{ + [Theory] + [InlineData(0, 0)] + [InlineData(0, 1)] + [InlineData(0, 2)] + [InlineData(0, 3)] + [InlineData(34, 0)] + [InlineData(34, 1)] + [InlineData(34, 2)] + [InlineData(34, 3)] + public void TransferAfterForwardedHeldWriteWaitsBeforeTouchingDisjointMemory(int readerQueue, int operation) + { + using var harness = new DeferredSignalHarness(); + harness.Pending.ForwardHeldWrites = true; + harness.AddDump(); + harness.Scheduler.Flush(); + var graphics = harness.Runner; + var writer = new StreamRunner(33, graphics.Host); + var reader = new StreamRunner(readerQueue, graphics.Host); + var label = StreamRunner.LabelAddress; + var flag = label + 0x200; + var source = label + 0x300; + var destination = label + 0x400; + graphics.Host.WriteDword(source, 7); + Assert.Equal(SubmissionProgress.Complete, graphics.Run(StreamRunner.Packet(PacketOpcode.ReleaseMemory, + 0x528, 1u << 29, StreamRunner.Low(label), StreamRunner.High(label), 1, 0, 0))); + Assert.Equal(SubmissionProgress.Complete, writer.Run(Wait(label, 1), + StreamRunner.Packet(PacketOpcode.WriteData, 0x500, StreamRunner.Low(flag), StreamRunner.High(flag), 5))); + Assert.Equal(SubmissionProgress.Complete, reader.Run(Wait(flag, 5))); + Assert.Equal(0u, graphics.Host.ReadDword(flag)); + + var immediate = operation is 0 or 3; + var input = immediate ? 9UL : source; + var transfer = operation < 2 + ? StreamRunner.Packet(PacketOpcode.DmaData, immediate ? 2u << 29 : 0u, + StreamRunner.Low(input), StreamRunner.High(input), StreamRunner.Low(destination), StreamRunner.High(destination), 4) + : StreamRunner.Packet(PacketOpcode.CopyData, 0x100u | (immediate ? 5u : 1u), + StreamRunner.Low(input), StreamRunner.High(input), StreamRunner.Low(destination), StreamRunner.High(destination)); + + Assert.Equal(SubmissionProgress.Blocked, reader.Run(transfer)); + Assert.Equal(0u, graphics.Host.ReadDword(destination)); + Assert.DoesNotContain(graphics.Host.Calls, IsTransfer); + + harness.Scheduler.Flush(); + harness.Device.Complete(harness.Scheduler.CurrentTick); + harness.Scheduler.RunCompletedOperations(); + Assert.Equal(5u, graphics.Host.ReadDword(flag)); + Assert.Equal(SubmissionProgress.Complete, reader.Run()); + Assert.Equal(immediate ? 9u : 7u, graphics.Host.ReadDword(destination)); + Assert.Single(graphics.Host.Calls.Where(IsTransfer)); + Assert.Equal(0, harness.Pending.Count); + } + + private static bool IsTransfer(string call) => call.StartsWith("copy ") || call.StartsWith("fill "); + private static uint[] Wait(ulong address, uint value) => StreamRunner.Packet(PacketOpcode.WaitRegisterMemory, + 0x13, StreamRunner.Low(address), StreamRunner.High(address), value, uint.MaxValue, 0); +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/LinkedCompileAdmissionTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/LinkedCompileAdmissionTests.cs new file mode 100644 index 000000000..a9234b7b4 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/LinkedCompileAdmissionTests.cs @@ -0,0 +1,69 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.VideoOut; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +// Linked compiles share the free commit: small ones run beside a large one, large ones one at a time. +public sealed class LinkedCompileAdmissionTests +{ + private const long GiB = 1L << 30; + private const long MiB = 1L << 20; + + // A 19 MB module (13 GB estimated) and a 0.5 MB one (0.3 GB), with 40 GB free. + [Fact] + public void ASmallCompileRunsBesideALargeOne() + { + var admission = new LinkedCompileAdmission(() => 40 * GiB); + Assert.True(admission.TryAdmit(19 * MiB, out _, out _)); + Assert.True(admission.TryAdmit(MiB / 2, out _, out var reserved)); + Assert.Equal(LinkedCompileAdmission.Estimate(19 * MiB), reserved); + } + + [Fact] + public void ALargeCompileWaitsWhileAnotherLargeOneRuns() + { + var admission = new LinkedCompileAdmission(() => 400 * GiB); + Assert.True(admission.TryAdmit(19 * MiB, out _, out _)); + Assert.False(admission.TryAdmit(8 * MiB, out _, out _)); + admission.Release(19 * MiB); + Assert.True(admission.TryAdmit(8 * MiB, out _, out _)); + } + + // The estimates of the running compiles count as committed: 17.5 GB free less the large compile's 13 GB leaves too + // little for a 2 MB compile (1.4 GB) and the 4 GB margin, until the large compile ends. + [Fact] + public void TheRunningEstimatesCountAgainstTheFreeCommit() + { + var admission = new LinkedCompileAdmission(() => 35 * GiB / 2); + Assert.True(admission.TryAdmit(19 * MiB, out _, out _)); + Assert.False(admission.TryAdmit(2 * MiB, out var available, out var reserved)); + Assert.Equal(35 * GiB / 2, available); + Assert.Equal(LinkedCompileAdmission.Estimate(19 * MiB), reserved); + admission.Release(19 * MiB); + Assert.True(admission.TryAdmit(2 * MiB, out _, out _)); + } + + [Fact] + public void ACompileWaitsUntilTheFreeCommitHoldsItsEstimateAndTheMargin() + { + var free = 5 * GiB; + var admission = new LinkedCompileAdmission(() => free); + Assert.False(admission.TryAdmit(2 * MiB, out _, out _)); + free = 6 * GiB; + Assert.True(admission.TryAdmit(2 * MiB, out _, out _)); + } + + // With the free commit unknown, one compile runs at a time. + [Fact] + public void WithoutTheFreeCommitOneCompileRunsAtATime() + { + var admission = new LinkedCompileAdmission(() => -1); + Assert.True(admission.TryAdmit(MiB, out _, out _)); + Assert.False(admission.TryAdmit(MiB, out _, out _)); + admission.Release(MiB); + Assert.True(admission.TryAdmit(MiB, out _, out _)); + } +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/PipelineBinaryStorePolicyTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/PipelineBinaryStorePolicyTests.cs new file mode 100644 index 000000000..6684a83f9 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/PipelineBinaryStorePolicyTests.cs @@ -0,0 +1,34 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.VideoOut; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +public sealed class PipelineBinaryStorePolicyTests +{ + [Fact] + public void UnsetStoresEveryBuildOf20MillisecondsOrMore() + { + Assert.Equal(20, PipelineBinaryStorePolicy.DefaultMilliseconds); + Assert.Equal(PipelineBinaryStorePolicy.DefaultMilliseconds, PipelineBinaryStorePolicy.Parse(null)); + Assert.Equal(PipelineBinaryStorePolicy.DefaultMilliseconds, PipelineBinaryStorePolicy.Parse("")); + } + + [Theory] + [InlineData("20", 20)] + [InlineData("0", 0)] + [InlineData("12.5", 12.5)] + public void ANumberOfMillisecondsBecomesTheThreshold(string value, double expected) => + Assert.Equal(expected, PipelineBinaryStorePolicy.Parse(value)); + + [Theory] + [InlineData("-5")] + [InlineData("abc")] + [InlineData("NaN")] + [InlineData("Infinity")] + [InlineData("1,5")] + public void AnythingElseKeepsTheDefault(string value) => + Assert.Equal(PipelineBinaryStorePolicy.DefaultMilliseconds, PipelineBinaryStorePolicy.Parse(value)); +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/PipelineBuildGateTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/PipelineBuildGateTests.cs new file mode 100644 index 000000000..63a363702 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/PipelineBuildGateTests.cs @@ -0,0 +1,79 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.VideoOut; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +// One build of a pipeline key at a time. +public sealed class PipelineBuildGateTests +{ + [Fact] + public void ASecondCreationOfAKeyWaitsForTheFirstBuild() + { + var gate = new PipelineBuildGate(); + var first = gate.Begin("key"); + Task second; + try + { + second = Task.Factory.StartNew(() => gate.Begin("key"), TaskCreationOptions.LongRunning); + Assert.False(second.Wait(200)); + } + finally + { + gate.Finish(first); + } + + Assert.True(second.Wait(5000)); + gate.Finish(second.Result); + } + + [Fact] + public void OtherKeysBuildSideBySide() + { + var gate = new PipelineBuildGate(); + var first = gate.Begin("first"); + var second = Task.Factory.StartNew(() => gate.Begin("second"), TaskCreationOptions.LongRunning); + Assert.True(second.Wait(5000)); + gate.Finish(second.Result); + gate.Finish(first); + } + + [Fact] + public void AWaiterLendsALowerPriorityBuilderItsPriorityUntilTheBuildEnds() + { + var gate = new PipelineBuildGate(); + using var registered = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + var after = ThreadPriority.Highest; + var builder = new Thread(() => + { + var build = gate.Begin("key"); + registered.Set(); + release.Wait(); + gate.Finish(build); + after = Thread.CurrentThread.Priority; + }) + { + Priority = ThreadPriority.BelowNormal, + }; + builder.Start(); + try + { + registered.Wait(); + var waiter = Task.Factory.StartNew(() => gate.Begin("key"), TaskCreationOptions.LongRunning); + Assert.True(SpinWait.SpinUntil(() => builder.Priority == ThreadPriority.Normal, 5000)); + release.Set(); + builder.Join(); + Assert.Equal(ThreadPriority.BelowNormal, after); + Assert.True(waiter.Wait(5000)); + gate.Finish(waiter.Result); + } + finally + { + release.Set(); + builder.Join(); + } + } +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/PresenterImageBindingTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/PresenterImageBindingTests.cs index 4aeb90290..199c60f9a 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/PresenterImageBindingTests.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/PresenterImageBindingTests.cs @@ -830,6 +830,116 @@ public void TargetSampledByItsOwnDraw_BindsTheTargetAsATexture() harness.Shutdown(); } + public enum StageBindingPattern + { + StorageThenSampled, + SampledThenStorage, + SampledTarget, + SampledOnly, + } + + [Theory] + [InlineData(false, StageBindingPattern.StorageThenSampled)] + [InlineData(true, StageBindingPattern.StorageThenSampled)] + [InlineData(false, StageBindingPattern.SampledThenStorage)] + [InlineData(true, StageBindingPattern.SampledThenStorage)] + [InlineData(false, StageBindingPattern.SampledTarget)] + [InlineData(true, StageBindingPattern.SampledTarget)] + [InlineData(false, StageBindingPattern.SampledOnly)] + [InlineData(true, StageBindingPattern.SampledOnly)] + public void StageTextureTransitions_UseCurrentRecordingBindings(bool worker, StageBindingPattern pattern) + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var presenter = new PresenterUnderTest(_vulkan); + var address = presenter.Harness.MapBacked(0x10000, ReadWrite); + + presenter.Run(() => + { + var acquired = AcquireTexture(presenter, Texture(address)); + var identifier = (ResourceSlotIdentifier)GetFieldValue(acquired, "ImageIdentifier"); + var image = (CachedImage)GetFieldValue(acquired, "CachedImage"); + var request = (ImageRequest)GetFieldValue(acquired, "Request"); + presenter.InvokeMethod("ResetImageBindings"); + image.Transition(ImageAccessState.GuestStorageAccess, null, presenter.Command); + + var previousWorker = presenter.GetField("_worker"); + var previousBuffer = presenter.GetField("_workerBuffer"); + var previousHazards = presenter.GetField("_hazards"); + var hazards = new SliceHazards(); + var shared = worker && pattern == StageBindingPattern.SampledOnly + ? new ImageBindingState { IsBound = true, IsTarget = true, ForceGeneral = true, ShaderWrite = true } + : default; + image.Binding = shared; + try + { + if (worker) + { + presenter.SetField("_workerBuffer", presenter.Harness.Scheduler.Current); + presenter.SetField("_hazards", hazards); + presenter.SetField("_worker", true); + } + + var uses = pattern switch + { + StageBindingPattern.StorageThenSampled => new[] { true, false }, + StageBindingPattern.SampledThenStorage => new[] { false, true }, + _ => new[] { false }, + }; + var bindings = Array.CreateInstance(TextureResourceType, uses.Length); + for (var index = 0; index < uses.Length; index++) + { + presenter.InvokeMethod("BindImage", identifier, uses[index]); + var binding = Activator.CreateInstance(TextureResourceType, true)!; + TextureResourceType.GetField("CachedImage")!.SetValue(binding, image); + TextureResourceType.GetField("ImageIdentifier")!.SetValue(binding, identifier); + TextureResourceType.GetField("Request")!.SetValue(binding, request); + TextureResourceType.GetField("IsStorage")!.SetValue(binding, uses[index]); + bindings.SetValue(binding, index); + } + + if (pattern == StageBindingPattern.SampledTarget) + { + presenter.InvokeMethod("BindRenderTarget", identifier); + } + + // Exercise the stage path used by PushDescriptors, not the older draw-texture helper. + presenter.InvokeMethod("RecordStageTextureTransitions", bindings); + if (worker) + { + Assert.Equal(shared, image.Binding); + } + presenter.InvokeMethod("ResetImageBindings"); + + // A subsequent read must still wait for writes from any binding in the previous stage. + var view = request.View; + var barriers = worker + ? hazards.Transition(image, AccessFlags.ShaderReadBit, PipelineStageFlags.FragmentShaderBit, out _) + : image.GetBarriers(AccessFlags.ShaderReadBit, PipelineStageFlags.FragmentShaderBit, + new SubresourceRange(view.BaseLevel, view.LevelCount, view.BaseLayer, view.LayerCount)).Barriers; + if (pattern == StageBindingPattern.SampledOnly) + { + Assert.Empty(barriers); + } + else + { + var expectedWrite = pattern == StageBindingPattern.SampledTarget + ? AccessFlags2.ColorAttachmentWriteBit : AccessFlags2.ShaderWriteBit; + var barrier = Assert.Single(barriers); + Assert.Equal(expectedWrite, barrier.SrcAccessMask & expectedWrite); + Assert.Equal(AccessFlags2.ShaderReadBit, barrier.DstAccessMask & AccessFlags2.ShaderReadBit); + } + } + finally + { + presenter.InvokeMethod("ResetImageBindings"); + presenter.SetField("_worker", previousWorker); + presenter.SetField("_workerBuffer", previousBuffer!); + presenter.SetField("_hazards", previousHazards!); + image.Binding = default; + } + }); + } + [Fact] public void DepthTarget_AcquiresAViewWithoutAClear() { diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/PresenterUnderTest.cs b/tests/SharpEmu.Libs.Tests/VideoOut/PresenterUnderTest.cs index e1849bbbe..e35496945 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/PresenterUnderTest.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/PresenterUnderTest.cs @@ -88,13 +88,15 @@ public PresenterUnderTest(HeadlessVulkan vulkan, bool startScheduler = true) "_batchResources", "_batchRetireBuffers", "_pendingGuestSubmissions", "_deferredGuestImageVersionDestroys", "_pipelineEntries", "_shaderModules", "_shaderModuleSpirvBytes", "_rectangleStageCode", + "_sharedPipelineBinaries", "_pipelineBuilds", "_pendingGraphicsPipelines", "_graphicsLibraries", "_graphicsLibraryLock", + "_graphicsLibraryCompiles", "_earlyPixelLibraryTasks", "_pendingComputePipelines", "_prewarmedComputePipelines", }) { var field = PresenterType.GetField(name, InstanceMembers)!; field.SetValue(Instance, Activator.CreateInstance(field.FieldType, nonPublic: true)); } - SetField("_shaderModuleCacheIdentities", new Dictionary()); + SetField("_shaderModuleCacheIdentities", new System.Collections.Concurrent.ConcurrentDictionary()); var cacheShards = PresenterType.GetField("_pipelineCacheShards", InstanceMembers)!; cacheShards.SetValue(Instance, Activator.CreateInstance(cacheShards.FieldType, nonPublic: true)); forwarder.Target = this; diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/PrewarmPoolTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/PrewarmPoolTests.cs new file mode 100644 index 000000000..3630e28bd --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/PrewarmPoolTests.cs @@ -0,0 +1,176 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections.Concurrent; +using SharpEmu.Libs.VideoOut; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +// The prewarm's threads serve both lanes, the item that must start first first, and each lane finishes once. +public sealed class PrewarmPoolTests +{ + // A lane over named items with their starts; it logs each item it runs and counts its finishes. + private sealed class TestLane(string name, ConcurrentQueue log, params float[] starts) + { + private readonly ConcurrentQueue _items = new(starts); + private readonly int _total = starts.Length; + + public int Finishes; + public bool EmptyWhenFinished = true; + + public PrewarmPool.Lane Lane => new(_total, + (out float start) => _items.TryPeek(out start), + _ => + { + if (!_items.TryDequeue(out var start)) + { + return false; + } + + log.Enqueue($"{name}{start}"); + return true; + }, + () => + { + EmptyWhenFinished &= _items.IsEmpty; + Interlocked.Increment(ref Finishes); + }); + } + + [Fact] + public void AWorkerRunsTheItemThatMustStartFirst() + { + var log = new ConcurrentQueue(); + var compute = new TestLane("c", log, 0, 5, 10); + var graphics = new TestLane("g", log, 3, 4, 20); + var pool = new PrewarmPool(static () => false); + // One thread, which begins at Start and so sees both lanes from its first turn. + pool.Add(graphics.Lane, 1, "test graphics"); + pool.Add(compute.Lane, 0, "test compute"); + pool.Start(); + pool.Stop(); + Assert.Equal(new[] { "c0", "g3", "g4", "c5", "c10", "g20" }, log); + Assert.Equal(1, compute.Finishes); + Assert.Equal(1, graphics.Finishes); + Assert.True(compute.EmptyWhenFinished && graphics.EmptyWhenFinished); + } + + // The threads added with one lane serve the other once theirs is empty. + [Fact] + public void ALanesThreadsServeTheOtherLane() + { + var log = new ConcurrentQueue(); + var compute = new TestLane("c", log, Enumerable.Range(0, 50).Select(static index => (float)index).ToArray()); + var graphics = new TestLane("g", log, 100); + var pool = new PrewarmPool(static () => false); + pool.Add(compute.Lane, 0, "test compute"); + pool.Add(graphics.Lane, 3, "test graphics"); + pool.Start(); + pool.Stop(); + Assert.Equal(51, log.Count); + Assert.Contains("g100", log); + Assert.Equal(1, compute.Finishes); + Assert.Equal(1, graphics.Finishes); + Assert.True(compute.EmptyWhenFinished && graphics.EmptyWhenFinished); + } + + // A lane whose items wait on a busy caller lets the other lane run; it waits for the caller only when the other is empty. + [Fact] + public void ALaneThatMustWaitLetsTheOtherRun() + { + var log = new ConcurrentQueue(); + var released = false; + var waits = 0; + var blocked = new PrewarmPool.Lane(1, + (out float start) => + { + start = 0; + return !Volatile.Read(ref released) || log.All(static entry => entry != "blocked"); + }, + mayWait => + { + if (!mayWait) + { + return false; + } + + Interlocked.Increment(ref waits); + Volatile.Write(ref released, true); + log.Enqueue("blocked"); + return true; + }, + static () => { }); + var other = new TestLane("g", log, 1, 2); + var pool = new PrewarmPool(static () => false); + pool.Add(blocked, 0, "test blocked"); + pool.Add(other.Lane, 1, "test other"); + pool.Start(); + pool.Stop(); + Assert.Equal(new[] { "g1", "g2", "blocked" }, log); + Assert.Equal(1, waits); + } + + // Stopping ends the threads before the lanes' last items; Stop then finishes those lanes once, also for a pool that never + // started. + [Fact] + public void StopFinishesTheLanesItStoppedBefore() + { + var never = 0; + var unstarted = new PrewarmPool(static () => false); + unstarted.Add(new PrewarmPool.Lane(1, (out float start) => { start = 0; return true; }, static _ => true, + () => Interlocked.Increment(ref never)), 2, "test unstarted"); + unstarted.Stop(); + Assert.Equal(1, never); + + var log = new ConcurrentQueue(); + var compute = new TestLane("c", log); + var finished = 0; + var pool = new PrewarmPool(static () => true); + var unfinished = new PrewarmPool.Lane(1, (out float start) => { start = 0; return true; }, static _ => true, + () => Interlocked.Increment(ref finished)); + pool.Add(unfinished, 2, "test unfinished"); + pool.Add(compute.Lane, 0, "test compute"); + pool.Start(); + pool.Stop(); + pool.Stop(); + Assert.Equal(1, finished); + Assert.Equal(1, compute.Finishes); + Assert.Empty(log); + } + + // A queue looks empty while a worker puts a busy caller's record back, so a lane finishes on the run of its last + // item, not when its queue looks empty with no run in progress. + [Fact] + public void ALaneFinishesOnItsLastItemNotWhenItsQueueLooksEmpty() + { + var finishes = 0; + var queued = 1; + var lane = new PrewarmPool.Lane(2, + (out float start) => + { + start = 0; + return queued > 0; + }, + _ => + { + if (queued == 0) + { + return false; + } + + queued--; + return true; + }, + () => finishes++); + Assert.True(lane.Run(mayWait: false)); + // The second item is out of the queue while a worker puts it back: the lane looks empty, with no run in progress. + Assert.False(lane.TryPeek(out _)); + Assert.False(lane.Run(mayWait: false)); + Assert.Equal(0, finishes); + queued = 1; + Assert.True(lane.Run(mayWait: false)); + Assert.Equal(1, finishes); + Assert.True(lane.Done); + } +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.BufferLifetime.cs b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.BufferLifetime.cs new file mode 100644 index 000000000..9a9120b04 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.BufferLifetime.cs @@ -0,0 +1,150 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Gpu.Images; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Gpu.Scheduling; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.ShaderCompiler.Resources; +using Silk.NET.Vulkan; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Images.ImageCacheTestSupport; + +namespace SharpEmu.Libs.Tests.VideoOut; + +public sealed unsafe partial class RenderHostDeviceTests +{ + [Theory] + [InlineData(ShaderStageKind.Vertex)] + [InlineData(ShaderStageKind.Pixel)] + [InlineData(ShaderStageKind.Compute)] + public void BindResources_ImageUploadKeepsTheStorageViewOnTheCurrentOwner(ShaderStageKind stage) + { + if (!Ready()) return; + using var presenter = new PresenterUnderTest(_vulkan!); + using var fatal = new FatalScope(); + presenter.SetField("_minStorageBufferOffsetAlignment", 256UL); + presenter.LoadRenderingCommands(); + var harness = presenter.Harness; + var address = harness.MapBacked(0x20000, ReadWrite); + var sampled = RegisterWords.Texture(address, GuestPixelFormat.Bits8_8_8_8UNorm, 128, 128); + var info = new ShaderResourceInfo + { + Buffers = [new BufferResource { Read = true, MaxByteExtent = 32 }], + Images = [new ImageResource + { + Dimension = ImageDimension.Dim2D, + ResourceClass = global::SharpEmu.ShaderCompiler.Resources.ImageResourceClass.Sampled, + NumericClass = ImageNumericClass.Float, + Read = true, + }], + }; + var snapshot = new ResourceSnapshot + { + Buffers = [[(uint)address, (uint)(address >> 32), 32, 0]], + Images = [sampled], + }; + var program = FixedProgramProvider.EmptyProgram(stage, 0x188, info); + presenter.Run(() => + { + // One small persistent GPU-written owner overlaps a larger texture. + var (original, offset) = harness.Cache.ObtainBuffer(address, 32, isWritten: true); + original.Fill(offset, 32, 0x11223344); + var texture = ImageRequestBuilders.Texture(sampled, + new ShaderImageShape(false, false, false, false, TextureNumericClass.Float)).Request; + Assert.True(texture.Description.Data.Size > original.Size); + using var preparation = presenter.RenderHost.BeginPreparation(); + var prepared = presenter.RenderHost.PrepareBindings(new ShaderStageResources(program, snapshot)); + presenter.RenderHost.BindResources(prepared); + var current = harness.Cache.GetBuffer(harness.Cache.FindBuffer(address, 32)); + Assert.NotSame(original, current); + // Inspect metadata only: never submit a shader with a known stale handle. + Assert.Equal(current.Handle.Handle, PreparedStorageHandle(prepared, 0)); + }); + harness.Finish(); + harness.Shutdown(); + } + + [Fact] + public void Preparation_AcquiredNativeBufferSurvivesALaterResourcePublicationWait() + { + if (!Ready()) return; + using var presenter = new PresenterUnderTest(_vulkan!); + using var fatal = new FatalScope(); + presenter.LoadRenderingCommands(); + var harness = presenter.Harness; + var address = harness.MapBacked(0x20000, ReadWrite); + presenter.Run(() => + { + var pending = presenter.GetField("_guestPublications"); + var publicationAddress = address + 0x18000; + var publication = pending.AddWrite(33, publicationAddress, 4); + pending.Register(publication, harness.Scheduler.CurrentTick); + harness.Scheduler.QueueMemoryPublication(() => pending.Publish(publication, () => + Assert.True(harness.Memory.TryWrite(publicationAddress, BitConverter.GetBytes(0xAABBCCDDu))))); + using var preparation = presenter.RenderHost.BeginPreparation(); + _ = presenter.RenderHost.ObtainBuffer(address, 32, isWritten: true); + var original = harness.Cache.GetBuffer(harness.Cache.FindBuffer(address, 32)); + var capturedHandle = original.Handle.Handle; + var replacement = harness.Cache.GetBuffer(harness.Cache.FindBuffer(address, 0x10000)); + Assert.NotSame(original, replacement); + // The next resource completes its held write through the normal host path. + // This submits the unregister tick and runs its retirement callback. + _ = presenter.RenderHost.ObtainBuffer(publicationAddress, 4, isWritten: false); + Assert.Equal(0, pending.Count); + Assert.Equal(capturedHandle, original.Handle.Handle); + }); + harness.Finish(); + harness.Shutdown(); + } + + [Fact] + public void RetainingAnOldOwnerDoesNotForwardLaterWritesToItsReplacement() + { + if (!Ready()) return; + using var presenter = new PresenterUnderTest(_vulkan!); + using var fatal = new FatalScope(); + presenter.LoadRenderingCommands(); + var harness = presenter.Harness; + var address = harness.MapBacked(0x20000, ReadWrite); + var original = presenter.Run(() => + { + var (buffer, offset) = harness.Cache.ObtainBuffer(address, 32, isWritten: true); + buffer.Fill(offset, 32, 0x11223344); + buffer.RetainForeignRead(); + return buffer; + }); + try + { + var replacement = presenter.Run(() => + { + var current = harness.Cache.GetBuffer(harness.Cache.FindBuffer(address, 0x10000)); + Assert.NotSame(original, current); + // The earlier native binding still names original, after the merge copy. + // Fill stands in for its late GPU write without needing a shader module. + original.Fill(original.Offset(address), 4, 0x55667788); + harness.Scheduler.Finish(); + Assert.NotEqual(0UL, original.Handle.Handle); + return current; + }); + Assert.Equal(0x55667788u, BitConverter.ToUInt32(harness.ReadBack(original, original.Offset(address), 4))); + Assert.Equal(0x11223344u, BitConverter.ToUInt32(harness.ReadBack(replacement, replacement.Offset(address), 4))); + } + finally + { + presenter.Run(original.ReleaseForeignRead); + } + harness.Shutdown(); + } + + private static ulong PreparedStorageHandle(IPreparedBindings prepared, int slot) + { + const System.Reflection.BindingFlags members = PresenterUnderTest.InstanceMembers; + var descriptors = prepared.GetType().GetProperty("Descriptors", members)!.GetValue(prepared)!; + var views = (Array)descriptors.GetType().GetField("Buffers", members)!.GetValue(descriptors)!; + var view = views.GetValue(slot)!; + return ((Silk.NET.Vulkan.Buffer)view.GetType().GetProperty("Buffer", members)!.GetValue(view)!).Handle; + } +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.DeviceAddressRanges.cs b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.DeviceAddressRanges.cs new file mode 100644 index 000000000..dfda42057 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.DeviceAddressRanges.cs @@ -0,0 +1,54 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE.GpuMemory; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Images.ImageCacheTestSupport; +using ResourceSnapshot = SharpEmu.ShaderCompiler.Resources.ResourceSnapshot; + +namespace SharpEmu.Libs.Tests.VideoOut; + +public sealed unsafe partial class RenderHostDeviceTests +{ + [Fact] + public void AReusedStageCarriesNoCallRecordsOfThePreviousProgram() + { + if (!Ready()) return; + using var presenter = new PresenterUnderTest(_vulkan!); + presenter.LoadRenderingCommands(); + var harness = presenter.Harness; + GuestGpuMemoryHook.Attach(harness.Gpu); + try + { + var named = harness.MapBacked(0x10000, ReadWrite); + var program = FixedProgramProvider.EmptyProgram(ShaderStageKind.Compute, 0xCA11); + var stage = new ShaderStageResources(program, new ResourceSnapshot()); + presenter.Run(() => + { + // The pooled stage last served a program whose call records named a written range. + var used = presenter.InvokeMethod("RentStage", stage, program)!; + var type = used.GetType(); + type.GetProperty("CallRecordWords")!.SetValue(used, new uint[] { 1, 0, 0, 0 }); + type.GetProperty("CallRecordRanges")!.SetValue(used, new DeviceAddressRange[] { new(uint.MaxValue, named, 0x1000, true, true) }); + presenter.InvokeMethod("ReturnStageScratch", used); + + using var preparation = presenter.RenderHost.BeginPreparation(); + var prepared = presenter.RenderHost.PrepareBindings(stage); + Assert.Same(used, prepared); + Assert.Empty((uint[])type.GetProperty("CallRecordWords")!.GetValue(prepared)!); + Assert.Empty((DeviceAddressRange[])type.GetProperty("CallRecordRanges")!.GetValue(prepared)!); + presenter.RenderHost.BindResources(prepared); + Assert.False(harness.Cache.IsRegionRegistered(named, 0x1000)); + Assert.False(harness.Cache.HasGpuDirtyBytes(named, 0x1000)); + }); + } + finally + { + GuestGpuMemoryHook.Attach(null); + } + + harness.Shutdown(); + } +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.DispatchThreads.cs b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.DispatchThreads.cs new file mode 100644 index 000000000..2d8e84123 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.DispatchThreads.cs @@ -0,0 +1,94 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.InteropServices; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Gpu.Scheduling; +using SharpEmu.Libs.Tests.Gpu.Buffers; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.Libs.Tests.Gpu.Vulkan; +using Silk.NET.Vulkan; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +public sealed unsafe partial class RenderHostDeviceTests +{ + // Thread counts a shader wrote become groups of the program's size in the pipeline's axis order, clamped to the device's + // group limits, and the counts themselves become the program's thread limits; a zero count launches nothing. The + // arguments and the limits sit at unaligned words of their buffers. + [Theory] + [InlineData(100u, 1u, 1u, 64u, 1u, 1u, 0, 1, 2, true)] + [InlineData(300u, 40u, 2u, 8u, 4u, 2u, 2, 0, 1, true)] + [InlineData(64u, 64u, 1u, 64u, 1u, 1u, 1, 2, 0, false)] + [InlineData(0u, 5u, 1u, 64u, 1u, 1u, 0, 1, 2, true)] + [InlineData(4u, 0u, 1u, 1u, 1u, 1u, 0, 1, 2, false)] + [InlineData(uint.MaxValue, 1u, 1u, 1u, 1u, 1u, 0, 1, 2, true)] + public void GpuThreadCountsBecomeGroupsAndThreadLimits(uint threadsX, uint threadsY, uint threadsZ, uint sizeX, uint sizeY, + uint sizeZ, int axisX, int axisY, int axisZ, bool writesLimits) + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var worker = new CacheWorker(_vulkan); + worker.Run(() => + { + var scheduler = worker.Scheduler; + scheduler.Begin(new SubmissionContext { QueueName = "dispatch-threads.test", SubmissionId = 1 }); + using var arguments = new GpuBuffer(_vulkan.DeviceInfo, scheduler, GpuBufferUsage.DeviceLocal, 0, GpuBuffer.AllFlags, 64); + using var limits = new GpuBuffer(_vulkan.DeviceInfo, scheduler, GpuBufferUsage.DeviceLocal, 0, GpuBuffer.AllFlags, 64); + using var download = new GpuBuffer(_vulkan.DeviceInfo, scheduler, GpuBufferUsage.Download, 0, GpuBuffer.AllFlags, 128); + using var pipeline = new DispatchThreadsPipeline(_vulkan.DeviceInfo); + uint[] groupSize = [sizeX, sizeY, sizeZ]; + int[] axis = [axisX, axisY, axisZ]; + using var prepared = pipeline.Prepare(scheduler, new BufferBinding(arguments.Handle.Handle, 4), + writesLimits ? new BufferBinding(limits.Handle.Handle, 8) : null, groupSize, axis); + try + { + var command = new CommandBuffer(scheduler.Current.Handle); + uint* words = stackalloc uint[4] { 0xDEAD, threadsX, threadsY, threadsZ }; + _vulkan.Vk.CmdUpdateBuffer(command, arguments.Handle, 0, 16, words); + uint* sentinel = stackalloc uint[8] { 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7 }; + _vulkan.Vk.CmdUpdateBuffer(command, limits.Handle, 0, 32, sentinel); + prepared.Record(command); + var barrier = new MemoryBarrier + { + SType = StructureType.MemoryBarrier, SrcAccessMask = AccessFlags.ShaderWriteBit | AccessFlags.TransferWriteBit, + DstAccessMask = AccessFlags.TransferReadBit, + }; + _vulkan.Vk.CmdPipelineBarrier(command, PipelineStageFlags.ComputeShaderBit | PipelineStageFlags.TransferBit, + PipelineStageFlags.TransferBit, 0, 1, &barrier, 0, null, 0, null); + var groupsCopy = new BufferCopy(0, 0, 12); + _vulkan.Vk.CmdCopyBuffer(command, prepared.GroupsBuffer, download.Handle, 1, &groupsCopy); + var limitsCopy = new BufferCopy(0, 64, 32); + _vulkan.Vk.CmdCopyBuffer(command, limits.Handle, download.Handle, 1, &limitsCopy); + barrier.SrcAccessMask = AccessFlags.TransferWriteBit; + barrier.DstAccessMask = AccessFlags.HostReadBit; + _vulkan.Vk.CmdPipelineBarrier(command, PipelineStageFlags.TransferBit, + PipelineStageFlags.HostBit, 0, 1, &barrier, 0, null, 0, null); + scheduler.Finish(); + download.Invalidate(0, 128); + var result = MemoryMarshal.Cast(download.Mapped[..128]); + var maximum = _vulkan.DeviceInfo.MaxComputeWorkGroupCount; + uint[] physicalLimit = [maximum.X, maximum.Y, maximum.Z]; + uint[] threads = [threadsX, threadsY, threadsZ]; + var empty = threadsX == 0 || threadsY == 0 || threadsZ == 0; + for (var logical = 0; logical < 3; logical++) + { + var groups = Math.Min(RenderExecutor.GroupsFromThreads(threads[logical], groupSize[logical]), physicalLimit[axis[logical]]); + Assert.Equal(empty ? 0u : groups, result[axis[logical]]); + } + + uint[] expectedLimits = writesLimits + ? [0xA0, 0xA1, threadsX, threadsY, threadsZ, 0xA5, 0xA6, 0xA7] + : [0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7]; + Assert.Equal(expectedLimits, result.Slice(16, 8).ToArray()); + } + finally + { + scheduler.Finish(); + } + }); + _vulkan.AssertNoValidationMessages(); + } +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.GraphicsPrewarm.cs b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.GraphicsPrewarm.cs new file mode 100644 index 000000000..81619a602 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.GraphicsPrewarm.cs @@ -0,0 +1,135 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections.Concurrent; +using SharpEmu.HLE.GpuMemory; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.Libs.Tests.Gpu.Pipelines; +using Silk.NET.Vulkan; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Images.ImageCacheTestSupport; + +namespace SharpEmu.Libs.Tests.VideoOut; + +public sealed unsafe partial class RenderHostDeviceTests +{ + // A draw records the state its pre-rasterization part compiled with under its program's prewarm identity, and the + // graphics prewarm builds that part again from the recorded program and state. + [Fact] + public void ADrawRecordsItsPreRasterizationState_AndThePrewarmBuildsThatPartAgain() + { + if (!Ready() || !_vulkan.SupportsGraphicsPipelineLibrary) + { + return; + } + + var directory = Path.Combine(Path.GetTempPath(), "SharpEmuTests", Guid.NewGuid().ToString("N")); + try + { + using var presenter = new PresenterUnderTest(_vulkan); + presenter.SetField("_graphicsPipelineLibraries", true); + presenter.SetField("_vertexPrewarmIdentities", new ConcurrentDictionary()); + presenter.LoadRenderingCommands(); + var harness = presenter.Harness; + var target = harness.MapBacked(0x10000, ReadWrite); + var vertices = harness.MapBacked(0x10000, ReadWrite); + var words = RegisterWords.Color(target, Size, Size); + harness.Write(vertices, Triangle(-1f, -1f, 3f, -1f, -1f, 3f)); + var host = (IShaderPipelineHost)presenter.Instance; + var provider = new FixedProgramProvider(host, vertices); + var executor = new RenderExecutor(presenter.RenderHost, provider); + using (var list = ShaderPrewarmList.Open(directory) ?? throw new InvalidOperationException("The list did not open.")) + { + var (identity, _, _) = VertexPrewarmTests.RecordEmbeddedFetchProgram(list); + presenter.SetField("_shaderPrewarmList", list); + presenter.Run(provider.CreateModules); + // The fixed vertex module stands for the recorded program: the draw records its part's state under the identity. + var vertexModule = presenter.GetField>("_shaderModules")[1]; + host.VertexProgramRecorded(vertexModule.Handle, identity); + GuestGpuMemoryHook.Attach(harness.Gpu); + try + { + presenter.Run(() => executor.DrawAuto(1, Banks(words), Draw())); + presenter.Run(() => presenter.InvokeMethod("FlushBatchedGuestCommands")); + harness.Finish(); + } + finally + { + GuestGpuMemoryHook.Attach(null); + } + + presenter.SetField("_shaderPrewarmList", null!); + } + + using (var reloaded = ShaderPrewarmList.Open(directory) ?? throw new InvalidOperationException("The list did not open.")) + { + var part = Assert.IsType(Assert.Single(reloaded.LoadedGraphicsPrewarm())); + Assert.Equal(new PreRasterizationState((int)PolygonMode.Fill, (int)CullModeFlags.None, part.State.FrontFace, false, false, + part.State.DepthClipEnable, part.State.NegativeOneToOne), part.State); + presenter.SetField("_prewarmedGraphicsModules", new ConcurrentDictionary(StringComparer.Ordinal)); + var compiler = new FakeShaderCompiler(VertexPrewarmTests.Compile); + Assert.True((bool)presenter.InvokeMethod("PrewarmPreRasterizationLibrary", part.Program, part.Code, part.State, compiler)!); + Assert.Equal(1, presenter.GetField("_graphicsPrewarmCompiled")); + Assert.Equal(0, presenter.GetField("_graphicsPrewarmFailed")); + } + + harness.Shutdown(); + } + finally + { + if (Directory.Exists(directory)) + { + Directory.Delete(directory, recursive: true); + } + } + } + + // The graphics prewarm builds a task-launched mesh program's pre-rasterization part with the generic task stage, as the + // session's pipelines take it. + [Fact] + public void ThePrewarmBuildsATaskLaunchedMeshPartWithItsTaskStage() + { + if (!Ready() || !_vulkan.SupportsGraphicsPipelineLibrary || !_vulkan.SupportsMeshShaders || !_vulkan.SupportsTaskShaders) + { + return; + } + + var directory = Path.Combine(Path.GetTempPath(), "SharpEmuTests", Guid.NewGuid().ToString("N")); + try + { + using var presenter = new PresenterUnderTest(_vulkan); + presenter.SetField("_graphicsPipelineLibraries", true); + presenter.SetField("_supportsMeshShader", true); + presenter.SetField("_supportsTaskShader", true); + presenter.SetField("_meshShaderLimits", VertexPrewarmTests.TaskMeshLimits); + presenter.SetField("_prewarmedGraphicsModules", new ConcurrentDictionary(StringComparer.Ordinal)); + var state = new PreRasterizationState((int)PolygonMode.Fill, (int)CullModeFlags.None, (int)FrontFace.CounterClockwise, + false, false, true, false); + using (var list = ShaderPrewarmList.Open(directory) ?? throw new InvalidOperationException("The list did not open.")) + { + var (identity, _, _) = VertexPrewarmTests.RecordTaskLaunchedMeshProgram(list); + list.RecordPreRasterization(identity, state); + } + + using (var reloaded = ShaderPrewarmList.Open(directory) ?? throw new InvalidOperationException("The list did not open.")) + { + var part = Assert.IsType(Assert.Single(reloaded.LoadedGraphicsPrewarm())); + var compiler = new FakeShaderCompiler(VertexPrewarmTests.Compile); + Assert.True((bool)presenter.InvokeMethod("PrewarmPreRasterizationLibrary", part.Program, part.Code, part.State, compiler)!); + Assert.Equal(1, presenter.GetField("_graphicsPrewarmCompiled")); + Assert.Equal(0, presenter.GetField("_graphicsPrewarmFailed")); + } + + presenter.Harness.Shutdown(); + } + finally + { + if (Directory.Exists(directory)) + { + Directory.Delete(directory, recursive: true); + } + } + } +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.IndirectLifetime.cs b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.IndirectLifetime.cs new file mode 100644 index 000000000..fd0be23d6 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.IndirectLifetime.cs @@ -0,0 +1,136 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.InteropServices; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Gpu.GpuCommands; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Gpu.Vulkan; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.Libs.Tests.Gpu.Rendering; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.Libs.Tests.Gpu.Vulkan; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Images.ImageCacheTestSupport; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.Libs.Tests.VideoOut; + +public sealed unsafe partial class RenderHostDeviceTests +{ + [Theory] + [InlineData(false)] + [InlineData(true)] + public void IndirectDispatch_ArgumentOwnerGrowthPreservesTheShaderOutput(bool registerArgumentsEarly) + { + if (!GatePrerequisites.Ready(_vulkan, shaderInt64: true)) return; + using var presenter = new PresenterUnderTest(_vulkan!); + using var fatal = new FatalScope(); + presenter.SetField("_minStorageBufferOffsetAlignment", 256UL); + presenter.LoadRenderingCommands(); + Assert.True(((ICommandStreamHost)presenter.Instance).ResolvesIndirectDispatchOnGpu); + var harness = presenter.Harness; + var page = GuestBufferCache.CachingPageSize; + var address = harness.MapBacked(4 * page, ReadWrite); + // Arguments start in the last DWORD of the output's first cache page. + // Their later 12-byte acquisition must grow its owner across the boundary. + var arguments = address + page - sizeof(uint); + harness.Write(address, new byte[(int)page]); + harness.Write(address + sizeof(uint), BitConverter.GetBytes(0xABCD1234u)); + uint[] counts = [1, 1, 1]; + uint[] initialCounts = [0, 1, 1]; + harness.Write(arguments, MemoryMarshal.AsBytes(initialCounts.AsSpan()).ToArray()); + + var decoded = Program(MoveVector(0, 4, 1), BufferAtomicAdd(8, 0), EndProgram(16)); + var plan = Extract(decoded, userDataCount: 4); + uint[] userData = [(uint)address, (uint)(address >> 32), sizeof(uint), 0]; + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + Assert.True(ResourceMaterializer.Materialize(plan, Inputs(userData), ref snapshot, ref specialization)); + var resources = ResourceMaterializer.ApplyTo(plan, specialization); + var layout = BindingLayout.Allocate(resources.Info, [0, 1, 2, 3], false, false, false, 32); + Assert.False(layout.UsesPushData); + var request = new ShaderCompileRequest(plan, resources, layout) + { + LocalSizeX = 1, LocalSizeY = 1, LocalSizeZ = 1, + }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + var stageInfo = new ShaderProgramInfo + { + Stage = ShaderStageKind.Compute, Hash = Hash, UserDataCount = 4, + Resources = resources, Bindings = layout, + Buffers = resources.Info.Buffers.Select(buffer => new BufferResourceInfo( + buffer.Read, buffer.Written, buffer.Atomic, buffer.Formatted, buffer.Scalar, + buffer.MaxByteExtent)).ToArray(), + }; + GpuBuffer? original = null; + var retained = false; + try + { + var current = presenter.Run(() => + { + // Establish and upload a persistent owner; the readonly stream path would + // otherwise hide the ownership change this regression is exercising. + original = harness.Cache.GetBuffer(harness.Cache.FindBuffer(address, page)); + Assert.Equal(address, original.CpuAddress); + Assert.Equal(page, original.Size); + harness.Cache.SynchronizeBuffersInRange(address, page); + original.RetainForeignRead(); + retained = true; + // A real GPU writer makes the argument DWORD dirty, independently of + // tracker page size, and prevents the readonly CPU stream shortcut. + var (producer, producerOffset) = harness.Cache.ObtainBuffer(arguments, sizeof(uint), isWritten: true); + Assert.Same(original, producer); + producer.Fill(producerOffset, sizeof(uint), 1); + if (registerArgumentsEarly) _ = harness.Cache.FindBuffer(arguments, 12); + + var pipelineHost = (IShaderPipelineHost)presenter.Instance; + var program = new ShaderProgram(1, pipelineHost.CreateShaderModule( + new VulkanCompiledGuestShader(shader.Spirv), ShaderStage.Compute, Hash, 1)); + var provider = new FixedProgramProvider(pipelineHost, 0) + { + Compute = new ComputeProgram + { + Program = program, + Input = new ComputeInputInfo + { + ThreadsX = 1, ThreadsY = 1, ThreadsZ = 1, + Stage = new ShaderStageResources(stageInfo, snapshot), + }, + }, + }; + var banks = RenderExecutorFixtures.Banks(); + banks.Shader.Compute.ThreadsX = 1; + banks.Shader.Compute.ThreadsY = 1; + banks.Shader.Compute.ThreadsZ = 1; + var executor = new RenderExecutor(presenter.RenderHost, provider); + // Exercise the production executor, including its argument acquisition, + // descriptor commit and final indirect command. No copied call sequence. + executor.Dispatch(1, banks, 1, 1, 1, 0x41u, arguments); + var owner = harness.Cache.GetBuffer(harness.Cache.FindBuffer(address, sizeof(uint))); + Assert.NotSame(original, owner); + return owner; + }); + var output = harness.ReadBack(current, current.Offset(address), 8); + var oldOutput = harness.ReadBack(original!, original!.Offset(address), 4); + var argumentBytes = harness.ReadBack(current, current.Offset(arguments), 12); + Assert.Equal(counts, MemoryMarshal.Cast(argumentBytes.AsSpan()).ToArray()); + Assert.Equal(0xABCD1234u, BitConverter.ToUInt32(output, 4)); + Assert.True(BitConverter.ToUInt32(output) == 1, + $"The current owner lost the dispatch write: current={BitConverter.ToUInt32(output)}, old={BitConverter.ToUInt32(oldOutput)}."); + } + finally + { + presenter.Run(() => + { + harness.Scheduler.Finish(); + if (retained) original!.ReleaseForeignRead(); + }); + } + harness.Shutdown(); + } +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.MeshDraw.cs b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.MeshDraw.cs index b4bb2f2d1..5cb3f74fc 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.MeshDraw.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.MeshDraw.cs @@ -37,13 +37,25 @@ public void MeshDrawRendersGuestInputsAndRetainsUploadedIndices(uint waveSize, b public void IndirectMeshDrawRendersGuestInputs(uint waveSize, bool wideIndices) => RenderMeshDraw(waveSize, true, indirect: true, wideIndices: wideIndices); + // A task-launched automatic indirect draw (MeshTaskLaunch): no conversion dispatch; the task stage reads the current + // arguments, by device address when a GPU copy wrote them, and from the push words when the CPU wrote them (the host + // ring holds them without a device address). + [Theory] + [InlineData(32u, true)] + [InlineData(64u, true)] + [InlineData(32u, false)] + [InlineData(64u, false)] + public void TaskLaunchedIndirectMeshDrawRendersGuestInputs(uint waveSize, bool gpuArguments) + => RenderMeshDraw(waveSize, false, indirect: true, taskLaunched: true, gpuArguments: gpuArguments); + private void RenderMeshDraw(uint waveSize, bool indexed, ulong? traceShaderAddress = null, - bool indirect = false, bool wideIndices = false) + bool indirect = false, bool wideIndices = false, bool taskLaunched = false, bool gpuArguments = false) { if (!GatePrerequisites.Ready(_vulkan, shaderInt64: true)) return; - if (!_vulkan.SupportsMeshShaders || !_vulkan.SupportsDynamicRendering || _vulkan.SubgroupSize != 32) + if (!_vulkan.SupportsMeshShaders || !_vulkan.SupportsDynamicRendering || _vulkan.SubgroupSize != 32 || + (taskLaunched && !_vulkan.SupportsTaskShaders)) { - Assert.False(GatePrerequisites.DeviceRequired, "This test requires mesh rendering with 32-lane subgroups."); + Assert.False(GatePrerequisites.DeviceRequired, "This test requires mesh (and task) rendering with 32-lane subgroups."); return; } using var presenter = new PresenterUnderTest(_vulkan); @@ -52,6 +64,12 @@ private void RenderMeshDraw(uint waveSize, bool indexed, ulong? traceShaderAddre var command = (IntPtr)(void*)_vulkan.Vk.GetDeviceProcAddr(_vulkan.Device, "vkCmdDrawMeshTasksEXT"); Assert.NotEqual(IntPtr.Zero, command); presenter.SetField("_cmdDrawMeshTasks", command); + if (taskLaunched) + { + presenter.SetField("_supportsTaskShader", true); + presenter.SetField("_meshShaderLimits", new MeshShaderLimits(128, 256, 256, 28672, 65535, 65535, 1u << 22, 128, + 32768, 49152, 1, 1, 128)); + } if (indirect) { var indirectCommand = (IntPtr)(void*)_vulkan.Vk.GetDeviceProcAddr(_vulkan.Device, "vkCmdDrawMeshTasksIndirectEXT"); @@ -64,7 +82,7 @@ private void RenderMeshDraw(uint waveSize, bool indexed, ulong? traceShaderAddre var banks = Banks(words); if (traceShaderAddress is { } shaderAddress) banks.Shader.Vertex.ExportAddress = shaderAddress; banks.Context.ShaderStages = 0x20; - var provider = new MeshFrameProgramProvider((IShaderPipelineHost)presenter.Instance, waveSize); + var provider = new MeshFrameProgramProvider((IShaderPipelineHost)presenter.Instance, waveSize, taskLaunched); var executor = new RenderExecutor(presenter.RenderHost, provider); if (indexed) { @@ -91,6 +109,22 @@ private void RenderMeshDraw(uint waveSize, bool indexed, ulong? traceShaderAddre Assert.Equal(0UL, presenter.HostBuffers.CachedBytes); } } + else if (indirect) + { + var arguments = harness.MapBacked(0x10000, ReadWrite); + if (gpuArguments) + { + var sourceArguments = harness.MapBacked(0x10000, ReadWrite); + harness.Write(sourceArguments, [3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + presenter.Run(() => harness.Cache.CopyBuffer(arguments, sourceArguments, 16, false, false)); + } + else + { + harness.Write(arguments, [3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + } + + presenter.Run(() => executor.DrawAuto(1, banks, Draw() with { IndirectArgumentsAddress = arguments })); + } else { presenter.Run(() => executor.DrawAuto(1, banks, Draw())); @@ -105,7 +139,7 @@ private void RenderMeshDraw(uint waveSize, bool indexed, ulong? traceShaderAddre harness.Shutdown(); } - private sealed class MeshFrameProgramProvider(IShaderPipelineHost host, uint waveSize) : IShaderPipelineProvider + private sealed class MeshFrameProgramProvider(IShaderPipelineHost host, uint waveSize, bool taskLaunched = false) : IShaderPipelineProvider { public bool MeshShadersSupported => true; @@ -137,7 +171,7 @@ public GraphicsPrograms GetMeshGraphicsPrograms(RegisterBanks banks, UserConfigR var request = new ShaderCompileRequest(plan, resources, layout) { WaveSize = waveSize, LocalSizeX = waveSize, - Mesh = new MeshShaderConfiguration(3, 1, 0, 1, 3, 0, false, 32), + Mesh = new MeshShaderConfiguration(3, 1, 0, 1, 3, 0, false, 32, TaskLaunched: taskLaunched), }; Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var compiled, out var error), error); var meshProgram = new ShaderProgram(1, host.CreateShaderModule( @@ -147,6 +181,7 @@ public GraphicsPrograms GetMeshGraphicsPrograms(RegisterBanks banks, UserConfigR var meshInfo = new ShaderProgramInfo { Stage = ShaderStageKind.Mesh, Hash = 1, Resources = resources, Bindings = layout, + MeshTask = taskLaunched ? new MeshTaskLaunchInfo(1, false) : null, }; return new GraphicsPrograms { @@ -161,6 +196,7 @@ public GraphicsPrograms GetMeshGraphicsPrograms(RegisterBanks banks, UserConfigR Geometry = new GuestGeometryConfiguration { WaveSize = waveSize, ThreadsPerGroup = waveSize, InputPrimitiveCountPerWorkgroup = 1, + TaskLaunched = taskLaunched, }, Execution = new MeshExecutionLimits { MaxGroupCountX = 65535, MaxGroupCountY = 65535, MaxGroupTotalCount = 65535 }, }, diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.MeshIndirect.cs b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.MeshIndirect.cs index c575ea5f7..82edbc677 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.MeshIndirect.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.MeshIndirect.cs @@ -37,7 +37,7 @@ public void IndirectMeshResourcesSurviveAbandonmentAndCompletion(bool record, bo (IntPtr)(void*)_vulkan.Vk.GetDeviceProcAddr(_vulkan.Device, "vkCmdDrawMeshTasksIndirectEXT")); var harness = presenter.Harness; var memory = harness.MapBacked(0x10000, ImageCacheTestSupport.ReadWrite); - // An instance count over the group limit is fatal, as on the CPU path. + // An instance count over the group limit launches nothing (status 2) and is left out, as on the CPU path. harness.Write(memory, [3, 0, 0, 0, invalid ? (byte)255 : (byte)1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); var request = new IndirectMeshDrawRequest(memory, memory + 64, 8, 2, false, 1, @@ -50,16 +50,125 @@ public void IndirectMeshResourcesSurviveAbandonmentAndCompletion(bool record, bo using var draw = presenter.RenderHost.PrepareIndirectMeshDraw(request); if (record) draw.Prepare(); } - if (invalid) + harness.Scheduler.Finish(); + Assert.Empty(fatal.Messages); + }); + harness.Shutdown(); + } + + // The helper writes its status word on every exit, so a reused status buffer needs no host clear: a draw over the + // group limits (status 2) returns its status buffer, and the next draw, which rents the same buffer, reports 0. + [Fact] + public void AReusedIndirectMeshStatusReportsTheNewDrawWithoutAHostClear() + { + if (!GatePrerequisites.Ready(_vulkan, shaderInt64: true)) return; + if (!_vulkan.SupportsMeshShaders) + { + Assert.False(GatePrerequisites.DeviceRequired, "This test requires mesh shader support."); + return; + } + using var worker = new CacheWorker(_vulkan); + worker.Run(() => + { + var scheduler = worker.Scheduler; + scheduler.Begin(new SubmissionContext { QueueName = "mesh-indirect-status.test", SubmissionId = 1 }); + using var arguments = new GpuBuffer(_vulkan.DeviceInfo, scheduler, GpuBufferUsage.DeviceLocal, + 0, GpuBuffer.AllFlags, 16); + using var pipeline = new MeshIndirectPipeline(_vulkan.DeviceInfo); + var request = IndirectMeshDrawRequest.ForAutomaticDraw(0, false, 1, + new MeshExecutionLimits { MaxGroupCountX = 32, MaxGroupCountY = 64, MaxGroupTotalCount = 64 }); + var binding = new BufferBinding(arguments.Handle.Handle, 0); + uint Run(uint count, uint instances) { - Assert.Throws(() => harness.Scheduler.Finish()); - // All completion callbacks must release their resources even when one reports an error. - for (var index = 0; index < 2; index++) - Assert.Throws(() => harness.Scheduler.RunCompletedOperations()); + using var prepared = pipeline.Prepare(scheduler, binding, binding, 0, request); + var command = new CommandBuffer(scheduler.Current.Handle); + uint* words = stackalloc uint[4] { count, instances, 0, 0 }; + _vulkan.Vk.CmdUpdateBuffer(command, arguments.Handle, 0, 16, words); + prepared.Record(command); + scheduler.Finish(); + return prepared.ReadStatus(); } - else harness.Scheduler.Finish(); + + Assert.Equal(2u, Run(120, 2)); + Assert.Equal(0u, Run(6, 2)); + Assert.Equal(2u, Run(120, 2)); + Assert.Equal(0u, Run(0, 2)); + scheduler.Finish(); }); - harness.Shutdown(); + _vulkan.AssertNoValidationMessages(); + } + + // An automatic draw: the groups follow the vertex count, and the parameters carry the + // first vertex and instance with no index buffer. + [Theory] + [InlineData(true, 6u, 2u, 0u)] + [InlineData(false, 7u, 2u, 0u)] + [InlineData(true, 0u, 2u, 0u)] + [InlineData(true, 6u, 0u, 0u)] + [InlineData(true, 40u, 2u, 2u)] + public void AutomaticIndirectMeshPreparationReadsVertexArguments(bool points, uint count, uint instances, uint expectedStatus) + { + if (!GatePrerequisites.Ready(_vulkan, shaderInt64: true)) return; + if (!_vulkan.SupportsMeshShaders) + { + Assert.False(GatePrerequisites.DeviceRequired, "This test requires mesh shader support."); + return; + } + using var worker = new CacheWorker(_vulkan); + worker.Run(() => + { + var scheduler = worker.Scheduler; + scheduler.Begin(new SubmissionContext { QueueName = "mesh-indirect-auto.test", SubmissionId = 1 }); + using var arguments = new GpuBuffer(_vulkan.DeviceInfo, scheduler, GpuBufferUsage.DeviceLocal, + 0, GpuBuffer.AllFlags, 16); + using var download = new GpuBuffer(_vulkan.DeviceInfo, scheduler, GpuBufferUsage.Download, + 0, GpuBuffer.AllFlags, 64); + using var pipeline = new MeshIndirectPipeline(_vulkan.DeviceInfo); + var request = IndirectMeshDrawRequest.ForAutomaticDraw(0, points, 1, + new MeshExecutionLimits { MaxGroupCountX = 32, MaxGroupCountY = 64, MaxGroupTotalCount = 64 }); + var binding = new BufferBinding(arguments.Handle.Handle, 0); + using var prepared = pipeline.Prepare(scheduler, binding, binding, 0, request); + try + { + var command = new CommandBuffer(scheduler.Current.Handle); + uint* words = stackalloc uint[4] { count, instances, 9, 5 }; + _vulkan.Vk.CmdUpdateBuffer(command, arguments.Handle, 0, 16, words); + prepared.Record(command); + var barrier = new MemoryBarrier + { + SType = StructureType.MemoryBarrier, SrcAccessMask = AccessFlags.ShaderWriteBit, + DstAccessMask = AccessFlags.TransferReadBit, + }; + _vulkan.Vk.CmdPipelineBarrier(command, PipelineStageFlags.ComputeShaderBit, + PipelineStageFlags.TransferBit, 0, 1, &barrier, 0, null, 0, null); + var copy = new BufferCopy(0, 0, 64); + _vulkan.Vk.CmdCopyBuffer(command, prepared.CommandBuffer, download.Handle, 1, ©); + barrier.SrcAccessMask = AccessFlags.TransferWriteBit; + barrier.DstAccessMask = AccessFlags.HostReadBit; + _vulkan.Vk.CmdPipelineBarrier(command, PipelineStageFlags.TransferBit, + PipelineStageFlags.HostBit, 0, 1, &barrier, 0, null, 0, null); + scheduler.Finish(); + Assert.Equal(expectedStatus, prepared.ReadStatus()); + download.Invalidate(0, 64); + var result = MemoryMarshal.Cast(download.Mapped[..64]); + var primitives = points ? count : count / 3; + var execute = expectedStatus != 2 && count != 0 && instances != 0; + Assert.Equal(execute ? primitives : 0, result[0]); + Assert.Equal(execute ? instances : 0, result[1]); + Assert.Equal(1u, result[2]); + Assert.Equal(execute ? points ? count : primitives * 3 : 0, result[4]); + Assert.Equal(9u, result[5]); + Assert.Equal(5u, result[6]); + Assert.Equal(0u, result[7]); + Assert.Equal(0u, result[8]); + Assert.Equal(0u, result[9]); + } + finally + { + scheduler.Finish(); + } + }); + _vulkan.AssertNoValidationMessages(); } [Theory] diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.NullImageMemo.cs b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.NullImageMemo.cs new file mode 100644 index 000000000..1df7ccb85 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.NullImageMemo.cs @@ -0,0 +1,164 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections; +using System.Reflection; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.Libs.VideoOut; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using PlanImageResourceClass = SharpEmu.ShaderCompiler.Resources.ImageResourceClass; +using ResourceSnapshot = SharpEmu.ShaderCompiler.Resources.ResourceSnapshot; + +namespace SharpEmu.Libs.Tests.VideoOut; + +// The image binding memo of a descriptor that names no memory: the placeholder it keeps, and its switch. +public sealed unsafe partial class RenderHostDeviceTests +{ + private const BindingFlags HostMembers = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + + private static readonly ImageResource SampledImage = new() + { + ResourceClass = PlanImageResourceClass.Sampled, + NumericClass = ImageNumericClass.Float, + Dimension = ImageDimension.Dim2D, + Read = true, + }; + + private static long HostCounter(PresenterUnderTest presenter, string name) => + (long)presenter.Recording.GetType().GetProperty(name, HostMembers)!.GetValue(presenter.Recording)!; + + // Prepares and binds one compute stage with one image and returns the image it bound. Each shader base misses the + // stage preparation of the others, so the image is resolved again through its binding memo. + private static ResourceSlotIdentifier BindOneImage(PresenterUnderTest presenter, ShaderProgramInfo program, uint[] words, ulong shaderBase) => + presenter.Run(() => + { + presenter.RenderHost.ResetBindings(); + using var preparation = presenter.RenderHost.BeginPreparation(); + var prepared = presenter.RenderHost.PrepareBindings( + new ShaderStageResources(program, new ResourceSnapshot { Images = [words] }, shaderBase)); + presenter.RenderHost.BindResources(prepared); + var textures = (Array)prepared.GetType().GetProperty("Textures", HostMembers)!.GetValue(prepared)!; + var texture = textures.GetValue(0)!; + return (ResourceSlotIdentifier)texture.GetType().GetField("ImageIdentifier", HostMembers)!.GetValue(texture)!; + }); + + // The image cache looks a placeholder up after completing the publications over its empty range. + private static Func CountNullLookups(PresenterUnderTest presenter) + { + var lookups = 0; + var publications = presenter.Harness.Cache.CompleteGuestPublications!; + presenter.Harness.Cache.CompleteGuestPublications = (address, size, access) => + { + lookups += address == 0 && size == 0 ? 1 : 0; + publications(address, size, access); + }; + return () => lookups; + } + + private static object[] KeptNullBindings(PresenterUnderTest presenter) => + presenter.GetField("_imageBindingMemos").Values.Cast() + .Where(memo => (bool)memo.GetType().GetField("NullImage")!.GetValue(memo)!).ToArray(); + + [Theory] + [InlineData("On", 1)] + [InlineData("Verify", 3)] + [InlineData("Off", 3)] + public void NullImageMemo_ADescriptorThatNamesNoMemoryKeepsItsPlaceholder(string mode, int lookups) + { + if (!Ready()) return; + using var presenter = new PresenterUnderTest(_vulkan!); + using var fatal = new FatalScope(); + presenter.LoadRenderingCommands(); + presenter.SetField("NullImageMemo", Enum.Parse(mode)); + var nullLookups = CountNullLookups(presenter); + var program = FixedProgramProvider.EmptyProgram(ShaderStageKind.Compute, 0xB3, new ShaderResourceInfo { Images = [SampledImage] }); + var words = new uint[8]; + + var first = BindOneImage(presenter, program, words, 0x1000); + var second = BindOneImage(presenter, program, words, 0x2000); + var third = BindOneImage(presenter, program, words, 0x3000); + + Assert.Equal(first, second); + Assert.Equal(first, third); + Assert.Equal(lookups, nullLookups()); + Assert.Equal(mode == "On" ? 2 : 0, HostCounter(presenter, "NullImageHits")); + Assert.Equal(mode == "Verify" ? 2 : 0, HostCounter(presenter, "NullImageVerifications")); + Assert.Equal(0, HostCounter(presenter, "NullImageMismatches")); + var kept = KeptNullBindings(presenter); + if (mode == "Off") + { + Assert.Empty(kept); + } + else + { + var memo = Assert.Single(kept); + Assert.Equal(first, (ResourceSlotIdentifier)memo.GetType().GetField("Found")!.GetValue(memo)!); + Assert.False((bool)memo.GetType().GetField("CompletesLookup")!.GetValue(memo)!); + } + + Assert.Empty(fatal.Messages); + presenter.Harness.Shutdown(); + } + + // Images created and removed elsewhere leave a kept placeholder valid: it is still served after the lookup generation + // moved. + [Fact] + public void NullImageMemo_AKeptPlaceholderOutlivesImagesCreatedElsewhere() + { + if (!Ready()) return; + using var presenter = new PresenterUnderTest(_vulkan!); + using var fatal = new FatalScope(); + presenter.LoadRenderingCommands(); + presenter.SetField("NullImageMemo", VulkanVideoPresenter.NullImageMemoMode.On); + var nullLookups = CountNullLookups(presenter); + var program = FixedProgramProvider.EmptyProgram(ShaderStageKind.Compute, 0xB4, new ShaderResourceInfo { Images = [SampledImage] }); + var words = new uint[8]; + + var first = BindOneImage(presenter, program, words, 0x1000); + var generation = presenter.Run(() => presenter.Harness.Images.LookupGeneration); + var address = presenter.Harness.MapBacked(0x10000, ImageCacheTestSupport.ReadWrite); + var request = ImageCacheTestSupport.Color32(address, 16); + _ = presenter.Harness.Find(ref request); + Assert.NotEqual(generation, presenter.Run(() => presenter.Harness.Images.LookupGeneration)); + + var second = BindOneImage(presenter, program, words, 0x2000); + Assert.Equal(first, second); + Assert.Equal(1, nullLookups()); + Assert.Equal(1, HostCounter(presenter, "NullImageHits")); + Assert.Empty(fatal.Messages); + presenter.Harness.Shutdown(); + } + + // A kept placeholder that differs from the lookup's image is counted in verify mode, and the lookup's image is bound. + [Fact] + public void NullImageMemo_VerifyCountsAPlaceholderTheLookupDoesNotGive() + { + if (!Ready()) return; + using var presenter = new PresenterUnderTest(_vulkan!); + using var fatal = new FatalScope(); + presenter.LoadRenderingCommands(); + presenter.SetField("NullImageMemo", VulkanVideoPresenter.NullImageMemoMode.Verify); + var program = FixedProgramProvider.EmptyProgram(ShaderStageKind.Compute, 0xB5, new ShaderResourceInfo { Images = [SampledImage] }); + var words = new uint[8]; + + var first = BindOneImage(presenter, program, words, 0x1000); + presenter.Run(() => + { + var memos = presenter.GetField("_imageBindingMemos"); + var key = memos.Keys.Cast().Single(); + var memo = memos[key]!; + memo.GetType().GetField("Found")!.SetValue(memo, new ResourceSlotIdentifier(first.Index + 1000, first.Generation)); + memos[key] = memo; + }); + + var second = BindOneImage(presenter, program, words, 0x2000); + Assert.Equal(first, second); + Assert.Equal(1, HostCounter(presenter, "NullImageVerifications")); + Assert.Equal(1, HostCounter(presenter, "NullImageMismatches")); + presenter.Harness.Shutdown(); + } +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.Tessellation.cs b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.Tessellation.cs index ba53b027d..1ff517678 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.Tessellation.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.Tessellation.cs @@ -77,14 +77,24 @@ public void TessellationOffchip_DecodesTheBufferCountAndGranularity() public void Tessellation_VertexOffsetUsesPacketRegistersOrIndirectArguments(bool indexed) => RenderTessellationPatch(0, false, true, verifyOffset: true, indexed: indexed); + // With pipeline libraries a pixel module reads its bindings from the pixel set, so a tessellated pipeline binds them + // there too: the pixel stage here takes its color from its shader data binding. The pipeline links its parts, the + // control and evaluation stages in its pre-rasterization part. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Tessellation_PixelStageReadsItsBindingsWithPipelineLibraries(bool computeFactors) => + RenderTessellationPatch(1f, true, computeFactors, libraries: true); + private void RenderTessellationPatch(float firstOuter, bool visible, bool computeFactors, uint patchCount = 1, - bool verifyOffset = false, bool indexed = false, uint ringPatches = 1, uint primitiveType = 4) + bool verifyOffset = false, bool indexed = false, uint ringPatches = 1, uint primitiveType = 4, bool libraries = false) { if (!Ready()) return; Assert.False(GatePrerequisites.DeviceRequired && !_vulkan!.SupportsTessellation, "The required tessellation test needs the tessellationShader device feature."); - if (!_vulkan!.SupportsTessellation) return; + if (!_vulkan!.SupportsTessellation || (libraries && !_vulkan.SupportsGraphicsPipelineLibrary)) return; using var presenter = new PresenterUnderTest(_vulkan!); + presenter.SetField("_graphicsPipelineLibraries", libraries); _vulkan!.Vk.GetPhysicalDeviceProperties(_vulkan.Physical, out var properties); presenter.SetField("_minStorageBufferOffsetAlignment", properties.Limits.MinStorageBufferOffsetAlignment); presenter.LoadRenderingCommands(); @@ -98,7 +108,7 @@ private void RenderTessellationPatch(float firstOuter, bool visible, bool comput var words = RegisterWords.Color(target, Size, Size); var executor = new RenderExecutor(presenter.RenderHost, new TessellationProgramProvider((IShaderPipelineHost)presenter.Instance, factors.DeviceAddress, guestFactors, firstOuter, - patchCount > 1 || verifyOffset, verifyOffset ? 2u : 0u, 24 * ringPatches)); + patchCount > 1 || verifyOffset, verifyOffset ? 2u : 0u, 24 * ringPatches, pixelReadsShaderData: libraries)); GuestGpuMemoryHook.Attach(harness.Gpu); try { @@ -134,6 +144,12 @@ private void RenderTessellationPatch(float firstOuter, bool visible, bool comput var image = harness.ReadImageBytes(TargetImage(presenter, words)); Assert.Equal(visible ? Red : 0u, Pixel(image, Size / 2, Size / 2)); Assert.Equal(visible ? Red : 0u, Pixel(image, 2, 2)); + if (libraries) + { + var parts = presenter.GetField>("_graphicsLibraries"); + Assert.Contains(parts.Keys, key => key.StartsWith("pr;", StringComparison.Ordinal) && key.Contains(";tess:", StringComparison.Ordinal)); + } + if (ringPatches > 1) { // Patch 0 wrote its zero factor at the start of the ring; patch 1 wrote its @@ -149,13 +165,18 @@ private void RenderTessellationPatch(float firstOuter, bool visible, bool comput } private sealed class TessellationProgramProvider(IShaderPipelineHost host, ulong factorAddress, ulong guestFactors, float firstOuter, - bool useAbsolutePatchId, uint factorSourceRegister, uint factorRingBytes) : IShaderPipelineProvider + bool useAbsolutePatchId, uint factorSourceRegister, uint factorRingBytes, bool pixelReadsShaderData = false) : IShaderPipelineProvider { private ShaderProgram _vertex, _control, _domain, _pixel; private ShaderProgramInfo _domainInfo = null!; private ComputeProgram? _hull; private static readonly ShaderProgramInfo PixelInfo = FixedProgramProvider.EmptyProgram(ShaderStageKind.Pixel, 4); + // Four user-data registers that start past the push range, so the pixel stage reads them from its shader data binding. + private static readonly ShaderProgramInfo ShaderDataPixelInfo = FixedProgramProvider.EmptyProgram(ShaderStageKind.Pixel, 4, + userDataRegisters: [0, 1, 2, 3], pushDataStart: PushData.DwordCount); + private static readonly uint[] RedUserData = [BitConverter.SingleToUInt32Bits(1f), 0, 0, BitConverter.SingleToUInt32Bits(1f)]; + public GraphicsPrograms GetGraphicsPrograms(RegisterBanks banks, ReadOnlySpan mappings, bool pixelActive, bool depthBound) => GetGraphicsPrograms(banks.Shader.Vertex, banks.Shader.Pixel, banks.Context.ShaderInterface, banks.Context, mappings, pixelActive, depthBound); @@ -186,7 +207,8 @@ public GraphicsPrograms GetGraphicsPrograms(VertexStageRegisters vertex, PixelSt _vertex = new(1, host.CreateShaderModule(new VulkanCompiledGuestShader(SpirvFixedShaders.CreateFullscreenVertex(0)), ShaderStage.Vertex, 1, 1)); _control = new(2, host.CreateShaderModule(new VulkanCompiledGuestShader(Gen5TessellationBridge.CompileControl(layout, Gen5TessellationDomain.Quads).Spirv), ShaderStage.TessellationEvaluation, 2, 2)); _domain = new(3, host.CreateShaderModule(new VulkanCompiledGuestShader(shader.Spirv), ShaderStage.TessellationEvaluation, Hash, 3)); - _pixel = new(4, host.CreateShaderModule(new VulkanCompiledGuestShader(SpirvFixedShaders.CreateSolidFragment(1, 0, 0, 1)), ShaderStage.Pixel, 4, 4)); + _pixel = new(4, host.CreateShaderModule(new VulkanCompiledGuestShader(pixelReadsShaderData + ? CreateShaderDataFragment() : SpirvFixedShaders.CreateSolidFragment(1, 0, 0, 1)), ShaderStage.Pixel, 4, 4)); if (guestFactors != 0) _hull = CreateHull(); } var data = new uint[Gen5TessellationData.DwordCount]; @@ -201,10 +223,54 @@ public GraphicsPrograms GetGraphicsPrograms(VertexStageRegisters vertex, PixelSt Vertex = _vertex, Pixel = _pixel, Tessellation = _hull is null ? null : new(new(Gen5TessellationDomain.Quads, Gen5TessellationSpacing.Equal, false, false), new(4, 4, 1, 0), _hull), VertexInput = new() { Tessellation = new(_control, _domain, 4), Stage = new(_domainInfo, new ResourceSnapshot()) { TessellationData = data } }, - PixelInput = new() { Stage = new(PixelInfo, new ResourceSnapshot()) }, + PixelInput = new() + { + Stage = pixelReadsShaderData + ? new(ShaderDataPixelInfo, new ResourceSnapshot { UserData = RedUserData }) + : new(PixelInfo, new ResourceSnapshot()), + }, }; } + // outColor = the first four dwords of the pixel stage's shader data, as floats. + private static byte[] CreateShaderDataFragment() + { + var module = new SpirvModuleBuilder(); + module.AddCapability(SpirvCapability.Shader); + var voidType = module.TypeVoid(); + var uintType = module.TypeInt(32, false); + var floatType = module.TypeFloat(32); + var vec4Type = module.TypeVector(floatType, 4); + var words = module.TypeRuntimeArray(uintType); + module.AddDecoration(words, SpirvDecoration.ArrayStride, 4); + var block = module.TypeStruct(words); + module.AddDecoration(block, SpirvDecoration.Block); + module.AddMemberDecoration(block, 0, SpirvDecoration.Offset, 0); + var data = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.StorageBuffer, block), SpirvStorageClass.StorageBuffer); + module.AddDecoration(data, SpirvDecoration.NonWritable); + module.AddDecoration(data, SpirvDecoration.DescriptorSet, 0u); + module.AddDecoration(data, SpirvDecoration.Binding, BindingLayout.NativeBindingIndex(ShaderStage.Pixel, DescriptorBindingKind.ShaderData)); + var output = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.Output, vec4Type), SpirvStorageClass.Output); + module.AddDecoration(output, SpirvDecoration.Location, 0); + var main = module.BeginFunction(voidType, module.TypeFunction(voidType)); + module.AddLabel(); + var wordPointer = module.TypePointer(SpirvStorageClass.StorageBuffer, uintType); + var channels = new uint[4]; + for (uint index = 0; index < 4; index++) + { + var word = module.AddInstruction(SpirvOp.Load, uintType, + module.AddInstruction(SpirvOp.AccessChain, wordPointer, data, module.Constant(uintType, 0), module.Constant(uintType, index))); + channels[index] = module.AddInstruction(SpirvOp.Bitcast, floatType, word); + } + + module.AddStatement(SpirvOp.Store, output, module.AddInstruction(SpirvOp.CompositeConstruct, vec4Type, channels)); + module.AddStatement(SpirvOp.Return); + module.EndFunction(); + module.AddEntryPoint(SpirvExecutionModel.Fragment, main, "main", [data, output]); + module.AddExecutionMode(main, SpirvExecutionMode.OriginUpperLeft); + return module.Build(); + } + private ComputeProgram CreateHull() { var instructions = new List @@ -236,7 +302,7 @@ private ComputeProgram CreateHull() { Stage = ShaderStageKind.Compute, Hash = Hash, UserDataBase = 8, UserDataCount = 20, Bindings = layout, Resources = resources, TessellationFactorBuffer = (int)Gen5TessellationLowering.FindFactorBuffer(plan, 0), - Buffers = [new(false, true, false, false, false, 24, 0)], + Buffers = [new(false, true, false, false, false, 24)], }; var data = new uint[20]; data[12] = BitConverter.SingleToUInt32Bits(firstOuter); diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.cs index 92d7688d8..e0f30139f 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.cs @@ -144,7 +144,8 @@ public void BeginPreparation_AcquiresMovieFrameOnceAndRetainsItUntilReplacement( // One float2 position program and one solid red pixel program over empty resource plans. private sealed class FixedProgramProvider(IShaderPipelineHost host, ulong vertexAddress, bool pushData = false, byte[]? interpolationShader = null, uint vertexCount = VertexCount, - byte[]? vertexShader = null, uint vertexComponents = 2, uint vertexStride = VertexStride) : IShaderPipelineProvider + byte[]? vertexShader = null, uint vertexComponents = 2, uint vertexStride = VertexStride, + bool announcePixelProgram = false, bool throughWorkers = false) : IShaderPipelineProvider { private const uint Float2Format = 64; private static readonly uint[] UserRegisters = [0, 1]; @@ -183,8 +184,14 @@ private void EnsureModules() vertexShader ?? CreatePositionVertexShader(interpolationShader is not null)), ShaderStage.Vertex, 1, 1)); _pixelProgram = new ShaderProgram(2, host.CreateShaderModule(new VulkanCompiledGuestShader( interpolationShader ?? SpirvFixedShaders.CreateSolidFragment(1f, 0f, 0f, 1f)), ShaderStage.Pixel, 2, 2)); + if (announcePixelProgram) + { + host.PixelProgramCreated(_pixel, _pixelProgram.Module); + } } + public void CreateModules() => EnsureModules(); + public GraphicsPrograms GetGraphicsPrograms( RegisterBanks banks, ReadOnlySpan targetExportMapping, @@ -217,16 +224,37 @@ public PipelineHandle CreateGraphicsPipeline( bool primitiveRestartEnabled, bool disableBlending, ShaderProgram vertexProgram, - ShaderProgram pixelProgram) => - host.CreateGraphicsPipeline(ShaderPipelineCache.BuildGraphicsDescription( + ShaderProgram pixelProgram) + { + var description = ShaderPipelineCache.BuildGraphicsDescription( colors, in depth, vertexInput, pixelInput, context, in rendering, topology, primitiveRestartEnabled, disableBlending, - vertexProgram, pixelProgram, host.NoAttachmentSampleCounts)); + vertexProgram, pixelProgram, host.NoAttachmentSampleCounts); + if (!throughWorkers) + { + return host.CreateGraphicsPipeline(description); + } + + // As the pipeline cache does: the pipeline builds on a worker and the draw waits for it. + PipelineHandle handle; + while (!host.TryCreateGraphicsPipeline(description, out handle)) + { + host.WaitForGraphicsPipeline(description); + } + + return handle; + } + + public ComputeProgram? Compute { get; init; } public ComputeProgram GetComputeProgram(ComputeStageRegisters compute, ShaderInterfaceRegisters shaderInterface, uint dispatchInitiator, uint dimensionX, uint dimensionY, uint dimensionZ) => - throw new InvalidOperationException("The test provider has no compute program."); + Compute ?? throw new InvalidOperationException("The test provider has no compute program."); public PipelineHandle CreateComputePipeline(ComputeInputInfo input, ShaderProgram program) => - throw new InvalidOperationException("The test provider has no compute pipeline."); + Compute is null ? throw new InvalidOperationException("The test provider has no compute pipeline.") : + host.CreateComputePipeline(new ComputePipelineDescription + { + Program = program, Stage = input.Stage.Program!, Input = input, + }); } // position = (input.xy, 0, 1) @@ -694,15 +722,189 @@ public void PrepareBindings_PrivateBufferUploadsCurrentBytesAndStillRejectsGpuWr Assert.Equal(HostPageProtection.ReadWriteExecute, harness.Protection(address)); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void APixelProgramsPart_CompilesWhenTheProgramIsCreated_AndItsDrawLinksIt(bool throughWorkers) + { + if (!Ready() || !_vulkan.SupportsGraphicsPipelineLibrary) + { + return; + } + + using var presenter = new PresenterUnderTest(_vulkan); + presenter.SetField("_graphicsPipelineLibraries", true); + presenter.LoadRenderingCommands(); + var harness = presenter.Harness; + var target = harness.MapBacked(0x10000, ReadWrite); + var vertices = harness.MapBacked(0x10000, ReadWrite); + var words = RegisterWords.Color(target, Size, Size); + harness.Write(vertices, Triangle(-1f, -1f, 3f, -1f, -1f, 3f)); + var provider = new FixedProgramProvider((IShaderPipelineHost)presenter.Instance, vertices, announcePixelProgram: true, + throughWorkers: throughWorkers); + var executor = new RenderExecutor(presenter.RenderHost, provider); + GuestGpuMemoryHook.Attach(harness.Gpu); + try + { + presenter.Run(provider.CreateModules); + presenter.InvokeMethod("WaitForEarlyPixelLibraries"); + var parts = presenter.GetField>("_graphicsLibraries"); + var pixelPart = Assert.Single(parts.Values); + + presenter.Run(() => executor.DrawAuto(1, Banks(words), Draw())); + presenter.Run(() => presenter.InvokeMethod("FlushBatchedGuestCommands")); + harness.Finish(); + + var pixels = harness.ReadImageBytes(TargetImage(presenter, words)); + Assert.All(Enumerable.Range(0, (int)(Size * Size)), index => Assert.Equal(Red, BitConverter.ToUInt32(pixels, index * 4))); + // The draw added the vertex input, vertex and output parts and linked the pixel part compiled before it. + Assert.Equal(4, parts.Count); + Assert.Contains(pixelPart, parts.Values); + } + finally + { + GuestGpuMemoryHook.Attach(null); + } + + harness.Shutdown(); + } + + // The bindless heap's set is visible to every graphics stage, so parts linked with independent sets all carry it, even when + // only one stage reads it: here the vertex stage reads it and the pixel stage does not. [Fact] - public void TwoDraws_RenderTheVertexVersionEachWasRecordedWith() + public void LinkedParts_AllCarryTheHeapSet_WhenOnlyTheVertexStageReadsIt() { - if (!Ready()) + if (!Ready() || !_vulkan.SupportsGraphicsPipelineLibrary) { return; } using var presenter = new PresenterUnderTest(_vulkan); + presenter.SetField("_graphicsPipelineLibraries", true); + presenter.LoadRenderingCommands(); + var harness = presenter.Harness; + var target = harness.MapBacked(0x10000, ReadWrite); + var vertices = harness.MapBacked(0x10000, ReadWrite); + var words = RegisterWords.Color(target, Size, Size); + harness.Write(vertices, Triangle(-1f, -1f, 3f, -1f, -1f, 3f)); + var host = (IShaderPipelineHost)presenter.Instance; + var executor = new RenderExecutor(presenter.RenderHost, new FixedProgramProvider(host, vertices)); + // A stand-in for the heap's set layout, which needs descriptor indexing the test device leaves off. + var binding = new DescriptorSetLayoutBinding + { + Binding = 0, + DescriptorType = DescriptorType.Sampler, + DescriptorCount = 1, + StageFlags = ShaderStageFlags.VertexBit | ShaderStageFlags.FragmentBit, + }; + var create = new DescriptorSetLayoutCreateInfo { SType = StructureType.DescriptorSetLayoutCreateInfo, BindingCount = 1, PBindings = &binding }; + Assert.Equal(Result.Success, _vulkan.Vk.CreateDescriptorSetLayout(_vulkan.Device, &create, null, out var heap)); + var layouts = new List(); + GuestGpuMemoryHook.Attach(harness.Gpu); + try + { + // A draw gives the pipeline state; new modules make every part of the second pipeline compile. + presenter.Run(() => executor.DrawAuto(1, Banks(words), Draw())); + var drawn = Assert.Single(presenter.GetField("_pipelineEntries").Values.Cast() + .Select(entry => entry.GetType().GetField("Description")!.GetValue(entry)).OfType()); + presenter.SetField("_heapSetLayout", heap); + presenter.SetField("LibraryLayoutCreatedForTest", (Action)( + (vertexSet, heapSet, pixelSet) => layouts.Add([vertexSet, heapSet, pixelSet]))); + presenter.Run(() => + { + var description = new GraphicsPipelineDescription + { + Rendering = drawn.Rendering, + VertexInput = drawn.VertexInput, + VertexInfo = drawn.VertexInfo, + VertexProgram = new ShaderProgram(3, host.CreateShaderModule(new VulkanCompiledGuestShader(CreatePositionVertexShader()), + ShaderStage.Vertex, 3, 3)), + VertexStage = FixedProgramProvider.EmptyProgram(ShaderStageKind.Vertex, 3, new ShaderResourceInfo { UsesBindlessHeap = true }, + fetchComponents: 2, userDataRegisters: [0, 1, 2, 3], pushDataStart: PushData.DwordCount), + PixelInfo = drawn.PixelInfo, + PixelProgram = new ShaderProgram(4, host.CreateShaderModule(new VulkanCompiledGuestShader( + SpirvFixedShaders.CreateSolidFragment(1f, 0f, 0f, 1f)), ShaderStage.Pixel, 4, 4)), + PixelStage = FixedProgramProvider.EmptyProgram(ShaderStageKind.Pixel, 4, userDataRegisters: [0, 1, 2, 3], + pushDataStart: PushData.DwordCount), + StaticParameters = drawn.StaticParameters, + }; + host.CreateGraphicsPipeline(description); + }); + + // The pipeline's own layout, its pre-rasterization part's (no pixel set) and its pixel part's (no vertex set). + Assert.Contains(layouts, layout => layout[0].Handle != 0 && layout[2].Handle != 0); + Assert.Contains(layouts, layout => layout[0].Handle != 0 && layout[2].Handle == 0); + Assert.Contains(layouts, layout => layout[0].Handle == 0 && layout[2].Handle != 0); + Assert.All(layouts, layout => Assert.Equal(heap.Handle, layout[1].Handle)); + } + finally + { + GuestGpuMemoryHook.Attach(null); + presenter.SetField("_heapSetLayout", default(DescriptorSetLayout)); + } + + harness.Shutdown(); + _vulkan.Vk.DestroyDescriptorSetLayout(_vulkan.Device, heap, null); + } + + private delegate bool DescriptorsAlreadyBoundCall(CommandBuffer command, PipelineBindPoint bindPoint, PipelineLayout layout, + ReadOnlySpan writes, uint setIndex); + + // A set bound with another pipeline layout disturbs the sets bound before it, so committing the same pixel descriptors + // again binds them again instead of reusing the earlier binding. + [Fact] + public void DescriptorShadow_BindsASetAgainAfterAnotherLayoutBindsASet() + { + var reuse = typeof(SharpEmu.Libs.VideoOut.VulkanVideoPresenter).GetField("NativeStateReuse", + System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic)!; + if (!Ready() || !(bool)reuse.GetValue(null)!) + { + return; + } + + using var presenter = new PresenterUnderTest(_vulkan); + var method = PresenterUnderTest.RecordingHostType.GetMethod("DescriptorsAlreadyBound", PresenterUnderTest.InstanceMembers)!; + var alreadyBound = (DescriptorsAlreadyBoundCall)Delegate.CreateDelegate(typeof(DescriptorsAlreadyBoundCall), presenter.Recording, method); + presenter.Run(() => + { + presenter.InvokeMethod("CurrentRecording"); + var command = presenter.Command; + var info = new DescriptorBufferInfo { Buffer = new Silk.NET.Vulkan.Buffer(1), Offset = 0, Range = 16 }; + ReadOnlySpan writes = + [ + new WriteDescriptorSet + { + SType = StructureType.WriteDescriptorSet, DescriptorType = DescriptorType.StorageBuffer, DescriptorCount = 1, PBufferInfo = &info, + }, + ]; + PipelineLayout first = new(1), second = new(2); + + Assert.False(alreadyBound(command, PipelineBindPoint.Graphics, first, writes, 2)); + Assert.True(alreadyBound(command, PipelineBindPoint.Graphics, first, writes, 2)); + Assert.False(alreadyBound(command, PipelineBindPoint.Graphics, second, writes, 0)); + Assert.False(alreadyBound(command, PipelineBindPoint.Graphics, first, writes, 2)); + + // The bindless heap set binds without a descriptor commit and disturbs the other sets too. + Assert.True(alreadyBound(command, PipelineBindPoint.Graphics, first, writes, 2)); + presenter.InvokeMethod("NoteSetBinding", command, PipelineBindPoint.Graphics, second); + Assert.False(alreadyBound(command, PipelineBindPoint.Graphics, first, writes, 2)); + }); + presenter.Harness.Finish(); + presenter.Harness.Shutdown(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void TwoDraws_RenderTheVertexVersionEachWasRecordedWith(bool libraries) + { + if (!Ready() || (libraries && !_vulkan.SupportsGraphicsPipelineLibrary)) + { + return; + } + + using var presenter = new PresenterUnderTest(_vulkan); + presenter.SetField("_graphicsPipelineLibraries", libraries); presenter.LoadRenderingCommands(); var harness = presenter.Harness; var firstTarget = harness.MapBacked(0x10000, ReadWrite); @@ -729,6 +931,9 @@ public void TwoDraws_RenderTheVertexVersionEachWasRecordedWith() Assert.Equal(Red, Pixel(second, 1, 1)); Assert.Equal(0u, Pixel(second, Size / 2, Size / 2)); Assert.Equal(0u, Pixel(second, Size - 2, Size - 2)); + // Both draws share one pipeline: its vertex input, vertex, pixel and output parts. + var parts = presenter.GetField>("_graphicsLibraries"); + Assert.Equal(libraries ? 4 : 0, parts.Count); } finally { @@ -945,6 +1150,43 @@ public void UploadTransient_TakesAHostBufferWhenTheRingWouldWrapOverThePreparati harness.Shutdown(); } + // A table block too large for a content upload goes to the stream ring; when the ring would wrap over the + // preparation, a host buffer of the draw takes it. + [Fact] + public void TableBlock_TakesAHostBufferWhenTheRingWouldWrapOverThePreparation() + { + if (!Ready()) + { + return; + } + + using var presenter = new PresenterUnderTest(_vulkan); + presenter.LoadRenderingCommands(); + var harness = presenter.Harness; + var stream = harness.Cache.GetUtilityBuffer(GpuBufferUsage.Stream); + var host = presenter.RenderHost; + var upload = host.GetType().GetMethod("UploadTableBlock", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)! + .CreateDelegate(host); + var chunk = new byte[stream.Size / 4]; + var block = new byte[128 * 1024]; + presenter.Run(() => + { + using var preparation = host.BeginPreparation(); + for (var index = 0; index < 4; index++) + { + Assert.Equal(stream.Handle.Handle, host.UploadTransient(chunk, 16).Handle); + } + + var address = upload(block, new ShaderProgramInfo()); + Assert.NotEqual(0UL, address); + Assert.False(address >= stream.DeviceAddress && address < stream.DeviceAddress + stream.Size); + }); + harness.Finish(); + harness.Shutdown(); + } + + private delegate ulong TableBlockUpload(ReadOnlySpan bytes, ShaderProgramInfo program); + // Retained ring bytes force expanded indices into a host buffer; the draw reads it before retirement. [Fact] public void OverflowIndexBuffer_IsConsumedByTheDrawAndRetiredWithIt() diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/ShaderPrewarmPresenterTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/ShaderPrewarmPresenterTests.cs index 1d29005a3..644782fa4 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/ShaderPrewarmPresenterTests.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/ShaderPrewarmPresenterTests.cs @@ -1,8 +1,11 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using System.Collections; using System.Collections.Concurrent; using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; using SharpEmu.Libs.Gpu.Pipelines; using SharpEmu.Libs.Gpu.Rendering; using SharpEmu.Libs.Tests.Gpu.Images; @@ -70,9 +73,89 @@ public void APrewarmRecordBuildsTheDevicePipeline() Assert.Equal(0, presenter.GetField("_shaderPrewarmFailed")); Assert.Equal(1, presenter.GetField("_shaderPrewarmCompiled")); Assert.True(prewarmed.ContainsKey(SharpEmu.Libs.VideoOut.VulkanPipelineCacheStorage.CompiledShaderIdentity(runtime))); + // The pipeline waits for the session's request; teardown destroys it when none came. + var handover = presenter.GetField("_prewarmedComputePipelines"); + Assert.Equal(1, handover.Count); + presenter.InvokeMethod("DestroyPrewarmedComputePipelines"); + Assert.Equal(0, handover.Count); vulkan.AssertNoValidationMessages(); } + // The session's request for the module and layout the prewarm built takes the prewarm's pipeline, with no compile. + [Fact] + public void TheSessionTakesThePrewarmsPipeline() + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan)) return; + + byte[] runtime; + ShaderProgramInfo info; + using (var list = ShaderPrewarmList.Open(_directory)!) + { + var guest = new PipelineTestGuest(Compile); + guest.Host.ShaderPrewarm = list; + guest.RegisterProgram(CodeAddress, HeaderAddress, PipelineTestGuest.FormatLoadProgram); + var cursor = 0u; + guest.Programs.GetOrCompile( + guest.Source(CodeAddress, ShaderStage.Compute, + PipelineTestGuest.BufferDescriptor(BufferAddress, 4, 64, BufferDescriptorWords.Format32UInt)), + PipelineTestGuest.ComputeOptions(threadsX: 64), ref cursor, out var stage); + runtime = Assert.Single(guest.Compiler.Shaders).Spirv; + info = stage.Program!; + } + + using var reloaded = ShaderPrewarmList.Open(_directory)!; + var (record, code) = Assert.Single(reloaded.LoadedComputes()); + using var presenter = new PresenterUnderTest(vulkan); + presenter.SetField("_prewarmedShaderIdentities", new ConcurrentDictionary(StringComparer.Ordinal)); + presenter.InvokeMethod("PrewarmComputePipeline", record, code, new FakeShaderCompiler(Compile), false, true); + var handover = presenter.GetField("_prewarmedComputePipelines"); + Assert.Equal(1, handover.Count); + + var registered = presenter.Run(() => + { + var host = (IShaderPipelineHost)presenter.Instance; + var program = new ShaderProgram(1, host.CreateShaderModule( + new SharpEmu.Libs.Gpu.Vulkan.VulkanCompiledGuestShader(runtime), ShaderStage.Compute, info.Hash, 1)); + return host.TryCreateComputePipeline(new ComputePipelineDescription + { + Program = program, Stage = info, Input = PipelineTestGuest.ComputeOptions(threadsX: 64).ComputeInfo!, + }, out _); + }); + + // A compile would leave the request pending (false) until the next call. + Assert.True(registered); + Assert.Equal(0, handover.Count); + Assert.Equal(1, presenter.GetField("_prewarmedComputeTaken")); + vulkan.AssertNoValidationMessages(); + } + + // A prewarm thread does not wait for the linked admission: while a large linked compile runs, another large one + // is refused at once. + [Fact] + public void ThePrewarmsLinkedAdmissionDoesNotWait() + { + var presenter = RuntimeHelpers.GetUninitializedObject(PresenterUnderTest.PresenterType); + var wait = PresenterUnderTest.PresenterType.GetMethod("WaitForLinkedAdmission", PresenterUnderTest.InstanceMembers)!; + var admission = (SharpEmu.Libs.VideoOut.LinkedCompileAdmission)PresenterUnderTest.PresenterType + .GetField("_linkedCompileAdmission", BindingFlags.Static | BindingFlags.NonPublic)!.GetValue(null)!; + const long large = 8L << 20; + var running = admission.TryAdmit(large, out _, out _); + try + { + var answer = Task.Run(() => (bool)wait.Invoke(presenter, [1UL, large, false])!); + Assert.True(answer.Wait(TimeSpan.FromSeconds(10))); + Assert.False(answer.Result); + } + finally + { + if (running) + { + admission.Release(large); + } + } + } + [Fact] public void Completion_IsCertifiedOnlyByASuccessfulNonemptyCacheSave() { diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/ShaderPrewarmQueueTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/ShaderPrewarmQueueTests.cs new file mode 100644 index 000000000..4daa1ae14 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/ShaderPrewarmQueueTests.cs @@ -0,0 +1,228 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections.Concurrent; +using SharpEmu.Libs.VideoOut; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +// The boot prewarm's shared records: one caller's linked permutations compile one at a time, newest first, and a worker +// never waits on a busy caller while another record is left. +public sealed class ShaderPrewarmQueueTests +{ + // A record: its name and its linked caller (null for a plain record). + private sealed record Item(string Name, ulong? Caller); + + private static ShaderPrewarmQueue Queue(params Item[] items) => new(items, static item => item.Caller); + + private static bool Never() => false; + + private const int Wait = ShaderPrewarmQueue.ReleaseWaitMilliseconds; + + [Fact] + public void EachCallersLinkedRecordsTakeItsPlacesNewestFirst() + { + Item[] items = + [ + new("a-old", 0xA), new("plain1", null), new("b-old", 0xB), new("a-mid", 0xA), new("plain2", null), + new("a-new", 0xA), new("b-new", 0xB), + ]; + + var ordered = ShaderPrewarmQueue.NewestLinkedFirst(items, static item => item.Caller); + + Assert.Equal(new[] { "a-new", "plain1", "b-new", "a-mid", "plain2", "a-old", "b-old" }, + ordered.Select(static item => item.Name)); + } + + // The background lane takes every caller's first record before any second one: the one its session asks for first + // (a-mid, c-new), else the oldest (b-old); then each caller's other records newest first. Slow callers go first within + // a round, then callers in the order first recorded. + [Fact] + public void TheLinkedLaneTakesEachCallersFirstAskedRecordFirstAndSlowCallersFirst() + { + Item[] items = + [ + new("a-old", 0xA), new("b-old", 0xB), new("a-mid", 0xA), new("c-old", 0xC), new("a-new", 0xA), + new("c-new", 0xC), new("b-new", 0xB), + ]; + + var ordered = ShaderPrewarmQueue.LinkedLaneOrder(items, static item => item.Caller!.Value, + static caller => caller == 0xC, static item => item.Name is "a-mid" or "c-new"); + + Assert.Equal(new[] { "c-new", "a-mid", "b-old", "c-old", "a-new", "b-new", "a-old" }, + ordered.Select(static item => item.Name)); + } + + // The lane's queue keeps the lane order. While one worker compiles a caller that takes minutes, a second worker takes the + // next caller's record, not the busy caller's second permutation, which waits until the first is released. + [Fact] + public void ALaneQueueKeepsTheLaneOrderAndASecondWorkerTakesTheNextCaller() + { + Item[] lane = [new("slow-first", 0xA), new("quick", 0xB), new("slow-second", 0xA), new("plain", null)]; + var queue = new ShaderPrewarmQueue(lane, static item => item.Caller, keepOrder: true); + + Assert.True(queue.TryTake(Never, out var first, out var firstGate)); + Assert.Equal("slow-first", first.Name); + Assert.True(queue.TryTake(Never, out var second, out var secondGate, mayWait: false)); + Assert.Equal("quick", second.Name); + queue.Release(secondGate); + Assert.True(queue.TryTake(Never, out var third, out var thirdGate, mayWait: false)); + Assert.Equal("plain", third.Name); + queue.Release(thirdGate); + Assert.False(queue.TryTake(Never, out _, out _, mayWait: false)); + queue.Release(firstGate); + Assert.True(queue.TryTake(Never, out var last, out var lastGate, mayWait: false)); + Assert.Equal("slow-second", last.Name); + queue.Release(lastGate); + Assert.Equal(0, queue.Count); + } + + [Theory] + [InlineData(32, 2)] + [InlineData(16, 2)] + [InlineData(12, 1)] + [InlineData(8, 1)] + [InlineData(1, 1)] + public void TheLinkedLaneRunsASecondWorkerOnlyWithSixteenHardwareThreads(int processorCount, int workers) => + Assert.Equal(workers, ShaderPrewarmQueue.LinkedLaneWorkers(processorCount)); + + // A peek leaves the record in place, and a take without waiting returns at once when every record left waits on a + // busy caller. + [Fact] + public void APeekLeavesTheRecordAndATakeWithoutWaitingReturnsAtOnce() + { + var queue = Queue(new("a-old", 0xA), new("a-new", 0xA)); + Assert.True(queue.TryPeek(out var peeked)); + Assert.Equal("a-new", peeked.Name); + Assert.True(queue.TryTake(Never, out var first, out var gate)); + Assert.Equal("a-new", first.Name); + var watch = System.Diagnostics.Stopwatch.StartNew(); + Assert.False(queue.TryTake(Never, out _, out _, mayWait: false)); + Assert.True(watch.ElapsedMilliseconds < Wait); + Assert.Equal(1, queue.Count); + queue.Release(gate); + Assert.True(queue.TryTake(Never, out var second, out var secondGate, mayWait: false)); + Assert.Equal("a-old", second.Name); + queue.Release(secondGate); + Assert.False(queue.TryPeek(out _)); + } + + [Fact] + public void ABusyCallersRecordGoesBackAndTheNextRecordIsTaken() + { + var queue = Queue(new("a-old", 0xA), new("a-new", 0xA), new("plain", null)); + + Assert.True(queue.TryTake(Never, out var first, out var firstGate)); + Assert.Equal("a-new", first.Name); + Assert.NotNull(firstGate); + + // The caller is busy: a-old goes back and the plain record is taken. + Assert.True(queue.TryTake(Never, out var second, out var secondGate)); + Assert.Equal("plain", second.Name); + Assert.Null(secondGate); + Assert.Equal(1, queue.Count); + Assert.Equal(1, queue.Deferrals); + + queue.Release(firstGate); + Assert.True(queue.TryTake(Never, out var third, out var thirdGate)); + Assert.Equal("a-old", third.Name); + queue.Release(thirdGate); + Assert.False(queue.TryTake(Never, out _, out _)); + } + + [Fact] + public void WhenOnlyBusyCallersAreLeftAWorkerWaitsForTheirReleaseWithoutSpinning() + { + var queue = Queue(new("a-old", 0xA), new("a-new", 0xA), new("b", 0xB)); + Assert.True(queue.TryTake(Never, out var a, out var aGate)); + Assert.True(queue.TryTake(Never, out var b, out var bGate)); + Assert.Equal(("a-new", "b"), (a.Name, b.Name)); + + // Only a-old is left and its caller is busy. + Item? waited = null; + SemaphoreSlim? waitedGate = null; + var worker = new Thread(() => + { + if (queue.TryTake(Never, out var record, out var gate)) (waited, waitedGate) = (record, gate); + }); + var deferrals = queue.Deferrals; + worker.Start(); + Assert.False(worker.Join(3 * Wait)); + Assert.Null(waited); + Assert.Equal(1, queue.Count); + // One pass (two tries of the one record) and no more while it waits. + Assert.InRange(queue.Deferrals - deferrals, 1, 2); + + // Releasing another caller wakes it for one more pass; a-old stays queued. + queue.Release(bGate); + Assert.False(worker.Join(2 * Wait)); + Assert.InRange(queue.Deferrals - deferrals, 2, 4); + + queue.Release(aGate); + Assert.True(worker.Join(TimeSpan.FromSeconds(10))); + Assert.Equal("a-old", waited!.Name); + queue.Release(waitedGate); + Assert.Equal(0, queue.Count); + } + + [Fact] + public void StoppingEndsAWaitAndTakesNothing() + { + var queue = Queue(new("a-old", 0xA), new("a-new", 0xA)); + Assert.True(queue.TryTake(Never, out _, out var gate)); + var stopping = false; + var taken = true; + var worker = new Thread(() => taken = queue.TryTake(() => Volatile.Read(ref stopping), out _, out _)); + worker.Start(); + Assert.False(worker.Join(2 * Wait)); + Volatile.Write(ref stopping, true); + Assert.True(worker.Join(TimeSpan.FromSeconds(10))); + Assert.False(taken); + queue.Release(gate); + } + + [Fact] + public void ManyWorkersTakeEveryRecordOnceAndNeverTwoOfOneCallerAtOnce() + { + var items = new List(); + for (var index = 0; index < 60; index++) + { + items.Add(new($"r{index}", (index % 3) switch { 0 => null, 1 => 0xA, _ => (ulong)(0xB + index % 2) })); + } + + var queue = new ShaderPrewarmQueue(items, static item => item.Caller); + var taken = new ConcurrentBag(); + var running = new ConcurrentDictionary(); + var overlap = 0; + var workers = Enumerable.Range(0, 4).Select(_ => new Thread(() => + { + while (queue.TryTake(Never, out var record, out var gate)) + { + try + { + if (record.Caller is { } caller && running.AddOrUpdate(caller, 1, static (_, count) => count + 1) > 1) + { + Interlocked.Increment(ref overlap); + } + + Thread.Sleep(1); + taken.Add(record.Name); + if (record.Caller is { } done) + { + running.AddOrUpdate(done, 0, static (_, count) => count - 1); + } + } + finally + { + queue.Release(gate); + } + } + })).ToArray(); + foreach (var worker in workers) worker.Start(); + foreach (var worker in workers) Assert.True(worker.Join(TimeSpan.FromSeconds(30))); + + Assert.Equal(0, overlap); + Assert.Equal(items.Select(static item => item.Name).Order(), taken.Order()); + } +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/SliceRecordingTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/SliceRecordingTests.cs index a4ec9ecf9..76ee1fb06 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/SliceRecordingTests.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/SliceRecordingTests.cs @@ -41,6 +41,7 @@ public void UnresolvedDrawsReachTheJoinerInOrderWithoutAllocatingRecordingBuffer SetHostField(host, "_presenter", presenter); SetHostField(host, "_bufferCache", RuntimeHelpers.GetUninitializedObject(typeof(GuestBufferCache))); SetHostField(host, "_arena", new SliceArena(null!, 1)); + SetHostField(host, "_sliceDescriptors", new SharpEmu.Libs.Gpu.Pipelines.SliceDescriptorHeap(null!, null!)); var slice = Activator.CreateInstance(SliceType, nonPublic: true)!; var items = (IList)SliceType.GetField("Items")!.GetValue(slice)!; var itemType = items.GetType().GetGenericArguments()[0]; diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/VulkanGraphicsSubgroupPolicyTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/VulkanGraphicsSubgroupPolicyTests.cs index 46eaa373a..d670e7408 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/VulkanGraphicsSubgroupPolicyTests.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/VulkanGraphicsSubgroupPolicyTests.cs @@ -37,4 +37,21 @@ public void AutomaticGraphicsSubgroupsRequireBothShaderStages(ShaderStageFlags s { Assert.Equal(expected, VulkanGraphicsSubgroupPolicy.ShouldUseNativeGraphicsSubgroups(32, supportedStages, null)); } + + // A forced SHARPEMU_GRAPHICS_SUBGROUPS=1 on a 64-lane device enables graphics subgroups, not pixel reductions. + [Theory] + [InlineData(32u, true, true, true)] + [InlineData(64u, true, true, false)] + [InlineData(32u, false, true, false)] + [InlineData(32u, true, false, false)] + public void PixelSubgroupArithmeticNeedsANative32LaneSubgroup( + uint nativeSubgroupSize, + bool graphicsSubgroups, + bool fragmentArithmetic, + bool expected) + { + Assert.Equal( + expected, + VulkanGraphicsSubgroupPolicy.ShouldUsePixelSubgroupArithmetic(nativeSubgroupSize, graphicsSubgroups, fragmentArithmetic)); + } } diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/VulkanPipelineBinaryTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/VulkanPipelineBinaryTests.cs new file mode 100644 index 000000000..f9e597ac1 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/VulkanPipelineBinaryTests.cs @@ -0,0 +1,310 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections.Concurrent; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.Libs.Tests.Gpu.Vulkan; +using SharpEmu.ShaderCompiler.Vulkan; +using Silk.NET.Core.Native; +using Silk.NET.Vulkan; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +public sealed class VulkanPipelineBinaryTests(HeadlessVulkanFixture fixture) : IClassFixture +{ + [Fact] + public void ASlowBuildIsStoredAndTheNextBuildIsMadeFromItsBinaries() + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan) || BinaryDevice.TryCreate(vulkan) is not { } device) return; + var directory = Path.Combine(Path.GetTempPath(), "SharpEmuTests", Guid.NewGuid().ToString("N")); + using var presenter = new PresenterUnderTest(vulkan); + var harnessDevice = presenter.GetField("_device"); + presenter.SetField("_device", device.Handle); + try + { + presenter.InvokeMethod("InitializePipelineBinaries", directory); + presenter.SetField("_pipelineBinarySlowMilliseconds", 0.0); + presenter.SetField("_sharedPipelineBinaryBytes", int.MaxValue); + using var compute = new ComputeObjects(vulkan.Vk, device.Handle, workGroupWidth: 21); + + compute.Build(presenter); + var files = Directory.GetFiles(directory, "*.bin"); + Assert.Single(files); + Assert.Equal(0, presenter.GetField("_pipelineBinaryLoads")); + compute.Build(presenter); + Assert.Equal(1, presenter.GetField("_pipelineBinaryLoads")); + + // A cut file is refused; the pipeline compiles and writes the file again. + var stored = File.ReadAllBytes(files[0]); + File.WriteAllBytes(files[0], stored[..^4]); + compute.Build(presenter); + Assert.Equal(1, presenter.GetField("_pipelineBinaryLoads")); + Assert.Equal(1, presenter.GetField("_pipelineBinaryRefusals")); + compute.Build(presenter); + Assert.Equal(2, presenter.GetField("_pipelineBinaryLoads")); + + // Another driver's file (a different global key in the first line) is not read. + var otherDriver = File.ReadAllBytes(files[0]); + otherDriver["SharpEmuPB2:".Length] ^= 0x01; + File.WriteAllBytes(files[0], otherDriver); + compute.Build(presenter); + Assert.Equal(2, presenter.GetField("_pipelineBinaryLoads")); + Assert.Equal(1, presenter.GetField("_pipelineBinaryRefusals")); + compute.Build(presenter); + Assert.Equal(3, presenter.GetField("_pipelineBinaryLoads")); + } + finally + { + presenter.SetField("_device", harnessDevice); + device.Dispose(); + if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public void DamagedFilesAreRefusedAndAnotherPipelinesFileIsNotRead() + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan) || BinaryDevice.TryCreate(vulkan) is not { } device) return; + var directory = Path.Combine(Path.GetTempPath(), "SharpEmuTests", Guid.NewGuid().ToString("N")); + using var presenter = new PresenterUnderTest(vulkan); + var harnessDevice = presenter.GetField("_device"); + presenter.SetField("_device", device.Handle); + try + { + presenter.InvokeMethod("InitializePipelineBinaries", directory); + presenter.SetField("_pipelineBinarySlowMilliseconds", 0.0); + presenter.SetField("_sharedPipelineBinaryBytes", int.MaxValue); + using var first = new ComputeObjects(vulkan.Vk, device.Handle, workGroupWidth: 26); + first.Build(presenter); + var file = Assert.Single(Directory.GetFiles(directory, "*.bin")); + var signature = (string)presenter.InvokeMethod("PipelineBinarySignature", Convert.FromHexString(Path.GetFileNameWithoutExtension(file)))!; + var good = File.ReadAllBytes(file); + Assert.True(PipelineCacheSignature.TryUnwrap(signature, good, out var payload)); + + // Payloads with a valid hash that do not hold exactly the binaries they declare: each is refused, then the + // pipeline builds and writes its file again. + var tooMany = payload.ToArray(); + BitConverter.GetBytes(17).CopyTo(tooMany, 0); + var oneMissing = payload.ToArray(); + BitConverter.GetBytes(BitConverter.ToInt32(payload, 0) + 1).CopyTo(oneMissing, 0); + var pastTheEnd = payload.ToArray(); + BitConverter.GetBytes(int.MaxValue).CopyTo(pastTheEnd, 8 + BitConverter.ToInt32(payload, 4)); + var refusals = 0; + foreach (var damaged in new byte[][] { tooMany, oneMissing, pastTheEnd, payload[..^1], [.. payload, 0] }) + { + File.WriteAllBytes(file, PipelineCacheSignature.Wrap(signature, damaged)); + first.Build(presenter); + Assert.Equal(++refusals, presenter.GetField("_pipelineBinaryRefusals")); + Assert.True(PipelineCacheSignature.TryUnwrap(signature, File.ReadAllBytes(file), out _)); + } + + Assert.Equal(0, presenter.GetField("_pipelineBinaryLoads")); + first.Build(presenter); + Assert.Equal(1, presenter.GetField("_pipelineBinaryLoads")); + + // A good file under another pipeline's name is not read. + using var second = new ComputeObjects(vulkan.Vk, device.Handle, workGroupWidth: 27); + second.Build(presenter); + var secondFile = Assert.Single(Directory.GetFiles(directory, "*.bin"), path => path != file); + File.Copy(file, secondFile, overwrite: true); + second.Build(presenter); + Assert.Equal(1, presenter.GetField("_pipelineBinaryLoads")); + Assert.Equal(refusals, presenter.GetField("_pipelineBinaryRefusals")); + second.Build(presenter); + Assert.Equal(2, presenter.GetField("_pipelineBinaryLoads")); + } + finally + { + presenter.SetField("_device", harnessDevice); + device.Dispose(); + if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public void ALargeBinaryIsKeptInTheSharedFolderAndAChangedOneIsWrittenAgain() + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan) || BinaryDevice.TryCreate(vulkan) is not { } device) return; + var directory = Path.Combine(Path.GetTempPath(), "SharpEmuTests", Guid.NewGuid().ToString("N")); + using var presenter = new PresenterUnderTest(vulkan); + var harnessDevice = presenter.GetField("_device"); + presenter.SetField("_device", device.Handle); + try + { + presenter.InvokeMethod("InitializePipelineBinaries", directory); + presenter.SetField("_pipelineBinarySlowMilliseconds", 0.0); + presenter.SetField("_sharedPipelineBinaryBytes", 1); + using var compute = new ComputeObjects(vulkan.Vk, device.Handle, workGroupWidth: 23); + + compute.Build(presenter); + var sharedFiles = Directory.GetFiles(Path.Combine(directory, "shared"), "*.bin"); + Assert.NotEmpty(sharedFiles); + var pipelineFile = Assert.Single(Directory.GetFiles(directory, "*.bin")); + Assert.True(new FileInfo(pipelineFile).Length < sharedFiles.Min(file => new FileInfo(file).Length)); + compute.Build(presenter); + Assert.Equal(1, presenter.GetField("_pipelineBinaryLoads")); + + // A shared binary whose contents no longer match its name is refused once read from disk again; the build + // that follows writes it again. + presenter.GetField>("_sharedPipelineBinaries").Clear(); + var changed = File.ReadAllBytes(sharedFiles[0]); + changed[^1] ^= 0x01; + File.WriteAllBytes(sharedFiles[0], changed); + compute.Build(presenter); + Assert.Equal(1, presenter.GetField("_pipelineBinaryLoads")); + Assert.Equal(1, presenter.GetField("_pipelineBinaryRefusals")); + presenter.GetField>("_sharedPipelineBinaries").Clear(); + compute.Build(presenter); + Assert.Equal(2, presenter.GetField("_pipelineBinaryLoads")); + } + finally + { + presenter.SetField("_device", harnessDevice); + device.Dispose(); + if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true); + } + } + + [Fact] + public void AFastBuildStoresNothingAndAKeyNeedsAFile() + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan) || BinaryDevice.TryCreate(vulkan) is not { } device) return; + var directory = Path.Combine(Path.GetTempPath(), "SharpEmuTests", Guid.NewGuid().ToString("N")); + using var presenter = new PresenterUnderTest(vulkan); + var harnessDevice = presenter.GetField("_device"); + presenter.SetField("_device", device.Handle); + try + { + presenter.InvokeMethod("InitializePipelineBinaries", directory); + presenter.SetField("_pipelineBinarySlowMilliseconds", double.MaxValue); + using var compute = new ComputeObjects(vulkan.Vk, device.Handle, workGroupWidth: 22); + compute.Build(presenter); + compute.Build(presenter); + Assert.False(Directory.Exists(directory) && Directory.GetFiles(directory, "*.bin").Length != 0); + Assert.Equal(0, presenter.GetField("_pipelineBinaryLoads")); + Assert.Equal(0, presenter.GetField("_pipelineBinaryRefusals")); + } + finally + { + presenter.SetField("_device", harnessDevice); + device.Dispose(); + if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true); + } + } + + // A device of its own with VK_KHR_pipeline_binary; null when the driver lacks it. + private sealed unsafe class BinaryDevice : IDisposable + { + private readonly Vk _vk; + + private BinaryDevice(Vk vk, Device handle) + { + _vk = vk; + Handle = handle; + } + + public Device Handle { get; } + + public static BinaryDevice? TryCreate(HeadlessVulkan vulkan) + { + var vk = vulkan.Vk; + uint count = 0; + vk.EnumerateDeviceExtensionProperties(vulkan.Physical, (byte*)null, &count, null); + var properties = new ExtensionProperties[count]; + fixed (ExtensionProperties* pointer = properties) + { + vk.EnumerateDeviceExtensionProperties(vulkan.Physical, (byte*)null, &count, pointer); + } + + var names = properties.Select(property => SilkMarshal.PtrToString((nint)property.ExtensionName)).ToHashSet(); + if (!names.Contains("VK_KHR_pipeline_binary") || !names.Contains("VK_KHR_maintenance5")) + { + return null; + } + + var binaryFeatures = new PhysicalDevicePipelineBinaryFeaturesKHR { SType = StructureType.PhysicalDevicePipelineBinaryFeaturesKhr, PipelineBinaries = true }; + var maintenance5 = new PhysicalDeviceMaintenance5FeaturesKHR { SType = StructureType.PhysicalDeviceMaintenance5FeaturesKhr, Maintenance5 = true, PNext = &binaryFeatures }; + var priority = 1f; + var queueInfo = new DeviceQueueCreateInfo { SType = StructureType.DeviceQueueCreateInfo, QueueFamilyIndex = vulkan.QueueFamily, QueueCount = 1, PQueuePriorities = &priority }; + var extensions = (byte**)SilkMarshal.StringArrayToPtr(["VK_KHR_pipeline_binary", "VK_KHR_maintenance5"]); + try + { + var info = new DeviceCreateInfo + { + SType = StructureType.DeviceCreateInfo, + PNext = &maintenance5, + QueueCreateInfoCount = 1, + PQueueCreateInfos = &queueInfo, + EnabledExtensionCount = 2, + PpEnabledExtensionNames = extensions, + }; + return vk.CreateDevice(vulkan.Physical, &info, null, out var device) == Result.Success + ? new BinaryDevice(vk, device) + : null; + } + finally + { + SilkMarshal.Free((nint)extensions); + } + } + + public void Dispose() => _vk.DestroyDevice(Handle, null); + } + + // A compute program with no resources, built through the presenter's worker compile path with a pipeline cache, as + // production builds are. + private sealed unsafe class ComputeObjects : IDisposable + { + private readonly Vk _vk; + private readonly Device _device; + private readonly ShaderModule _module; + private readonly PipelineLayout _layout; + private readonly PipelineCache _cache; + + public ComputeObjects(Vk vk, Device device, uint workGroupWidth) + { + _vk = vk; + _device = device; + var builder = new SpirvModuleBuilder(); + builder.AddCapability(SpirvCapability.Shader); + var voidType = builder.TypeVoid(); + var main = builder.BeginFunction(voidType, builder.TypeFunction(voidType)); + builder.AddLabel(); + builder.AddStatement(SpirvOp.Return); + builder.EndFunction(); + builder.AddEntryPoint(SpirvExecutionModel.GLCompute, main, "main", []); + builder.AddExecutionMode(main, SpirvExecutionMode.LocalSize, workGroupWidth, 1, 1); + var code = builder.Build(); + fixed (byte* pointer = code) + { + var moduleInfo = new ShaderModuleCreateInfo { SType = StructureType.ShaderModuleCreateInfo, CodeSize = (nuint)code.Length, PCode = (uint*)pointer }; + Assert.Equal(Result.Success, vk.CreateShaderModule(device, &moduleInfo, null, out _module)); + } + + var layoutInfo = new PipelineLayoutCreateInfo { SType = StructureType.PipelineLayoutCreateInfo }; + Assert.Equal(Result.Success, vk.CreatePipelineLayout(device, &layoutInfo, null, out _layout)); + var cacheInfo = new PipelineCacheCreateInfo { SType = StructureType.PipelineCacheCreateInfo }; + Assert.Equal(Result.Success, vk.CreatePipelineCache(device, &cacheInfo, null, out _cache)); + } + + public void Build(PresenterUnderTest presenter) + { + var pipeline = (Pipeline)presenter.InvokeMethod("CompileComputePipeline", _vk, _device, _cache, _module, _layout, 0u)!; + Assert.NotEqual(0ul, pipeline.Handle); + _vk.DestroyPipeline(_device, pipeline, null); + } + + public void Dispose() + { + _vk.DestroyPipelineCache(_device, _cache, null); + _vk.DestroyPipelineLayout(_device, _layout, null); + _vk.DestroyShaderModule(_device, _module, null); + } + } +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/VulkanPipelineLibraryTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/VulkanPipelineLibraryTests.cs new file mode 100644 index 000000000..bb0e535a9 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/VulkanPipelineLibraryTests.cs @@ -0,0 +1,39 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Reflection; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +public sealed class VulkanPipelineLibraryTests +{ + // Pixel modules move their own bindings from set 0 to set 2 when pipelines link from libraries; the bindless heap + // (set 1) and every other instruction stay as they were. + [Fact] + public void WithDescriptorSet_MovesOnlyTheNamedSet() + { + uint[] words = + [ + 0x07230203, 0x00010500, 0, 10, 0, + (4u << 16) | 71, 5, 34, 0, // OpDecorate %5 DescriptorSet 0 + (4u << 16) | 71, 5, 33, 58, // OpDecorate %5 Binding 58 + (4u << 16) | 71, 6, 34, 1, // OpDecorate %6 DescriptorSet 1 + (4u << 16) | 71, 7, 34, 0, // OpDecorate %7 DescriptorSet 0 + (5u << 16) | 43, 1, 8, 34, 0, // OpConstant %1 %8 = 34 0 (looks like a decoration, is not one) + ]; + var code = new byte[words.Length * 4]; + Buffer.BlockCopy(words, 0, code, 0, code.Length); + var method = PresenterUnderTest.PresenterType.GetMethod("WithDescriptorSet", BindingFlags.NonPublic | BindingFlags.Static)!; + + var moved = (byte[])method.Invoke(null, [code, 0u, 2u])!; + + var result = new uint[words.Length]; + Buffer.BlockCopy(moved, 0, result, 0, moved.Length); + var expected = (uint[])words.Clone(); + expected[8] = 2; + expected[20] = 2; + Assert.Equal(expected, result); + Assert.Equal(0u, BitConverter.ToUInt32(code, 8 * 4)); + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5ArrayReadDimensionTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5ArrayReadDimensionTests.cs new file mode 100644 index 000000000..2cb300fce --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5ArrayReadDimensionTests.cs @@ -0,0 +1,117 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Tests.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; + +namespace SharpEmu.ShaderCompiler.Tests; + +// An array read (MIMG dimension 2D array) of a 2D texture, a 2D-array texture or a null descriptor compiles as one +// program: each is bound as an array view. A storage image keeps its T#'s dimension. +public sealed class Gen5ArrayReadDimensionTests +{ + private const ulong ShaderAddress = 0x1_0000_C000; + private const uint Format32Float = 22; + private const uint ImageType2D = 9; + private const uint ImageType2DArray = 13; + private const uint DimensionArray = 5; + + private static (ShaderResourcePlan Plan, ResourceSpecialization Specialization, Gen5ShaderProgram Program) Materialize( + string opcode, uint imageType) + { + // x, y and the slice, then the LOD of a SAMPLE_L or the mip of a LOAD_MIP. + var addressCount = opcode is "ImageSampleL" or "ImageLoadMip" ? 4 : 3; + var control = new Gen5ImageControl(0xF, 0, Enumerable.Range(0, addressCount).Select(static value => (uint)value).ToArray(), 4, 8, 16, + DimensionArray, true, false, false, false, false); + var program = new Gen5ShaderProgram(ShaderAddress, + [ + new Gen5ShaderInstruction(0, Gen5ShaderEncoding.Mimg, opcode, [], [], [], control), + new Gen5ShaderInstruction(8, Gen5ShaderEncoding.Sopp, "SEndpgm", [0xBF810000], [], [], null), + ]); + var plan = ShaderResourcePlan.Extract(program, ShaderStage.Pixel, ResourceTestProgram.Hash, 0, 20); + var userData = new uint[20]; + if (imageType != 0) + { + userData[8] = 0x20; + userData[9] = Format32Float << 20; + userData[11] = imageType << 28; + userData[12] = imageType == ImageType2DArray ? 3u : 0u; + } + + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + Assert.True(ResourceMaterializer.Materialize(plan, ResourceTestProgram.Inputs(userData), ref snapshot, ref specialization)); + return (plan, specialization, program); + } + + private static List Compile(ShaderResourcePlan plan, ResourceSpecialization specialization, Gen5ShaderProgram program) + { + var resources = ResourceMaterializer.ApplyTo(plan, specialization); + var layout = BindingLayout.Allocate(resources.Info, BindingLayout.CollectUserDataRegisters(program, 0, 20), false, + ShaderCompileRequest.RequiresFlattenedTable(plan, resources), false); + var request = new ShaderCompileRequest(plan, resources, layout) + { + PixelOutputs = [new Gen5PixelOutputBinding(0, 0, Gen5PixelOutputKind.Float)], + }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + Gen5MipStatisticsTests.ValidateWhenAvailable(shader.Spirv); + var opcodes = new List(); + for (var index = 20; index + 4 <= shader.Spirv.Length;) + { + var word = BitConverter.ToUInt32(shader.Spirv, index); + opcodes.Add((SpirvOp)(word & 0xFFFF)); + index += (int)(word >> 16) * sizeof(uint); + } + + return opcodes; + } + + [Theory] + [InlineData("ImageSample", ImageType2D)] + [InlineData("ImageSample", ImageType2DArray)] + [InlineData("ImageSample", 0u)] + [InlineData("ImageSampleL", ImageType2D)] + [InlineData("ImageLoad", ImageType2D)] + [InlineData("ImageLoadMip", ImageType2D)] + public void AnArrayReadOfAnyTextureIsCompiledAsAnArrayRead(string opcode, uint imageType) + { + var (plan, specialization, program) = Materialize(opcode, imageType); + + Assert.Equal(ImageDimension.Dim2DArray, Assert.Single(specialization.Images).Dimension); + Compile(plan, specialization, program); + } + + [Fact] + public void AnArrayReadOfA2DTextureAndOfA2DArrayTextureIsOneProgram() + { + var (_, flat, _) = Materialize("ImageSample", ImageType2D); + var (_, array, _) = Materialize("ImageSample", ImageType2DArray); + var (_, unbound, _) = Materialize("ImageSample", 0); + + Assert.Equal(array, flat); + Assert.Equal(array, unbound); + } + + // A fetch past a view's last layer reads zero; the hardware clamps the slice. + [Theory] + [InlineData("ImageLoad", true)] + [InlineData("ImageLoadMip", true)] + [InlineData("ImageSample", false)] + public void AFetchFromAnArrayClampsItsLayer(string opcode, bool clamps) + { + var (plan, specialization, program) = Materialize(opcode, ImageType2D); + + var opcodes = Compile(plan, specialization, program); + Assert.Equal(clamps, opcodes.Contains(SpirvOp.ImageQuerySizeLod)); + } + + [Fact] + public void AStorageImageKeepsItsDescriptorDimension() + { + var (_, specialization, _) = Materialize("ImageStore", ImageType2D); + + Assert.Equal(ImageDimension.Dim2D, Assert.Single(specialization.Images).Dimension); + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5BufferAtomic64Tests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5BufferAtomic64Tests.cs new file mode 100644 index 000000000..d6c621c30 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5BufferAtomic64Tests.cs @@ -0,0 +1,102 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Tests.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.ShaderCompiler.Tests; + +public sealed class Gen5BufferAtomic64Tests +{ + // BUFFER_ATOMIC_SWAP_X2 and OR_X2 are one 64-bit atomic on the GPU. As two dword atomics, a thread group polling another's + // {value, status} pair can read the value of an older update with the status of a newer one. + [Theory] + [InlineData("BufferAtomicSwapX2", SpirvOp.AtomicExchange, false)] + [InlineData("BufferAtomicOrX2", SpirvOp.AtomicOr, false)] + [InlineData("BufferAtomicAndX2", SpirvOp.AtomicAnd, false)] + [InlineData("BufferAtomicSwapX2", SpirvOp.AtomicExchange, true)] + [InlineData("BufferAtomicOrX2", SpirvOp.AtomicOr, true)] + [InlineData("BufferAtomicAndX2", SpirvOp.AtomicAnd, true)] + public void AnX2AtomicIsOne64BitAtomic(string opcode, SpirvOp atomic, bool runtimeDescriptor) + { + var spirv = Compile(X2Program(opcode, runtimeDescriptor), bufferInt64Atomics: true); + + Assert.Contains((uint)SpirvCapability.Int64Atomics, new SpirvModuleInspector(spirv).Capabilities); + Assert.Equal(1, CountAtomics(spirv, atomic, width: 64)); + Gen5MipStatisticsTests.ValidateWhenAvailable(spirv); + } + + // A device without shaderBufferInt64Atomics takes no 64-bit buffer atomic, so the pair stays two dword atomics. + [Theory] + [InlineData("BufferAtomicSwapX2", false)] + [InlineData("BufferAtomicOrX2", true)] + [InlineData("BufferAtomicAndX2", false)] + public void WithoutTheDeviceFeatureAnX2AtomicStaysTwoDwordAtomics(string opcode, bool runtimeDescriptor) + { + var spirv = Compile(X2Program(opcode, runtimeDescriptor), bufferInt64Atomics: false); + + Assert.DoesNotContain((uint)SpirvCapability.Int64Atomics, new SpirvModuleInspector(spirv).Capabilities); + Assert.Equal(0, CountAtomics(spirv, SpirvOp.AtomicExchange, width: 64) + CountAtomics(spirv, SpirvOp.AtomicOr, width: 64) + + CountAtomics(spirv, SpirvOp.AtomicAnd, width: 64)); + } + + // Only a program with an X2 atomic changes with the device feature; every other module stays the same, so no other + // shader compiles again. + [Theory] + [InlineData("BufferAtomicAdd", 1u)] + [InlineData("BufferStoreDwordx2", 2u)] + public void AProgramWithoutAnX2AtomicIsTheSameModuleEitherWay(string opcode, uint dwords) + { + var program = Program(Glc(BufferAccess(0, opcode, 4, dwords: dwords, vectorData: 2)), EndProgram(8)); + + Assert.Equal(Compile(program, bufferInt64Atomics: false), Compile(program, bufferInt64Atomics: true)); + } + + // buffer_atomic__x2 v[2:3], off, s[resource:resource+3], 0 glc. A V# read from a lane-chosen address is a runtime + // descriptor, reached through device addresses. + private static Gen5ShaderProgram X2Program(string opcode, bool runtimeDescriptor) + { + var program = runtimeDescriptor + ? Program(ReadFirstLane(0, 12, 0), MoveScalar(4, 13, 0), ScalarLoad(8, 12, 16, count: 4), + Glc(BufferAccess(16, opcode, 16, dwords: 2, vectorData: 2)), EndProgram(24)) + : Program(Glc(BufferAccess(0, opcode, 4, dwords: 2, vectorData: 2)), EndProgram(8)); + Assert.Equal(runtimeDescriptor, Extract(program).Memory.Find(runtimeDescriptor ? 16u : 0u)!.DeviceDescriptor); + return program; + } + + private static Gen5ShaderInstruction Glc(Gen5ShaderInstruction access) => + access with { Control = ((Gen5BufferMemoryControl)access.Control!) with { Glc = true } }; + + private static byte[] Compile(Gen5ShaderProgram program, bool bufferInt64Atomics) + { + var (plan, resources, layout) = Prepare(program); + var request = new ShaderCompileRequest(plan, resources, layout) { SupportsBufferInt64Atomics = bufferInt64Atomics }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + return shader.Spirv; + } + + // The atomics of one opcode whose result is an integer of the given width. + private static int CountAtomics(byte[] spirv, SpirvOp atomic, uint width) + { + var words = new uint[spirv.Length / sizeof(uint)]; + Buffer.BlockCopy(spirv, 0, words, 0, spirv.Length); + var types = new HashSet(); + var count = 0; + for (var offset = 5; offset < words.Length; offset += Math.Max((int)(words[offset] >> 16), 1)) + { + var opcode = (SpirvOp)(words[offset] & 0xFFFF); + if (opcode == SpirvOp.TypeInt && words[offset + 2] == width) + { + types.Add(words[offset + 1]); + } + else if (opcode == atomic && types.Contains(words[offset + 1])) + { + count++; + } + } + + return count; + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5DataShareRead64Tests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5DataShareRead64Tests.cs index 294a3ba91..07417a35b 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Gen5DataShareRead64Tests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5DataShareRead64Tests.cs @@ -43,6 +43,33 @@ public void EncodedPairedReadHasFourDestinationsAndCompiles( Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out _, out var spirvError), spirvError); } + // DS_READ2ST64_B64 (opcode 0x78) reads the same two pairs at 512-byte offset steps. + [Theory] + [InlineData(false, 0u, 4u)] + [InlineData(true, 1u, 255u)] + public void EncodedStride64PairedReadHasFourDestinationsAndCompilesOnBothBackends(bool global, uint firstOffset, uint secondOffset) + { + var memory = new ShaderMemory(); + uint[] words = [0xD9E00000u | (global ? 1u << 17 : 0) | firstOffset | (secondOffset << 8), 0x03000003, 0xBF810000]; + var bytes = new byte[words.Length * sizeof(uint)]; + for (var index = 0; index < words.Length; index++) + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(index * sizeof(uint)), words[index]); + Assert.True(memory.TryWrite(0x1000, bytes)); + Assert.True(Gen5ShaderTranslator.TryDecodeProgram(new CpuContext(memory, Generation.Gen5), 0x1000, + out var decoded, out var error), error); + + var read = decoded.Instructions[0]; + Assert.Equal("DsRead2St64B64", read.Opcode); + Assert.Equal([Gen5Operand.Vector(3), Gen5Operand.Vector(4), Gen5Operand.Vector(5), Gen5Operand.Vector(6)], read.Destinations); + var control = Assert.IsType(read.Control); + Assert.Equal((firstOffset, secondOffset, global), (control.Offset0, control.Offset1, control.Gds)); + var program = Program(MoveVector(0, 3, SourceAddress), read with { Pc = 4 }, MoveScalar(12, 126, 1), + BufferAccess(16, "BufferStoreDwordx4", 4, dwords: 4, vectorData: 3), EndProgram(24)); + var (plan, resources, layout) = Prepare(program); + var request = new ShaderCompileRequest(plan, resources, layout) { LocalSizeX = 1, ThreadCountX = 1 }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out _, out var spirvError), spirvError); + } + public static uint[] PairedReadExpected(uint firstOffset, uint secondOffset, bool readEnabled) => readEnabled ? [LowerWord ^ firstOffset, UpperWord ^ firstOffset, LowerWord ^ secondOffset, UpperWord ^ secondOffset] : [SourceAddress, UnchangedUpperWord, 0x11112222, 0x33334444]; diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5DeviceBufferFormatStoreTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5DeviceBufferFormatStoreTests.cs new file mode 100644 index 000000000..c3ec188fe --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5DeviceBufferFormatStoreTests.cs @@ -0,0 +1,33 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Tests.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.ShaderCompiler.Tests; + +public sealed class Gen5DeviceBufferFormatStoreTests +{ + // A V# read from a lane-chosen address is a runtime descriptor; its format is known only when the shader runs. + [Theory] + [InlineData(1u)] + [InlineData(4u)] + public void AFormattedStoreThroughARuntimeDescriptorCompiles(uint components) + { + var program = Program( + ReadFirstLane(0, 12, 0), + MoveScalar(4, 13, 0), + ScalarLoad(8, 12, 16, count: 4), + BufferStore(16, 16, dwords: components, formatted: true), + EndProgram(24)); + Assert.True(Extract(program).Memory.Find(16)!.DeviceDescriptor); + var request = Request(program); + + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + var module = new SpirvModuleInspector(shader.Spirv); + Assert.Contains((ushort)SpirvOp.AtomicCompareExchange, module.Opcodes); + Gen5MipStatisticsTests.ValidateWhenAvailable(shader.Spirv); + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5Float16ArithmeticTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5Float16ArithmeticTests.cs index 47083fb69..82c4ce09d 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Gen5Float16ArithmeticTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5Float16ArithmeticTests.cs @@ -140,10 +140,48 @@ public void CompactFloat16ArithmeticDecodesAndCompilesWithoutNativeFloat16() Assert.Contains((ushort)SpirvOp.FAdd, opcodes); Assert.Contains((ushort)SpirvOp.FSub, opcodes); Assert.Contains((ushort)SpirvOp.FMul, opcodes); - Assert.True(opcodes.Count(opcode => opcode == (ushort)SpirvOp.ExtInst) >= 3); + // The reciprocal square root and the maximum are GLSL instructions. + Assert.True(opcodes.Count(opcode => opcode == (ushort)SpirvOp.ExtInst) >= 2); Assert.DoesNotContain((ushort)SpirvCapability.Float16, ReadCapabilities(shader.Spirv)); } + // With NativeFloat16Conversions v_rcp_f16 widens its operand and narrows its result with OpFConvert, and the module declares + // 16-bit floats with the float controls of the conversions (round-to-nearest-even, denormals and NaN kept, three execution + // modes beside LocalSize). + [Fact] + public void NativeFloat16ConversionsDeclareTheirFloatControls() + { + var (plan, resources, layout) = ResourceTestProgram.Prepare(Decode([0x7E000000u | (0x54u << 9) | 257u, SEndpgm]), userDataCount: 0); + var request = new ShaderCompileRequest(plan, resources, layout) { NativeFloat16Conversions = true }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + var opcodes = ReadOpcodes(shader.Spirv); + Assert.Equal(2, opcodes.Count(opcode => opcode == (ushort)SpirvOp.FConvert)); + Assert.Equal(4, opcodes.Count(opcode => opcode == (ushort)SpirvOp.ExecutionMode)); + Assert.Superset( + new HashSet([(ushort)SpirvCapability.Float16, (ushort)SpirvCapability.DenormPreserve, + (ushort)SpirvCapability.RoundingModeRte, (ushort)SpirvCapability.SignedZeroInfNanPreserve]), + ReadCapabilities(shader.Spirv).ToHashSet()); + } + + // With NativeFloat16Conversions v_add_f16 adds its halves as an f16 OpFAdd, without a conversion, where the f32 forms keep + // signed zero and NaN; without SignedZeroInfNanPreserve for 32 bits it keeps the f32 add between conversions. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void NativeFloat16AddStaysInHalves(bool preserveNan) + { + var (plan, resources, layout) = ResourceTestProgram.Prepare(Decode([0x64000501, SEndpgm]), userDataCount: 0); + var request = new ShaderCompileRequest(plan, resources, layout) + { + NativeFloat16Conversions = true, ShaderSignedZeroInfNanPreserveFloat32Supported = preserveNan, + }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + var opcodes = ReadOpcodes(shader.Spirv); + Assert.Equal(preserveNan ? 0 : 3, opcodes.Count(opcode => opcode == (ushort)SpirvOp.FConvert)); + Assert.Equal(1, opcodes.Count(opcode => opcode == (ushort)SpirvOp.FAdd)); + Assert.Contains((ushort)SpirvCapability.Float16, ReadCapabilities(shader.Spirv)); + } + [Theory] [InlineData(0x54u, "VRcpF16")] [InlineData(0x55u, "VSqrtF16")] @@ -233,7 +271,10 @@ public void Vop3Float16FmaDecodesAndCompiles() Assert.True( Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); - Assert.Contains((ushort)SpirvOp.ExtInst, ReadOpcodes(shader.Spirv)); + // The product and the sum of the round-to-odd fma. + var opcodes = ReadOpcodes(shader.Spirv); + Assert.Contains((ushort)SpirvOp.FMul, opcodes); + Assert.Contains((ushort)SpirvOp.FAdd, opcodes); Assert.DoesNotContain((ushort)SpirvCapability.Float16, ReadCapabilities(shader.Spirv)); } diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5ImageTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5ImageTests.cs index 01bbecac9..a60483290 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Gen5ImageTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5ImageTests.cs @@ -231,6 +231,47 @@ public void UintImageStoreUsesUintTexelAndInverseDescriptorSwizzle() Assert.Equal([6, 5, 4, 7], GetStoredVgprRegisters(spirv)); } + // With storage image selects as shader data, every select compiles to one module, whose store reads its channel map. + [Theory] + [InlineData("ImageStore", 0xFu, 71u)] + [InlineData("ImageStore", 0x5u, 71u)] + [InlineData("ImageStoreMip", 0xFu, 71u)] + [InlineData("ImageStore", 0xFu, 69u)] // FORMAT_16_16_16_16_UINT + public void RuntimeSwizzleStoresOfEverySelectShareOneModule(string opcode, uint dmask, uint unifiedFormat) + { + var selects = new[] { 0xFACu, 0x9F5u, 0xF2Eu, 0x3ACu, 0xFA4u, 0x204u, 0x924u, 0x000u }; + var modules = selects.Select(select => CompileImageOperation(opcode, dimension: 1, dmask, select, unifiedFormat, + runtimeImageSwizzles: true)).ToArray(); + foreach (var module in modules.Skip(1)) + { + Assert.Equal(modules[0], module); + } + + var request = ImageOperationRequest(opcode, dimension: 1, dmask, 0x9F5u, unifiedFormat, runtimeImageSwizzles: true); + Assert.Equal(1u, request.Bindings.StorageImageSwizzleCount); + Assert.Equal(DescriptorConstants.IdentityImageSwizzle, Assert.Single(request.Resources.Info.Images).ShaderSwizzle); + var instructions = ReadSpirvInstructions(modules[0]); + Assert.Equal(4, instructions.Count(item => item.Opcode == SpirvOp.VectorExtractDynamic)); + Assert.Single(instructions, item => item.Opcode == SpirvOp.ImageWrite); + } + + // A function decodes the map once, in its entry block; each further store adds a pick and a select per channel. + [Fact] + public void RuntimeSwizzleStoresShareTheMapDecode() + { + var one = ReadSpirvInstructions(CompileImageOperation("ImageStore", dimension: 1, 0xF, 0xF2E, runtimeImageSwizzles: true)); + var two = ReadSpirvInstructions(CompileImageOperation("ImageStore", dimension: 1, 0xF, 0xF2E, runtimeImageSwizzles: true, + instructions: 2)); + int Count(IReadOnlyList module, SpirvOp opcode) => module.Count(item => item.Opcode == opcode); + Assert.Equal(2, Count(two, SpirvOp.ImageWrite)); + Assert.Equal(8, Count(two, SpirvOp.VectorExtractDynamic)); + Assert.Equal(Count(one, SpirvOp.Select) + 4, Count(two, SpirvOp.Select)); + foreach (var decode in new[] { SpirvOp.BitFieldUExtract, SpirvOp.BitwiseXor, SpirvOp.ULessThan }) + { + Assert.Equal(Count(one, decode), Count(two, decode)); + } + } + private static byte[] CompileImageOperation( string opcode, uint dimension, @@ -240,9 +281,12 @@ private static byte[] CompileImageOperation( uint samplerWord0 = 0u, uint samplerWord2 = 0u, uint? descriptorType = null, - bool arrayed = false) + bool arrayed = false, + bool runtimeImageSwizzles = false, + int instructions = 1) { - var request = ImageOperationRequest(opcode, dimension, dmask, dstSelect, unifiedFormat, samplerWord0, samplerWord2, descriptorType, arrayed); + var request = ImageOperationRequest(opcode, dimension, dmask, dstSelect, unifiedFormat, samplerWord0, samplerWord2, descriptorType, arrayed, + runtimeImageSwizzles, instructions); Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); return shader.Spirv; } @@ -256,7 +300,9 @@ private static ShaderCompileRequest ImageOperationRequest( uint samplerWord0 = 0u, uint samplerWord2 = 0u, uint? descriptorType = null, - bool arrayed = false) + bool arrayed = false, + bool runtimeImageSwizzles = false, + int instructions = 1) { var coordinateCount = dimension == 2 || arrayed ? 3 : 2; var addressCount = coordinateCount + @@ -277,24 +323,26 @@ private static ShaderCompileRequest ImageOperationRequest( Slc: false, A16: false, D16: false); - var imageInstruction = new Gen5ShaderInstruction( - 0, + // Each further instruction reads its data from the next four registers. + var imageInstructions = Enumerable.Range(0, instructions).Select(index => new Gen5ShaderInstruction( + (uint)index * 8, Gen5ShaderEncoding.Mimg, opcode, [], [], [], - control); + control with { VectorData = 4 + (uint)index * 4 })); var end = new Gen5ShaderInstruction( - 8, + (uint)instructions * 8, Gen5ShaderEncoding.Sopp, "SEndpgm", [SEndpgm], [], [], null); - var program = new Gen5ShaderProgram(ShaderAddress, [imageInstruction, end]); - var plan = ShaderResourcePlan.Extract(program, ShaderStage.Compute, ResourceTestProgram.Hash, 0, 20); + var program = new Gen5ShaderProgram(ShaderAddress, [.. imageInstructions, end]); + var plan = ShaderResourcePlan.Extract(program, ShaderStage.Compute, ResourceTestProgram.Hash, 0, 20, + runtimeImageSwizzles: runtimeImageSwizzles); var userData = new uint[20]; userData[8] = 0x20; userData[9] = unifiedFormat << 20; @@ -428,10 +476,11 @@ private static void AssertCoordinateVectorWidth( instructions, item => item.Opcode == operation); var coordinateId = imageOperation.Operands[coordinateOperand]; + // A fetch from an array ends its coordinates with the clamped layer. var coordinate = Assert.Single( instructions, item => - item.Opcode == SpirvOp.CompositeConstruct && + item.Opcode is SpirvOp.CompositeConstruct or SpirvOp.CompositeInsert && item.Operands.Length >= 2 && item.Operands[1] == coordinateId); AssertVectorTypeWidth( diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5MeshShaderTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5MeshShaderTests.cs index c44a79ecc..556efd6a3 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Gen5MeshShaderTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5MeshShaderTests.cs @@ -16,6 +16,223 @@ public sealed class Gen5MeshShaderTests public void IndirectMeshPreparationValidates() => ValidateWithInstalledSdk(SpirvMeshIndirect.Create()); + [Fact] + public void TaskStageValidates() + => ValidateWithInstalledSdk(SpirvMeshTask.Create()); + + // The task stage's host interface: one TaskEXT invocation, eight push words after the shared push + // data, five specialization constants with their defaults, and one emit that passes the payload. + [Fact] + public void TaskStageDeclaresItsHostInterface() + { + var spirv = SpirvMeshTask.Create(); + var module = ReadInstructions(spirv); + var inspector = new SpirvModuleInspector(spirv); + Assert.Equal(new[] { SpirvCapability.Shader, SpirvCapability.Int64, SpirvCapability.PhysicalStorageBufferAddresses, + SpirvCapability.MeshShadingExt }.Select(capability => (uint)capability).Order(), inspector.Capabilities.Order()); + Assert.Equal(5348u, inspector.AddressingModel); + var entryPoint = Assert.Single(module, instruction => instruction.Op == SpirvOp.EntryPoint); + Assert.Equal((uint)SpirvExecutionModel.TaskExt, entryPoint.Operands[0]); + Assert.Equal(new uint[] { (uint)SpirvExecutionMode.LocalSize, 1, 1, 1 }, + Assert.Single(module, instruction => instruction.Op == SpirvOp.ExecutionMode).Operands[1..]); + + Assert.Equal(128u, SpirvMeshTask.PushOffsetBytes); + var push = Assert.Single(module, instruction => instruction.Op == SpirvOp.Variable && + instruction.Operands[2] == (uint)SpirvStorageClass.PushConstant); + Assert.Contains(push.Operands[1], EntryPointInterface(entryPoint)); + var block = PointeeType(module, push.Operands[0]); + Assert.Equal(new[] { block.Operands[0], 0u, (uint)SpirvDecoration.Offset, SpirvMeshTask.PushOffsetBytes }, + Assert.Single(module, instruction => instruction.Op == MemberDecorate && instruction.Operands[0] == block.Operands[0]).Operands); + var constants = Constants(module); + var words = Assert.Single(module, instruction => instruction.Op == SpirvOp.TypeArray && instruction.Operands[0] == block.Operands[1]); + Assert.Equal(SpirvMeshTask.PushWordCount, constants[words.Operands[2]]); + Assert.Equal(Enumerable.Range(0, (int)SpirvMeshTask.PushWordCount).Select(word => (ulong)word), + module.Where(instruction => instruction.Op == SpirvOp.AccessChain && instruction.Operands[2] == push.Operands[1]) + .Select(instruction => constants[instruction.Operands[^1]]).Order()); + + var specIds = module.Where(instruction => instruction.Op == SpirvOp.Decorate && instruction.Operands[1] == (uint)SpirvDecoration.SpecId) + .ToDictionary(instruction => instruction.Operands[0], instruction => instruction.Operands[2]); + Assert.Equal(new[] + { + (SpirvMeshTask.SpecPrimitivesPerGroup, 1u), (SpirvMeshTask.SpecPointList, 0u), (SpirvMeshTask.SpecMaxGroupCountX, 1u), + (SpirvMeshTask.SpecMaxGroupCountY, 1u), (SpirvMeshTask.SpecMaxGroupTotalCount, 1u), + }, + module.Where(instruction => instruction.Op == SpirvOp.SpecConstant) + .Select(instruction => (specIds[instruction.Operands[1]], instruction.Operands[2])).Order()); + + var payload = Assert.Single(module, instruction => instruction.Op == SpirvOp.Variable && + instruction.Operands[2] == (uint)SpirvStorageClass.TaskPayloadWorkgroupExt); + var emit = Assert.Single(module, instruction => instruction.Op == SpirvOp.EmitMeshTasksExt); + Assert.Equal(4, emit.Operands.Length); + Assert.Equal(payload.Operands[1], emit.Operands[3]); + Assert.Equal(Enumerable.Repeat((32u, 0u), (int)SpirvMeshTask.PayloadWordCount), TaskPayloadMembers(module)); + } + + // Each argument merges a device load, which only a nonzero address reaches, with push word 4 to 7, + // so the arguments of a draw without an address read no memory. + [Fact] + public void TaskStageReadsPushedArgumentsWithoutAnAddress() + { + var module = ReadInstructions(SpirvMeshTask.Create()); + var constants = Constants(module); + var values = module.Where(instruction => instruction.Op is SpirvOp.Load or SpirvOp.AccessChain or SpirvOp.ConvertUToPtr or + SpirvOp.INotEqual or SpirvOp.IAdd).ToDictionary(instruction => instruction.Operands[1]); + var push = Assert.Single(module, instruction => instruction.Op == SpirvOp.Variable && + instruction.Operands[2] == (uint)SpirvStorageClass.PushConstant).Operands[1]; + bool IsDeviceLoad(SpirvInstruction instruction) => instruction.Op == SpirvOp.Load && + values.TryGetValue(instruction.Operands[2], out var pointer) && pointer.Op == SpirvOp.ConvertUToPtr; + + var entry = module.First(instruction => instruction.Op == SpirvOp.Label).Operands[0]; + var branch = Assert.Single(module, instruction => instruction.Op == SpirvOp.BranchConditional && instruction.Block == entry); + var (condition, read, merge) = (values[branch.Operands[0]], branch.Operands[1], branch.Operands[2]); + Assert.Equal(SpirvOp.INotEqual, condition.Op); + Assert.Equal(0ul, constants[condition.Operands[3]]); + Assert.Equal(4, module.Count(IsDeviceLoad)); + Assert.All(module.Where(IsDeviceLoad), load => Assert.Equal(read, load.Block)); + var phis = module.Where(instruction => instruction.Op == SpirvOp.Phi).ToList(); + Assert.Equal(4, phis.Count); + for (var index = 0; index < phis.Count; index++) + { + Assert.Equal(merge, phis[index].Block); + var incoming = phis[index].Operands[2..].Chunk(2).ToDictionary(pair => pair[1], pair => values[pair[0]]); + Assert.Equal(2, incoming.Count); + var loaded = incoming[read]; + Assert.True(IsDeviceLoad(loaded)); + Assert.Equal(new uint[] { 2, 4 }, loaded.Operands[3..]); + // The first argument is read at the address itself: its "+ 0" folds away. + var target = values[loaded.Operands[2]].Operands[2]; + if (index == 0) + { + Assert.Equal(condition.Operands[2], target); + } + else + { + var address = values[target]; + Assert.Equal(condition.Operands[2], address.Operands[2]); + Assert.Equal((ulong)index * 4, constants[address.Operands[3]]); + } + var pushed = values[incoming[entry].Operands[2]]; + Assert.Equal(push, pushed.Operands[2]); + Assert.Equal((ulong)index + 4, constants[pushed.Operands[^1]]); + } + } + + // A task-launched mesh shader takes its draw parameters from the payload the task stage declares and + // reads none of them from the shader data, in each wave arrangement. Left off, the module is unchanged. + [Theory] + [InlineData(32u, 32u, 0u)] + [InlineData(32u, 32u, 32u)] + [InlineData(64u, 192u, 32u)] + [InlineData(64u, 64u, 64u)] + public void TaskLaunchedMeshReadsItsDrawParametersFromThePayload(uint waveSize, uint localSize, uint hostSubgroupSize) + { + var (plan, resources, layout) = ResourceTestProgram.Prepare(AllocatingMeshProgram(), ShaderStage.Mesh, userDataCount: 0); + var mesh = new MeshShaderConfiguration(localSize, 16, 0, 8, 24, 0, DeviceSubgroupLaneCount: hostSubgroupSize); + byte[] Compile(MeshShaderConfiguration configuration) + { + var request = new ShaderCompileRequest(plan, resources, layout) + { + WaveSize = waveSize, LocalSizeX = localSize, Mesh = configuration, + }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + return shader.Spirv; + } + var shaderData = Compile(mesh); + Assert.Equal(shaderData, Compile(mesh with { TaskLaunched = false })); + var task = Compile(mesh with { TaskLaunched = true }); + + Assert.True(layout.UsesPushData); + var parameters = Enumerable.Range(0, 6) + .Select(index => (ulong)(layout.PushDataStartDword + layout.MeshDrawParametersDword) + (ulong)index).ToHashSet(); + Assert.True(PushDataReads(shaderData, parameters) >= parameters.Count); + Assert.Equal(0, PushDataReads(task, parameters)); + Assert.False(new SpirvModuleInspector(shaderData).HasVariableInStorageClass(SpirvStorageClass.TaskPayloadWorkgroupExt)); + // The validator checks each stage alone, so the payload the two stages share is compared here. + Assert.Equal(TaskPayloadMembers(ReadInstructions(SpirvMeshTask.Create())), TaskPayloadMembers(ReadInstructions(task))); + ValidateWithInstalledSdk(task); + } + + // An allocating mesh program with a position and a primitive export. + private static Gen5ShaderProgram AllocatingMeshProgram() => new(0, + [ + new Gen5ShaderInstruction(0, Gen5ShaderEncoding.Sop1, "SMovB32", [0], + [Gen5Operand.Source(131)], [Gen5Operand.Scalar(124)], null), + new Gen5ShaderInstruction(4, Gen5ShaderEncoding.Sopp, "SSendmsg", [0xBF900009], [], [], null), + new Gen5ShaderInstruction(8, Gen5ShaderEncoding.Exp, "Exp", [0, 0], + [Gen5Operand.Vector(0), Gen5Operand.Vector(1), Gen5Operand.Vector(2), Gen5Operand.Vector(3)], [], + new Gen5ExportControl(12, 15, false, false, false)), + new Gen5ShaderInstruction(16, Gen5ShaderEncoding.Exp, "Exp", [0, 0], + [Gen5Operand.Vector(4), Gen5Operand.Vector(4), Gen5Operand.Vector(4), Gen5Operand.Vector(4)], [], + new Gen5ExportControl(20, 1, false, true, false)), + new Gen5ShaderInstruction(24, Gen5ShaderEncoding.Sopp, "SEndpgm", [0xBF810000], [], [], null), + ]); + + private const SpirvOp MemberDecorate = (SpirvOp)72; + + // One instruction of a module: its opcode, its operand words and the label of the block it is in. + private readonly record struct SpirvInstruction(SpirvOp Op, uint[] Operands, uint Block); + + private static List ReadInstructions(byte[] spirv) + { + var words = new uint[spirv.Length / sizeof(uint)]; + Buffer.BlockCopy(spirv, 0, words, 0, spirv.Length); + var instructions = new List(); + var block = 0u; + for (var offset = 5; offset < words.Length; offset += (int)(words[offset] >> 16)) + { + var op = (SpirvOp)(words[offset] & 0xffff); + var operands = words[(offset + 1)..(offset + (int)(words[offset] >> 16))]; + if (op == SpirvOp.Label) block = operands[0]; + instructions.Add(new SpirvInstruction(op, operands, block)); + } + return instructions; + } + + // The integer constants of a module by id, 64-bit ones included. + private static Dictionary Constants(List module) => + module.Where(instruction => instruction.Op == SpirvOp.Constant).ToDictionary(instruction => instruction.Operands[1], + instruction => instruction.Operands.Length > 3 ? instruction.Operands[2] | (ulong)instruction.Operands[3] << 32 : instruction.Operands[2]); + + private static SpirvInstruction PointeeType(List module, uint pointerType) + { + var pointer = Assert.Single(module, instruction => instruction.Op == SpirvOp.TypePointer && instruction.Operands[0] == pointerType); + return Assert.Single(module, instruction => instruction.Op is >= SpirvOp.TypeVoid and <= SpirvOp.TypeFunction && + instruction.Operands[0] == pointer.Operands[2]); + } + + // The interface of an entry point: the ids after its nul-terminated name. + private static uint[] EntryPointInterface(SpirvInstruction entryPoint) + { + var name = 2; + while (entryPoint.Operands[name] >> 24 != 0) name++; + return entryPoint.Operands[(name + 1)..]; + } + + // The members of a module's task payload as (width, signedness). Its variable is in the entry point's + // interface, and the payload type has no decorations. + private static (uint Width, uint Signedness)[] TaskPayloadMembers(List module) + { + var payload = Assert.Single(module, instruction => instruction.Op == SpirvOp.Variable && + instruction.Operands[2] == (uint)SpirvStorageClass.TaskPayloadWorkgroupExt); + Assert.Contains(payload.Operands[1], EntryPointInterface(Assert.Single(module, instruction => instruction.Op == SpirvOp.EntryPoint))); + var structure = PointeeType(module, payload.Operands[0]); + Assert.Equal(SpirvOp.TypeStruct, structure.Op); + Assert.DoesNotContain(module, instruction => instruction.Op is SpirvOp.Decorate or MemberDecorate && + instruction.Operands[0] == structure.Operands[0]); + return [.. structure.Operands[1..].Select(member => Assert.Single(module, instruction => instruction.Op == SpirvOp.TypeInt && + instruction.Operands[0] == member)).Select(type => (type.Operands[1], type.Operands[2]))]; + } + + // The number of reads of the given push data dwords. + private static int PushDataReads(byte[] spirv, IReadOnlySet dwords) + { + var module = ReadInstructions(spirv); + var constants = Constants(module); + var pushData = new SpirvModuleInspector(spirv).Names.Single(name => name.Value == "pushData").Key; + return module.Count(instruction => instruction.Op == SpirvOp.AccessChain && instruction.Operands[2] == pushData && + constants.TryGetValue(instruction.Operands[^1], out var dword) && dwords.Contains(dword)); + } + [Theory] [InlineData(null, 11, 41984ul)] [InlineData(1501u, 8, 32768ul)] @@ -317,7 +534,8 @@ public void DppShufflePreservesTheNativeSubgroupLaneRange(uint waveSize, uint ho Assert.Equal(expectedMask, laneMasks[words[offset + 5]]); shuffleCount++; } - Assert.True(shuffleCount >= 2); + // A wave32 DPP16 source reads the guest EXEC of its lane from a ballot, not from a second shuffle. + Assert.True(shuffleCount >= (operation == "dpp" && waveSize == 32 ? 1 : 2)); ValidateWithInstalledSdk(shader.Spirv); } @@ -553,6 +771,64 @@ public void MeshProgramDeclaresOutputsAndAllocation() ValidateWithInstalledSdk(shader.Spirv); } + // A primitive export packs three 9-bit vertex indices at bits 0, 10 and 20; bit 9 of each field is the vertex's + // edge flag, so a set edge flag must not move the index past 511. + [Fact] + public void PrimitiveExportIndicesLeaveOutTheEdgeFlags() + { + var program = new Gen5ShaderProgram(0, + [ + new Gen5ShaderInstruction(0, Gen5ShaderEncoding.Sop1, "SMovB32", [0], + [Gen5Operand.Source(131)], [Gen5Operand.Scalar(124)], null), + new Gen5ShaderInstruction(4, Gen5ShaderEncoding.Sopp, "SSendmsg", [0xBF900009], + [], [], null), + new Gen5ShaderInstruction(8, Gen5ShaderEncoding.Exp, "Exp", [0, 0], + [Gen5Operand.Vector(0), Gen5Operand.Vector(1), + Gen5Operand.Vector(2), Gen5Operand.Vector(3)], [], + new Gen5ExportControl(12, 15, false, false, false)), + new Gen5ShaderInstruction(16, Gen5ShaderEncoding.Exp, "Exp", [0, 0], + [Gen5Operand.Vector(4), Gen5Operand.Vector(4), + Gen5Operand.Vector(4), Gen5Operand.Vector(4)], [], + new Gen5ExportControl(20, 1, false, true, false)), + new Gen5ShaderInstruction(24, Gen5ShaderEncoding.Sopp, "SEndpgm", [0xBF810000], + [], [], null), + ]); + var (plan, resources, layout) = ResourceTestProgram.Prepare( + program, ShaderStage.Mesh, userDataCount: 0); + var request = new ShaderCompileRequest(plan, resources, layout) + { + WaveSize = 32, + LocalSizeX = 32, + Mesh = new MeshShaderConfiguration(32, 16, 0, 8, 24, 0), + }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + + var words = new uint[shader.Spirv.Length / 4]; + Buffer.BlockCopy(shader.Spirv, 0, words, 0, shader.Spirv.Length); + var constants = new Dictionary(); + var extracts = new List<(uint Offset, uint Count)>(); + for (var index = 5; index < words.Length; index += (int)(words[index] >> 16)) + { + var opcode = (SpirvOp)(words[index] & 0xFFFF); + if (opcode == SpirvOp.Constant && words[index] >> 16 == 4) + constants[words[index + 2]] = words[index + 3]; + else if (opcode == SpirvOp.BitFieldUExtract) + extracts.Add((words[index + 4], words[index + 5])); + } + + var fields = extracts.Select(extract => + (Offset: constants.GetValueOrDefault(extract.Offset, uint.MaxValue), + Count: constants.GetValueOrDefault(extract.Count, uint.MaxValue))).ToList(); + // (0, 10) also decodes the vertex count of the GS allocation request, so only fields 1 and 2 tell the old width. + foreach (var offset in new[] { 0u, 10u, 20u }) + { + Assert.Contains((offset, 9u), fields); + } + + Assert.DoesNotContain((10u, 10u), fields); + Assert.DoesNotContain((20u, 10u), fields); + } + private sealed class MeshFixtureTheoryAttribute : TheoryAttribute { public MeshFixtureTheoryAttribute() diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5NonTessellationSpirvStabilityTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5NonTessellationSpirvStabilityTests.cs index f7093d8cc..f1ce6089b 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Gen5NonTessellationSpirvStabilityTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5NonTessellationSpirvStabilityTests.cs @@ -13,21 +13,21 @@ namespace SharpEmu.ShaderCompiler.Tests; public sealed class Gen5NonTessellationSpirvStabilityTests { [Theory] - [InlineData("lds-readback", ShaderStage.Vertex, 64u, "9BCF02647F837E55")] - [InlineData("lds-readback", ShaderStage.Vertex, 32u, "BF4344E36DEA217E")] - [InlineData("lds-readback", ShaderStage.Pixel, 64u, "D576CD6C4222535C")] - [InlineData("lds-readback", ShaderStage.Pixel, 32u, "CB5C1CDED8103BC2")] - [InlineData("lds-readback", ShaderStage.Compute, 64u, "51DC6ACDCA96B659")] - [InlineData("lds-readback", ShaderStage.Compute, 32u, "7461E219AEAFAC53")] - [InlineData("lds-staging-export", ShaderStage.Vertex, 64u, "D6060044105BFC27")] - [InlineData("lds-staging-export", ShaderStage.Vertex, 32u, "02D77B4078336EDC")] - [InlineData("lds-barrier", ShaderStage.Compute, 64u, "6002AC8936414DF5")] - [InlineData("lds-barrier", ShaderStage.Compute, 32u, "FC521693C8309CEE")] - [InlineData("divergent", ShaderStage.Vertex, 64u, "4075CAB9F922B279")] - [InlineData("divergent", ShaderStage.Pixel, 32u, "143C3C99F37CBD63")] - [InlineData("divergent", ShaderStage.Compute, 64u, "341B4840D46530B4")] - [InlineData("image-load", ShaderStage.Pixel, 64u, "FAE742FAEE7FE228")] - [InlineData("image-load", ShaderStage.Compute, 32u, "E725B8040EEACCDD")] + [InlineData("lds-readback", ShaderStage.Vertex, 64u, "5EBAF2623DFC2562")] + [InlineData("lds-readback", ShaderStage.Vertex, 32u, "07442FCECCA2DDCE")] + [InlineData("lds-readback", ShaderStage.Pixel, 64u, "EDCA97979AFF99D0")] + [InlineData("lds-readback", ShaderStage.Pixel, 32u, "FBA897766E85B5FA")] + [InlineData("lds-readback", ShaderStage.Compute, 64u, "CF076D8E6E250868")] + [InlineData("lds-readback", ShaderStage.Compute, 32u, "2D0F02D45D20526C")] + [InlineData("lds-staging-export", ShaderStage.Vertex, 64u, "BE08A4A73684E389")] + [InlineData("lds-staging-export", ShaderStage.Vertex, 32u, "EE5C38C25315D90F")] + [InlineData("lds-barrier", ShaderStage.Compute, 64u, "FFD7904E27D5566C")] + [InlineData("lds-barrier", ShaderStage.Compute, 32u, "5315B95DBA904C3A")] + [InlineData("divergent", ShaderStage.Vertex, 64u, "98635A5D60464A2B")] + [InlineData("divergent", ShaderStage.Pixel, 32u, "3DC9BF439D0CDC0B")] + [InlineData("divergent", ShaderStage.Compute, 64u, "BE3B17CDE203BC05")] + [InlineData("image-load", ShaderStage.Pixel, 64u, "D093219EBDF3135D")] + [InlineData("image-load", ShaderStage.Compute, 32u, "C4882A0E0C6FC215")] public void SpirvIsUnchanged(string name, ShaderStage stage, uint waveSize, string expected) { var (plan, resources, layout) = Prepare(Programs[name](), stage); diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5ShaderCallLinkerTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5ShaderCallLinkerTests.cs index c31cdac16..d301d8024 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Gen5ShaderCallLinkerTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5ShaderCallLinkerTests.cs @@ -84,7 +84,22 @@ public void Link_ResolvesTargetsBeyondTheGuestBranchRange() public void Link_RejectsUnsupportedFunctionControl(string opcode) { var body = Program(Sop1(0, opcode, 0, Gen5Operand.Scalar(0)), Sop1(4, "SSetpcB64", 0, Gen5Operand.Scalar(14))); - Assert.Throws(() => Link(body)); + Assert.Throws(() => Link(body)); + } + + // s_swappc_b64 null, s[14:15] saves no return address, so it returns to the caller like s_setpc_b64; with another + // source it is a jump the linker cannot resolve. + [Fact] + public void Link_ReturnsThroughASwapWithTheNullDestination() + { + var caller = Program(Sop1(0, "SSwappcB64", 14, Gen5Operand.Scalar(14)), EndProgram(4)); + var body = Program(Nop(0), Sop1(4, "SSwappcB64", 125, Gen5Operand.Scalar(14))); + var linked = Gen5ShaderCallLinker.Link(caller, [new(0, 14, 16, 14, 4, [new ShaderCallTarget(0x2000, 0x3000, body)])]); + Assert.DoesNotContain(linked.Instructions, instruction => instruction.Opcode is "SSwappcB64" or "SSetpcB64"); + var branch = Assert.Single(linked.Instructions, instruction => instruction.Control is ShaderLinkedBranchControl); + Assert.Equal(linked.Instructions[^1].Pc, ((ShaderLinkedBranchControl)branch.Control!).TargetPc); + + Assert.Throws(() => Link(Program(Nop(0), Sop1(4, "SSwappcB64", 125, Gen5Operand.Scalar(20))))); } // A function that reads its program address gets its own: the dispatch's shader base is the caller's address, and @@ -104,6 +119,41 @@ public void Link_KeepsTheFunctionAddressForProgramCounterReads(ulong function) Assert.True(BindingLayout.ReadsShaderBase(linked)); } + // A caller may read its program address with S_GETPC_B64, to address the constants placed after its code. The linked + // copy keeps the caller's offset, although the callee body linked at the call before it moved the instruction. An + // S_SETPC_B64 in a caller is a jump the linker cannot follow. + [Fact] + public void Link_KeepsTheCallerOffsetForProgramCounterReads() + { + var caller = Program(Sop1(0, "SSwappcB64", 14, Gen5Operand.Scalar(14)), Sop1(4, "SGetpcB64", 2, Gen5Operand.Scalar(0)), + EndProgram(8)); + var body = Program(Nop(0), Nop(4), Sop1(8, "SSetpcB64", 0, Gen5Operand.Scalar(14))); + ShaderCallSite[] calls = [new(0, 14, 16, 14, 4, [new ShaderCallTarget(0x2000, 0x3000, body)])]; + var linked = Gen5ShaderCallLinker.Link(caller, calls); + var read = Assert.Single(linked.Instructions, instruction => instruction.Opcode == "SGetpcB64"); + Assert.True(read.Pc > 4); + Assert.Equal(4ul, read.ProgramOffset); + Assert.Null(read.Control); + Assert.True(BindingLayout.ReadsShaderBase(linked)); + + var jump = Program(Sop1(0, "SSwappcB64", 14, Gen5Operand.Scalar(14)), Sop1(4, "SSetpcB64", 0, Gen5Operand.Scalar(2)), + EndProgram(8)); + Assert.Throws(() => Gen5ShaderCallLinker.Link(jump, calls)); + } + + // S_CBRANCH_CDBG* branch only under an attached GPU debugger, to stubs past S_ENDPGM that the decode leaves out. A + // linked program holds them as S_NOP, in the caller and in a callee. + [Fact] + public void Link_HoldsDebuggerBranchesAsNops() + { + var caller = Program(Branch(0, "SCbranchCdbgsysOrUser", 3), Sop1(4, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + EndProgram(8)); + var body = Program(Branch(0, "SCbranchCdbguser", 7), Sop1(4, "SSetpcB64", 0, Gen5Operand.Scalar(14))); + var linked = Gen5ShaderCallLinker.Link(caller, [new(4, 14, 16, 14, 8, [new ShaderCallTarget(0x2000, 0x3000, body)])]); + Assert.DoesNotContain(linked.Instructions, instruction => instruction.Opcode.StartsWith("SCbranchCdbg", StringComparison.Ordinal)); + Assert.Equal(2, linked.Instructions.Count(instruction => instruction.Opcode == "SNop")); + } + // The host pushes the callees in the order the module tests them: each once, by site and then by record. [Fact] public void CallTargets_FollowTheSitesAndRecords() @@ -125,9 +175,9 @@ public void CallTargets_FollowTheSitesAndRecords() [Fact] public void Link_RejectsChangedOrUnresolvedReturnAddresses() { - Assert.Throws(() => Link(Program(MoveScalar(0, 15, 0), Sop1(4, "SSetpcB64", 0, Gen5Operand.Scalar(14))))); - Assert.Throws(() => Link(Program(Sop1(0, "SSetpcB64", 0, Gen5Operand.Scalar(12))))); - Assert.Throws(() => Link(Program(Nop(0)))); + Assert.Throws(() => Link(Program(MoveScalar(0, 15, 0), Sop1(4, "SSetpcB64", 0, Gen5Operand.Scalar(14))))); + Assert.Throws(() => Link(Program(Sop1(0, "SSetpcB64", 0, Gen5Operand.Scalar(12))))); + Assert.Throws(() => Link(Program(Nop(0)))); Assert.Throws(() => Link(Program(Branch(0, "SBranch", 100), Sop1(4, "SSetpcB64", 0, Gen5Operand.Scalar(14))))); } diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5ShaderClockTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5ShaderClockTests.cs new file mode 100644 index 000000000..a6e230b46 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5ShaderClockTests.cs @@ -0,0 +1,116 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.Text; +using SharpEmu.HLE; +using SharpEmu.ShaderCompiler.Tests.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.ShaderCompiler.Tests; + +public sealed class Gen5ShaderClockTests +{ + // S_MEMTIME (0x24) and S_MEMREALTIME (0x25) write a 64-bit counter to an SGPR pair and read nothing. + [Theory] + [InlineData(0xF4900180u, "SMemtime", 6u)] + [InlineData(0xF4940100u, "SMemrealtime", 4u)] + public void AClockReadDecodesToItsRegisterPair(uint word, string opcode, uint destination) + { + var memory = new ShaderMemory(); + uint[] words = [word, 0, 0xBF810000]; + var bytes = new byte[words.Length * sizeof(uint)]; + for (var index = 0; index < words.Length; index++) + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(index * sizeof(uint)), words[index]); + Assert.True(memory.TryWrite(0x1000, bytes)); + + Assert.True(Gen5ShaderTranslator.TryDecodeProgram(new CpuContext(memory, Generation.Gen5), 0x1000, + out var program, out var error), error); + + var clock = program.Instructions[0]; + Assert.Equal(opcode, clock.Opcode); + Assert.Equal([Gen5Operand.Scalar(destination), Gen5Operand.Scalar(destination + 1)], clock.Destinations); + Assert.Empty(clock.Sources); + } + + // S_SLEEP (SOPP 0x0E) pauses the wave, often inside a loop that waits on the clock; it has no effect on results. + [Fact] + public void ASleepDecodesAndCompilesToNothing() + { + var memory = new ShaderMemory(); + uint[] words = [0xBF8E0001, 0xBF810000]; + var bytes = new byte[words.Length * sizeof(uint)]; + for (var index = 0; index < words.Length; index++) + BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(index * sizeof(uint)), words[index]); + Assert.True(memory.TryWrite(0x1000, bytes)); + + Assert.True(Gen5ShaderTranslator.TryDecodeProgram(new CpuContext(memory, Generation.Gen5), 0x1000, + out var program, out var error), error); + Assert.Equal("SSleep", program.Instructions[0].Opcode); + var (plan, resources, layout) = Prepare(program); + Assert.True(Gen5SpirvTranslator.TryCompileProgram(new ShaderCompileRequest(plan, resources, layout), out _, out error), error); + } + + [Fact] + public void AClockReadUsesTheDeviceClockWhenTheDeviceHasOne() + { + var shader = Compile(supportsShaderDeviceClock: true, out var error); + + Assert.True(shader is not null, error); + var module = new SpirvModuleInspector(shader!); + Assert.Contains((uint)SpirvCapability.ShaderClockKhr, module.Capabilities); + Assert.Contains((ushort)SpirvOp.ReadClockKhr, module.Opcodes); + Assert.Contains("SPV_KHR_shader_clock", Encoding.ASCII.GetString(shader!)); + Gen5MipStatisticsTests.ValidateWhenAvailable(shader!); + } + + // A program that waits for the counter to pass a value must still finish without a device clock. + [Fact] + public void AClockReadWithoutADeviceClockStepsACounter() + { + var shader = Compile(supportsShaderDeviceClock: false, out var error); + + Assert.True(shader is not null, error); + var module = new SpirvModuleInspector(shader!); + Assert.DoesNotContain((uint)SpirvCapability.ShaderClockKhr, module.Capabilities); + Assert.DoesNotContain((ushort)SpirvOp.ReadClockKhr, module.Opcodes); + Assert.Contains(module.Names, name => name.Value == "steppedClock"); + Gen5MipStatisticsTests.ValidateWhenAvailable(shader!); + } + + private static byte[]? Compile(bool supportsShaderDeviceClock, out string error) + { + var program = Program( + new Gen5ShaderInstruction(0, Gen5ShaderEncoding.Smem, "SMemrealtime", [0u, 0u], [], + [Gen5Operand.Scalar(4), Gen5Operand.Scalar(5)], null), + MoveVectorFromScalar(8, 4, 4), + MoveVectorFromScalar(12, 5, 5), + BufferAccess(16, "BufferStoreDwordx2", 0, dwords: 2, vectorData: 4), + EndProgram(24)); + var (plan, resources, layout) = Prepare(program); + var request = new ShaderCompileRequest(plan, resources, layout) { SupportsShaderDeviceClock = supportsShaderDeviceClock }; + return Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out error) ? shader.Spirv : null; + } + + private sealed class ShaderMemory : ICpuMemory + { + private const ulong BaseAddress = 0x1000; + private readonly byte[] _bytes = new byte[256]; + + public bool TryRead(ulong address, Span destination) + { + if (destination.Length > _bytes.Length || address < BaseAddress || address - BaseAddress > (ulong)(_bytes.Length - destination.Length)) return false; + _bytes.AsSpan((int)(address - BaseAddress), destination.Length).CopyTo(destination); + return true; + } + + public bool TryWrite(ulong address, ReadOnlySpan source) + { + if (source.Length > _bytes.Length || address < BaseAddress || address - BaseAddress > (ulong)(_bytes.Length - source.Length)) return false; + source.CopyTo(_bytes.AsSpan((int)(address - BaseAddress), source.Length)); + return true; + } + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5VertexSystemRegisterTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5VertexSystemRegisterTests.cs index 898b5634a..75c7adabf 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Gen5VertexSystemRegisterTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5VertexSystemRegisterTests.cs @@ -47,8 +47,12 @@ public void VertexCapacityIsInitializedBeforeThePackedCountRead(bool subgroups) var store = instructions.FindIndex(item => item.Opcode == SpirvOp.Store && item.Operands[0] == register); Assert.True(store >= 0); var value = instructions[store].Operands[1]; - var read = instructions.FindIndex(item => item.Opcode == SpirvOp.BitFieldUExtract && item.Operands[2] == value); - Assert.True(store >= 0 && store < read, "The vertex count must be initialized before its first read."); + // The read (S_BFE_U32 of the field at bit 12, 9 bits wide) folds: s10 receives the count field of the stored value. + var count = Register(instructions, "s10"); + var read = instructions.FindIndex(item => item.Opcode == SpirvOp.Store && item.Operands[0] == count); + Assert.True(store < read, "The vertex count must be initialized before its first read."); + Assert.Equal(32u, Assert.Single(instructions, item => item.Opcode == SpirvOp.Constant && + item.Operands[1] == instructions[read].Operands[1]).Operands[2]); var packed = Assert.Single(instructions, item => item.Opcode == SpirvOp.Constant && item.Operands[1] == value).Operands[2]; Assert.Equal(32u << 12, packed); Assert.Equal(0u, (packed >> 22) & 0x1ff); diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/BindingLayoutTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/BindingLayoutTests.cs index 44b9f0950..52c23694a 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/BindingLayoutTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/BindingLayoutTests.cs @@ -65,6 +65,29 @@ public void DispatchLimitsFollowPackedOffsetsAndTakePartInAllocation(uint cursor BindingLayoutValidator.Validate(limits, info, [0u], false, false, true, Hash, ShaderStage.Pixel)); } + // A program with an indexed buffer access carries every buffer binding's stride, two to a dword, after the store + // coverage bases; a program without one carries none. + [Fact] + public void IndexedBuffersCarryTheirStridesTwoToADword() + { + var info = new ShaderResourceInfo + { + Buffers = Enumerable.Range(0, 3).Select(_ => new BufferResource { Read = true }).ToList(), + UsesIndexedBuffers = true, + }; + var indexed = BindingLayout.Allocate(info, [0u], false, false, false); + Assert.Equal(3u, indexed.BufferStrideCount); + Assert.Equal(indexed.CallTargetsDword + indexed.CallTargetCount * 2, indexed.BufferStridesDword); + Assert.Equal(indexed.BufferStridesDword + 2, indexed.ShaderDataDwordCount); + BindingLayoutValidator.Validate(indexed, info, [0u], false, false, false, Hash, ShaderStage.Compute); + + info.UsesIndexedBuffers = false; + var plain = BindingLayout.Allocate(info, [0u], false, false, false); + Assert.Equal(0u, plain.BufferStrideCount); + Assert.Equal(plain.BufferStridesDword, plain.ShaderDataDwordCount); + Assert.NotEqual(indexed, plain); + } + [Fact] public void ShaderInfoAndBindingLayout() { @@ -337,6 +360,40 @@ public void GraphicsPushConstantLayout() Assert.Equal(6u, cursor); } + // Data placed at the top of the push range takes one place for every cursor it fits above (a vertex stage after pixel + // stages of different sizes) and the shader data block above that, exactly where the cursor's own place would not fit; each + // layout validates from its own allocation cursor. + [Fact] + public void TopPlacedDataTakesOnePlaceForEveryCursorItFitsAbove() + { + static uint[] UserData(uint count) => Enumerable.Range(0, (int)count).Select(index => (uint)index).ToArray(); + var info = new ShaderResourceInfo(); + var layouts = new[] { 0u, 4u, 13u, 23u } + .Select(cursor => BindingLayout.Allocate(info, UserData(9), false, false, false, cursor, pushDataAtTop: true)).ToArray(); + foreach (var layout in layouts) + { + Assert.True(layout.UsesPushData); + Assert.Equal(23u, layout.PushDataStartDword); + Assert.Equal(23u, layout.AllocationCursor); + Assert.Equal(layouts[0], layout); + BindingLayoutValidator.Validate(layout, info, UserData(9), false, false, false, Hash, ShaderStage.Vertex); + } + + Assert.Equal(23u, layouts[0].PushStartFor(0)); + Assert.Equal(23u, layouts[0].PushStartFor(23)); + Assert.Equal(PushData.NoStart, layouts[0].PushStartFor(24)); + var spill = BindingLayout.Allocate(info, UserData(9), false, false, false, 24, pushDataAtTop: true); + Assert.False(spill.UsesPushData); + Assert.NotNull(spill.Find(DescriptorBindingKind.ShaderData)); + Assert.Equal(PushData.DwordCount, spill.AllocationCursor); + BindingLayoutValidator.Validate(spill, info, UserData(9), false, false, false, Hash, ShaderStage.Vertex); + Assert.False(BindingLayout.Allocate(info, UserData(9), false, false, false, 24).UsesPushData); + + // Without the top placement each cursor is its own place, and a layout of the same place but the other rule differs. + Assert.Equal(4u, BindingLayout.Allocate(info, UserData(9), false, false, false, 4).PushDataStartDword); + Assert.NotEqual(layouts[0], BindingLayout.Allocate(info, UserData(9), false, false, false, 23)); + } + // A stage that spilled at cursor 13 is valid; validation must not reallocate at zero. [Fact] public void ValidatorAcceptsAStageThatSpilledToShaderData() diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/BindlessHeapTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/BindlessHeapTests.cs new file mode 100644 index 000000000..02c019c5f --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/BindlessHeapTests.cs @@ -0,0 +1,343 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.ShaderCompiler.Tests.Resources; + +public sealed class BindlessHeapTests +{ + // With the heap set (bindlessHeap), an image read from a heap V# at a lane-chosen offset is a heap record: its reads + // stay on the host, and the shader takes the record its key picks from descriptor set 1 and marks it for the host. A + // record past the heap's range (the call records' elements) reads null. + [Fact] + public void AnImageReadAtALaneChosenOffsetIsAHeapRecord() + { + var program = ResourceTrackerTests.LaneIndexedImageProgram(); + + var plan = Extract(program, stage: ShaderStage.Compute, bindlessHeap: true); + + var record = Assert.Single(plan.HeapRecords); + Assert.False(record.Sampler); + var heap = plan.DescriptorSources[(int)record.Source].Heap!; + Assert.Equal((0u, BindlessHeap.ImageRecordBytes, false), (heap.Immediate, heap.RecordBytes, heap.Cube)); + Assert.Equal(40u, plan.Memory[heap.KeyMemoryIndex].Pc); + Assert.Equal(new HeapRecordSource(heap.HeapSource, false), Assert.Single(plan.HeapRecordSources)); + for (var component = 0u; component < 8; component++) + { + Assert.True(plan.Memory.TryGetIndex(40, component, out var index)); + Assert.True(plan.Memory[index].PlanningOnly); + } + + Assert.True(plan.Info.UsesBindlessHeap); + var request = Request(program, bindlessHeap: true); + Assert.True(request.UsesBindlessHeap); + Assert.True(request.Bindings.UsesBindlessHeap); + Assert.Contains(heap.KeyMemoryIndex, request.IndirectOffsetKeyMemoryIndices); + + var module = Compile(request); + Assert.Equal([0u, BindlessHeap.FeedbackBinding], module.SetOneBindings); + Assert.Contains(SpirvOp.AtomicOr, module.Opcodes); + Assert.Contains((uint)SpirvDecoration.NonUniform, module.Decorations); + Assert.Contains((uint)SpirvCapability.SampledImageArrayNonUniformIndexing, module.Capabilities); + Assert.Contains(SpirvOp.ULessThan, module.Opcodes); + Assert.Contains(BindlessHeap.CallRecordFirstIndex, module.Constants); + Assert.Contains(BindlessHeap.CallRecordNullIndex, module.Constants); + } + + // A sampler read from a heap V# at a lane-chosen offset indexes the sampler array of set 1; its words still load. + [Fact] + public void ASamplerReadAtALaneChosenOffsetIsAHeapRecord() + { + var program = ResourceTrackerTests.LaneIndexedSamplerProgram(); + + var plan = Extract(program, stage: ShaderStage.Pixel, bindlessHeap: true); + + var record = Assert.Single(plan.HeapRecords); + Assert.True(record.Sampler); + var heap = plan.DescriptorSources[(int)record.Source].Heap!; + Assert.Equal((0u, BindlessHeap.SamplerRecordBytes), (heap.Immediate, heap.RecordBytes)); + Assert.True(plan.Memory.TryGetIndex(24, 0, out var index)); + Assert.False(plan.Memory[index].PlanningOnly); + + var module = Compile(Request(program, ShaderStage.Pixel, bindlessHeap: true)); + Assert.Equal([(uint)BindlessHeap.SamplerSlot, BindlessHeap.FeedbackBinding], module.SetOneBindings); + } + + // With both opt-ins, a heap record is read from the heap and not as null. + [Fact] + public void AHeapRecordIsNotReadAsNull() + { + var plan = Extract(ResourceTrackerTests.LaneIndexedImageProgram(), stage: ShaderStage.Compute, + bindlessNullDescriptors: true, bindlessHeap: true); + + Assert.Single(plan.HeapRecords); + Assert.Empty(plan.NullBindlessDescriptorPcs); + } + + // Each draw evaluates the heap V# for the host, and the heap image takes its class from the instruction. + [Fact] + public void MaterializingReportsTheHeapAndSpecializesTheImageFromTheInstruction() + { + var plan = Extract(ResourceTrackerTests.LaneIndexedImageProgram(), stage: ShaderStage.Compute, bindlessHeap: true); + var userData = new uint[64]; + userData[0] = 0x0001_0000; + userData[1] = 32u << 16; + userData[2] = 4096; + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + + Assert.True(ResourceMaterializer.Materialize(plan, Inputs(userData), ref snapshot, ref specialization)); + + Assert.Equal([new BindlessHeapDescriptor(false, 0x0001_0000, 4096, 32)], snapshot.Heaps); + var image = Assert.Single(specialization.Images); + Assert.Equal((ImageNumericClass.Float, ImageDimension.Dim2D, false), (image.NumericClass, image.Dimension, image.Cube)); + } + + // Materialized the way the program cache chooses its path, a heap program still reports its heap: the fast path + // assembles no heap descriptors, and with an empty heap the shader's records read nothing. + [Fact] + public void AHeapProgramKeepsItsHeapOnThePathTheCacheChooses() + { + var plan = Extract(ResourceTrackerTests.LaneIndexedImageProgram(), stage: ShaderStage.Compute, bindlessHeap: true); + var userData = new uint[64]; + userData[0] = 0x0001_0000; + userData[1] = 32u << 16; + userData[2] = 4096; + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + + var materialized = ResourceMaterializer.CanMaterializeFast(plan) + ? ResourceMaterializer.MaterializeFast(plan, Inputs(userData), ref snapshot, ref specialization, out _) + : ResourceMaterializer.Materialize(plan, Inputs(userData), ref snapshot, ref specialization); + + Assert.True(materialized); + Assert.Equal([new BindlessHeapDescriptor(false, 0x0001_0000, 4096, 32)], snapshot.Heaps); + } + + // A 3D read of a heap record also has the record's 2D-array element: a record that holds a 2D texture has a null 3D + // element, and the hardware takes the third coordinate as the layer. + [Fact] + public void AHeapVolumeReadFallsBackToTheRecordsLayers() + { + var module = Compile(Request(ResourceTrackerTests.LaneIndexedImageProgram(dimension: 2), bindlessHeap: true)); + + Assert.Equal([(uint)BindlessHeap.VolumeLayerSlot, (uint)BindlessHeap.VolumeSlot, BindlessHeap.FeedbackBinding], module.SetOneBindings); + Assert.Contains(SpirvOp.ImageQueryLevels, module.Opcodes); + Assert.Contains((uint)SpirvCapability.ImageQuery, module.Capabilities); + } + + // A heap read takes the element of its record when set 1 holds that record (below CallRecordFirstIndex) and the null + // element for any other record, however large: the range test reads the record itself, not a value cut to the set's + // size, so no record reads the element of another record. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ARecordSetOneCannotHoldReadsTheNullElement(bool sampler) + { + var program = sampler ? ResourceTrackerTests.LaneIndexedSamplerProgram() : ResourceTrackerTests.LaneIndexedImageProgram(); + Assert.True(Gen5SpirvTranslator.TryCompileProgram(Request(program, ShaderStage.Pixel, bindlessHeap: true), out var shader, out var error), error); + Gen5MipStatisticsTests.ValidateWhenAvailable(shader.Spirv); + var module = new Expressions(shader.Spirv); + var recordBytes = sampler ? BindlessHeap.SamplerRecordBytes : BindlessHeap.ImageRecordBytes; + + var tested = module.ComparedWith(BindlessHeap.CallRecordFirstIndex).ToList(); + Assert.NotEmpty(tested); + Assert.All(tested, value => Assert.Equal(SpirvOp.ShiftRightLogical, module.Opcode(value))); + var indexes = module.ElementIndexes(sampler ? (uint)BindlessHeap.SamplerSlot : 0u); + Assert.NotEmpty(indexes); + foreach (var index in indexes) + { + var offset = module.ShiftedOperand(index, sampler ? 4u : 5u); + foreach (var record in new[] { 0u, 1234u, BindlessHeap.CallRecordFirstIndex - 1 }) + { + Assert.Equal(record, module.Evaluate(index, offset, record * recordBytes)); + } + + foreach (var record in new[] { BindlessHeap.CallRecordFirstIndex, BindlessHeap.Capacity, BindlessHeap.Capacity + 1234, 3 * BindlessHeap.Capacity + 7 }) + { + Assert.Equal(BindlessHeap.CallRecordNullIndex, module.Evaluate(index, offset, record * recordBytes)); + } + } + } + + // Without the heap set nothing changes: compute still rejects the lane-chosen image. + [Fact] + public void WithoutTheOptInTheImageIsStillRejected() + { + var error = Assert.Throws(() => + Extract(ResourceTrackerTests.LaneIndexedImageProgram(), stage: ShaderStage.Compute)); + Assert.Contains("not a valid runtime value", error.Message); + } + + private sealed record Module(List Opcodes, List Decorations, List Capabilities, List SetOneBindings, + List Constants); + + private static Module Compile(ShaderCompileRequest request) + { + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + Gen5MipStatisticsTests.ValidateWhenAvailable(shader.Spirv); + var code = shader.Spirv; + var opcodes = new List(); + var decorations = new List(); + var capabilities = new List(); + var constants = new List(); + var sets = new Dictionary(); + var bindings = new Dictionary(); + for (var offset = 20; offset + 4 <= code.Length;) + { + var word = BitConverter.ToUInt32(code, offset); + var count = (int)(word >> 16); + var opcode = (SpirvOp)(word & 0xFFFF); + uint Operand(int index) => BitConverter.ToUInt32(code, offset + index * sizeof(uint)); + opcodes.Add(opcode); + if (opcode == SpirvOp.Capability) + { + capabilities.Add(Operand(1)); + } + else if (opcode == SpirvOp.Constant && count == 4) + { + constants.Add(Operand(3)); + } + else if (opcode == SpirvOp.Decorate) + { + decorations.Add(Operand(2)); + if (Operand(2) == (uint)SpirvDecoration.DescriptorSet) + { + sets[Operand(1)] = Operand(3); + } + else if (Operand(2) == (uint)SpirvDecoration.Binding) + { + bindings[Operand(1)] = Operand(3); + } + } + + offset += count * sizeof(uint); + } + + var setOne = sets.Where(pair => pair.Value == BindlessHeap.DescriptorSet).Select(pair => bindings[pair.Key]).Order().ToList(); + return new Module(opcodes, decorations, capabilities, setOne, constants); + } + + // The integer value instructions of a module, enough to evaluate a set-1 element index for a given byte offset. + private sealed class Expressions + { + private readonly Dictionary _definitions = []; + private readonly Dictionary _constants = []; + private readonly Dictionary _bindings = []; + private readonly List<(uint Base, uint Index)> _elementPointers = []; + + public Expressions(byte[] code) + { + for (var offset = 20; offset + 4 <= code.Length;) + { + var word = BitConverter.ToUInt32(code, offset); + var count = (int)(word >> 16); + var opcode = (SpirvOp)(word & 0xFFFF); + var operands = new uint[count - 1]; + for (var index = 0; index < operands.Length; index++) + { + operands[index] = BitConverter.ToUInt32(code, offset + (index + 1) * sizeof(uint)); + } + + switch (opcode) + { + case SpirvOp.Constant when operands.Length == 3: + _constants[operands[1]] = operands[2]; + break; + case SpirvOp.Decorate when operands.Length == 3 && operands[1] == (uint)SpirvDecoration.DescriptorSet: + _bindings[operands[0]] = (operands[2], _bindings.GetValueOrDefault(operands[0]).Binding); + break; + case SpirvOp.Decorate when operands.Length == 3 && operands[1] == (uint)SpirvDecoration.Binding: + _bindings[operands[0]] = (_bindings.GetValueOrDefault(operands[0]).Set, operands[2]); + break; + case SpirvOp.AccessChain when operands.Length >= 4: + _elementPointers.Add((operands[2], operands[3])); + break; + case SpirvOp.IAdd or SpirvOp.ISub or SpirvOp.BitwiseAnd or SpirvOp.BitwiseOr or SpirvOp.ShiftLeftLogical or + SpirvOp.ShiftRightLogical or SpirvOp.ULessThan or SpirvOp.Select or SpirvOp.CopyObject or SpirvOp.Bitcast: + _definitions[operands[1]] = (opcode, operands[2..]); + break; + } + + offset += count * sizeof(uint); + } + } + + // The indexes of the element pointers into the set-1 array at binding slot. + public List ElementIndexes(uint slot) + { + var array = Assert.Single(_bindings, entry => entry.Value.Set == BindlessHeap.DescriptorSet && entry.Value.Binding == slot).Key; + return _elementPointers.Where(pointer => pointer.Base == array).Select(pointer => pointer.Index).ToList(); + } + + // What the nearest logical right shift by amount under value shifts: the read's byte offset. + public uint ShiftedOperand(uint value, uint amount) + { + var pending = new Queue(); + pending.Enqueue(value); + var seen = new HashSet(); + while (pending.TryDequeue(out var id)) + { + if (!seen.Add(id) || !_definitions.TryGetValue(id, out var definition)) + { + continue; + } + + if (definition.Opcode == SpirvOp.ShiftRightLogical && + _constants.TryGetValue(definition.Operands[1], out var shift) && shift == amount) + { + return definition.Operands[0]; + } + + foreach (var operand in definition.Operands) + { + pending.Enqueue(operand); + } + } + + throw new InvalidOperationException($"No right shift by {amount} feeds %{value}."); + } + + // The left operands of the unsigned comparisons with the constant bound. + public IEnumerable ComparedWith(uint bound) => + _definitions.Values + .Where(definition => definition.Opcode == SpirvOp.ULessThan && + _constants.TryGetValue(definition.Operands[1], out var value) && value == bound) + .Select(definition => definition.Operands[0]); + + public SpirvOp Opcode(uint id) => _definitions.TryGetValue(id, out var definition) ? definition.Opcode : SpirvOp.Nop; + + // The value of id when the value named offset holds value. + public uint Evaluate(uint id, uint offset, uint value) + { + if (id == offset) + { + return value; + } + + if (_constants.TryGetValue(id, out var constant)) + { + return constant; + } + + var (opcode, operands) = _definitions[id]; + uint Operand(int index) => Evaluate(operands[index], offset, value); + return opcode switch + { + SpirvOp.IAdd => Operand(0) + Operand(1), + SpirvOp.ISub => Operand(0) - Operand(1), + SpirvOp.BitwiseAnd => Operand(0) & Operand(1), + SpirvOp.BitwiseOr => Operand(0) | Operand(1), + SpirvOp.ShiftLeftLogical => Operand(0) << (int)(Operand(1) & 31), + SpirvOp.ShiftRightLogical => Operand(0) >> (int)(Operand(1) & 31), + SpirvOp.ULessThan => Operand(0) < Operand(1) ? 1u : 0u, + SpirvOp.Select => Operand(0) != 0 ? Operand(1) : Operand(2), + _ => Operand(0), + }; + } + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/BranchSelectionSeedTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/BranchSelectionSeedTests.cs new file mode 100644 index 000000000..14d6f485b --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/BranchSelectionSeedTests.cs @@ -0,0 +1,70 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; +using Mode = SharpEmu.ShaderCompiler.Resources.RuntimeValueEvaluator.CompiledBranchMode; + +namespace SharpEmu.ShaderCompiler.Tests.Resources; + +// The branch walk successfully reads a guest word that a later CLEAN table slot also needs. The compiled path may +// not read it again. +public sealed class BranchSelectionSeedTests +{ + [Theory] + [InlineData(0u)] + [InlineData(1u)] + public void SuccessfulCleanPredicateSeedsTheLaterCleanTable(uint condition) + { + var plan = Extract(Program(ScalarLoad(0, 12, 8), + Sopc(8, "SCmpEqU32", Gen5Operand.Scalar(8), Operand(1)), + Branch(12, "SCbranchScc1", 3), + BufferLoad(16, 0), Branch(24, "SBranch", 2), + BufferLoad(28, 4), EndProgram(36)), userDataCount: 14); + Assert.NotEmpty(plan.ResourceBranches); + Assert.NotEmpty(plan.TableReads); + Array.Fill((byte[])plan.CleanFlatSlots, (byte)1); + plan.CompileEvaluatorNow(); + Assert.IsType(plan.CompiledBranches); + + uint[] userData = [0x1000, 0, 256, 0, 0x2000, 0, 256, 0, 0, 0, 0, 0, 0x3000, 0]; + uint[]? expectedTable = null; + foreach (var mode in new[] { Mode.Off, Mode.On }) + { + var cleanReads = 0; + bool ReadClean(ulong address, out uint word) + { + Assert.Equal(0x3000ul, address); + Assert.Equal(1, ++cleanReads); + word = condition; + return true; + } + bool ReadGeneral(ulong address, out uint word) + { + word = 0; + throw new System.InvalidOperationException("The predicate and table use the clean reader in this fixture."); + } + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + var served = RuntimeValueEvaluator.BranchesServedOnThread; + var previousMode = RuntimeValueEvaluator.BranchModeOverride; + RuntimeValueEvaluator.BranchModeOverride = mode; + try + { + Assert.True(ResourceMaterializer.Materialize(plan, Inputs(userData, ReadGeneral, ReadClean), + ref snapshot, ref specialization)); + } + finally + { + RuntimeValueEvaluator.BranchModeOverride = previousMode; + } + Assert.Equal(1, cleanReads); + Assert.Equal(condition == 0 ? 0x1000u : 0u, snapshot.Buffers[0][0]); + Assert.Equal(condition == 1 ? 0x2000u : 0u, snapshot.Buffers[1][0]); + if (expectedTable is null) expectedTable = [.. snapshot.FlattenedResourceTable]; + else Assert.Equal(expectedTable, snapshot.FlattenedResourceTable); + if (mode == Mode.On) Assert.Equal(served + 1, RuntimeValueEvaluator.BranchesServedOnThread); + } + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledBranchTransactionTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledBranchTransactionTests.cs new file mode 100644 index 000000000..f1c61493c --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledBranchTransactionTests.cs @@ -0,0 +1,231 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; +using Mode = SharpEmu.ShaderCompiler.Resources.RuntimeValueEvaluator.CompiledBranchMode; + +namespace SharpEmu.ShaderCompiler.Tests.Resources; + +public sealed class CompiledBranchTransactionTests +{ + // Two buffers, one in each arm of a uniform branch on user data s8. Both V#s are read through one pointer the shader + // loads first, so whenever s8 selects the second arm the pointer's first use is in the inactive first arm. + private static ShaderResourcePlan SharedPointerBranches(bool cleanSlots = false) + { + var plan = Extract(Program( + ScalarLoad(0, 0, 10, 2), + Sopc(8, "SCmpEqU32", Gen5Operand.Scalar(8), Operand(1)), + Branch(12, "SCbranchScc1", 5), + ScalarLoad(16, 10, 16, 4), + BufferLoad(24, 16), + Branch(32, "SBranch", 4), + ScalarLoad(36, 10, 20, 4, 16), + BufferLoad(44, 20), + EndProgram(52)), userDataCount: 9); + if (cleanSlots) Array.Fill((byte[])plan.CleanFlatSlots, (byte)1); + plan.CompileEvaluatorNow(); + return plan; + } + + private static TracedMemory Memory() + { + var memory = new TracedMemory(); + memory.Words[0x1000] = 0x2000; + memory.Words[0x1004] = 0; + uint[] first = [0x5000, 0, 256, 0]; + uint[] second = [0x6000, 0, 512, 0]; + for (var index = 0; index < 4; index++) + { + memory.Words[0x2000 + (ulong)index * 4] = first[index]; + memory.Words[0x2010 + (ulong)index * 4] = second[index]; + } + + return memory; + } + + private static uint[] Words(ResourceSnapshot snapshot) => + [.. snapshot.Buffers.SelectMany(words => words), .. snapshot.FlattenedResourceTable]; + + private readonly record struct Outcome(bool Succeeded, ResourceSnapshot Snapshot, string[] Trace, int Served); + + private static Outcome Run(ShaderResourcePlan plan, TracedMemory memory, uint condition, Mode mode, bool cleanReader = true) + { + memory.Trace.Clear(); + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + var served = RuntimeValueEvaluator.BranchesServedOnThread; + RuntimeValueEvaluator.BranchModeOverride = mode; + bool succeeded; + try + { + using (MaterializationProgramCheck.Suspend()) + { + succeeded = ResourceMaterializer.Materialize(plan, memory.Inputs(condition, cleanReader), ref snapshot, ref specialization); + } + } + finally + { + RuntimeValueEvaluator.BranchModeOverride = null; + } + + return new Outcome(succeeded, snapshot, [.. memory.Trace], RuntimeValueEvaluator.BranchesServedOnThread - served); + } + + [Theory] + [InlineData(0u, true, false)] + [InlineData(1u, true, false)] + [InlineData(0u, false, false)] + [InlineData(1u, false, false)] + [InlineData(0u, true, true)] + [InlineData(1u, true, true)] + public void CompiledBranchesReadWhatTheFallbackReadsInItsOrder(uint condition, bool cleanReader, bool cleanSlots) + { + var plan = SharedPointerBranches(cleanSlots); + Assert.NotEmpty(plan.ResourceBranches); + Assert.NotNull(plan.CompiledBranches); + var memory = Memory(); + var reference = Run(plan, memory, condition, Mode.Off, cleanReader); + Assert.True(reference.Succeeded); + var compiled = Run(plan, memory, condition, Mode.On, cleanReader); + Assert.Equal(1, compiled.Served); + Assert.True(compiled.Succeeded); + Assert.Equal(reference.Trace, compiled.Trace); + Assert.Equal(Words(reference.Snapshot), Words(compiled.Snapshot)); + } + + // The first arm's V# words are flattened slots too: the inactive arm must leave them to the table, which reads them in + // its own phase, while the shared pointer is read once, by the active arm, before its V#. + [Fact] + public void AValueFirstNeededByAnInactiveSourceIsReadOnceWhereTheActiveSourceNeedsIt() + { + var plan = SharedPointerBranches(); + var memory = Memory(); + var reference = Run(plan, memory, 1, Mode.Off); + var compiled = Run(plan, memory, 1, Mode.On); + Assert.Equal(1, compiled.Served); + Assert.True(compiled.Succeeded); + Assert.Equal(reference.Trace, compiled.Trace); + Assert.Single(compiled.Trace, item => item.StartsWith("R:1000:", StringComparison.Ordinal)); + foreach (var address in new[] { 0x2000, 0x2004, 0x2008, 0x200C }) + { + var reads = compiled.Trace.Where(item => item.StartsWith($"R:{address:X}:", StringComparison.Ordinal)).ToArray(); + Assert.Single(reads); + Assert.EndsWith(":True", reads[0]); + } + + foreach (var address in new[] { 0x2010, 0x2014, 0x2018, 0x201C }) + Assert.EndsWith(":False", Assert.Single(compiled.Trace, item => item.StartsWith($"R:{address:X}:", StringComparison.Ordinal))); + var pointer = Array.FindIndex(compiled.Trace, item => item.StartsWith("R:1000:", StringComparison.Ordinal)); + var descriptor = Array.FindIndex(compiled.Trace, item => item.StartsWith("R:2010:", StringComparison.Ordinal)); + var table = Array.IndexOf(compiled.Trace, "P:True"); + Assert.True(pointer < descriptor && descriptor < table); + Assert.Equal(0x6000u, compiled.Snapshot.Buffers.Single(words => words[0] != 0)[0]); + } + + // A failed read fails the call at the same read in every mode, whether an active arm, the table (which reads an inactive + // arm's flattened V#) or the shared pointer meets it first. + [Theory] + [InlineData(0u, 0x2004UL)] + [InlineData(1u, 0x2004UL)] + [InlineData(1u, 0x1000UL)] + [InlineData(0u, 0x2018UL)] + [InlineData(1u, 0x2018UL)] + public void FailuresAndTheirReadsMatchTheFallback(uint condition, ulong failure) + { + var plan = SharedPointerBranches(); + var memory = Memory(); + memory.FailureAddress = failure; + var reference = Run(plan, memory, condition, Mode.Off); + var compiled = Run(plan, memory, condition, Mode.On); + Assert.False(reference.Succeeded); + Assert.False(compiled.Succeeded); + Assert.Equal(1, compiled.Served); + Assert.Equal(reference.Trace, compiled.Trace); + Assert.Equal(failure == 0x1000UL || (condition == 0) == (failure < 0x2010UL), !reference.Trace.Contains("P:True")); + } + + [Fact] + public void CallsOwnTheirOutputsAndAFailureKeepsTheCallersSnapshot() + { + var plan = SharedPointerBranches(); + var memory = Memory(); + var first = Run(plan, memory, 0, Mode.On); + var saved = Words(first.Snapshot); + memory.Words[0x2000] = 0x7000; + var second = Run(plan, memory, 0, Mode.On); + Assert.Equal(saved, Words(first.Snapshot)); + Assert.Equal(0x7000u, second.Snapshot.Buffers.Single(words => words[0] != 0)[0]); + + memory.FailureAddress = 0x2004; + var snapshot = second.Snapshot; + var specialization = new ResourceSpecialization(); + var savedSpecialization = specialization; + RuntimeValueEvaluator.BranchModeOverride = Mode.On; + try + { + Assert.False(ResourceMaterializer.Materialize(plan, memory.Inputs(0, true), ref snapshot, ref specialization)); + } + finally + { + RuntimeValueEvaluator.BranchModeOverride = null; + } + + Assert.Same(second.Snapshot, snapshot); + Assert.Same(savedSpecialization, specialization); + } + + [Fact] + public void ParallelCallsOwnTheirOutputs() + { + var plan = SharedPointerBranches(); + Parallel.For(0, 32, index => + { + var memory = Memory(); + memory.Words[0x2010] = 0x6000 + (uint)index * 0x100; + var reference = Run(plan, memory, 1, Mode.Off); + var compiled = Run(plan, memory, 1, Mode.On); + Assert.Equal(1, compiled.Served); + Assert.Equal(Words(reference.Snapshot), Words(compiled.Snapshot)); + }); + } + + [Fact] + public void CompiledBranchesAreOnUnlessConfigured() + { + if (Environment.GetEnvironmentVariable("SHARPEMU_COMPILED_BRANCHES") is not null) return; + Assert.Equal(Mode.On, RuntimeValueEvaluator.BranchMode); + } + + private sealed class TracedMemory + { + public Dictionary Words { get; } = new(); + public List Trace { get; } = []; + public ulong FailureAddress { get; set; } = ulong.MaxValue; + private bool _inTable; + + public ResourceRuntimeInputs Inputs(uint condition, bool cleanReader) => new() + { + UserData = [0x1000, 0, 0, 0, 0, 0, 0, 0, condition], + ReadMemory = Read, + ReadCleanMemory = cleanReader ? ReadClean : null, + TablePhase = table => + { + _inTable = table; + Trace.Add("P:" + table); + }, + }; + + private bool Read(ulong address, out uint word) => ReadCore(address, false, out word); + + private bool ReadClean(ulong address, out uint word) => ReadCore(address, true, out word); + + private bool ReadCore(ulong address, bool clean, out uint word) + { + Trace.Add($"R:{address:X}:{clean}:{_inTable}"); + word = Words.TryGetValue(address, out var value) ? value : (uint)address; + return address != FailureAddress; + } + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledCallRecordRangeTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledCallRecordRangeTests.cs new file mode 100644 index 000000000..0388c801e --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledCallRecordRangeTests.cs @@ -0,0 +1,470 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; +using Mode = SharpEmu.ShaderCompiler.Resources.CompiledDeviceAddressRanges.Mode; + +namespace SharpEmu.ShaderCompiler.Tests.Resources; + +// CallRecordPlanner.AddRecordRanges with SHARPEMU_COMPILED_RANGES against the interpreter, record after record: the same +// results, ranges and reads. Runs in the compiled-range collection, which runs alone. +[Collection("CompiledDeviceAddressRanges")] +public sealed class CompiledCallRecordRangeTests +{ + public enum Path { Off, On } + + public enum Resident { None, Serve, Refuse } + + private sealed class Scope : IDisposable + { + private readonly Mode _mode = CompiledDeviceAddressRanges.Configured; + + public Scope(Path path) => CompiledDeviceAddressRanges.Configured = path switch + { + Path.On => Mode.On, + _ => Mode.Off, + }; + + public void Dispose() + { + CompiledDeviceAddressRanges.Configured = _mode; + } + } + + private sealed class Memory(Dictionary words, Resident resident = Resident.None) + { + public readonly List Reads = []; + public readonly List<(ulong Address, int Bytes)> ResidentReads = []; + public readonly HashSet FailOnce = []; + + public bool Read(ulong address, out uint word) + { + Reads.Add(address); + word = 0; + return !FailOnce.Remove(address) && words.TryGetValue(address, out word); + } + + public bool ReadResident(ulong address, Span destination, bool clean) + { + ResidentReads.Add((address, destination.Length)); + if (resident != Resident.Serve) return false; + for (var offset = 0; offset < destination.Length; offset += 4) + { + if (!words.TryGetValue(address + (ulong)offset, out var word)) return false; + BinaryPrimitives.WriteUInt32LittleEndian(destination[offset..], word); + } + + return true; + } + + public ResourceRuntimeInputs Inputs(uint[] userData) => new() + { + UserData = userData, + ReadMemory = Read, + ReadResidentMemory = resident == Resident.None ? null : (ResidentGuestBytesReader)ReadResident, + }; + } + + private static void SetBuffers(ShaderResourcePlan plan, params CallRecordBufferWords[] buffers) => + typeof(ShaderResourcePlan).GetProperty(nameof(ShaderResourcePlan.CallRecordCallees))! + .SetValue(plan, new List { new([], buffers, 64) }); + + // A plan whose callee 0 computes the given buffers; the scalar load gives the memory entries (offsets 0, 4, 8, 12) the + // argument reads use. + private static ShaderResourcePlan Plan(Func buffers) + { + var plan = Extract(Program(ScalarLoad(0, 0, 4, 4), EndProgram(8)), userDataCount: 4); + SetBuffers(plan, buffers(plan)); + return plan; + } + + private static ScalarValue ArgumentRegister(uint index) => ScalarValue.UserData(ScalarValueGraph.CallArgumentRegisterBase + index); + + private static ScalarValue ArgumentHandle() => ScalarValue.Handle(ScalarValueKind.AddressHandle, [ArgumentRegister(0), ArgumentRegister(1)]); + + // The dword a handle points at, plus an immediate of 0, 4, 8 or 12. + private static ScalarValue ArgumentWord(ShaderResourcePlan plan, ScalarValue handle, uint offset) + { + Assert.True(plan.Memory.TryGetIndex(0, offset / 4, out var index)); + return ScalarValue.MemoryRead(ScalarValueKind.ScalarAddressWord, handle, ScalarValue.ConstantOf(0u), index); + } + + // A: the record's V# at its argument. B (written): A's address + 0x100 and A's stride, the fourth word as records (shares + // A's first two reads). C: an address from a user-data register in the gap below the argument registers (reads zero). + // D: a register past the argument pair (fails). + private static CallRecordBufferWords[] Buffers(ShaderResourcePlan plan) + { + var handle = ArgumentHandle(); + var words = new[] { 0u, 4u, 8u, 12u }.Select(offset => ArgumentWord(plan, handle, offset)).ToArray(); + return + [ + new(words, false), + new([ScalarValue.MakeOperation(ScalarOperation.IAdd32, ScalarValueType.U32, words[0], ScalarValue.ConstantOf(0x100u)), + words[1], words[3], ScalarValue.ConstantOf(0u)], true), + new([ScalarValue.MakeOperation(ScalarOperation.IAdd32, ScalarValueType.U32, ScalarValue.UserData(100), ScalarValue.ConstantOf(0x7000u)), + ScalarValue.UserData(1), ScalarValue.ConstantOf(8u), ScalarValue.ConstantOf(0u)], false), + new([ScalarValue.UserData(ScalarValueGraph.CallArgumentRegisterBase + 2), ScalarValue.ConstantOf(0u), + ScalarValue.ConstantOf(8u), ScalarValue.ConstantOf(0u)], false), + ]; + } + + private static readonly ulong[] Arguments = [0x1000, 0x2000, 0x3000, 0x4000, 0x5000, 0x1000]; + + // 0x1000: both buffers. 0x2000: the stride word fails once, so A is skipped and B reads it again. 0x3000: A fits, then B + // (written) is larger than 4 GiB: the record returns false after adding A. 0x4000: A is larger than 4 GiB (read-only, + // skipped), B fits. 0x5000: zero address and zero size, nothing added. 0x1000 again: a new record reads again. + private static readonly Dictionary Words = new() + { + [0x1000] = 0x5000, [0x1004] = 16u << 16, [0x1008] = 4, [0x100C] = 16, + [0x2000] = 0x6000, [0x2004] = 16u << 16, [0x2008] = 2, [0x200C] = 16, + [0x3000] = 0x8000, [0x3004] = 16u << 16, [0x3008] = 1, [0x300C] = 0x2000_0000, + [0x4000] = 0x7000, [0x4004] = 16u << 16, [0x4008] = 0x2000_0000, [0x400C] = 16, + [0x5000] = 0, [0x5004] = 0, [0x5008] = 0, [0x500C] = 0, + }; + + private sealed record Outcome(bool[] Results, DeviceAddressRange[] Ranges, ulong[] Reads, (ulong Address, int Bytes)[] ResidentReads); + + private static Outcome Run(Path path, Func buffers, ulong[] arguments, + ulong[]? failOnce = null, Resident resident = Resident.None, Dictionary? words = null) + { + using var scope = new Scope(path); + var plan = Plan(buffers); + plan.CompileEvaluatorNow(); + if (path == Path.Off) Assert.Null(plan.CompiledRanges); + else Assert.Null(Assert.IsType(plan.CompiledRanges).Record(0)!.Refusal); + var memory = new Memory(words ?? Words, resident); + foreach (var address in failOnce ?? []) memory.FailOnce.Add(address); + var inputs = memory.Inputs([0, 0, 0, 0]); + var ranges = new List(); + bool[] results = [.. arguments.Select(argument => CallRecordPlanner.AddRecordRanges(plan, 0, argument, inputs, 0, ranges))]; + return new(results, [.. ranges], [.. memory.Reads], [.. memory.ResidentReads]); + } + + private static Outcome RunAll(Func buffers, ulong[] arguments, ulong[]? failOnce = null) + { + var reference = Run(Path.Off, buffers, arguments, failOnce); + var outcome = Run(Path.On, buffers, arguments, failOnce); + Assert.Equal(reference.Results, outcome.Results); + Assert.Equal(reference.Ranges, outcome.Ranges); + Assert.Equal(reference.Reads, outcome.Reads); + return reference; + } + + // Both paths: a memo shared by a record's buffers and new per record, + // a failed read evaluated again by a later buffer, the 4 GiB and 48-bit rules, a written buffer that describes no buffer + // failing its record, the zero gap below the argument registers. + [Fact] + public void RecordsMatchTheInterpreterReadForRead() + { + var outcome = RunAll(Buffers, Arguments, [0x2004]); + Assert.Equal(new[] { true, true, false, true, true, true }, outcome.Results); + Assert.Equal(new ulong[] + { + 0x1000, 0x1004, 0x1008, 0x100C, + 0x2000, 0x2004, 0x2004, 0x200C, + 0x3000, 0x3004, 0x3008, 0x300C, + 0x4000, 0x4004, 0x4008, 0x400C, + 0x5000, 0x5004, 0x5008, 0x500C, + 0x1000, 0x1004, 0x1008, 0x100C, + }, outcome.Reads); + Assert.Equal(new DeviceAddressRange[] + { + new(uint.MaxValue, 0x5000, 64, true, false), new(uint.MaxValue, 0x5100, 256, true, true), new(uint.MaxValue, 0x7000, 8, true, false), + new(uint.MaxValue, 0x6100, 256, true, true), new(uint.MaxValue, 0x7000, 8, true, false), + new(uint.MaxValue, 0x8000, 16, true, false), + new(uint.MaxValue, 0x7100, 256, true, true), new(uint.MaxValue, 0x7000, 8, true, false), + new(uint.MaxValue, 0x7000, 8, true, false), + new(uint.MaxValue, 0x5000, 64, true, false), new(uint.MaxValue, 0x5100, 256, true, true), new(uint.MaxValue, 0x7000, 8, true, false), + }, outcome.Ranges); + } + + // A record whose user data reaches the argument registers throws as WithCallArguments does, on every path. + [Theory] + [InlineData(Path.Off)] + [InlineData(Path.On)] + public void UserDataReachingTheArgumentRegistersThrows(Path path) + { + using var scope = new Scope(path); + var plan = Plan(Buffers); + plan.CompileEvaluatorNow(); + var inputs = Inputs(new uint[ScalarValueGraph.CallArgumentRegisterBase + 1], new Memory(Words).Read); + var error = Assert.Throws(() => CallRecordPlanner.AddRecordRanges(plan, 0, 0x1000, inputs, 0, [])); + Assert.Equal("userDataBase", error.ParamName); + } + + // A callee the builder refuses stays on the interpreter. + [Fact] + public void RefusedCalleeStaysOnTheInterpreter() + { + using var scope = new Scope(Path.On); + CallRecordBufferWords[] Deep(ShaderResourcePlan plan) + { + var value = ArgumentRegister(0); + for (var index = 0; index < 70; index++) + value = ScalarValue.MakeOperation(ScalarOperation.IAdd32, ScalarValueType.U32, value, ScalarValue.ConstantOf((uint)index + 1)); + return [new([value, ScalarValue.ConstantOf(0u), ScalarValue.ConstantOf(8u), ScalarValue.ConstantOf(0u)], false)]; + } + var plan = Plan(Deep); + plan.CompileEvaluatorNow(); + Assert.Equal("too_deep", plan.CompiledRanges!.Record(0)!.Refusal); + var ranges = new List(); + Assert.True(CallRecordPlanner.AddRecordRanges(plan, 0, 0x1000, Inputs([0, 0, 0, 0]), 0, ranges)); + Assert.Equal(new DeviceAddressRange(uint.MaxValue, 0x1000 + 70 * 71 / 2, 8, true, false), Assert.Single(ranges)); + } + + // ---- one read of the resident reader for consecutive words ---- + + // The argument's four words are one read per record, fresh each record, with the interpreter's results; a null base + // reads its words alone, as the interpreter does. + [Fact] + public void ConsecutiveWordsTakeOneResidentReadPerRecord() + { + ulong[] arguments = [0x1000, 0x2000, 0x3000, 0x4000, 0x5000, 0x1000, 0]; + var reference = Run(Path.Off, Buffers, arguments, resident: Resident.Serve); + var outcome = Run(Path.On, Buffers, arguments, resident: Resident.Serve); + Assert.Equal(reference.Results, outcome.Results); + Assert.Equal(reference.Ranges, outcome.Ranges); + Assert.Empty(reference.ResidentReads); + Assert.Equal(arguments[..^1].Select(argument => (argument, 16)), outcome.ResidentReads); + Assert.Equal(new ulong[] { 0, 4, 8, 12 }, outcome.Reads); + } + + // A refused read leaves the record to the word reads in the interpreter's order, and is tried once per record. + [Fact] + public void RefusedResidentReadFallsBackToTheWordReads() + { + var reference = Run(Path.Off, Buffers, Arguments, [0x2004]); + var outcome = Run(Path.On, Buffers, Arguments, [0x2004], resident: Resident.Refuse); + Assert.Equal(reference.Results, outcome.Results); + Assert.Equal(reference.Ranges, outcome.Ranges); + Assert.Equal(reference.Reads, outcome.Reads); + Assert.Equal(Arguments.Select(argument => (argument, 16)), outcome.ResidentReads); + } + + // Only consecutive words are read together: the words at 0 and 4 are one read, the one at 12 is read alone. + [Fact] + public void ResidentReadsTakeOnlyConsecutiveWords() + { + CallRecordBufferWords[] Gapped(ShaderResourcePlan plan) + { + var handle = ArgumentHandle(); + return [new([ArgumentWord(plan, handle, 0), ArgumentWord(plan, handle, 4), ScalarValue.ConstantOf(8u), ArgumentWord(plan, handle, 12)], false)]; + } + var reference = Run(Path.Off, Gapped, [0x1000]); + var outcome = Run(Path.On, Gapped, [0x1000], resident: Resident.Serve); + Assert.Equal(new DeviceAddressRange[] { new(uint.MaxValue, 0x5000, 128, true, false) }, reference.Ranges); + Assert.Equal(reference.Ranges, outcome.Ranges); + Assert.Equal(new[] { (0x1000ul, 8) }, outcome.ResidentReads); + Assert.Equal(new ulong[] { 0x100C }, outcome.Reads); + } + + // A V# read through a pointer the record holds (a computed V#): the pointer's two words and the V#'s four are one read + // each. + [Fact] + public void PointerAndDescriptorWordsTakeOneResidentReadEach() + { + CallRecordBufferWords[] Indirect(ShaderResourcePlan plan) + { + var argument = ArgumentHandle(); + var pointer = ScalarValue.Handle(ScalarValueKind.AddressHandle, [ArgumentWord(plan, argument, 8), ArgumentWord(plan, argument, 12)]); + return [new([.. new[] { 0u, 4u, 8u, 12u }.Select(offset => ArgumentWord(plan, pointer, offset))], false)]; + } + var words = new Dictionary + { + [0x1008] = 0x2000, [0x100C] = 0, + [0x2000] = 0x9000, [0x2004] = 4u << 16, [0x2008] = 8, [0x200C] = 0, + }; + var reference = Run(Path.Off, Indirect, [0x1000], words: words); + var outcome = Run(Path.On, Indirect, [0x1000], resident: Resident.Serve, words: words); + Assert.Equal(new ulong[] { 0x1008, 0x100C, 0x2000, 0x2004, 0x2008, 0x200C }, reference.Reads); + Assert.Equal(new DeviceAddressRange[] { new(uint.MaxValue, 0x9000, 32, true, false) }, reference.Ranges); + Assert.Equal(reference.Ranges, outcome.Ranges); + Assert.Equal(new[] { (0x1008ul, 8), (0x2000ul, 16) }, outcome.ResidentReads); + Assert.Empty(outcome.Reads); + } + + [Theory] + [InlineData(Resident.None)] + [InlineData(Resident.Serve)] + public void CompiledRecordAllocatesNothing(Resident resident) + { + using var scope = new Scope(Path.On); + var plan = Plan(Buffers); + plan.CompileEvaluatorNow(); + var inputs = new ResourceRuntimeInputs + { + UserData = new uint[4], + ReadMemory = static (ulong address, out uint word) => Words.TryGetValue(address, out word), + ReadResidentMemory = resident == Resident.None ? null : (ResidentGuestBytesReader)(static (ulong address, Span destination, bool clean) => + { + for (var offset = 0; offset < destination.Length; offset += 4) + { + if (!Words.TryGetValue(address + (ulong)offset, out var word)) return false; + BinaryPrimitives.WriteUInt32LittleEndian(destination[offset..], word); + } + + return true; + }), + }; + var ranges = new List(64); + for (var warm = 0; warm < 4; warm++) + { + ranges.Clear(); + CallRecordPlanner.AddRecordRanges(plan, 0, 0x1000, inputs, 0, ranges); + } + + var smallest = long.MaxValue; + for (var attempt = 0; attempt < 5; attempt++) + { + ranges.Clear(); + var before = GC.GetAllocatedBytesForCurrentThread(); + CallRecordPlanner.AddRecordRanges(plan, 0, 0x1000, inputs, 0, ranges); + smallest = Math.Min(smallest, GC.GetAllocatedBytesForCurrentThread() - before); + } + + Assert.Equal(0, smallest); + Assert.Equal(3, ranges.Count); + } + + // Records evaluated on several threads at once give each thread the interpreter's ranges. + [Fact] + public void CompiledRecordsAreThreadSafe() + { + using var scope = new Scope(Path.On); + var plan = Plan(Buffers); + plan.CompileEvaluatorNow(); + var inputs = Inputs([0, 0, 0, 0], static (ulong address, out uint word) => Words.TryGetValue(address, out word)); + var expected = new List(); + var kept = Arguments.Select(argument => CallRecordPlanner.AddRecordRangesInterpreted(plan, 0, argument, inputs, 0, expected)).ToArray(); + Parallel.For(0, 8, _ => + { + for (var pass = 0; pass < 200; pass++) + { + var ranges = new List(); + Assert.Equal(kept, Arguments.Select(argument => CallRecordPlanner.AddRecordRanges(plan, 0, argument, inputs, 0, ranges)).ToArray()); + Assert.Equal(expected, ranges); + } + }); + } + + // ---- Record input boundaries, on the interpreter and the compiled code ---- + + private static ShaderResourcePlan MemoryPlan(bool written = false) + { + var plan = Extract(Program(ScalarLoad(0, 0, 4, 4), BufferLoad(8, 4), EndProgram(16)), userDataCount: 2); + var graph = plan.Graph; + var handle = graph.Handle(ScalarValueKind.AddressHandle, + graph.UserData(ScalarValueGraph.CallArgumentRegisterBase), + graph.UserData(ScalarValueGraph.CallArgumentRegisterBase + 1)); + var words = new ScalarValue[4]; + for (var word = 0; word < 4; word++) + { + Assert.True(plan.Memory.TryGetIndex(0, (uint)word, out var index)); + words[word] = graph.MemoryRead(ScalarValueKind.ScalarAddressWord, handle, graph.Constant(0u), index); + } + SetBuffers(plan, new CallRecordBufferWords(words, written)); + plan.CompileEvaluatorNow(); + return plan; + } + + [Theory] + [InlineData(Path.Off)] + [InlineData(Path.On)] + public void SameRecordPointerReadsChangedPayloadAndDoesNotMutateEarlierOutput(Path path) + { + using var scope = new Scope(path); + var plan = MemoryPlan(); + uint[] words = [0x4000, 0, 16, 0]; + var reads = new List(); + bool Read(ulong address, out uint word) + { + reads.Add(address); + Assert.InRange(address, 0x1000ul, 0x100Cul); + word = words[(int)((address - 0x1000) / 4)]; + return true; + } + var inputs = Inputs([], Read); + var first = new List(); + var second = new List(); + Assert.True(CallRecordPlanner.AddRecordRanges(plan, 0, 0x1000, inputs, 0, first)); + var saved = Assert.Single(first); + words[0] = 0x8000; + words[2] = 32; + Assert.True(CallRecordPlanner.AddRecordRanges(plan, 0, 0x1000, inputs, 0, second)); + Assert.Equal(new DeviceAddressRange(uint.MaxValue, 0x4000, 16, true, false), saved); + Assert.Equal(saved, Assert.Single(first)); + Assert.Equal(new DeviceAddressRange(uint.MaxValue, 0x8000, 32, true, false), Assert.Single(second)); + Assert.Equal(new ulong[] { 0x1000, 0x1004, 0x1008, 0x100C, 0x1000, 0x1004, 0x1008, 0x100C }, reads); + } + + [Theory] + [InlineData(Path.Off)] + [InlineData(Path.On)] + public void FailedFirstRecordRetriesInFreshStateForTheNextRecord(Path path) + { + using var scope = new Scope(path); + var plan = MemoryPlan(); + var reads = new List(); + var fail = true; + bool Read(ulong address, out uint word) + { + reads.Add(address); + word = address == 0x1000 ? 0x4000u : address == 0x1008 ? 16u : 0u; + if (fail) { fail = false; return false; } + return true; + } + var inputs = Inputs([], Read); + var first = new List(); + var second = new List(); + Assert.True(CallRecordPlanner.AddRecordRanges(plan, 0, 0x1000, inputs, 0, first)); + Assert.True(CallRecordPlanner.AddRecordRanges(plan, 0, 0x1000, inputs, 0, second)); + Assert.Empty(first); // Unresolved descriptor is skipped; it does not fail the record. + Assert.Equal(0x4000ul, Assert.Single(second).Base); + Assert.Equal(new ulong[] { 0x1000, 0x1000, 0x1004, 0x1008, 0x100C }, reads); + } + + [Theory] + [InlineData(Path.Off, false, true)] + [InlineData(Path.Off, true, false)] + [InlineData(Path.On, false, true)] + [InlineData(Path.On, true, false)] + public void OversizedReadOnlyBufferIsSkippedButWrittenBufferRejectsRecord(Path path, bool written, bool success) + { + using var scope = new Scope(path); + var plan = MemoryPlan(written); + uint[] words = [0x4000, 2u << 16, uint.MaxValue, 0]; + bool Read(ulong address, out uint word) + { + word = words[(int)((address - 0x1000) / 4)]; + return true; + } + var ranges = new List(); + Assert.Equal(success, CallRecordPlanner.AddRecordRanges(plan, 0, 0x1000, Inputs([], Read), 0, ranges)); + Assert.Empty(ranges); + } + + [Theory] + [InlineData(Path.Off)] + [InlineData(Path.On)] + public void ArgumentOverlayKeepsZeroFilledGapAndRefreshesArgument(Path path) + { + using var scope = new Scope(path); + var plan = Extract(Program(EndProgram(0)), userDataCount: 1); + var graph = plan.Graph; + // WithCallArguments currently zero-fills unused ordinary user-data slots. + var size = graph.Operation(ScalarOperation.IAdd32, ScalarValueType.U32, graph.UserData(8), graph.Constant(16u)); + SetBuffers(plan, new CallRecordBufferWords([ + graph.UserData(ScalarValueGraph.CallArgumentRegisterBase), + graph.UserData(ScalarValueGraph.CallArgumentRegisterBase + 1), size, graph.Constant(0u)], false)); + plan.CompileEvaluatorNow(); + foreach (var argument in new ulong[] { 0x4000, 0x5000, 0x4000 }) + { + var ranges = new List(); + Assert.True(CallRecordPlanner.AddRecordRanges(plan, 0, argument, Inputs([99]), 0, ranges)); + Assert.Equal(new DeviceAddressRange(uint.MaxValue, argument, 16, true, false), Assert.Single(ranges)); + } + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledDeviceAddressRangeTests.Large.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledDeviceAddressRangeTests.Large.cs new file mode 100644 index 000000000..7faec2180 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledDeviceAddressRangeTests.Large.cs @@ -0,0 +1,103 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.ShaderCompiler.Tests.Resources; + +public sealed partial class CompiledDeviceAddressRangeTests +{ + private static void SetRanges(ShaderResourcePlan plan, DeviceAddressRangePlan[] ranges) => + typeof(ShaderResourcePlan).GetProperty(nameof(ShaderResourcePlan.DeviceAddressRanges))!.SetValue(plan, ranges); + + private static ShaderResourcePlan Expanded(Scenario scenario) + { + var plan = scenario.Extract(); + scenario.Prepare?.Invoke(plan); + var original = plan.DeviceAddressRanges.ToArray(); + Assert.NotEmpty(original); + // More than 16K external roots, with shared successful and failed reads. Distinct trailing + // roots also cross method boundaries after reference-identical roots have been compacted. + var extra = Enumerable.Range(0, 128).Select(index => original[0] with + { + BaseLow = ScalarValue.MakeOperation(ScalarOperation.IAdd32, ScalarValueType.U32, + ScalarValue.UserData(0), ScalarValue.ConstantOf((uint)index)), + BaseHigh = ScalarValue.ConstantOf(0u), + }); + SetRanges(plan, Enumerable.Range(0, 8193).SelectMany(_ => original).Concat(extra) + .Select((range, index) => range with { Handle = (uint)index }).ToArray()); + return plan; + } + + [Theory] + [InlineData("table")] + [InlineData("table_failures")] + [InlineData("first_lane_read")] + [InlineData("first_lane_select")] + [InlineData("function")] + public void PartitionedPlansPreserveRangesAndReadOrderAcrossMethodBoundaries(string name) + { + var scenario = Named(name); + var plan = Expanded(scenario); + Assert.Equal("too_large", CompiledDeviceAddressRanges.Build(plan, compileLarge: false).Refusal); + var compiled = CompiledDeviceAddressRanges.Build(plan, compileLarge: true); + Assert.Null(compiled.Refusal); + Assert.True(compiled.Partitions > 1); + Assert.True(compiled.RootCount > 16384); + Assert.True(compiled.DistinctRootCount < compiled.RootCount); + var expected = new Memory(scenario.Words); + var actual = new Memory(scenario.Words); + foreach (var address in scenario.FailOnce ?? []) + { + expected.FailOnce.Add(address); + actual.FailOnce.Add(address); + } + var ranges = DeviceAddressRangePlanner.EvaluateInterpreted(plan, Inputs(scenario.UserData, expected.Read)); + Assert.Equal(ranges, compiled.Evaluate(plan, Inputs(scenario.UserData, actual.Read))); + // Shared successful reads stay memoized across pieces; a failed read is retried in the same order as the reference. + Assert.Equal(expected.Reads, actual.Reads); + } + + [Fact] + public void PartitioningRetainsTheOriginalDepthRefusal() + { + Assert.Equal("too_deep", CompiledDeviceAddressRanges.Build(DeepPlan(), compileLarge: true).Refusal); + } + + [Fact] + public void OneOversizedRootStillRefusesInsteadOfGeneratingAnOversizedMethod() + { + var plan = TablePlan(); + var nodes = Enumerable.Range(0, 2048).Select(_ => ScalarValue.UserData(0)).ToArray(); + while (nodes.Length > 1) + nodes = Enumerable.Range(0, nodes.Length / 2).Select(index => + ScalarValue.MakeOperation(ScalarOperation.IAdd32, ScalarValueType.U32, nodes[index * 2], nodes[index * 2 + 1])).ToArray(); + SetRanges(plan, [plan.DeviceAddressRanges[0] with { BaseLow = nodes[0], BaseHigh = ScalarValue.ConstantOf(0u) }]); + Assert.Equal("too_large", CompiledDeviceAddressRanges.Build(plan, compileLarge: true).Refusal); + } + + [Fact] + public void ExcessiveTotalRootsRefuseBeforeCompilingAnyPartition() + { + var plan = TablePlan(); + var range = plan.DeviceAddressRanges[0]; + SetRanges(plan, Enumerable.Range(0, 131073).Select(index => range with { Handle = (uint)index }).ToArray()); + Assert.Equal("large_root_budget", CompiledDeviceAddressRanges.Build(plan, compileLarge: true).Refusal); + } + + [Fact] + public void ExcessiveDistinctRootsRefuseEvenWithinTheExternalRootBudget() + { + var plan = TablePlan(); + var range = plan.DeviceAddressRanges[0]; + SetRanges(plan, Enumerable.Range(0, 32769).Select(index => range with + { + Handle = (uint)index, + BaseLow = ScalarValue.UserData(0), + BaseHigh = ScalarValue.UserData(1), + }).ToArray()); + Assert.Equal("large_distinct_root_budget", CompiledDeviceAddressRanges.Build(plan, compileLarge: true).Refusal); + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledDeviceAddressRangeTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledDeviceAddressRangeTests.cs new file mode 100644 index 000000000..ddde52d74 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledDeviceAddressRangeTests.cs @@ -0,0 +1,507 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; +using Mode = SharpEmu.ShaderCompiler.Resources.CompiledDeviceAddressRanges.Mode; + +namespace SharpEmu.ShaderCompiler.Tests.Resources; + +[CollectionDefinition("CompiledDeviceAddressRanges", DisableParallelization = true)] +public sealed class CompiledDeviceAddressRangeCollection; + +// SHARPEMU_COMPILED_RANGES against the interpreter: the same ranges or exception and the same reads in the same order, +// with the switch off and on. The mode is process-wide, so these tests run alone. +[Collection("CompiledDeviceAddressRanges")] +public sealed partial class CompiledDeviceAddressRangeTests +{ + public enum Path { Off, On } + + // Sets the mode for one test and restores it. + private sealed class Scope : IDisposable + { + private readonly Mode _mode = CompiledDeviceAddressRanges.Configured; + + public Scope(Path path) => CompiledDeviceAddressRanges.Configured = path switch + { + Path.On => Mode.On, + _ => Mode.Off, + }; + + public void Dispose() + { + CompiledDeviceAddressRanges.Configured = _mode; + } + } + + // Words by address and a log of every read; an address in FailOnce fails its first read. + private sealed class Memory(Dictionary words) + { + public readonly List Reads = []; + public readonly HashSet FailOnce = []; + + public bool Read(ulong address, out uint word) + { + Reads.Add(address); + word = 0; + return !FailOnce.Remove(address) && words.TryGetValue(address, out word); + } + } + + private sealed record Outcome(DeviceAddressRange[]? Ranges, string? Error, ulong[] Reads); + + private sealed record Scenario(Func Extract, uint[] UserData, Dictionary Words, + ulong[]? FailOnce = null, Action? Prepare = null); + + // A fresh plan built under the path's mode, evaluated once through DeviceAddressRangePlanner.Evaluate. + private static Outcome Run(Path path, Scenario scenario) + { + using var scope = new Scope(path); + var plan = scenario.Extract(); + scenario.Prepare?.Invoke(plan); + plan.CompileEvaluatorNow(); + if (path == Path.Off) Assert.Null(plan.CompiledRanges); + else Assert.Null(Assert.IsType(plan.CompiledRanges).Refusal); + var memory = new Memory(scenario.Words); + foreach (var address in scenario.FailOnce ?? []) memory.FailOnce.Add(address); + DeviceAddressRange[]? ranges = null; + string? error = null; + try + { + ranges = DeviceAddressRangePlanner.Evaluate(plan, Inputs(scenario.UserData, memory.Read)); + } + catch (ResourcePlanException exception) + { + error = exception.Message; + } + + return new(ranges, error, [.. memory.Reads]); + } + + // Runs both paths; the compiled code must match the interpreter's ranges or exception and its reads. + private static Outcome RunAll(Scenario scenario) + { + var reference = Run(Path.Off, scenario); + var outcome = Run(Path.On, scenario); + Assert.Equal(reference.Error, outcome.Error); + Assert.Equal(reference.Ranges, outcome.Ranges); + Assert.Equal(reference.Reads, outcome.Reads); + return reference; + } + + private static Dictionary Words(params (ulong Address, uint Word)[] words) => + words.ToDictionary(static entry => entry.Address, static entry => entry.Word); + + private static ShaderResourcePlan TablePlan() => Extract(Program( + ScalarLoad(0, 0, 8, 2), ScalarLoad(8, 2, 10, 4), + Vop1(16, "VMovB32", 0, Operand(0)), + GlobalAccess(20, "GlobalLoadDword", 8, offset: 8), + GlobalAccess(28, "GlobalStoreDword", 10, offset: -4), + GlobalAccess(36, "GlobalLoadDwordx2", 12, offset: 16, dwords: 2), + EndProgram(44)), userDataCount: 4); + + private static readonly Dictionary TableWords = + Words((0x1000, 0x5000), (0x1004, 0), (0x2000, 0x6000), (0x2004, 0), (0x2008, 0x7000), (0x200C, 0)); + + // A global load of 16 bytes at s[0:1], then function buffers through V#1 at 0x1000 (0x3000, stride 16, 4 records) and + // V#2 at 0x2000 (0x1000, 16 bytes, the global load's range): read, written, read again, V#2. + private static ShaderResourcePlan FunctionPlan() => Extract(Program( + ScalarLoad(0, 0, 4, 4), ScalarLoad(8, 2, 8, 4), + Vop1(16, "VMovB32", 0, Operand(0)), + GlobalAccess(20, "GlobalLoadDwordx4", 0, dwords: 4), + BufferLoad(28, 4), BufferStore(36, 4), BufferLoad(44, 4, offset: 4), BufferLoad(52, 8), + EndProgram(60)) with { FunctionBufferAccesses = new HashSet { 28, 36, 44, 52 } }, userDataCount: 4); + + private static readonly Dictionary FunctionWords = Words( + (0x1000, 0x3000), (0x1004, 16u << 16), (0x1008, 4), (0x100C, 0), + (0x2000, 0x1000), (0x2004, 0), (0x2008, 16), (0x200C, 0)); + + private static ShaderResourcePlan DeepPlan() + { + var instructions = new List(); + uint pc = 0; + for (var index = 0; index < 70; index++, pc += 4) + instructions.Add(Sop2(pc, index % 2 == 0 ? "SAddU32" : "SXorB32", 0, Gen5Operand.Scalar(0), Operand((uint)index + 1))); + instructions.Add(Vop1(pc, "VMovB32", 0, Operand(0))); + instructions.Add(GlobalAccess(pc + 4, "GlobalLoadDword", 0)); + instructions.Add(EndProgram(pc + 12)); + return Extract(Program([.. instructions]), userDataCount: 2); + } + + private static void WithCallRecordCallee(ShaderResourcePlan plan) => + typeof(ShaderResourcePlan).GetProperty(nameof(ShaderResourcePlan.CallRecordCallees))! + .SetValue(plan, new List { new([], [], 0) }); + + private static void MarkDeviceDescriptor(ShaderResourcePlan plan, uint pc) + { + Assert.True(plan.Memory.TryGetIndex(pc, 0, out var index)); + plan.Memory[index].DeviceDescriptor = true; + } + + private static Scenario Named(string name) => name switch + { + "bounded" => new(() => Extract(Program( + Vop1(0, "VMovB32", 0, Operand(0)), + GlobalAccess(4, "GlobalLoadDword", 0, offset: 8), + GlobalAccess(12, "GlobalLoadDwordx4", 0, offset: 32, dwords: 4), + EndProgram(20))), [0x1000, 0], []), + "negative" => new(() => Extract(Program( + Vop1(0, "VMovB32", 0, Operand(0)), + GlobalAccess(4, "GlobalStoreDword", 0, offset: -8), + GlobalAccess(12, "GlobalLoadDwordx2", 0, offset: 8, dwords: 2), + EndProgram(20))), [0x2008, 0], []), + "runtime_offset" => new(() => Extract(Program(GlobalAccess(0, "GlobalLoadDword", 0, offset: 8, vectorAddress: 0), EndProgram(8))), + [0x1000, 0], []), + "unplannable" => new(() => Extract(Program(GlobalAccess(0, "FlatStoreDword", 0, vectorAddress: 2), EndProgram(8))), [], []), + "table" => new(TablePlan, [0x1000, 0, 0x2000, 0], TableWords), + "table_failures" => new(TablePlan, [0x1000, 0, 0x2000, 0], TableWords, [0x1004, 0x2000]), + "null_base" => new(TablePlan, [0, 0, 0x2000, 0], TableWords), + "missing_user_data" => new(TablePlan, [0x1000, 0], TableWords), + "arithmetic" => new(() => Extract(Program( + ScalarLoad(0, 0, 8, 2), + Sop2(8, "SAddU32", 10, Gen5Operand.Scalar(8), Operand(0x100)), + Sop2(12, "SAddcU32", 11, Gen5Operand.Scalar(9), Operand(0)), + Vop1(16, "VMovB32", 0, Operand(0)), + GlobalAccess(20, "GlobalLoadDword", 10), + EndProgram(28)), userDataCount: 2), [0x1000, 0], Words((0x1000, 0xFFFFFF80), (0x1004, 1))), + "buffer_word" => new(() => Extract(Program( + ScalarBufferLoad(0, 0, 8, 2, immediateOffset: 8), + Vop1(8, "VMovB32", 0, Operand(0)), + GlobalAccess(12, "GlobalLoadDword", 8), + EndProgram(20)), userDataCount: 4), [0x3000, 0, 16, 0], Words((0x3008, 0x9000), (0x300C, 0))), + "buffer_word_past_records" => new(() => Extract(Program( + ScalarBufferLoad(0, 0, 8, 2, immediateOffset: 8), + Vop1(8, "VMovB32", 0, Operand(0)), + GlobalAccess(12, "GlobalLoadDword", 8), + EndProgram(20)), userDataCount: 4), [0x3000, 0, 12, 0], Words((0x3008, 0x9000), (0x300C, 0))), + "absolute" => new(() => Extract(Program( + Sop1(0, "SMovB32", 4, Operand(0x10000)), Sop1(4, "SMovB32", 5, Operand(0)), + ScalarLoad(8, 4, 8, 2), + Vop1(16, "VMovB32", 0, Operand(0)), + GlobalAccess(20, "GlobalLoadDword", 8), + EndProgram(28)), userDataCount: 2), [], []), + "first_lane" => new(() => Extract(Program( + Vop1(0, "VMovB32", 1, Gen5Operand.Scalar(0)), + ReadFirstLane(4, 8, 1), + Sop1(8, "SMovB32", 9, Gen5Operand.Scalar(1)), + Vop1(12, "VMovB32", 0, Operand(0)), + GlobalAccess(16, "GlobalLoadDword", 8), + EndProgram(24)), userDataCount: 2), [0x4000, 0], []), + // The lane select under the active mask takes its first value; the plain select would fail on the compare. + "first_lane_select" => new(() => Extract(Program( + Vopc(0, "VCmpxLtU32", Operand(3), 5), + Vop1(4, "VMovB32", 1, Gen5Operand.Scalar(0)), + ReadFirstLane(8, 8, 1), + Sop1(12, "SMovB32", 9, Gen5Operand.Scalar(1)), + Vop1(16, "VMovB32", 0, Operand(0)), + GlobalAccess(20, "GlobalLoadDword", 8), + EndProgram(28)), userDataCount: 2), [0x4000, 0], []), + // A first-lane value evaluates again in its own evaluator: the table word it wraps is read again. + "first_lane_read" => new(() => Extract(Program( + ScalarLoad(0, 0, 8, 2), + Vop1(8, "VMovB32", 1, Gen5Operand.Scalar(8)), + ReadFirstLane(12, 10, 1), + Sop1(16, "SMovB32", 11, Gen5Operand.Scalar(9)), + Vop1(20, "VMovB32", 0, Operand(0)), + GlobalAccess(24, "GlobalLoadDword", 8), + GlobalAccess(32, "GlobalLoadDword", 10), + EndProgram(40)), userDataCount: 2), [0x1000, 0], Words((0x1000, 0x5000), (0x1004, 0))), + "function" => new(FunctionPlan, [0x1000, 0, 0x2000, 0], FunctionWords), + "function_unresolved" => new(() => Extract(Program( + ScalarLoad(0, 0, 4, 4), BufferLoad(8, 4), EndProgram(16)) with { FunctionBufferAccesses = new HashSet { 8 } }, + userDataCount: 2), [0x1000, 0], Words((0x1000, 0x3000))), + "function_unresolved_callee" => new(() => Extract(Program( + ScalarLoad(0, 0, 4, 4), BufferLoad(8, 4), BufferLoad(16, 8), EndProgram(24)) + with { FunctionBufferAccesses = new HashSet { 8, 16 } }), + [0x1000, 0, 0, 0, 0, 0, 0, 0, 0x5000, 0, 8, 0], Words((0x1000, 0x3000)), Prepare: WithCallRecordCallee), + "function_missing_descriptor" => new(() => Extract(Program( + ScalarLoad(0, 0, 4, 4), BufferLoad(8, 4), + Vop1(16, "VMovB32", 0, Operand(0)), + GlobalAccess(20, "GlobalLoadDword", 2), + BufferLoad(28, 4), + EndProgram(36)) with { FunctionBufferAccesses = new HashSet { 8, 20, 28 } }, userDataCount: 4), + [0x1000, 0, 0x2000, 0], FunctionWords, Prepare: plan => MarkDeviceDescriptor(plan, 20)), + "function_swizzled" => new(() => Extract(Program(BufferLoad(0, 0), EndProgram(8)) + with { FunctionBufferAccesses = new HashSet { 0 } }), [0x2000, 0x80000000, 10, 0], []), + "function_swizzled_empty" => new(() => Extract(Program(BufferLoad(0, 0), EndProgram(8)) + with { FunctionBufferAccesses = new HashSet { 0 } }), [0x2000, 0x80000000, 0, 0], []), + "function_empty" => new(() => Extract(Program(BufferLoad(0, 0), EndProgram(8)) + with { FunctionBufferAccesses = new HashSet { 0 } }), [0x2000, 16u << 16, 0, 0], []), + "function_wraps" => new(() => Extract(Program(BufferLoad(0, 0), EndProgram(8)) + with { FunctionBufferAccesses = new HashSet { 0 } }), [0xFFFFFFF0, 0xFFFF | (16u << 16), 2, 0], []), + _ => throw new ArgumentOutOfRangeException(nameof(name)), + }; + + [Theory] + [InlineData("bounded")] + [InlineData("negative")] + [InlineData("runtime_offset")] + [InlineData("unplannable")] + [InlineData("table")] + [InlineData("table_failures")] + [InlineData("null_base")] + [InlineData("missing_user_data")] + [InlineData("arithmetic")] + [InlineData("buffer_word")] + [InlineData("buffer_word_past_records")] + [InlineData("absolute")] + [InlineData("first_lane")] + [InlineData("first_lane_select")] + [InlineData("first_lane_read")] + [InlineData("function")] + [InlineData("function_unresolved")] + [InlineData("function_unresolved_callee")] + [InlineData("function_missing_descriptor")] + [InlineData("function_swizzled")] + [InlineData("function_swizzled_empty")] + [InlineData("function_empty")] + [InlineData("function_wraps")] + public void EveryPathMatchesTheInterpreter(string name) => RunAll(Named(name)); + + [Fact] + public void TableBasesReadOnceInOrder() + { + var outcome = RunAll(Named("table")); + Assert.Null(outcome.Error); + Assert.Equal(new ulong[] { 0x1000, 0x1004, 0x2000, 0x2004, 0x2008, 0x200C }, outcome.Reads); + var ranges = outcome.Ranges!; + Assert.Contains(ranges, range => range.Planned && range.Base == 0x5008 && range.Size == 4 && !range.Written); + Assert.Contains(ranges, range => range.Planned && range.Base == 0x5FFC && range.Size == 4 && range.Written); + Assert.Contains(ranges, range => range.Planned && range.Base == 0x7010 && range.Size == 8 && !range.Written); + } + + // A failed base high leaves its range unplanned, a failed base low also skips its high, and later ranges still plan. + [Fact] + public void FailedBasesLeaveOnlyTheirRangesUnplanned() + { + var outcome = RunAll(Named("table_failures")); + Assert.Equal(new ulong[] { 0x1000, 0x1004, 0x2000, 0x2008, 0x200C }, outcome.Reads); + var ranges = outcome.Ranges!; + Assert.DoesNotContain(ranges, range => range.Planned && (range.Base == 0x5008 || range.Base == 0x5FFC)); + Assert.Contains(ranges, range => range.Planned && range.Base == 0x7010 && range.Size == 8); + Assert.Equal(2, ranges.Count(range => !range.Planned && range.Base == 0 && range.Size == 0)); + } + + [Fact] + public void FirstLaneSelectTakesTheActiveValueAndRereadsInItsOwnEvaluator() + { + var select = RunAll(Named("first_lane_select")); + Assert.Contains(select.Ranges!, range => range.Planned && range.Base == 0x4000); + var reread = RunAll(Named("first_lane_read")); + Assert.Equal(new ulong[] { 0x1000, 0x1004, 0x1000 }, reread.Reads); + Assert.Equal(2, reread.Ranges!.Count(range => range.Planned && range.Base == 0x5000)); + } + + // Function V#s dedupe by (base, size, written) among themselves, in access order; a normal range is not in that set. + [Fact] + public void FunctionBuffersDedupeInOrder() + { + var outcome = RunAll(Named("function")); + Assert.Equal(new ulong[] { 0x1000, 0x1004, 0x1008, 0x100C, 0x2000, 0x2004, 0x2008, 0x200C }, outcome.Reads); + Assert.Equal(new DeviceAddressRange[] + { + new(0, 0x1000, 16, true, false), + new(1, 0x3000, 64, true, false), + new(2, 0x3000, 64, true, true), + new(3, 0x1000, 16, true, false), + }, outcome.Ranges); + } + + [Theory] + [InlineData("function_unresolved", DeviceAddressRangePlanner.UnresolvedFunctionBuffer, 2)] + [InlineData("function_missing_descriptor", DeviceAddressRangePlanner.MissingFunctionDescriptor, 4)] + [InlineData("function_swizzled", DeviceAddressRangePlanner.SwizzledFunctionBuffer, 0)] + [InlineData("function_swizzled_empty", DeviceAddressRangePlanner.SwizzledFunctionBuffer, 0)] + [InlineData("function_wraps", DeviceAddressRangePlanner.WrappingFunctionBuffer, 0)] + public void FunctionBufferFailuresThrowAfterTheSameReads(string name, string message, int reads) + { + var outcome = RunAll(Named(name)); + Assert.Equal(message, outcome.Error); + Assert.Equal(reads, outcome.Reads.Length); + } + + // With call-record callees an unreadable V# is skipped and later V#s still resolve. + [Fact] + public void CallRecordCalleesSkipAnUnresolvedFunctionBuffer() + { + var outcome = RunAll(Named("function_unresolved_callee")); + Assert.Null(outcome.Error); + Assert.Equal(new ulong[] { 0x1000, 0x1004 }, outcome.Reads); + Assert.Equal(new DeviceAddressRange[] { new(0, 0x5000, 8, true, false) }, outcome.Ranges); + } + + [Fact] + public void EmptyFunctionBufferIsSkipped() + { + var outcome = RunAll(Named("function_empty")); + Assert.Null(outcome.Error); + Assert.Empty(outcome.Ranges!); + } + + // ---- Failure-boundary fixtures, run on every path ---- + + private static int[] GlobalRanges(ShaderResourcePlan plan) => + plan.DeviceAddressRanges.Select((range, index) => (range, index)) + .Where(entry => entry.range.MemoryIndices.Any(index => plan.Memory[index].Kind == MemoryResourceKind.Global)) + .Select(entry => entry.index).ToArray(); + + [Theory] + [InlineData(Path.Off)] + [InlineData(Path.On)] + public void FailedLowSkipsItsHighAndDoesNotAbortLaterIndependentRange(Path path) + { + using var scope = new Scope(path); + var plan = Extract(Program( + ScalarLoad(0, 0, 8, 2), ScalarLoad(8, 2, 10, 2), + Vop1(16, "VMovB32", 0, Operand(0)), + GlobalAccess(20, "GlobalLoadDword", 8), + GlobalAccess(28, "GlobalLoadDword", 10), EndProgram(36)), userDataCount: 4); + plan.CompileEvaluatorNow(); + var globals = GlobalRanges(plan); + Assert.Equal(2, globals.Length); + var reads = new List(); + bool Read(ulong address, out uint word) + { + reads.Add(address); + word = address == 0x2000 ? 0x6000u : 0u; + Assert.Contains(address, new ulong[] { 0x1000, 0x2000, 0x2004 }); + return address != 0x1000; + } + bool Clean(ulong address, out uint word) + { + word = 0; + throw new System.InvalidOperationException("Device-address range evaluation must retain its ordinary reader context."); + } + var result = DeviceAddressRangePlanner.Evaluate(plan, Inputs([0x1000, 0, 0x2000, 0], Read, Clean)); + var failed = result[globals[0]]; + Assert.False(failed.Planned); + Assert.Equal(0ul, failed.Base); + Assert.Equal(0ul, failed.Size); + var later = result[globals[1]]; + Assert.True(later.Planned); + Assert.Equal(0x6000ul, later.Base); + Assert.Equal(4ul, later.Size); + Assert.Equal(new ulong[] { 0x1000, 0x2000, 0x2004 }, reads); + } + + [Theory] + [InlineData(true, Path.Off)] + [InlineData(true, Path.On)] + [InlineData(false, Path.Off)] + [InlineData(false, Path.On)] + public void SharedFailedNodeIsRetriedButSuccessfulDependenciesStayMemoized(bool failLow, Path path) + { + using var scope = new Scope(path); + var plan = Extract(Program( + ScalarLoad(0, 0, 8, 2), Vop1(8, "VMovB32", 0, Operand(0)), + GlobalAccess(12, "GlobalLoadDword", 8), + Sop2(20, "SAddU32", 10, Gen5Operand.Scalar(8), Operand(16)), + Sop1(24, "SMovB32", 11, Gen5Operand.Scalar(9)), + GlobalAccess(28, "GlobalLoadDword", 10), EndProgram(36)), userDataCount: 2); + plan.CompileEvaluatorNow(); + var globals = GlobalRanges(plan); + Assert.Equal(2, globals.Length); + var reads = new List(); + var failedAddress = failLow ? 0x1000ul : 0x1004ul; + var didFail = false; + bool Read(ulong address, out uint word) + { + reads.Add(address); + Assert.Contains(address, new ulong[] { 0x1000, 0x1004 }); + word = address == 0x1000 ? 0x4000u : 0u; + if (address == failedAddress && !didFail) + { + didFail = true; + return false; + } + return true; + } + var result = DeviceAddressRangePlanner.Evaluate(plan, Inputs([0x1000, 0], Read)); + Assert.True(didFail); + Assert.False(result[globals[0]].Planned); + Assert.Equal(0ul, result[globals[0]].Base); + Assert.Equal(0ul, result[globals[0]].Size); + Assert.True(result[globals[1]].Planned); + Assert.Equal(0x4010ul, result[globals[1]].Base); + Assert.Equal(4ul, result[globals[1]].Size); + Assert.Equal(failLow + ? new ulong[] { 0x1000, 0x1000, 0x1004 } + : new ulong[] { 0x1000, 0x1004, 0x1004 }, reads); + } + + // ---- switch and allocation ---- + + [Fact] + public void SwitchDefaultsOnAndOffBuildsNothing() + { + Assert.Equal(Mode.On, CompiledDeviceAddressRanges.Parse(null)); + Assert.Equal(Mode.On, CompiledDeviceAddressRanges.Parse("")); + Assert.Equal(Mode.Off, CompiledDeviceAddressRanges.Parse("0")); + Assert.Equal(Mode.Off, CompiledDeviceAddressRanges.Parse("true")); + Assert.Equal(Mode.On, CompiledDeviceAddressRanges.Parse("1")); + using var scope = new Scope(Path.Off); + var plan = TablePlan(); + plan.CompileEvaluatorNow(); + Assert.Null(plan.CompiledRanges); + } + + // A shape the builder refuses stays on the interpreter. + [Fact] + public void RefusedPlanStaysOnTheInterpreter() + { + using var scope = new Scope(Path.On); + var plan = DeepPlan(); + plan.CompileEvaluatorNow(); + Assert.Equal("too_deep", plan.CompiledRanges!.Refusal); + var result = DeviceAddressRangePlanner.Evaluate(plan, Inputs([0x1000, 0])); + Assert.Equal(DeviceAddressRangePlanner.EvaluateInterpreted(plan, Inputs([0x1000, 0])), result); + } + + [Fact] + public void CompiledEvaluationAllocatesOnlyItsResult() + { + using var scope = new Scope(Path.On); + var plan = FunctionPlan(); + plan.CompileEvaluatorNow(); + var inputs = Inputs([0x1000, 0, 0x2000, 0], (ulong address, out uint word) => FunctionWords.TryGetValue(address, out word)); + for (var warm = 0; warm < 4; warm++) DeviceAddressRangePlanner.Evaluate(plan, inputs); + var length = DeviceAddressRangePlanner.EvaluateInterpreted(plan, inputs).Length; + Assert.Equal(4, length); + var start = GC.GetAllocatedBytesForCurrentThread(); + var array = new DeviceAddressRange[length]; + var arrayBytes = GC.GetAllocatedBytesForCurrentThread() - start; + GC.KeepAlive(array); + long Smallest(Func evaluate) + { + var smallest = long.MaxValue; + for (var attempt = 0; attempt < 5; attempt++) + { + var before = GC.GetAllocatedBytesForCurrentThread(); + var result = evaluate(); + smallest = Math.Min(smallest, GC.GetAllocatedBytesForCurrentThread() - before); + Assert.Equal(length, result.Length); + } + + return smallest; + } + + Assert.Equal(arrayBytes, Smallest(() => DeviceAddressRangePlanner.Evaluate(plan, inputs))); + Assert.True(Smallest(() => DeviceAddressRangePlanner.EvaluateInterpreted(plan, inputs)) > arrayBytes); + } + + [Fact] + public void CompiledEvaluationIsThreadSafe() + { + using var scope = new Scope(Path.On); + var plan = FunctionPlan(); + plan.CompileEvaluatorNow(); + var inputs = Inputs([0x1000, 0, 0x2000, 0], (ulong address, out uint word) => FunctionWords.TryGetValue(address, out word)); + var expected = DeviceAddressRangePlanner.EvaluateInterpreted(plan, inputs); + Parallel.For(0, 8, _ => + { + for (var iteration = 0; iteration < 2000; iteration++) + Assert.Equal(expected, DeviceAddressRangePlanner.Evaluate(plan, inputs)); + }); + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledResourceTransactionTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledResourceTransactionTests.cs index ed5255480..7cae04005 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledResourceTransactionTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledResourceTransactionTests.cs @@ -194,10 +194,12 @@ public void GuardReusesShapeButNotPayloadsOrCallerMutableSpecialization() Assert.Equal(expected, specialization); Assert.Equal(memory.DescriptorAddress, snapshot.Buffers[0][0]); Assert.NotEqual(previous.Buffers[0][0], snapshot.Buffers[0][0]); + // A stride is a payload too (an indexed access reads it at run time): the guard and the specialization stay. memory.DescriptorStride = 16u << 16; Assert.True(ResourceMaterializer.Materialize(plan, memory.Inputs(false), ref snapshot, ref specialization)); - Assert.NotSame(guard, plan.SpecializationGuard); - Assert.NotEqual(expected, specialization); + Assert.Same(guard, plan.SpecializationGuard); + Assert.Equal(expected, specialization); + Assert.Equal(16u << 16, snapshot.Buffers[0][1]); var saved = snapshot; var savedSpecialization = specialization; var savedGuard = plan.SpecializationGuard; diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/DeviceRecordCountTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/DeviceRecordCountTests.cs new file mode 100644 index 000000000..b37176692 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/DeviceRecordCountTests.cs @@ -0,0 +1,309 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.ShaderCompiler.Tests.Resources; + +public sealed class DeviceRecordCountTests +{ + private static readonly uint[] UserData = [0x1000, 16u << 16, 0x2000, 0]; + private static readonly DispatchBufferFootprint.Dispatch Dispatch = new(2, 1, 1, 8, 1, 1, 64, 1, new(4, null, null, null)); + + private static Gen5ShaderProgram CountProgram(bool dataIndex = false) => Program( + MoveScalarRegister(0, 8, 2), Sop2(4, "SOrB32", 9, Gen5Operand.Scalar(3), Operand(4u << 16)), + MoveScalar(8, 10, 1), MoveScalar(12, 11, 0x16204), MoveScalar(16, 3, 0x16204), + ScalarBufferLoad(20, 8, 2), + Vop3(28, "VLshlAddU32", 1, Gen5Operand.Scalar(4), Operand(3), Gen5Operand.Vector(0)), + dataIndex ? Vop1(36, "VMovB32", 1, Gen5Operand.Scalar(2)) : Nop(36), + BufferAccess(40, "BufferStoreDwordx4", 0, dwords: 4, indexEnabled: true, vectorAddress: 1), EndProgram(48)); + + private static ShaderResourcePlan Plan(Gen5ShaderProgram program, bool enabled = true) + { + var plan = ShaderResourcePlan.Extract(program, ShaderStage.Compute, Hash, 0, 4, + deviceRecordCounts: enabled); + if (plan.DeviceRecordCounts is { } counts) counts.QueueProof = action => { action(); return true; }; + return plan; + } + + [Fact] + public void PendingProofUsesTheExactCountThenInvalidatesItsCachedMaterialization() + { + var plan = Plan(CountProgram()); + var jobs = new Queue(); + var counts = plan.DeviceRecordCounts!; + counts.QueueProof = action => { jobs.Enqueue(action); return true; }; + var reads = 0; + bool Read(ulong address, out uint value) { reads++; value = 7; return true; } + static bool Resident(ulong address, Span destination, bool clean) + { + for (var index = 0; index < destination.Length; index++) + destination[index] = index % 4 == 0 ? (byte)7 : (byte)0; + return true; + } + var cache = new ResourceMaterializationCache(); + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + var inputs = InputsFor(Read); + Assert.True(cache.Materialize(plan, inputs, Resident, ref snapshot, ref specialization, out _)); + Assert.Equal(112ul, Assert.Single(snapshot.DeviceAddressRanges).Size); + Assert.Equal(0, counts.ProofRevision); + Assert.Single(jobs); + Assert.True(cache.Materialize(plan, inputs, Resident, ref snapshot, ref specialization, out _)); + Assert.Single(jobs); // Pending cache hits never enqueue the shape twice. + jobs.Dequeue()(); + Assert.Equal(1, counts.ProofRevision); + var oldReads = reads; + Assert.True(cache.Materialize(plan, inputs, Resident, ref snapshot, ref specialization, out _)); + Assert.Equal(256ul, Assert.Single(snapshot.DeviceAddressRanges).Size); + Assert.Equal(oldReads, reads); + Assert.Empty(jobs); + Assert.True(cache.Materialize(plan, InputsFor(Read, mapped: false), Resident, ref snapshot, ref specialization, out _)); + Assert.Equal(112ul, Assert.Single(snapshot.DeviceAddressRanges).Size); + Assert.Equal(oldReads + 1, reads); + Assert.True(cache.Materialize(plan, inputs, Resident, ref snapshot, ref specialization, out _)); + Assert.Equal(256ul, Assert.Single(snapshot.DeviceAddressRanges).Size); + Assert.Equal(oldReads + 1, reads); + } + + [Fact] + public void EvictionByPendingShapesCannotReuseAnUnmappedMaterialization() + { + var plan = Plan(CountProgram()); + static bool Read(ulong address, out uint value) { value = 7; return true; } + static bool Resident(ulong address, Span destination, bool clean) => false; + var cache = new ResourceMaterializationCache(); + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + Assert.True(cache.Materialize(plan, InputsFor(Read), Resident, ref snapshot, ref specialization, out _)); + Assert.True(cache.Materialize(plan, InputsFor(Read), Resident, ref snapshot, ref specialization, out _)); + Assert.Equal(256ul, Assert.Single(snapshot.DeviceAddressRanges).Size); + var revision = plan.DeviceRecordCounts!.ProofRevision; + var jobs = new Queue(); + plan.DeviceRecordCounts.QueueProof = action => { jobs.Enqueue(action); return true; }; + for (uint groups = 3; groups <= 34; groups++) + DeviceAddressRangePlanner.Evaluate(plan, InputsFor(Read, groups: groups)); + Assert.Equal(revision, plan.DeviceRecordCounts.ProofRevision); + Assert.Equal(32, jobs.Count); + Assert.True(cache.Materialize(plan, InputsFor(Read, mapped: false), Resident, ref snapshot, ref specialization, out _)); + Assert.Equal(112ul, Assert.Single(snapshot.DeviceAddressRanges).Size); + Assert.Equal(33, jobs.Count); + } + + [Fact] + public void FullProofQueueFallsBackAndRetriesAdmissionLater() + { + var plan = Plan(CountProgram()); + static bool Read(ulong address, out uint value) { value = 7; return true; } + static bool Resident(ulong address, Span destination, bool clean) => false; + var cache = new ResourceMaterializationCache(); + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + plan.DeviceRecordCounts!.QueueProof = _ => false; + Assert.True(cache.Materialize(plan, InputsFor(Read), Resident, ref snapshot, ref specialization, out _)); + Assert.Equal(112ul, Assert.Single(snapshot.DeviceAddressRanges).Size); + plan.DeviceRecordCounts.QueueProof = action => { action(); return true; }; + Assert.True(cache.Materialize(plan, InputsFor(Read), Resident, ref snapshot, ref specialization, out _)); + Assert.Equal(256ul, Assert.Single(snapshot.DeviceAddressRanges).Size); + } + + private static ResourceRuntimeInputs InputsFor(GuestWordReader reader, uint groups = 2, bool mapped = true, bool proof = true) => new() + { + UserData = UserData, ShaderBase = 0x8000, ReadMemory = reader, ReadCleanMemory = reader, + IsRangeMapped = (_, _) => mapped, + ComputeState = new(64, 8, 1, 1, false, 0, 1) + { + Dispatch = Dispatch with { GroupsX = groups }, DeviceCountProof = proof, + }, + }; + + [Fact] + public void CountStaysInTheShaderAndResidencyUsesTheWholeDispatch() + { + var program = CountProgram(); + var ordinary = Plan(program, false); + Assert.Single(ordinary.TableReads); + var plan = Plan(program); + Assert.NotNull(plan.DeviceRecordCounts); + Assert.Empty(plan.TableReads); + Assert.True(plan.Memory.Find(40)!.DeviceDescriptor); + static bool NoRead(ulong address, out uint value) => throw new InvalidOperationException($"Unexpected count read: {address:X}"); + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + Assert.True(ResourceMaterializer.Materialize(plan, InputsFor(NoRead), ref snapshot, ref specialization)); + var span = Assert.Single(snapshot.DeviceAddressRanges); + Assert.Equal(0x1000ul, span.Base); + Assert.Equal(256ul, span.Size); + Assert.True(span.Written); + + var resources = ResourceMaterializer.ApplyTo(plan, specialization); + var layout = BindingLayout.Allocate(resources.Info, BindingLayout.CollectUserDataRegisters(program, 0, 4), + false, ShaderCompileRequest.RequiresFlattenedTable(plan, resources), false, 0); + Assert.True(Gen5SpirvTranslator.TryCompileProgram(new ShaderCompileRequest(plan, resources, layout) + { + WaveSize = 64, LocalSizeX = 8, ComputeSystemRegisters = Dispatch.Registers, + }, out var compiled, out var error), error); + Gen5MipStatisticsTests.ValidateWhenAvailable(compiled.Spirv); + } + + [Theory] + [InlineData(true, true, true)] + [InlineData(false, false, true)] + [InlineData(false, true, false)] + public void UnknownIndexUnmappedSpanAndOffSwitchReadTheActualCount(bool dataIndex, bool mapped, bool proof) + { + var reads = 0; + bool Read(ulong address, out uint value) + { + Assert.Equal(0x2000ul, address); + reads++; value = 7; return true; + } + var plan = Plan(CountProgram(dataIndex)); + var spans = DeviceAddressRangePlanner.Evaluate(plan, InputsFor(Read, mapped: mapped, proof: proof)); + var span = Assert.Single(spans); + Assert.Equal(112ul, span.Size); + Assert.Equal(1, reads); + Assert.True(plan.Memory.Find(40)!.DeviceDescriptor); + } + + [Fact] + public void DispatchChangesCannotReuseThePreviousFootprint() + { + static bool NoRead(ulong address, out uint value) => throw new InvalidOperationException(); + var plan = Plan(CountProgram()); + Assert.Equal(256ul, Assert.Single(DeviceAddressRangePlanner.Evaluate(plan, InputsFor(NoRead))).Size); + Assert.Equal(512ul, Assert.Single(DeviceAddressRangePlanner.Evaluate(plan, InputsFor(NoRead, groups: 4))).Size); + } + + [Fact] + public void ReturningToACachedShapeRechecksItsMapping() + { + var reads = 0; + bool Read(ulong address, out uint value) { reads++; value = 7; return true; } + var plan = Plan(CountProgram()); + Assert.Equal(256ul, Assert.Single(DeviceAddressRangePlanner.Evaluate(plan, InputsFor(Read))).Size); + Assert.Equal(512ul, Assert.Single(DeviceAddressRangePlanner.Evaluate(plan, InputsFor(Read, groups: 4))).Size); + Assert.Equal(0, reads); + Assert.Equal(112ul, Assert.Single(DeviceAddressRangePlanner.Evaluate(plan, InputsFor(Read, mapped: false))).Size); + Assert.Equal(1, reads); + Assert.Equal(256ul, Assert.Single(DeviceAddressRangePlanner.Evaluate(plan, InputsFor(Read))).Size); + Assert.Equal(1, reads); + } + + [Fact] + public void UnmodifiedDescriptorAndCountStayEligibleAcrossLoopHeaders() + { + var instructions = CountProgram().Instructions.Where(instruction => instruction.Pc < 36).ToList(); + instructions.AddRange([ + MoveScalar(36, 6, 0), + BufferAccess(40, "BufferStoreDwordx4", 0, dwords: 4, indexEnabled: true, vectorAddress: 1), + Sop2(48, "SAddI32", 6, Gen5Operand.Scalar(6), Operand(1)), + Sopc(52, "SCmpLtU32", Gen5Operand.Scalar(6), Operand(2)), + Branch(56, "SCbranchScc1", -5), EndProgram(60), + ]); + var plan = Plan(Program(instructions.ToArray())); + Assert.NotNull(plan.DeviceRecordCounts); + Assert.Empty(plan.TableReads); + Assert.True(plan.Memory.Find(40)!.DeviceDescriptor); + static bool NoRead(ulong address, out uint value) => throw new InvalidOperationException(); + Assert.Equal(256ul, Assert.Single(DeviceAddressRangePlanner.Evaluate(plan, InputsFor(NoRead))).Size); + } + + [Theory] + [InlineData(0u)] // The descriptor base changes each iteration. + [InlineData(2u)] // The loaded count changes each iteration. + public void ChangingDescriptorWordsAcrossLoopHeadersRemainIneligible(uint changedRegister) + { + var instructions = CountProgram().Instructions.Where(instruction => instruction.Pc < 36).ToList(); + instructions.AddRange([ + MoveScalar(36, 6, 0), + BufferAccess(40, "BufferStoreDwordx4", 0, dwords: 4, indexEnabled: true, vectorAddress: 1), + Sop2(48, "SAddI32", changedRegister, Gen5Operand.Scalar(changedRegister), Operand(16)), + Sop2(52, "SAddI32", 6, Gen5Operand.Scalar(6), Operand(1)), + Sopc(56, "SCmpLtU32", Gen5Operand.Scalar(6), Operand(2)), + Branch(60, "SCbranchScc1", -6), EndProgram(64), + ]); + var graph = ScalarValueGraph.Build(Program(instructions.ToArray()), 0, 4); + Assert.Null(DeviceRecordCountPlan.Create(graph, ShaderStage.Compute)); + } + + [Fact] + public void UnsupportedDescriptorModeSelectsTheOrdinaryPlan() + { + var plan = Plan(CountProgram()); + Assert.False(plan.DeviceRecordCounts!.SupportsDescriptors(plan, new() + { + UserData = [0x1000, (16u << 16) | 0x80000000, 0x2000, 0], + })); + Assert.False(Plan(CountProgram(), false).Memory.Find(40)!.DeviceDescriptor); + } + + [Fact] + public void UnknownBranchesIncludeBothStoreAddresses() + { + var program = Program(ScalarLoad(0, 0, 8), Sopc(8, "SCmpEqU32", Gen5Operand.Scalar(8), Operand(0)), + Branch(12, "SCbranchScc1", 2), Vop1(16, "VMovB32", 1, Operand(20)), Branch(20, "SBranch", 1), + Vop1(24, "VMovB32", 1, Operand(40)), + BufferAccess(28, "BufferStoreDword", 0, indexEnabled: true, vectorAddress: 1), EndProgram(36)); + Assert.True(DispatchBufferFootprint.TryEvaluate(program, [0x1000, 4u << 16, 100, 0x16204], 0, + Dispatch with { GroupsX = 1 }, new HashSet { 28 }, out var spans)); + Assert.Equal(164ul, spans[28].Size); + } + + [Theory] + [InlineData("SCbranchScc1", 1u)] + [InlineData("SCbranchScc0", 0u)] + public void KnownUntakenBranchesStillIncludeFallthroughStores(string opcode, uint compared) + { + var program = Program(Sopc(0, "SCmpEqU32", Operand(compared), Operand(0)), + Branch(4, opcode, 4), Vop1(8, "VMovB32", 1, Operand(20)), + BufferAccess(12, "BufferStoreDword", 0, indexEnabled: true, vectorAddress: 1), + EndProgram(20), EndProgram(24)); + Assert.True(DispatchBufferFootprint.TryEvaluate(program, [0x1000, 4u << 16, 100, 0x16204], 0, + Dispatch with { GroupsX = 1 }, new HashSet { 12 }, out var spans)); + Assert.Equal(84ul, spans[12].Size); + } + + [Fact] + public void SdwaComparePoisonsItsActualScalarDestination() + { + var compare = Vopc(4, "VCmpLtU32", Gen5Operand.Vector(2), 3) with + { + Control = new Gen5SdwaControl(6, 0, 6, 6, false, false, 0, 0, 0, false, 8), + Destinations = [Gen5Operand.Scalar(8)], + }; + var program = Program(MoveScalar(0, 8, 0), compare, Vop1(8, "VMovB32", 1, Gen5Operand.Scalar(8)), + BufferAccess(12, "BufferStoreDword", 0, indexEnabled: true, vectorAddress: 1), EndProgram(20)); + Assert.False(DispatchBufferFootprint.TryEvaluate(program, [0x1000, 4u << 16, 100, 0x16204], 0, + Dispatch with { GroupsX = 1 }, new HashSet { 12 }, out _)); + } + + [Fact] + public void PartialExecWritesPreserveInactiveLanesInTheBound() + { + var program = Program(Vop1(0, "VMovB32", 1, Operand(100)), + Sop1(4, "SMovB64", 126, Operand(1)), Vop1(8, "VMovB32", 1, Operand(0)), + Sop1(12, "SMovB64", 126, Gen5Operand.Source(193)), + BufferAccess(16, "BufferStoreDword", 0, indexEnabled: true, vectorAddress: 1), EndProgram(24)); + Assert.True(DispatchBufferFootprint.TryEvaluate(program, [0x1000, 4u << 16, 200, 0x16204], 0, + Dispatch with { GroupsX = 1 }, new HashSet { 16 }, out var spans)); + Assert.Equal(404ul, spans[16].Size); + } + + [Fact] + public void ReciprocalRoundingAlternativesSurviveIntegerConversion() + { + var program = Program(Vop1(0, "VCvtF32U32", 1, Operand(8)), + Vop1(4, "VRcpIflagF32", 1, Gen5Operand.Vector(1)), + Vop2(8, "VMulF32", 1, Gen5Operand.Vector(1), Operand(BitConverter.SingleToUInt32Bits(32))), + Vop1(12, "VCvtU32F32", 1, Gen5Operand.Vector(1)), ReadFirstLane(16, 6, 1), + Vop1(20, "VMovB32", 1, Gen5Operand.Scalar(6)), + BufferAccess(24, "BufferStoreDword", 0, indexEnabled: true, vectorAddress: 1), EndProgram(32)); + Assert.True(DispatchBufferFootprint.TryEvaluate(program, [0x1000, 4u << 16, 100, 0x16204], 0, + Dispatch with { GroupsX = 1 }, new HashSet { 24 }, out var spans)); + Assert.Equal(20ul, spans[24].Size); + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/DirectImageTableTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/DirectImageTableTests.cs index c1ddee5b7..18b0a5df0 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/DirectImageTableTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/DirectImageTableTests.cs @@ -311,14 +311,13 @@ bool Read(ulong address, out uint word) [Theory] [InlineData(false)] [InlineData(true)] - public void MixedDimensionsRetainEveryCandidateAndUseSeparateBindings(bool arrayFirst) + public void MixedDimensionsRetainEveryCandidateAsArrayReads(bool arrayFirst) { var (snapshot, request) = PrepareMixedDimensions(1, arrayFirst); Assert.Equal(3, snapshot.Images.Length); var images = request.Resources.Info.Images; Assert.Equal(3, images[0].IndirectResources.Count); - Assert.Contains(images, image => image.Dimension == ImageDimension.Dim2D); - Assert.Contains(images, image => image.Dimension == ImageDimension.Dim2DArray); + Assert.All(images, image => Assert.Equal(ImageDimension.Dim2DArray, image.Dimension)); var mapping = (int)images[0].IndirectMappingOffset; Assert.Equal(32u, snapshot.FlattenedResourceTable[mapping]); Assert.Equal(344u + 31 * 32, snapshot.FlattenedResourceTable[mapping + 63]); diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/FastMaterializationCheck.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/FastMaterializationCheck.cs index cabbc08b5..e1fe5b179 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/FastMaterializationCheck.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/FastMaterializationCheck.cs @@ -85,6 +85,11 @@ private static void CompareOne(ShaderResourcePlan plan, ResourceSnapshot expecte { throw new InvalidOperationException($"The fast table, user data or ranges differ: hash=0x{plan.Hash:X16}."); } + + if (!expected.Heaps.AsSpan().SequenceEqual(fast.Heaps)) + { + throw new InvalidOperationException($"The fast bindless heaps differ: hash=0x{plan.Hash:X16}."); + } } private static void Same(string what, ShaderResourcePlan plan, uint[][] expected, uint[][] actual) diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/FlattenedReadReuseTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/FlattenedReadReuseTests.cs index 36d2a9398..d3e755407 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/FlattenedReadReuseTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/FlattenedReadReuseTests.cs @@ -41,7 +41,8 @@ internal static Gen5ShaderProgram RepeatedReadProgram(uint components, bool dyna public void EquivalentReads_ShareHostReadsAndPreserveEveryDestination(uint components) { var program = RepeatedReadProgram(components); - var (plan, resources, layout) = Prepare(program, userDataCount: 9); + // The host-flattened table, independent of the process policy (SHARPEMU_GPU_SCALAR_DATA). + var (plan, resources, layout) = Prepare(program, userDataCount: 9, scalarDataOnDevice: false); var request = new ShaderCompileRequest(plan, resources, layout); Assert.Equal((int)components, plan.TableReads.Count); Assert.False(plan.Info.UsesDeviceAddresses); @@ -68,7 +69,8 @@ public void EquivalentReads_ShareHostReadsAndPreserveEveryDestination(uint compo [InlineData(4u)] public void EquivalentReads_CompileWithoutDeviceAddressBindings(uint components) { - var request = Request(RepeatedReadProgram(components), userDataCount: 9); + // The host-flattened table, independent of the process policy (SHARPEMU_GPU_SCALAR_DATA). + var request = Request(RepeatedReadProgram(components), userDataCount: 9, scalarDataOnDevice: false); Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var spirv, out var spirvError), spirvError); var module = new SpirvModuleInspector(spirv.Spirv); Assert.Equal(0u, module.AddressingModel); diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceBranchTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceBranchTests.cs index 391302dd3..4f915ed73 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceBranchTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceBranchTests.cs @@ -7,8 +7,12 @@ namespace SharpEmu.ShaderCompiler.Tests.Resources; -public sealed class ResourceBranchTests +public class ResourceBranchTests { + // Null: the configured path (the materialization program, else the fallback in tests). The derived class runs every + // case through the compiled branch transaction. + internal virtual RuntimeValueEvaluator.CompiledBranchMode? BranchMode => null; + private static Gen5ShaderProgram ConditionalBuffers(string branch = "SCbranchScc1", bool shared = false) => Program( Sopc(0, "SCmpEqU32", Gen5Operand.Scalar(8), Operand(1)), Branch(4, branch, 3), BufferLoad(8, 0), Branch(16, "SBranch", 2), @@ -36,14 +40,54 @@ public void EmptySourceEvaluationPreservesBranchActivity(uint condition) private static bool CleanRead(ulong address, out uint word) { word = 0; return false; } - private static ResourceSnapshot Materialize(ShaderResourcePlan plan, uint[] userData, GuestWordReader? cleanReader) + private ResourceSnapshot Materialize(ShaderResourcePlan plan, uint[] userData, GuestWordReader? cleanReader) => + Materialize(plan, Inputs(userData, readCleanMemory: cleanReader)); + + private ResourceSnapshot Materialize(ShaderResourcePlan plan, ResourceRuntimeInputs inputs) => Materialize(plan, inputs, out _); + + private ResourceSnapshot Materialize(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, out ResourceSpecialization specialization) { var snapshot = new ResourceSnapshot(); - var specialization = new ResourceSpecialization(); - Assert.True(ResourceMaterializer.Materialize(plan, Inputs(userData, readCleanMemory: cleanReader), ref snapshot, ref specialization)); + specialization = new ResourceSpecialization(); + var mode = BranchMode; + if (mode is not null) + { + plan.CompileEvaluatorNow(); + inputs = WithTablePhase(inputs); + } + + var served = RuntimeValueEvaluator.BranchesServedOnThread; + RuntimeValueEvaluator.BranchModeOverride = mode; + try + { + Assert.True(ResourceMaterializer.Materialize(plan, inputs, ref snapshot, ref specialization)); + } + finally + { + RuntimeValueEvaluator.BranchModeOverride = null; + } + + if (plan.ResourceBranches.Count != 0 && mode == RuntimeValueEvaluator.CompiledBranchMode.On) + Assert.True(RuntimeValueEvaluator.BranchesServedOnThread > served, "the compiled branch transaction did not serve"); return snapshot; } + // The materialization cache reads with a table phase, which leaves the materialization program out, so the + // selected sources are evaluated by the compiled branch transaction. + private static ResourceRuntimeInputs WithTablePhase(ResourceRuntimeInputs inputs) => new() + { + UserData = inputs.UserData, + ShaderBase = inputs.ShaderBase, + ReadMemory = inputs.ReadMemory, + ReadCleanMemory = inputs.ReadCleanMemory, + ComputeState = inputs.ComputeState, + IsRangeMapped = inputs.IsRangeMapped, + TraceImageCandidate = inputs.TraceImageCandidate, + TablePhase = inputs.TablePhase ?? (static _ => { }), + ReadResidentMemory = inputs.ReadResidentMemory, + ReadsClean = inputs.ReadsClean, + }; + [Theory] [InlineData("SCbranchScc1", 0u, 0)] [InlineData("SCbranchScc1", 1u, 1)] @@ -94,13 +138,108 @@ public void ShaderWritesAndAtomicsDisablePruning(bool atomic) { var instructions = ConditionalBuffers().Instructions.ToArray(); instructions[2] = atomic ? BufferAtomicAdd(8, 0) : BufferStore(8, 0); - var plan = Extract(Program(instructions)); + var plan = ExtractWithWrites(Program(instructions), false); Assert.Empty(plan.ResourceBranches); var snapshot = Materialize(plan, UserData(1), CleanRead); Assert.Equal(0x1000u, snapshot.Buffers[0][0]); Assert.Equal(0x2000u, snapshot.Buffers[1][0]); } + // A count read from the buffer at s[0:3] guards a 2D-array sample of the T# at s[8:15]; the shader then stores + // through the buffer at s[4:7]. The count is the first word of the guest memory at 0x1000. + private static Gen5ShaderProgram CountedSampleThenStore() => Program( + ScalarBufferLoad(0, 0, 24), Sopc(8, "SCmpEqU32", Gen5Operand.Scalar(24), Operand(0)), Branch(12, "SCbranchScc1", 2), + Image(16, "ImageSample", 8, 16, dimension: 5), BufferStore(24, 4), EndProgram(32)); + + private static readonly uint[] VolumeImage = [.. ResourceTrackerTests.ImageDescriptor()[..3], + (ResourceTrackerTests.ImageDescriptor()[3] & 0x0FFFFFFFu) | (GuestImageFormat.ImageType3D << 28), 0, 0, 0, 0]; + + private static ShaderResourcePlan ExtractWithWrites(Gen5ShaderProgram program, bool allowed) + { + ResourceBranchBlock.WritesOverride = allowed; + try + { + return Extract(program); + } + finally + { + ResourceBranchBlock.WritesOverride = null; + } + } + + private static ResourceRuntimeInputs CountedInputs(uint count, uint writtenBase, uint writtenWord1) + { + var memory = ResourceTrackerTests.LinearMemory(); + memory.At(0x1000) = count; + uint[] userData = [0x1000, 0, 16, 0, writtenBase, writtenWord1, 64, 0, .. VolumeImage, 0, 0, 0, 0]; + return Inputs(userData, memory.Read, memory.Read); + } + + private ResourceSnapshot MaterializeCounted(uint count, uint writtenBase, uint writtenWord1, out ResourceSpecialization specialization, + out ShaderResourcePlan plan) + { + plan = ExtractWithWrites(CountedSampleThenStore(), true); + return Materialize(plan, CountedInputs(count, writtenBase, writtenWord1), out specialization); + } + + [Fact] + public void WritingShaderPrunesWhenNoWriteCanReachItsPredicate() + { + var snapshot = MaterializeCounted(0, 0x1800, 0, out var specialization, out var plan); + Assert.NotEmpty(plan.ResourceBranches); + Assert.Equal(0x1800u, snapshot.Buffers[(int)Assert.Single(plan.ResourceBranchWrites)][0]); + Assert.All(Assert.Single(snapshot.Images), word => Assert.Equal(0u, word)); + // The sample the count skips does not specialize the module: a null image keeps the 2D-array view it samples. + Assert.Equal(ImageDimension.Dim2DArray, Assert.Single(specialization.Images).Dimension); + } + + [Theory] + [InlineData(1u, 0x1800u, 0u)] + [InlineData(0u, 0x1000u, 0u)] + [InlineData(0u, 0x0F00u, 0u)] + [InlineData(0u, 0x1800u, 0x8000_0000u)] + public void WritingShaderKeepsTheSampleItMayReach(uint count, uint writtenBase, uint writtenWord1) + { + // A taken branch, a store whose buffer (or its margin) covers the count, or a swizzled store keeps every source. + var snapshot = MaterializeCounted(count, writtenBase, writtenWord1, out var specialization, out _); + Assert.Equal(VolumeImage, Assert.Single(snapshot.Images)); + Assert.Equal(ImageDimension.Dim3D, Assert.Single(specialization.Images).Dimension); + } + + [Fact] + public void WritesOutsideStaticBuffersKeepTheOldRule() + { + var instructions = CountedSampleThenStore().Instructions.ToArray(); + instructions[4] = GlobalAccess(24, "GlobalStoreDword", 4); + Assert.Empty(ExtractWithWrites(Program(instructions), true).ResourceBranches); + Assert.NotEmpty(ExtractWithWrites(CountedSampleThenStore(), true).ResourceBranches); + Assert.Empty(ExtractWithWrites(CountedSampleThenStore(), false).ResourceBranches); + } + + // ConditionalBuffers, then a write to LDS or scratch where both paths join. It writes through no buffer. + private static Gen5ShaderProgram ConditionalBuffersThenPrivateWrite(bool scratch) => Program([ + .. ConditionalBuffers().Instructions.SkipLast(1), + scratch ? GlobalMemory(28, "ScratchStoreDword", NullOperand, 0, 0, 8) : DataShareWrite(28, gds: false), + EndProgram(36)]); + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void PrivateWritesKeepTheBlocks(bool scratch) + { + var original = ExtractWithWrites(ConditionalBuffersThenPrivateWrite(scratch), false); + Assert.Empty(original.ResourceBranches); + var plan = ExtractWithWrites(ConditionalBuffersThenPrivateWrite(scratch), true); + Assert.NotEmpty(plan.ResourceBranches); + Assert.True(plan.ResourceBranchesWithWrites); + Assert.Empty(plan.ResourceBranchWrites); + + // With the switch, the path the condition skips materializes its buffer as null. + var selected = Materialize(plan, Inputs(UserData(1), readCleanMemory: CleanRead)); + Assert.All(selected.Buffers[0], word => Assert.Equal(0u, word)); + Assert.Equal(0x2000u, selected.Buffers[1][0]); + } + [Fact] public void UnknownBranchConditionKeepsBothPaths() { @@ -120,11 +259,10 @@ public void UnreadablePredicateDoesNotFallBackToGeneralMemory() uint[] userData = [.. UserData(1), 0, 0, 0, 0x3000, 0]; var generalReads = 0; bool GeneralRead(ulong address, out uint word) { generalReads++; word = 1; return true; } - var snapshot = new ResourceSnapshot(); - var specialization = new ResourceSpecialization(); + ResourceSnapshot snapshot; using (MaterializationProgramCheck.Suspend()) { - Assert.True(ResourceMaterializer.Materialize(plan, Inputs(userData, GeneralRead, CleanRead), ref snapshot, ref specialization)); + snapshot = Materialize(plan, Inputs(userData, GeneralRead, CleanRead)); } Assert.Equal(0x1000u, snapshot.Buffers[0][0]); @@ -196,3 +334,8 @@ public void UnknownInnerBranchKeepsBothSuccessors() Assert.Equal(0x2000u, snapshot.Buffers[1][0]); } } + +public sealed class CompiledResourceBranchTests : ResourceBranchTests +{ + internal override RuntimeValueEvaluator.CompiledBranchMode? BranchMode => RuntimeValueEvaluator.CompiledBranchMode.On; +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceMaterializerTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceMaterializerTests.cs index f20842703..aa83b2140 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceMaterializerTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceMaterializerTests.cs @@ -323,7 +323,7 @@ public void FailedMaterialization_LeavesSnapshotAndSpecializationUnchanged() { var plan = Extract(Program(BufferLoad(0, 0), EndProgram(8))); var snapshot = new ResourceSnapshot { UserData = [0xFEEDBEEF] }; - var specialization = new ResourceSpecialization { Buffers = [new BufferSpecialization(7, 0, 0)] }; + var specialization = new ResourceSpecialization { Buffers = [new BufferSpecialization(7, 0)] }; var priorSnapshot = snapshot; var priorSpecialization = specialization; @@ -331,7 +331,7 @@ public void FailedMaterialization_LeavesSnapshotAndSpecializationUnchanged() Assert.Same(priorSnapshot, snapshot); Assert.Same(priorSpecialization, specialization); Assert.Equal([0xFEEDBEEFu], snapshot.UserData); - Assert.Equal(7u, specialization.Buffers[0].PackedStride); + Assert.Equal(7u, specialization.Buffers[0].DescriptorFormat); } [Fact] diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceTestProgram.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceTestProgram.cs index a1946753f..e9f6a2538 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceTestProgram.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceTestProgram.cs @@ -167,17 +167,22 @@ public static Gen5ShaderInstruction MoveVectorFromScalar(uint pc, uint destinati public static Gen5ShaderProgram Program(params Gen5ShaderInstruction[] instructions) => new(0, instructions); + // The helpers plan scalar data reads into the host-flattened table unless a test asks for device reads, whatever the + // process default (ScalarDataReadPolicy). public static ShaderResourcePlan Extract(Gen5ShaderProgram program, uint userDataBase = 0, uint userDataCount = 64, ShaderStage stage = ShaderStage.Compute, - uint waveSize = 64) => - ShaderResourcePlan.Extract(program, stage, Hash, userDataBase, userDataCount, waveSize: waveSize); + uint waveSize = 64, bool bindlessNullDescriptors = false, bool bindlessHeap = false) => + ShaderResourcePlan.Extract(program, stage, Hash, userDataBase, userDataCount, waveSize: waveSize, + bindlessNullDescriptors: bindlessNullDescriptors, bindlessHeap: bindlessHeap, scalarDataOnDevice: false); // The plan, its default specialization applied, and the layout of one program. public static (ShaderResourcePlan Plan, SpecializedResourceInfo Resources, BindingLayout Layout) Prepare( Gen5ShaderProgram program, ShaderStage stage = ShaderStage.Compute, uint userDataBase = 0, uint userDataCount = 64, uint pushDataStartDword = 0, - bool usesDispatchThreadLimits = false, bool callRecords = false, bool callMarks = false, bool tableBlock = false) + bool usesDispatchThreadLimits = false, bool bindlessNullDescriptors = false, bool bindlessHeap = false, + bool callRecords = false, bool callMarks = false, bool scalarDataOnDevice = false, bool tableBlock = false) { var plan = ShaderResourcePlan.Extract(program, stage, Hash, userDataBase, userDataCount, - callRecords: callRecords, callMarks: callMarks); + bindlessNullDescriptors: bindlessNullDescriptors, bindlessHeap: bindlessHeap, callRecords: callRecords, callMarks: callMarks, + scalarDataOnDevice: scalarDataOnDevice); var resources = ResourceMaterializer.ApplyTo(plan, ResourceSpecialization.Default(plan.Info)); var layout = BindingLayout.Allocate( resources.Info, @@ -195,10 +200,12 @@ public static (ShaderResourcePlan Plan, SpecializedResourceInfo Resources, Bindi } public static ShaderCompileRequest Request(Gen5ShaderProgram program, ShaderStage stage = ShaderStage.Compute, uint userDataBase = 0, uint userDataCount = 64, uint pushDataStartDword = 0, - bool callRecords = false, bool callMarks = false, bool tableBlock = false) + bool bindlessNullDescriptors = false, bool bindlessHeap = false, bool callRecords = false, bool callMarks = false, + bool scalarDataOnDevice = false, bool tableBlock = false) { var (plan, resources, layout) = Prepare(program, stage, userDataBase, userDataCount, pushDataStartDword, - callRecords: callRecords, callMarks: callMarks, tableBlock: tableBlock); + bindlessNullDescriptors: bindlessNullDescriptors, bindlessHeap: bindlessHeap, callRecords: callRecords, callMarks: callMarks, + scalarDataOnDevice: scalarDataOnDevice, tableBlock: tableBlock); return new ShaderCompileRequest(plan, resources, layout) { PixelOutputs = stage == ShaderStage.Pixel ? [new Gen5PixelOutputBinding(0, 0, Gen5PixelOutputKind.Float)] : [], diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceTrackerTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceTrackerTests.cs index eb181047f..d682528d6 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceTrackerTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceTrackerTests.cs @@ -31,6 +31,122 @@ public void ImageAtomicOnTwoDataDwordsIsMarkedWide(string opcode, uint dmask, bo Assert.Equal(wide, image.Atomic64); } + // A descriptor word that 40 branches each change on both sides is a web with 2^40 paths. Planning and evaluating + // it must look at each node once: walking every path did not finish. + [Fact] + public void ADescriptorWordMergedThroughManyBranchesIsPlannedQuickly() + { + var instructions = new List + { + // s5..s7 are loaded words; s4 starts as user data. + ScalarLoad(0, 0, 8, count: 4), + MoveScalarRegister(8, 5, 9), + MoveScalarRegister(12, 6, 10), + MoveScalarRegister(16, 7, 11), + MoveScalarRegister(20, 4, 2), + }; + var pc = 24u; + for (var branch = 0; branch < 40; branch++, pc += 20) + { + // if (s3 == 0) s4 += 1; else s4 += 2; + instructions.Add(Sopc(pc, "SCmpEqU32", Gen5Operand.Scalar(3), Operand(0))); + instructions.Add(Branch(pc + 4, "SCbranchScc0", 2)); + instructions.Add(Sop2(pc + 8, "SAddU32", 4, Gen5Operand.Scalar(4), Operand(1))); + instructions.Add(Branch(pc + 12, "SBranch", 1)); + instructions.Add(Sop2(pc + 16, "SAddU32", 4, Gen5Operand.Scalar(4), Operand(2))); + } + + instructions.Add(BufferLoad(pc, 4)); + instructions.Add(EndProgram(pc + 8)); + var program = Program([.. instructions]); + + // The V# words s5..s7 are read at 0x1000; s2 = 0x2000 and s3 = 0, so every branch adds 1. + var memory = new TestWordMemory { Words = [0, 0, 16, 0] }; + var userData = new uint[64]; + userData[0] = 0x1000; + userData[2] = 0x2000; + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + var materialized = false; + Exception? failure = null; + var planning = new Thread(() => + { + try + { + var plan = Extract(program); + materialized = ResourceMaterializer.Materialize(plan, Inputs(userData, memory.Read, memory.Read), + ref snapshot, ref specialization); + } + catch (Exception exception) + { + failure = exception; + } + }) + { + IsBackground = true, + }; + planning.Start(); + + Assert.True(planning.Join(TimeSpan.FromSeconds(30)), "planning did not finish"); + Assert.Null(failure); + Assert.True(materialized); + Assert.Equal(0x2000u + 40u, Assert.Single(snapshot.Buffers)[0]); + } + + // Behind exec branches the same word is a web of phis, which the runtime-descriptor check walks for a memory read. + // A buffer base that differs per lane cannot be bound, so the plan is rejected, at once. + [Fact] + public void ADescriptorWordMergedThroughManyExecBranchesIsPlannedQuickly() + { + var instructions = new List + { + ScalarLoad(0, 0, 8, count: 4), + MoveScalarRegister(8, 5, 9), + MoveScalarRegister(12, 6, 10), + MoveScalarRegister(16, 7, 11), + MoveScalarRegister(20, 4, 2), + // One more exec branch makes s5..s7 phis too, which the check accepts as runtime words. + Vopc(24, "VCmpxEqU32", Operand(1), 24), + Branch(28, "SCbranchExecz", 3), + Sop2(32, "SAddU32", 5, Gen5Operand.Scalar(5), Operand(1)), + Sop2(36, "SAddU32", 6, Gen5Operand.Scalar(6), Operand(1)), + Sop2(40, "SAddU32", 7, Gen5Operand.Scalar(7), Operand(1)), + }; + var pc = 44u; + for (var branch = 0; branch < 40; branch++, pc += 12) + { + // Lanes where v24 == 1 add 1 to s4; with none, the block is skipped. + instructions.Add(Vopc(pc, "VCmpxEqU32", Operand(1), 24)); + instructions.Add(Branch(pc + 4, "SCbranchExecz", 1)); + instructions.Add(Sop2(pc + 8, "SAddU32", 4, Gen5Operand.Scalar(4), Operand(1))); + } + + instructions.Add(BufferLoad(pc, 4)); + instructions.Add(EndProgram(pc + 8)); + var program = Program([.. instructions]); + + Exception? failure = null; + var planning = new Thread(() => + { + try + { + Extract(program); + } + catch (Exception exception) + { + failure = exception; + } + }) + { + IsBackground = true, + }; + planning.Start(); + + Assert.True(planning.Join(TimeSpan.FromSeconds(30)), "planning did not finish"); + var rejection = Assert.IsType(failure); + Assert.Contains("BufferHandle dword 0 is not a valid runtime value", rejection.Message); + } + [Fact] public void DenseBufferTracking() { @@ -199,22 +315,64 @@ public void ImageDescriptorLoadedAtALaneChosenIndexInCompute_IsStillRejected() [Fact] public void SamplerLoadedAtALaneChosenIndex_IsStillRejected() { - var program = Program( - MoveScalarRegister(0, 16, 0), - MoveScalarRegister(4, 17, 1), - MoveScalarRegister(8, 18, 2), - MoveScalarRegister(12, 19, 3), - Vop2(16, "VLshlrevB32", 1, Operand(12), Gen5Operand.Vector(0)), - ReadFirstLane(20, 106, 1), - ScalarBufferLoad(24, 16, destination: 24, count: 4, dynamicOffsetRegister: 106), - Image(32, "ImageSample", 8, 24), - EndProgram(40)); + var program = LaneIndexedSamplerProgram(); var error = Assert.Throws(() => Extract(program, stage: ShaderStage.Pixel)); Assert.Contains("not a valid runtime value", error.Message); } - private static Gen5ShaderProgram LaneIndexedImageProgram() => Program( + // Opted in to the bindless fallback, the same heap entry reads as a null image in compute too, and the plan names + // the access. + [Fact] + public void ImageDescriptorLoadedAtALaneChosenIndexInCompute_ReadsAsNullWhenOptedIn() + { + var program = LaneIndexedImageProgram(); + + var plan = Extract(program, stage: ShaderStage.Compute, bindlessNullDescriptors: true); + + var image = Assert.Single(plan.DescriptorSources, source => source.DwordCount == 8); + Assert.All(image.Dwords, dword => Assert.True(dword.IsConstant && dword.ConstantU32 == 0)); + Assert.Equal([48u], plan.NullBindlessDescriptorPcs); + Assert.True(Gen5SpirvTranslator.TryCompileProgram(Request(program, bindlessNullDescriptors: true), out var shader, out var error), error); + Assert.NotEmpty(shader.Spirv); + } + + // A sampler read from a heap at a lane-chosen index reads as a null sampler when opted in. + [Fact] + public void SamplerLoadedAtALaneChosenIndex_ReadsAsNullWhenOptedIn() + { + var program = LaneIndexedSamplerProgram(); + + var plan = Extract(program, stage: ShaderStage.Pixel, bindlessNullDescriptors: true); + + Assert.Single(plan.DescriptorSources, source => + source.DwordCount == 4 && source.Dwords.All(dword => dword.IsConstant && dword.ConstantU32 == 0)); + Assert.Equal([32u], plan.NullBindlessDescriptorPcs); + Assert.True(Gen5SpirvTranslator.TryCompileProgram(Request(program, ShaderStage.Pixel, bindlessNullDescriptors: true), out var shader, out var error), error); + Assert.NotEmpty(shader.Spirv); + } + + // The plan lists only what the opt-in added: a pixel shader's lane-chosen image reads as null without it. + [Fact] + public void ThePlanListsOnlyTheOptedInFallbacks() + { + var plan = Extract(LaneIndexedImageProgram(), stage: ShaderStage.Pixel, bindlessNullDescriptors: true); + + Assert.Empty(plan.NullBindlessDescriptorPcs); + } + + internal static Gen5ShaderProgram LaneIndexedSamplerProgram() => Program( + MoveScalarRegister(0, 16, 0), + MoveScalarRegister(4, 17, 1), + MoveScalarRegister(8, 18, 2), + MoveScalarRegister(12, 19, 3), + Vop2(16, "VLshlrevB32", 1, Operand(12), Gen5Operand.Vector(0)), + ReadFirstLane(20, 106, 1), + ScalarBufferLoad(24, 16, destination: 24, count: 4, dynamicOffsetRegister: 106), + Image(32, "ImageSample", 8, 24), + EndProgram(40)); + + internal static Gen5ShaderProgram LaneIndexedImageProgram(uint dimension = 1) => Program( // The table V# in s16..s19 and the sampler in s24..s27 come from user data. MoveScalarRegister(0, 16, 0), MoveScalarRegister(4, 17, 1), @@ -228,7 +386,7 @@ private static Gen5ShaderProgram LaneIndexedImageProgram() => Program( ReadFirstLane(32, 106, 7), Sop2(36, "SLshlB32", 106, Gen5Operand.Scalar(106), Operand(5)), ScalarBufferLoad(40, 16, destination: 0, count: 8, dynamicOffsetRegister: 106), - Image(48, "ImageSample", 0, 24), + Image(48, "ImageSample", 0, 24, dimension: dimension), EndProgram(56)); // A shader that selects among states with v_cmpx and s_cbranch_execz sets a constant sampler up in the first state's block and samples // with it in a later state's block. The skip edge of the first branch reaches the join with the sampler registers unwritten, so the host @@ -700,15 +858,24 @@ public void ResourceTableFlatteningAndRuntimeMemoization() memory.Reads = 0; memory.FailAfter = 0; var snapshot = new ResourceSnapshot { UserData = [1] }; - var specialization = new ResourceSpecialization { Buffers = [new BufferSpecialization(7, 0, 0)] }; + var specialization = new ResourceSpecialization { Buffers = [new BufferSpecialization(7, 0)] }; Assert.False(ResourceMaterializer.Materialize(plan, inputs, ref snapshot, ref specialization)); Assert.Equal([1u], snapshot.UserData); - Assert.Equal(7u, specialization.Buffers[0].PackedStride); + Assert.Equal(7u, specialization.Buffers[0].DescriptorFormat); var layout = BindingLayout.Allocate(plan.Info, BindingLayout.CollectUserDataRegisters(program, 0, 64), false, plan.TableReads.Count != 0, false); Assert.NotNull(layout.Find(DescriptorBindingKind.FlattenedResourceTable)); } + // An indexed buffer access (idxen) makes the program read its buffers' strides at run time; offsets alone do not. + [Fact] + public void AnIndexedBufferAccessReadsTheBufferStridesAtRunTime() + { + Assert.True(Extract(Program(BufferAccess(0, "BufferLoadDword", 0, indexEnabled: true, vectorAddress: 1), EndProgram(8))) + .Info.UsesIndexedBuffers); + Assert.False(Extract(Program(BufferLoad(0, 0), EndProgram(8))).Info.UsesIndexedBuffers); + } + [Fact] public void DynamicResourceTableReadRemainsExplicit() { diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/RuntimeImageSwizzleTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/RuntimeImageSwizzleTests.cs new file mode 100644 index 000000000..b79daaccc --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/RuntimeImageSwizzleTests.cs @@ -0,0 +1,129 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.ShaderCompiler.Tests.Resources; + +// Storage image destination selects as shader data (RuntimeImageSwizzle). +public sealed class RuntimeImageSwizzleTests +{ + // Every 12-bit select, permutation or not: the map names, per physical channel, the logical component a baked store puts + // there (GetImageStoreSourceIndex with all four components enabled), or zero. + [Fact] + public void StoreChannelMapPlacesComponentsAsTheBakedStoreForEverySelect() + { + for (var select = 0u; select < 0x1000; select++) + { + var map = RuntimeImageSwizzle.StoreChannelMap(select); + Assert.Equal(0u, map >> 12); + for (var channel = 0; channel < 4; channel++) + { + var code = ((map >> (channel * 3)) & 7u) ^ (uint)channel; + var expected = Gen5ShaderTranslator.GetImageStoreSourceIndex(select, 0xF, channel); + Assert.Equal(expected < 0 ? 4u : (uint)expected, code); + } + } + + Assert.Equal(0u, RuntimeImageSwizzle.StoreChannelMap(DescriptorConstants.IdentityImageSwizzle)); + } + + // Slots go to the written storage images, in image order: not to sampled, unwritten, converted or indirect ones. + [Fact] + public void SlotsRankTheWrittenImagesTheRuntimeSelectServes() + { + var images = new List + { + Storage(written: true), + new() { ResourceClass = ImageResourceClass.Sampled }, + Storage(written: false), + Storage(written: true, conversionFormat: GuestImageFormat.Format11x2x10Uint), + Storage(written: true, indirectRoot: 0), + Storage(written: true), + Storage(written: true), + }; + Assert.Equal([0, -1, -1, -1, -1, 1, 2], Enumerable.Range(0, images.Count).Select(index => RuntimeImageSwizzle.Slot(images, index))); + Assert.Equal(-1, RuntimeImageSwizzle.Slot(images, images.Count)); + Assert.Equal(3u, RuntimeImageSwizzle.SlotCount(images)); + } + + [Fact] + public void WriteStoreMapsPacksTwoMapsToADwordWithTheIdentityForNullDescriptors() + { + var layout = new BindingLayout { MemoryOffsetDword = 2, StorageImageSwizzleCount = 3 }; + var shaderData = Enumerable.Repeat(0xFFFF_FFFFu, (int)layout.ShaderDataDwordCount).ToArray(); + uint[] Descriptor(uint select) => [0x1000, 71u << 20, 0, (9u << 28) | select, 0, 0, 0, 0]; + List images = + [Storage(written: true), new() { ResourceClass = ImageResourceClass.Sampled }, Storage(written: true), Storage(written: true)]; + RuntimeImageSwizzle.WriteStoreMaps(shaderData, layout, images, + [Descriptor(0xF2E), Descriptor(0x9F5), new uint[8], Descriptor(0x204)]); + Assert.Equal(RuntimeImageSwizzle.StoreChannelMap(0xF2E), shaderData[layout.StorageImageSwizzlesDword]); + Assert.Equal(RuntimeImageSwizzle.StoreChannelMap(0x204), shaderData[layout.StorageImageSwizzlesDword + 1]); + Assert.Equal(layout.StorageImageSwizzlesDword + 2, layout.ShaderDataDwordCount); + Assert.Throws(() => RuntimeImageSwizzle.WriteStoreMaps(shaderData, layout, images.Take(2).ToList(), + [Descriptor(0xF2E), Descriptor(0x9F5)])); + } + + [Theory] + [InlineData("ImageStore", true, 1u)] + [InlineData("ImageStore", false, 0u)] + [InlineData("ImageLoad", true, 0u)] + public void TheLayoutCarriesMapsWhenARuntimeSelectImageIsWritten(string opcode, bool runtimeImageSwizzles, uint expected) + { + var (plan, resources) = Materialize(opcode, 0x9F5, runtimeImageSwizzles); + Assert.Equal(runtimeImageSwizzles, plan.Info.UsesRuntimeImageSwizzles); + var layout = BindingLayout.Allocate(resources.Info, [], false, false, false); + Assert.Equal(expected, layout.StorageImageSwizzleCount); + } + + [Fact] + public void CanonicalKeepsTheIdentitySelectOfRuntimeSelectImagesOnly() + { + var (plan, _) = Materialize("ImageStore", 0xFAC, runtimeImageSwizzles: true); + var recorded = new ResourceSpecialization + { + BaseBufferCount = 0, + Images = [new ImageSpecialization(ImageNumericClass.Float, ImageDimension.Dim2D, 1, 0, 0x9F5, + DescriptorConstants.NoIndex, 0, 0, false)], + }; + var canonical = RuntimeImageSwizzle.Canonical(plan, recorded); + Assert.Equal(DescriptorConstants.IdentityImageSwizzle, Assert.Single(canonical.Images).ShaderSwizzle); + Assert.Equal(0x9F5u, Assert.Single(recorded.Images).ShaderSwizzle); + + var converted = new ResourceSpecialization + { + Images = [recorded.Images[0] with { ConversionFormat = GuestImageFormat.Format11x2x10Uint }], + }; + Assert.Same(converted, RuntimeImageSwizzle.Canonical(plan, converted)); + var (bakedPlan, _) = Materialize("ImageStore", 0xFAC, runtimeImageSwizzles: false); + Assert.Same(recorded, RuntimeImageSwizzle.Canonical(bakedPlan, recorded)); + } + + private static ImageResource Storage(bool written, uint conversionFormat = DescriptorConstants.InvalidFormat, + uint indirectRoot = DescriptorConstants.NoIndex) => new() + { + ResourceClass = ImageResourceClass.Storage, + Written = written, + ConversionFormat = conversionFormat, + IndirectRoot = indirectRoot, + }; + + private static (ShaderResourcePlan Plan, SpecializedResourceInfo Resources) Materialize(string opcode, uint select, + bool runtimeImageSwizzles) + { + var program = Program(Image(0, opcode, resourceRegister: 8), EndProgram(8)); + var plan = ShaderResourcePlan.Extract(program, ShaderStage.Compute, Hash, 0, 16, runtimeImageSwizzles: runtimeImageSwizzles); + var userData = new uint[16]; + userData[8] = 0x20; + userData[9] = 71u << 20; + userData[11] = (9u << 28) | select; + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + Assert.True(ResourceMaterializer.Materialize(plan, Inputs(userData), ref snapshot, ref specialization, out var failure), + failure.ToString()); + return (plan, ResourceMaterializer.ApplyTo(plan, specialization)); + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ScalarBufferBoundsTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ScalarBufferBoundsTests.cs new file mode 100644 index 000000000..14e48699c --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ScalarBufferBoundsTests.cs @@ -0,0 +1,90 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.ShaderCompiler.Tests.Resources; + +// A scalar buffer load does not read the dwords past its V#'s records (RDNA2 ISA, scalar memory bounds checking): they read +// as zero, so a descriptor fetched past the end of its table is a null descriptor, as on the GPU. +public sealed class ScalarBufferBoundsTests +{ + private const ulong TableBase = 0x1000; + private const ulong DescriptorBase = 0x1100; + private const int IndexOffset = 0x24; + private const uint DescriptorRecords = 4 * 32; + + // The index is a dword of the table s[8:11]; the image descriptor is entry `index` (32 bytes each) of the descriptor + // array s[0:3], sampled with the sampler s[24:27]. + private static Gen5ShaderProgram IndexedImageProgram() => Program( + ScalarBufferLoad(0, 8, destination: 12, immediateOffset: IndexOffset), + Sop2(8, "SLshlB32", 13, Gen5Operand.Scalar(12), Operand(5)), + ScalarBufferLoad(16, 0, destination: 16, count: 8, dynamicOffsetRegister: 13), + MoveScalar(24, 24, 0), + MoveScalar(32, 25, 0), + MoveScalar(40, 26, 0), + MoveScalar(48, 27, 0), + Image(56, "ImageSampleLz", 16, 24, dmask: 1), + EndProgram(64)); + + private static (ResourceSnapshot Snapshot, bool Materialized) Materialize(uint index) + { + var plan = Extract(IndexedImageProgram(), userDataCount: 16); + var userData = new uint[16]; + new uint[] { (uint)DescriptorBase, 0, DescriptorRecords, 0 }.CopyTo(userData, 0); + new uint[] { (uint)TableBase, 0, 0x100, 0 }.CopyTo(userData, 8); + var memory = ResourceTrackerTests.LinearMemory(); + memory.At(TableBase + IndexOffset) = index; + for (uint entry = 0; entry < DescriptorRecords / 32; entry++) + { + var descriptor = ResourceTrackerTests.ImageDescriptor(); + descriptor[0] = 0x20 + entry; + ResourceTrackerTests.WriteImage(memory, DescriptorBase + entry * 32, descriptor); + } + + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + var materialized = ResourceMaterializer.Materialize(plan, Inputs(userData, memory.Read, memory.Read), ref snapshot, + ref specialization, out _); + return (snapshot, materialized); + } + + [Fact] + public void DescriptorInsideTheBufferIsRead() + { + var (snapshot, materialized) = Materialize(2); + Assert.True(materialized); + Assert.Equal(0x22u, Assert.Single(snapshot.Images)[0]); + } + + // An index of 0x0376131F puts its descriptor 1.86 GB past the descriptor array. The GPU reads it as zero. + [Theory] + [InlineData(4u)] + [InlineData(0x0376131Fu)] + [InlineData(0x03FFFFFFu)] + public void DescriptorPastTheBufferReadsAsNull(uint index) + { + var (snapshot, materialized) = Materialize(index); + Assert.True(materialized); + Assert.All(Assert.Single(snapshot.Images), word => Assert.Equal(0u, word)); + } + + // The bounds checks each dword: a descriptor that starts inside the buffer and ends past it keeps the dwords inside. + [Fact] + public void ResolvedAddressesFollowTheRecords() + { + const ulong records = 0x40; + Assert.Equal(RuntimeValueEvaluator.RawAddress.Read, + RuntimeValueEvaluator.ResolveRawAddress(ScalarValueKind.ScalarBufferWord, 0x2000, 0, records, 0, 0x3C, out var last)); + Assert.Equal(0x203Cul, last); + Assert.Equal(RuntimeValueEvaluator.RawAddress.Zero, + RuntimeValueEvaluator.ResolveRawAddress(ScalarValueKind.ScalarBufferWord, 0x2000, 0, records, 0, 0x40, out _)); + Assert.Equal(RuntimeValueEvaluator.RawAddress.Zero, + RuntimeValueEvaluator.ResolveRawAddress(ScalarValueKind.ScalarBufferWord, 0x2000, 0, records, 0x20, 0x6EC263E0, out _)); + // A negative immediate offset is not a valid scalar buffer access: it still fails. + Assert.Equal(RuntimeValueEvaluator.RawAddress.Failed, + RuntimeValueEvaluator.ResolveRawAddress(ScalarValueKind.ScalarBufferWord, 0x2000, 0, records, -4, 0, out _)); + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ScalarDataReadPolicyTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ScalarDataReadPolicyTests.cs new file mode 100644 index 000000000..aace04a26 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ScalarDataReadPolicyTests.cs @@ -0,0 +1,119 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.ShaderCompiler.Tests.Resources; + +public sealed class ScalarDataReadPolicyTests +{ + private static Gen5ShaderProgram BoundsProgram() => Program( + ScalarLoad(0, 0, 16, 4), ScalarLoad(8, 0, 106, 2, immediateOffset: 16), + Vop3(16, "VSubF32", 0, Gen5Operand.Scalar(106), Gen5Operand.Scalar(17)), + Vop3(24, "VSubF32", 1, Gen5Operand.Scalar(107), Gen5Operand.Scalar(18)), + Vop3(32, "VSubF32", 2, Gen5Operand.Scalar(19), Gen5Operand.Scalar(16)), EndProgram(40)); + + private static ShaderResourcePlan Plan(Gen5ShaderProgram program, bool enabled, ShaderStage stage = ShaderStage.Compute) => + ShaderResourcePlan.Extract(program, stage, Hash, 0, 2, scalarDataOnDevice: enabled); + + [Fact] + public void SixBoundsWordsUseOneExactGpuRangeWithoutHostDataReads() + { + var program = BoundsProgram(); + var ordinary = Plan(program, false); + Assert.Equal(6, ordinary.TableReads.Count); + var plan = Plan(program, true); + Assert.Empty(plan.TableReads); + Assert.Empty(plan.FlattenedSlotByMemoryIndex); + Assert.True(plan.Info.UsesDeviceAddresses); + var range = Assert.Single(plan.DeviceAddressRanges); + Assert.True(range.Bounded); + Assert.True(range.Plannable); + Assert.False(range.Written); + Assert.Equal(0, range.FirstByte); + Assert.Equal(24, range.EndByte); + Assert.All(plan.Memory.Entries, memory => Assert.False(memory.PlanningOnly)); + + static bool UnexpectedRead(ulong address, out uint value) => throw new InvalidOperationException($"Host read at {address:X}"); + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + Assert.True(ResourceMaterializer.Materialize(plan, Inputs([0x1000, 0], UnexpectedRead, UnexpectedRead), + ref snapshot, ref specialization)); + var actual = Assert.Single(snapshot.DeviceAddressRanges); + Assert.Equal(0x1000ul, actual.Base); + Assert.Equal(24ul, actual.Size); + Assert.True(actual.Planned); + Assert.False(actual.Written); + + var resources = ResourceMaterializer.ApplyTo(plan, specialization); + var layout = BindingLayout.Allocate(resources.Info, BindingLayout.CollectUserDataRegisters(program, 0, 2), + false, ShaderCompileRequest.RequiresFlattenedTable(plan, resources), false, 0); + var request = new ShaderCompileRequest(plan, resources, layout) { WaveSize = 32 }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + Gen5MipStatisticsTests.ValidateWhenAvailable(shader.Spirv); + } + + [Fact] + public void DescriptorWordsStillUseTheHostPlan() + { + var program = Program(ScalarLoad(0, 0, 4, 4), BufferLoad(8, 4), EndProgram(16)); + var plan = Plan(program, true); + Assert.Equal(4, plan.TableReads.Count); + Assert.Empty(plan.DeviceAddressRanges); + Assert.False(plan.Info.UsesDeviceAddresses); + Assert.Single(plan.Info.Buffers); + } + + [Fact] + public void BranchPredicatesStillUseTheHostPlan() + { + var program = Program(ScalarLoad(0, 0, 4), Sopc(8, "SCmpEqU32", Gen5Operand.Scalar(4), Operand(0)), + Branch(12, "SCbranchScc1", 1), Vop1(16, "VMovB32", 0, Gen5Operand.Scalar(4)), EndProgram(20)); + var plan = Plan(program, true); + Assert.Single(plan.TableReads); + Assert.Empty(plan.DeviceAddressRanges); + } + + [Fact] + public void MemoryDependentPointersStillUseTheHostPlan() + { + var program = Program(ScalarLoad(0, 0, 4, 2), ScalarLoad(8, 4, 16), + Vop1(16, "VMovB32", 0, Gen5Operand.Scalar(16)), EndProgram(20)); + var plan = Plan(program, true); + Assert.Equal(3, plan.TableReads.Count); + Assert.Empty(plan.DeviceAddressRanges); + } + + [Fact] + public void GraphicsKeepsTheOrdinaryPolicy() + { + var plan = Plan(BoundsProgram(), true, ShaderStage.Pixel); + Assert.Equal(6, plan.TableReads.Count); + Assert.Empty(plan.DeviceAddressRanges); + } + + [Fact] + public void ASeparateScalarOffsetKeepsTheOrdinaryPolicy() + { + // The existing range planner bounds the instruction's immediate offset, not an extra SGPR offset. + var program = Program(Sop1(0, "SMovB32", 4, Operand(16)), + ScalarLoad(4, 0, 16, dynamicOffsetRegister: 4), Vop1(12, "VMovB32", 0, Gen5Operand.Scalar(16)), EndProgram(16)); + var plan = Plan(program, true); + Assert.Single(plan.TableReads); + Assert.Empty(plan.DeviceAddressRanges); + } + + [Fact] + public void ResidencyIncludesTheFirstDwordOfAnUnalignedScalarRead() + { + var plan = Plan(BoundsProgram(), true); + var range = Assert.Single(DeviceAddressRangePlanner.EvaluateInterpreted(plan, Inputs([0x1003, 0]))); + Assert.Equal(0x1000ul, range.Base); + Assert.Equal(27ul, range.Size); + plan.CompileEvaluatorNow(); + Assert.Equal(range, Assert.Single(DeviceAddressRangePlanner.Evaluate(plan, Inputs([0x1003, 0])))); + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ScalarGraphDiskCacheTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ScalarGraphDiskCacheTests.cs index dfabb1e02..883f51074 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ScalarGraphDiskCacheTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ScalarGraphDiskCacheTests.cs @@ -44,6 +44,58 @@ byte[] Snapshot(ScalarValueGraph graph) finally { if (Directory.Exists(directory)) Directory.Delete(directory, true); } } + [Fact] + public void HitMarksItsEntryUsedWithoutRewritingIt() + { + var directory = Path.Combine(Path.GetTempPath(), "sharpemu-graph-" + Guid.NewGuid().ToString("N")); + try + { + var program = Program(ScalarLoad(0, 2, 8), EndProgram(8)); + _ = ScalarGraphDiskCache.Build(program, 0, 16, null, 64, directory); + var file = Assert.Single(Directory.GetFiles(directory, "*.graph")); + var written = File.GetLastWriteTimeUtc(file); + var old = written.AddDays(-1); + File.SetLastAccessTimeUtc(file, old); + _ = ScalarGraphDiskCache.Build(program, 0, 16, null, 64, directory); + Assert.Equal(written, File.GetLastWriteTimeUtc(file)); + Assert.True(File.GetLastAccessTimeUtc(file) > old); + } + finally { if (Directory.Exists(directory)) Directory.Delete(directory, true); } + } + + [Fact] + public void TrimDropsTheEntriesUsedLongestAgoUntilTheTarget() + { + var directory = Path.Combine(Path.GetTempPath(), "sharpemu-graph-" + Guid.NewGuid().ToString("N")); + try + { + Directory.CreateDirectory(directory); + var now = DateTime.UtcNow; + string Entry(string name, int hoursAgoWritten, int hoursAgoUsed) + { + var path = Path.Combine(directory, name + ".graph"); + File.WriteAllBytes(path, new byte[100]); + File.SetLastWriteTimeUtc(path, now.AddHours(-hoursAgoWritten)); + File.SetLastAccessTimeUtc(path, now.AddHours(-hoursAgoUsed)); + return path; + } + + // Written first but used last: kept, where trimming by write time would drop it first. A hit leaves the + // last access time at or after the write time. + var usedLast = Entry("a", 10, 0); + var usedFirst = Entry("b", 9, 9); + var usedSecond = Entry("c", 8, 5); + var usedThird = Entry("d", 7, 3); + Assert.Equal(400, ScalarGraphDiskCache.Trim(directory, 100, 500, 300)); + Assert.Equal(200, ScalarGraphDiskCache.Trim(directory, 100, 450, 300)); + Assert.True(File.Exists(usedLast)); + Assert.True(File.Exists(usedThird)); + Assert.False(File.Exists(usedFirst)); + Assert.False(File.Exists(usedSecond)); + } + finally { if (Directory.Exists(directory)) Directory.Delete(directory, true); } + } + [Fact] public void CachePreservesExcludedRegistersAcrossReloads() { diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ScalarValueGraphTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ScalarValueGraphTests.cs index 1f5fb430f..5b6f25642 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ScalarValueGraphTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ScalarValueGraphTests.cs @@ -327,12 +327,15 @@ static Gen5ShaderProgram Read(int immediate) => Program( var memory = new TestWordMemory { Base = 0x3000 }; memory.At(0x300C) = 0xA5A5A5A5; + memory.At(0x3010) = 0x5A5A5A5A; var plan = Extract(Read(12), userDataCount: 0); Assert.True(RuntimeValueEvaluator.FlattenResourceTable(plan, Inputs([], memory.Read), out var table)); Assert.Equal([0xA5A5A5A5u], table); + // Past the 16-byte buffer the load reads zero, as on the GPU, not the memory that follows the buffer. var overflow = Extract(Read(16), userDataCount: 0); - Assert.False(RuntimeValueEvaluator.FlattenResourceTable(overflow, Inputs([], memory.Read), out _)); + Assert.True(RuntimeValueEvaluator.FlattenResourceTable(overflow, Inputs([], memory.Read), out var overflowTable)); + Assert.Equal([0u], overflowTable); } // A loop whose body runs under a divergent mask still reaches a fixpoint: the diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/SpecializationGuardTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/SpecializationGuardTests.cs index 9049475fe..8b8a8f586 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/SpecializationGuardTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/SpecializationGuardTests.cs @@ -79,7 +79,9 @@ public void ConcurrentMaterializationsDoNotShareMutableOutputs() uint[] words = [(uint)(0x8000 + index * 4096), (uint)(index % 4) << 16, 64, 0]; Assert.True(ResourceMaterializer.Materialize(plan, Inputs(words), ref snapshot, ref specialization)); Assert.Equal(words, Assert.Single(snapshot.Buffers)); - Assert.Equal((uint)(index % 4), Assert.Single(specialization.Buffers).PackedStride); + // The stride does not reach the specialization. + Assert.Equal(new BufferSpecialization(DescriptorConstants.InvalidFormat, DescriptorConstants.IdentityDestinationSelect), + Assert.Single(specialization.Buffers)); specialization.Buffers.Clear(); }); } diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/SpirvBindingDeclarationTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/SpirvBindingDeclarationTests.cs index 35384d6c1..14ed5c81d 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/SpirvBindingDeclarationTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/SpirvBindingDeclarationTests.cs @@ -351,14 +351,16 @@ public void IndirectImageAfterAPlainImage_SelectsByCandidateIndex(bool gpuDepend [Theory] [InlineData(ImageType2D, ImageType2DArray)] [InlineData(ImageType2DArray, ImageType2D)] - public void IndirectImage_Mixed2DAnd2DArrayCandidatesCompileAcrossBindingClasses(uint firstImageType, uint secondImageType) + public void IndirectImage_Mixed2DAnd2DArrayCandidatesShareTheArrayBindingClass(uint firstImageType, uint secondImageType) { + // An array read takes a 2D texture as a one-layer array. var (request, snapshot) = IndirectImageAfterPlainImageRequest( firstImageType: firstImageType, secondImageType: secondImageType, indirectDimension: 5); var root = request.Resources.Info.Images[1]; var candidate = request.Resources.Info.Images[2]; - Assert.NotEqual(root.Dimension, candidate.Dimension); - Assert.NotEqual(ImageDescriptorBinding.ForImage(root), ImageDescriptorBinding.ForImage(candidate)); + Assert.Equal(ImageDimension.Dim2DArray, root.Dimension); + Assert.Equal(ImageDimension.Dim2DArray, candidate.Dimension); + Assert.Equal(ImageDescriptorBinding.ForImage(root), ImageDescriptorBinding.ForImage(candidate)); Assert.Equal(firstImageType, snapshot.Images[1][3] >> 28); Assert.Equal(secondImageType, snapshot.Images[2][3] >> 28); Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/StableImageBindingTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/StableImageBindingTests.cs new file mode 100644 index 000000000..f29674436 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/StableImageBindingTests.cs @@ -0,0 +1,159 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.ShaderCompiler.Tests.Resources; + +public sealed class StableImageBindingTests +{ + private static readonly StableImageDescriptorLimits Limits = new(16, 16, 4, 3, 19); + + private static Gen5ShaderProgram ImageProgram(int count = 16, string opcode = "ImageSampleLz") + { + var instructions = new List { ScalarLoad(0, 0, 24, 4, count * 32) }; + for (uint index = 0; index < count; index++) + { + var pc = 8 + index * 16; + instructions.Add(ScalarLoad(pc, 0, 16, 8, (int)index * 32)); + instructions.Add(Image(pc + 8, opcode, 16, 24)); + } + instructions.Add(EndProgram(8 + (uint)count * 16)); + return Program([.. instructions]); + } + + private static ShaderResourcePlan Plan(StableImageDescriptorLimits limits, ShaderStage stage = ShaderStage.Compute) => + ShaderResourcePlan.Extract(ImageProgram(), stage, Hash, 0, 2, stableImageLimits: limits); + + [Theory] + [InlineData(16u, 4u, 3u, 19u, true)] + [InlineData(15u, 4u, 3u, 19u, false)] + [InlineData(16u, 3u, 3u, 19u, false)] + [InlineData(16u, 4u, 2u, 19u, false)] + [InlineData(16u, 4u, 3u, 18u, false)] + public void AdmissionIncludesSamplerCopiesAndAllOrdinaryHelpers( + uint images, uint samplers, uint buffers, uint resources, bool expected) + { + var plan = Plan(new(images, 16, samplers, buffers, resources)); + Assert.Equal(16, plan.Info.Images.Count); + Assert.Single(plan.Info.Samplers); + Assert.Equal(expected, plan.StableImageBindings); + } + + // A graphics stage binds its images one per slot within the budget its caller passes for that stage. + [Theory] + [InlineData(ShaderStage.Pixel)] + [InlineData(ShaderStage.Vertex)] + public void AGraphicsStageFitsItsOwnBudget(ShaderStage stage) + { + Assert.True(Plan(Limits, stage).StableImageBindings); + Assert.False(Plan(Limits with { SampledImages = 15 }, stage).StableImageBindings); + Assert.False(Plan(default, stage).StableImageBindings); + } + + [Fact] + public void DynamicMipAndIndirectPlansStayCompact() + { + var mip = ShaderResourcePlan.Extract(ImageProgram(1, "ImageStoreMip"), ShaderStage.Compute, Hash, 0, 2, + stableImageLimits: Limits); + Assert.Equal(ImageMipMode.DynamicStorage, Assert.Single(mip.Info.Images).MipMode); + Assert.False(mip.StableImageBindings); + var indirect = ShaderResourcePlan.Extract(ResourceTrackerTests.IndirectImageProgram(false), ShaderStage.Compute, + Hash, 0, 64, stableImageLimits: new(1024, 1024, 1024, 1024, 4096)); + Assert.NotEmpty(indirect.IndirectImages); + Assert.False(indirect.StableImageBindings); + } + + [Fact] + public void StorageImagesUseTheirOwnLimit() + { + var program = ImageProgram(2, "ImageStore"); + // The budget leaves no room for the device-address buffers that device scalar data reads would add. + ShaderResourcePlan ExtractWith(uint storage) => ShaderResourcePlan.Extract(program, ShaderStage.Compute, Hash, 0, 2, + stableImageLimits: new(0, storage, 0, 3, 5), scalarDataOnDevice: false); + Assert.True(ExtractWith(2).StableImageBindings); + Assert.False(ExtractWith(1).StableImageBindings); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void AliasPartitionChangesOnlySplitCompactSpecializations(bool stable) + { + var plan = Plan(stable ? Limits : Limits with { SampledImages = 15 }); + var memory = new TestWordMemory { Words = new uint[0x10000 / 4] }; + uint[][] partitions = + [ + [0, 1, 2, 1, 2, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2], + [0, 1, 1, 1, 4, 1, 1, 1, 8, 8, 8, 8, 8, 8, 8, 8], + ]; + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + var versions = new List(); + var modules = new List(); + foreach (var partition in partitions) + { + for (var index = 0; index < partition.Length; index++) + { + var image = ResourceTrackerTests.ImageDescriptor(); + image[0] += partition[index]; + ResourceTrackerTests.WriteImage(memory, 0x1000 + (ulong)index * 32, image); + } + Assert.True(ResourceMaterializer.Materialize(plan, Inputs([0x1000, 0], memory.Read, memory.Read), + ref snapshot, ref specialization)); + Assert.Equal(stable, specialization.StableImageBindings); + Assert.Equal(0x20u + partition[4], snapshot.Images[4][0]); + if (stable) Assert.Empty(specialization.ImageDescriptorGroups); + else Assert.Equal(partition, specialization.ImageDescriptorGroups); + var resources = ResourceMaterializer.ApplyTo(plan, specialization); + var layout = BindingLayout.Allocate(resources.Info, [0, 1], false, true, false); + Assert.Equal(stable ? 16 : partition.Distinct().Count(), layout.Descriptors + .Where(binding => ImageDescriptorBinding.ResourceClass(binding.Kind) == ImageResourceClass.Sampled) + .Sum(binding => binding.Resources.Count)); + Assert.True(Gen5SpirvTranslator.TryCompileProgram(new ShaderCompileRequest(plan, resources, layout), + out var module, out var error), error); + modules.Add(module.Spirv); + versions.Add(specialization.Clone()); + } + Assert.Equal(stable, versions[0].Equals(versions[1])); + if (stable) + { + Assert.Equal(versions[0].GetHashCode(), versions[1].GetHashCode()); + Assert.Equal(modules[0], modules[1]); + // A semantic image-type change still requires a new specialization. + memory.At(0x1000 + 32 + 4) = 75u << 20; + Assert.True(ResourceMaterializer.Materialize(plan, Inputs([0x1000, 0], memory.Read, memory.Read), + ref snapshot, ref specialization)); + Assert.NotEqual(versions[0], specialization); + Assert.True(specialization.StableImageBindings); + } + } + + [Fact] + public void GuardAndApplyRejectTheOtherPolicyEvenWithEqualPayloads() + { + var compact = Plan(default); + var stable = Plan(Limits); + var memory = new TestWordMemory { Words = new uint[0x10000 / 4] }; + for (var index = 0; index < 16; index++) + ResourceTrackerTests.WriteImage(memory, 0x1000 + (ulong)index * 32, ResourceTrackerTests.ImageDescriptor()); + var inputs = Inputs([0x1000, 0], memory.Read, memory.Read); + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + Assert.True(ResourceMaterializer.Materialize(compact, inputs, ref snapshot, ref specialization)); + var compactSpecialization = specialization.Clone(); + Assert.NotNull(compact.SpecializationGuard); + stable.SpecializationGuard = compact.SpecializationGuard; + Assert.True(ResourceMaterializer.Materialize(stable, inputs, ref snapshot, ref specialization)); + Assert.True(specialization.StableImageBindings); + Assert.Empty(specialization.ImageDescriptorGroups); + Assert.Throws(() => ResourceMaterializer.ApplyTo(stable, compactSpecialization)); + Assert.Throws(() => ResourceMaterializer.ApplyTo(compact, specialization)); + specialization.ImageDescriptorGroups.AddRange(Enumerable.Repeat(0u, 16)); + Assert.Throws(() => ResourceMaterializer.ApplyTo(stable, specialization)); + Assert.NotEqual(new ResourceSpecialization(), new ResourceSpecialization { StableImageBindings = true }); + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/SpirvEmitterContractTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/SpirvEmitterContractTests.cs new file mode 100644 index 000000000..b4342ba95 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/SpirvEmitterContractTests.cs @@ -0,0 +1,325 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Tests.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.ShaderCompiler.Tests; + +[Collection("SpirvOptimization")] +public sealed class SpirvEmitterContractTests +{ + [Fact] + public void DontInlineCallKeepsItsInputStoreAndReloadsItsWrittenPrivateRegister() + { + var m = new SpirvModuleBuilder(); + m.AddCapability(SpirvCapability.Shader); + var u = m.TypeInt(32, false); + var register = Variable(m, u, SpirvStorageClass.Private); + var output = Output(m, u); + var a = m.Constant(u, 11); + var b = m.Constant(u, 22); + var helper = m.BeginFunction(m.TypeVoid(), m.TypeFunction(m.TypeVoid()), 2); // DontInline. + m.AddLabel(); + var read = m.AddInstruction(SpirvOp.Load, u, register); + m.AddStatement(SpirvOp.Store, output, read); + m.AddStatement(SpirvOp.Store, register, b); + End(m); + + var (main, _) = Vertex(m, register, output); + m.AddStatement(SpirvOp.Store, register, a); + m.AddInstruction(SpirvOp.FunctionCall, m.TypeVoid(), helper); + var after = m.AddInstruction(SpirvOp.Load, u, register); + Assert.NotEqual(a, after); + m.AddStatement(SpirvOp.Store, output, after); + End(m); + + var instructions = Instructions(m.Build()).ToArray(); + var call = Assert.Single(instructions.Where(i => i.Function == main && i.Op == SpirvOp.FunctionCall)); + Assert.Contains(instructions, i => i.Function == main && i.Op == SpirvOp.Store && + i.Words[0] == register && i.Words[1] == a && i.Offset < call.Offset); + Assert.Contains(instructions, i => i.Function == helper && i.Op == SpirvOp.Load && + i.Words[2] == register); + Assert.Contains(instructions, i => i.Function == main && i.Op == SpirvOp.Load && + i.Words[1] == after && i.Words[2] == register && i.Offset > call.Offset); + } + + [Fact] + public void SpecializationValueIsNeitherFoldedToItsDefaultNorHoistedFromItsBlock() + { + var m = new SpirvModuleBuilder(); + m.AddCapability(SpirvCapability.Shader); + var u = m.TypeInt(32, false); + var output = Output(m, u); + var input = Variable(m, u, SpirvStorageClass.Input); + m.AddDecoration(input, SpirvDecoration.Location, 1); + var spec = m.SpecConstant(u, 7, 9); + var (main, entry) = Vertex(m, input, output); + var condition = m.AddInstruction(SpirvOp.INotEqual, m.TypeBool(), + m.AddInstruction(SpirvOp.Load, u, input), m.Constant(u, 0)); + var run = m.AllocateId(); + var merge = m.AllocateId(); + m.AddStatement(SpirvOp.SelectionMerge, merge, 0); + m.AddStatement(SpirvOp.BranchConditional, condition, run, merge); + m.AddLabel(run); + var sum = m.AddInstruction(SpirvOp.IAdd, u, spec, m.Constant(u, 1)); + Assert.NotEqual(m.Constant(u, 10), sum); + m.AddStatement(SpirvOp.Store, output, sum); + m.AddStatement(SpirvOp.Branch, merge); + m.AddLabel(merge); + End(m); + + var instructions = Instructions(m.Build()).ToArray(); + var addition = Assert.Single(instructions.Where(i => i.Op == SpirvOp.IAdd && i.Words[1] == sum)); + Assert.Equal(main, addition.Function); + Assert.Equal(run, addition.Block); + Assert.NotEqual(entry, addition.Block); + Assert.Contains(instructions, i => i.Op == SpirvOp.SpecConstant && i.Words[1] == spec); + } + + [Fact] + public void TwoClockReadsRemainTwoDistinctEffectfulInstructions() + { + var m = new SpirvModuleBuilder(); + m.AddCapability(SpirvCapability.Shader); + m.AddCapability(SpirvCapability.Int64); + m.AddCapability(SpirvCapability.ShaderClockKhr); + m.AddExtension("SPV_KHR_shader_clock"); + var u = m.TypeInt(32, false); + var wide = m.TypeInt(64, false); + var output = Output(m, wide); + Vertex(m, output); + var scope = m.Constant(u, 1); + var first = m.AddInstruction(SpirvOp.ReadClockKhr, wide, scope); + var second = m.AddInstruction(SpirvOp.ReadClockKhr, wide, scope); + Assert.NotEqual(first, second); + m.AddStatement(SpirvOp.Store, output, m.AddInstruction(SpirvOp.ISub, wide, second, first)); + End(m); + var clocks = Instructions(m.Build()).Where(i => i.Op == SpirvOp.ReadClockKhr).ToArray(); + Assert.Equal(2, clocks.Length); + Assert.Contains(clocks, i => i.Words[1] == first); + Assert.Contains(clocks, i => i.Words[1] == second); + } + + [Fact] + public void ExtraSubgroupArithmeticIsNotMergedAsAnOrdinaryValue() + { + var m = new SpirvModuleBuilder(); + m.AddCapability(SpirvCapability.Shader); + m.AddCapability(SpirvCapability.GroupNonUniform); + m.AddCapability(SpirvCapability.GroupNonUniformArithmetic); + var u = m.TypeInt(32, false); + var output = Output(m, u); + Vertex(m, output); + var scope = m.Constant(u, 3); + var one = m.Constant(u, 1); + var first = m.AddInstruction(SpirvOp.GroupNonUniformIAdd, u, scope, 0, one); + var second = m.AddInstruction(SpirvOp.GroupNonUniformIAdd, u, scope, 0, one); + Assert.NotEqual(first, second); + m.AddStatement(SpirvOp.Store, output, m.AddInstruction(SpirvOp.IAdd, u, first, second)); + End(m); + var reductions = Instructions(m.Build()).Where(i => i.Op == SpirvOp.GroupNonUniformIAdd).ToArray(); + Assert.Equal(2, reductions.Length); + Assert.Contains(reductions, i => i.Words[1] == first); + Assert.Contains(reductions, i => i.Words[1] == second); + } + + [Fact] + public void ConditionalScratchStoreMergesBothIncomingValuesWithAPhi() + { + var m = new SpirvModuleBuilder(); + m.AddCapability(SpirvCapability.Shader); + var u = m.TypeInt(32, false); + var scratch = Variable(m, u, SpirvStorageClass.Private); + var input = Variable(m, u, SpirvStorageClass.Input); + m.AddDecoration(input, SpirvDecoration.Location, 1); + var output = Output(m, u); + Vertex(m, scratch, input, output); + var zero = m.Constant(u, 0); + var changed = m.Constant(u, 23); + m.AddStatement(SpirvOp.Store, scratch, zero); + var condition = m.AddInstruction(SpirvOp.INotEqual, m.TypeBool(), + m.AddInstruction(SpirvOp.Load, u, input), zero); + var yes = m.AllocateId(); + var no = m.AllocateId(); + var merge = m.AllocateId(); + m.AddStatement(SpirvOp.SelectionMerge, merge, 0); + m.AddStatement(SpirvOp.BranchConditional, condition, yes, no); + m.AddLabel(yes); + m.AddStatement(SpirvOp.Store, scratch, changed); + m.AddStatement(SpirvOp.Branch, merge); + m.AddLabel(no); + m.AddStatement(SpirvOp.Branch, merge); + m.AddLabel(merge); + var loaded = m.AddInstruction(SpirvOp.Load, u, scratch); + m.AddStatement(SpirvOp.Store, output, loaded); + End(m); + Assert.True(m.InheritedBlocksHeld); + + var instructions = Instructions(m.Build()).ToArray(); + var phi = Assert.Single(instructions.Where(i => i.Op == SpirvOp.Phi && i.Words[1] == loaded)); + Assert.Equal(merge, phi.Block); + var incoming = Enumerable.Range(0, (phi.Words.Length - 2) / 2) + .Select(i => (Value: phi.Words[2 + i * 2], Block: phi.Words[3 + i * 2])).ToArray(); + Assert.Equal(2, incoming.Length); + Assert.Contains((changed, yes), incoming); + Assert.Contains((zero, no), incoming); + Assert.Contains(instructions, i => i.Op == SpirvOp.Store && i.Words[0] == output && i.Words[1] == loaded); + } + + [Fact] + public void RuntimeValuesDoNotCrossFromMainIntoAnOutlinedFunction() + { + // Two sites share the body, so the module runs it as a DontInline function that both sites call. A linked body + // reaches its buffer through a device address, and the caller stores through one after the calls: main and the + // body each resolve their addresses with the page table's length, which every function reads itself. + var caller = Program( + MoveScalar(0, 14, 0x2000), MoveScalar(4, 15, 0), + MoveScalar(8, 16, 0), MoveScalar(12, 17, 0), + Sop1(16, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + MoveScalar(20, 14, 0x2000), MoveScalar(24, 15, 0), + Sop1(28, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + GlobalAccess(32, "GlobalStoreDword", 20, vectorAddress: 5), EndProgram(40)); + var body = Program( + BufferAccess(0, "BufferLoadDword", 4, vectorData: 6, offsetEnabled: true, vectorAddress: 5), + BufferAccess(8, "BufferStoreDword", 4, vectorData: 6, offsetEnabled: true, vectorAddress: 5), + Sop1(16, "SSetpcB64", 0, Gen5Operand.Scalar(14))); + ShaderCallTarget[] Records() => [new(0x2000, 0, body), new(0x2000, 1, body)]; + var linked = Gen5ShaderCallLinker.Link(caller, + [new(16, 14, 16, 14, 20, Records()), new(28, 14, 16, 14, 32, Records())]); + var code = Compile(Request(linked)); + var instructions = Instructions(code).ToArray(); + var inspected = new SpirvModuleInspector(code); + var main = Assert.Single(inspected.Names, p => p.Value == "main").Key; + var pageTable = Assert.Single(inspected.Names, p => p.Value == "deviceAddressPageTable").Key; + + // One device store is main's; the other is the body's, in a DontInline function that main calls from both sites. + const uint dontInline = 2; + var devicePointers = instructions.Where(i => i.Op == SpirvOp.ConvertUToPtr).Select(i => i.Words[1]).ToHashSet(); + var deviceStores = instructions.Where(i => i.Op == SpirvOp.Store && devicePointers.Contains(i.Words[0])).ToArray(); + Assert.Contains(deviceStores, i => i.Function == main); + var outlined = Assert.Single(deviceStores, i => i.Function != main).Function; + Assert.Contains(instructions, i => i.Op == SpirvOp.Function && i.Words[1] == outlined && i.Words[2] == dontInline); + Assert.Equal(2, instructions.Count(i => i.Function == main && i.Op == SpirvOp.FunctionCall && i.Words[2] == outlined)); + foreach (var function in new[] { main, outlined }) + Assert.Contains(instructions, i => i.Function == function && i.Op == SpirvOp.ArrayLength && i.Words[2] == pageTable); + + // An id defined in a function is used only in that function. + var types = instructions.Where(i => (uint)i.Op is >= 19 and <= 39).Select(i => i.Words[0]).ToHashSet(); + var owners = instructions.Where(i => i.Function != 0 && i.Op != SpirvOp.Function && i.Words.Length >= 2 && + types.Contains(i.Words[0])).ToDictionary(i => i.Words[1], i => i.Function); + foreach (var instruction in instructions.Where(i => i.Function != 0)) + foreach (var operand in IdOperands(instruction)) + if (owners.TryGetValue(operand, out var owner)) + Assert.Equal(instruction.Function, owner); + } + + [Fact] + public void UndeclaredCompareExchangeLoopRequestsInheritanceFallbackAfterAnEarlyRead() + { + var inherited = CompareExchangeLoop(inherit: true); + Assert.False(inherited.InheritedBlocksHeld); + var fallback = CompareExchangeLoop(inherit: false); + Assert.True(fallback.InheritedBlocksHeld); + Assert.Contains(Instructions(fallback.Build()), i => i.Op == SpirvOp.AtomicCompareExchange); + } + + private static SpirvModuleBuilder CompareExchangeLoop(bool inherit) + { + var m = new SpirvModuleBuilder { InheritBlockState = inherit }; + m.AddCapability(SpirvCapability.Shader); + var u = m.TypeInt(32, false); + var register = Variable(m, u, SpirvStorageClass.Private); + var atomic = Variable(m, u, SpirvStorageClass.Workgroup); + var function = m.BeginFunction(m.TypeVoid(), m.TypeFunction(m.TypeVoid())); + m.AddEntryPoint(SpirvExecutionModel.GLCompute, function, "main", [register, atomic]); + m.AddExecutionMode(function, SpirvExecutionMode.LocalSize, 1, 1, 1); + m.AddLabel(); + var zero = m.Constant(u, 0); + var one = m.Constant(u, 1); + var header = m.AllocateId(); + var again = m.AllocateId(); + var done = m.AllocateId(); + m.AddStatement(SpirvOp.Store, register, one); + m.AddStatement(SpirvOp.Branch, header); + m.AddLabel(header); // Deliberately no DeclareLoopHeader: exercise the conservative retry guard. + var value = m.AddInstruction(SpirvOp.Load, u, register); + var previous = m.AddInstruction(SpirvOp.AtomicCompareExchange, u, + atomic, m.Constant(u, 2), zero, zero, value, zero); + var success = m.AddInstruction(SpirvOp.IEqual, m.TypeBool(), previous, zero); + m.AddStatement(SpirvOp.LoopMerge, done, again, 0); + m.AddStatement(SpirvOp.BranchConditional, success, done, again); + m.AddLabel(again); + m.AddStatement(SpirvOp.Store, register, m.Constant(u, 2)); + m.AddStatement(SpirvOp.Branch, header); + m.AddLabel(done); + End(m); + return m; + } + + private static byte[] Compile(ShaderCompileRequest request) + { + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + return shader.Spirv; + } + + private static uint Variable(SpirvModuleBuilder m, uint type, SpirvStorageClass storage) => + m.AddGlobalVariable(m.TypePointer(storage, type), storage); + + private static uint Output(SpirvModuleBuilder m, uint type) + { + var output = Variable(m, type, SpirvStorageClass.Output); + m.AddDecoration(output, SpirvDecoration.Location, 0); + return output; + } + + private static (uint Function, uint Entry) Vertex(SpirvModuleBuilder m, params uint[] interfaces) + { + var function = m.BeginFunction(m.TypeVoid(), m.TypeFunction(m.TypeVoid())); + m.AddEntryPoint(SpirvExecutionModel.Vertex, function, "main", interfaces); + return (function, m.AddLabel()); + } + + private static void End(SpirvModuleBuilder m) + { + m.AddStatement(SpirvOp.Return); + m.EndFunction(); + } + + private sealed record Instruction(SpirvOp Op, uint[] Words, int Offset, uint Function, uint Block); + + // The operands of a function's instruction that name ids; memory operands, extracted indices, an extended instruction's + // number and merge controls are literals. + private static IEnumerable IdOperands(Instruction instruction) => instruction.Op switch + { + SpirvOp.Load or SpirvOp.ArrayLength or SpirvOp.CompositeExtract => instruction.Words.Skip(2).Take(1), + SpirvOp.Store => instruction.Words.Take(2), + SpirvOp.CompositeInsert or SpirvOp.VectorShuffle => instruction.Words.Skip(2).Take(2), + SpirvOp.ExtInst => instruction.Words.Skip(2).Take(1).Concat(instruction.Words.Skip(4)), + SpirvOp.BranchConditional or SpirvOp.Switch or SpirvOp.ReturnValue => instruction.Words.Take(1), + SpirvOp.Function or SpirvOp.Variable or SpirvOp.Label or SpirvOp.Branch or SpirvOp.SelectionMerge or SpirvOp.LoopMerge => [], + _ => instruction.Words.Skip(2), + }; + + private static IEnumerable Instructions(byte[] code) + { + var words = new uint[code.Length / sizeof(uint)]; + Buffer.BlockCopy(code, 0, words, 0, code.Length); + uint function = 0, block = 0; + for (var offset = 5; offset < words.Length;) + { + var length = checked((int)(words[offset] >> 16)); + Assert.True(length > 0 && offset + length <= words.Length); + var op = (SpirvOp)(words[offset] & 0xffff); + var operands = words.AsSpan(offset + 1, length - 1).ToArray(); + if (op == SpirvOp.Function) function = operands[1]; + if (op == SpirvOp.Label) block = operands[0]; + yield return new Instruction(op, operands, offset, function, block); + if (op == SpirvOp.FunctionEnd) { function = 0; block = 0; } + offset += length; + } + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/SpirvExtInstOperandTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/SpirvExtInstOperandTests.cs new file mode 100644 index 000000000..3eedd2597 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/SpirvExtInstOperandTests.cs @@ -0,0 +1,91 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; + +namespace SharpEmu.ShaderCompiler.Tests; + +[Collection("SpirvOptimization")] +public sealed class SpirvExtInstOperandTests +{ + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public void OperationLiteralDoesNotEscapeAnUnrelatedPrivatePointer(bool indexed, bool folded) + { + const uint umin = 38; + var module = new SpirvModuleBuilder(); + module.AddCapability(SpirvCapability.Shader); + var glsl = module.ImportExtInst("GLSL.std.450"); + var integer = module.TypeInt(32, false); + var pointerType = module.TypePointer(SpirvStorageClass.Private, integer); + var output = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.Output, integer), SpirvStorageClass.Output); + module.AddDecoration(output, SpirvDecoration.Location, 0); + var zero = module.Constant(integer, 0); + var first = module.Constant(integer, 7); + var second = module.Constant(integer, 9); + var stored = module.Constant(integer, 42); + var array = indexed + ? module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.Private, module.TypeArray(integer, 2)), + SpirvStorageClass.Private) + : 0; + var function = module.BeginFunction(module.TypeVoid(), module.TypeFunction(module.TypeVoid())); + module.AddEntryPoint(SpirvExecutionModel.Vertex, function, "main", indexed ? [array, output] : [output]); + module.AddLabel(); + ReserveIdsBefore(module, umin); + var pointer = indexed + ? module.AddInstruction(SpirvOp.AccessChain, pointerType, array, zero) + : module.AddGlobalVariable(pointerType, SpirvStorageClass.Private); + Assert.Equal(umin, pointer); + module.AddStatement(SpirvOp.Store, pointer, stored); + var minimum = module.AddInstruction(SpirvOp.ExtInst, integer, glsl, umin, first, folded ? first : second); + if (folded) Assert.Equal(first, minimum); + // The literal 38 names an operation, not this coincidentally numbered pointer. + Assert.Equal(stored, module.AddInstruction(SpirvOp.Load, integer, pointer)); + module.AddStatement(SpirvOp.Store, output, minimum); + module.AddStatement(SpirvOp.Return); + module.EndFunction(); + } + + [Theory] + [InlineData(35u)] + [InlineData(51u)] + public void ActualExtendedInstructionOutputPointerStillEscapes(uint operation) + { + var module = new SpirvModuleBuilder(); + module.AddCapability(SpirvCapability.Shader); + var glsl = module.ImportExtInst("GLSL.std.450"); + var floating = module.TypeFloat(32); + var resultType = operation == 35 ? floating : module.TypeInt(32, true); + var pointer = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.Private, resultType), + SpirvStorageClass.Private); + var value = operation == 35 ? module.ConstantFloat(floating, 4) : module.Constant(resultType, 4); + var input = module.ConstantFloat(floating, 1.5f); + var output = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.Output, resultType), SpirvStorageClass.Output); + module.AddDecoration(output, SpirvDecoration.Location, 0); + var function = module.BeginFunction(module.TypeVoid(), module.TypeFunction(module.TypeVoid())); + module.AddEntryPoint(SpirvExecutionModel.Vertex, function, "main", [pointer, output]); + module.AddLabel(); + module.AddStatement(SpirvOp.Store, pointer, value); + module.AddInstruction(SpirvOp.ExtInst, floating, glsl, operation, input, pointer); + var loaded = module.AddInstruction(SpirvOp.Load, resultType, pointer); + Assert.NotEqual(value, loaded); + module.AddStatement(SpirvOp.Store, output, loaded); + module.AddStatement(SpirvOp.Return); + module.EndFunction(); + } + + private static void ReserveIdsBefore(SpirvModuleBuilder module, uint target) + { + uint reserved; + do + { + reserved = module.AllocateId(); + } + while (reserved < target - 1); + Assert.Equal(target - 1, reserved); + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/SpirvExtInstUseTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/SpirvExtInstUseTests.cs new file mode 100644 index 000000000..ee9552b17 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/SpirvExtInstUseTests.cs @@ -0,0 +1,136 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; + +namespace SharpEmu.ShaderCompiler.Tests; + +[Collection("SpirvOptimization")] +public sealed class SpirvExtInstUseTests +{ + [Fact] + public void OperationLiteralDoesNotKeepUnreadPrivateStorageOrItsMetadata() + { + var (module, integer, glsl, input, output, function) = BeginIntegerModule(); + var one = module.Constant(integer, 1); + var pointerType = module.TypePointer(SpirvStorageClass.Private, integer); + ReserveIdsBefore(module, 38); + var variable = module.AddGlobalVariable(pointerType, SpirvStorageClass.Private); + Assert.Equal(38u, variable); + module.AddName(variable, "unreadLiteralCollision"); + module.AddStatement(SpirvOp.Store, variable, one); + var loaded = module.AddInstruction(SpirvOp.Load, integer, input); + var minimum = module.AddInstruction(SpirvOp.ExtInst, integer, glsl, 38, loaded, one); + module.AddStatement(SpirvOp.Store, output, minimum); + var words = Finish(module, function, [input, output, variable]); + Assert.DoesNotContain(words, value => (SpirvOp)(value[0] & 0xffff) == SpirvOp.Variable && value[2] == variable); + Assert.DoesNotContain(words, value => (SpirvOp)(value[0] & 0xffff) == SpirvOp.Store && value[1] == variable); + Assert.DoesNotContain(words, value => (SpirvOp)(value[0] & 0xffff) == SpirvOp.Name && value[1] == variable); + Assert.DoesNotContain(variable, Assert.Single(words.Where(value => + (SpirvOp)(value[0] & 0xffff) == SpirvOp.EntryPoint))); + Assert.Contains(words, value => (SpirvOp)(value[0] & 0xffff) == SpirvOp.ExtInst && value[2] == minimum); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void LiteralUseAndItsRemovalDoNotChangeARealDefinitionUse(bool keepDefinition) + { + var (module, integer, glsl, input, output, function) = BeginIntegerModule(); + var loaded = module.AddInstruction(SpirvOp.Load, integer, input); + var divisor = module.Constant(integer, 2); + ReserveIdsBefore(module, 38); + var divided = module.AddInstruction(SpirvOp.UDiv, integer, loaded, divisor); + Assert.Equal(38u, divided); + module.AddName(divided, "definitionLiteralCollision"); + var minimum = module.AddInstruction(SpirvOp.ExtInst, integer, glsl, 38, loaded, divisor); + var selected = keepDefinition ? divided : minimum; + module.AddStatement(SpirvOp.Store, output, selected); + var words = Finish(module, function, [input, output]); + Assert.Equal(keepDefinition, words.Any(value => + (SpirvOp)(value[0] & 0xffff) == SpirvOp.UDiv && value[2] == divided)); + Assert.Equal(keepDefinition, words.Any(value => + (SpirvOp)(value[0] & 0xffff) == SpirvOp.Name && value[1] == divided)); + Assert.Equal(!keepDefinition, words.Any(value => + (SpirvOp)(value[0] & 0xffff) == SpirvOp.ExtInst && value[2] == minimum)); + Assert.Contains(words, value => (SpirvOp)(value[0] & 0xffff) == SpirvOp.Store && + value[1] == output && value[2] == selected); + } + + [Theory] + [InlineData(35u)] + [InlineData(51u)] + public void ActualOutputPointerKeepsStorageEvenWhenItsIdEqualsTheOperation(uint operation) + { + var module = new SpirvModuleBuilder(); + module.AddCapability(SpirvCapability.Shader); + var glsl = module.ImportExtInst("GLSL.std.450"); + var floating = module.TypeFloat(32); + var valueType = operation == 35 ? floating : module.TypeInt(32, true); + var privatePointer = module.TypePointer(SpirvStorageClass.Private, valueType); + var output = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.Output, valueType), + SpirvStorageClass.Output); + module.AddDecoration(output, SpirvDecoration.Location, 0); + var input = module.ConstantFloat(floating, 1.5f); + var function = module.BeginFunction(module.TypeVoid(), module.TypeFunction(module.TypeVoid())); + module.AddLabel(); + ReserveIdsBefore(module, operation); + var variable = module.AddGlobalVariable(privatePointer, SpirvStorageClass.Private); + Assert.Equal(operation, variable); + // No load follows: the output-pointer argument is the variable's only function use. + module.AddInstruction(SpirvOp.ExtInst, floating, glsl, operation, input, variable); + var keptOutput = operation == 35 ? module.ConstantFloat(floating, 0) : module.Constant(valueType, 0); + module.AddStatement(SpirvOp.Store, output, keptOutput); + var words = Finish(module, function, [output, variable]); + Assert.Contains(words, value => (SpirvOp)(value[0] & 0xffff) == SpirvOp.Variable && value[2] == variable); + Assert.Contains(words, value => (SpirvOp)(value[0] & 0xffff) == SpirvOp.ExtInst && + value[4] == operation && value[6] == variable); + Assert.Contains(variable, Assert.Single(words.Where(value => + (SpirvOp)(value[0] & 0xffff) == SpirvOp.EntryPoint))); + } + + private static (SpirvModuleBuilder Module, uint Integer, uint Glsl, uint Input, uint Output, uint Function) + BeginIntegerModule() + { + var module = new SpirvModuleBuilder(); + module.AddCapability(SpirvCapability.Shader); + var glsl = module.ImportExtInst("GLSL.std.450"); + var integer = module.TypeInt(32, false); + var input = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.Input, integer), SpirvStorageClass.Input); + var output = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.Output, integer), SpirvStorageClass.Output); + module.AddDecoration(input, SpirvDecoration.Location, 0); + module.AddDecoration(output, SpirvDecoration.Location, 0); + var function = module.BeginFunction(module.TypeVoid(), module.TypeFunction(module.TypeVoid())); + module.AddLabel(); + return (module, integer, glsl, input, output, function); + } + + private static uint[][] Finish(SpirvModuleBuilder module, uint function, uint[] interfaces) + { + module.AddEntryPoint(SpirvExecutionModel.Vertex, function, "main", interfaces); + module.AddStatement(SpirvOp.Return); + module.EndFunction(); + var code = module.Build(); + var words = new uint[code.Length / sizeof(uint)]; + Buffer.BlockCopy(code, 0, words, 0, code.Length); + var instructions = new List(); + for (var offset = 5; offset < words.Length; offset += (int)(words[offset] >> 16)) + { + var count = (int)(words[offset] >> 16); + instructions.Add(words[offset..(offset + count)]); + } + return instructions.ToArray(); + } + + private static void ReserveIdsBefore(SpirvModuleBuilder module, uint target) + { + uint reserved; + do + { + reserved = module.AllocateId(); + } + while (reserved < target - 1); + Assert.Equal(target - 1, reserved); + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/SpirvOptimizationTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/SpirvOptimizationTests.cs index 751324888..f6e24eebc 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/SpirvOptimizationTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/SpirvOptimizationTests.cs @@ -75,4 +75,204 @@ public void ForwardedRegisterValuesKeepTheirOutputWhenUnreadStorageIsRemoved(boo SpirvModuleBuilder.KeepsUnreadVariables = previous; } } + + [Fact] + public void ExplicitNoneLoadKeepsThePrivateStoreItReadsBeforeALaterStore() + { + var module = new SpirvModuleBuilder(); + module.AddCapability(SpirvCapability.Shader); + var integer = module.TypeInt(32, false); + var register = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.Private, integer), SpirvStorageClass.Private); + var output = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.Output, integer), SpirvStorageClass.Output); + module.AddDecoration(output, SpirvDecoration.Location, 0); + var function = module.BeginFunction(module.TypeVoid(), module.TypeFunction(module.TypeVoid())); + module.AddEntryPoint(SpirvExecutionModel.Vertex, function, "main", [register, output]); + module.AddLabel(); + var first = module.Constant(integer, 41); + var second = module.Constant(integer, 73); + module.AddStatement(SpirvOp.Store, register, first); + var loaded = module.AddInstruction(SpirvOp.Load, integer, register, 0); // Memory Access: None. + module.AddStatement(SpirvOp.Store, register, second); + module.AddStatement(SpirvOp.Store, output, loaded); + module.AddStatement(SpirvOp.Return); + module.EndFunction(); + + var instructions = Instructions(module.Build()); + var stores = instructions.Where(words => (SpirvOp)(words[0] & 0xffff) == SpirvOp.Store && words[1] == register).ToArray(); + Assert.Collection(stores, + words => Assert.Equal(new uint[] { ((uint)SpirvOp.Store) | (3u << 16), register, first }, words), + words => Assert.Equal(new uint[] { ((uint)SpirvOp.Store) | (3u << 16), register, second }, words)); + var load = Assert.Single(instructions.Where(words => (SpirvOp)(words[0] & 0xffff) == SpirvOp.Load && words[2] == loaded)); + Assert.Equal(new uint[] { ((uint)SpirvOp.Load) | (5u << 16), integer, loaded, register, 0 }, load); + Assert.True(Array.IndexOf(instructions, stores[0]) < Array.IndexOf(instructions, load)); + Assert.True(Array.IndexOf(instructions, load) < Array.IndexOf(instructions, stores[1])); + Assert.Contains(instructions, words => (SpirvOp)(words[0] & 0xffff) == SpirvOp.Store && words[1] == output && words[2] == loaded); + } + + [Fact] + public void ExplicitNoneElementStoreInvalidatesThePreviouslyForwardedValue() + { + var module = new SpirvModuleBuilder(); + module.AddCapability(SpirvCapability.Shader); + var integer = module.TypeInt(32, false); + var array = module.TypeArray(integer, 2); + var register = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.Private, array), SpirvStorageClass.Private); + var output = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.Output, integer), SpirvStorageClass.Output); + module.AddDecoration(output, SpirvDecoration.Location, 0); + var function = module.BeginFunction(module.TypeVoid(), module.TypeFunction(module.TypeVoid())); + module.AddEntryPoint(SpirvExecutionModel.Vertex, function, "main", [register, output]); + module.AddLabel(); + var pointer = module.AddInstruction(SpirvOp.AccessChain, + module.TypePointer(SpirvStorageClass.Private, integer), register, module.Constant(integer, 1)); + var first = module.Constant(integer, 41); + var second = module.Constant(integer, 73); + module.AddStatement(SpirvOp.Store, pointer, first); + module.AddStatement(SpirvOp.Store, pointer, second, 0); // Memory Access: None. + var loaded = module.AddInstruction(SpirvOp.Load, integer, pointer); + Assert.NotEqual(first, loaded); + module.AddStatement(SpirvOp.Store, output, loaded); + module.AddStatement(SpirvOp.Return); + module.EndFunction(); + + var instructions = Instructions(module.Build()); + var explicitStore = Assert.Single(instructions.Where(words => + (SpirvOp)(words[0] & 0xffff) == SpirvOp.Store && words.Length == 4 && words[1] == pointer)); + Assert.Equal(new uint[] { ((uint)SpirvOp.Store) | (4u << 16), pointer, second, 0 }, explicitStore); + var load = Assert.Single(instructions.Where(words => + (SpirvOp)(words[0] & 0xffff) == SpirvOp.Load && words[2] == loaded)); + Assert.Equal(new uint[] { ((uint)SpirvOp.Load) | (4u << 16), integer, loaded, pointer }, load); + Assert.True(Array.IndexOf(instructions, explicitStore) < Array.IndexOf(instructions, load)); + Assert.Contains(instructions, words => (SpirvOp)(words[0] & 0xffff) == SpirvOp.Store && words[1] == output && words[2] == loaded); + } + + [Fact] + public void VolatileLoadKeepsItsStoreWhileAnUntrackedExplicitLoadKeepsPrivateForwarding() + { + var module = new SpirvModuleBuilder(); + module.AddCapability(SpirvCapability.Shader); + var integer = module.TypeInt(32, false); + var register = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.Private, integer), SpirvStorageClass.Private); + var input = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.Input, integer), SpirvStorageClass.Input); + module.AddDecoration(input, SpirvDecoration.Location, 0); + var output = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.Output, integer), SpirvStorageClass.Output); + module.AddDecoration(output, SpirvDecoration.Location, 0); + var inputOutput = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.Output, integer), SpirvStorageClass.Output); + module.AddDecoration(inputOutput, SpirvDecoration.Location, 1); + var function = module.BeginFunction(module.TypeVoid(), module.TypeFunction(module.TypeVoid())); + module.AddEntryPoint(SpirvExecutionModel.Vertex, function, "main", [register, input, output, inputOutput]); + module.AddLabel(); + var first = module.Constant(integer, 41); + var second = module.Constant(integer, 73); + module.AddStatement(SpirvOp.Store, register, first); + var inputValue = module.AddInstruction(SpirvOp.Load, integer, input, 0); // Untracked Input, explicit None. + var forwarded = module.AddInstruction(SpirvOp.Load, integer, register); + Assert.Equal(first, forwarded); + var loaded = module.AddInstruction(SpirvOp.Load, integer, register, 1); // Memory Access: Volatile. + module.AddStatement(SpirvOp.Store, register, second); + module.AddStatement(SpirvOp.Store, output, loaded); + module.AddStatement(SpirvOp.Store, inputOutput, inputValue); + module.AddStatement(SpirvOp.Return); + module.EndFunction(); + + var instructions = Instructions(module.Build()); + var stores = instructions.Where(words => (SpirvOp)(words[0] & 0xffff) == SpirvOp.Store && words[1] == register).ToArray(); + Assert.Collection(stores, + words => Assert.Equal(new uint[] { ((uint)SpirvOp.Store) | (3u << 16), register, first }, words), + words => Assert.Equal(new uint[] { ((uint)SpirvOp.Store) | (3u << 16), register, second }, words)); + var volatileLoad = Assert.Single(instructions.Where(words => + (SpirvOp)(words[0] & 0xffff) == SpirvOp.Load && words[2] == loaded)); + Assert.Equal(new uint[] { ((uint)SpirvOp.Load) | (5u << 16), integer, loaded, register, 1 }, volatileLoad); + Assert.DoesNotContain(instructions, words => + (SpirvOp)(words[0] & 0xffff) == SpirvOp.Load && words.Length == 4 && words[3] == register); + var untrackedLoad = Assert.Single(instructions.Where(words => + (SpirvOp)(words[0] & 0xffff) == SpirvOp.Load && words[2] == inputValue)); + Assert.Equal(new uint[] { ((uint)SpirvOp.Load) | (5u << 16), integer, inputValue, input, 0 }, untrackedLoad); + Assert.True(Array.IndexOf(instructions, stores[0]) < Array.IndexOf(instructions, volatileLoad)); + Assert.True(Array.IndexOf(instructions, volatileLoad) < Array.IndexOf(instructions, stores[1])); + Assert.Contains(instructions, words => (SpirvOp)(words[0] & 0xffff) == SpirvOp.Store && words[1] == output && words[2] == loaded); + Assert.Contains(instructions, words => (SpirvOp)(words[0] & 0xffff) == SpirvOp.Store && words[1] == inputOutput && words[2] == inputValue); + } + + [Fact] + public void ExplicitAccessInAnUndeclaredLoopHeaderKeepsTheInheritedReadGuard() + { + var module = new SpirvModuleBuilder(); + module.AddCapability(SpirvCapability.Shader); + var integer = module.TypeInt(32, false); + var register = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.Private, integer), SpirvStorageClass.Private); + var function = module.BeginFunction(module.TypeVoid(), module.TypeFunction(module.TypeVoid())); + module.AddEntryPoint(SpirvExecutionModel.GLCompute, function, "main", [register]); + module.AddExecutionMode(function, SpirvExecutionMode.LocalSize, 1, 1, 1); + module.AddLabel(); + var header = module.AllocateId(); + var latch = module.AllocateId(); + var done = module.AllocateId(); + module.AddStatement(SpirvOp.Store, register, module.Constant(integer, 1)); + module.AddStatement(SpirvOp.Branch, header); + module.AddLabel(header); // No DeclareLoopHeader: the header inherits register = 1. + var inherited = module.AddInstruction(SpirvOp.Load, integer, register); + module.AddInstruction(SpirvOp.Load, integer, register, 0); // Explicit None: resets the memory state. + var again = module.AddInstruction(SpirvOp.INotEqual, module.TypeBool(), inherited, module.Constant(integer, 2)); + module.AddStatement(SpirvOp.LoopMerge, done, latch, 0); + module.AddStatement(SpirvOp.BranchConditional, again, latch, done); + module.AddLabel(latch); + module.AddStatement(SpirvOp.Store, register, module.Constant(integer, 2)); + module.AddStatement(SpirvOp.Branch, header); + module.AddLabel(done); + module.AddStatement(SpirvOp.Return); + module.EndFunction(); + + // The inherited read happened before the reset, so the header must still request the retry. + Assert.False(module.InheritedBlocksHeld); + } + + [Fact] + public void ElementLoadKeepsTheWholePrivateStoreItReadsBeforeALaterWholeStore() + { + var module = new SpirvModuleBuilder(); + module.AddCapability(SpirvCapability.Shader); + var integer = module.TypeInt(32, false); + var array = module.TypeArray(integer, 2); + var register = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.Private, array), SpirvStorageClass.Private); + var output = module.AddGlobalVariable(module.TypePointer(SpirvStorageClass.Output, integer), SpirvStorageClass.Output); + module.AddDecoration(output, SpirvDecoration.Location, 0); + var first = module.ConstantComposite(array, module.Constant(integer, 41), module.Constant(integer, 42)); + var second = module.ConstantComposite(array, module.Constant(integer, 73), module.Constant(integer, 74)); + var function = module.BeginFunction(module.TypeVoid(), module.TypeFunction(module.TypeVoid())); + module.AddEntryPoint(SpirvExecutionModel.Vertex, function, "main", [register, output]); + module.AddLabel(); + var pointer = module.AddInstruction(SpirvOp.AccessChain, + module.TypePointer(SpirvStorageClass.Private, integer), register, module.Constant(integer, 1)); + module.AddStatement(SpirvOp.Store, register, first); + var loaded = module.AddInstruction(SpirvOp.Load, integer, pointer); + module.AddStatement(SpirvOp.Store, register, second); + module.AddStatement(SpirvOp.Store, output, loaded); + module.AddStatement(SpirvOp.Return); + module.EndFunction(); + + var instructions = Instructions(module.Build()); + var stores = instructions.Where(words => (SpirvOp)(words[0] & 0xffff) == SpirvOp.Store && words[1] == register).ToArray(); + Assert.Collection(stores, + words => Assert.Equal(new uint[] { ((uint)SpirvOp.Store) | (3u << 16), register, first }, words), + words => Assert.Equal(new uint[] { ((uint)SpirvOp.Store) | (3u << 16), register, second }, words)); + var load = Assert.Single(instructions.Where(words => + (SpirvOp)(words[0] & 0xffff) == SpirvOp.Load && words[2] == loaded)); + Assert.Equal(new uint[] { ((uint)SpirvOp.Load) | (4u << 16), integer, loaded, pointer }, load); + Assert.True(Array.IndexOf(instructions, stores[0]) < Array.IndexOf(instructions, load)); + Assert.True(Array.IndexOf(instructions, load) < Array.IndexOf(instructions, stores[1])); + Assert.Contains(instructions, words => (SpirvOp)(words[0] & 0xffff) == SpirvOp.Store && words[1] == output && words[2] == loaded); + } + + private static uint[][] Instructions(byte[] code) + { + var words = new uint[code.Length / sizeof(uint)]; + Buffer.BlockCopy(code, 0, words, 0, code.Length); + var instructions = new List(); + for (var offset = 5; offset < words.Length; offset += (int)(words[offset] >> 16)) + { + instructions.Add(words.AsSpan(offset, (int)(words[offset] >> 16)).ToArray()); + } + + return instructions.ToArray(); + } } From 871cdda8b56db061d31a7db6c87826954c3733cc Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:42:10 +0300 Subject: [PATCH 015/134] [ShaderPrewarm] Leave the load address out of a compute record's identity --- src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.cs index 72389bb8e..440ec220e 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.cs @@ -579,7 +579,7 @@ public static void WriteStamp(string path, string stamp) // The global cache stamp cannot certify a separate caller cache or pipeline binary file. public bool HasLinkedComputes => _loadedComputes.Any(record => record.Linked is not null); - public static ulong Identity(ComputePrewarmRecord record) => XxHash3.HashToUInt64(SerializeCompute(record)); + public static ulong Identity(ComputePrewarmRecord record) => XxHash3.HashToUInt64(SerializeCompute(record, address: 0)); // A graphics program loaded at another address translates the same (the program cache keys omit the address), so // its record's identity leaves the address out and a session that meets the program elsewhere records nothing new. @@ -677,7 +677,7 @@ private static string ProgressKey(string stamp) => public void RecordCompute(ShaderCodeCapture code, ComputePrewarmRecord record) { var payload = SerializeCompute(record); - var identity = XxHash3.HashToUInt64(payload); + var identity = Identity(record); var seconds = SessionSeconds(); lock (_gate) { @@ -1243,13 +1243,15 @@ private static ShaderCodeCapture DeserializeCode(byte[] payload) }; } - private static byte[] SerializeCompute(ComputePrewarmRecord record) + private static byte[] SerializeCompute(ComputePrewarmRecord record) => SerializeCompute(record, record.Address); + + private static byte[] SerializeCompute(ComputePrewarmRecord record, ulong address) { using var stream = new MemoryStream(); using var writer = new BinaryWriter(stream); writer.Write(record.Hash); writer.Write(record.CodeSize); - writer.Write(record.Address); + writer.Write(address); writer.Write(record.ContinuationAddressOffset); writer.Write(record.UserDataBase); writer.Write(record.UserDataCount); From ee107d691101cfea81949b2b7695b4d899d1648f Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:03:57 +0300 Subject: [PATCH 016/134] [GPU] Validate a stage's remembered textures under one image cache lock --- .../Gpu/Images/GuestImageCache.Lookup.cs | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Lookup.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Lookup.cs index 0e803a1a0..85014855e 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Lookup.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Lookup.cs @@ -113,6 +113,79 @@ public bool TryTouchRemembered(ResourceSlotIdentifier imageIdentifier, ref ulong return true; } + internal readonly record struct RememberedTexture(ResourceSlotIdentifier Image, bool Ranged, ulong Begin, ulong End); + + internal bool TryTouchRememberedSet(ReadOnlySpan textures, ref ulong generation) + { + using var held = _lock.Hold(); + if (!RememberedSetHolds(textures, generation)) + { + return false; + } + + var tick = _scheduler.CurrentTick; + var ranged = false; + foreach (var texture in textures) + { + if (!texture.Ranged) + { + continue; + } + + var image = _slots[texture.Image]; + image.LastAccessTick = tick; + TouchImage(image); + ranged = true; + } + + if (ranged) + { + generation = _lookupGeneration; + } + + return true; + } + + internal bool TryRememberedSetForSlice(ReadOnlySpan textures, ref ulong generation) + { + using var held = _lock.Read(); + if (!RememberedSetHolds(textures, generation)) + { + return false; + } + + foreach (var texture in textures) + { + if (texture.Ranged) + { + generation = _lookupGeneration; + break; + } + } + + return true; + } + + private bool RememberedSetHolds(ReadOnlySpan textures, ulong generation) + { + foreach (var texture in textures) + { + if (_slots.TryGet(texture.Image) is not { } image || + ((!image.Registered || image.DepthOwner.IsValid) && !ImageDescription.IsEmptyRange(image.Description.Data)) || + image.Binding.NeedsRebind) + { + return false; + } + + if (texture.Ranged && (!LookupUnchangedSince(generation, texture.Begin, texture.End) || image is not { Registered: true, Parked: false })) + { + return false; + } + } + + return true; + } + public GuestSpan RememberedRange(ResourceSlotIdentifier imageIdentifier, in ImageRequest request) { using var held = _lock.Read(); From 8ab70b38be7891906a4c63d7d19bbcab988c2fbe Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:03:57 +0300 Subject: [PATCH 017/134] [GPU] Check stage memo freshness with one lock per stage --- .../VulkanVideoPresenter.Descriptors.cs | 26 ++++++++++++------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs index 55b324efc..111521233 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs @@ -403,22 +403,28 @@ private bool IsFreshStagePreparation(StagePreparationMemo memo) } var generation = memo.LookupGeneration; - for (var index = 0; index < memo.Textures.Length; index++) + var textures = memo.Textures; + if (textures.Length != 0) { - var texture = memo.Textures[index]; - var range = memo.TextureRanges[index]; - var checkedGeneration = memo.LookupGeneration; - if (IsStaleImage(texture.ImageIdentifier, out _) || - !ImageDescription.IsEmptyRange(texture.Request.Description.Data) && !(_worker - ? _imageCache.TryRememberedForSlice(texture.ImageIdentifier, ref checkedGeneration, range.Address, range.End) - : _imageCache.TryTouchRemembered(texture.ImageIdentifier, ref checkedGeneration, range.Address, range.End))) + Span remembered = textures.Length <= 64 + ? stackalloc GuestImageCache.RememberedTexture[textures.Length] + : new GuestImageCache.RememberedTexture[textures.Length]; + for (var index = 0; index < textures.Length; index++) + { + var texture = textures[index]; + var range = memo.TextureRanges[index]; + remembered[index] = new GuestImageCache.RememberedTexture(texture.ImageIdentifier, + !ImageDescription.IsEmptyRange(texture.Request.Description.Data), range.Address, range.End); + } + + if (!(_worker + ? _imageCache.TryRememberedSetForSlice(remembered, ref generation) + : _imageCache.TryTouchRememberedSet(remembered, ref generation))) { memo.Invalidate(); Interlocked.Increment(ref _stageMemoStale); return false; } - - generation = checkedGeneration; } memo.LookupGeneration = generation; From 617fa82b8c9d58fd805cd42774df85c4f145b0f5 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:03:58 +0300 Subject: [PATCH 018/134] [GPU] Share the native color clear registration check --- .../GuestImageCache.NativeColorClear.cs | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.NativeColorClear.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.NativeColorClear.cs index 98d8c29dd..7321741e3 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.NativeColorClear.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.NativeColorClear.cs @@ -98,15 +98,7 @@ internal bool NativeColorClearSettled(ResourceSlotIdentifier imageIdentifier, in using (_lock.Read()) { - if (_slots.TryGet(imageIdentifier) is not { } image || - !_surfaceMetadata.TryGetValue(metadata.Range.Address, out var registration) || - registration.Invalidated || registration.Kind != metadataKind || !registration.NativeColorClear || - !ReferenceEquals(image.MetadataRegistration, registration) || registration.DccSliceCount != layers || - registration.ClearMask != 0 || registration.FillSize != 0 || registration.FillValue != uint.MaxValue || - registration.RangeSize < metadata.Range.Size || registration.Size < metadata.Range.Size || - _maximumMetadataSize < metadata.Range.Size || !_metadataWriteRanges.Contains(metadata.Range.Address, metadata.Range.Size) || - !MemoryMarshal.AsBytes(new ReadOnlySpan(in image.Description.Metadata)) - .SequenceEqual(MemoryMarshal.AsBytes(new ReadOnlySpan(in metadata)))) + if (!NativeColorClearRegistered(imageIdentifier, in metadata, metadataKind, layers)) return false; } @@ -120,6 +112,18 @@ internal bool NativeColorClearSettled(ResourceSlotIdentifier imageIdentifier, in return true; } + private bool NativeColorClearRegistered(ResourceSlotIdentifier imageIdentifier, in MetadataDescription metadata, + SurfaceMetadataKind metadataKind, uint layers) => + _slots.TryGet(imageIdentifier) is { } image && + _surfaceMetadata.TryGetValue(metadata.Range.Address, out var registration) && + !registration.Invalidated && registration.Kind == metadataKind && registration.NativeColorClear && + ReferenceEquals(image.MetadataRegistration, registration) && registration.DccSliceCount == layers && + registration.ClearMask == 0 && registration.FillSize == 0 && registration.FillValue == uint.MaxValue && + registration.RangeSize >= metadata.Range.Size && registration.Size >= metadata.Range.Size && + _maximumMetadataSize >= metadata.Range.Size && _metadataWriteRanges.Contains(metadata.Range.Address, metadata.Range.Size) && + MemoryMarshal.AsBytes(new ReadOnlySpan(in image.Description.Metadata)) + .SequenceEqual(MemoryMarshal.AsBytes(new ReadOnlySpan(in metadata))); + private bool TryInspectColorClear(in ImageRequest request, uint layer, ulong address, ulong sliceSize, Span bytes, out ColorClearOperation operation) { From 4caad68955f9cebe9a3418b883aa93505e2bd698 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:03:58 +0300 Subject: [PATCH 019/134] [GPU] Take the write lock only when a native color clear registration changes --- .../Gpu/Images/GuestImageCache.NativeColorClear.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.NativeColorClear.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.NativeColorClear.cs index 7321741e3..48316b471 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.NativeColorClear.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.NativeColorClear.cs @@ -39,8 +39,15 @@ internal void ApplyNativeColorClear(ResourceSlotIdentifier imageIdentifier, in I layerCount > layers - metadata.ColorMetadataBaseLayer) throw SubmissionScheduler.Fatal("The native color metadata view is outside its slices."); - using (var held = _lock.Hold()) + bool registered; + using (_lock.Read()) + { + registered = NativeColorClearRegistered(imageIdentifier, in metadata, metadataKind, layers); + } + + if (!registered) { + using var held = _lock.Hold(); IncludeMetadataWriteRange(metadata.Range.Address, metadata.Range.Size); // A new metadata use must not retain another surface's clear state or ownership. var changed = false; From cd359a6a579177f8f65d3f1eea49598ad29ee952 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:03:59 +0300 Subject: [PATCH 020/134] [GPU] Skip zeroing the native color clear scan buffer --- .../Gpu/Images/GuestImageCache.NativeColorClear.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.NativeColorClear.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.NativeColorClear.cs index 48316b471..6c8031db0 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.NativeColorClear.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.NativeColorClear.cs @@ -1,6 +1,7 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using SharpEmu.Libs.Gpu.Buffers; using SharpEmu.Libs.Gpu.Scheduling; @@ -24,6 +25,7 @@ internal void SynchronizeColorMetadata(in ImageRequest request) } } + [SkipLocalsInit] internal void ApplyNativeColorClear(ResourceSlotIdentifier imageIdentifier, in ImageRequest request) { var description = request.Description; @@ -88,6 +90,7 @@ internal void ApplyNativeColorClear(ResourceSlotIdentifier imageIdentifier, in I } // True when ApplyNativeColorClear would change nothing: the registration is current and no slice holds a clear code. + [SkipLocalsInit] internal bool NativeColorClearSettled(ResourceSlotIdentifier imageIdentifier, in ImageRequest request) { var description = request.Description; From 9e1eed21335d5ebd4d6a8a68a9452b6099326985 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:03:59 +0300 Subject: [PATCH 021/134] [GPU] Read guest memory without the store lock when the page has no pending store --- .../VideoOut/VulkanVideoPresenter.CommandThread.cs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs index d2f9e944e..16af2d525 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs @@ -487,8 +487,19 @@ public bool ReadOverlay(ulong address, Span destination) public bool ReadOverlayBefore(ulong address, Span destination, long sequence) { var size = (ulong)destination.Length; - if (_pendingRangeCount == 0 && !HasPendingStores(address, size)) + if (!HasPendingStores(address, size)) { + if (_pendingRangeCount != 0) + { + foreach (var pending in _pendingRangeSnapshot) + { + if (pending.Sequence != 0 && pending.Sequence < sequence && address < pending.Address + pending.RangeSize && pending.Address < address + size) + { + throw new SerialResolveRequiredException("pending range read"); + } + } + } + return _memory.TryRead(address, destination); } lock (_writeLock) From 20bf3eabdcedaf99ab597482cacd670d5db878f1 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:03:59 +0300 Subject: [PATCH 022/134] [GPU] Keep images used this frame when a render worker resolves an overlap --- src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Slices.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Slices.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Slices.cs index 46d4a28ec..a5d6ad7de 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Slices.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Slices.cs @@ -234,7 +234,8 @@ private bool TryResolveOverlapForSlice(in ImageDescription requested, ImageRole ref readonly var cachedInfo = ref cached.Description; var currentTick = _scheduler.CurrentTick; - var safeToDelete = currentTick - Math.Min(currentTick, cached.LastAccessTick) > TicksBeforeRemoval; + var usedThisFrame = cached.Registered && _recencyQueue.GetLastUseTick(cached.RecencyEntryIndex) >= _collectionTick; + var safeToDelete = !usedThisFrame && currentTick - Math.Min(currentTick, cached.LastAccessTick) > TicksBeforeRemoval; if (requested.Data.Address == cachedInfo.Data.Address && requested.BlockExtent.Width == cachedInfo.BlockExtent.Width && requested.BlockExtent.Height == cachedInfo.BlockExtent.Height && requested.BytesPerBlock * requested.Samples == cachedInfo.BytesPerBlock * cachedInfo.Samples) From db54bffaaab1fcc9c4ab44f822a485a11149f78a Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:04:00 +0300 Subject: [PATCH 023/134] [GPU] Stop a render worker slice at a repeated image lookup failure --- .../VulkanVideoPresenter.Rendering.cs | 28 ++++++++++++++++--- .../VideoOut/VulkanVideoPresenter.Slices.cs | 1 + 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs index c86a3a55f..4f75539ea 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs @@ -356,10 +356,30 @@ public ResourceSlotIdentifier FindImage(ref ImageRequest request, bool exactForm return imageIdentifier; } - private ResourceSlotIdentifier LookUpImage(ref ImageRequest request, bool exactFormat = false) => - _worker - ? _imageCache.TryFindImageForSlice(ref request, exactFormat, out var found) ? found : throw Serial("image lookup", resumable: true) - : _imageCache.FindImage(ref request, exactFormat); + private ResourceSlotIdentifier LookUpImage(ref ImageRequest request, bool exactFormat = false) + { + if (!_worker) + { + return _imageCache.FindImage(ref request, exactFormat); + } + + if (_imageCache.TryFindImageForSlice(ref request, exactFormat, out var found)) + { + return found; + } + + var address = request.Description.Data.Address; + var repeated = StopRepeatedLookupFailures && _failedSliceLookups.Contains(address); + if (!repeated) + { + _failedSliceLookups.Add(address); + } + + throw Serial(repeated ? "repeated image lookup" : "image lookup", resumable: !repeated); + } + + private static readonly bool StopRepeatedLookupFailures = Environment.GetEnvironmentVariable("SHARPEMU_STOP_REPEATED_LOOKUP_FAILURES") != "0"; + private readonly List _failedSliceLookups = new(); public void ResetBindings() { diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs index ea7134865..c9d612080 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs @@ -899,6 +899,7 @@ bool IRenderingState.TryDeferUntilRenderingEnds(PipelineStageFlags sourceStages, internal void RecordSlice(RenderSlice slice) { slice.Host = this; + _failedSliceLookups.Clear(); _buffers = _bufferCache.Snapshot; SliceSegment? segment = null; slice.Resume = slice.Items.Count; From fdf15e7b884a7caebe5aade2052599ca1335e242 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:04:09 +0300 Subject: [PATCH 024/134] [GPU] Queue a slice's rest chunks through one helper --- .../VulkanVideoPresenter.CommandThread.cs | 31 ++++++++++++------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs index 16af2d525..ed1947075 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs @@ -962,18 +962,7 @@ private int JoinSlice(RenderSlice slice, Action betweenItems) if (_presenter.SlicesEnabled && remaining >= RestInlineItems + MinimumSliceItems) { inline = slice.Resume + RestInlineItems; - var chunks = (slice.Items.Count - inline + RestChunkItems - 1) / RestChunkItems; - var start = inline; - for (var chunk = 0; chunk < chunks; chunk++) - { - var end = inline + (int)((long)(slice.Items.Count - inline) * (chunk + 1) / chunks); - var rest = new RenderSlice { Origin = 2 }; - rest.Items.AddRange(slice.Items.GetRange(start, end - start)); - _units.Insert(_unitHead + chunk, new Unit { Slice = rest }); - _presenter.DispatchSlice(rest, urgent: true); - Presenter.NoteRestChunk(rest.Items.Count); - start = end; - } + QueueRestChunks(slice, inline); } for (var position = slice.Resume; position < inline; position++) @@ -985,6 +974,24 @@ private int JoinSlice(RenderSlice slice, Action betweenItems) return ran; } + private static readonly bool SplitStolenSlices = Environment.GetEnvironmentVariable("SHARPEMU_SPLIT_STOLEN_SLICES") != "0"; + + private void QueueRestChunks(RenderSlice slice, int inline) + { + var chunks = (slice.Items.Count - inline + RestChunkItems - 1) / RestChunkItems; + var start = inline; + for (var chunk = 0; chunk < chunks; chunk++) + { + var end = inline + (int)((long)(slice.Items.Count - inline) * (chunk + 1) / chunks); + var rest = new RenderSlice { Origin = 2 }; + rest.Items.AddRange(slice.Items.GetRange(start, end - start)); + _units.Insert(_unitHead + chunk, new Unit { Slice = rest }); + _presenter.DispatchSlice(rest, urgent: true); + Presenter.NoteRestChunk(rest.Items.Count); + start = end; + } + } + private static void NoteItemCost(Item item, int stage, long started) => Diagnostics.ItemCostTally.Note(item.Work?.CostKind ?? Diagnostics.ItemCostTally.Other, stage, Stopwatch.GetTimestamp() - started); From 575d26b14b91b1820ed8aa6b0b551d03a34f791b Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:04:09 +0300 Subject: [PATCH 025/134] [GPU] Hand the rest of a stolen slice to the render workers --- .../VideoOut/VulkanVideoPresenter.CommandThread.cs | 13 ++++++++++--- .../VideoOut/VulkanVideoPresenter.Slices.cs | 4 ++-- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs index ed1947075..ba0a887a0 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs @@ -892,13 +892,20 @@ private int JoinSlice(RenderSlice slice, Action betweenItems) if (slice.TryClaim()) { - Presenter.NoteStolen(slice); + var stolenInline = slice.Items.Count; + if (SplitStolenSlices && _presenter.SlicesEnabled && stolenInline >= RestInlineItems + MinimumSliceItems) + { + stolenInline = RestInlineItems; + QueueRestChunks(slice, stolenInline); + } + + Presenter.NoteStolen(slice, stolenInline); slice.Done.Set(); try { - foreach (var item in slice.Items) + for (var position = 0; position < stolenInline; position++) { - RunInline(item, betweenItems); + RunInline(slice.Items[position], betweenItems); ran++; } } diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs index c9d612080..95a8f04e7 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs @@ -497,10 +497,10 @@ internal void DispatchSlice(RenderSlice slice, bool urgent = false) _workers!.Dispatch(slice, urgent); } - internal static void NoteStolen(RenderSlice slice) + internal static void NoteStolen(RenderSlice slice, int inlineItems) { _slicesStolen.Increment(); - _stolenItems.Add(slice.Items.Count); + _stolenItems.Add(inlineItems); _stolenByOrigin[slice.Origin].Increment(); var age = (System.Diagnostics.Stopwatch.GetTimestamp() - slice.DispatchedAt) * 1_000_000 / System.Diagnostics.Stopwatch.Frequency; _stolenByAge[age < 100 ? 0 : age < 1000 ? 1 : 2].Increment(); From 9ed271ef9b1add81dc189ccbc68121db8a47be07 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:04:09 +0300 Subject: [PATCH 026/134] [GPU] Read the slice lookahead per render worker from the environment --- .../VideoOut/VulkanVideoPresenter.CommandThread.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs index ba0a887a0..01f096fbc 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs @@ -24,6 +24,9 @@ private sealed class CommandThread : AgcExports.IDeferredWorkSink // two threads take turns waiting on each other (128 did, with draws resolving on the pool). private static readonly int MaxOutstanding = int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_COMMAND_QUEUE_DEPTH"), out var depth) && depth >= 128 ? depth : 1024; + + private static readonly int SlicesAheadPerWorker = + int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_SLICES_AHEAD"), out var ahead) && ahead >= 1 ? ahead : 2; private const int ShadowSweepCount = 64; private const int StorePageShift = 12; @@ -793,7 +796,7 @@ private void FillUnits(int maxItems) } } - var limit = slicing ? 2 * _presenter.WorkerCount : 0; + var limit = slicing ? SlicesAheadPerWorker * _presenter.WorkerCount : 0; var pulled = 0; while (slicesAhead <= limit && pulled < maxItems) { From 7e14183c08a4ca22c6cd07508581e984db61fbd7 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:04:10 +0300 Subject: [PATCH 027/134] [GPU] Reset a draw record's resolve and copy fields only after those kinds --- .../Gpu/Rendering/ResolvedCommands.cs | 30 +++++++++++++------ 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ResolvedCommands.cs b/src/SharpEmu.Libs/Gpu/Rendering/ResolvedCommands.cs index 05cafcbad..80ee02064 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ResolvedCommands.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ResolvedCommands.cs @@ -112,6 +112,7 @@ internal sealed class ResolvedDraw public void Reset() { + var previous = Kind; Sequence = 0; Kind = ResolvedDrawKind.Skipped; Announce = false; @@ -140,15 +141,26 @@ public void Reset() SetAutoDebug = false; IndexedTrace = null; PacketAddress = 0; - Clear = default; - ResolveSource = default; - ResolveDestination = default; - CopyRead = default; - CopyWrite = default; - CopyReadFormat = default; - CopyWriteFormat = default; - CopyExtent = default; - CopyAspects = default; + if (previous == ResolvedDrawKind.ClearColorTargets) + { + Clear = default; + } + + if (previous == ResolvedDrawKind.MultisampleResolve) + { + ResolveSource = default; + ResolveDestination = default; + } + + if (previous == ResolvedDrawKind.DepthStencilCopy) + { + CopyRead = default; + CopyWrite = default; + CopyReadFormat = default; + CopyWriteFormat = default; + CopyExtent = default; + CopyAspects = default; + } } } From 9aaf2465a6479b52ffa50c8b6e3a3ab27eba7e19 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:04:10 +0300 Subject: [PATCH 028/134] [GPU] Expose the image request comparison --- src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Lookup.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Lookup.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Lookup.cs index 85014855e..5f00c6b1c 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Lookup.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Lookup.cs @@ -237,7 +237,7 @@ private static int LookupSlot(in ImageRequest request, bool exactFormat) return hash & (LookupSlots - 1); } - private static bool SameRequest(in ImageRequest left, in ImageRequest right) => + internal static bool SameRequest(in ImageRequest left, in ImageRequest right) => SameDescription(left.Description, right.Description) && left.View == right.View && left.Role == right.Role && left.TraceTextureMetadataAddress == right.TraceTextureMetadataAddress && string.Equals(left.TraceTextureDescriptor, right.TraceTextureDescriptor, StringComparison.Ordinal) && From 5ef10719ad3820ea9a3c8189fbeda832b28f510e Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:04:11 +0300 Subject: [PATCH 029/134] [GPU] Repeat draw targets that resolve to the same attachments --- .../Gpu/Rendering/RenderRecorder.cs | 65 +++++++++++++++++-- 1 file changed, 61 insertions(+), 4 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs index c7299e5b1..908a69a0f 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs @@ -49,6 +49,10 @@ private sealed class InPlaceDraw public bool DepthResolved; public readonly ResourceSlotIdentifier[] Found = new ResourceSlotIdentifier[RenderingState.ColorAttachmentCapacity]; public ResourceSlotIdentifier FoundDepth; + public readonly ColorTargetResolution[] FoundResolutions = new ColorTargetResolution[RenderingState.ColorAttachmentCapacity]; + public readonly uint[] FoundSlots = new uint[RenderingState.ColorAttachmentCapacity]; + public bool FoundDepthTarget; + public DepthTargetState FoundDepthState; public uint AcquiredCount; public readonly ImageView[] Views = new ImageView[RenderingState.ColorAttachmentCapacity]; public readonly uint[] Slots = new uint[RenderingState.ColorAttachmentCapacity]; @@ -57,13 +61,61 @@ private sealed class InPlaceDraw public RenderingState Rendering; } + private static readonly bool InPlaceByTargets = Environment.GetEnvironmentVariable("SHARPEMU_INPLACE_BY_TARGETS") != "0"; + private bool RepeatsPreviousTargets(ResolvedDraw record, in DrawState state, DrawScopeToken token) { var kept = _inPlace; - return kept.Valid && token.IsActive && token == kept.Token && !ImageClearTrace.Enabled && record.ContextStamp == kept.ContextStamp && - record.DynamicStamp == kept.DynamicStamp && record.TargetVersion == kept.TargetVersion && state.PixelActive == kept.PixelActive && - state.Programs.Vertex.Id == kept.VertexProgram && state.Programs.Pixel.Id == kept.PixelProgram && state.ColorCount == kept.FoundCount && - state.DepthResolved == kept.DepthResolved; + if (!kept.Valid || !token.IsActive || token != kept.Token || ImageClearTrace.Enabled || state.PixelActive != kept.PixelActive || + state.ColorCount != kept.FoundCount || state.DepthResolved != kept.DepthResolved) + { + return false; + } + + if (!InPlaceByTargets) + { + return record.ContextStamp == kept.ContextStamp && record.DynamicStamp == kept.DynamicStamp && record.TargetVersion == kept.TargetVersion && + state.Programs.Vertex.Id == kept.VertexProgram && state.Programs.Pixel.Id == kept.PixelProgram; + } + + for (var index = 0; index < state.ColorCount; index++) + { + if (state.Colors[index].Slot != kept.FoundSlots[index] || !SameColorTarget(in state.Colors[index].Resolution, in kept.FoundResolutions[index])) + { + return false; + } + } + + return state.Depth.HasTarget == kept.FoundDepthTarget && (!state.Depth.HasTarget || SameDepthAttachment(in state.Depth.Target, in kept.FoundDepthState)); + } + + private static bool SameColorTarget(in ColorTargetResolution current, in ColorTargetResolution kept) => + current.BaseAddress == kept.BaseAddress && current.BackingSize == kept.BackingSize && + current.Extent.Width == kept.Extent.Width && current.Extent.Height == kept.Extent.Height && + current.BaseMipLevel == kept.BaseMipLevel && current.BaseArrayLayer == kept.BaseArrayLayer && current.Samples == kept.Samples && + current.ExportMapping.Packed == kept.ExportMapping.Packed && current.MetadataClearSupported == kept.MetadataClearSupported && + current.MetadataFixedClearSupported == kept.MetadataFixedClearSupported && + current.ColorClearValue.Uint32_0 == kept.ColorClearValue.Uint32_0 && current.ColorClearValue.Uint32_1 == kept.ColorClearValue.Uint32_1 && + current.ColorClearValue.Uint32_2 == kept.ColorClearValue.Uint32_2 && current.ColorClearValue.Uint32_3 == kept.ColorClearValue.Uint32_3 && + GuestImageCache.SameRequest(current.Request, kept.Request); + + private static bool SameDepthTarget(in DepthTargetResolution current, in DepthTargetResolution kept) => + current.Format == kept.Format && current.Width == kept.Width && current.Height == kept.Height && current.Samples == kept.Samples && + current.HasStencil == kept.HasStencil && current.HasHtile == kept.HasHtile && current.DepthAddress == kept.DepthAddress && + current.DepthSize == kept.DepthSize && current.StencilAddress == kept.StencilAddress && current.StencilSize == kept.StencilSize && + current.HtileAddress == kept.HtileAddress && current.HtileSize == kept.HtileSize && current.DepthClearEnabled == kept.DepthClearEnabled && + current.StencilClearEnabled == kept.StencilClearEnabled && current.DepthWriteDisabled == kept.DepthWriteDisabled && + current.StencilWriteDisabled == kept.StencilWriteDisabled && GuestImageCache.SameRequest(current.Request, kept.Request); + + private static bool SameDepthAttachment(in DepthTargetState current, in DepthTargetState kept) + { + var format = current.Target.Format; + return SameDepthTarget(current.Target, kept.Target) && + current.State.AttachmentWriteAspects(format) == kept.State.AttachmentWriteAspects(format) && + current.State.DepthClearEnabled == kept.State.DepthClearEnabled && + current.State.DepthClearValue.Equals(kept.State.DepthClearValue) && + current.State.StencilClearEnabled == kept.State.StencilClearEnabled && + current.State.StencilClearValue == kept.State.StencilClearValue; } private void RestoreFoundTargets(ref DrawState state) @@ -121,8 +173,13 @@ private void NoteFoundTargets(ref DrawState state) for (var index = 0; index < state.ColorCount; index++) { kept.Found[index] = state.Colors[index].Image; + kept.FoundResolutions[index] = state.Colors[index].Resolution; + kept.FoundSlots[index] = state.Colors[index].Slot; } + kept.FoundDepthTarget = state.Depth.HasTarget; + kept.FoundDepthState = state.Depth.Target; + kept.DepthResolved = state.DepthResolved; kept.FoundDepth = state.DepthResolved ? state.Depth.Image : default; } From 1e26b9ef574c8d512544e6635e219bb4a8acbbc8 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:04:11 +0300 Subject: [PATCH 030/134] [Diagnostics] Count metadata changes by call site --- .../Gpu/Images/GuestImageCache.Metadata.cs | 24 ++++++++++++++++++- .../Gpu/Images/GuestImageCache.Slices.cs | 3 ++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Metadata.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Metadata.cs index 538db2ba7..58a66a9e8 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Metadata.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Metadata.cs @@ -404,8 +404,30 @@ private void TraceMetadataBinding(in ImageRequest request) public long MetadataGeneration => Volatile.Read(ref _metadataGeneration); - private void NoteMetadataChange(ulong address) + private static readonly System.Collections.Concurrent.ConcurrentDictionary _metadataChangeSites = new(); + + internal static string TakeMetadataChangeReport() + { + var parts = new List(); + foreach (var site in _metadataChangeSites.Keys) + { + if (_metadataChangeSites.TryRemove(site, out var count) && count != 0) + { + parts.Add(FormattableString.Invariant($"{site}:{count}")); + } + } + + return parts.Count == 0 ? "none" : string.Join(",", parts); + } + + private void NoteMetadataChange(ulong address, + [System.Runtime.CompilerServices.CallerMemberName] string caller = "", [System.Runtime.CompilerServices.CallerLineNumber] int line = 0) { + if (RenderPhaseProfile.Enabled) + { + _metadataChangeSites.AddOrUpdate(FormattableString.Invariant($"{caller}@{line}"), 1, static (_, count) => count + 1); + } + var generation = _metadataGeneration + 1; _metadataEvents[generation & (MetadataEventSlots - 1)] = (generation, address); Volatile.Write(ref _metadataGeneration, generation); diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Slices.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Slices.cs index a5d6ad7de..882e47917 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Slices.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Slices.cs @@ -69,7 +69,8 @@ private static bool SliceLookupFailed(SliceLookupFailure reason, ImageRole role) public static string TakeSliceLookupReport() => "lookup_fail=" + TakeCounts(SliceLookupFailures, SliceLookupFailureNames) + " lookup_fail_role=" + TakeCounts(SliceLookupRoleFailures, SliceLookupRoleNames) + - FormattableString.Invariant($" parks={Interlocked.Exchange(ref _parks, 0)} park_releases={Interlocked.Exchange(ref _parkReleases, 0)} unparks={Interlocked.Exchange(ref _unparks, 0)} park_expiries={Interlocked.Exchange(ref _parkExpiries, 0)}"); + FormattableString.Invariant($" parks={Interlocked.Exchange(ref _parks, 0)} park_releases={Interlocked.Exchange(ref _parkReleases, 0)} unparks={Interlocked.Exchange(ref _unparks, 0)} park_expiries={Interlocked.Exchange(ref _parkExpiries, 0)}") + + " metadata_changes=" + TakeMetadataChangeReport(); private static string TakeCounts(long[] counters, string[] names) { From c816ac8841c02daa53e09139accb80084d9f0ad4 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:47:37 +0300 Subject: [PATCH 031/134] [Diagnostics] Log the command queue depth and slice lookahead per render worker --- .../VideoOut/VulkanVideoPresenter.CommandThread.cs | 3 +++ src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs index 01f096fbc..fd62b35cd 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs @@ -27,6 +27,9 @@ private sealed class CommandThread : AgcExports.IDeferredWorkSink private static readonly int SlicesAheadPerWorker = int.TryParse(Environment.GetEnvironmentVariable("SHARPEMU_SLICES_AHEAD"), out var ahead) && ahead >= 1 ? ahead : 2; + + internal static string DescribeQueue() => + FormattableString.Invariant($"command queue depth={MaxOutstanding} slices ahead per worker={SlicesAheadPerWorker}"); private const int ShadowSweepCount = 64; private const int StorePageShift = 12; diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs index 95a8f04e7..60025773c 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs @@ -473,7 +473,7 @@ private void CreateRenderWorkers() _arenaPool = new SliceArenaPool(_deviceInfo, _scheduler); _descriptorPoolStock ??= new DescriptorPoolStock(_deviceInfo); _workers = new RenderWorkerPool(this, RenderWorkerCount); - Console.Error.WriteLine($"[LOADER][INFO] Render workers: {RenderWorkerCount}"); + Console.Error.WriteLine($"[LOADER][INFO] Render workers: {RenderWorkerCount} {CommandThread.DescribeQueue()}"); } private void StopRenderWorkers() From 99744f832e6142a4b6d9a4f6a9593419d2300be6 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:47:37 +0300 Subject: [PATCH 032/134] [GPU] Capture a draw's bindings for a replay of the next item --- .../Gpu/Rendering/IRenderHost.cs | 8 + .../VulkanVideoPresenter.Descriptors.cs | 4 + .../VulkanVideoPresenter.DrawReplay.cs | 212 ++++++++++++++++++ 3 files changed, 224 insertions(+) create mode 100644 src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.DrawReplay.cs diff --git a/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs b/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs index 331c7cb70..03d6f9b5e 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs @@ -190,6 +190,14 @@ IIndirectMeshDraw PrepareIndirectMeshDraw(in IndirectMeshDrawRequest request) => // Changes whenever a buffer owner is unregistered; buffers bound before a change are bound again (RebindBuffers). long BufferOwnerGeneration => 0; + long CurrentItemSequence => 0; + + void SealDrawReplay() + { + } + + bool TryReplayDraw(in PipelineHandle pipeline, ReadOnlySpan vertexUserData, ReadOnlySpan pixelUserData) => false; + void RebindBuffers(IPreparedBindings prepared) { } diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs index 111521233..e38029de8 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs @@ -2300,6 +2300,7 @@ public void CommitBindings(PipelineBindPoint bindPoint, in PipelineHandle pipeli } } + var replayPushStages = default(ShaderStageFlags); if (hasPushData) { var pushStages = bindPoint != PipelineBindPoint.Graphics @@ -2312,8 +2313,11 @@ public void CommitBindings(PipelineBindPoint bindPoint, in PipelineHandle pipeli (entry.Description?.Tessellation is null ? 0 : ShaderStageFlags.TessellationControlBit | ShaderStageFlags.TessellationEvaluationBit); PushConstantsShadowed(command, entry.Layout, pushStages, pushData); + replayPushStages = pushStages; } + CaptureDrawReplay(bindPoint, entry, stages, pushData, hasPushData, replayPushStages); + // A pipeline linked from libraries binds set 0 (vertex), the heap (set 1), then set 2 (pixel): binding a set // with another layout disturbs the sets above it. var vertexWrites = entry.LinkedFromLibraries && pixelWriteStart >= 0 ? pixelWriteStart : writeIndex; diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.DrawReplay.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.DrawReplay.cs new file mode 100644 index 000000000..6102a44ad --- /dev/null +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.DrawReplay.cs @@ -0,0 +1,212 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Gpu.Scheduling; +using SharpEmu.Libs.Gpu.Vulkan; +using SharpEmu.ShaderCompiler.Resources; +using Silk.NET.Vulkan; + +namespace SharpEmu.Libs.VideoOut; + +internal static unsafe partial class VulkanVideoPresenter +{ + private sealed partial class RecordingHost + { + private static readonly bool DrawReplayCapture = Environment.GetEnvironmentVariable("SHARPEMU_DRAW_REPLAY") != "0"; + private readonly uint[] _replayPushData = new uint[PushData.DwordCount]; + private bool _replayCaptured; + private bool _replaySealed; + private bool _replayHasPush; + private PipelineLayout _replayLayout; + private ShaderStageFlags _replayPushStages; + private BindingLayout? _replayVertexLayout; + private uint _replayVertexBase; + private BindingLayout? _replayPixelLayout; + private uint _replayPixelBase; + private RecordingBuffer? _replayRecording; + private long _replayGeneration; + private long _replayEpoch; + private SliceSegment? _replaySegment; + private DrawScopeToken _replayScope; + private long _replayOwners; + private static readonly string[] ReplayHostMissNames = ["unsealed", "recording", "generation", "epoch", "segment", "scope", "owners", "layout", "patch"]; + private static readonly long[] _replayHostMisses = new long[ReplayHostMissNames.Length]; + + internal static string TakeReplayHostMisses() + { + var parts = new List(); + for (var index = 0; index < ReplayHostMissNames.Length; index++) + { + var count = Interlocked.Exchange(ref _replayHostMisses[index], 0); + if (count != 0) + { + parts.Add(FormattableString.Invariant($"{ReplayHostMissNames[index]}:{count}")); + } + } + + return parts.Count == 0 ? "none" : string.Join(",", parts); + } + + private static bool ReplayHostMiss(int reason) + { + Interlocked.Increment(ref _replayHostMisses[reason]); + return false; + } + + long IRenderHost.CurrentItemSequence => _worker ? _itemSequence : _presenter._commandThread is { } thread ? thread.Executed + 1 : 0; + + private void CaptureDrawReplay(PipelineBindPoint bindPoint, RenderPipelineEntry entry, ReadOnlySpan stages, uint* pushData, + bool hasPushData, ShaderStageFlags pushStages) + { + _replayCaptured = false; + _replaySealed = false; + if (!DrawReplayCapture || bindPoint != PipelineBindPoint.Graphics || entry.UsesBindlessHeap || stages.Length is < 1 or > 2 || + _preparation?.StencilStorageImages is not null) + { + return; + } + + _replayVertexLayout = null; + _replayPixelLayout = null; + foreach (var prepared in stages) + { + var stage = (PreparedStageBindings)prepared; + if (stage.Descriptors.GlobalDataShare.Buffer.Handle != 0) + { + return; + } + + foreach (var texture in stage.Textures) + { + if (texture.IsHostMovie) + { + return; + } + } + + if (StageOf(stage.Program) == ShaderStage.Pixel) + { + _replayPixelLayout = stage.Layout; + _replayPixelBase = stage.Program.UserDataBase; + } + else + { + _replayVertexLayout = stage.Layout; + _replayVertexBase = stage.Program.UserDataBase; + } + } + + new ReadOnlySpan(pushData, (int)PushData.DwordCount).CopyTo(_replayPushData); + _replayHasPush = hasPushData; + _replayLayout = entry.Layout; + _replayPushStages = pushStages; + _replayCaptured = true; + } + + void IRenderHost.SealDrawReplay() + { + _replaySealed = false; + if (!_replayCaptured || !_renderingActive) + { + return; + } + + var recording = CurrentRecording(); + _replayRecording = recording; + _replayGeneration = recording.Generation; + _replayEpoch = NativeBindingEpoch.Value; + _replaySegment = _segment; + _replayScope = DrawScope; + _replayOwners = _worker ? 0 : _bufferCache.OwnerGeneration; + _replaySealed = true; + } + + bool IRenderHost.TryReplayDraw(in PipelineHandle pipeline, ReadOnlySpan vertexUserData, ReadOnlySpan pixelUserData) + { + if (!_replaySealed) + { + return ReplayHostMiss(0); + } + + _replaySealed = false; + var recording = CurrentRecording(); + if (!ReferenceEquals(recording, _replayRecording)) + { + return ReplayHostMiss(1); + } + + if (recording.Generation != _replayGeneration) + { + return ReplayHostMiss(2); + } + + if (NativeBindingEpoch.Value != _replayEpoch) + { + return ReplayHostMiss(3); + } + + if (!ReferenceEquals(_segment, _replaySegment)) + { + return ReplayHostMiss(4); + } + + if (DrawScope != _replayScope) + { + return ReplayHostMiss(5); + } + + if (!_worker && _bufferCache.OwnerGeneration != _replayOwners) + { + return ReplayHostMiss(6); + } + + var entry = RequirePipelineEntry(in pipeline); + if (entry.Layout.Handle != _replayLayout.Handle || entry.UsesBindlessHeap) + { + return ReplayHostMiss(7); + } + + if (!_replayHasPush) + { + return true; + } + + var push = stackalloc uint[(int)PushData.DwordCount]; + var data = new Span(push, (int)PushData.DwordCount); + _replayPushData.CopyTo(data); + if (!PatchReplayUserData(data, _replayVertexLayout, _replayVertexBase, vertexUserData) || + !PatchReplayUserData(data, _replayPixelLayout, _replayPixelBase, pixelUserData)) + { + return ReplayHostMiss(8); + } + + PushConstantsShadowed(BeginBatchedGuestStateCommands(), _replayLayout, _replayPushStages, push); + return true; + } + + private static bool PatchReplayUserData(Span push, BindingLayout? layout, uint userDataBase, ReadOnlySpan userData) + { + if (layout is not { UsesPushData: true }) + { + return true; + } + + var registers = layout.UserDataRegisters; + for (var index = 0; index < registers.Count; index++) + { + var register = registers[index]; + var userIndex = (long)register - userDataBase; + if (userIndex < 0 || userIndex >= userData.Length) + { + return false; + } + + push[(int)layout.PushDataStartDword + index] = userData[(int)userIndex]; + } + + return true; + } + } +} From 9c72a85052b2e3238e8b1b520cdbdc78ffe600c7 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:47:37 +0300 Subject: [PATCH 033/134] [GPU] Replay a draw that repeats the previous item's resources --- .../Gpu/Rendering/RenderRecorder.cs | 349 +++++++++++++++++- 1 file changed, 348 insertions(+), 1 deletion(-) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs index 908a69a0f..56291b567 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs @@ -32,8 +32,72 @@ internal sealed partial class RenderRecorder : IResolvedCommandSink private static readonly ThreadCounter _inPlaceDraws = new(); private static readonly ThreadCounter _inPlaceRefused = new(); + private static readonly ThreadCounter _drawReplays = new(); + private static readonly ThreadCounter _drawReplayMisses = new(); + private static readonly bool DrawReplayEnabled = Environment.GetEnvironmentVariable("SHARPEMU_DRAW_REPLAY") != "0"; + private readonly Dictionary _replayablePrograms = new(ReferenceEqualityComparer.Instance); + private bool _replayValid; + private long _replaySequence; + private ShaderStageResources _replayVertex; + private ShaderStageResources _replayPixel; + private VertexInputBuffer[] _replayVertexBuffers = []; + private VertexAttributeResource[] _replayVertexAttributes = []; + private bool _replayPixelActive; + + private static readonly string[] ReplayMissNames = + ["sequence", "pixel_active", "vertex_program", "vertex_images", "vertex_samplers", "vertex_buffers", "vertex_table", "vertex_extras", + "vertex_ranges", "vertex_heaps", "vertex_mips", + "pixel_program", "pixel_images", "pixel_samplers", "pixel_buffers", "pixel_table", "pixel_extras", "pixel_ranges", "pixel_heaps", "pixel_mips", + "vertex_input", "targets", "host"]; + private static readonly ThreadCounter[] _replayMisses = Array.ConvertAll(ReplayMissNames, _ => new ThreadCounter()); + + private static bool ReplayMiss(int reason) + { + _replayMisses[reason].Increment(); + _drawReplayMisses.Increment(); + return false; + } + + private static string TakeReplayMisses() + { + var parts = new List(); + for (var index = 0; index < ReplayMissNames.Length; index++) + { + var count = _replayMisses[index].Take(); + if (count != 0) + { + parts.Add(FormattableString.Invariant($"{ReplayMissNames[index]}:{count}")); + } + } + + return parts.Count == 0 ? "none" : string.Join(",", parts); + } + + private static readonly string[] SealRefusalNames = ["kind", "writes", "trace", "tessellation", "targets", "vertex", "pixel", "sequence"]; + private static readonly ThreadCounter[] _sealRefusals = Array.ConvertAll(SealRefusalNames, _ => new ThreadCounter()); + private static readonly System.Collections.Concurrent.ConcurrentDictionary _unreplayablePrograms = new(); + + private static string TakeSealRefusals() + { + var parts = new List(); + for (var index = 0; index < SealRefusalNames.Length; index++) + { + var count = _sealRefusals[index].Take(); + if (count != 0) + { + parts.Add(FormattableString.Invariant($"{SealRefusalNames[index]}:{count}")); + } + } + + return parts.Count == 0 ? "none" : string.Join(",", parts); + } + + private static string DescribeUnreplayablePrograms() => + _unreplayablePrograms.IsEmpty ? "none" : string.Join(",", _unreplayablePrograms.Select(pair => FormattableString.Invariant($"{pair.Key}:{pair.Value}"))); + public static string TakeInPlaceReport() => FormattableString.Invariant( - $"in_place={_inPlaceDraws.Take()} in_place_refused={_inPlaceRefused.Take()}"); + $"in_place={_inPlaceDraws.Take()} in_place_refused={_inPlaceRefused.Take()} draw_replays={_drawReplays.Take()} draw_replay_misses={_drawReplayMisses.Take()} ") + + "replay_seal_refused=" + TakeSealRefusals() + " replay_miss=" + TakeReplayMisses() + " unreplayable_programs=" + DescribeUnreplayablePrograms(); private sealed class InPlaceDraw { @@ -450,6 +514,12 @@ private void RecordDrawCommands(ResolvedDraw record, ref DrawState state, bool i throw _host.Fatal("A task-launched mesh program reached a draw that is not automatic and indirect."); } + if (meshInput is null && indirectMesh is null && TryReplayDraw(record, ref state, inPlace, vertexInput, pixelInput, in indexSource, in emission, in draw)) + { + return; + } + + _replayValid = false; var meshVertexCount = draw.Count; if (MeshDrawTrace.Active) MeshDrawTrace.Write("programs", $"mesh={meshInput is not null} vertexHash=0x{vertexInput.Stage.Program?.Hash:X16} pixelHash=0x{pixelInput.Stage.Program?.Hash:X16} pixelActive={state.PixelActive}"); @@ -705,6 +775,10 @@ private void RecordDrawCommands(ResolvedDraw record, ref DrawState state, bool i else { KeepTargets(record, ref state); + if (meshInput is null && indirectMesh is null && imageSnapshot == 0) + { + SealReplay(record, in state, vertexInput, pixelInput); + } } if (record.SetAutoDebug) @@ -713,6 +787,279 @@ private void RecordDrawCommands(ResolvedDraw record, ref DrawState state, bool i } } + private bool IsReplayable(ShaderProgramInfo? program) + { + if (program is null) + { + return false; + } + + if (_replayablePrograms.TryGetValue(program, out var known)) + { + return known; + } + + var layout = program.Bindings; + var reason = layout is null ? "no_layout" + : layout.UsesBindlessHeap ? "bindless" + : program.UsesDeviceAddresses ? "device_addresses" + : program.CallRecordCallees.Count != 0 || layout.CallTargetCount != 0 || layout.CallArgumentCount != 0 ? "calls" + : layout.UsesTessellationData ? "tessellation" + : program.Frontend is { RequiresOrderedImagePreparation: true } ? "frontend" + : layout.Find(ShaderCompiler.Resources.DescriptorBindingKind.ShaderData) is not null ? "shader_data" + : layout.Find(ShaderCompiler.Resources.DescriptorBindingKind.FlattenedResourceTable) is not null ? "flattened_table" + : layout.Find(ShaderCompiler.Resources.DescriptorBindingKind.CallRecords) is not null || + layout.Find(ShaderCompiler.Resources.DescriptorBindingKind.CallMarks) is not null ? "call_records" + : layout.Find(ShaderCompiler.Resources.DescriptorBindingKind.GlobalDataShare) is not null ? "gds" + : layout.Find(ShaderCompiler.Resources.DescriptorBindingKind.DeviceAddressFallback) is not null ? "device_address_fallback" + : null; + var replayable = reason is null; + if (!replayable) + { + _unreplayablePrograms.AddOrUpdate(reason!, 1, static (_, count) => count + 1); + } + + _replayablePrograms[program] = replayable; + return replayable; + } + + private static bool SameWordSets(uint[][] current, uint[][] kept) + { + if (ReferenceEquals(current, kept)) + { + return true; + } + + if (current.Length != kept.Length) + { + return false; + } + + for (var index = 0; index < current.Length; index++) + { + if (!ReferenceEquals(current[index], kept[index]) && !current[index].AsSpan().SequenceEqual(kept[index])) + { + return false; + } + } + + return true; + } + + private static int StageInputMismatch(in ShaderStageResources current, in ShaderStageResources kept) + { + if (!ReferenceEquals(current.Program, kept.Program) || current.ShaderBase != kept.ShaderBase) + { + return 0; + } + + if (current.ThreadLimits != kept.ThreadLimits || current.MeshDraw != kept.MeshDraw || current.TessellationData is { Length: > 0 } || + kept.TessellationData is { Length: > 0 } || + !(current.CallArguments ?? []).AsSpan().SequenceEqual(kept.CallArguments ?? [])) + { + return 5; + } + + var resources = current.Resources; + var keptResources = kept.Resources; + if (ReferenceEquals(resources, keptResources)) + { + return -1; + } + + if (!SameWordSets(resources.Images, keptResources.Images)) + { + return 1; + } + + if (!SameWordSets(resources.Samplers, keptResources.Samplers)) + { + return 2; + } + + if (!SameWordSets(resources.Buffers, keptResources.Buffers)) + { + return 3; + } + + if (!resources.FlattenedResourceTable.AsSpan().SequenceEqual(keptResources.FlattenedResourceTable)) + { + return 4; + } + + if (!ReferenceEquals(resources.DeviceAddressRanges, keptResources.DeviceAddressRanges) && + !resources.DeviceAddressRanges.AsSpan().SequenceEqual(keptResources.DeviceAddressRanges)) + { + return 6; + } + + if (resources.Heaps.Length != 0 || keptResources.Heaps.Length != 0) + { + return 7; + } + + return ReferenceEquals(resources.MipStatistics, keptResources.MipStatistics) || + (resources.MipStatistics ?? []).AsSpan().SequenceEqual(keptResources.MipStatistics ?? []) + ? -1 + : 8; + } + + private bool SameVertexInput(VertexInputInfo vertexInput) => + vertexInput.Tessellation is null && + (ReferenceEquals(vertexInput.Buffers, _replayVertexBuffers) || vertexInput.Buffers.AsSpan().SequenceEqual(_replayVertexBuffers)) && + (ReferenceEquals(vertexInput.Attributes, _replayVertexAttributes) || vertexInput.Attributes.AsSpan().SequenceEqual(_replayVertexAttributes)); + + private void SealReplay(ResolvedDraw record, in DrawState state, VertexInputInfo vertexInput, PixelInputInfo pixelInput) + { + _replayValid = false; + if (!DrawReplayEnabled) + { + return; + } + + var refusal = record.Kind != ResolvedDrawKind.Draw ? 0 + : record.WritesMemory ? 1 + : record.IndexedTrace is not null ? 2 + : vertexInput.Tessellation is not null ? 3 + : !_inPlace.Valid ? 4 + : !IsReplayable(vertexInput.Stage.Program) ? 5 + : state.PixelActive && !IsReplayable(pixelInput.Stage.Program) ? 6 + : -1; + var sequence = _host.CurrentItemSequence; + if (refusal < 0 && sequence == 0) + { + refusal = 7; + } + + if (refusal >= 0) + { + _sealRefusals[refusal].Increment(); + return; + } + + _replayVertex = vertexInput.Stage; + _replayPixel = state.PixelActive ? pixelInput.Stage : default; + _replayVertexBuffers = vertexInput.Buffers; + _replayVertexAttributes = vertexInput.Attributes; + _replayPixelActive = state.PixelActive; + _replaySequence = sequence; + _replayValid = true; + _host.SealDrawReplay(); + } + + private bool TryReplayDraw(ResolvedDraw record, ref DrawState state, bool inPlace, VertexInputInfo vertexInput, PixelInputInfo pixelInput, + in IndexSource indexSource, in DrawEmission emission, in DrawCall draw) + { + if (!DrawReplayEnabled || !_replayValid || !inPlace || record.Kind != ResolvedDrawKind.Draw || record.WritesMemory || + record.WriteStages != PipelineStageFlags.None || record.IndexedTrace is not null || MeshDrawTrace.Active) + { + return false; + } + + var sequence = _host.CurrentItemSequence; + if (sequence == 0 || sequence != _replaySequence + 1) + { + return ReplayMiss(0); + } + + if (state.PixelActive != _replayPixelActive) + { + return ReplayMiss(1); + } + + if (StageInputMismatch(vertexInput.Stage, _replayVertex) is var vertexMismatch and >= 0) + { + return ReplayMiss(2 + vertexMismatch); + } + + if (state.PixelActive && StageInputMismatch(pixelInput.Stage, _replayPixel) is var pixelMismatch and >= 0) + { + return ReplayMiss(11 + pixelMismatch); + } + + if (!SameVertexInput(vertexInput)) + { + return ReplayMiss(20); + } + + RenderExecutor.DropUnwrittenColorTargets(record.Context, ref state, state.PixelActive ? pixelInput.Stage.Program : null); + if (!TryRestoreAttachments(ref state)) + { + return ReplayMiss(21); + } + + var indexBuffer = AcquireIndexBuffer(in indexSource); + var indirectArguments = emission.IndirectArgumentsAddress != 0 + ? _host.ObtainBuffer(emission.IndirectArgumentsAddress, + emission.Indexed ? RenderExecutor.IndexedIndirectArgumentsSize : RenderExecutor.AutoIndirectArgumentsSize, isWritten: false) + : default; + var pipeline = ResolvePipeline(record, ref state, vertexInput, state.PixelActive ? pixelInput : null); + if (!_host.TryReplayDraw(in pipeline, vertexInput.Stage.Resources.UserData, + state.PixelActive ? pixelInput.Stage.Resources.UserData : ReadOnlySpan.Empty)) + { + return ReplayMiss(22); + } + + NoteSampledTextures(vertexInput.Stage); + if (state.PixelActive) + { + NoteSampledTextures(pixelInput.Stage); + } + + var submitId = record.SubmitId; + if (record.SetBindDebug) + { + SetDrawDebugPhase(submitId, in draw, 0x100); + } + + if (record.SetAutoDebug) + { + SetDrawDebugPhase(submitId, in draw, 0x400); + } + + if (indexBuffer.Size != 0) + { + _host.BindIndexBuffer(indexBuffer.Binding, indexBuffer.Type); + } + + _host.SetDynamicState(in record.Dynamic); + _host.BeginRendering(in state.Rendering); + _host.BindPipeline(PipelineBindPoint.Graphics, in pipeline); + if (record.SetAutoDebug) + { + SetDrawDebugPhase(submitId, in draw, 0x500); + } + + if (emission.IndirectArgumentsAddress != 0 && emission.Indexed) + { + _host.DrawIndexedIndirect(indirectArguments); + } + else if (emission.IndirectArgumentsAddress != 0) + { + _host.DrawIndirect(indirectArguments); + } + else + { + EmitDraw(record.PrimitiveType, vertexInput, in draw, in emission); + } + + if (record.SetAutoDebug) + { + SetDrawDebugPhase(submitId, in draw, 0x600); + } + + KeepTargets(record, ref state); + if (record.SetAutoDebug) + { + SetDrawDebugPhase(submitId, in draw, 0x700); + } + + _replaySequence = sequence; + _host.SealDrawReplay(); + _drawReplays.Increment(); + return true; + } + private void DrawMeshTasks(ResolvedDraw record, MeshDrawConfiguration mesh, uint meshVertexCount) { ref readonly var draw = ref record.Draw; From 31add4d9f0766c252400b897ad0e0ff224c4c9ef Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 02:47:37 +0300 Subject: [PATCH 034/134] [Diagnostics] Report why a host refuses a draw replay --- src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs index e38029de8..f1f1e6e95 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs @@ -1519,6 +1519,7 @@ private BufferView BindStorageBuffer( private static readonly ThreadCounter _sliceUseStale = new(); internal static string TakeTableReport() => + "replay_host_miss=" + TakeReplayHostMisses() + " " + FormattableString.Invariant($"table_blocks={Interlocked.Exchange(ref _tableBlocks, 0)} descriptors_shadowed={Interlocked.Exchange(ref _descriptorsShadowed, 0)} ") + FormattableString.Invariant($"vsharp_cache=hit:{_sliceUseHits.Take()},miss:{_sliceUseMisses.Take()},stale:{_sliceUseStale.Take()} found_sets_hit={_foundSetsHit.Take()} "); From 68be9f760ecc982ed6e584c7530a4e5e2f7d4511 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:00:38 +0300 Subject: [PATCH 035/134] [ShaderCompiler] Order a materialization level's reads by base and offset once --- .../Resources/MaterializationProgram.cs | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs b/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs index d9eaa1c13..4f49c0a10 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs @@ -384,7 +384,13 @@ public MaterializationProgram Finish(int[][] sourceWords, int[] tableWords, uint var levels = new Level[levelCount]; for (var level = 0; level < levelCount; level++) { - levels[level] = new Level { Reads = [.. reads[level]], Steps = [.. steps[level]] }; + ReadStep[] levelReads = [.. reads[level]]; + if (StaticReadOrder) + { + Array.Sort(levelReads, CompareReadOrder); + } + + levels[level] = new Level { Reads = levelReads, Steps = [.. steps[level]] }; } return new MaterializationProgram(_constants.Count, [.. _constants], [.. _constantValid], levels, sourceWords, tableWords, tableOffsets, @@ -657,6 +663,20 @@ private static void Execute(in Step step, ResourceRuntimeInputs inputs, ulong[] } } + private static readonly bool StaticReadOrder = Environment.GetEnvironmentVariable("SHARPEMU_STATIC_READ_ORDER") != "0"; + + private static int CompareReadOrder(ReadStep left, ReadStep right) + { + var order = left.Low.CompareTo(right.Low); + if (order == 0) order = left.High.CompareTo(right.High); + if (order == 0) order = left.Offset.CompareTo(right.Offset); + if (order == 0) order = left.Records.CompareTo(right.Records); + if (order == 0) order = left.Word3.CompareTo(right.Word3); + if (order == 0) order = left.Kind.CompareTo(right.Kind); + if (order == 0) order = (left.Immediate + left.ConstantOffset).CompareTo(right.Immediate + right.ConstantOffset); + return order != 0 ? order : left.Target.CompareTo(right.Target); + } + private static void ReadLevel(ReadStep[] reads, ResourceRuntimeInputs inputs, Scratch scratch) { var values = scratch.Values; From cb74b13a3a077a01c8520731c6b27ba01d90928a Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:00:38 +0300 Subject: [PATCH 036/134] [GPU] Remember a resolve's last clean page for direct reads --- .../VideoOut/VulkanVideoPresenter.CommandStream.cs | 4 ++++ .../VideoOut/VulkanVideoPresenter.Pipelines.cs | 14 ++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandStream.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandStream.cs index c92dd0a52..0a0f76e60 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandStream.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandStream.cs @@ -221,6 +221,9 @@ private sealed class ResolveWorkerState public long Sequence; public ResolveReadLog Reads = null!; public CleanReadPages? CleanReads; + public ulong DirectPage = ulong.MaxValue; + public nint DirectAlias; + public object? DirectSnapshot; } [ThreadStatic] @@ -243,6 +246,7 @@ void ICommandStreamHost.BeginWorkerResolve(long sequence, ResolveReadLog reads) worker.Sequence = sequence; worker.Reads = reads; + worker.DirectPage = ulong.MaxValue; reads.Version = _bufferCache.GpuModifiedVersion; reads.Publications = _guestPublications.Ordinal; } diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Pipelines.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Pipelines.cs index fc54520d8..9619d5251 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Pipelines.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Pipelines.cs @@ -592,6 +592,20 @@ private bool TryReadAliasBytes(ulong address, Span destination) } } + private void RememberDirectPage(ResolveWorkerState worker, ulong address, ulong size) + { + if (!DirectPageReads || !TryGetCleanReadPage(address, size, out var page, out var slot) || Reads is not { } pages || + pages.Tags[slot] != page + 1 || pages.Aliases[slot] == 0 || _guestBacking.BackingAliasSnapshot is not { } snapshot || + !ReferenceEquals(pages.Snapshots[slot], snapshot)) + { + return; + } + + worker.DirectPage = page; + worker.DirectAlias = (nint)pages.Aliases[slot]; + worker.DirectSnapshot = snapshot; + } + private bool TryGetAliasPointer(ulong address, ulong size, out byte* pointer) { pointer = null; From 7f70b2cfe2568fcd4d3536fd2b7373fbb7acd5d7 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:00:38 +0300 Subject: [PATCH 037/134] [GPU] Read a resolve's remembered clean page without the read checks --- .../VulkanVideoPresenter.Pipelines.cs | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Pipelines.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Pipelines.cs index 9619d5251..948e7b14f 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Pipelines.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Pipelines.cs @@ -355,14 +355,33 @@ private bool ReadWordOnResolveWorker(ulong address, out uint word) return true; } + private static readonly bool DirectPageReads = Environment.GetEnvironmentVariable("SHARPEMU_DIRECT_PAGE_READS") != "0"; + private bool ReadResidentBytesOnResolveWorker(ulong address, Span destination, bool clean) { var size = (ulong)destination.Length; - CompletePendingPublicationsForResourceRead(address, size); var worker = _resolveWorker!; + if (!clean && DirectPageReads && TryGetCleanReadPage(address, size, out var directPage, out _) && directPage == worker.DirectPage && + ReferenceEquals(_guestBacking.BackingAliasSnapshot, worker.DirectSnapshot) && _guestBacking.TryEnterBackingAliasAccess()) + { + try + { + new ReadOnlySpan((byte*)(worker.DirectAlias + (nint)(address - directPage)), destination.Length).CopyTo(destination); + } + finally + { + _guestBacking.ExitBackingAliasAccess(); + } + + worker.Reads.Add(address, destination); + return true; + } + + CompletePendingPublicationsForResourceRead(address, size); if (!clean && IsCleanReadPage(address, size) && TryReadAliasBytes(address, destination)) { worker.Reads.Add(address, destination); + RememberDirectPage(worker, address, size); return true; } From 6da4b2d6567b87cf0484a577be2e7114a022c559 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:00:47 +0300 Subject: [PATCH 038/134] [ShaderCompiler] Read a level's runs in their static order --- src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs b/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs index 4f49c0a10..c0b223f63 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/MaterializationProgram.cs @@ -718,7 +718,7 @@ private static void ReadLevel(ReadStep[] reads, ResourceRuntimeInputs inputs, Sc var targets = scratch.Targets; var bases = scratch.NullBases; var absolute = scratch.Absolute; - for (var index = 1; index < count; index++) + for (var index = StaticReadOrder ? count : 1; index < count; index++) { var address = addresses[index]; var target = targets[index]; From 45675c5511b1e62ef382e091e1d31ad3a4a7b318 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:44:39 +0300 Subject: [PATCH 039/134] [ShaderCompiler] Bound a computed device-address read offset by its operations and access guard --- .../Resources/DeviceAddressRangePlanner.cs | 218 +++++++++++++++++- 1 file changed, 215 insertions(+), 3 deletions(-) diff --git a/src/SharpEmu.ShaderCompiler/Resources/DeviceAddressRangePlanner.cs b/src/SharpEmu.ShaderCompiler/Resources/DeviceAddressRangePlanner.cs index e4be4ff4d..fc179c8fb 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/DeviceAddressRangePlanner.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/DeviceAddressRangePlanner.cs @@ -61,21 +61,36 @@ public static string TakeUnboundedReport() return string.Join(" ", parts); } - public static IReadOnlyList Plan(ShaderResourcePlan plan) + public static IReadOnlyList Plan(ShaderResourcePlan plan) => Plan(plan, out _); + + public static IReadOnlyList Plan(ShaderResourcePlan plan, out bool readsBounded) { + readsBounded = true; var ranges = new List(); var handles = new List(); var slotsByHash = new Dictionary>(); for (var index = 0; index < plan.Memory.Count; index++) { var memory = plan.Memory[index]; - if (memory.Kind is not (MemoryResourceKind.Flat or MemoryResourceKind.Global or MemoryResourceKind.ScalarAddress) || memory.PlanningOnly) + if (memory.DeviceDescriptor || memory.Opcode is "ImageBvhIntersectRay" or "ImageBvh64IntersectRay") + { + readsBounded = false; + } + + if (memory.Kind is not (MemoryResourceKind.Flat or MemoryResourceKind.Global or MemoryResourceKind.ScalarAddress)) { continue; } + if (memory.PlanningOnly) + { + readsBounded &= memory.Kind == MemoryResourceKind.ScalarAddress; + continue; + } + if (plan.Accesses[index]?.Handle is not { Kind: ScalarValueKind.AddressHandle } handle || handle.Operands.Length != 2) { + readsBounded = false; continue; } @@ -119,9 +134,18 @@ public static IReadOnlyList Plan(ShaderResourcePlan plan // The immediate offset is signed; the span keeps the lowest and highest byte. var written = memory.Access is MemoryAccess.Write or MemoryAccess.Atomic; + readsBounded &= memory.Access == MemoryAccess.Read; var bytes = Math.Max((memory.DataBits + 7) / 8, 1u) * Math.Max(memory.DataDwords, 1u); var firstByte = (long)unchecked((int)memory.Offset); var reason = UnboundedReasonOf(plan, index); + var spread = 0L; + if (reason != DeviceAddressUnboundedReason.None && !written && BoundedOffsets && OffsetInterval(plan, index) is { } interval && + interval.High - interval.Low + bytes <= (long)MaxRangeBytes) + { + reason = DeviceAddressUnboundedReason.None; + firstByte += interval.Low; + spread = interval.High - interval.Low; + } ranges[slot] = ranges[slot] with { MemoryIndices = [.. ranges[slot].MemoryIndices, index], @@ -130,7 +154,7 @@ public static IReadOnlyList Plan(ShaderResourcePlan plan Bounded = ranges[slot].Bounded && reason == DeviceAddressUnboundedReason.None, UnboundedReason = ranges[slot].UnboundedReason != DeviceAddressUnboundedReason.None ? ranges[slot].UnboundedReason : reason, FirstByte = Math.Min(ranges[slot].FirstByte, firstByte), - EndByte = Math.Max(ranges[slot].EndByte, firstByte + bytes), + EndByte = Math.Max(ranges[slot].EndByte, firstByte + spread + bytes), }; } @@ -140,11 +164,199 @@ public static IReadOnlyList Plan(ShaderResourcePlan plan { Plannable = plan.ValidateRuntimeValue(ranges[slot].BaseLow) && plan.ValidateRuntimeValue(ranges[slot].BaseHigh), }; + var range = ranges[slot]; + readsBounded &= range.Bounded && range.Plannable && !range.Written && range.Extent <= MaxRangeBytes; } + readsBounded &= ranges.Count != 0 && plan.DeviceRecordCounts is null && plan.Graph.Program.FunctionBufferAccesses.Count == 0; return ranges; } + private static readonly bool BoundedOffsets = Environment.GetEnvironmentVariable("SHARPEMU_BOUNDED_BDA") != "0"; + + private static readonly (uint Low, uint High) FullRange = (0u, uint.MaxValue); + + private static (long Low, long High)? OffsetInterval(ShaderResourcePlan plan, int memoryIndex) + { + var memory = plan.Memory[memoryIndex]; + var access = plan.Accesses[memoryIndex]; + ScalarValue? value; + ScalarValue? predicate; + if (memory.Kind == MemoryResourceKind.ScalarAddress) + { + value = access?.Read is { Operands.Length: >= 2 } read ? read.Operands[1] : null; + predicate = null; + } + else + { + value = access?.Offset; + predicate = access?.Active; + } + + if (value is null || value.IsUndefined) + { + return null; + } + + var budget = 4096; + var (low, high) = BoundValue(plan, value, predicate, ref budget, 0); + return low == FullRange.Low && high == FullRange.High ? null : (low, high); + } + + private static bool SameValue(ShaderResourcePlan plan, ScalarValue left, ScalarValue right) => + ReferenceEquals(left, right) || plan.Graph.Equivalent(left, right); + + private static bool Implies(ShaderResourcePlan plan, ScalarValue predicate, ScalarValue condition, ref int budget, int depth) + { + if (budget <= 0) + { + return false; + } + + budget--; + if (SameValue(plan, predicate, condition)) + { + return true; + } + + if (depth >= 12 || predicate.Kind != ScalarValueKind.Operation || predicate.Operation != ScalarOperation.LogicalAnd || + predicate.Operands.Length != 2) + { + return false; + } + + return Implies(plan, predicate.Operands[0], condition, ref budget, depth + 1) || + Implies(plan, predicate.Operands[1], condition, ref budget, depth + 1); + } + + private static uint PredicateUpper(ShaderResourcePlan plan, ScalarValue value, ScalarValue? predicate, ref int budget, int depth) + { + if (predicate is null || budget <= 0 || depth >= 12 || predicate.Kind != ScalarValueKind.Operation || predicate.Operands.Length != 2) + { + return uint.MaxValue; + } + + budget--; + var left = predicate.Operands[0]; + var right = predicate.Operands[1]; + switch (predicate.Operation) + { + case ScalarOperation.LogicalAnd: + return Math.Min(PredicateUpper(plan, value, left, ref budget, depth + 1), PredicateUpper(plan, value, right, ref budget, depth + 1)); + case ScalarOperation.ULessThan32 when right.IsConstant && right.ConstantU32 != 0 && SameValue(plan, left, value): + return right.ConstantU32 - 1; + case ScalarOperation.UGreaterThan32 when left.IsConstant && left.ConstantU32 != 0 && SameValue(plan, right, value): + return left.ConstantU32 - 1; + case ScalarOperation.ULessThanEqual32 when right.IsConstant && SameValue(plan, left, value): + return right.ConstantU32; + case ScalarOperation.UGreaterThanEqual32 when left.IsConstant && SameValue(plan, right, value): + return left.ConstantU32; + default: + return uint.MaxValue; + } + } + + private static (uint Low, uint High) BoundValue(ShaderResourcePlan plan, ScalarValue value, ScalarValue? predicate, ref int budget, int depth) + { + if (budget <= 0) + { + return FullRange; + } + + budget--; + value = plan.Graph.ResolveInvariantPhi(value) ?? value; + if (value.IsConstant && value.Type == ScalarValueType.U32) + { + return (value.ConstantU32, value.ConstantU32); + } + + var result = FullRange; + if (depth < 24) + { + var operands = value.Operands; + switch (value.Kind) + { + case ScalarValueKind.Operation when operands.Length >= 2: + switch (value.Operation) + { + case ScalarOperation.And32: + { + var left = BoundValue(plan, operands[0], predicate, ref budget, depth + 1); + var right = BoundValue(plan, operands[1], predicate, ref budget, depth + 1); + result = (0, Math.Min(left.High, right.High)); + break; + } + case ScalarOperation.UMin32: + { + var left = BoundValue(plan, operands[0], predicate, ref budget, depth + 1); + var right = BoundValue(plan, operands[1], predicate, ref budget, depth + 1); + result = (Math.Min(left.Low, right.Low), Math.Min(left.High, right.High)); + break; + } + case ScalarOperation.IAdd32: + case ScalarOperation.IMul32: + { + var left = BoundValue(plan, operands[0], predicate, ref budget, depth + 1); + var right = BoundValue(plan, operands[1], predicate, ref budget, depth + 1); + var add = value.Operation == ScalarOperation.IAdd32; + var high = add ? (ulong)left.High + right.High : (ulong)left.High * right.High; + if (high <= uint.MaxValue) + { + result = (add ? left.Low + right.Low : left.Low * right.Low, (uint)high); + } + + break; + } + case ScalarOperation.ShiftLeft32 when operands[1].IsConstant && operands[1].ConstantU32 < 32: + { + var shift = (int)operands[1].ConstantU32; + var source = BoundValue(plan, operands[0], predicate, ref budget, depth + 1); + if (((ulong)source.High << shift) <= uint.MaxValue) + { + result = (source.Low << shift, source.High << shift); + } + + break; + } + case ScalarOperation.ShiftRightLogical32 when operands[1].IsConstant && operands[1].ConstantU32 < 32: + { + var shift = (int)operands[1].ConstantU32; + var source = BoundValue(plan, operands[0], predicate, ref budget, depth + 1); + result = (source.Low >> shift, source.High >> shift); + break; + } + case ScalarOperation.BitFieldUExtract when operands.Length == 3 && operands[1].IsConstant && operands[2].IsConstant && + operands[2].ConstantU32 < 32 && operands[1].ConstantU32 <= 32 - operands[2].ConstantU32: + result = (0, (1u << (int)operands[2].ConstantU32) - 1); + break; + } + + break; + case ScalarValueKind.Select when operands.Length == 3: + if (predicate is not null && Implies(plan, predicate, operands[0], ref budget, 0)) + { + result = BoundValue(plan, operands[1], predicate, ref budget, depth + 1); + } + else + { + var whenTrue = BoundValue(plan, operands[1], predicate, ref budget, depth + 1); + var whenFalse = BoundValue(plan, operands[2], predicate, ref budget, depth + 1); + result = (Math.Min(whenTrue.Low, whenFalse.Low), Math.Max(whenTrue.High, whenFalse.High)); + } + + break; + } + } + + var upper = PredicateUpper(plan, value, predicate, ref budget, 0); + if (upper < result.High) + { + result.High = upper; + } + + return result.Low > result.High ? FullRange : result; + } + private static FlatAddressSpace ClassifyFlatAddress(ShaderResourcePlan plan, ScalarValue high, ScalarValue? active) { var range = UnsignedRange(plan, high, active, []); From 378d87d1054f930f0dbf7e4be27b9099518c7234 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:44:39 +0300 Subject: [PATCH 040/134] [ShaderCompiler] Mark a plan whose device-address reads are all bounded --- src/SharpEmu.ShaderCompiler/Resources/ShaderResourcePlan.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/SharpEmu.ShaderCompiler/Resources/ShaderResourcePlan.cs b/src/SharpEmu.ShaderCompiler/Resources/ShaderResourcePlan.cs index b9b524f33..6f7c0ccf1 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ShaderResourcePlan.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ShaderResourcePlan.cs @@ -333,8 +333,9 @@ ScalarValue RewriteRead(ScalarValue read) plan.ResourceBranches = ResourceBranchBlock.Build(plan, Rewrite); plan.ResourceBranchesWithWrites = plan.ResourceBranches.Count != 0 && ResourceBranchBlock.Writes(plan); plan.ResourceBranchWrites = plan.ResourceBranchesWithWrites ? ResourceBranchBlock.WrittenBuffers(plan) ?? [] : []; - plan.DeviceAddressRanges = DeviceAddressRangePlanner.Plan(plan); + plan.DeviceAddressRanges = DeviceAddressRangePlanner.Plan(plan, out var readsBounded); plan.CallRecordCallees = CallRecordPlanner.Plan(plan); + plan.DeviceAddressReadsBounded = readsBounded && plan.CallRecordCallees.Count == 0; // Each written handle owns three flattened slots after the table reads: base // low, base high and size, which the shader checks every store against. @@ -358,6 +359,8 @@ ScalarValue RewriteRead(ScalarValue read) // Planned after tracking; optional, and never a reason for the plan to fail. public IReadOnlyList DeviceAddressRanges { get; private set; } = []; + public bool DeviceAddressReadsBounded { get; private set; } + public IReadOnlyDictionary WrittenRangeSlotByHandle { get; private set; } = new Dictionary(); public int WrittenRangeCount => WrittenRangeSlotByHandle.Count; From e894cadd12755fcb8ee039ae47241ce1658218f0 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:44:39 +0300 Subject: [PATCH 041/134] [GPU] Carry a plan's bounded device-address reads into its program info --- src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs | 1 + src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs | 1 + 2 files changed, 2 insertions(+) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index 7315bae95..896807fa4 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -2533,6 +2533,7 @@ private static ShaderProgramInfo CreateProgramInfo( VertexOffsetScalarRegister = entry.EmbeddedFetch?.VertexOffsetScalarRegister ?? ShaderProgramInfo.NoScalarRegister, InstanceOffsetScalarRegister = entry.EmbeddedFetch?.InstanceOffsetScalarRegister ?? ShaderProgramInfo.NoScalarRegister, UsesDeviceAddresses = info.UsesDeviceAddresses, + DeviceAddressReadsBounded = entry.Plan.DeviceAddressReadsBounded, ConstantStoreValue = FindConstantStoreValue(entry.Program), HasBitwiseExclusiveOr = entry.HasBitwiseExclusiveOr, ConstantFill = entry.ConstantFill, diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs b/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs index ff25eaa83..c6ed3f6cb 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs @@ -57,6 +57,7 @@ public class ShaderProgramInfo public int VertexOffsetScalarRegister { get; init; } = NoScalarRegister; public int InstanceOffsetScalarRegister { get; init; } = NoScalarRegister; public bool UsesDeviceAddresses { get; init; } + public bool DeviceAddressReadsBounded { get; init; } // The dword every invocation stores when the whole program is 'index, v_mov constant, one // buffer store, end' (AGC's constant fill kernels); null for any other program. From 8d7c9c2fdbfd4d71434d8291d3e2c317bc017456 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:44:40 +0300 Subject: [PATCH 042/134] [GPU] Skip the device-address sweep for programs whose reads are all bounded --- .../Gpu/Buffers/GuestBufferCache.cs | 20 ++++++++ .../VulkanVideoPresenter.Descriptors.cs | 48 ++++++++++++++++++- .../VideoOut/VulkanVideoPresenter.Slices.cs | 5 ++ 3 files changed, 72 insertions(+), 1 deletion(-) diff --git a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs index cabbc5af0..71f0a3ae4 100644 --- a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs +++ b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs @@ -1128,6 +1128,25 @@ public void PrepareBda(IReadOnlyList spans, ulong mapping) _faultProcessPending = true; } + public void PrepareBoundedBda(IReadOnlyList spans, ulong mapping) + { + if (SubmissionScheduler.ReadOnlyThread) + { + throw SubmissionScheduler.ReadOnlyViolation("bda"); + } + + if (_retirementPolicy.CurrentTick != _bdaTouchTick || mapping != _bdaTouchMapping) + { + for (var index = 0; index < spans.Count; index++) + TouchBuffersInRange(spans[index].Address, spans[index].Size); + _bdaTouchTick = _retirementPolicy.CurrentTick; + _bdaTouchMapping = mapping; + } + + _faultProcessPending = true; + Interlocked.Increment(ref BdaBoundedPreparations); + } + private Action? _uploadDirtyBuffersInRange; private bool _inDeviceAddressSweep; private int _uploadBatchDepth; @@ -1267,6 +1286,7 @@ private void RecordSweepBarrier(CommandBuffer native, PipelineStageFlags sourceS private long _observation; public static long BdaSweeps; public static long BdaSweepsSkipped; + public static long BdaBoundedPreparations; // With the command stream on its own thread, guest CPU writes reach the GPU at the stream's // order points (a submission, a label, a write or copy the stream performs); a device-address diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs index f1f1e6e95..408b1650b 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs @@ -1322,9 +1322,18 @@ public void PrepareDeviceAddresses() if (traceAddress != 0 && !memory.Covers(traceAddress, 1)) GuestGpuMemoryHook.Trace(traceAddress, 1, $"device-address-mapping-check readable={_guestMemory.CanRead(traceAddress, 1)} backed={_guestBacking.IsBackedView(traceAddress)}"); + var bounded = BoundedDeviceAddressReads && ReadsOnlyBoundedRanges(preparation); if (_worker) { - Requests.NeedsBdaSweep = true; + if (bounded) + { + Requests.NeedsBdaTouch = true; + } + else + { + Requests.NeedsBdaSweep = true; + } + Requests.BdaSpans = spans; Requests.BdaMapping = _bdaSpanMapping; return; @@ -1339,9 +1348,46 @@ public void PrepareDeviceAddresses() } } + if (bounded) + { + _bufferCache.PrepareBoundedBda(spans, _bdaSpanMapping); + return; + } + _bufferCache.PrepareBda(spans, _bdaSpanMapping); } + private static readonly bool BoundedDeviceAddressReads = Environment.GetEnvironmentVariable("SHARPEMU_BOUNDED_BDA") != "0"; + + private bool ReadsOnlyBoundedRanges(RenderPreparation preparation) + { + var any = false; + foreach (var stage in preparation.Stages) + { + if (!stage.Program.UsesDeviceAddresses) + { + continue; + } + + if (!stage.Program.DeviceAddressReadsBounded) + { + return false; + } + + foreach (var range in DeviceAddressRangesOf(stage)) + { + if (!range.Planned || range.Written || range.Size > ShaderCompiler.Resources.DeviceAddressRangePlanner.MaxRangeBytes) + { + return false; + } + + any = true; + } + } + + return any; + } + private List? _bdaSpans; private GuestGpuMemory? _bdaSpanMemory; private long _bdaSpanVersion = -1; diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs index 60025773c..8791e0d92 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs @@ -278,6 +278,7 @@ private static bool SameBytes(in T left, in T right) where T : unmanaged => public readonly List<(ulong Address, uint[] Words)> KnownWrites = new(); public readonly List Resources = new(); public bool NeedsBdaSweep; + public bool NeedsBdaTouch; public long BufferSerial; public long? ReadsVersion; public bool MixedReadsVersions; @@ -830,6 +831,10 @@ private void RecordSlicePrologue(SliceRequests requests) { _bufferCache.PrepareBda(spans, requests.BdaMapping); } + else if (requests.NeedsBdaTouch && requests.BdaSpans is { } touched) + { + _bufferCache.PrepareBoundedBda(touched, requests.BdaMapping); + } foreach (var (address, size) in requests.SyncRanges) { From 15bbe826a51bea098dd706ab5049ee2675ced12b Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:44:40 +0300 Subject: [PATCH 043/134] [GPU] Hold a clean read slice use on its registered buffer --- .../Gpu/Buffers/GuestBufferCache.Slices.cs | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.Slices.cs b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.Slices.cs index c7fc7d595..7a2192e89 100644 --- a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.Slices.cs +++ b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.Slices.cs @@ -1,6 +1,8 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using SharpEmu.HLE.Diagnostics; + namespace SharpEmu.Libs.Gpu.Buffers; public readonly record struct BufferSliceUse(ulong Address, ulong Size, bool Written, bool Texel, bool InvalidateImages, GpuBuffer Buffer); @@ -144,8 +146,43 @@ public bool ValidateSliceBuffers(List uses) return true; } + private static readonly bool HeldSliceUses = Environment.GetEnvironmentVariable("SHARPEMU_HELD_SLICE_USES") != "0"; + private static readonly ThreadCounter _heldSliceUses = new(); + private static readonly ThreadCounter _obtainedSliceUses = new(); + + public static string TakeHeldSliceUseReport() => + FormattableString.Invariant($"held_uses={_heldSliceUses.Take()}/obtained:{_obtainedSliceUses.Take()}"); + + private bool TryHoldSliceUse(in BufferSliceUse use) + { + if (!HeldSliceUses || use.Written || use.Texel || use.InvalidateImages || ObtainMemoUse != ObtainMemoMode.On || use.Buffer is null) + { + return false; + } + + CompleteGuestPublications?.Invoke(use.Address, use.Size, PublicationAccess.OverlaidRead); + var identifier = _registry.FindContainingBuffer(use.Address, use.Size); + var buffer = use.Buffer; + if (!ReferenceEquals(_registry.TryGetRegisteredBuffer(identifier), buffer) || !buffer.IsInBounds(use.Address, use.Size) || + _tracker.MayHaveCpuDirtyPages(use.Address, use.Size)) + { + return false; + } + + TouchBuffer(identifier); + OverlayGuestPublications?.Invoke(buffer, buffer.Offset(use.Address), use.Address, use.Size); + _heldSliceUses.Increment(); + return true; + } + public void ApplySliceUse(in BufferSliceUse use) { + if (TryHoldSliceUse(in use)) + { + return; + } + + _obtainedSliceUses.Increment(); _ = ObtainBuffer(use.Address, use.Size, use.Written, use.Texel, allowStream: false); if (use.InvalidateImages) { From 7da2ddaa236aac471756cdb4e17bf980d6152338 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:44:41 +0300 Subject: [PATCH 044/134] [Diagnostics] Report bounded device-address preparations and held slice uses --- src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs index 8791e0d92..3cc6b1096 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs @@ -126,7 +126,7 @@ public static (long Ticks, ulong Address, int Kind, string Site) TakeSlowest() internal static string TakeSliceReport() => FormattableString.Invariant($"[PERF][SLICES] slices={_slicesRecorded.Take()} segments={_segmentsRecorded.Take()} empty={_segmentsEmpty.Take()} uses_shared={_usesShared.Take()} attachments_kept={RecordingHost.TakeAttachmentsKept()} worker_queries={RecordingHost.TakeWorkerQueries()} native_rechecks_failed={_nativeColorRechecksFailed.Take()} ") + SharpEmu.Libs.Gpu.Rendering.RenderRecorder.TakeInPlaceReport() + FormattableString.Invariant($" textures_kept={RecordingHost.TakeTexturesKept()} ") + RecordingHost.TakeTableReport() + - FormattableString.Invariant($"bda_sweeps={Interlocked.Exchange(ref GuestBufferCache.BdaSweeps, 0)}/skipped:{Interlocked.Exchange(ref GuestBufferCache.BdaSweepsSkipped, 0)} ") + + FormattableString.Invariant($"bda_sweeps={Interlocked.Exchange(ref GuestBufferCache.BdaSweeps, 0)}/skipped:{Interlocked.Exchange(ref GuestBufferCache.BdaSweepsSkipped, 0)}/bounded:{Interlocked.Exchange(ref GuestBufferCache.BdaBoundedPreparations, 0)} ") + GuestBufferCache.TakeHeldSliceUseReport() + " " + FormattableString.Invariant($"serial_cuts={_slicesSerial.Take()} invalid={_slicesInvalid.Take()} frontend_textures_stale={_frontendTexturesStale.Take()} ") + FormattableString.Invariant($"slice_items={_sliceItems.Take()} serial_items={_serialItems.Take()} join_wait_ms={_sliceWaitTicks.Take() * 1000.0 / System.Diagnostics.Stopwatch.Frequency:F1} ") + FormattableString.Invariant($"image_barriers={ImageAccessState.Barriers.Take()}/elided:{ImageAccessState.BarriersElided.Take()} ") + From 41038b85c748af070f4a979c47c24c7ab77d07c9 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:44:49 +0300 Subject: [PATCH 045/134] [GPU] Compare a stage's inputs without its thread limits --- src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs index 56291b567..5631dcec9 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs @@ -846,14 +846,14 @@ private static bool SameWordSets(uint[][] current, uint[][] kept) return true; } - private static int StageInputMismatch(in ShaderStageResources current, in ShaderStageResources kept) + private static int StageInputMismatch(in ShaderStageResources current, in ShaderStageResources kept, bool compareThreadLimits = true) { if (!ReferenceEquals(current.Program, kept.Program) || current.ShaderBase != kept.ShaderBase) { return 0; } - if (current.ThreadLimits != kept.ThreadLimits || current.MeshDraw != kept.MeshDraw || current.TessellationData is { Length: > 0 } || + if ((compareThreadLimits && current.ThreadLimits != kept.ThreadLimits) || current.MeshDraw != kept.MeshDraw || current.TessellationData is { Length: > 0 } || kept.TessellationData is { Length: > 0 } || !(current.CallArguments ?? []).AsSpan().SequenceEqual(kept.CallArguments ?? [])) { From 89c6599c8e4f21f4f8c2221d0eb883a625da017a Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:44:49 +0300 Subject: [PATCH 046/134] [GPU] Replay a dispatch's bound state for the next dispatch of its pipeline --- .../Gpu/Rendering/IRenderHost.cs | 6 + .../Gpu/Rendering/RenderRecorder.Compute.cs | 124 +++++++++- .../VulkanVideoPresenter.Descriptors.cs | 8 + .../VulkanVideoPresenter.DrawReplay.cs | 220 ++++++++++++++++++ 4 files changed, 357 insertions(+), 1 deletion(-) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs b/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs index 03d6f9b5e..f15466269 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/IRenderHost.cs @@ -198,6 +198,12 @@ void SealDrawReplay() bool TryReplayDraw(in PipelineHandle pipeline, ReadOnlySpan vertexUserData, ReadOnlySpan pixelUserData) => false; + void SealDispatchReplay() + { + } + + bool TryReplayDispatch(in PipelineHandle pipeline, in ShaderStageResources stage) => false; + void RebindBuffers(IPreparedBindings prepared) { } diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Compute.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Compute.cs index 959aa4b42..9fb20b774 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Compute.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Compute.cs @@ -1,6 +1,8 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using SharpEmu.HLE.Diagnostics; +using SharpEmu.Libs.Gpu.Pipelines; using SharpEmu.ShaderCompiler.Vulkan; using Silk.NET.Vulkan; @@ -114,6 +116,20 @@ private void RecordDispatch(ResolvedDispatch record) _keptComputePipeline = pipeline; } + if (!TryReplayDispatch(record, computeProgram, input, in pipeline)) + { + RecordPreparedDispatch(record, computeProgram, input, program, in pipeline); + } + } + + _host.ResetBindings(); + } + + private void RecordPreparedDispatch(ResolvedDispatch record, ComputeProgram computeProgram, ComputeInputInfo input, ShaderProgramInfo program, + in PipelineHandle pipeline) + { + _dispatchReplayValid = false; + { // The indirect arguments are registered before the resources bind, so acquiring them merges no owner the // dispatch already bound. using var arguments = record.IndirectArgumentsAddress != 0 @@ -177,9 +193,115 @@ private void RecordDispatch(ResolvedDispatch record) _host.NoteKnownGpuContents(known.Address, known.Words); known.Release(); } + + if (DispatchReplayEnabled && record.IndirectArgumentsAddress == 0 && !record.GpuThreadCounts && threadDispatch is null && imageSnapshot == 0 && + IsReplayable(program) && _host.CurrentItemSequence is var sequence and not 0) + { + _dispatchReplayStage = stage; + _dispatchReplayPipeline = pipeline; + _dispatchReplaySequence = sequence; + _dispatchReplayValid = true; + _host.SealDispatchReplay(); + } } + } - _host.ResetBindings(); + private static readonly bool DispatchReplayEnabled = Environment.GetEnvironmentVariable("SHARPEMU_DISPATCH_REPLAY") != "0"; + private bool _dispatchReplayValid; + private long _dispatchReplaySequence; + private ShaderStageResources _dispatchReplayStage; + private PipelineHandle _dispatchReplayPipeline; + private static readonly ThreadCounter _dispatchReplays = new(); + private static readonly string[] DispatchMissNames = + ["sequence", "pipeline", "program", "images", "samplers", "buffers", "table", "extras", "ranges", "heaps", "mips", "host"]; + private static readonly ThreadCounter[] _dispatchMisses = Array.ConvertAll(DispatchMissNames, _ => new ThreadCounter()); + + private static bool DispatchMiss(int reason) + { + _dispatchMisses[reason].Increment(); + return false; + } + + internal static string TakeDispatchReplayReport() + { + var parts = new List(); + for (var index = 0; index < DispatchMissNames.Length; index++) + { + var count = _dispatchMisses[index].Take(); + if (count != 0) + { + parts.Add(FormattableString.Invariant($"{DispatchMissNames[index]}:{count}")); + } + } + + return FormattableString.Invariant($"dispatch_replays={_dispatchReplays.Take()} dispatch_replay_miss=") + + (parts.Count == 0 ? "none" : string.Join(",", parts)); + } + + private bool TryReplayDispatch(ResolvedDispatch record, ComputeProgram computeProgram, ComputeInputInfo input, in PipelineHandle pipeline) + { + if (!_dispatchReplayValid) + { + return false; + } + + _dispatchReplayValid = false; + if (!DispatchReplayEnabled || record.IndirectArgumentsAddress != 0 || record.GpuThreadCounts || MeshDrawTrace.Active) + { + return false; + } + + var sequence = _host.CurrentItemSequence; + if (sequence == 0 || sequence != _dispatchReplaySequence + 1) + { + return DispatchMiss(0); + } + + if (pipeline.Pipeline != _dispatchReplayPipeline.Pipeline || pipeline.Layout != _dispatchReplayPipeline.Layout) + { + return DispatchMiss(1); + } + + var stage = input.Stage; + if (stage.GpuThreadLimits || _dispatchReplayStage.GpuThreadLimits) + { + return DispatchMiss(7); + } + + if (StageInputMismatch(in stage, in _dispatchReplayStage, compareThreadLimits: false) is var mismatch and >= 0) + { + return DispatchMiss(2 + mismatch); + } + + if (!_host.TryReplayDispatch(in pipeline, in stage)) + { + return DispatchMiss(11); + } + + var chain = _dispatchChain ??= new DispatchChain(); + if (chain.NeedsHazardBarrier(record, in stage, _host.DeferredBarrierPromotions)) + { + _host.ShaderWriteHazardBarrier(); + } + + _host.BeginCheckedDispatch(); + _host.BindPipeline(PipelineBindPoint.Compute, in pipeline); + var (groupsX, groupsY, groupsZ) = PhysicalGroups(input, record); + _host.Dispatch(groupsX, groupsY, groupsZ); + _host.EndCheckedDispatch(); + chain.Commit(_host.TryDeferShaderAccessBarrier(), _host.DeferredBarrierPromotions); + if (computeProgram.KnownWrite is { } known) + { + _host.NoteKnownGpuContents(known.Address, known.Words); + known.Release(); + } + + _dispatchReplayStage = stage; + _dispatchReplaySequence = sequence; + _dispatchReplayValid = true; + _host.SealDispatchReplay(); + _dispatchReplays.Increment(); + return true; } private bool TryConsume(ResolvedDispatch record, ShaderProgramInfo program) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs index 408b1650b..d92b22b23 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs @@ -1553,6 +1553,11 @@ private BufferView BindStorageBuffer( _imageCache.InvalidateMemoryCopiesFromGpu(address, size); } + if (_holdingStorage && obtained.Buffer is not null) + { + _stageStorage.Add(new HeldStorage(address, size, resource, obtained.Buffer, obtained.Offset)); + } + return obtained; } @@ -1688,6 +1693,8 @@ private void BindBuffers(PreparedStageBindings prepared) throw SubmissionScheduler.Fatal($"The prepared bindings are stale: hash=0x{program.Hash:X16}."); } + _holdingStorage = DispatchReplayCapture && program.Stage == ShaderStageKind.Compute; + _stageStorage.Clear(); if (layout.UsesTableBlock) { WriteTableBlock(prepared, shaderData); @@ -2364,6 +2371,7 @@ public void CommitBindings(PipelineBindPoint bindPoint, in PipelineHandle pipeli } CaptureDrawReplay(bindPoint, entry, stages, pushData, hasPushData, replayPushStages); + CaptureDispatchReplay(bindPoint, entry, stages, pushData, hasPushData); // A pipeline linked from libraries binds set 0 (vertex), the heap (set 1), then set 2 (pixel): binding a set // with another layout disturbs the sets above it. diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.DrawReplay.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.DrawReplay.cs index 6102a44ad..f8413240b 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.DrawReplay.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.DrawReplay.cs @@ -1,6 +1,7 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using SharpEmu.Libs.Gpu.Buffers; using SharpEmu.Libs.Gpu.Pipelines; using SharpEmu.Libs.Gpu.Rendering; using SharpEmu.Libs.Gpu.Scheduling; @@ -186,6 +187,225 @@ bool IRenderHost.TryReplayDraw(in PipelineHandle pipeline, ReadOnlySpan ve return true; } + private static readonly bool DispatchReplayCapture = Environment.GetEnvironmentVariable("SHARPEMU_DISPATCH_REPLAY") != "0"; + + private readonly record struct HeldStorage(ulong Address, ulong Size, BufferResource Resource, GpuBuffer Buffer, ulong Offset); + + private readonly List _stageStorage = new(); + private bool _holdingStorage; + private HeldStorage[] _dispatchStorage = new HeldStorage[16]; + private int _dispatchStorageCount; + private readonly uint[] _dispatchPushData = new uint[PushData.DwordCount]; + private bool _dispatchCaptured; + private bool _dispatchSealed; + private bool _dispatchHasPush; + private PipelineLayout _dispatchLayout; + private BindingLayout? _dispatchStageLayout; + private uint _dispatchUserDataBase; + private ulong _dispatchProgramHash; + private RecordingBuffer? _dispatchRecording; + private long _dispatchGeneration; + private long _dispatchEpoch; + private SliceSegment? _dispatchSegment; + private DrawScopeToken _dispatchScope; + private long _dispatchOwners; + private static readonly string[] DispatchHostMissNames = + ["unsealed", "recording", "generation", "epoch", "segment", "scope", "owners", "layout", "patch", "written", "dirty", "texel"]; + private static readonly long[] _dispatchHostMisses = new long[DispatchHostMissNames.Length]; + + internal static string TakeDispatchHostMisses() + { + var parts = new List(); + for (var index = 0; index < DispatchHostMissNames.Length; index++) + { + var count = Interlocked.Exchange(ref _dispatchHostMisses[index], 0); + if (count != 0) + { + parts.Add(FormattableString.Invariant($"{DispatchHostMissNames[index]}:{count}")); + } + } + + return parts.Count == 0 ? "none" : string.Join(",", parts); + } + + private static bool DispatchHostMiss(int reason) + { + Interlocked.Increment(ref _dispatchHostMisses[reason]); + return false; + } + + private void CaptureDispatchReplay(PipelineBindPoint bindPoint, RenderPipelineEntry entry, ReadOnlySpan stages, uint* pushData, + bool hasPushData) + { + if (bindPoint != PipelineBindPoint.Compute) + { + return; + } + + _dispatchCaptured = false; + _dispatchSealed = false; + _holdingStorage = false; + if (!DispatchReplayCapture || entry.UsesBindlessHeap || stages.Length != 1 || _preparation?.StencilStorageImages is not null) + { + return; + } + + var stage = (PreparedStageBindings)stages[0]; + if (stage.Descriptors.GlobalDataShare.Buffer.Handle != 0 || stage.Layout.MipStatisticsCount != 0 || + stage.Layout.Find(DescriptorBindingKind.ShaderData) is not null) + { + return; + } + + foreach (var texture in stage.Textures) + { + if (texture.IsHostMovie) + { + return; + } + } + + if (_dispatchStorage.Length < _stageStorage.Count) + { + _dispatchStorage = new HeldStorage[Math.Max(_stageStorage.Count, _dispatchStorage.Length * 2)]; + } + + for (var index = 0; index < _stageStorage.Count; index++) + { + var held = _stageStorage[index]; + if (!held.Resource.Written && held.Buffer is GpuRingBuffer) + { + return; + } + + _dispatchStorage[index] = held; + } + + _dispatchStorageCount = _stageStorage.Count; + new ReadOnlySpan(pushData, (int)PushData.DwordCount).CopyTo(_dispatchPushData); + _dispatchHasPush = hasPushData; + _dispatchLayout = entry.Layout; + _dispatchStageLayout = stage.Layout; + _dispatchUserDataBase = stage.Program.UserDataBase; + _dispatchProgramHash = stage.Program.Hash; + _dispatchCaptured = true; + } + + void IRenderHost.SealDispatchReplay() + { + _dispatchSealed = false; + if (!_dispatchCaptured) + { + return; + } + + var recording = CurrentRecording(); + _dispatchRecording = recording; + _dispatchGeneration = recording.Generation; + _dispatchEpoch = NativeBindingEpoch.Value; + _dispatchSegment = _segment; + _dispatchScope = DrawScope; + _dispatchOwners = _worker ? 0 : _bufferCache.OwnerGeneration; + _dispatchSealed = true; + } + + bool IRenderHost.TryReplayDispatch(in PipelineHandle pipeline, in ShaderStageResources stage) + { + if (!_dispatchSealed) + { + return DispatchHostMiss(0); + } + + _dispatchSealed = false; + var recording = CurrentRecording(); + if (!ReferenceEquals(recording, _dispatchRecording)) + { + return DispatchHostMiss(1); + } + + if (recording.Generation != _dispatchGeneration) + { + return DispatchHostMiss(2); + } + + if (NativeBindingEpoch.Value != _dispatchEpoch) + { + return DispatchHostMiss(3); + } + + if (!ReferenceEquals(_segment, _dispatchSegment)) + { + return DispatchHostMiss(4); + } + + if (DrawScope != _dispatchScope) + { + return DispatchHostMiss(5); + } + + var entry = RequirePipelineEntry(in pipeline); + if (entry.Layout.Handle != _dispatchLayout.Handle || entry.UsesBindlessHeap) + { + return DispatchHostMiss(7); + } + + if (!_worker) + { + if (_bufferCache.OwnerGeneration != _dispatchOwners) + { + return DispatchHostMiss(6); + } + + for (var index = 0; index < _dispatchStorageCount; index++) + { + var held = _dispatchStorage[index]; + if (!held.Resource.Written && !held.Resource.Formatted) + { + if (_bufferCache.MayHaveCpuDirtyPages(held.Address, held.Size)) + { + return DispatchHostMiss(10); + } + + continue; + } + + var (buffer, offset, _) = ObtainStorageBuffer(held.Address, held.Size, held.Resource, default, _dispatchProgramHash); + if (!ReferenceEquals(buffer, held.Buffer) || offset != held.Offset) + { + return DispatchHostMiss(held.Resource.Written ? 9 : 11); + } + } + + if (_bufferCache.OwnerGeneration != _dispatchOwners) + { + return DispatchHostMiss(6); + } + } + + if (!_dispatchHasPush) + { + return true; + } + + var push = stackalloc uint[(int)PushData.DwordCount]; + var data = new Span(push, (int)PushData.DwordCount); + _dispatchPushData.CopyTo(data); + var layout = _dispatchStageLayout; + if (!PatchReplayUserData(data, layout, _dispatchUserDataBase, stage.Resources.UserData)) + { + return DispatchHostMiss(8); + } + + if (layout is { UsesPushData: true, UsesDispatchThreadLimits: true } && !stage.GpuThreadLimits) + { + stage.WriteDispatchThreadLimits(data.Slice((int)layout.PushDataStartDword, (int)layout.ShaderDataDwordCount)); + } + + data.CopyTo(_dispatchPushData); + PushConstantsShadowed(BeginBatchedGuestStateCommands(), _dispatchLayout, ShaderStageFlags.ComputeBit, push); + return true; + } + private static bool PatchReplayUserData(Span push, BindingLayout? layout, uint userDataBase, ReadOnlySpan userData) { if (layout is not { UsesPushData: true }) From f32fb555c7299476154fafc065de1bf2bfd3dee6 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:44:50 +0300 Subject: [PATCH 047/134] [Diagnostics] Report dispatch replays and their misses --- src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs | 3 ++- src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs index 5631dcec9..aaf5e71f9 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs @@ -97,7 +97,8 @@ private static string DescribeUnreplayablePrograms() => public static string TakeInPlaceReport() => FormattableString.Invariant( $"in_place={_inPlaceDraws.Take()} in_place_refused={_inPlaceRefused.Take()} draw_replays={_drawReplays.Take()} draw_replay_misses={_drawReplayMisses.Take()} ") + - "replay_seal_refused=" + TakeSealRefusals() + " replay_miss=" + TakeReplayMisses() + " unreplayable_programs=" + DescribeUnreplayablePrograms(); + "replay_seal_refused=" + TakeSealRefusals() + " replay_miss=" + TakeReplayMisses() + " unreplayable_programs=" + DescribeUnreplayablePrograms() + + " " + TakeDispatchReplayReport(); private sealed class InPlaceDraw { diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs index d92b22b23..fd89d8068 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs @@ -1570,7 +1570,7 @@ private BufferView BindStorageBuffer( private static readonly ThreadCounter _sliceUseStale = new(); internal static string TakeTableReport() => - "replay_host_miss=" + TakeReplayHostMisses() + " " + + "replay_host_miss=" + TakeReplayHostMisses() + " dispatch_host_miss=" + TakeDispatchHostMisses() + " " + FormattableString.Invariant($"table_blocks={Interlocked.Exchange(ref _tableBlocks, 0)} descriptors_shadowed={Interlocked.Exchange(ref _descriptorsShadowed, 0)} ") + FormattableString.Invariant($"vsharp_cache=hit:{_sliceUseHits.Take()},miss:{_sliceUseMisses.Take()},stale:{_sliceUseStale.Take()} found_sets_hit={_foundSetsHit.Take()} "); From 85c6af649d3c0615574fc781f6ded3314894fa46 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:57:01 +0300 Subject: [PATCH 048/134] fix tests --- .../SharpEmu.Libs.Tests/GUI/ShortcutSplashTests.cs | 2 +- .../Gpu/Rendering/RenderExecutorDrawTests.cs | 13 +++++++++---- .../VideoOut/SliceRecordingTests.cs | 1 + 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/tests/SharpEmu.Libs.Tests/GUI/ShortcutSplashTests.cs b/tests/SharpEmu.Libs.Tests/GUI/ShortcutSplashTests.cs index 9702d4838..de1c7c2ea 100644 --- a/tests/SharpEmu.Libs.Tests/GUI/ShortcutSplashTests.cs +++ b/tests/SharpEmu.Libs.Tests/GUI/ShortcutSplashTests.cs @@ -37,7 +37,7 @@ public void PrepareKeepsTheOriginalPngAndSurvivesSourceRemoval(int width, int he Assert.Equal(ShortcutSplashCache.PathForGame(game, cache), path); Assert.Equal(File.ReadAllBytes(source), File.ReadAllBytes(path)); File.Delete(source); - using var cached = SKBitmap.Decode(path); + using var cached = SKBitmap.Decode(File.ReadAllBytes(path)); Assert.NotNull(cached); Assert.Equal(width, cached.Width); Assert.Equal(height, cached.Height); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorDrawTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorDrawTests.cs index 0070c1ad5..1983f9667 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorDrawTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorDrawTests.cs @@ -87,14 +87,18 @@ public void IndexedDraw_RecordsTheFullSequenceInOrder() Assert.Contains("create_graphics_pipeline colors=1 depth=False topology=TriangleList restart=False", _pipelines.Calls); } - [Fact] - public void ADrawRepeatingThePreviousTargetsInItsScopeKeepsTheirAcquisitions() + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ADrawRepeatingThePreviousTargetsInItsScopeKeepsTheirAcquisitions(bool markWritten) { _pipelines.Graphics = Programs(vertexBuffers: [new VertexInputBuffer(VertexBase, 16, 4)]); _host.Scope = new DrawScopeToken(1, 1, 1); var banks = Banks(); _executor.DrawIndexed(7, banks, Indexed(6)); _host.Calls.Clear(); + if (markWritten) + banks.MarkWritten(1u << (int)RegisterStamp.ColorTargets); _executor.DrawIndexed(8, banks, Indexed(6)); Assert.DoesNotContain(_host.Calls, call => call.StartsWith("find_image", StringComparison.Ordinal) || call.StartsWith("acquire_color", StringComparison.Ordinal)); @@ -102,7 +106,7 @@ public void ADrawRepeatingThePreviousTargetsInItsScopeKeepsTheirAcquisitions() } [Fact] - public void ADrawAcquiresItsTargetsAgainOnceTheScopeOrTheRegistersChange() + public void ADrawAcquiresItsTargetsAgainOnceTheScopeOrTheTargetChanges() { _pipelines.Graphics = Programs(vertexBuffers: [new VertexInputBuffer(VertexBase, 16, 4)]); _host.Scope = new DrawScopeToken(1, 1, 1); @@ -115,9 +119,10 @@ public void ADrawAcquiresItsTargetsAgainOnceTheScopeOrTheRegistersChange() Assert.Contains(_host.Calls, call => call.StartsWith("acquire_color", StringComparison.Ordinal)); _host.Calls.Clear(); + banks.Context.ColorTargets[0] = RegisterWords.Color(SecondColorBase, 64, 64); banks.MarkWritten(1u << (int)RegisterStamp.ColorTargets); _executor.DrawIndexed(9, banks, Indexed(6)); - Assert.Contains(_host.Calls, call => call.StartsWith("acquire_color", StringComparison.Ordinal)); + Assert.Contains("acquire_color 0 100100000 image=2", _host.Calls); } [Fact] diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/SliceRecordingTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/SliceRecordingTests.cs index 76ee1fb06..41bfe0e54 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/SliceRecordingTests.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/SliceRecordingTests.cs @@ -40,6 +40,7 @@ public void UnresolvedDrawsReachTheJoinerInOrderWithoutAllocatingRecordingBuffer var host = RuntimeHelpers.GetUninitializedObject(PresenterUnderTest.RecordingHostType); SetHostField(host, "_presenter", presenter); SetHostField(host, "_bufferCache", RuntimeHelpers.GetUninitializedObject(typeof(GuestBufferCache))); + SetHostField(host, "_failedSliceLookups", new List()); SetHostField(host, "_arena", new SliceArena(null!, 1)); SetHostField(host, "_sliceDescriptors", new SharpEmu.Libs.Gpu.Pipelines.SliceDescriptorHeap(null!, null!)); var slice = Activator.CreateInstance(SliceType, nonPublic: true)!; From f484338f5595ce0764be9aa0a906063c3f2545f3 Mon Sep 17 00:00:00 2001 From: Usif <19160089+Im-Usif@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:19:55 +0300 Subject: [PATCH 049/134] [AGC/Loader/GPU/Kernel] Super Meat Boy 3D: AGC exports, red-zone patching, GPU-write protection before stores and two missing imports (#1146) * AGC: compute command buffer free space from the 32-bit cursor distance A command buffer's free space is the dword distance between its cursors, truncated to 32 bits, less the reserved space. Unreal Engine writes its jumps and submission prologues through a stack allocator whose down cursor is null and relies on that wrap for room. Returning 0 there sent every such write to the allocator's overflow callback, which is fatal ("Command buffer overflow"). * AGC: add the ACB copy-data export and reference-clock copies on compute queues sceAgcAcbCopyData takes the MEC's raw source and destination selectors; the DCB form carries the CP engine in bit 0 above the selector. Compute queues now store the GPU reference clock for source 9, which Unreal Engine uses to timestamp each submission. The size exports of both forms report the fixed 6-dword packet. * AGC: make a DCB wait take the size its size export reports sceAgcDcbWaitOnAddressGetSize reports the native 14 or 16 dwords, but the wait builder wrote a 7 or 9-dword packet. Unreal Engine sizes its submission prologue with that export and then fills it with waits, so the prologue was left with zero dwords that the command processor cannot parse. The builder now pads the wait with a NOP to the reported size. The new sceAgcAcbWaitOnAddressGetSize reports the 7 or 9-dword packet the ACB wait builder writes. * AGC: add sceAgcDriverSubmitMultiAcbs Submits each command buffer, in order and under one submission lock as sceAgcDriverSubmitMultiDcbs does, on the queue given in the first argument: the same owner sceAgcDriverSubmitAcb takes. * AGC: read sceAgcAcbJump's cache policy, target and size from their registers sceAgcAcbJump takes the command buffer, the cache policy, the target and the size: sceAgcDcbJump's arguments without the jump mode, since an async command buffer always chains. The target was read from the cache policy's register and the size from the target's, so chaining an async command buffer wrote a jump to address 0. The cache policy now goes into the packet as it does for the DCB jump. * AGC: add the event-write and context-register size exports A title reserves room for a packet with its size export before it writes the packet. Unreal Engine's AGC backend imports sceAgcDcbEventWriteGetSize and sceAgcDcbSetCxRegisterDirectGetSize, which were missing. They report what sceAgcDcbEventWrite and sceAgcDcbSetCxRegisterDirect write: 4 dwords for the two event types that carry an address and 2 for the others, and 3 dwords for a context register. * Red-zone patch: an unresolved indirect jump no longer hides a frame's red-zone accesses The frame analysis merged an unknown stack state into every instruction at an indirect jump, so a leaf with a switch lost the state its direct paths had proven and was never treated as a red-zone function: none of its accesses were relocated. The unknown targets now get no state of their own; an access only they reach still proves nothing. * Red-zone patch: split code at direct call targets and follow jump tables by data flow .eh_frame_hdr lists only the functions with unwind entries; in Super Meat Boy 3D one entry spans about 100 MB of code, so the scan saw a single function whose indirect jumps kept every short access from being relocated. Direct call targets now start functions too. Jump tables are resolved where compilers put them apart: the table load interleaved with other instructions, the selector bounded by AND or by CMP; JA away from the jump, and, for a switch inside a loop, the table address loaded once before the loop. That address must be the one LEA that reaches the load on every path, which the table's own targets then confirm. * Vulkan: block CPU reads of earlier GPU writes before a command-stream store lands GPU writes, from copies and from shaders, mark their pages GPU-dirty when the render thread records them, but the read protection that makes a CPU read wait for them is deferred to the next submission. A command-stream store, such as an end-of-pipe label the guest polls, is applied in stream order before that. A guest that saw the label could read the written memory before it was protected and get the bytes from before the write: Super Meat Boy 3D copies its streaming feedback into a pooled staging buffer, read another readback's data from it and crashed. The pending protections are now applied before a store lands. * Kernel: add sceKernelUtimes Sets a file's or directory's access and modification times from two timevals, or both to the current time when the array is null, with the path handling of sceKernelChmod. Super Meat Boy 3D calls it once at startup and got the unresolved-import default. * LibcInternal: run thread_local destructors when a thread exits The guest's libc registers a destructor for each C++ thread_local object with _sceLibcInternalThreadAtexit (destructor, object, DSO handle). It was not implemented, so registrations were dropped and the destructors never ran. They are now kept per thread and run newest first when the thread exits, before its pthread key destructors. * [GPU] Note the GPU copy writes a command-stream store must protect * [GPU] Protect earlier GPU writes before a store only after a copy * [Tests] Cover store protection after copies and shader writes --------- Co-authored-by: ParantezTech <12572227+par274@users.noreply.github.com> --- scripts/ps5_names.txt | 1 + .../Loader/GuestRedZonePatcher.Cache.cs | 2 +- .../Loader/GuestRedZonePatcher.cs | 511 +++++++++++++++++- .../Loader/GuestStackFrameAnalysis.cs | 4 +- .../Agc/AgcExports.CommandPackets.cs | 35 +- .../Agc/AgcExports.ControlFlow.cs | 10 +- .../Agc/AgcExports.DmaPackets.cs | 44 +- src/SharpEmu.Libs/Agc/AgcExports.Events.cs | 17 + .../Agc/AgcExports.RegisterPackets.cs | 12 + .../Agc/AgcExports.Submissions.cs | 60 ++ src/SharpEmu.Libs/Agc/AgcExports.cs | 10 +- .../Gpu/Buffers/GuestBufferCache.cs | 27 +- .../GpuCommandInterpreter.Memory.cs | 4 + .../Images/GuestImageCache.MemoryDetile.cs | 1 + src/SharpEmu.Libs/Kernel/KernelExports.cs | 2 + .../Kernel/KernelMemoryCompatExports.cs | 101 ++++ src/SharpEmu.Libs/LibcInternalExports.cs | 40 ++ .../VulkanVideoPresenter.CommandThread.cs | 3 + .../Agc/AgcCommandBufferChainTests.cs | 32 +- .../Agc/AgcCopyDataRuntimeTests.cs | 29 + .../Agc/AgcEventWriteTests.cs | 28 + .../Agc/AgcSetShRegisterRangeTests.cs | 19 + .../Agc/AgcSubmissionShutdownTests.cs | 1 + .../Agc/AgcWaitRegMemTests.cs | 52 +- .../GpuCommandInterpreterMemoryTests.cs | 37 ++ .../Kernel/KernelUtimesTests.cs | 67 +++ .../LibcInternalThreadAtexitTests.cs | 95 ++++ .../Loader/GuestRedZonePatcherTests.cs | 82 +++ .../CommandStreamStoreProtectionTests.cs | 81 +++ 29 files changed, 1371 insertions(+), 36 deletions(-) create mode 100644 tests/SharpEmu.Libs.Tests/Kernel/KernelUtimesTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/LibcInternal/LibcInternalThreadAtexitTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/CommandStreamStoreProtectionTests.cs diff --git a/scripts/ps5_names.txt b/scripts/ps5_names.txt index 53f57fa8a..bca61b7ca 100644 --- a/scripts/ps5_names.txt +++ b/scripts/ps5_names.txt @@ -115733,6 +115733,7 @@ _sceLibcFree _sceLibcGetMallocParam _sceLibcInitialize _sceLibcInternal +_sceLibcInternalThreadAtexit _sceLibcLockFinalize _sceLibcLockInitialize _sceLibcMalloc diff --git a/src/SharpEmu.Core/Loader/GuestRedZonePatcher.Cache.cs b/src/SharpEmu.Core/Loader/GuestRedZonePatcher.Cache.cs index 3de336eba..c68bbd9f6 100644 --- a/src/SharpEmu.Core/Loader/GuestRedZonePatcher.Cache.cs +++ b/src/SharpEmu.Core/Loader/GuestRedZonePatcher.Cache.cs @@ -11,7 +11,7 @@ namespace SharpEmu.Core.Loader; internal static partial class GuestRedZonePatcher { - private const int PatchCacheVersion = 1; + private const int PatchCacheVersion = 2; private const int MaximumPatchCacheBytes = 32 << 20; private sealed record CachedSite(ulong Offset, int Length, bool TerminalBranch); private sealed record CachedPlan(int Version, string Key, PatchResult Scan, CachedSite[] Sites); diff --git a/src/SharpEmu.Core/Loader/GuestRedZonePatcher.cs b/src/SharpEmu.Core/Loader/GuestRedZonePatcher.cs index 3e7ecad13..51823b2eb 100644 --- a/src/SharpEmu.Core/Loader/GuestRedZonePatcher.cs +++ b/src/SharpEmu.Core/Loader/GuestRedZonePatcher.cs @@ -20,6 +20,7 @@ internal static partial class GuestRedZonePatcher private const ulong MaximumRelativeJumpDistance = 0x7FFF_FFFF; private const int MaximumJumpTableEntries = 4096; private const int MaximumJumpTableSetupInstructions = 6; + private const int MaximumJumpTableSliceInstructions = 16; private const ulong LargeExecutableBytes = 32UL << 20; private static readonly TimeSpan ProgressInterval = TimeSpan.FromSeconds(2); @@ -274,6 +275,7 @@ private static List CollectPatchSites( continue; } + segmentFunctions = AddDirectCallTargets(segmentBytes, segmentStart, segmentEnd, segmentFunctions); for (var functionIndex = 0; functionIndex < segmentFunctions.Length; functionIndex++) { progress?.Report(scannedFunctions++); @@ -396,6 +398,39 @@ private static List CollectPatchSites( return sites; } + // .eh_frame_hdr lists only the functions that have unwind entries, so the span between two entries can hold many + // functions: one red-zone leaf among them sends every access of its neighbours to a trampoline, and one unresolved + // indirect jump among them leaves the leaf unprotected. Direct call targets are function entries too. + private static ulong[] AddDirectCallTargets(byte[] segmentBytes, ulong segmentStart, ulong segmentEnd, ulong[] functionStarts) + { + var starts = new HashSet(functionStarts); + for (var index = 0; index < functionStarts.Length; index++) + { + var start = functionStarts[index]; + var end = index + 1 < functionStarts.Length ? functionStarts[index + 1] : segmentEnd; + var reader = new ArraySliceCodeReader(segmentBytes, checked((int)(start - segmentStart)), checked((int)(end - start))); + var decoder = Decoder.Create(64, reader, DecoderOptions.None); + decoder.IP = start; + while (decoder.IP < end && reader.CanRead) + { + decoder.Decode(out var instruction); + if (instruction.Code == Code.INVALID) + { + break; + } + + if (instruction.FlowControl == FlowControl.Call && + instruction.Op0Kind == OpKind.NearBranch64 && + instruction.NearBranch64 >= segmentStart && instruction.NearBranch64 < segmentEnd) + { + starts.Add(instruction.NearBranch64); + } + } + } + + return starts.Count == functionStarts.Length ? functionStarts : starts.Order().ToArray(); + } + private static List DecodeFunction( byte[] segmentBytes, ulong segmentStart, @@ -455,8 +490,9 @@ private static bool TryCollectJumpTableTargets( ulong functionEnd, HashSet branchTargets) { - List? resolvedTargets = null; HashSet? instructionBoundaries = null; + Dictionary>? jumpTargets = null; + List? unresolved = null; for (var instructionIndex = 0; instructionIndex < decoded.Count; instructionIndex++) { if (decoded[instructionIndex].Instruction.FlowControl != FlowControl.IndirectBranch) @@ -467,8 +503,19 @@ private static bool TryCollectJumpTableTargets( instructionBoundaries ??= decoded .Select(static entry => entry.Instruction.IP) .ToHashSet(); - resolvedTargets ??= new List(); - if (!TryResolveJumpTable( + var targets = new List(); + if (TryResolveJumpTable( + memory, + programHeaders, + imageBase, + decoded, + instructionIndex, + functionStart, + functionEnd, + instructionBoundaries, + branchTargets, + targets) || + TryResolveSlicedJumpTable( memory, programHeaders, imageBase, @@ -478,15 +525,51 @@ private static bool TryCollectJumpTableTargets( functionEnd, instructionBoundaries, branchTargets, - resolvedTargets)) + null, + targets)) { - return false; + (jumpTargets ??= new())[instructionIndex] = targets; + } + else + { + (unresolved ??= new()).Add(instructionIndex); } } - if (resolvedTargets is not null) + // A switch inside a loop loads its table address before the loop; the jumps resolved above give the data flow + // their exact edges. + if (unresolved is not null) { - branchTargets.UnionWith(resolvedTargets); + jumpTargets ??= new(); + foreach (var jumpIndex in unresolved) + { + var targets = new List(); + if (!TryResolveSlicedJumpTable( + memory, + programHeaders, + imageBase, + decoded, + jumpIndex, + functionStart, + functionEnd, + instructionBoundaries!, + branchTargets, + jumpTargets, + targets)) + { + return false; + } + + jumpTargets[jumpIndex] = targets; + } + } + + if (jumpTargets is not null) + { + foreach (var targets in jumpTargets.Values) + { + branchTargets.UnionWith(targets); + } } return true; @@ -657,6 +740,420 @@ private static bool TryResolveJumpTable( return true; } + // Compilers interleave independent instructions with the table load, bound the selector with AND or with CMP; JA far + // from the jump, and load the table address once before a loop that holds the switch. Follow the data flow instead of + // fixed positions: jmp T, where T = movsxd [B + S*4] + B and B = lea [rip + table]. B comes from straight-line code no + // branch enters, or, once 'resolvedJumps' gives the function's other tables, from the one LEA that reaches the load + // on every path; that needs a bounded selector and holds only if the table's own edges keep it the one definition. + // A bounded table must name instructions of this function throughout; any other is read until an entry stops naming + // one, which can only add targets. + private static bool TryResolveSlicedJumpTable( + IVirtualMemory memory, + IReadOnlyList programHeaders, + ulong imageBase, + IReadOnlyList decoded, + int jumpIndex, + ulong functionStart, + ulong functionEnd, + IReadOnlySet instructionBoundaries, + IReadOnlySet knownBranchTargets, + IReadOnlyDictionary>? resolvedJumps, + List targets) + { + var jump = decoded[jumpIndex].Instruction; + if (jump.Mnemonic != Mnemonic.Jmp || jump.OpCount != 1 || jump.GetOpKind(0) != OpKind.Register || + jump.GetOpRegister(0).GetSize() != sizeof(ulong) || knownBranchTargets.Contains(jump.IP)) + { + return false; + } + + var factory = new InstructionInfoFactory(); + var targetRegister = jump.GetOpRegister(0); + var addIndex = FindDefinition(decoded, jumpIndex - 1, targetRegister, Register.None, knownBranchTargets, factory); + if (addIndex < 0) + { + return false; + } + + var add = decoded[addIndex].Instruction; + if (add.Mnemonic != Mnemonic.Add || add.OpCount != 2 || + add.GetOpKind(0) != OpKind.Register || add.GetOpRegister(0) != targetRegister || + add.GetOpKind(1) != OpKind.Register || add.GetOpRegister(1).GetSize() != sizeof(ulong) || + add.GetOpRegister(1) == targetRegister || knownBranchTargets.Contains(add.IP)) + { + return false; + } + + var tableRegister = add.GetOpRegister(1); + var loadIndex = FindDefinition(decoded, addIndex - 1, targetRegister, tableRegister, knownBranchTargets, factory); + if (loadIndex < 0) + { + return false; + } + + var load = decoded[loadIndex].Instruction; + if (load.Mnemonic != Mnemonic.Movsxd || load.OpCount != 2 || + load.GetOpKind(0) != OpKind.Register || load.GetOpRegister(0) != targetRegister || + load.GetOpKind(1) != OpKind.Memory || load.MemorySize.GetSize() != sizeof(int) || + load.MemoryBase != tableRegister || load.MemoryIndexScale != sizeof(int) || + load.MemoryIndex.GetSize() != sizeof(ulong) || load.MemoryIndex.GetFullRegister() == tableRegister.GetFullRegister() || + load.MemoryDisplacement64 != 0 || knownBranchTargets.Contains(load.IP)) + { + return false; + } + + var entryLimit = MaximumJumpTableEntries; + var bounded = TryFindSelectorBound(decoded, loadIndex, load.MemoryIndex, knownBranchTargets, factory, out var comparedEntries); + if (bounded) + { + entryLimit = comparedEntries; + } + else + { + var selectorIndex = FindDefinition(decoded, loadIndex - 1, load.MemoryIndex, Register.None, knownBranchTargets, factory); + if (selectorIndex >= 0) + { + var selector = decoded[selectorIndex].Instruction; + // A 32-bit AND clears the upper half too; a narrower one would leave it. + if (selector.Mnemonic == Mnemonic.And && selector.OpCount == 2 && + selector.GetOpKind(0) == OpKind.Register && selector.GetOpRegister(0).GetSize() >= sizeof(int) && + TryGetNonNegativeImmediate(selector, 1, out var mask) && mask < MaximumJumpTableEntries) + { + entryLimit = (int)mask + 1; + bounded = true; + } + else if (ComparesBeforeRedefinition(decoded, selectorIndex, load.MemoryIndex)) + { + // The bounds check applied to the value the redefinition replaced. + return false; + } + } + } + + Dictionary? index = null; + var leaIndex = FindDefinition(decoded, loadIndex - 1, tableRegister, Register.None, knownBranchTargets, factory); + if (leaIndex < 0 && bounded && resolvedJumps is not null) + { + index = new Dictionary(decoded.Count); + for (var position = 0; position < decoded.Count; position++) + { + index[decoded[position].Instruction.IP] = position; + } + + leaIndex = FindReachingDefinition(decoded, index, loadIndex, tableRegister, jumpIndex, null, resolvedJumps, factory); + } + + if (leaIndex < 0) + { + return false; + } + + var lea = decoded[leaIndex].Instruction; + if (lea.Mnemonic != Mnemonic.Lea || lea.OpCount != 2 || !lea.IsIPRelativeMemoryOperand || + lea.GetOpRegister(0) != tableRegister) + { + return false; + } + + var tableAddress = lea.IPRelativeMemoryAddress; + var firstTarget = targets.Count; + Span entry = stackalloc byte[sizeof(int)]; + for (var entryIndex = 0; entryIndex < entryLimit; entryIndex++) + { + var entryAddress = tableAddress + (ulong)entryIndex * sizeof(int); + if (!IsRangeInReadableLoad(programHeaders, imageBase, entryAddress, sizeof(int)) || + !memory.TryRead(entryAddress, entry) || + !TryAddSignedOffset(tableAddress, BinaryPrimitives.ReadInt32LittleEndian(entry), out var target) || + target < functionStart || target >= functionEnd || + !instructionBoundaries.Contains(target)) + { + if (bounded || entryIndex == 0) + { + targets.RemoveRange(firstTarget, targets.Count - firstTarget); + return false; + } + + break; + } + + targets.Add(target); + } + + if (index is not null && + FindReachingDefinition(decoded, index, loadIndex, tableRegister, jumpIndex, targets.GetRange(firstTarget, targets.Count - firstTarget), + resolvedJumps!, factory) != leaIndex) + { + targets.RemoveRange(firstTarget, targets.Count - firstTarget); + return false; + } + + return true; + } + + // CMP S, N; JA default, then straight-line code that leaves S alone and that no known branch enters, up to the + // table load: S indexes N + 1 entries. + private static bool TryFindSelectorBound( + IReadOnlyList decoded, + int loadIndex, + Register selector, + IReadOnlySet knownBranchTargets, + InstructionInfoFactory factory, + out int entryCount) + { + entryCount = 0; + var fullSelector = selector.GetFullRegister(); + for (var index = loadIndex - 1; index > 0 && index > loadIndex - MaximumJumpTableSliceInstructions; index--) + { + var instruction = decoded[index].Instruction; + if (instruction.Mnemonic == Mnemonic.Ja) + { + var compare = decoded[index - 1].Instruction; + if (compare.Mnemonic != Mnemonic.Cmp || compare.OpCount != 2 || compare.GetOpKind(0) != OpKind.Register || + compare.GetOpRegister(0).GetFullRegister() != fullSelector || + compare.GetOpRegister(0).GetSize() < sizeof(int) || + !TryGetNonNegativeImmediate(compare, 1, out var maximum) || maximum >= MaximumJumpTableEntries) + { + return false; + } + + entryCount = (int)maximum + 1; + return true; + } + + if (instruction.FlowControl != FlowControl.Next || knownBranchTargets.Contains(instruction.IP) || + WritesRegister(instruction, fullSelector, factory)) + { + return false; + } + } + + return false; + } + + // The one instruction whose write of 'register' reaches 'use' on every path, or -1. Paths follow fall-through and + // direct branches inside the function; a resolved jump table reaches its targets, and every other indirect jump + // (the one at 'jumpIndex' too when 'jumpTargets' is null) may reach any instruction. The function entry, and any + // other instruction that neither direct flow nor a known table reaches, brings in an unknown value; when + // 'jumpTargets' is null that is only the entry, which can name the definition but not confirm it. A call ends a + // caller-saved register's value. + private static int FindReachingDefinition( + IReadOnlyList decoded, + IReadOnlyDictionary index, + int use, + Register register, + int jumpIndex, + IReadOnlyList? jumpTargets, + IReadOnlyDictionary> resolvedJumps, + InstructionInfoFactory factory) + { + const int MaximumDefinitions = 63; + const int MaximumPasses = 128; + var fullRegister = register.GetFullRegister(); + var callerSaved = fullRegister is Register.RAX or Register.RCX or Register.RDX or Register.RSI or Register.RDI or + Register.R8 or Register.R9 or Register.R10 or Register.R11; + var count = decoded.Count; + var definition = new int[count]; + var definitions = new List { -1 }; + var reached = new bool[count]; + for (var position = 0; position < count; position++) + { + var instruction = decoded[position].Instruction; + definition[position] = -1; + if (instruction.FlowControl is FlowControl.Call or FlowControl.IndirectCall) + { + if (callerSaved) definition[position] = 0; + } + else if (WritesRegister(instruction, fullRegister, factory)) + { + if (definitions.Count > MaximumDefinitions) return -1; + definition[position] = definitions.Count; + definitions.Add(position); + } + + if (instruction.FlowControl is FlowControl.Next or FlowControl.ConditionalBranch or FlowControl.Call or + FlowControl.IndirectCall && position + 1 < count) + { + reached[position + 1] = true; + } + + if (instruction.FlowControl is FlowControl.ConditionalBranch or FlowControl.UnconditionalBranch && + TryGetNearBranchTarget(instruction, out var target) && index.TryGetValue(target, out var targetIndex)) + { + reached[targetIndex] = true; + } + } + + var input = new ulong[count]; + input[0] = 1; + if (jumpTargets is not null) + { + foreach (var targets in resolvedJumps.Values) + foreach (var target in targets) + if (index.TryGetValue(target, out var targetIndex)) reached[targetIndex] = true; + foreach (var target in jumpTargets) + if (index.TryGetValue(target, out var targetIndex)) reached[targetIndex] = true; + for (var position = 1; position < count; position++) + { + var instruction = decoded[position].Instruction; + if (!reached[position] && instruction.Mnemonic is not (Mnemonic.Nop or Mnemonic.Int3)) + { + input[position] = 1; + } + } + } + + var anywhere = 0UL; + for (var pass = 0; ; pass++) + { + if (pass == MaximumPasses) return -1; + var changed = false; + for (var position = 0; position < count; position++) + { + var instruction = decoded[position].Instruction; + var output = definition[position] >= 0 ? 1UL << definition[position] : input[position] | anywhere; + switch (instruction.FlowControl) + { + case FlowControl.Next: + case FlowControl.Call: + case FlowControl.IndirectCall: + Flow(position + 1, output); + break; + case FlowControl.ConditionalBranch: + Flow(position + 1, output); + FlowTo(instruction, output); + break; + case FlowControl.UnconditionalBranch: + FlowTo(instruction, output); + break; + case FlowControl.IndirectBranch: + var targets = position == jumpIndex ? jumpTargets : resolvedJumps.GetValueOrDefault(position); + if (targets is null) + { + if ((anywhere | output) != anywhere) + { + anywhere |= output; + changed = true; + } + } + else + { + foreach (var target in targets) + if (index.TryGetValue(target, out var targetIndex)) Flow(targetIndex, output); + } + + break; + } + } + + if (!changed) break; + + void Flow(int target, ulong mask) + { + if (target >= count || (input[target] | mask) == input[target]) return; + input[target] |= mask; + changed = true; + } + + void FlowTo(in Instruction branch, ulong mask) + { + if (TryGetNearBranchTarget(branch, out var target) && index.TryGetValue(target, out var targetIndex)) + Flow(targetIndex, mask); + } + } + + var reaching = input[use] | anywhere; + if (reaching == 0 || (reaching & 1) != 0 || (reaching & (reaching - 1)) != 0) return -1; + return definitions[System.Numerics.BitOperations.TrailingZeroCount(reaching)]; + } + + private static bool WritesRegister(in Instruction instruction, Register fullRegister, InstructionInfoFactory factory) + { + foreach (var used in factory.GetInfo(instruction).GetUsedRegisters()) + { + if (used.Access is (OpAccess.Write or OpAccess.CondWrite or OpAccess.ReadWrite or OpAccess.ReadCondWrite) && + used.Register.GetFullRegister() == fullRegister) + { + return true; + } + } + + return false; + } + + private static bool ComparesBeforeRedefinition(IReadOnlyList decoded, int definitionIndex, Register register) + { + var fullRegister = register.GetFullRegister(); + for (var index = definitionIndex - 1; index >= 0 && index > definitionIndex - MaximumJumpTableSliceInstructions; index--) + { + var instruction = decoded[index].Instruction; + if (instruction.Mnemonic == Mnemonic.Cmp && instruction.OpCount == 2 && + instruction.GetOpKind(0) == OpKind.Register && instruction.GetOpRegister(0).GetFullRegister() == fullRegister) + { + return true; + } + + if (instruction.FlowControl is not (FlowControl.Next or FlowControl.ConditionalBranch)) + { + return false; + } + } + + return false; + } + + // The last instruction at or before 'from' that writes 'register', through straight-line code that leaves + // 'protectedRegister' alone and that no known branch enters past the definition; -1 when there is none nearby. + private static int FindDefinition( + IReadOnlyList decoded, + int from, + Register register, + Register protectedRegister, + IReadOnlySet knownBranchTargets, + InstructionInfoFactory factory) + { + var fullRegister = register.GetFullRegister(); + var fullProtected = protectedRegister == Register.None ? Register.None : protectedRegister.GetFullRegister(); + for (var index = from; index >= 0 && index > from - MaximumJumpTableSliceInstructions; index--) + { + var instruction = decoded[index].Instruction; + if (instruction.FlowControl != FlowControl.Next) + { + return -1; + } + + var writesRegister = false; + foreach (var used in factory.GetInfo(instruction).GetUsedRegisters()) + { + if (used.Access is not (OpAccess.Write or OpAccess.CondWrite or OpAccess.ReadWrite or OpAccess.ReadCondWrite)) + { + continue; + } + + var written = used.Register.GetFullRegister(); + if (written == fullRegister) + { + writesRegister = true; + } + else if (written == fullProtected) + { + return -1; + } + } + + if (writesRegister) + { + return index; + } + + if (knownBranchTargets.Contains(instruction.IP)) + { + return -1; + } + } + + return -1; + } + private static bool IsStoreToMemory(in Instruction instruction) => instruction.Mnemonic == Mnemonic.Mov && instruction.OpCount == 2 && instruction.GetOpKind(0) == OpKind.Memory; diff --git a/src/SharpEmu.Core/Loader/GuestStackFrameAnalysis.cs b/src/SharpEmu.Core/Loader/GuestStackFrameAnalysis.cs index d44fbe4d0..3ee7ce69c 100644 --- a/src/SharpEmu.Core/Loader/GuestStackFrameAnalysis.cs +++ b/src/SharpEmu.Core/Loader/GuestStackFrameAnalysis.cs @@ -44,8 +44,8 @@ internal static bool UsesFrameRedZone(IReadOnlyList instructions) if (indices.TryGetValue(instruction.NearBranchTarget, out var target)) Merge(target, next); break; case FlowControl.IndirectBranch: - // Unknown targets can enter any instruction with unknown stack state. - for (var targetIndex = 0; targetIndex < instructions.Count; targetIndex++) Merge(targetIndex, new(null, null)); + // Unknown targets get no state: an access only they reach proves nothing, and the jump cannot undo + // a red-zone access that direct flow from the entry already proved. break; } } diff --git a/src/SharpEmu.Libs/Agc/AgcExports.CommandPackets.cs b/src/SharpEmu.Libs/Agc/AgcExports.CommandPackets.cs index 8fca58dd3..7365375a6 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.CommandPackets.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.CommandPackets.cs @@ -244,6 +244,23 @@ public static int AcbAcquireMemGetSize(CpuContext ctx) return (int)ctx[CpuRegister.Rax]; } + // Matches the packet AcbWaitRegMem writes: 7 dwords for a 32-bit label, 9 for a 64-bit one. + [SysAbiExport( + Nid = "idlaArvdXEs", + ExportName = "sceAgcAcbWaitOnAddressGetSize", + Target = Generation.Gen5, + LibraryName = "libSceAgc")] + public static int AcbWaitOnAddressGetSize(CpuContext ctx) + { + ctx[CpuRegister.Rax] = (uint)ctx[CpuRegister.Rdi] switch + { + 0 => 7u * sizeof(uint), + 1 => 9u * sizeof(uint), + _ => 0, + }; + return (int)ctx[CpuRegister.Rax]; + } + [SysAbiExport( Nid = "htn36gPnBk4", ExportName = "sceAgcAcbWaitRegMem", @@ -675,7 +692,7 @@ public static int DcbWaitRegMem(CpuContext ctx) var packetDwords = size == 0 ? 7u : 9u; var packetRegister = size == 0 ? RWaitMem32 : RWaitMem64; - if (!TryAllocateCommandDwords(ctx, commandBufferAddress, packetDwords, out var commandAddress) || + if (!TryAllocateCommandDwords(ctx, commandBufferAddress, packetDwords + WaitOnAddressPadDwords, out var commandAddress) || !TryWriteUInt32(ctx, commandAddress, Pm4(packetDwords, ItNop, packetRegister)) || !TryWriteUInt32(ctx, commandAddress + 4, (uint)address & (size == 0 ? ~0x3u : ~0x7u)) || !TryWriteUInt32(ctx, commandAddress + 8, (uint)(address >> 32) & 0x3FFFFu) || @@ -701,6 +718,14 @@ public static int DcbWaitRegMem(CpuContext ctx) return ReturnPointer(ctx, 0); } + Span pad = stackalloc uint[(int)WaitOnAddressPadDwords]; + pad.Clear(); + pad[0] = Pm4(WaitOnAddressPadDwords, ItNop, RZero); + if (!TryWriteCommandDwords(ctx, commandAddress + (packetDwords * sizeof(uint)), pad)) + { + return ReturnPointer(ctx, 0); + } + if (ShouldTraceHotPath(ref _dcbWaitRegMemTraceCount)) { TraceAgc( @@ -712,6 +737,10 @@ public static int DcbWaitRegMem(CpuContext ctx) return ReturnPointer(ctx, commandAddress); } + // A DCB wait takes the native size sceAgcDcbWaitOnAddressGetSize reports: the wait packet, then a NOP over the rest. + // Titles size buffers with that export and fill them with waits (UE's submission prologue), so the two must agree. + private const uint WaitOnAddressPadDwords = 7; + [SysAbiExport( Nid = "43WJ08sSugE", ExportName = "sceAgcDcbWaitOnAddressGetSize", @@ -722,8 +751,8 @@ public static int GetWaitOnAddressSize(CpuContext context) var labelSize = (uint)context[CpuRegister.Rdi]; context[CpuRegister.Rax] = labelSize switch { - 0 => 14u * sizeof(uint), - 1 => 16u * sizeof(uint), + 0 => (7u + WaitOnAddressPadDwords) * sizeof(uint), + 1 => (9u + WaitOnAddressPadDwords) * sizeof(uint), _ => 0, }; return (int)context[CpuRegister.Rax]; diff --git a/src/SharpEmu.Libs/Agc/AgcExports.ControlFlow.cs b/src/SharpEmu.Libs/Agc/AgcExports.ControlFlow.cs index b5bcf3fa1..435b42466 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.ControlFlow.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.ControlFlow.cs @@ -271,6 +271,8 @@ public static int AcbJumpGetSize(CpuContext ctx) return (int)ctx[CpuRegister.Rax]; } + // The arguments are sceAgcDcbJump's without the jump mode, since an async command buffer always chains: + // (acb, cache policy, target, size). [SysAbiExport( Nid = "e1DFTg+Sd8U", ExportName = "sceAgcAcbJump", @@ -279,15 +281,17 @@ public static int AcbJumpGetSize(CpuContext ctx) public static int AcbJump(CpuContext ctx) { var acb = ctx[CpuRegister.Rdi]; - var target = ctx[CpuRegister.Rsi]; - var sizeDwords = (uint)ctx[CpuRegister.Rdx]; - if (acb == 0) + var cachePolicy = (uint)ctx[CpuRegister.Rsi]; + var target = ctx[CpuRegister.Rdx]; + var sizeDwords = (uint)ctx[CpuRegister.Rcx]; + if (acb == 0 || cachePolicy > 3) { return ReturnPointer(ctx, 0); } const uint chainMode = 1; var control = 0x0F20_0000u | + ((cachePolicy & 0x3u) << 28) | (chainMode << 20) | (sizeDwords & 0xFFFFFu); if (!TryAllocateCommandDwords(ctx, acb, 4, out var cmd) || diff --git a/src/SharpEmu.Libs/Agc/AgcExports.DmaPackets.cs b/src/SharpEmu.Libs/Agc/AgcExports.DmaPackets.cs index 5d1c8bb55..39a57fe72 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.DmaPackets.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.DmaPackets.cs @@ -15,7 +15,12 @@ public static partial class AgcExports ExportName = "sceAgcDcbCopyData", Target = Generation.Gen5, LibraryName = "libSceAgc")] - public static int DcbCopyData(CpuContext ctx) + public static int DcbCopyData(CpuContext ctx) => + CopyData(ctx, rawSelectors: false); + + // The DCB selectors carry the CP engine in bit 0 above the hardware selector; the ACB selectors are the MEC's + // raw hardware values, with no engine. + private static int CopyData(CpuContext ctx, bool rawSelectors) { var commandBufferAddress = ctx[CpuRegister.Rdi]; var destinationSelector = (uint)(ctx[CpuRegister.Rsi] & 0xFF); @@ -36,14 +41,15 @@ public static int DcbCopyData(CpuContext ctx) var elementSize = (uint)(elementSizeRaw & 0xFF); var confirmWrite = (uint)(confirmWriteRaw & 0xFF); + var selectors = rawSelectors + ? (sourceSelector & 0xFu) | ((destinationSelector & 0xFu) << 8) + : ((sourceSelector >> 1) & 0xFu) | (((destinationSelector >> 1) & 0xFu) << 8) | ((sourceSelector & 0x1u) << 30); var control = - ((sourceSelector >> 1) & 0xFu) | - (((destinationSelector >> 1) & 0xFu) << 8) | + selectors | ((sourcePolicy & 0x3u) << 13) | ((elementSize & 0x1u) << 16) | ((confirmWrite & 0x1u) << 20) | - ((destinationPolicy & 0x3u) << 25) | - ((sourceSelector & 0x1u) << 30); + ((destinationPolicy & 0x3u) << 25); if (!TryWriteUInt32(ctx, packetAddress, Pm4(6, ItCopyData, 0)) || !TryWriteUInt32(ctx, packetAddress + 4, control) || @@ -56,12 +62,38 @@ public static int DcbCopyData(CpuContext ctx) } TraceAgc( - $"agc.dcb_copy_data buf=0x{commandBufferAddress:X16} cmd=0x{packetAddress:X16} " + + $"agc.{(rawSelectors ? "acb" : "dcb")}_copy_data buf=0x{commandBufferAddress:X16} cmd=0x{packetAddress:X16} " + $"dstSel=0x{destinationSelector:X2} srcSel=0x{sourceSelector:X2} " + $"dst=0x{destinationAddress:X16} src=0x{sourceValue:X16} control=0x{control:X8}"); return ReturnPointer(ctx, packetAddress); } + // Matches the fixed 6-dword COPY_DATA packet DcbCopyData and AcbCopyData write. + [SysAbiExport( + Nid = "b5u0Jzm8TF8", + ExportName = "sceAgcDcbCopyDataGetSize", + Target = Generation.Gen5, + LibraryName = "libSceAgc")] + [SysAbiExport( + Nid = "CbQh3DKMSno", + ExportName = "sceAgcAcbCopyDataGetSize", + Target = Generation.Gen5, + LibraryName = "libSceAgc")] + public static int CopyDataGetSize(CpuContext ctx) + { + ctx[CpuRegister.Rax] = 6u * sizeof(uint); + return (int)ctx[CpuRegister.Rax]; + } + + // The ACB form takes the same arguments; its selectors are the raw MEC values. + [SysAbiExport( + Nid = "qzMN2XKGA4k", + ExportName = "sceAgcAcbCopyData", + Target = Generation.Gen5, + LibraryName = "libSceAgc")] + public static int AcbCopyData(CpuContext ctx) => + CopyData(ctx, rawSelectors: true); + [SysAbiExport( Nid = "WmAc2MEj6Io", ExportName = "sceAgcDcbDmaData", diff --git a/src/SharpEmu.Libs/Agc/AgcExports.Events.cs b/src/SharpEmu.Libs/Agc/AgcExports.Events.cs index 25ae2b099..3d4814619 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.Events.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.Events.cs @@ -86,6 +86,23 @@ public static int DcbEventWrite(CpuContext ctx) return ReturnPointer(ctx, commandAddress); } + // Matches the packet DcbEventWrite writes: 4 dwords for the two event types that carry an address, 2 for the rest. + [SysAbiExport( + Nid = "C4l9fB17t8w", + ExportName = "sceAgcDcbEventWriteGetSize", + Target = Generation.Gen5, + LibraryName = "libSceAgc")] + public static int DcbEventWriteGetSize(CpuContext ctx) + { + ctx[CpuRegister.Rax] = (uint)(ctx[CpuRegister.Rdi] & 0xFF) switch + { + 0x38 or 0x39 => 4u * sizeof(uint), + <= 0x3F => 2u * sizeof(uint), + _ => 0, + }; + return (int)ctx[CpuRegister.Rax]; + } + [SysAbiExport( Nid = "MWiElSNE8j8", ExportName = "sceAgcDcbWaitUntilSafeForRendering", diff --git a/src/SharpEmu.Libs/Agc/AgcExports.RegisterPackets.cs b/src/SharpEmu.Libs/Agc/AgcExports.RegisterPackets.cs index 661d52880..1d1e7262b 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.RegisterPackets.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.RegisterPackets.cs @@ -375,6 +375,18 @@ public static int DcbSetCfRegisterRangeDirect(CpuContext ctx) => public static int DcbSetCxRegisterDirect(CpuContext ctx) => DcbSetRegisterDirect(ctx, ItSetContextReg, "cx"); + // Matches the 3-dword SET_CONTEXT_REG packet DcbSetCxRegisterDirect writes. + [SysAbiExport( + Nid = "1DeUNpRIDDA", + ExportName = "sceAgcDcbSetCxRegisterDirectGetSize", + Target = Generation.Gen5, + LibraryName = "libSceAgc")] + public static int DcbSetCxRegisterDirectGetSize(CpuContext ctx) + { + ctx[CpuRegister.Rax] = 3u * sizeof(uint); + return (int)ctx[CpuRegister.Rax]; + } + private static int DcbSetRegisterRangeDirect(CpuContext ctx, uint op, string registerSpace) { var commandBufferAddress = ctx[CpuRegister.Rdi]; diff --git a/src/SharpEmu.Libs/Agc/AgcExports.Submissions.cs b/src/SharpEmu.Libs/Agc/AgcExports.Submissions.cs index 73a284eb5..a964b6f86 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.Submissions.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.Submissions.cs @@ -355,6 +355,66 @@ public static int DriverSubmitMultiDcbs(CpuContext ctx) return (int)OrbisGen2Result.ORBIS_GEN2_OK; } + // ABI: EDI is the queue (the owner sceAgcDriverSubmitAcb takes), RSI points to addresses, RDX points to dword + // counts, and ECX contains the count. + [SysAbiExport( + Nid = "HF3YllT3mXU", + ExportName = "sceAgcDriverSubmitMultiAcbs", + Target = Generation.Gen5, + LibraryName = "libSceAgcDriver")] + public static int DriverSubmitMultiAcbs(CpuContext ctx) + { + if (HostSessionControl.IsShutdownRequested) + { + return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_CANCELED); + } + + var ownerHandle = (uint)ctx[CpuRegister.Rdi]; + var addressArray = ctx[CpuRegister.Rsi]; + var sizeArray = ctx[CpuRegister.Rdx]; + var bufferCount = (uint)ctx[CpuRegister.Rcx]; + if (addressArray == 0 || sizeArray == 0 || bufferCount == 0 || bufferCount > 4096) + { + return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT); + } + + (GuestGpu.Current as IGuestImageSnapshotBackend)?.AttachGuestMemory(ctx.Memory); + var gpuState = _submittedGpuStates.GetValue(CanonicalMemory(ctx.Memory), static _ => new SubmittedGpuState()); + lock (gpuState.CommandSubmissionGate) + lock (gpuState.Gate) + { + for (uint bufferIndex = 0; bufferIndex < bufferCount; bufferIndex++) + { + if (!ctx.TryReadUInt64(addressArray + bufferIndex * 8, out var commandAddress) || + commandAddress == 0 || + !ctx.TryReadUInt32(sizeArray + bufferIndex * 4, out var dwordCount) || + dwordCount == 0) + { + continue; + } + + TraceAgc( + $"agc.driver_submit_multi_acbs owner={ownerHandle} index={bufferIndex}/{bufferCount} " + + $"addr=0x{commandAddress:X16} dwords={dwordCount}"); + SubmissionFlowProfile.RecordGuest(SubmissionFlowProfile.EventKind.SubmitEntered, + ownerHandle, 0, commandAddress, dwordCount); + if (!TrySubmitCommandStream( + ctx.Memory, + ownerHandle, + commandAddress, + dwordCount, + ++gpuState.SubmissionSequence, + null)) + { + return SetReturn(ctx, OrbisGen2Result.ORBIS_GEN2_ERROR_CANCELED); + } + } + } + + ctx[CpuRegister.Rax] = 0; + return (int)OrbisGen2Result.ORBIS_GEN2_OK; + } + private static Dictionary? CaptureSubmittedTables(CpuContext ctx, ulong address, ReadOnlySpan commands) { var words = System.Runtime.InteropServices.MemoryMarshal.Cast(commands); diff --git a/src/SharpEmu.Libs/Agc/AgcExports.cs b/src/SharpEmu.Libs/Agc/AgcExports.cs index afc2d9535..5f5b20661 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.cs @@ -585,17 +585,15 @@ scheduler is null || return true; } + // The free space is the dword distance between the cursors truncated to 32 bits, + // less the reserved space. Titles rely on the truncation: an allocator with a null down cursor still has room. private static uint GetRemainingCommandDwords( ulong cursorUp, ulong cursorDown, uint reservedDwords) { - var availableDwords = cursorDown >= cursorUp - ? Math.Min((cursorDown - cursorUp) / sizeof(uint), uint.MaxValue) - : 0; - return availableDwords > reservedDwords - ? (uint)availableDwords - reservedDwords - : 0; + var availableDwords = unchecked((uint)((long)(cursorDown - cursorUp) / sizeof(uint))); + return Math.Max(availableDwords, reservedDwords) - reservedDwords; } private static int ReturnPointer(CpuContext ctx, ulong pointer) diff --git a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs index 71f0a3ae4..f29e11b6a 100644 --- a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs +++ b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs @@ -142,7 +142,17 @@ public bool DefersGpuWriteProtection set => _tracker.DefersGpuWriteProtection = value; } - public void ApplyPendingGpuProtections() => _tracker.ApplyPendingGpuProtections(); + public void ApplyPendingGpuProtections() + { + Volatile.Write(ref _copyWritesPending, 0); + _tracker.ApplyPendingGpuProtections(); + } + + private int _copyWritesPending; + + public bool CopyWritesPending => Volatile.Read(ref _copyWritesPending) != 0; + + public void NoteCopyWrite() => Volatile.Write(ref _copyWritesPending, 1); public GpuBuffer GdsBuffer => _gds; @@ -452,6 +462,7 @@ public void PrepareBufferAllocations(ReadOnlySpan ranges) return null; } + NoteCopyWrite(); return ObtainBuffer(guestAddress, size, isWritten: true).Buffer; } @@ -598,7 +609,12 @@ public void FillBuffer(ulong guestAddress, ulong size, uint value, bool isGds) = private void FillBuffer(ulong guestAddress, ulong size, uint value, bool isGds, bool publishFill) { - if (!isGds) CompleteGuestPublications?.Invoke(guestAddress, size, PublicationAccess.Write); + if (!isGds) + { + CompleteGuestPublications?.Invoke(guestAddress, size, PublicationAccess.Write); + NoteCopyWrite(); + } + if ((guestAddress & 3) != 0 || size == 0 || (size & 3) != 0 || size > ulong.MaxValue - guestAddress) { throw SubmissionScheduler.Fatal("The fill range must be aligned to four bytes."); @@ -849,7 +865,12 @@ public bool TryCopyWordsOnHost(ulong destination, ulong source, ulong sourceWord public void CopyBuffer(ulong dstVaddr, ulong srcVaddr, ulong size, bool dstGds, bool srcGds) { - if (!dstGds) CompleteGuestPublications?.Invoke(dstVaddr, size, PublicationAccess.Write); + if (!dstGds) + { + CompleteGuestPublications?.Invoke(dstVaddr, size, PublicationAccess.Write); + NoteCopyWrite(); + } + if (!srcGds) CompleteGuestPublications?.Invoke(srcVaddr, size, PublicationAccess.Read); var dstMemory = !dstGds; var srcMemory = !srcGds; diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Memory.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Memory.cs index 78240e4f6..5553154a3 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Memory.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Memory.cs @@ -304,6 +304,10 @@ private void CopyDataOnComputeQueue(uint control, ulong source, ulong destinatio case 6: CopyAtomicReturn(destinationSelect, destination, byteCount, usePfp: false); return; + case 9 when dmaDestination == 3: + // Source 9: the GPU reference clock stored to memory (a timestamp). + WriteReferenceClock(destination, byteCount); + return; default: throw _host.Fatal($"The copy-data source selector is not supported: selector=0x{sourceSelect:X2} queue={QueueId}."); } diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.MemoryDetile.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.MemoryDetile.cs index 2b6cac64f..c5ac724df 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.MemoryDetile.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.MemoryDetile.cs @@ -17,6 +17,7 @@ public bool TryDetileMemory(ulong tiledAddress, ulong tiledSize, ulong linearAdd PublishImagesUnderRead(tiledAddress, tiledSize); InvalidateMemoryFromGpu(linearAddress, linearSize); var (source, sourceOffset) = _bufferCache.ObtainBuffer(tiledAddress, tiledSize, isWritten: false, isTexelBuffer: true); + _bufferCache.NoteCopyWrite(); var (target, targetOffset) = _bufferCache.ObtainBuffer(linearAddress, linearSize, isWritten: true, isTexelBuffer: true); _tiler.Detile(source.Handle, sourceOffset, tiledSize, target.Handle, targetOffset, linearSize, transfers); return true; diff --git a/src/SharpEmu.Libs/Kernel/KernelExports.cs b/src/SharpEmu.Libs/Kernel/KernelExports.cs index c1e305434..9ab75576e 100644 --- a/src/SharpEmu.Libs/Kernel/KernelExports.cs +++ b/src/SharpEmu.Libs/Kernel/KernelExports.cs @@ -311,6 +311,7 @@ public static int PthreadExit(CpuContext ctx) { var value = ctx[CpuRegister.Rdi]; // Run cleanup on the still-executable thread before unwinding it. + LibcInternal.LibcInternalExports.RunThreadAtexitDestructors(ctx); KernelPthreadExtendedCompatExports.RunThreadLocalDestructors(ctx); KernelMemoryCompatExports.RunThreadDtors(ctx); GuestThreadExecution.RequestCurrentEntryExit("scePthreadExit", value); @@ -326,6 +327,7 @@ public static int PthreadExit(CpuContext ctx) public static int PosixPthreadExit(CpuContext ctx) { var value = ctx[CpuRegister.Rdi]; + LibcInternal.LibcInternalExports.RunThreadAtexitDestructors(ctx); KernelPthreadExtendedCompatExports.RunThreadLocalDestructors(ctx); KernelMemoryCompatExports.RunThreadDtors(ctx); GuestThreadExecution.RequestCurrentEntryExit("pthread_exit", value); diff --git a/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.cs b/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.cs index 5fc028528..caaf65cc0 100644 --- a/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.cs +++ b/src/SharpEmu.Libs/Kernel/KernelMemoryCompatExports.cs @@ -8008,6 +8008,107 @@ public static int KernelChmod(CpuContext ctx) ctx[CpuRegister.Rax] = 0; return (int)OrbisGen2Result.ORBIS_GEN2_OK; } + + // utimes: times[0] is the access time and times[1] the modification time, each a timeval of seconds and + // microseconds; a null array sets both to the current time. + [SysAbiExport( + Nid = "0Cq8ipKr9n0", + ExportName = "sceKernelUtimes", + Target = Generation.Gen4 | Generation.Gen5, + LibraryName = "libKernel")] + public static int KernelUtimes(CpuContext ctx) + { + var pathAddress = ctx[CpuRegister.Rdi]; + var timesAddress = ctx[CpuRegister.Rsi]; + if (pathAddress == 0) + { + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT; + } + + if (!TryReadNullTerminatedUtf8(ctx, pathAddress, MaxGuestStringLength, out var guestPath)) + { + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT; + } + + var hostPath = ResolveGuestPath(guestPath); + if (IsReadOnlyGuestMutationPath(guestPath)) + { + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_PERMISSION_DENIED; + } + + var isFile = File.Exists(hostPath); + if (!isFile && !Directory.Exists(hostPath)) + { + AddNegativeStatCacheForGuestPath(guestPath); + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND; + } + + DateTime accessed; + DateTime modified; + if (timesAddress == 0) + { + accessed = modified = DateTime.UtcNow; + } + else if (!TryReadTimeval(ctx, timesAddress, out accessed, out var accessValid) || + !TryReadTimeval(ctx, timesAddress + 16, out modified, out var modifiedValid)) + { + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT; + } + else if (!accessValid || !modifiedValid) + { + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT; + } + + try + { + if (isFile) + { + File.SetLastAccessTimeUtc(hostPath, accessed); + File.SetLastWriteTimeUtc(hostPath, modified); + } + else + { + Directory.SetLastAccessTimeUtc(hostPath, accessed); + Directory.SetLastWriteTimeUtc(hostPath, modified); + } + } + catch (ArgumentOutOfRangeException) + { + // Host file times start in 1601. + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + LogOpenTrace($"utimes failed path='{guestPath}' host='{hostPath}' error={exception.Message}"); + return (int)OrbisGen2Result.ORBIS_GEN2_ERROR_PERMISSION_DENIED; + } + + LogOpenTrace($"utimes path='{guestPath}' host='{hostPath}' accessed={accessed:O} modified={modified:O}"); + ctx[CpuRegister.Rax] = 0; + return (int)OrbisGen2Result.ORBIS_GEN2_OK; + + static bool TryReadTimeval(CpuContext ctx, ulong address, out DateTime time, out bool valid) + { + time = default; + valid = false; + if (!ctx.TryReadUInt64(address, out var seconds) || !ctx.TryReadUInt64(address + 8, out var microseconds)) + { + return false; + } + + var secondsValue = unchecked((long)seconds); + var microsecondsValue = unchecked((long)microseconds); + valid = microsecondsValue is >= 0 and < 1_000_000 && + secondsValue >= DateTimeOffset.MinValue.ToUnixTimeSeconds() && + secondsValue < DateTimeOffset.MaxValue.ToUnixTimeSeconds(); + if (valid) + { + time = DateTimeOffset.FromUnixTimeSeconds(secondsValue).AddTicks(microsecondsValue * 10).UtcDateTime; + } + + return true; + } + } private static bool TryCompareStringsCaseInsensitive( CpuContext ctx, ulong left, diff --git a/src/SharpEmu.Libs/LibcInternalExports.cs b/src/SharpEmu.Libs/LibcInternalExports.cs index ab6ca0da3..9fa04d419 100644 --- a/src/SharpEmu.Libs/LibcInternalExports.cs +++ b/src/SharpEmu.Libs/LibcInternalExports.cs @@ -17,6 +17,46 @@ public static class LibcInternalExports private static readonly object _heapTraceGate = new(); private static nint _heapTraceStorage; + // C++ thread_local destructors the guest's libc registered on this thread; they run, newest first, when it exits. + [ThreadStatic] + private static List<(ulong Destructor, ulong Object)>? _threadAtexitDestructors; + + // The guest's libc registers a destructor for each thread_local object here: (destructor, object, DSO handle). + [SysAbiExport( + Nid = "qBS714-Jr3g", + ExportName = "_sceLibcInternalThreadAtexit", + Target = Generation.Gen5, + LibraryName = "LibcInternalExt")] + public static int LibcInternalThreadAtexit(CpuContext ctx) + { + var destructor = ctx[CpuRegister.Rdi]; + if (destructor != 0) + { + (_threadAtexitDestructors ??= []).Add((destructor, ctx[CpuRegister.Rsi])); + } + + ctx[CpuRegister.Rax] = 0; + return (int)OrbisGen2Result.ORBIS_GEN2_OK; + } + + // Runs on the exiting guest thread before its pthread key destructors. A destructor can register another one, + // which runs in the same pass. + public static void RunThreadAtexitDestructors(CpuContext ctx) + { + var destructors = _threadAtexitDestructors; + if (destructors is null || GuestThreadExecution.Scheduler is not { } scheduler) + { + return; + } + + while (destructors.Count != 0) + { + var (destructor, obj) = destructors[^1]; + destructors.RemoveAt(destructors.Count - 1); + _ = scheduler.TryCallGuestFunction(ctx, destructor, obj, 0, 0, 0, "thread_atexit_destructor", out _); + } + } + [SysAbiExport( Nid = "NWtTN10cJzE", ExportName = "sceLibcHeapGetTraceInfo", diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs index fd62b35cd..e2172cd8b 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CommandThread.cs @@ -1072,6 +1072,9 @@ private void Execute(Item item) break; case Kind.Write: _presenter._bufferCache.NoteObservation(); + // The store can be an end-of-pipe label that tells the guest earlier GPU writes are done. Their + // pages must block CPU reads before it lands, not only at the next submission. + if (_presenter._bufferCache.CopyWritesPending) _presenter._bufferCache.ApplyPendingGpuProtections(); ApplyWrite(item); break; } diff --git a/tests/SharpEmu.Libs.Tests/Agc/AgcCommandBufferChainTests.cs b/tests/SharpEmu.Libs.Tests/Agc/AgcCommandBufferChainTests.cs index f240568e3..f3b87f954 100644 --- a/tests/SharpEmu.Libs.Tests/Agc/AgcCommandBufferChainTests.cs +++ b/tests/SharpEmu.Libs.Tests/Agc/AgcCommandBufferChainTests.cs @@ -126,21 +126,45 @@ public void DcbJump_EncodesModeCachePolicyAndSize() Assert.Equal(0x2F20_0123u, ReadUInt32(memory, FirstLinkAddress + 12)); } + // The free space truncates the cursor distance to 32 bits, so an allocator + // whose down cursor is null still has room. Unreal Engine writes its jumps and submission prologues through one. [Fact] - public void AcbJump_AlwaysEncodesChainMode() + public void DcbJump_WritesThroughAnAllocatorWithANullDownCursor() + { + var memory = new FakeCpuMemory(BaseAddress, MemorySize); + var ctx = new CpuContext(memory, Generation.Gen5); + + WriteUInt64(memory, CommandBufferAddress + 0x10, FirstLinkAddress); + WriteUInt64(memory, CommandBufferAddress + 0x18, 0); + ctx[CpuRegister.Rdi] = CommandBufferAddress; + ctx[CpuRegister.Rsi] = 1; // chain + ctx[CpuRegister.Rdx] = 0; + ctx[CpuRegister.Rcx] = SecondLinkAddress; + ctx[CpuRegister.R8] = 0x40; + + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, AgcExports.DcbJump(ctx)); + Assert.Equal(FirstLinkAddress, ctx[CpuRegister.Rax]); + Assert.Equal(FirstLinkAddress + 16, ReadUInt64(memory, CommandBufferAddress + 0x10)); + } + + [Theory] + [InlineData(0u, 0x0F30_0123u)] + [InlineData(2u, 0x2F30_0123u)] + public void AcbJump_EncodesCachePolicyAndSizeAndAlwaysChains(uint cachePolicy, uint control) { var memory = new FakeCpuMemory(BaseAddress, MemorySize); var ctx = new CpuContext(memory, Generation.Gen5); PointCommandBufferAt(memory, FirstLinkAddress); ctx[CpuRegister.Rdi] = CommandBufferAddress; - ctx[CpuRegister.Rsi] = SecondLinkAddress; - ctx[CpuRegister.Rdx] = 0x123; + ctx[CpuRegister.Rsi] = cachePolicy; + ctx[CpuRegister.Rdx] = SecondLinkAddress; + ctx[CpuRegister.Rcx] = 0x123; Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, AgcExports.AcbJump(ctx)); Assert.Equal(FirstLinkAddress, ctx[CpuRegister.Rax]); Assert.Equal(unchecked((uint)SecondLinkAddress), ReadUInt32(memory, FirstLinkAddress + 4)); - Assert.Equal(0x0F30_0123u, ReadUInt32(memory, FirstLinkAddress + 12)); + Assert.Equal(control, ReadUInt32(memory, FirstLinkAddress + 12)); } [Fact] diff --git a/tests/SharpEmu.Libs.Tests/Agc/AgcCopyDataRuntimeTests.cs b/tests/SharpEmu.Libs.Tests/Agc/AgcCopyDataRuntimeTests.cs index 6caf26b95..a4a3d7010 100644 --- a/tests/SharpEmu.Libs.Tests/Agc/AgcCopyDataRuntimeTests.cs +++ b/tests/SharpEmu.Libs.Tests/Agc/AgcCopyDataRuntimeTests.cs @@ -59,6 +59,35 @@ public void ImmediateCopy_ReleasesWaitingGraphicsSubmission() Assert.False(stream.Queue.HasPending); } + [Fact] + public void MultiAcbSubmit_RunsEachBufferOnTheOwnersComputeQueue() + { + var memory = new FakeCpuMemory(BaseAddress, MemorySize); + var ctx = new CpuContext(memory, Generation.Gen5); + const uint expected = 0x1122_3344; + var graphicsDwords = WriteWaitThenResult(memory, LabelAddress, expected); + var stream = AgcExports.GetHeadlessCommandStreamForTests(memory); + SubmitDcb(ctx, memory, GraphicsCommandAddress, graphicsDwords); + Assert.Equal(1, stream.Queue.BlockedQueueCount); + + WriteCopyData(memory, ComputeCommandAddress, control: 5u | (2u << 8), source: 0x55, destination: SecondResultAddress); + WriteCopyData(memory, LaterComputeCommandAddress, control: 5u | (2u << 8), source: expected, destination: LabelAddress); + WriteUInt64(memory, ComputeSubmitAddress, ComputeCommandAddress); + WriteUInt64(memory, ComputeSubmitAddress + 8, LaterComputeCommandAddress); + WriteUInt32(memory, ComputeSubmitAddress + 16, 6); + WriteUInt32(memory, ComputeSubmitAddress + 20, 6); + ctx[CpuRegister.Rdi] = FirstComputeOwner; + ctx[CpuRegister.Rsi] = ComputeSubmitAddress; + ctx[CpuRegister.Rdx] = ComputeSubmitAddress + 16; + ctx[CpuRegister.Rcx] = 2; + + Assert.Equal(0, AgcExports.DriverSubmitMultiAcbs(ctx)); + Assert.Equal(0x55u, ReadUInt32(memory, SecondResultAddress)); + Assert.Equal(expected, ReadUInt32(memory, LabelAddress)); + Assert.Equal(0xCAFE_BABEu, ReadUInt32(memory, ResultAddress)); + Assert.False(stream.Queue.HasPending); + } + [Fact] public void MemoryCopy_ReadsAndWritesGuestMemoryInQueueOrder() { diff --git a/tests/SharpEmu.Libs.Tests/Agc/AgcEventWriteTests.cs b/tests/SharpEmu.Libs.Tests/Agc/AgcEventWriteTests.cs index 22b4453bc..5191ae282 100644 --- a/tests/SharpEmu.Libs.Tests/Agc/AgcEventWriteTests.cs +++ b/tests/SharpEmu.Libs.Tests/Agc/AgcEventWriteTests.cs @@ -87,6 +87,34 @@ public void AddressedEvent_RequiresSpaceForTheAddressWords() Assert.Equal(0xDEADBEEFu, host.ReadDword(PacketAddress)); } + // A title reserves room with sceAgcDcbEventWriteGetSize before it writes the event; the two must agree. + [Theory] + [InlineData(0x38u)] + [InlineData(0x39u)] + [InlineData(0x07u)] + [InlineData(0x3Au)] + public void GetSize_ReportsTheBytesTheWriterTakes(uint eventType) + { + var host = CreateHost(out var context); + context[CpuRegister.Rdi] = eventType; + var size = AgcExports.DcbEventWriteGetSize(context); + context[CpuRegister.Rdi] = CommandBufferAddress; + context[CpuRegister.Rsi] = eventType; + context[CpuRegister.Rdx] = ResultAddress; + + Assert.Equal(0, AgcExports.DcbEventWrite(context)); + Assert.Equal(PacketAddress + (ulong)size, host.ReadQword(CommandBufferAddress + 0x10)); + } + + [Fact] + public void GetSize_IsZeroForAnInvalidEvent() + { + CreateHost(out var context); + context[CpuRegister.Rdi] = 0x40; + + Assert.Equal(0, AgcExports.DcbEventWriteGetSize(context)); + } + [Fact] public void InvalidEvent_DoesNotAllocateAPacket() { diff --git a/tests/SharpEmu.Libs.Tests/Agc/AgcSetShRegisterRangeTests.cs b/tests/SharpEmu.Libs.Tests/Agc/AgcSetShRegisterRangeTests.cs index 417452d02..ffdc0e531 100644 --- a/tests/SharpEmu.Libs.Tests/Agc/AgcSetShRegisterRangeTests.cs +++ b/tests/SharpEmu.Libs.Tests/Agc/AgcSetShRegisterRangeTests.cs @@ -72,6 +72,25 @@ public void GetSize_EqualsBytesConsumedByEmitter() Assert.Equal(0x5566_7788u, ReadUInt32(memory, PacketAddress + 20)); } + [Fact] + public void CxRegisterDirectGetSize_EqualsBytesConsumedByEmitter() + { + var memory = new FakeCpuMemory(BaseAddress, 0x1000); + var ctx = new CpuContext(memory, Generation.Gen5); + WriteUInt64(memory, CommandBufferAddress + 0x10, PacketAddress); + WriteUInt64(memory, CommandBufferAddress + 0x18, PacketAddress + 0x100); + + var size = AgcExports.DcbSetCxRegisterDirectGetSize(ctx); + ctx[CpuRegister.Rdi] = CommandBufferAddress; + ctx[CpuRegister.Rsi] = (0x1122_3344UL << 32) | 0x0201; + + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, AgcExports.DcbSetCxRegisterDirect(ctx)); + Assert.Equal(PacketAddress, ctx[CpuRegister.Rax]); + Assert.Equal(PacketAddress + (ulong)size, ReadUInt64(memory, CommandBufferAddress + 0x10)); + Assert.Equal(0x0201u, ReadUInt32(memory, PacketAddress + 4)); + Assert.Equal(0x1122_3344u, ReadUInt32(memory, PacketAddress + 8)); + } + [Theory] [InlineData(1u)] [InlineData(64u)] diff --git a/tests/SharpEmu.Libs.Tests/Agc/AgcSubmissionShutdownTests.cs b/tests/SharpEmu.Libs.Tests/Agc/AgcSubmissionShutdownTests.cs index 90eb6df00..1d7d34781 100644 --- a/tests/SharpEmu.Libs.Tests/Agc/AgcSubmissionShutdownTests.cs +++ b/tests/SharpEmu.Libs.Tests/Agc/AgcSubmissionShutdownTests.cs @@ -25,6 +25,7 @@ public void Shutdown_RejectsGuestSubmissionsWithoutReadingPackets() Assert.Equal(cancelled, AgcExports.DriverSubmitDcb(context)); Assert.Equal(cancelled, AgcExports.DriverSubmitAcb(context)); Assert.Equal(cancelled, AgcExports.DriverSubmitMultiDcbs(context)); + Assert.Equal(cancelled, AgcExports.DriverSubmitMultiAcbs(context)); } finally { diff --git a/tests/SharpEmu.Libs.Tests/Agc/AgcWaitRegMemTests.cs b/tests/SharpEmu.Libs.Tests/Agc/AgcWaitRegMemTests.cs index a496399b9..86e864a99 100644 --- a/tests/SharpEmu.Libs.Tests/Agc/AgcWaitRegMemTests.cs +++ b/tests/SharpEmu.Libs.Tests/Agc/AgcWaitRegMemTests.cs @@ -168,7 +168,8 @@ public void DcbWaitRegMem32_EmitsGen5PacketLayout() Assert.Equal(0x5566_7788u, ReadUInt32(memory, PacketAddress + 16)); Assert.Equal(0x0400_0053u, ReadUInt32(memory, PacketAddress + 20)); Assert.Equal(0xFFFFu, ReadUInt32(memory, PacketAddress + 24)); - Assert.Equal(PacketAddress + 28, ReadUInt64(memory, CommandBufferAddress + 0x10)); + Assert.Equal(0xC005_1000u, ReadUInt32(memory, PacketAddress + 28)); + Assert.Equal(PacketAddress + 56, ReadUInt64(memory, CommandBufferAddress + 0x10)); } [Fact] @@ -197,6 +198,55 @@ public void DcbWaitRegMem64_EmitsGen5PacketLayout() Assert.Equal(0x1122_3344u, ReadUInt32(memory, PacketAddress + 24)); Assert.Equal(0x0200_0096u, ReadUInt32(memory, PacketAddress + 28)); Assert.Equal(0x32u, ReadUInt32(memory, PacketAddress + 32)); + Assert.Equal(0xC005_1000u, ReadUInt32(memory, PacketAddress + 36)); + Assert.Equal(PacketAddress + 64, ReadUInt64(memory, CommandBufferAddress + 0x10)); + } + + // Titles size a buffer with the size export and then fill it with waits (UE's submission prologue), so a wait + // must take exactly the size its export reports. + [Theory] + [InlineData(0u)] + [InlineData(1u)] + public void DcbWaitRegMem_TakesTheSizeItsSizeExportReports(uint labelSize) + { + var memory = CreateMemory(out var ctx); + ctx[CpuRegister.Rdi] = labelSize; + var reportedBytes = (ulong)AgcExports.GetWaitOnAddressSize(ctx); + ctx[CpuRegister.Rdi] = CommandBufferAddress; + ctx[CpuRegister.Rsi] = labelSize; + ctx[CpuRegister.Rdx] = 3; + ctx[CpuRegister.Rcx] = 0; + ctx[CpuRegister.R8] = 2; + ctx[CpuRegister.R9] = BaseAddress + 0xC00; + WriteUInt64(memory, StackAddress + 8, 1); + WriteUInt64(memory, StackAddress + 16, ulong.MaxValue); + WriteUInt32(memory, StackAddress + 24, 400); + + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, AgcExports.DcbWaitRegMem(ctx)); + Assert.Equal(PacketAddress, ctx[CpuRegister.Rax]); + Assert.Equal(PacketAddress + reportedBytes, ReadUInt64(memory, CommandBufferAddress + 0x10)); + } + + [Theory] + [InlineData(0u)] + [InlineData(1u)] + public void AcbWaitRegMem_TakesTheSizeItsSizeExportReports(uint labelSize) + { + var memory = CreateMemory(out var ctx); + ctx[CpuRegister.Rdi] = labelSize; + var reportedBytes = (ulong)AgcExports.AcbWaitOnAddressGetSize(ctx); + ctx[CpuRegister.Rdi] = CommandBufferAddress; + ctx[CpuRegister.Rsi] = labelSize; + ctx[CpuRegister.Rdx] = 3; + ctx[CpuRegister.Rcx] = 2; + ctx[CpuRegister.R8] = BaseAddress + 0xC00; + ctx[CpuRegister.R9] = 1; + WriteUInt64(memory, StackAddress + 8, ulong.MaxValue); + WriteUInt32(memory, StackAddress + 16, 400); + + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, AgcExports.AcbWaitRegMem(ctx)); + Assert.Equal(PacketAddress, ctx[CpuRegister.Rax]); + Assert.Equal(PacketAddress + reportedBytes, ReadUInt64(memory, CommandBufferAddress + 0x10)); } [Theory] diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/GpuCommandInterpreterMemoryTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/GpuCommandInterpreterMemoryTests.cs index 0cc3c827b..d69482d2b 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/GpuCommandInterpreterMemoryTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/GpuCommandInterpreterMemoryTests.cs @@ -5,6 +5,7 @@ using SharpEmu.Libs.Agc; using SharpEmu.Libs.Gpu.GpuCommands; using SharpEmu.Libs.Gpu.Images; +using SharpEmu.Libs.Gpu.Scheduling; using Xunit; namespace SharpEmu.Libs.Tests.Gpu.GpuCommands; @@ -194,6 +195,42 @@ public void CopyDataBuilder_EncodesGuestArguments() Assert.Equal(immediateValue, runner.Host.ReadQword(Label)); } + // The ACB selectors are the MEC's raw values: source 9 is the reference clock and destination 2 is memory through the L2, with no engine bit. + [Fact] + public void AcbCopyData_WritesRawSelectorsAndTheComputeQueueStoresTheClock() + { + var runner = new StreamRunner(queueId: 1); + var context = new CpuContext(runner.Host.Memory, Generation.Gen5); + const ulong commandBufferAddress = StreamRunner.TableAddress; + const ulong stackAddress = StreamRunner.TableAddress + 0x100; + runner.Host.WriteQword(commandBufferAddress + 0x10, StreamRunner.CommandAddress); + runner.Host.WriteQword(commandBufferAddress + 0x18, StreamRunner.CommandAddress + 0x100); + context[CpuRegister.Rdi] = commandBufferAddress; + context[CpuRegister.Rsi] = 2; + context[CpuRegister.Rdx] = 3; + context[CpuRegister.Rcx] = Label; + context[CpuRegister.R8] = 9; + context[CpuRegister.R9] = 3; + context[CpuRegister.Rsp] = stackAddress; + runner.Host.WriteQword(stackAddress + 8, 0); + runner.Host.WriteQword(stackAddress + 16, 1); + runner.Host.WriteQword(stackAddress + 24, 1); + + AgcExports.AcbCopyData(context); + + var control = runner.Host.ReadDword(StreamRunner.CommandAddress + 4); + Assert.Equal(9u, control & 0xFu); + Assert.Equal(2u, (control >> 8) & 0xFu); + Assert.Equal(0u, control >> 30); + Assert.Equal( + StreamRunner.CommandAddress + (ulong)AgcExports.CopyDataGetSize(context), + runner.Host.ReadQword(commandBufferAddress + 0x10)); + + var before = EndOfPipe.ReadReferenceClock(); + runner.Interpreter.Process(new PacketCursorStack(), StreamRunner.CommandAddress, 6); + Assert.InRange(runner.Host.ReadQword(Label), before, EndOfPipe.ReadReferenceClock()); + } + [Fact] public void CopyData_MapsSelectorsToTransfers() { diff --git a/tests/SharpEmu.Libs.Tests/Kernel/KernelUtimesTests.cs b/tests/SharpEmu.Libs.Tests/Kernel/KernelUtimesTests.cs new file mode 100644 index 000000000..e1dd3244b --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Kernel/KernelUtimesTests.cs @@ -0,0 +1,67 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; + +using SharpEmu.HLE; +using SharpEmu.Libs.Kernel; + +using Xunit; + +namespace SharpEmu.Libs.Tests.Kernel; + +[Collection(KernelMemoryCompatStateCollection.Name)] +public sealed class KernelUtimesTests +{ + private const ulong MemoryBase = 0x1_0000_0000; + private const ulong PathAddress = MemoryBase + 0x100; + private const ulong TimesAddress = MemoryBase + 0x400; + + // times[0] is the access time and times[1] the modification time, each seconds and microseconds. + [Fact] + public void KernelUtimes_SetsTheAccessAndModificationTimes() + { + var identity = Guid.NewGuid().ToString("N"); + var mountPoint = $"/utimes-{identity}"; + var hostRoot = Path.Combine(Path.GetTempPath(), $"sharpemu-utimes-{identity}"); + var hostPath = Path.Combine(hostRoot, "SAVE.DAT"); + Directory.CreateDirectory(hostRoot); + File.WriteAllBytes(hostPath, [1]); + KernelMemoryCompatExports.RegisterGuestPathMount(mountPoint, hostRoot); + var memory = new FakeCpuMemory(MemoryBase, 0x1000); + var context = new CpuContext(memory, Generation.Gen5); + try + { + memory.WriteCString(PathAddress, $"{mountPoint}/SAVE.DAT"); + WriteTimeval(memory, TimesAddress, 1_600_000_000, 250_000); + WriteTimeval(memory, TimesAddress + 16, 1_700_000_000, 500_000); + context[CpuRegister.Rdi] = PathAddress; + context[CpuRegister.Rsi] = TimesAddress; + + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, KernelMemoryCompatExports.KernelUtimes(context)); + Assert.Equal(DateTimeOffset.FromUnixTimeSeconds(1_600_000_000).AddMilliseconds(250).UtcDateTime, + File.GetLastAccessTimeUtc(hostPath)); + Assert.Equal(DateTimeOffset.FromUnixTimeSeconds(1_700_000_000).AddMilliseconds(500).UtcDateTime, + File.GetLastWriteTimeUtc(hostPath)); + + WriteTimeval(memory, TimesAddress, 1_600_000_000, 1_000_000); + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_ERROR_INVALID_ARGUMENT, KernelMemoryCompatExports.KernelUtimes(context)); + + memory.WriteCString(PathAddress, $"{mountPoint}/MISSING.DAT"); + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_ERROR_NOT_FOUND, KernelMemoryCompatExports.KernelUtimes(context)); + } + finally + { + _ = KernelMemoryCompatExports.UnregisterGuestPathMount(mountPoint); + Directory.Delete(hostRoot, recursive: true); + } + } + + private static void WriteTimeval(FakeCpuMemory memory, ulong address, long seconds, long microseconds) + { + Span bytes = stackalloc byte[16]; + BinaryPrimitives.WriteInt64LittleEndian(bytes, seconds); + BinaryPrimitives.WriteInt64LittleEndian(bytes[8..], microseconds); + Assert.True(memory.TryWrite(address, bytes)); + } +} diff --git a/tests/SharpEmu.Libs.Tests/LibcInternal/LibcInternalThreadAtexitTests.cs b/tests/SharpEmu.Libs.Tests/LibcInternal/LibcInternalThreadAtexitTests.cs new file mode 100644 index 000000000..7c7348de0 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/LibcInternal/LibcInternalThreadAtexitTests.cs @@ -0,0 +1,95 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using SharpEmu.Libs.LibcInternal; + +using Xunit; + +namespace SharpEmu.Libs.Tests.LibcInternal; + +// The scheduler is process-wide state. +[Collection("GuestThreadFlowProfile")] +public sealed class LibcInternalThreadAtexitTests +{ + private const ulong Base = 0x3_0000_0000; + + // The guest's libc registers a destructor for each thread_local object. The exiting thread runs them newest + // first, and a destructor registered while they run runs in the same pass. + [Fact] + public void ThreadAtexit_RunsDestructorsNewestFirstWhenTheThreadExits() + { + var context = new CpuContext(new FakeCpuMemory(Base, 0x1000), Generation.Gen5); + var scheduler = new RecordingScheduler(); + var previousScheduler = GuestThreadExecution.Scheduler; + try + { + GuestThreadExecution.Scheduler = scheduler; + Register(context, 0x1000, 0xA); + Register(context, 0x2000, 0xB); + scheduler.OnCall = entryPoint => + { + if (entryPoint == 0x2000) + { + Register(context, 0x3000, 0xC); + } + }; + + LibcInternalExports.RunThreadAtexitDestructors(context); + Assert.Equal([(0x2000UL, 0xBUL), (0x3000UL, 0xCUL), (0x1000UL, 0xAUL)], scheduler.Calls); + + scheduler.Calls.Clear(); + LibcInternalExports.RunThreadAtexitDestructors(context); + Assert.Empty(scheduler.Calls); + } + finally + { + GuestThreadExecution.Scheduler = previousScheduler; + } + } + + private static void Register(CpuContext context, ulong destructor, ulong obj) + { + context[CpuRegister.Rdi] = destructor; + context[CpuRegister.Rsi] = obj; + context[CpuRegister.Rdx] = Base; + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, LibcInternalExports.LibcInternalThreadAtexit(context)); + Assert.Equal(0UL, context[CpuRegister.Rax]); + } + + private sealed class RecordingScheduler : IGuestThreadScheduler + { + public List<(ulong EntryPoint, ulong Argument)> Calls { get; } = []; + public Action? OnCall { get; set; } + public bool SupportsGuestContextTransfer => false; + + public bool TryCallGuestFunction(CpuContext callerContext, ulong entryPoint, ulong firstArgument, ulong secondArgument, + ulong stackAddress, ulong stackSize, string reason, out string? error) + { + Calls.Add((entryPoint, firstArgument)); + OnCall?.Invoke(entryPoint); + error = null; + return true; + } + + public void RegisterGuestThreadContext(ulong threadHandle, CpuContext context) => throw new NotSupportedException(); + public bool TryStartThread(CpuContext creatorContext, GuestThreadStartRequest request, out string? error) => throw new NotSupportedException(); + public bool TryJoinThread(CpuContext callerContext, ulong threadHandle, out ulong returnValue, out string? error) => throw new NotSupportedException(); + public void Pump(CpuContext callerContext, string reason) => throw new NotSupportedException(); + public int WakeBlockedThreads(string wakeKey, int maxCount = int.MaxValue) => throw new NotSupportedException(); + public bool HasPendingGuestExceptionForCurrentThread() => false; + public bool TrySetGuestThreadPriority(ulong guestThreadHandle, int guestPriority) => throw new NotSupportedException(); + public bool TrySetGuestThreadAffinity(ulong guestThreadHandle, ulong affinityMask) => throw new NotSupportedException(); + public IReadOnlyList SnapshotThreads() => throw new NotSupportedException(); + public bool TryCallGuestFunction(CpuContext callerContext, ulong entryPoint, ulong firstArgument, ulong secondArgument, + ulong thirdArgument, ulong stackAddress, ulong stackSize, string reason, out ulong returnValue, out string? error) => + throw new NotSupportedException(); + public bool TryCallGuestFunction(CpuContext callerContext, ulong entryPoint, ulong firstArgument, ulong secondArgument, + ulong thirdArgument, ulong fourthArgument, ulong stackAddress, ulong stackSize, string reason, + out ulong returnValue, out string? error) => throw new NotSupportedException(); + public bool TryCallGuestContinuation(CpuContext callerContext, GuestCpuContinuation continuation, string reason, + out string? error) => throw new NotSupportedException(); + public bool TryRaiseGuestException(CpuContext callerContext, ulong threadHandle, ulong handler, int exceptionType, + out string? error) => throw new NotSupportedException(); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Loader/GuestRedZonePatcherTests.cs b/tests/SharpEmu.Libs.Tests/Loader/GuestRedZonePatcherTests.cs index 34ed7e8f6..ef25076ec 100644 --- a/tests/SharpEmu.Libs.Tests/Loader/GuestRedZonePatcherTests.cs +++ b/tests/SharpEmu.Libs.Tests/Loader/GuestRedZonePatcherTests.cs @@ -30,6 +30,7 @@ public sealed class GuestRedZonePatcherTests [InlineData("554889E574044883EC20488B45F8C3", false)] [InlineData("554889E54883EC0875FA488B45F8C3", false)] [InlineData("554889E5FFE0488B45F8C3", false)] + [InlineData("554889E55353535353488945D0FFE0C3", true)] [InlineData("554889E5488D45F8C3", false)] [InlineData("554889E5904883EC40488B45F8C3", false)] [InlineData("554889E55353535353488945D0C3", true)] @@ -420,6 +421,87 @@ public void KeepsRefusingASwitchWhoseSetupChangesTheSelector() } } + // A switch inside a loop loads its table address once, before the loop. Each case's short store borrows the jump + // that follows it, which needs the table's targets: the base is the one LEA that reaches the table load. + [Fact] + public unsafe void PatchesShortAccessesInASwitchWhoseTableAddressIsLoadedBeforeTheLoop() + { + if (RuntimeInformation.ProcessArchitecture != Architecture.X64) + return; + + var function = BuildLoopSwitchFunction(clobberBase: false); + using var image = PatchedImage.Create(function.Code, [(0x2100, 0x0302_0100u), (0x2200, 0u)], (SwitchTableOffset, function.Table)); + if (!OperatingSystem.IsWindows()) + return; + + Assert.Equal(1, image.Result.RedZoneFunctions); + Assert.Equal(0, image.Result.UnrelocatableSites); + Assert.Equal(0, image.Result.FailedSites); + Assert.Equal(6, image.Result.PatchedSites); + var call = (delegate* unmanaged)image.Base; + Assert.Equal(image.Base + 0x2100, call(image.Base + 0x2100, image.Base + 0x2200)); + Assert.Equal(15u, image.ReadUInt32(0x2200)); + } + + // A case that writes the base register gives the load a second definition, so the table stays unresolved. + [Fact] + public void KeepsRefusingALoopSwitchWhoseCaseWritesTheTableRegister() + { + if (RuntimeInformation.ProcessArchitecture != Architecture.X64) + return; + + var function = BuildLoopSwitchFunction(clobberBase: true); + using var image = PatchedImage.Create(function.Code, [(0x2100, 0x0302_0100u), (0x2200, 0u)], (SwitchTableOffset, function.Table)); + if (OperatingSystem.IsWindows()) + { + Assert.Equal(1, image.Result.PatchedSites); + Assert.Equal(4, image.Result.IndirectBranchRefusals); + } + } + + // for (i = 0; i < 4; i++) switch (sel[i]) { case n: *acc += 1 << n; } with the table address in r9 from before the loop; + // returns sel. Windows argument registers; with 'clobberBase' the last case writes r9 instead of its store. + private static (byte[] Code, byte[] Table) BuildLoopSwitchFunction(bool clobberBase) + { + byte[] code = + [ + 0x48, 0x89, 0x4C, 0x24, 0xF8, // 0x00 mov [rsp-8], rcx + 0x4C, 0x8D, 0x0D, 0, 0, 0, 0, // 0x05 lea r9, [rip + table] + 0x45, 0x31, 0xC0, // 0x0C xor r8d, r8d + 0x42, 0x0F, 0xB6, 0x04, 0x01, // 0x0F loop: movzx eax, byte [rcx + r8] + 0x48, 0x83, 0xF8, 0x03, // 0x14 cmp rax, 3 + 0x77, 0x1D, // 0x18 ja next + 0x49, 0x63, 0x04, 0x81, // 0x1A movsxd rax, dword [r9 + rax*4] + 0x4C, 0x01, 0xC8, // 0x1E add rax, r9 + 0xFF, 0xE0, // 0x21 jmp rax + 0x83, 0x02, 0x01, 0xEB, 0x0F, // 0x23 add dword [rdx], 1; jmp next + 0x83, 0x02, 0x02, 0xEB, 0x0A, // 0x28 add dword [rdx], 2; jmp next + 0x83, 0x02, 0x04, 0xEB, 0x05, // 0x2D add dword [rdx], 4; jmp next + 0x83, 0x02, 0x08, 0xEB, 0x00, // 0x32 add dword [rdx], 8; jmp next + 0x49, 0xFF, 0xC0, // 0x37 next: inc r8 + 0x49, 0x83, 0xF8, 0x04, // 0x3A cmp r8, 4 + 0x72, 0xCF, // 0x3E jb loop + 0x48, 0x8B, 0x44, 0x24, 0xF8, // 0x40 mov rax, [rsp-8] + 0xC3, // 0x45 ret + ]; + if (clobberBase) + { + code[0x32] = 0x4D; // 0x32 mov r9, r8 replaces the last case's store + code[0x33] = 0x89; + code[0x34] = 0xC1; + } + + BinaryPrimitives.WriteInt32LittleEndian(code.AsSpan(0x05 + 3), SwitchTableOffset - (0x05 + 7)); + var table = new byte[4 * sizeof(int)]; + int[] cases = [0x23, 0x28, 0x2D, 0x32]; + for (var index = 0; index < cases.Length; index++) + { + BinaryPrimitives.WriteInt32LittleEndian(table.AsSpan(index * sizeof(int)), cases[index] - SwitchTableOffset); + } + + return (code, table); + } + private const int SwitchTableOffset = 0x2000; // switch (ecx) { case 0..3: return *rdx + ecx + 1; default: return 0; } as a jump table, for the Windows argument registers. diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/CommandStreamStoreProtectionTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/CommandStreamStoreProtectionTests.cs new file mode 100644 index 000000000..66db3cbad --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/CommandStreamStoreProtectionTests.cs @@ -0,0 +1,81 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections; +using System.Reflection; +using SharpEmu.HLE; +using SharpEmu.HLE.Host; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.Libs.Tests.Gpu.Vulkan; +using SharpEmu.Libs.VideoOut; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +[Collection(SchedulingStateCollection.Name)] +public sealed class CommandStreamStoreProtectionTests : IClassFixture +{ + private static readonly Type CommandThreadType = typeof(VulkanVideoPresenter).GetNestedType("CommandThread", BindingFlags.NonPublic)!; + private readonly HeadlessVulkan? _vulkan; + + public CommandStreamStoreProtectionTests(HeadlessVulkanFixture fixture) => _vulkan = fixture.Vulkan; + + // An end-of-pipe label tells the guest that a GPU copy in front of it is done. Its pages must block CPU reads by the + // time the label lands, or the guest reads the bytes from before the copy. + [Fact] + public void ACommandStreamStoreLandsAfterEarlierGpuCopiesBlockCpuReads() + { + if (_vulkan is null || !OperatingSystem.IsWindows()) + return; + + using var presenter = new PresenterUnderTest(_vulkan); + var harness = presenter.Harness; + harness.Cache.DefersGpuWriteProtection = true; + var address = harness.MapBacked(0x10000, GuestPageProtection.Read | GuestPageProtection.Write); + harness.Worker.Run(() => + { + harness.Cache.ObtainBuffer(address + 0x4000, 0x1000, isWritten: true); + harness.Cache.CopyBuffer(address, address + 0x4000, 0x1000, dstGds: false, srcGds: false); + }); + Assert.Equal(HostPageProtection.ReadOnly, harness.Protection(address)); + + var label = address + 0x8000; + LandStore(presenter, label); + + Assert.Equal(HostPageProtection.NoAccess, harness.Protection(address)); + Assert.Equal(1, harness.Read(label, 1)[0]); + } + + // A shader write keeps its read protection deferred to the submission: applying it before every store stalled guests + // that read their GPU output right after a label. + [Fact] + public void ACommandStreamStoreLeavesShaderWriteProtectionToTheSubmission() + { + if (_vulkan is null || !OperatingSystem.IsWindows()) + return; + + using var presenter = new PresenterUnderTest(_vulkan); + var harness = presenter.Harness; + harness.Cache.DefersGpuWriteProtection = true; + var address = harness.MapBacked(0x10000, GuestPageProtection.Read | GuestPageProtection.Write); + harness.Worker.Run(() => harness.Cache.ObtainBuffer(address, 0x1000, isWritten: true)); + Assert.Equal(HostPageProtection.ReadOnly, harness.Protection(address)); + + var label = address + 0x8000; + LandStore(presenter, label); + + Assert.Equal(HostPageProtection.ReadOnly, harness.Protection(address)); + Assert.Equal(1, harness.Read(label, 1)[0]); + } + + private static void LandStore(PresenterUnderTest presenter, ulong label) + { + var harness = presenter.Harness; + var thread = Activator.CreateInstance(CommandThreadType, PresenterUnderTest.InstanceMembers, null, + [presenter.Instance, null, harness.Memory, null, null], null)!; + CommandThreadType.GetMethod("PostOwnedWrite")!.Invoke(thread, [label, new byte[] { 1, 0, 0, 0 }, false]); + var stores = (IEnumerable)CommandThreadType.GetField("_pendingWrites", PresenterUnderTest.InstanceMembers)!.GetValue(thread)!; + var store = Assert.Single(stores.Cast()); + harness.Worker.Run(() => CommandThreadType.GetMethod("Execute", PresenterUnderTest.InstanceMembers)!.Invoke(thread, [store])); + } +} From 80a1be65c24ea92c6fa0a0b534f237a29429a389 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:05:07 +0300 Subject: [PATCH 050/134] [GPU] Proven memo ticks --- .../Gpu/Images/GuestImageCache.Lookup.cs | 2 + .../VulkanVideoPresenter.Descriptors.cs | 29 ++++++++++- .../RenderHostDeviceTests.StagePreparation.cs | 50 +++++++++++++++++++ 3 files changed, 80 insertions(+), 1 deletion(-) create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.StagePreparation.cs diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Lookup.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Lookup.cs index 5f00c6b1c..29224d6b0 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Lookup.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Lookup.cs @@ -65,6 +65,8 @@ private void InvalidateLookups(ulong begin, ulong end) // that remembers a lookup's result can tell when it may have changed. public ulong LookupGeneration => _lookupGeneration; + internal ulong CollectionTick => Volatile.Read(ref _collectionTick); + // What a remembered lookup still does on reuse: the image counts as used now. False when the // image is gone. public bool TryReuseAcquired(ResourceSlotIdentifier imageIdentifier, ulong backing) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs index fd89d8068..d9b329bac 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs @@ -64,7 +64,7 @@ internal enum NullImageMemoMode }; internal static string TakeStagePreparationReport() => - FormattableString.Invariant($"[PERF][STAGE_MEMO] hits={Interlocked.Exchange(ref _stageMemoHits, 0)} misses={Interlocked.Exchange(ref _stageMemoMisses, 0)} captures={Interlocked.Exchange(ref _stageMemoCaptures, 0)} ") + + FormattableString.Invariant($"[PERF][STAGE_MEMO] proven={Interlocked.Exchange(ref RecordingHost._stageMemoProven, 0)} hits={Interlocked.Exchange(ref _stageMemoHits, 0)} misses={Interlocked.Exchange(ref _stageMemoMisses, 0)} captures={Interlocked.Exchange(ref _stageMemoCaptures, 0)} ") + FormattableString.Invariant($"stale={Interlocked.Exchange(ref _stageMemoStale, 0)} invalidations={Interlocked.Exchange(ref _stageMemoInvalidations, 0)} acquire_reuses={Interlocked.Exchange(ref _stageMemoAcquireReuses, 0)} ") + FormattableString.Invariant($"content_hits={Interlocked.Exchange(ref _stageMemoContentHits, 0)} evictions={Interlocked.Exchange(ref _stageMemoEvictions, 0)} ") + FormattableString.Invariant($"null_images=hits:{_nullImageHits.Take()},verified:{_nullImageVerified.Take()},mismatches:{_nullImageMismatches.Take()}"); @@ -87,12 +87,16 @@ private sealed class StagePreparationMemo public TextureResource[] Textures = []; public GuestSpan[] TextureRanges = []; public ulong LookupGeneration; + public ulong ProvenGeneration = ulong.MaxValue; + public ulong ProvenCollection; + public ulong ProvenTick; public Sampler[] SamplerHandles = []; public (BufferDescriptorWords Descriptor, ResourceSlotIdentifier Buffer, ulong MappedSize)[] Sources = []; public bool Valid; public void Invalidate() { + ProvenGeneration = ulong.MaxValue; if (Valid) { Valid = false; @@ -395,6 +399,9 @@ private bool TryFindStagePreparation(StagePreparationSet set, ResourceSnapshot s return false; } + private const ulong ProvenMemoTicks = 8; + internal static long _stageMemoProven; + private bool IsFreshStagePreparation(StagePreparationMemo memo) { if (!memo.Valid) @@ -402,6 +409,16 @@ private bool IsFreshStagePreparation(StagePreparationMemo memo) return false; } + var proofGeneration = _imageCache.LookupGeneration; + var proofCollection = _imageCache.CollectionTick; + var proofTick = _scheduler.CurrentTick; + if (!_worker && memo.ProvenGeneration == proofGeneration && memo.ProvenCollection == proofCollection && + proofTick - memo.ProvenTick < ProvenMemoTicks) + { + Interlocked.Increment(ref _stageMemoProven); + return true; + } + var generation = memo.LookupGeneration; var textures = memo.Textures; if (textures.Length != 0) @@ -428,6 +445,13 @@ private bool IsFreshStagePreparation(StagePreparationMemo memo) } memo.LookupGeneration = generation; + if (!_worker) + { + memo.ProvenGeneration = proofGeneration; + memo.ProvenCollection = proofCollection; + memo.ProvenTick = proofTick; + } + return true; } @@ -565,6 +589,8 @@ private void NoteStagePreparation(StagePreparationSet set, PreparedStageBindings for (var index = 0; index < images.Length; index++) { memo.Textures[index].CopyBindingFrom(images[index]); + // Recycling an invalid memo clears the binding's owner before this recapture. + memo.Textures[index].Preparation = memo; memo.TextureRanges[index] = _imageCache.RememberedRange(images[index].ImageIdentifier, images[index].Request); } @@ -589,6 +615,7 @@ private void NoteStagePreparation(StagePreparationSet set, PreparedStageBindings memo.Buffers = snapshot.Buffers; memo.Ranges = snapshot.DeviceAddressRanges; memo.ShaderBase = shaderBase; + memo.ProvenGeneration = ulong.MaxValue; memo.RegistrationSerial = _bufferCache.RegistrationSerial; memo.Spans = GuestGpuMemoryHook.Current?.SpanVersion ?? 0; memo.Valid = true; diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.StagePreparation.cs b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.StagePreparation.cs new file mode 100644 index 000000000..7402a9175 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.StagePreparation.cs @@ -0,0 +1,50 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections; +using System.Reflection; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +public sealed unsafe partial class RenderHostDeviceTests +{ + [Fact] + public void StagePreparation_RecapturedBindingsSurviveSubmissionRecycling() + { + if (!Ready()) return; + using var presenter = new PresenterUnderTest(_vulkan!); + using var fatal = new FatalScope(); + presenter.LoadRenderingCommands(); + var program = FixedProgramProvider.EmptyProgram(ShaderStageKind.Compute, 0xB6, + new ShaderResourceInfo { Images = [SampledImage] }); + var words = new uint[8]; + var first = BindOneImage(presenter, program, words, 0x1000); + Assert.Equal(first, BindOneImage(presenter, program, words, 0x1000)); + + var set = presenter.GetField("_stagePreparations")[program]!; + var memo = set.GetType().GetField("Last")!.GetValue(set)!; + var texture = ((Array)memo.GetType().GetField("Textures")!.GetValue(memo)!).GetValue(0)!; + presenter.Run(() => + { + // Feedback invalidates a memo; completing its submission then resets its binding. + memo.GetType().GetMethod("Invalidate")!.Invoke(memo, null); + presenter.InvokeMethod("ReturnTextureResource", texture); + }); + + Assert.Equal(first, BindOneImage(presenter, program, words, 0x1000)); + Assert.Equal(first, BindOneImage(presenter, program, words, 0x1000)); + + // An older submission can still return this same binding after the memo was recaptured. + presenter.Run(() => presenter.InvokeMethod("ReturnTextureResource", texture)); + var proven = PresenterUnderTest.RecordingHostType.GetField("_stageMemoProven", BindingFlags.Static | BindingFlags.NonPublic)!; + var before = (long)proven.GetValue(null)!; + Assert.Equal(first, BindOneImage(presenter, program, words, 0x1000)); + Assert.Equal(before + 1, (long)proven.GetValue(null)!); + Assert.Empty(fatal.Messages); + presenter.Harness.Shutdown(); + } +} From e95bfad1814309552ee4ea894d5d01d63a08bfd2 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:06:06 +0300 Subject: [PATCH 051/134] [Kernel] Add high-resolution sleep support for Windows and Linux --- src/SharpEmu.Libs/HostHighResolutionSleep.cs | 222 ++++++++++++++++++ .../Kernel/KernelRuntimeCompatExports.cs | 34 +-- 2 files changed, 239 insertions(+), 17 deletions(-) create mode 100644 src/SharpEmu.Libs/HostHighResolutionSleep.cs diff --git a/src/SharpEmu.Libs/HostHighResolutionSleep.cs b/src/SharpEmu.Libs/HostHighResolutionSleep.cs new file mode 100644 index 000000000..3981bba93 --- /dev/null +++ b/src/SharpEmu.Libs/HostHighResolutionSleep.cs @@ -0,0 +1,222 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace SharpEmu.Libs; + +internal static unsafe partial class HostHighResolutionSleep +{ + private const long SpinLimit100ns = 500; + private const long SpinLimitNanoseconds = 50_000; + private const uint CreateWaitableTimerManualReset = 0x1; + private const uint CreateWaitableTimerHighResolution = 0x2; + private const uint TimerAllAccess = 0x1F0003; + private const uint Infinite = 0xFFFFFFFF; + private const int ClockMonotonic = 1; + private const int TimerAbsoluteTime = 1; + private const int ErrorInterrupted = 4; + private const long NanosecondsPerSecond = 1_000_000_000; + + [ThreadStatic] + private static nint _timer; + + [ThreadStatic] + private static bool _timerInitialized; + + private static int _posixClockState; + + public static void SleepMicroseconds(ulong microseconds) => + Sleep100ns(microseconds > long.MaxValue / 10 ? long.MaxValue : (long)microseconds * 10, allowSpinning: true); + + private static void Sleep100ns(long units, bool allowSpinning) + { + if (units <= 0) + { + return; + } + + if (OperatingSystem.IsWindows()) + { + SleepWindows(units, allowSpinning); + return; + } + + if (OperatingSystem.IsLinux() && TrySleepPosix(units * 100, allowSpinning)) + { + return; + } + + if (OperatingSystem.IsMacOS() && TryNanosleep(units * 100)) + { + return; + } + + SleepFallback(units); + } + + private static bool TryNanosleep(long nanoseconds) + { + if (Volatile.Read(ref _posixClockState) < 0) + { + return false; + } + + var request = new Timespec + { + Seconds = nanoseconds / NanosecondsPerSecond, + Nanoseconds = nanoseconds % NanosecondsPerSecond, + }; + Timespec remaining; + try + { + while (Nanosleep(&request, &remaining) != 0) + { + if (Marshal.GetLastPInvokeError() != ErrorInterrupted) + { + break; + } + + request = remaining; + } + } + catch (Exception exception) when (exception is DllNotFoundException or EntryPointNotFoundException) + { + Volatile.Write(ref _posixClockState, -1); + return false; + } + + return true; + } + + private static void SleepWindows(long units, bool allowSpinning) + { + if (allowSpinning && units <= SpinLimit100ns) + { + var deadline = Stopwatch.GetTimestamp() + Math.Max(units * Stopwatch.Frequency / 10_000_000, 1); + do + { + Thread.SpinWait(1); + } + while (Stopwatch.GetTimestamp() < deadline); + return; + } + + var timer = ThreadTimer(); + if (timer != 0) + { + var dueTime = -units; + if (SetWaitableTimerEx(timer, &dueTime, 0, 0, 0, 0, 0) != 0) + { + _ = WaitForSingleObject(timer, Infinite); + return; + } + } + + SleepFallback(units); + } + + private static nint ThreadTimer() + { + if (_timerInitialized) + { + return _timer; + } + + _timerInitialized = true; + var timer = CreateWaitableTimerExW(0, 0, CreateWaitableTimerHighResolution, TimerAllAccess); + if (timer == 0) + { + timer = CreateWaitableTimerExW(0, 0, CreateWaitableTimerManualReset, TimerAllAccess); + } + + _timer = timer; + return timer; + } + + private static bool TrySleepPosix(long nanoseconds, bool allowSpinning) + { + if (Volatile.Read(ref _posixClockState) < 0) + { + return false; + } + + Timespec deadline; + try + { + if (ClockGetTime(ClockMonotonic, &deadline) != 0) + { + return false; + } + } + catch (Exception exception) when (exception is DllNotFoundException or EntryPointNotFoundException) + { + Volatile.Write(ref _posixClockState, -1); + return false; + } + + var target = deadline.Nanoseconds + nanoseconds % NanosecondsPerSecond; + deadline.Seconds += nanoseconds / NanosecondsPerSecond + target / NanosecondsPerSecond; + deadline.Nanoseconds = target % NanosecondsPerSecond; + + if (allowSpinning && nanoseconds <= SpinLimitNanoseconds) + { + Timespec now; + do + { + if (ClockGetTime(ClockMonotonic, &now) != 0) + { + return true; + } + } + while (now.Seconds < deadline.Seconds || + (now.Seconds == deadline.Seconds && now.Nanoseconds < deadline.Nanoseconds)); + return true; + } + + while (ClockNanosleep(ClockMonotonic, TimerAbsoluteTime, &deadline, null) == ErrorInterrupted) + { + } + + return true; + } + + private static void SleepFallback(long units) + { + var milliseconds = units / 10_000 + (units % 10_000 == 0 ? 0 : 1); + Thread.Sleep((int)Math.Min(milliseconds, int.MaxValue)); + } + + [StructLayout(LayoutKind.Sequential)] + private struct Timespec + { + public long Seconds; + public long Nanoseconds; + } + + [LibraryImport("kernel32.dll")] + private static partial nint CreateWaitableTimerExW(nint attributes, nint name, uint flags, uint desiredAccess); + + [LibraryImport("kernel32.dll")] + private static partial int SetWaitableTimerEx( + nint timer, + long* dueTime, + int period, + nint completionRoutine, + nint argument, + nint wakeContext, + uint tolerableDelay); + + [LibraryImport("kernel32.dll")] + private static partial uint WaitForSingleObject(nint handle, uint milliseconds); + + [LibraryImport("libc", EntryPoint = "clock_gettime")] + private static partial int ClockGetTime(int clock, Timespec* time); + + [LibraryImport("libc", EntryPoint = "clock_nanosleep")] + private static partial int ClockNanosleep(int clock, int flags, Timespec* request, Timespec* remaining); + + [LibraryImport("libc", EntryPoint = "nanosleep", SetLastError = true)] + private static partial int Nanosleep(Timespec* request, Timespec* remaining); +} diff --git a/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs b/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs index efb4d10fe..7492e7006 100644 --- a/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs +++ b/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs @@ -70,8 +70,8 @@ public static partial class KernelRuntimeCompatExports private static readonly bool _traceGuestThreads = string.Equals(Environment.GetEnvironmentVariable("SHARPEMU_LOG_GUEST_THREADS"), "1", StringComparison.Ordinal); - [ThreadStatic] - private static int _shortUsleepCount; + private const ulong UsleepStepMicroseconds = 10_000; + private const ulong UsleepSpinLimitMicroseconds = 50; private static readonly bool _stopwatchTicksAreNanoseconds = Stopwatch.Frequency == 1_000_000_000L; @@ -104,27 +104,27 @@ public static int KernelUsleep(CpuContext ctx) GuestThreadExecution.Scheduler?.Pump(ctx, "sceKernelUsleep"); - if (micros < 1000) + if (micros > UsleepSpinLimitMicroseconds) { - // Guest worker pools use usleep(1) as a polling backoff. Do not turn - // PS microsecond waits into Windows millisecond sleeps on hot paths. - if ((++_shortUsleepCount & 255) == 0) + micros = Audio.AudioOut2Exports.ProducerSleepMicroseconds(micros); + } + + while (micros > 0) + { + var step = Math.Min(micros, UsleepStepMicroseconds); + if (step <= 1) { - Thread.Sleep(0); + if (!Thread.Yield()) + { + Thread.Sleep(0); + } } else { - Thread.Yield(); + HostHighResolutionSleep.SleepMicroseconds(step); } - } - else - { - _shortUsleepCount = 0; - // Precise sleep: rounding microseconds up to Thread.Sleep - // milliseconds (which itself overshoots by a scheduler quantum) - // hard-caps games that pace their frame loop with usleep. - micros = Audio.AudioOut2Exports.ProducerSleepMicroseconds(micros); - HostTiming.SleepMicroseconds((long)Math.Min(micros, long.MaxValue)); + + micros -= step; } ctx[CpuRegister.Rax] = 0; From ab92008fdef762003133ef2598be8155a63d0b06 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:52:56 +0300 Subject: [PATCH 052/134] [ShaderCompiler] Honor early depth tests and preserve inactive image address registers --- .../Gpu/Pipelines/ShaderProgramCache.cs | 1 + .../Gen5SpirvTranslator.cs | 5 +++++ .../SpirvModuleBuilder.cs | 1 + .../Ir/Gen5VectorObservationAnalysis.cs | 16 ++++++++++++-- .../ShaderCompileRequest.cs | 1 + .../Gpu/Pipelines/ShaderProgramCacheTests.cs | 19 ++++++++++++++++ .../Gen5PixelOutputMappingTests.cs | 16 +++++++++++++- .../Gen5VectorObservationAnalysisTests.cs | 22 +++++++++++++++++++ 8 files changed, 78 insertions(+), 3 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index 896807fa4..01f641a33 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -2103,6 +2103,7 @@ private static ShaderCompileRequest BuildPixelRequest(IShaderPipelineHost host, NativeFloat16Conversions = host.NativeFloat16Conversions, PixelOutputs = options.PixelOutputs, PixelDepthExportEnable = info.DepthExportEnable, + PixelEarlyDepth = info.EarlyDepth, PixelInputEnable = options.PixelInputEnable, PixelCustomInterpolationMask = info.CustomInterpolationMask, SupportsPerVertexPixelInputs = host.PerVertexPixelInputsSupported, diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.cs index 44c40dee9..ed26026ed 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.cs @@ -537,6 +537,11 @@ uint EncodeBool(uint condition) => if (_stage == Gen5SpirvStage.Pixel) { _module.AddExecutionMode(main, SpirvExecutionMode.OriginUpperLeft); + // Rejected fragments must not write guest buffers or storage images. + if (_request.PixelEarlyDepth) + { + _module.AddExecutionMode(main, SpirvExecutionMode.EarlyFragmentTests); + } if (_pixelDepthOutput != 0) { _module.AddExecutionMode(main, SpirvExecutionMode.DepthReplacing); diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/SpirvModuleBuilder.cs b/src/SharpEmu.ShaderCompiler.Vulkan/SpirvModuleBuilder.cs index 8776eed7c..1d9434d47 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/SpirvModuleBuilder.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/SpirvModuleBuilder.cs @@ -280,6 +280,7 @@ public enum SpirvExecutionMode : uint Quads = 24, Isolines = 25, OriginUpperLeft = 7, + EarlyFragmentTests = 9, DepthReplacing = 12, LocalSize = 17, DenormPreserve = 4459, diff --git a/src/SharpEmu.ShaderCompiler/Ir/Gen5VectorObservationAnalysis.cs b/src/SharpEmu.ShaderCompiler/Ir/Gen5VectorObservationAnalysis.cs index 37eba4e5d..970830aec 100644 --- a/src/SharpEmu.ShaderCompiler/Ir/Gen5VectorObservationAnalysis.cs +++ b/src/SharpEmu.ShaderCompiler/Ir/Gen5VectorObservationAnalysis.cs @@ -226,7 +226,7 @@ private static bool TryDescribe(Gen5ShaderInstruction instruction, out Effect ef break; case Gen5ShaderEncoding.Mimg: cross = cross.Union(reads); - DescribeImage(instruction, ref reads, ref writes); + DescribeImage(instruction, ref reads, ref cross, ref writes); break; case Gen5ShaderEncoding.Ds: if (opcode is "DsSwizzleB32" or "DsBpermuteB32" or "DsPermuteB32") @@ -326,8 +326,20 @@ private static void DescribeBuffer(Gen5ShaderInstruction instruction, ref Vector } } - private static void DescribeImage(Gen5ShaderInstruction instruction, ref VectorRegisterSet reads, ref VectorRegisterSet writes) + private static void DescribeImage(Gen5ShaderInstruction instruction, ref VectorRegisterSet reads, + ref VectorRegisterSet cross, ref VectorRegisterSet writes) { + if (instruction.Control is Gen5ImageControl address) + { + // Sources may name only the base; keep the whole possible address tuple, including layer, LOD and gradients. + for (var component = 0; component < 16; component++) + { + var register = address.GetAddressRegister(component); + reads = reads.With(register); + cross = cross.With(register); + } + } + var (data, count) = instruction.Control switch { Gen5ImageControl image => (image.VectorData, 5u), diff --git a/src/SharpEmu.ShaderCompiler/ShaderCompileRequest.cs b/src/SharpEmu.ShaderCompiler/ShaderCompileRequest.cs index 6569f2ba6..5cf9f62f5 100644 --- a/src/SharpEmu.ShaderCompiler/ShaderCompileRequest.cs +++ b/src/SharpEmu.ShaderCompiler/ShaderCompileRequest.cs @@ -348,6 +348,7 @@ [.. uses.Where(use => use.Callee == callee).Select(use => use.Field).Distinct() public IReadOnlyList PixelOutputs { get; init; } = []; public bool PixelDepthExportEnable { get; init; } + public bool PixelEarlyDepth { get; init; } public uint PixelInputEnable { get; init; } public uint PixelCustomInterpolationMask { get; init; } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderProgramCacheTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderProgramCacheTests.cs index fe8c90c36..ecd44b261 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderProgramCacheTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderProgramCacheTests.cs @@ -144,6 +144,25 @@ public void PixelImageAliasPartitionsReuseOnePermutationWhenTheGraphicsBudgetFit private readonly FatalScope _fatal = new(); private readonly PipelineTestGuest _guest = new(); + [Fact] + public void PixelEarlyDepthHasSeparateProgramKeysAndReachesTheCompiler() + { + _guest.RegisterProgram(CodeA, HeaderA, PipelineTestGuest.EndProgram); + var source = _guest.Source(CodeA, ShaderStage.Pixel, []); + var cursor = 0u; + ShaderProgram Compile(bool earlyDepth) => _guest.Programs.GetOrCompile(source, new StageCompileOptions + { + PixelInfo = new PixelInputInfo { EarlyDepth = earlyDepth }, PixelOutputs = [], + }, ref cursor, out _); + + var late = Compile(false); + var early = Compile(true); + Assert.NotEqual(late, early); + Assert.Equal(late, Compile(false)); + Assert.Equal(early, Compile(true)); + Assert.Equal(new[] { false, true }, _guest.Compiler.Requests.Select(request => request.PixelEarlyDepth)); + } + [Fact] public void PixelOutputModesHaveSeparateProgramKeys() { diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5PixelOutputMappingTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5PixelOutputMappingTests.cs index bcf29b4a1..9a1e4a6fb 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Gen5PixelOutputMappingTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5PixelOutputMappingTests.cs @@ -14,6 +14,18 @@ namespace SharpEmu.ShaderCompiler.Tests; public sealed class Gen5PixelOutputMappingTests { + [Theory] + [InlineData(false)] + [InlineData(true)] + public void PixelEarlyDepthControlsFragmentTestOrdering(bool earlyDepth) + { + var code = CompilePixelProgram(Gen5ColorComponentMapping.Identity, earlyDepth: earlyDepth); + Assert.Equal(earlyDepth, ReadInstructions(code).Any(instruction => + instruction.Opcode == SpirvOp.ExecutionMode && + instruction.Operands[1] == (uint)SpirvExecutionMode.EarlyFragmentTests)); + ValidateDepthModule(code); + } + [Theory] [InlineData(true, 1u, 8u, true)] [InlineData(true, 3u, 8u, true)] @@ -371,7 +383,8 @@ private static byte[] CompilePixelProgram( IReadOnlyList? prefix = null, bool enableGraphicsSubgroupOperations = true, bool depthExportEnable = false, - IReadOnlyList? suffix = null) + IReadOnlyList? suffix = null, + bool earlyDepth = false) { var prefixInstructions = prefix ?? []; var suffixInstructions = suffix ?? []; @@ -407,6 +420,7 @@ private static byte[] CompilePixelProgram( componentMapping)], EnableGraphicsSubgroupOperations = enableGraphicsSubgroupOperations, PixelDepthExportEnable = depthExportEnable, + PixelEarlyDepth = earlyDepth, }; Assert.True( diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5VectorObservationAnalysisTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5VectorObservationAnalysisTests.cs index e49dc6e92..d24e94a89 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Gen5VectorObservationAnalysisTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5VectorObservationAnalysisTests.cs @@ -62,6 +62,28 @@ public void ACrossLaneReadObservesInactiveLanes() Assert.False(Analyze().UnobservedWrites(write).Contains(3)); } + [Theory] + [InlineData("ImageStore", false)] + [InlineData("ImageLoad", false)] + [InlineData("ImageSample", false)] + [InlineData("ImageStore", true)] + public void ImageArrayLayerPreservesInactiveValuesWhenExecIsRestored(string opcode, bool nonSequential) + { + var layer = nonSequential ? 90u : 42u; + SaveExec(); + Narrow(); + var write = Add(MoveVector(0, layer, 0)); + RestoreExec(); + var image = Image(0, opcode, 0, dimension: 5, vectorAddress: 40, dmask: 1); + image = image with { Control = ((Gen5ImageControl)image.Control!) with + { + AddressRegisters = nonSequential ? [40, 41, layer] : [40], + } }; + Add(image); + + Assert.False(Analyze().UnobservedWrites(write).Contains(layer)); + } + [Fact] public void AFullWriteUnderAFullExecEndsTheObservation() { From 99f9fe9303734ade2a4efc4386273d033f31a5e3 Mon Sep 17 00:00:00 2001 From: "Ainesh M." <236408161+Kuaryn@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:48:12 +0000 Subject: [PATCH 053/134] =?UTF-8?q?[GPU/ShaderCompiler/Images]=20Ghost=20o?= =?UTF-8?q?f=20Y=C5=8Dtei:=20boots=20to=20the=20world=20and=20renders=20it?= =?UTF-8?q?s=20terrain=20(#1147)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [GPU] Sweep the device-address spans current at a slice join, not the ones a worker captured Ghost of Yotei 02.002 failed fast about 130 s in, right after the world loaded (launches 341/342): RecordSlicePrologue -> PrepareBda -> FlushSweepUploads read a buffer over memory the guest had unmapped (guest=unmapped host=Reserved). A guest unmap marks the buffers it covers CPU-dirty but leaves them registered, so any device-address sweep that still includes the range reads memory that is gone. Worker slices capture the GPU spans when the worker prepares them; the render thread then runs relay commands (the guest munmap among them) between items, joins the slice and swept the captured spans. The join now sweeps the spans current on the render thread. BdaSweepUnmapTests fails RED with the production stack before the fix and passes after it. Ported from the fork commit below without its parts for the retained device-address fault ranges (SHARPEMU_FAULT_RETAIN), which main does not have, and without the SHARPEMU_ZERO_UNREADABLE_UPLOADS fallback. (cherry picked from commit 6edadaac8619dba286f3858835dddf28de08b6cc) (cherry picked from commit 029868f4ccf5a3c522d88ec1696bf19f2c3dfd1d) (cherry picked from commit 315a8b93bae5c92327d265d4949ceb51476c6c83) * [ShaderCompiler] FLAT opcode is bits 24:18 only, offset is 12-bit signed Ghost of Yotei 02.002 crashed decoding compute 0x79B0066F0CD1F3CD (unknown-flat segment=0x2 op=0x88 word=0xDC2080D9). That word is global_load_ubyte v2, v53, s[0:1] offset:217. DecodeFlat took word bit 0 as opcode bit 7, a MIMG-only rule (OPM); in FLAT bit 0 is offset bit 0, so any odd offset turned op 0x08 into 0x88. 02.002 is the first Yotei build with odd-offset byte loads (26 of them, 2 in each of 13 programs of this family). The offset field also took 13 bits (the GFX9 width). On GFX10 bit 12 is DLC, so a DLC load would get a wrong, negative offset. No Yotei 01.512 or 02.002 shader sets it; fixed with the opcode for exact ISA semantics. The full program (all_shaders.xpps offset 0x1A0158, 0xB2D0 bytes, XxHash3 matches) now decodes (8077 instructions) and compiles to SPIR-V offline. (cherry picked from commit ffdb6ad90b286dfbd897f82a07566ddc7713891d) (cherry picked from commit b171762443d60f828c46690cf2dd3c6211b13911) (cherry picked from commit 09b00360075c3b1a2a5697e1fd1a8ed11e6fa306) * [ShaderCompiler] Decode and translate s_brev_b64 SOP1 opcode 0x0C. Eleven Ghost of Yotei compute programs (the same eleven in 01.512 and 02.002) use it to build a 64-bit constant from a 32-bit literal: s_brev_b64 sN, 0x0A000000. They stopped at decode with unknown-sop1 op=0x0C. The instruction reverses all 64 bits and leaves SCC alone. Vulkan limits OpBitReverse to 32-bit operands, so the translator reverses each half and swaps them; the scalar value graph does the same, which keeps a table address built this way resolvable for the resource plan. The lane-local analysis lists it as a two-register writer that keeps SCC. Offline over every program in both all_shaders.xpps files: nine of the eleven now decode and compile to SPIR-V; the other two go on to MIMG 0xE5, which stops ten compute programs in each version and is left alone. (cherry picked from commit f1b2b1081361bc0d53838e4ba0e80ae4af240771) (cherry picked from commit 2edecf7b3b60789c41edf2f0b6aa36472007bca4) (cherry picked from commit 05929e003cf684529735a800b174bceaedb84a96) * [GPU] Run a complete hull binary that was never fused from two halves Ghost of Yotei 02.002 died about 50 s in (launches 279-281) with "The tessellation path requires a registered merged local/hull program." 01.512 ships each tessellation hull as two AGC shaders, a local front (type 5, 0x370 bytes) and a hull back (type 7, 0x2430 bytes), and joins them with sceAgcFuseShaderHalves. That call registers the pair, and the tessellation path only knew that form. 02.002 no longer imports sceAgcFuseShaderHalves or sceAgcGetFusedShaderSize. Its seven hull headers are type 3, one complete 0x2630-byte program (all_shaders.xpps 0x308058) bound through SPI_SHADER_PGM_LO_LS alone, so nothing is registered and SPI_SHADER_PGM_LO_HS stays zero. Inside that program the local half runs for the lanes below the low byte of s3 and skips to the hull half when it has none; the hull half re-opens exec and keeps the lanes below the second byte. It differs from the fused pair in two ways: - all user data is in s8..s15 (RSRC2_HS declares 8). The table the back half used to load through s0:s1 is now s14:s15, as the header's user data map says (slot 6), so no hull table address is appended; - the hull half reads registers the local half left (v0, v9, v12, v13) instead of recomputing them. One compute program per lane already carries those across. TryFindCombinedHullEntry finds the hull entry: the s_mov_b64 exec, -1 in front of the first v_cmpx that tests the second byte of s3. PrepareCombinedHull puts the workgroup barrier there, where the local skip lands, and moves nothing into s0:s1. A branch that crosses the entry anywhere else is rejected. PrepareTessellationHull takes this path for an unfused local program and still stops the draw when there is no hull half. VGT_LS_HS_CONFIG (0x1043F: 4 in, 4 out, 63 patches), VGT_TF_PARAM and the domain shader are the same in both versions. Offline, the real 02.002 hull decodes (1509 instructions), its entry is 0x22C, the factor ring resolves and it compiles to SPIR-V at 64 and 256 threads, like the fused 01.512 pair does. Not yet run in-game. The test helper DecodeHarness comes from the same fork. (cherry picked from commit 21278d43b86127475b7e9e06108d0fab0a1b01cf) (cherry picked from commit 638c66c1c5f7383dc52bd24fb8f8f930e374b4b3) (cherry picked from commit d6784c8596577a8c6888ff24408fcb941495a6a4) * [GPU] Upload a streamed texture's resident mips and zero the rest A streamed texture maps only its resident mips. A tiled chain lays the mip tail and small levels at the start and level 0 at the end, so the resident part is a backed prefix and the rest is unmapped. Reading the whole chain failed fatally. Read the backed prefix page by page and zero the unmapped tail as the last fallback after the CPU and PRT backing reads; a backed page after a hole is still rejected. (cherry picked from commit 7a2a0cfc1bf70ad19be72e22edde1eedb38fd1ee) (cherry picked from commit 3f80ddaee2d634a391fb08d2aa5c02f3f5a70c2a) (cherry picked from commit ce77d5bb46f9bbec96290a39d172b8d3eb27cd9b) * [GPU] SHARPEMU_IMAGE_BACKING_HOLES zero-fills unmapped pages inside an image's backing Ghost of Yotei 02.002 stopped with "Could not read the mapped guest image backing" (launches 366, 388, 542: first_byte_backed=True last_byte_backed=False, a 5.3 MiB image at 0xA279EA0000). The resident-prefix reader takes a backed prefix and an unmapped tail, but these images have a backed page after a hole, which it rejects, and the failure is fatal. SHARPEMU_IMAGE_BACKING_HOLES=1 (default off): every unmapped page after the first backed one reads as zero and every backed page as its bytes. With it, launch 621 (02.002, same save) ran its 450 s to the end. Test: ResidentImageBackingTests.WithHolesAllowedEveryHoleIsZeroedAndEveryBackedPageCopied. (cherry picked from commit 9a30a5a1d5b90e0e7c1486abeb6d0760cd430669) (cherry picked from commit 66c448a5328de0b756c7a1b6899b6ace77550c0e) (cherry picked from commit a0839e68719944bde622719b5b00a7cd1a4f5606) * [ShaderCompiler] A V_WRITELANE alone declares the guest lane inputs V_WRITELANE writes the lane whose guest lane index equals its lane select. A program that used no other lane-aware operation (no readlane, DPP, mbcnt, compare, exec or VCC operand) compiled without the subgroup lane inputs, so in the emulated wave64 lowering every invocation saw itself as lane 0 and a write to any other lane was dropped. Real programs nearly always have one of the others; the paired lowering always declares the inputs. Wave64Subgroup32DeviceTests.WriteLane_WritesOneLaneOfTheUpperHalf fails with SHARPEMU_WAVE64_PAIRED=0 and passes with this change. (cherry picked from commit 73fb0280bde3877ffe50e65c8b7ba2a3a07ee87b) * [ShaderCompiler] Run one-wave compute workgroups as two host subgroups On 32-lane hosts the paired wave64 lowering gives each host invocation a pair of guest lanes and runs the two wave halves in turn. For a workgroup of one wave that means one 32-lane subgroup doing the work of two, while the emulated lowering runs the two halves as two subgroups side by side. Workgroups of more than one wave are faster paired, since the emulated waves meet at rendezvous counters. The paired lowering is now used only for workgroups of more than 64 threads. SHARPEMU_WAVE64_PAIRED=1 pairs every workgroup as before, =0 still turns the paired lowering off. Ghost of Yotei 02.002 (fork measurements, same build and environment apart from the switch): RTX 3080 762/763 119.2 vs 128.3 ms frame p50, RTX 4070 Laptop 304/305 114.1 vs 120.2 ms, late captures matching. Per kernel (RTX 3080, 791 paired vs 796 emulated): one-wave kernels 0x70E4B6D3 and 0xD0BBFF78 23% and 34% faster emulated, 512- and 1024-thread kernels 0x0D379B92 and 0xC2A548AA 17% and 80% slower. Port of 97f2622b and 1eaeb350. (cherry picked from commit d9f832d971d561ed0c7199be779c99fcc9d42246) * [GPU] Accept texture views at any 256-byte T# address A tiled texture whose T# address was not a multiple of the layout alignment was rejected as fatal (Yotei: address 0x5032B23800, format 71, Standard4KB, align 0x1000). A T# stores its base address in 256-byte units, so 256 bytes is the finest address a view can express; the layout alignment only describes where a new surface allocation may be placed, and guests legitimately bind views inside larger allocations. The tiled offsets (CPU twins and tiler shaders) are computed from x/y/z relative to the view base with no absolute address bits, and the tiler handles unaligned buffer offsets, so such views tile and detile identically. The check now requires only 256-byte alignment plus a non-empty footprint. (cherry picked from commit 2c1460f4891554604e8ee9f540469c25f0726fb5) * [ShaderCompiler] Read control-flow-selected V#s from their registers A vector-buffer V# chosen by control flow (a phi over several descriptors, possibly loop-carried) has no single source to bind, so the resource plan failed with "BufferHandle dword N is not a valid runtime value". The hardware uses whichever V# sits in the SGPRs when the access runs, so such an access now takes the device-descriptor path and the translator reads base, size, stride and format from the registers. The route is taken when descriptor validation fails because of a control-dependent phi, or when an operand is recomputed from memory read on a previous loop iteration (a pointer walk). Typed (tbuffer) accesses have no device lowering and keep the plan error. Descriptors that validate statically stay host-bound, and a scalar-buffer access whose handle depends on a loop-carried read is no longer treated as host-bindable. (cherry picked from commit 6491fa009511e0ac2b5a84cc13d2c6be34adfc14) * [ShaderCompiler] Test: Control-flow-chosen V#s read through their registers on main foufouadi's fix (previous commit) routes a buffer access whose V# a phi chooses to the device-descriptor path. Two tests still described the old outcome: - ADescriptorWordMergedThroughManyExecBranchesIsPlannedQuickly (#1144) expected the plan to be rejected; it now plans, still at once, and the load reads its V# from its registers. - DescriptorWalkedByALoop_ReadsThroughRegisters (from the fork, older base) expected a runtime-provenance binding; main already reads a V# loaded from scalar-buffer data through its registers (IsDeviceLoadedBufferHandle). * [ShaderCompiler] Image gather4 with explicit LOD (cherry picked from commit 10c1c598479575a7f5ee9d064f88ad061394f49d) * [ShaderCompiler] Read the requested LOD for image_gather4_c_l by default OpImageDrefGather has no level operand, so image_gather4_c_l read the base level. A visibility pass that gathers a depth pyramid at the footprint's level then tests only a 2x2 corner of the base level and drops patches that are visible. The four texels are now compared at the requested level by default; SHARPEMU_GATHER_COMPARE_LOD=0 reads the base level again for bisecting. (cherry picked from commit 5e9b69a08d0df1780ab7b9c24f7669a59b748d1f) * [ShaderCompiler] Decode buffer_load/store_format_d16_hi_x (MUBUF 0x26, 0x27) Ghost of Yotei 02.002 stopped with "The shader program cannot be compiled: stage=compute hash=0x0041B6A03DB7472D ... pc=0x14E4 MubufRaw27: unsupported buffer opcode MubufRaw27" (India run 1657): main did not decode the D16_HI forms of the formatted buffer access. Both move one component through bits 16..31 of VDATA. The load converts the X component as BUFFER_LOAD_FORMAT_D16_X does and writes it to the high half, keeping bits 0..15; the store takes the component from the high half. They reuse the D16 paths (FormatD16Components, StoreBufferD16Components, LoadBufferD16Component) with a high-half flag. Tests: decode of both opcodes; BufferLoadFormatD16HiDeviceTests (from foufouadi's fork commit 39f237b1, which translated the load on the fork's older buffer path) and BufferStoreFormatD16HiDeviceTests on a device. * [GPU] 8-bit and 8_8 sRGB colour targets resolve their pixel output Ghost of Yotei 02.002 stopped with "The color target format has no pixel output kind: slot=5 layout=1 numberType=6 order=0" (India run 1661): the render target decode had no entry for the narrow sRGB targets. The image path already stands a same-width UNORM format in for them (GuestPixelFormats: Bits8Srgb -> R8Unorm, Bits8_8Srgb -> R8G8Unorm); the decode now says the same, with a float output. Number type 9 is accepted as for RGBA8 sRGB. The Yotei fork lineage carries the same entries (MathiasYG b97c43d4, foufouadi); native R8/R8G8 sRGB attachments (foufouadi f2d4e856) are a separate improvement. Test: VulkanPresentEncodeFormatTests.FullWidthTargetsFollowTheirNumberType (1/6, 1/9, 3/6). * [AGC] Serialize appends to one command buffer across guest threads Guest threads run HLE exports concurrently, and two appends to one buffer both read its cursor before either stored it back, so the second packet overwrote the first. The cursor update is now atomic per buffer under a striped lock that is released around the buffer-full callback. A diagnostic marker from a thread that is not the buffer's last ordinary writer is skipped instead of reserving or overwriting the owner's unpublished packet. On main, Ghost of Yotei 02.002 stopped right after a PopMarker with "The packet opcode is unknown" (India runs 1659 and 1660: a zero dword where the header of a SET_SH_REG belonged, and six stray dwords) or hung there (run 1662); the boot timing decides whether the race hits. Port of the fork commits 57c48b40 and a0fb44ba (main's allocator differs; the marker paths now pass isMarker). Test: AgcCommandBufferConcurrencyTests from 57c48b40. (ported from commit 57c48b40944ead6ae2cb73d1e0cae8f146161499) (ported from commit a0fb44ba49540459b3f137abbc7029dd626cd261) * [ShaderCompiler] Bound indirect image selectors by the shader's own clamps An indirect material-heap image whose selector has no proven value set was enumerated exhaustively (every residue + k * step, as the 32-bit product wraps) and failed past the probe cap, even when the shader clamps the selector. IndirectSelectorBound walks the selector's reaching definitions and derives an inclusive unsigned upper bound from the shader's own clamps and masks (v_min_u32/s_min_u32/v_min3_u32, v_med3_u32, and-masks, bfe, right shifts, selects over bounded values, non-overflowing add/mul/shl; signed forms only when no operand can be negative; an unbounded operand counts as the maximum). The bound is carried as IndirectImageSelector.SelectorBound and the materializer probes exactly selector in [0, bound] (clamp_bounded). Without a clamp the exhaustive enumeration is unchanged and still fails past the cap, so wrapped selector domains stay complete (the intent of yotei-good b04e3cff). Ported from yotei-good a7cee72b; the record-aligned fallback it removed never existed here. (cherry picked from commit 0b968936cfb6975fa00a6f13fc07a1fe40bcc336) * [GPU] Track HTile clears for depth arrays beyond 32 slices Ghost of Yotei 02.002 stopped with "HTile clear tracking supports at most 32 slices: last=35" (India run 1673): it binds a depth array of 36 layers. SurfaceMetadata on main already keeps the clear state of the slices past 31 apart from the 32-bit mask; the depth target check and the metadata queries still refused them. HTile now tracks any slice; DCC keeps its own slice count and CMask/FMask stay at 32. Port of the fork commit below (main's SurfaceMetadata differs). Test: GuestImageCacheTests (HTile slice 35 cleared, set and queried). (ported from commit 93a9e9601740692c8a65c9b72b72dc96414b2f95) * [ShaderCompiler] An indirect image table too large to enumerate reads as the null image Ghost of Yotei 02.002 stopped on its first terrain tessellation draw: pixel 0x81ED2D51E7B0E819 reads its texture through a material table whose selector the shader does not bound, and the table is larger than MaxIndirectImageProbes (India runs 1664/1666: "could not be materialized ... reason=Other"; with the selector-bound commit, run 1672: ImageCapacityExceeded, which strict shaders, the default, turn into a fatal error). Such a table cannot be enumerated into bindings. The access now reads the null image, as a heap record at an index the host cannot evaluate already does (BindlessNullDescriptors, on by default), so the draw runs. Reading the table on the device at run time (the Yotei fork's runtime descriptors) is the full fix and a separate change. Test: ResourceMaterializerTests.UnclampedSelectorOverTheProbeCapReadsTheNullImage (was ...StillFails). * [GPU] A write-only signed-integer storage image stores unsigned bits Ghost of Yotei 02.002 stopped in its first world load with "shader resource specialization failed: storage image descriptor 1 uses unsupported format 12" (compute 0x753C552FAE650EC4, a 16_SINT output; India run 1675). The materializer already compiles a write-only 32_SINT storage image as raw unsigned bits; a store keeps only the low bits of each register, which are the same for signed and unsigned, so this now holds for every signed width. The image is viewed through the unsigned format of its width (R16Uint for R16Sint, ...), as R32Uint already is. A signed storage image the program also reads still needs a signed binding class, which main does not have (the Yotei fork adds one, foufouadi 9e151904). Test: ResourceMaterializerTests.WriteOnlySignedStorageImage_IsCompiledAsUnsignedBits. * [AGC] Read sceAgcAcbJump's target and size after its cache policy The export takes (acb, cachePolicy, target, sizeDwords). Reading the target from the second argument chained the ACB to the cache policy value. The policy is validated and encoded in the INDIRECT_BUFFER control dword like sceAgcDcbJump does. (cherry picked from commit d8f22f212818f62d19104146d74be9dc4beb80cc) * [GPU] Resolve a stencil storage view against the depth image that owns its plane (cherry picked from commit cd5c96ab185388007cf68144ae274ebe5341de63) * [GPU] Find a stencil storage binding again when its depth image moved to another stencil plane A dispatch's stencil storage binding resolved to a depth image keeps pointing at it after the depth image is bound with another stencil plane (Ghost of Yotei 02.002 alternates two planes of one 1920x1080 depth image). The view then no longer fits the attachment's plane and stencil storage stops with a fatal error. When no depth image holds the requested plane any more, the binding is stale like a binding whose image was replaced: it is found again, and one that keeps losing its image reads as a null image (RefindStaleBindings). * [GPU] Make shader buffer writes visible to indirect argument reads Port of 3bda19a5 (DarthPotato) to main, whose ShaderWriteBarrier had no indirect-argument stage at all: the barrier after a draw or dispatch whose shaders write buffers made the writes visible to shader, vertex, index, uniform, transfer and attachment access, but not to the argument read of a later indirect draw. A stage that writes those arguments (GPU-driven culling) left the draw reading stale arguments. The destination now includes DRAW_INDIRECT with INDIRECT_COMMAND_READ. The original reports 4 of 4 device losses within four minutes of Ghost of Yotei gameplay on an RTX 3080 before, and two 480 s runs without a loss after. The barrier's request is now built by a static helper so a test can check it. * [GPU] Direct draws keep explicit NUM_INSTANCES after indirect draws Port of 7738e57f (DarthPotato) to main. Main made every indirect draw the source of the persistent instance count: a CPU-read record set it at once, and a GPU-resolved one left its record address for a later direct draw to read. In Ghost of Yotei a direct 714-index draw then drew ~1e9 instances (records holding float data such as 0x3F800000 at the instance word); the fork saw device losses in that draw and stray geometry shards. Indirect draws now take their instance count from their own record and leave NUM_INSTANCES alone. A CPU-read record with zero instances draws nothing (a zero passed on meant "use NUM_INSTANCES"). SHARPEMU_INDIRECT_INSTANCE_INHERIT=1 restores inheritance: AMD PAL treats indirect draws as clobbering NUM_INSTANCES and re-emits it, and Gen5 persistence is undocumented. The fork's VGT_NUM_INSTANCES-on-GPU work (4f4365b7) only serves inheritance, so it is not ported. Fork result: 5 of 5 four-minute Yotei runs without a device loss (was about 3 of 5). * [ShaderCompiler] Read graphics lanes a partial host subgroup never launched by the ISA rules A fragment subgroup of a small or thin primitive holds only the quads the rasterizer packed into it; the PS5 wave behind it still has its dead lanes. Ghost of Yotei's G-buffer pixel shaders (07B3D5ECAC4AAD8A, 18DFD71F9F0D3B33, CB2D39D7AA92B475) take a whole-wave minimum of a per-pixel ID (S_ORN2_SAVEEXEC of EXEC, identity 0xFFFFFFFF in the dead lanes, V_MIN_U32 DPP row_shr:1/2/4/8, V_PERMLANEX16 with BOUND_CTRL, V_READLANE 31/63) and loop until every lane's ID is done. DPP, DPP8 and PERMLANE shuffled from invocations that do not exist, which is undefined, and V_READLANE in pixel and vertex stages returned the reading lane's own value. The minimum became a value no lane owns, the loop never ended and the shaders ran into the step guard: black small, thin and near geometry. Graphics stages now look a source lane up in a ballot of true. A present lane is shuffled and judged by its EXEC state; an absent lane reads as the calling lane and is judged by its bit in the guest EXEC mask, which keeps the bits of lanes the host never launched (whole-wave code sets them). The ISA invalid-source results follow: DPP with BOUND_CTRL clear keeps the destination, set writes zero; PERMLANE likewise by OP_SEL[1]. V_READLANE reads the selected lane of the invocation's own group. This restores what foufouadi's "Read absent graphics lanes as the reading lane" and "Read the selected lane for V_READLANE in graphics stages" (6f4594e4, 71b2fb89, reverted with c7bbb093) did in the October lineage that rendered Yotei correctly. Compute and mesh stages are unchanged, so their SPIR-V stays byte-identical. Device tests (RTX 4070): the exact sequence drawn as a one-pixel triangle produced black for wave32 and wave64 before the change; quad-DPP derivatives still read helper lanes. Port to main: main's DPP16 path already reads through a ballot (GetDppSource), treating an absent invocation as an invalid source, so a BOUND_CTRL-set V_MIN_U32 row_shr read zero from a dead lane. ApplyDppSource and IsDppWriteEnabled now take the graphics-lane path first for graphics stages; compute, mesh and paired lowering keep main's code. The ballot capability is declared where the lane test builds its ballot. (cherry picked from commit 8d953c01cf3375b8020595932d45e5f3354e184a) * [ShaderCompiler] An image descriptor read in parts from a scalar buffer is a runtime descriptor A T# whose words a shader reads from one scalar buffer at a uniform offset, but not as one contiguous record, was rejected ("ImageHandle dword 0 is not a valid runtime value"). Each word is a scalar buffer read the host evaluates when the draw is bound (RuntimeValueEvaluator works word by word), so ValidateSource decides alone; a non-contiguous record with an SAndB32 hole still reads as null. Ghost of Yotei's terrain material PS 4470D4F01A1E8469 builds the T# in s88..s95 from record bytes 48..63 and 192..207 of a 136-byte material record (pc 0x258). The fork's best branch reaches it through foufouadi's runtime descriptor tables (#1097 work); main's planner only needed the contiguity rule lifted (plan checked offline on the game's shader binary with main's bindless heap on). MalformedIndirectImage_IsRejected becomes MalformedIndirectImage_IsReadWordByWord: such a record is still not an indirect heap image, and its words are read one by one. * [GPU] Keep an indirect draw's arguments on the GPU when it names a base vertex in user data An indirect draw packet that names a register for the base vertex (DRAW_INDIRECT / DRAW_INDEX_INDIRECT base_vtx_loc) had its arguments read on the CPU at packet time so the register could be written. Arguments a compute pass writes earlier in the frame are then read before the GPU wrote them: Ghost of Yotei's terrain draws (VS 34EF10C2E37E97B5, 1EBB2FA4F19E0AD1, which add s18 = base vertex and s19 = start instance to their vertex and instance ids) drew from stale counts, and the terrain material draw never ran. A base vertex in the vertex program's live user data now works like the start instance already did (StartInstanceUserData): the draw passes the arguments' base vertex to the host, names that user data (BaseVertexUserData), and the program stores gl_BaseVertex there and counts its vertex index from it, as the CP's register write leaves the hardware's. The host can then draw from the arguments where they are. A base vertex in a register the program does not load, or in a tessellation or mesh draw, is still read and written here. The value is part of the vertex stage key and the graphics prewarm record (the graphics schema fingerprint changes; vertex prewarm records carry it as an optional field after the start instance). The fork's best branch draws these from GPU arguments too (it leaves the named registers unwritten); this is the register-faithful form for main. * [ShaderCompiler] Heap records are read through the heap views of each draw A bindless image or sampler read from a buffer at an offset only the shader knows was one record of one global heap of packed descriptors: element (key + immediate) / 32 of descriptor set 1, read back from the heap V# of the last draw prepared. Ghost of Yotei reads such descriptors from many tables in one frame, whose records hold more than a descriptor: the terrain Hi-Z cull (compute 0x0041B6A03DB7472D) reads each tile's height texture from a table of 440-byte tile records, at tile * 440. Three of four tile records were read at an address rounded down to 32 bytes, and every table's records shared the elements of the others, whichever draw was prepared last. The cull sampled no height and culled every tile, the quadtree builder (0xD9B838ED6CEC8237) got an empty mask, and no terrain patch was drawn (India runs 1990 main vs 1992 fork: 0 against 4133 instances). Each descriptor offset of each heap V# a program reads is now a heap view. The host gives every view of a draw its own run of set-1 elements (BindlessHeapViewTable) and names it in two dwords of shader data (HeapView): first element, record stride, descriptor offset in a record, record count. The shader takes element first + offset / stride when the read is at the view's descriptor of a record the view holds, and the null element otherwise. A heap whose V# stride is the descriptor's size or less is packed descriptors, as before. The elements of a view are resolved from the marks its shaders leave, as before. A view keeps its run while draws read it. A table the guest allocates per frame is the same records at another address: the moved table takes over the run of a view of its shape that no pending command reads, and only records that differ are resolved again. Without such a run a view takes free elements, then those of the least recently used views whose commands completed, and at last shares the run of a view of its shape that is still read, as main did for every heap. Set 1 holds 131072 elements (was 65536): Ghost of Yotei keeps two copies of a 46158-record texture heap beside its tables. The arrays need 1048576 update-after-bind sampled images, which the device check already tests. The records of a view are compared with the guest's every 16 ticks while draws read the view, not all records of all views, and a view no draw read for 256 ticks gives its elements up: the memory of a table that moved holds other data (India run 1997 stopped at the title screen on such a record, "The image data range is invalid"). A record can also name a texture the guest has unloaded (run 2085, "Could not read the mapped guest image backing"): a T# that names no mapped guest memory is no image for now, and is looked at again while its view is read. The idea of resolving descriptors a shader picks at run time from tables is foufouadi's (#1097 on the fork, run-time descriptors keyed by their words); this keeps main's set-1 heap (#1144) and makes it hold more than one heap. Tests: BindlessHeapTests (AHeapReadTakesTheElementOfItsViewsRecord evaluates the emitted element index for a 440-byte table and a packed heap; EachDescriptorOfATablesRecordsIsAView; AViewsRecordsAreItsHeapsRecords), BindlessHeapViewTableTests, BindlessHeapRunTests.RunsOverATablesRecordsReadEachRecordsDescriptor, GuestImageCacheTests.AnImageRangeIsBackedWhenItsFirstPageIsMapped. * [ShaderCompiler] RESOURCE_LEVEL of a T# is not a reserved bit GFX10/10.3 texture descriptor word 2 bit 31 is RESOURCE_LEVEL. The candidate check for heap records and indirect image tables counted it as reserved, so a T# with the bit set was no image. Ghost of Yotei's terrain tile records hold their R16 height textures with it set (words 80689630 00700000 80800080 9050024C): the terrain Hi-Z cull (compute 0x0041B6A03DB7472D) got a null element for every tile height (India run 2081: 343 of 343 such records unresolved), culled every tile, and no terrain was drawn. Port of the mask change in Foued Attar's c7bbb093 ("Ghost of Yotei and Tsushima in game", reverted on main by 3f84f590); the test is new. Test: BindlessHeapTests.AHeapRecordWithItsResourceLevelSetIsAnImage. * [GPU] A mip copy skips a level the destination's backing does not hold When one image replaces another over the same memory, the old image is copied into the level of the new one it matches (CopyIntoMip, from GrowImage and from the merge in ResolveOverlap). A backing keeps no more levels than its extent has, so the matched level can be past the backing's last one; CopyMipFrom then stopped with "The mip copy target is invalid: mip=9 layer=0 levels=1 layers=1". Ghost of Yotei reaches this once its bindless table records resolve (India runs 2087 and 2092, 30 to 70 s into the world; runs 1999 and 2081 with mip=2): the destination then keeps what it read from the guest. No unit test: the descriptor that triggers it was not captured (the request builder already clamps a 1x1 texture's level count, so that is not it). Evidence is the in-game stop and the runs without it. * [ShaderCompiler] A draw served from a cached entry reads its heap V#s again The materialization cache serves a draw from an entry when the bytes it read are unchanged, or changed only in bases it has learned to move (a buffer the guest allocates per frame). The entry's snapshot was rebased, but its heaps (the V#s the draw's bindless records are read from, for descriptor set 1) stayed those of the draw the entry was built for. A table of records that is also a buffer of the program has such a learned base: Ghost of Yotei's terrain Hi-Z cull (compute 0x0041B6A03DB7472D) reads tile heights from its per-frame tile table, and two to three minutes into the world the cache began to serve it rebased. The host then kept resolving the records of a table address that was 100 s old and held other data (India run 2096: heap view stuck at 0x200A123A00 while the bound table moved every frame), every tile height read null, and the terrain disappeared for the rest of the run (runs 2089, 2094, 2096). Every cached path (hit, rebased hit, table refresh) now evaluates the heap V#s for the draw. ResourceMaterializer.TryEvaluateHeaps is the block the full walk already ran. Test: ResourceMaterializationCacheTests.ACachedDrawReportsTheHeapWhereItIsNow (RED: the fifth draw reports the fourth draw's heap). * [GPU] An 8-bit signed integer texture is a sampled format Guest format 6 (8 bits, SInt) had no row in the sampled-format table, no element size and no host format, so a T# of that format named no texture the host can view. Ghost of Yotei's foliage passes (computes 0xDF8A399258032A62, 0x246848246735BE0A, 0x9A1A1228B20E3710, 0x01EC8EA1AD2F2865, 0x27670C5F3455E700 and others, one group each) load a 128x128 map of this format at 0x2009748000: the fork's build binds it (pass log of India run 1992), on main every image of those passes was null (run 2091). The 16-bit and 32-bit signed formats already have these rows. Port of the Bits8SInt rows of Foued Attar's c7bbb093 ("Ghost of Yotei and Tsushima in game", reverted on main by 3f84f590); the test is new. Test: GuestPixelFormatsTests.AnEightBitSignedIntegerTextureIsSampledAsSigned. * [ShaderCompiler] A heap record that holds an integer texture is read through an integer view Set 1's image arrays were float: the format of a bindless heap record is unknown until the shader picks it, and the host gave a record of an integer format no view, so every load of one read null. Ghost of Yotei's terrain tile records (440 bytes) hold an 8-bit unsigned 513x513 mask 96 bytes in, next to the R16 height (words 80813360 00500000 80800080 90500924; India runs 2091/2096: every such element marked by a shader and left without a view), and its foliage passes load an 8-bit signed 128x128 map. A load of a heap record (ImageLoad, ImageLoadMip, ImageGetResinfo) now has a float, an unsigned and a signed declaration of its array at the array's binding, and takes the one of the element's numeric class. The host knows the class when it reads the record's T#: it writes an integer view for an integer record and the element's class (two bits) into the feedback buffer, after the mark bitsets, in command order. Each declaration reads a record's element only when the element holds a view of its class and the null element otherwise, a sampled read too, so no declaration reads a view of another class. The declarations share the binding because set 1 already holds 1048576 sampled images, the update-after-bind limit of NVIDIA drivers. The cube and depth-compare classes stay float: loads do not use them. The idea of reading a record through the declaration of its numeric class is from Foued Attar's c7bbb093 (RuntimeImageNumericClass), which takes the class from the T# words in the shader; main resolves heap T#s on the host, so the host names the class. Tests: BindlessHeapTests.AHeapRecordOfAnIntegerTextureHasItsNumericClass, AHeapLoadReadsAnIntegerRecordThroughTheIntegerDeclarationsOfItsArray, AHeapSampleDoesNotReadAnIntegerRecord. * [ShaderCompiler] A 16-byte T# read from a heap record is its four words An R128 image instruction reads a 16-byte T#. The heap planned every image record as 32 bytes: the host read 32 bytes at the descriptor's offset and checked all eight words, so where a record holds 16-byte T#s one after another the words of the next one counted as the first one's upper half, set its reserved bits, and the record got no view. Large material records that hold their textures that way (at offsets such as 468, 484 and 500) were refused for every record of the table. The heap view of an R128 read now says so (HeapRecordSelector.R128, from the image instruction), and its descriptor is 16 bytes: the host reads the four words and takes the rest of the T# as zero, a heap of packed 16-byte T#s has an element for each, and a run of elements is taken over only by a view of the same descriptor size. Call records keep 32-byte T#s. The records of a view are read again in runs through the view's own descriptor size (BindlessHeapViewTable.Region.Descriptors): read as 32 bytes there, an R128 record got its view from the first read and lost it at the next one. The readers are full-screen computes that shade from the G-buffer (ImageSampleLz/ImageSampleD with bit 15 set in the T# words; one 16-dword load feeds three T#s). Tests: BindlessHeapTests.AnR128ImageReadFromAHeapIsASixteenByteDescriptor, BindlessHeapRunTests.RunsOverR128DescriptorsReadSixteenBytesOfEachRecord, BindlessHeapViewTableTests.AnR128ViewDoesNotTakeOverTheRunOfAViewOfWholeDescriptors and ARunsDescriptorsAreTheSizeItsHeapReads. (cherry picked from commit 8c995d39def61a40d01712b118cf811fd0d7ffa1) * [ShaderCompiler] Pair every wave64 compute workgroup unless the one-wave split is asked for The one-wave split from the previous commit ran wave64 compute workgroups of up to 64 threads on 32-lane hosts (NVIDIA, Intel) through the emulated lowering by default. That changed the SPIR-V of most 64-thread kernels in every game, and was measured on two Ghost of Yotei kernels only; disabling pairing lowers FPS in other games. SHARPEMU_WAVE64_PAIRED unset (or =1) now pairs every workgroup again, as on main. =small opts in to the one-wave split (paired only above 64 threads), =0 still turns the paired lowering off. * [GPU] Indirect draws read on the CPU pass their instance count on again The previous NUM_INSTANCES change left NUM_INSTANCES alone for every indirect draw, so a direct draw after an indirect one kept the last explicit count. Main passed the record's count on (since #887, kept by #955), which is what hardware CP indirect draws do, and other games can rely on it. A record read on the CPU sets NUM_INSTANCES again, as on main. What changes from main by default is only the deferred read of a record resolved on the GPU: main read it on the CPU at the next direct draw that needed the count, before the GPU had written it, which in Ghost of Yotei gave ~1e9 instances and a lost device. That count now stays as it was. SHARPEMU_INDIRECT_INSTANCE_INHERIT=1 restores the deferred read (main exactly), =0 leaves NUM_INSTANCES alone for every indirect draw. A record with zero instances still draws nothing. * [ShaderCompiler] Put the partial-subgroup graphics lane reads behind SHARPEMU_GRAPHICS_PARTIAL_LANES The ISA lane reads for partial graphics subgroups (DPP, DPP8, PERMLANE and V_READLANE through a ballot and the guest EXEC mask, V_READLANE reading the selected lane) changed every vertex and pixel shader with cross-lane operations in every game, with no way back, and were proven on Ghost of Yotei only. They are now off by default, so vertex and pixel shaders compile as on main. SHARPEMU_GRAPHICS_PARTIAL_LANES=1 turns them on (ShaderCompileRequest.GraphicsPartialSubgroupLanes); Ghost of Yotei needs it for its G-buffer wave-minimum loops. The switch is part of the shader prewarm stamp. * [GPU] One heap read at several immediates is one heap view The per-draw heap views keyed a view by the whole heap descriptor, immediate included, and counted a view's records from the V#'s NUM_RECORDS. A packed heap (stride of the descriptor's size or less) read at immediates 0, 32 and 64 became three views over the same descriptors, and a raw V# (stride 0), whose NUM_RECORDS counts bytes, claimed 32 times as many elements as it has descriptors. In games that read a large texture heap that way, views filled set 1, evicted each other or shared runs, and each move revalidated the region: CPU churn and textures reading null for a frame. A view is now keyed by BindlessHeapDescriptor.ViewKey: a packed heap ignores the immediate (the read's whole offset picks the descriptor, as on main's single run) and counts its V#'s bytes over the descriptor size, and a record view keeps only the descriptor's offset in a record. * fix(playgo): read the installed chunks from cache_ps5/playgo.pgm Ghost of Yotei exited at boot: it ships no PlayGo sidecar and no pakchunk files, so the metadata fell back to chunk 0 only and its scePlayGo queries returned 0x80B2000A/B, after which the title called exit(1). PS5 titles carry the chunk count in cache_ps5/playgo.pgm (DMGP header, count at 0x10); read it first and report chunks 0..count-1 as Assumed, so ids outside the list are not rejected. get_progress now reports a fully installed title (1/1 instead of 0/0). Sidecar and pak-discovery fallbacks are unchanged. * feat(gpu): snorm, narrow integer and 11_11_10 unorm render targets * fix(shader): read an image table too large to bind from the bindless heap An indirect image table binds every image it can select, and a draw may bind only so many. Ghost of Yotei's material pixel shader selects one image out of hundreds of fixed-stride records and was rejected with ImageCapacityExceeded, which strict shaders turn into a fatal error. When materialization fails that way (or with IncompatibleImageCandidates) and the host has the bindless heap, the program is planned again once with preferHeapRecords: the heap records are planned before the indirect-image planner may claim their handles, so the sampled images the heap can serve are read at run time through descriptor set 1 instead of being enumerated. The plan is swapped under the cache gate, the permutations compiled from the old plan are dropped, and materialization is retried. A program with no such access, or a host without the heap, keeps the original rejection. Default planning is unchanged. Replanned programs are not recorded for prewarm, whose replay plans with the default options. Tests: the captured shader through the program cache with a small table (still an indirect table), a large table without the heap (rejected) and with it (heap records, kept across draws). * fix(images): size stencil storage images by the view the shader binds * fix(images): give a streamed texture an image of its resident levels only A sampled texture whose descriptor starts past mip 0 never reads the levels before its base, and a streamed texture has not even mapped them. The cache still created the whole chain for it, zero-filled the unmapped levels and counted their memory: a 2048x2048 chain sampled from mip 3 held 64 times the memory of its resident 256x256 levels. Ghost of Yotei streams most village textures that way (yotei-good uploads the same addresses with 8 to 10 of 12 levels), so the image working set outgrew the collection budget and the allocation-time collection recreated it every frame. The request now starts its image at the descriptor's base level (ImageDescription.FirstLevel; Extent and MipLayout still describe the guest chain). The upload drops the copy regions and tile transfers of the levels before it. The lookup keeps the whole chain when that memory is all mapped or an image over the range holds GPU contents, and serves a request from an image that starts at an earlier level through a rebased view, so rendered or fully loaded chains stay one image. Resident-level images never take part in mip/slice containment or alias copies, and are released when another resource takes their range. Port: applied onto the upstream image cache with its own copy of IsSameLayoutAlias and the overlap code (the usedThisFrame / ReleaseImage(identifier) forms; the fork's SyncResizedSibling and IsResizeSibling terms are not here and were left out). Added the FirstLevel == 0 terms to IsDepthPlaneAlias that the earlier port of 9b9dbe06 had to drop for want of this change. The test that uploads a partly mapped chain (StreamedTexture_HoldsOnlyItsResidentLevels) is not part of this commit: the upload still reads the whole range here and is fixed by the next commit. Upstream counted AccountedSize from the whole guest range, which kept the unmapped levels in the working-set total whatever the host image held (the fork derived it from the backing). It now counts ImageDescription.HeldGuestSize, the span of the resident levels, with a test. GcnImageDescriptor.ResolveTexture (GCN textures are converted into a whole linear chain) asks for the whole mip chain, so those textures never become resident-level images. (cherry picked from commit 019d2cdb0c0a824ca79ea57550e44d0a422f65bb) * fix(images): upload only the mapped levels of a streamed texture A streamed texture maps only its resident mips. A tiled chain lays the mip tail and small levels at the start and level 0 at the end, so the resident part is a mapped prefix and the rest is unmapped. Uploading the image read the whole range and failed fatally on the unmapped end (Ghost of Yotei, during loading). The image holds only the levels from its first resident one, so the upload now reads only the bytes those levels occupy: the end of the last kept tile transfer. The staging read, the detile and the edge hash of the image stop there, and the unmapped end of the range is neither read nor invented. A byte of a level the image holds that is not mapped still fails the upload. Port: 7a2a0cfc read the backed prefix page by page and zero-filled the unmapped tail as a fallback after the CPU and PRT backing reads. With the image of resident levels only (previous commit) that tail belongs to no level the image holds, so nothing needs zero-filling and the ResidentImageBacking reader is not ported; the CPU and PRT backing reads stay as they are. Its tests are replaced by tests of the new read: a partly mapped chain uploads its mapped levels, an unmapped byte of a held level still fails, and the edge hash stays inside the bytes read. (cherry picked from commit 7a2a0cfc1bf70ad19be72e22edde1eedb38fd1ee) * fix(images): fail an upload that meets an unmapped byte of a held level A streamed texture's image now holds only its resident levels and its upload reads only the bytes they occupy, so the resident-prefix fallback that zero-filled every unmapped page after the backed prefix no longer stands in for missing levels: it only hid a level the image does hold but the guest never mapped. Image reads take CPU-visible or PRT backing; SHARPEMU_IMAGE_BACKING_HOLES=1 keeps the zero-fill for games whose backing has holes. Test: GuestImageCacheTests.StreamedTexture_AnUnmappedByteOfAHeldLevelFailsTheUpload. * [ShaderCompiler] An image table the heap cannot serve reads its images of another kind as null Demon's Souls (compute 0x9FB5CC274B5E4F82) logged "indirect image table at pc 0x00001044 has incompatible candidates" hundreds of times and its dispatch was skipped (COMPUTE_SKIPPED, IncompatibleImageCandidates): one specialization binds every image a table can select in one typed binding, and a candidate of another numeric class or dimension cannot share it. Main read a T# with RESOURCE_LEVEL set as null; since 4cb1a6bc it is a candidate of its own kind, the likely source of these. When the bindless heap cannot serve the table either (no heap on the host, or the heap replan gains no record), the program cache now sets NullIncompatibleImageCandidates on the plan and materializes again. A candidate of another kind than the table's first image then reads as null, as a shared selector's candidate already does, and the operation runs. Tables of one kind materialize as before, and the materializer itself still reports the failure by default. Tests: HeapRecordReplanTests.ATableWithAnImageOfAnotherKindReadsItAsNullWithoutTheHeap (was rejected with IncompatibleImageCandidates) and ...IsReadFromTheHeapWhenTheHostHasOne. GraphicsRejectionPolicyTests.PixelCandidateTableCompilesStrictOrNot (was ...HonorsCapacityAndStrictMode, which expected the 3D candidate among 2D ones to reject the draw). * [PlayGo] Read playgo.pgm only for a title with no other chunk list cf18e9e3 (foufouadi, "read the installed chunks from cache_ps5/playgo.pgm") let Ghost of Yotei boot: it ships no PlayGo sidecar and no pakchunk files, so it got chunk 0 only and exited on the PlayGo errors that followed. The pgm was read before everything else, though, so a title with playgo-chunk.dat, playgo-scenario.json, playgo-chunkdefs.xml or pakchunk files lost its exact chunk list for chunks 0..count-1 that accept any id. Every title also read scePlayGoGetProgress as 1/1 instead of 0/0. The pgm is now the last fallback: it is read only when there is no sidecar metadata and no pakchunk file. get_progress reports 1/1 only while the pgm chunk list is in use; every other title reads 0/0 as before. Tests: PlayGoExportsTests.GetLocus_ChunkDefinitionsTakePrecedenceOverPgm and GetLocus_PakChunksTakePrecedenceOverPgm (replace ...PgmTakesPrecedence...), GetProgress_PgmChunks_ReportsAFullyInstalledTitle, GetProgress_WithoutPgm_ReportsZeroOfZero. * fix(shader): prewarm the programs that read their image tables from the heap A program whose image table selects more images than a draw can bind is planned again with heap records (PreferHeapRecords), and such programs were kept out of the shader prewarm because its replay planned with the default options. They compiled live on every launch: Demon's Souls' compute 0x9FB5 cost a ~100 ms hitch at the start of each loading screen. Each prewarm record now carries the heap-record choice as an optional field written only when set (a compute extension bit, a trailing byte for pixel, vertex and stage records), so records without it keep their bytes, identity and schema, and the lists recorded before still load. The replay plans a flagged record with heap records, and a session plans a program a record names that way from the start instead of failing to materialize it first. A linked compute program stays out: its heap plan comes from the linker. Tests: a replanned program is recorded with the flag and replays to the draw's SPIR-V; a later session plans it with heap records at once; a host without the heap is unchanged; the flag round-trips beside the existing optional fields. * fix(shader): replan a linked program with its own planning policy PreferHeapRecords replanned every program with CreateEntry's extraction policy. A linked program is planned by LinkProgram with its call records, call marks and image normalizer, so its heap replan dropped them, and the prewarm kept replanned linked programs out for that reason. Each program entry now carries the replan of the policy that produced its plan: CreateEntry's, or the link's with its call records. A link the prewarm list names plans with heap records from the start, falling back to the plain plan as CreateEntry does, and replanned linked programs are recorded for the prewarm like the others. Tests: a linked program's heap replan keeps its call records and marks; a linked program the prewarm prefers is planned, recorded and replayed with heap records to the runtime's SPIR-V and layout. --------- Co-authored-by: foufouadi Co-authored-by: Yilmaz Kasapoglu <82238608+DarthPotato@users.noreply.github.com> --- .../Shaders/GcnImageDescriptor.cs | 11 +- .../Agc/AgcExports.CommandPackets.cs | 7 +- .../Agc/AgcExports.ControlFlow.cs | 2 + src/SharpEmu.Libs/Agc/AgcExports.cs | 102 ++++- .../Gpu/Buffers/GuestBufferCache.cs | 4 +- .../GpuCommandInterpreter.Draws.cs | 81 ++-- .../Gpu/GpuCommands/GpuCommandInterpreter.cs | 6 +- .../Gpu/GpuCommands/ICommandStreamHost.cs | 8 +- .../Gpu/Images/CachedImage.Transfers.cs | 23 +- src/SharpEmu.Libs/Gpu/Images/CachedImage.cs | 17 +- .../Gpu/Images/GuestImageCache.Lookup.cs | 2 +- .../Gpu/Images/GuestImageCache.Metadata.cs | 13 +- .../Gpu/Images/GuestImageCache.Overlap.cs | 22 + .../Gpu/Images/GuestImageCache.PieceUpload.cs | 2 +- .../Gpu/Images/GuestImageCache.Transfers.cs | 81 +++- .../Gpu/Images/GuestImageCache.cs | 65 ++- .../Gpu/Images/GuestPixelFormats.cs | 5 +- .../Gpu/Images/ImageDescription.cs | 46 ++- .../ImageRequestBuilders.DepthTarget.cs | 5 - .../Images/ImageRequestBuilders.Texture.cs | 80 +++- .../Gpu/Images/ResidentImageBacking.cs | 65 +++ .../ShaderPipelineCache.Tessellation.cs | 11 +- .../Gpu/Pipelines/ShaderPipelineCache.cs | 41 +- .../Gpu/Pipelines/ShaderPrewarmList.Vertex.cs | 41 +- .../Gpu/Pipelines/ShaderPrewarmList.cs | 93 ++++- .../Gpu/Pipelines/ShaderProgramCache.cs | 190 +++++++-- .../Gpu/Pipelines/StageStaticKey.cs | 1 + .../Gpu/Rendering/IShaderPipelineProvider.cs | 3 +- .../Gpu/Rendering/RenderExecutor.cs | 11 +- .../Gpu/Rendering/ResolvedCommands.cs | 6 +- .../Gpu/Rendering/ShaderStageResources.cs | 1 + src/SharpEmu.Libs/PlayGo/PlayGoExports.cs | 78 +++- .../VideoOut/BindlessHeapViewTable.cs | 188 +++++++++ .../VulkanVideoPresenter.BindlessHeap.cs | 374 ++++++++++++----- .../VulkanVideoPresenter.CachedImages.cs | 49 ++- .../VulkanVideoPresenter.Descriptors.cs | 30 +- .../VulkanVideoPresenter.GuestDraws.cs | 19 +- .../VulkanVideoPresenter.Rendering.cs | 37 +- .../VulkanVideoPresenter.ShaderPrewarm.cs | 1 + .../VideoOut/VulkanVideoPresenter.Slices.cs | 12 +- .../Gen5SpirvTranslator.Alu.cs | 87 +++- .../Gen5SpirvTranslator.PairedLanes.cs | 17 +- .../Gen5SpirvTranslator.Resources.cs | 128 ++++-- .../Gen5SpirvTranslator.cs | 259 +++++++++++- .../SpirvModuleBuilder.cs | 1 + .../Gen5ShaderTranslator.cs | 15 +- .../Gen5TessellationLowering.cs | 49 +++ .../Ir/Gen5WaveLaneLocalAnalysis.cs | 4 +- .../Resources/BindingLayout.cs | 11 +- .../Resources/BindlessHeap.cs | 129 +++++- .../Resources/GuestImageFormat.cs | 2 +- .../Resources/IndirectSelectorBound.cs | 178 ++++++++ .../Resources/IndirectSelectorValues.cs | 8 +- .../Resources/ResourceMaterializationCache.cs | 36 +- .../Resources/ResourceMaterializer.cs | 147 +++++-- .../Resources/ResourceTracker.cs | 96 ++++- .../Resources/ScalarValueGraph.Builder.cs | 5 +- .../Resources/ShaderResourceInfo.cs | 8 + .../Resources/ShaderResourcePlan.cs | 38 +- .../ShaderCompileRequest.cs | 14 +- .../Agc/AgcCommandBufferChainTests.cs | 41 ++ .../Agc/AgcCommandBufferConcurrencyTests.cs | 132 ++++++ .../Agc/Gen5VertexInstanceIdSpirvTests.cs | 42 ++ .../Gpu/Buffers/CacheHarness.cs | 16 + .../GpuCommandInterpreterDrawTests.cs | 114 +++++- .../Gpu/Images/GpuTilerTests.cs | 32 ++ .../Images/GuestImageCacheTests.HeapHold.cs | 18 + .../Images/GuestImageCacheTests.Metadata.cs | 8 +- .../GuestImageCacheTests.PartlyMapped.cs | 101 +++++ .../GuestImageCacheTests.ResidentLevels.cs | 94 +++++ .../Gpu/Images/GuestPixelFormatsTests.cs | 18 +- .../Gpu/Images/ImageRequestBuildersTests.cs | 63 ++- .../Gpu/Images/ResidentImageBackingTests.cs | 120 ++++++ .../Gpu/Images/TextureTransferLayoutTests.cs | 66 +++ .../Gpu/Pipelines/CapturedShaders.cs | 72 ++++ .../Pipelines/GraphicsRejectionPolicyTests.cs | 31 +- .../Gpu/Pipelines/HeapRecordPrewarmTests.cs | 308 ++++++++++++++ .../Gpu/Pipelines/HeapRecordReplanTests.cs | 164 ++++++++ .../Pipelines/LinkedHeapRecordReplanTests.cs | 150 +++++++ .../Gpu/Pipelines/PipelineTestSupport.cs | 6 + .../Gpu/Pipelines/ShaderPipelineCacheTests.cs | 57 +++ .../Gpu/Pipelines/ShaderPrewarmListTests.cs | 2 +- .../Rendering/ResolvedCommandReplayTests.cs | 3 +- .../BufferLoadFormatD16HiDeviceTests.cs | 119 ++++++ .../BufferStoreFormatD16HiDeviceTests.cs | 84 ++++ .../Gpu/Vulkan/GlobalMemoryShaderTests.cs | 74 ++++ .../RenderTargetFormatSupportDeviceTests.cs | 41 ++ .../Gpu/Vulkan/TessellationWaveDeviceTests.cs | 44 ++ .../Gpu/Vulkan/Wave64HalfMaskDeviceTests.cs | 3 +- .../Gpu/Vulkan/WaveLaneTransferDeviceTests.cs | 17 +- .../PlayGo/PlayGoExportsTests.cs | 108 +++++ .../VideoOut/BdaSweepUnmapTests.cs | 74 ++++ .../VideoOut/BindlessHeapRunTests.cs | 56 ++- .../VideoOut/BindlessHeapViewTableTests.cs | 236 +++++++++++ .../VideoOut/PresenterImageBindingTests.cs | 128 +++++- .../RenderHostDeviceTests.WaveMinimum.cs | 185 +++++++++ .../VideoOut/ShaderWriteBarrierTests.cs | 29 ++ .../VulkanPresentEncodeFormatTests.cs | 30 ++ .../DecodeHarness.cs | 68 ++++ .../Gen5FlatMemoryTests.cs | 74 ++++ .../Gen5ImageGatherDecodeTests.cs | 27 ++ .../Gen5ScalarAddImmediateTests.cs | 41 +- .../Gen5TessellationTests.cs | 101 +++++ .../Gen5TypedBufferLoadDecodeTests.cs | 15 + .../GraphicsPartialLanesSwitchTests.cs | 42 ++ .../Resources/BindlessHeapTests.cs | 384 ++++++++++++++++-- .../ResourceMaterializationCacheTests.cs | 53 +++ .../Resources/ResourceMaterializerTests.cs | 85 ++++ .../Resources/ResourceTrackerTests.cs | 144 ++++++- .../Resources/ScalarValueGraphTests.cs | 6 +- .../Wave64LoweringChoiceTests.cs | 27 ++ 111 files changed, 6464 insertions(+), 554 deletions(-) create mode 100644 src/SharpEmu.Libs/Gpu/Images/ResidentImageBacking.cs create mode 100644 src/SharpEmu.Libs/VideoOut/BindlessHeapViewTable.cs create mode 100644 src/SharpEmu.ShaderCompiler/Resources/IndirectSelectorBound.cs create mode 100644 tests/SharpEmu.Libs.Tests/Agc/AgcCommandBufferConcurrencyTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.PartlyMapped.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.ResidentLevels.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Images/ResidentImageBackingTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/CapturedShaders.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/HeapRecordPrewarmTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/HeapRecordReplanTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/LinkedHeapRecordReplanTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Vulkan/BufferLoadFormatD16HiDeviceTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Vulkan/BufferStoreFormatD16HiDeviceTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Vulkan/RenderTargetFormatSupportDeviceTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/BdaSweepUnmapTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/BindlessHeapViewTableTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.WaveMinimum.cs create mode 100644 tests/SharpEmu.Libs.Tests/VideoOut/ShaderWriteBarrierTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/DecodeHarness.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Gen5ImageGatherDecodeTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/GraphicsPartialLanesSwitchTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Wave64LoweringChoiceTests.cs diff --git a/src/SharpEmu.GnmMode/Shaders/GcnImageDescriptor.cs b/src/SharpEmu.GnmMode/Shaders/GcnImageDescriptor.cs index 55e3d5306..872afaefa 100644 --- a/src/SharpEmu.GnmMode/Shaders/GcnImageDescriptor.cs +++ b/src/SharpEmu.GnmMode/Shaders/GcnImageDescriptor.cs @@ -179,6 +179,11 @@ private static ImageRequest DepthCopyRequest(ulong address, ulong size) return new ImageRequest(description, default, ImageRole.DepthTarget); } + // A GCN texture is converted into a linear chain the translator writes whole, so every level + // is there: it never takes the resident-levels image of a streamed texture. + private static TextureRequestResolution WholeChain(TextureRequestResolution resolution) => + resolution with { Request = ImageRequestBuilders.WithWholeMipChain(resolution.Request) }; + internal static TextureRequestResolution ResolveTexture(ReadOnlySpan words, in ShaderImageShape shape, ulong shaderHash, int imageIndex) { @@ -188,7 +193,7 @@ internal static TextureRequestResolution ResolveTexture(ReadOnlySpan words linear.Width == descriptor.Width + 1 && linear.Height == descriptor.Height + 1 && linear.Format == descriptor.Format && TileGeometry.TryGetElementLayout(linear.Format, out var element)) { - var pitched = ImageRequestBuilders.Texture(words, shape, shaderHash, imageIndex); + var pitched = WholeChain(ImageRequestBuilders.Texture(words, shape, shaderHash, imageIndex)); var pitchedRequest = pitched.Request; var size = (linear.Pitch + (ulong)element.TexelWidth - 1) / element.TexelWidth * ((linear.Height + (ulong)element.TexelHeight - 1) / element.TexelHeight) * element.Bytes; @@ -198,7 +203,7 @@ internal static TextureRequestResolution ResolveTexture(ReadOnlySpan words return pitched with { Request = pitchedRequest }; } if (descriptor.TileMode != GuestTileMode.RenderTarget) - return ImageRequestBuilders.Texture(words, shape, shaderHash, imageIndex); + return WholeChain(ImageRequestBuilders.Texture(words, shape, shaderHash, imageIndex)); // GNM placements can be 32 KiB aligned. Only known GPU attachments use the // shared host layout; CPU-resident GCN tiles still require a real detiler. @@ -206,7 +211,7 @@ internal static TextureRequestResolution ResolveTexture(ReadOnlySpan words var address = (descriptor.BaseAddress + 0xFFFFUL) & ~0xFFFFUL; aligned[0] = (uint)(address >> 8); aligned[1] = (aligned[1] & ~63u) | (uint)(address >> 40); - var resolution = ImageRequestBuilders.Texture(aligned, shape, shaderHash, imageIndex); + var resolution = WholeChain(ImageRequestBuilders.Texture(aligned, shape, shaderHash, imageIndex)); var request = resolution.Request; request.Description.Data = request.Description.Data with { Address = descriptor.BaseAddress }; return resolution with { Request = request }; diff --git a/src/SharpEmu.Libs/Agc/AgcExports.CommandPackets.cs b/src/SharpEmu.Libs/Agc/AgcExports.CommandPackets.cs index 7365375a6..bad29e6da 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.CommandPackets.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.CommandPackets.cs @@ -862,7 +862,9 @@ public static int DcbPushMarker(CpuContext ctx) var payloadDwords = Math.Max(((uint)marker.Length + 4) / 4, 1); var packetDwords = payloadDwords + 1; - if (!TryAllocateCommandDwords(ctx, commandBufferAddress, packetDwords, out var commandAddress) || + // A marker from a thread other than the buffer's writer is skipped (null pointer): it must not reserve space inside + // that writer's unpublished inline packet. + if (!TryAllocateCommandDwords(ctx, commandBufferAddress, packetDwords, out var commandAddress, isMarker: true) || !TryWriteUInt32(ctx, commandAddress, Pm4(packetDwords, ItNop, RPushMarker))) { return ReturnPointer(ctx, 0); @@ -912,7 +914,8 @@ public static int DcbPopMarker(CpuContext ctx) { var commandBufferAddress = ctx[CpuRegister.Rdi]; if (commandBufferAddress == 0 || - !TryEmitCommandDwords(ctx, commandBufferAddress, out var commandAddress, Pm4(2, ItNop, RPopMarker), 0)) + !TryAllocateCommandDwords(ctx, commandBufferAddress, 2, out var commandAddress, isMarker: true) || + !TryWriteCommandDwords(ctx, commandAddress, Pm4(2, ItNop, RPopMarker), 0)) { return ReturnPointer(ctx, 0); } diff --git a/src/SharpEmu.Libs/Agc/AgcExports.ControlFlow.cs b/src/SharpEmu.Libs/Agc/AgcExports.ControlFlow.cs index 435b42466..15c1a1d92 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.ControlFlow.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.ControlFlow.cs @@ -280,6 +280,8 @@ public static int AcbJumpGetSize(CpuContext ctx) LibraryName = "libSceAgc")] public static int AcbJump(CpuContext ctx) { + // (acb, cachePolicy, target, sizeDwords): an ACB jump always chains, so unlike + // sceAgcDcbJump it takes no mode argument. var acb = ctx[CpuRegister.Rdi]; var cachePolicy = (uint)ctx[CpuRegister.Rsi]; var target = ctx[CpuRegister.Rdx]; diff --git a/src/SharpEmu.Libs/Agc/AgcExports.cs b/src/SharpEmu.Libs/Agc/AgcExports.cs index 5f5b20661..49e2e9b69 100644 --- a/src/SharpEmu.Libs/Agc/AgcExports.cs +++ b/src/SharpEmu.Libs/Agc/AgcExports.cs @@ -492,8 +492,59 @@ private static ulong ComputeFingerprint(ReadOnlySpan bytes) return fingerprint; } - private static bool TryAllocateCommandDwords(CpuContext ctx, ulong commandBufferAddress, uint sizeDwords, out ulong commandAddress) - => TryPrepareCommandDwords(ctx, commandBufferAddress, sizeDwords, true, out commandAddress); + private static bool TryAllocateCommandDwords(CpuContext ctx, ulong commandBufferAddress, uint sizeDwords, out ulong commandAddress, + bool isMarker = false) + => TryPrepareCommandDwords(ctx, commandBufferAddress, sizeDwords, true, out commandAddress, isMarker); + + // Guest threads run HLE exports concurrently. Two exports appending to one command buffer both read its cursor before + // either stores it back, and the second packet overwrites the first: a game's DCB lost the header of a + // SET_SH_REG to a concurrent PopMarker (seen as "The packet opcode is unknown" right after a PopMarker). + // The cursor update is atomic per buffer, under a striped lock that is released around the guest's buffer-full callback. + private const int CommandBufferLockStripes = 64; + private static readonly object[] _commandBufferLocks = Enumerable.Range(0, CommandBufferLockStripes).Select(static _ => new object()).ToArray(); + + // Inline guest stores do not take the lock. The last ordinary packet writer of each buffer is remembered, so a + // diagnostic marker from another guest thread is skipped (null packet pointer) instead of reserving space inside that + // writer's unpublished inline packet. An ordinary export takes the buffer over, which allows a handoff between threads. + // Writers are scoped to the guest memory, and guest thread handles survive migration between host threads. + private static readonly ConditionalWeakTable> _commandBufferWriters = new(); + + private readonly record struct CommandBufferWriter(ulong ThreadHandle, CpuContext Context) + { + public bool Matches(CpuContext ctx) => ThreadHandle != 0 && GuestThreadExecution.CurrentGuestThreadHandle != 0 + ? ThreadHandle == GuestThreadExecution.CurrentGuestThreadHandle + : ReferenceEquals(Context, ctx); + } + + // Worker threads keep their command buffer objects at the same offset of stacks 16 MiB apart; a multiplicative hash + // keeps them on different stripes. + private static int CommandBufferStripe(ulong commandBufferAddress) => + (int)((commandBufferAddress * 0x9E3779B97F4A7C15UL) >> 58); + + private static bool TryPrepareCommandDwords(CpuContext ctx, ulong commandBufferAddress, uint sizeDwords, bool advanceCursor, + out ulong commandAddress, bool isMarker = false) + { + var gate = _commandBufferLocks[CommandBufferStripe(commandBufferAddress)]; + lock (gate) + { + var writers = _commandBufferWriters.GetValue(CanonicalMemory(ctx.Memory), static _ => new()); + if (isMarker && writers.TryGetValue(commandBufferAddress, out var writer) && !writer.Matches(ctx)) + { + commandAddress = 0; + return false; + } + + // A first marker establishes a writer too; an ordinary export takes ownership. + if (!writers.TryGetValue(commandBufferAddress, out writer) || !writer.Matches(ctx) || + writer.ThreadHandle != GuestThreadExecution.CurrentGuestThreadHandle) + { + writers[commandBufferAddress] = new(GuestThreadExecution.CurrentGuestThreadHandle, ctx); + } + + return TryPrepareCommandDwordsLocked(ctx, commandBufferAddress, sizeDwords, advanceCursor, gate, writers, isMarker, + out commandAddress); + } + } private static bool TryEmitCommandDwords(CpuContext ctx, ulong commandBufferAddress, out ulong commandAddress, params ReadOnlySpan dwords) { @@ -524,7 +575,8 @@ private static bool TryReadCommandBufferState(CpuContext ctx, ulong commandBuffe return true; } - private static bool TryPrepareCommandDwords(CpuContext ctx, ulong commandBufferAddress, uint sizeDwords, bool advanceCursor, out ulong commandAddress) + private static bool TryPrepareCommandDwordsLocked(CpuContext ctx, ulong commandBufferAddress, uint sizeDwords, bool advanceCursor, + object gate, ConcurrentDictionary writers, bool isMarker, out ulong commandAddress) { commandAddress = 0; if (sizeDwords == 0 || @@ -540,19 +592,31 @@ private static bool TryPrepareCommandDwords(CpuContext ctx, ulong commandBufferA var scheduler = GuestThreadExecution.Scheduler; ulong callbackResult = 0; string? callbackError = null; - if (callback == 0 || - scheduler is null || - !scheduler.TryCallGuestFunction( - ctx, - callback, - commandBufferAddress, - (ulong)sizeDwords + reservedDwords, - userData, - 0, - 0, - "agc_command_buffer_full", - out callbackResult, - out callbackError)) + bool called; + // The callback is guest code; it may block or append to this buffer itself. + Monitor.Exit(gate); + try + { + called = callback != 0 && + scheduler is not null && + scheduler.TryCallGuestFunction( + ctx, + callback, + commandBufferAddress, + (ulong)sizeDwords + reservedDwords, + userData, + 0, + 0, + "agc_command_buffer_full", + out callbackResult, + out callbackError); + } + finally + { + Monitor.Enter(gate); + } + + if (!called) { TraceAgc( $"agc.cmd_alloc_callback_failed buf=0x{commandBufferAddress:X16} " + @@ -561,6 +625,12 @@ scheduler is null || return false; } + // The callback ran with the lock released: an ordinary export may have taken the buffer over meanwhile. + if (isMarker && writers.TryGetValue(commandBufferAddress, out var currentWriter) && !currentWriter.Matches(ctx)) + { + return false; + } + TraceAgc( $"agc.cmd_alloc_callback_complete buf=0x{commandBufferAddress:X16} " + $"callback=0x{callback:X16} result=0x{callbackResult:X16}"); diff --git a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs index f29e11b6a..533caf4b2 100644 --- a/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs +++ b/src/SharpEmu.Libs/Gpu/Buffers/GuestBufferCache.cs @@ -535,9 +535,7 @@ private bool StreamUseExceeded(ulong guestAddress, ulong size) throw SubmissionScheduler.Fatal( $"Cannot reserve image staging space: address=0x{guestAddress:X16} size=0x{size:X16} capacity=0x{_staging.Size:X16} tick={_scheduler.CurrentTick}."); } - if (!_backing.TryReadBacking(guestAddress, _staging.Mapped.Slice((int)stageOffset, (int)size)) && - !KernelMemoryCompatExports.TryReadPrtBacking(_backing, guestAddress, - _staging.Mapped.Slice((int)stageOffset, (int)size))) + if (!ResidentImageBacking.TryRead(_backing, guestAddress, _staging.Mapped.Slice((int)stageOffset, (int)size))) { throw SubmissionScheduler.Fatal( $"Could not read the mapped guest image backing: address=0x{guestAddress:X16} size=0x{size:X16} range_backed={_backing.IsBackedRange(guestAddress, size)} first_byte_backed={_backing.IsBackedRange(guestAddress, 1)} last_byte_backed={_backing.IsBackedRange(guestAddress + size - 1, 1)} tick={_scheduler.CurrentTick}."); diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Draws.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Draws.cs index 4998a62d9..c23d10780 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Draws.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Draws.cs @@ -38,7 +38,7 @@ public sealed partial class GpuCommandInterpreter }; internal void DrawIndexed(ulong packetAddress, uint opcode, uint indexCount, ulong indexAddress, uint instanceCount = 0, int baseVertex = 0, uint firstInstance = 0, DrawOffsetSource offsetSource = DrawOffsetSource.Packet, - bool baseVertexInRegister = false, bool firstInstanceInRegister = false, int startInstanceUserData = -1) + bool baseVertexInRegister = false, bool firstInstanceInRegister = false, int startInstanceUserData = -1, int baseVertexUserData = -1) { if (instanceCount == 0) { @@ -53,7 +53,8 @@ internal void DrawIndexed(ulong packetAddress, uint opcode, uint indexCount, ulo if (Rendering.ScissorTrace.Instance is { Active: true } trace) trace.DrawIssued(TypedRegisters, SubmitId, QueueId, packetAddress); _host.DrawIndexed(SubmitId, new DrawIndexedArguments(packetAddress, opcode, indexCount, indexAddress, IndexTypeAndSize, instanceCount, baseVertex, firstInstance, offsetSource, - StartInstanceUserData: startInstanceUserData, BaseVertexInRegister: baseVertexInRegister, FirstInstanceInRegister: firstInstanceInRegister)); + StartInstanceUserData: startInstanceUserData, BaseVertexInRegister: baseVertexInRegister, FirstInstanceInRegister: firstInstanceInRegister, + BaseVertexUserData: baseVertexUserData)); } internal void DrawIndexedOffset(ulong packetAddress, uint indexOffset, uint indexCount) @@ -63,7 +64,7 @@ internal void DrawIndexedOffset(ulong packetAddress, uint indexOffset, uint inde } internal void DrawAuto(ulong packetAddress, uint opcode, uint vertexCount, uint instanceCount = 0, uint firstVertex = 0, uint firstInstance = 0, DrawOffsetSource offsetSource = DrawOffsetSource.Packet, - bool firstVertexInRegister = false, bool firstInstanceInRegister = false, int startInstanceUserData = -1) + bool firstVertexInRegister = false, bool firstInstanceInRegister = false, int startInstanceUserData = -1, int baseVertexUserData = -1) { if (instanceCount == 0) { @@ -73,9 +74,26 @@ internal void DrawAuto(ulong packetAddress, uint opcode, uint vertexCount, uint if (Rendering.ScissorTrace.Instance is { Active: true } trace) trace.DrawIssued(TypedRegisters, SubmitId, QueueId, packetAddress); _host.DrawAuto(SubmitId, new DrawAutoArguments(packetAddress, opcode, vertexCount, instanceCount, firstVertex, firstInstance, offsetSource, startInstanceUserData, - FirstVertexInRegister: firstVertexInRegister, FirstInstanceInRegister: firstInstanceInRegister)); + FirstVertexInRegister: firstVertexInRegister, FirstInstanceInRegister: firstInstanceInRegister, BaseVertexUserData: baseVertexUserData)); } + // Which indirect draws leave their instance count in NUM_INSTANCES for later direct draws. Hardware CP indirect + // draws write it (AMD PAL re-emits it after them), and a record read on the CPU passes it on by default. A record + // resolved on the GPU is not read back later by default: read on the CPU at a later direct draw it can hold data + // the GPU has not written yet (Ghost of Yotei: float data such as 0x3F800000, ~1e9 instances, a lost device). + // SHARPEMU_INDIRECT_INSTANCE_INHERIT=1 reads that record too, =0 leaves NUM_INSTANCES alone for every indirect draw. + internal IndirectInstanceInheritance IndirectInstanceInherit { get; set; } = + ParseIndirectInstanceInheritance(Environment.GetEnvironmentVariable("SHARPEMU_INDIRECT_INSTANCE_INHERIT")); + + internal static IndirectInstanceInheritance ParseIndirectInstanceInheritance(string? mode) => mode switch + { + "0" => IndirectInstanceInheritance.None, + "1" => IndirectInstanceInheritance.All, + _ => IndirectInstanceInheritance.CpuReadRecords, + }; + + internal enum IndirectInstanceInheritance { None, CpuReadRecords, All } + // Indirect arguments are read from guest memory now, as the packet executes. internal void DrawIndirect(ulong packetAddress, uint opcode, uint dataOffset, uint drawInitiator, bool indexed, DrawRegisterLocations locations = default) @@ -130,14 +148,19 @@ internal void DrawIndirectMulti(ulong packetAddress, uint opcode, uint dataOffse } // A value the CP writes to a register reaches the shader there, which adds it to its vertex or instance id; the - // draw then counts those from 0. A start instance in the vertex program's live user data stays in the arguments - // instead: the draw passes it as its first instance and the program stores its base instance in that user data - // (StartInstanceUserData), so the host can leave the arguments on the GPU. A named base vertex, or a start instance - // in another register, takes its value here, so the draw reads its arguments now. + // draw then counts those from 0. A base vertex or start instance in the vertex program's live user data stays in + // the arguments instead: the draw passes it as its base vertex or first instance and the program stores + // gl_BaseVertex or gl_BaseInstance in that user data (BaseVertexUserData, StartInstanceUserData), so the host can + // leave the arguments on the GPU, where a shader may have written them. One named in another register takes its + // value here, so the draw reads its arguments now. private void DrawIndirectArguments(ulong packetAddress, uint opcode, ulong argumentsAddress, bool indexed, DrawRegisterLocations locations, uint drawIndex) { - var startInstanceUserData = StartInstanceUserData(locations.StartInstance); - var vertexInRegister = DrawRegisterLocations.Names(locations.BaseVertex); + var startInstanceUserData = VertexUserDataIndex(locations.StartInstance); + // Only a plain vertex program stores gl_BaseVertex in its user data; a tessellation or mesh stage reads the register. + var baseVertexUserData = Rendering.RenderExecutor.RunsPlainVertexProgram(TypedRegisters.Context.ShaderStages) + ? VertexUserDataIndex(locations.BaseVertex) + : -1; + var vertexInRegister = DrawRegisterLocations.Names(locations.BaseVertex) && baseVertexUserData < 0; var instanceInRegister = DrawRegisterLocations.Names(locations.StartInstance) && startInstanceUserData < 0; var registersNeedArguments = vertexInRegister || instanceInRegister; if (!indexed) @@ -146,11 +169,11 @@ private void DrawIndirectArguments(ulong packetAddress, uint opcode, ulong argum { WriteDrawRegister(locations.DrawIndex, drawIndex); // The host reads the four arguments on the GPU, or itself when the draw needs the counts. - _deferredInstanceCountAddress = argumentsAddress + 4; + if (IndirectInstanceInherit == IndirectInstanceInheritance.All) _deferredInstanceCountAddress = argumentsAddress + 4; if (Rendering.ScissorTrace.Instance is { Active: true } gpuTrace) gpuTrace.DrawIssued(TypedRegisters, SubmitId, QueueId, packetAddress); _host.DrawAuto(SubmitId, new DrawAutoArguments(packetAddress, opcode, uint.MaxValue, 1, 0, 0, - DrawOffsetSource.IndirectArguments, startInstanceUserData, argumentsAddress)); + DrawOffsetSource.IndirectArguments, startInstanceUserData, argumentsAddress, BaseVertexUserData: baseVertexUserData)); return; } @@ -158,11 +181,13 @@ private void DrawIndirectArguments(ulong packetAddress, uint opcode, ulong argum var instanceCount = ReadDword(argumentsAddress + 4); var startVertex = ReadDword(argumentsAddress + 8); var startInstance = ReadDword(argumentsAddress + 12); - InstanceCount = instanceCount; - WriteDrawRegisters(locations, startVertex, startInstance, drawIndex, instanceInRegister); + if (IndirectInstanceInherit != IndirectInstanceInheritance.None) InstanceCount = instanceCount; + WriteDrawRegisters(locations, startVertex, startInstance, drawIndex, vertexInRegister, instanceInRegister); + // A record with no instances draws nothing; a zero passed on would mean "use NUM_INSTANCES". + if (instanceCount == 0) return; DrawAuto(packetAddress, opcode, vertexCount, instanceCount, vertexInRegister ? 0 : startVertex, instanceInRegister ? 0 : startInstance, DrawOffsetSource.IndirectArguments, vertexInRegister, instanceInRegister, - startInstanceUserData); + startInstanceUserData, baseVertexUserData); return; } @@ -172,13 +197,13 @@ private void DrawIndirectArguments(ulong packetAddress, uint opcode, ulong argum // The host reads the five arguments on the GPU. It draws from the whole index // range; the arguments pick the indices. The host falls back to reading them // itself when the draw needs the counts. - _deferredInstanceCountAddress = argumentsAddress + 4; + if (IndirectInstanceInherit == IndirectInstanceInheritance.All) _deferredInstanceCountAddress = argumentsAddress + 4; if (Rendering.ScissorTrace.Instance is { Active: true } trace) trace.DrawIssued(TypedRegisters, SubmitId, QueueId, packetAddress); _host.DrawIndexed(SubmitId, new DrawIndexedArguments( packetAddress, opcode, gpuIndexCount, IndexBaseAddress, IndexTypeAndSize, 1, 0, 0, DrawOffsetSource.IndirectArguments, argumentsAddress, UnboundedIndexBuffer: IndexBufferSize == 0, - StartInstanceUserData: startInstanceUserData)); + StartInstanceUserData: startInstanceUserData, BaseVertexUserData: baseVertexUserData)); return; } @@ -189,22 +214,28 @@ private void DrawIndirectArguments(ulong packetAddress, uint opcode, ulong argum var indexedStartInstance = ReadDword(argumentsAddress + 16); var indexAddress = IndexBaseAddress + (startIndex * IndexElementSize); var indexCount = IndexBufferSize != 0 ? Math.Min(indexCountPerInstance, IndexBufferSize) : indexCountPerInstance; - InstanceCount = indexedInstanceCount; + if (IndirectInstanceInherit != IndirectInstanceInheritance.None) InstanceCount = indexedInstanceCount; if (IndexBufferSize == 0 && IndexTypeAndSize is 0 or 1) { LearnIndexExtent(startIndex, indexCountPerInstance); } - WriteDrawRegisters(locations, baseVertex, indexedStartInstance, drawIndex, instanceInRegister); + WriteDrawRegisters(locations, baseVertex, indexedStartInstance, drawIndex, vertexInRegister, instanceInRegister); + if (indexedInstanceCount == 0) return; DrawIndexed(packetAddress, opcode, indexCount, indexAddress, indexedInstanceCount, vertexInRegister ? 0 : unchecked((int)baseVertex), instanceInRegister ? 0 : indexedStartInstance, DrawOffsetSource.IndirectArguments, vertexInRegister, instanceInRegister, - startInstanceUserData); + startInstanceUserData, baseVertexUserData); } - private void WriteDrawRegisters(DrawRegisterLocations locations, uint baseVertex, uint startInstance, uint drawIndex, bool instanceInRegister) + private void WriteDrawRegisters(DrawRegisterLocations locations, uint baseVertex, uint startInstance, uint drawIndex, bool vertexInRegister, + bool instanceInRegister) { - WriteDrawRegister(locations.BaseVertex, baseVertex); + if (vertexInRegister) + { + WriteDrawRegister(locations.BaseVertex, baseVertex); + } + if (instanceInRegister) { WriteDrawRegister(locations.StartInstance, startInstance); @@ -213,9 +244,9 @@ private void WriteDrawRegisters(DrawRegisterLocations locations, uint baseVertex WriteDrawRegister(locations.DrawIndex, drawIndex); } - // The vertex program's user data index of a start instance register, or -1 when the register is not one of the - // user data registers the program loads. - private int StartInstanceUserData(uint location) + // The vertex program's user data index of a base vertex or start instance register, or -1 when the register is not + // one of the user data registers the program loads. + private int VertexUserDataIndex(uint location) { var index = location - ShaderRegisterOffset.SpiShaderUserDataGs0; return index < TypedRegisters.Shader.Vertex.GeometryResource2.UserScalarCount ? (int)index : -1; diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs index 2946b69f3..b0259b07f 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.cs @@ -116,9 +116,9 @@ internal void SetPacketHandlers(PacketHandler?[] handlers) public ulong DispatchIndirectArgumentsBase { get; private set; } - // Persistent draw state: indirect draws update it for later draws. An indirect draw - // resolved on the GPU leaves the count in guest memory; it is read only if a later - // draw needs it. + // Persistent draw state (NUM_INSTANCES). Indirect draws update it for later draws as + // IndirectInstanceInherit says; with All, one resolved on the GPU leaves the count in + // guest memory, read only if a later draw needs it. public uint InstanceCount { get diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs index eb131aa38..fdec4e545 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs @@ -35,7 +35,10 @@ public readonly record struct DrawIndexedArguments( // The indirect packet named a shader register for the base vertex or the start instance: the // value is in that register, and BaseVertex or FirstInstance is 0. bool BaseVertexInRegister = false, - bool FirstInstanceInRegister = false); + bool FirstInstanceInRegister = false, + // The vertex program's user data index the indirect packet names for the base vertex, or -1 (StartInstanceUserData + // likewise): the draw passes BaseVertex and the program stores it there. + int BaseVertexUserData = -1); // Arguments of a non-indexed draw as the packet stream describes them. public readonly record struct DrawAutoArguments( @@ -53,7 +56,8 @@ public readonly record struct DrawAutoArguments( // The indirect packet named a shader register for the start vertex or the start instance: the // value is in that register, and FirstVertex or FirstInstance is 0. bool FirstVertexInRegister = false, - bool FirstInstanceInRegister = false); + bool FirstInstanceInRegister = false, + int BaseVertexUserData = -1); public enum EndOfPipeWriteKind { diff --git a/src/SharpEmu.Libs/Gpu/Images/CachedImage.Transfers.cs b/src/SharpEmu.Libs/Gpu/Images/CachedImage.Transfers.cs index 5f48cc431..65a0d85f7 100644 --- a/src/SharpEmu.Libs/Gpu/Images/CachedImage.Transfers.cs +++ b/src/SharpEmu.Libs/Gpu/Images/CachedImage.Transfers.cs @@ -554,20 +554,25 @@ public static uint CalculateRowsPerCopy(ulong rowSize, uint rows, ulong capacity } // A storage image holds the stencil bytes while the shader runs; the attachment stays the owner. - public CachedImage CreateStencilStorageImage() + // `width` x `height` is the storage view the shader binds, which can cover only the top-left + // part of the attachment (a dynamic-resolution pass): the shader then sees that size. + public CachedImage CreateStencilStorageImage(uint width, uint height) { if ((ViewFormatRules.FullAspects(Backing.Format) & ImageAspectFlags.StencilBit) == 0 || - Backing.ImageType != ImageType.Type2D || Backing.Samples != 1 || Backing.MipLevels != 1) + Backing.ImageType != ImageType.Type2D || Backing.Samples != 1 || Backing.MipLevels != 1 || + width == 0 || height == 0 || width > Backing.Extent.Width || height > Backing.Extent.Height) { - throw SubmissionScheduler.Fatal("Stencil storage needs a single-sample, single-level 2D stencil image."); + throw SubmissionScheduler.Fatal( + $"Stencil storage needs a single-sample, single-level 2D stencil image covering the view: " + + $"view={width}x{height} attachment={Backing.Extent.Width}x{Backing.Extent.Height} mips={Backing.MipLevels} samples={Backing.Samples}."); } var description = ImageDescription.Create(); description.PixelFormat = Format.R8Uint; description.GuestFormat = GuestPixelFormat.Bits8UInt; - description.Extent = Backing.Extent; + description.Extent = new Extent3D(width, height, 1); description.Resources = new SubresourceCount(1, Backing.Layers); - description.Pitch = Backing.Extent.Width; + description.Pitch = width; description.BytesPerBlock = 1; return new CachedImage(_device, _scheduler, _guestBacking, description); } @@ -578,11 +583,12 @@ public void CopyStencilStorage(CachedImage storage, GpuBuffer buffer, bool write Backing.ImageType != ImageType.Type2D || Backing.Samples != 1 || Backing.MipLevels != 1 || storage.Backing.Format is not (Format.R8Uint or Format.R8Unorm) || storage.Backing.ImageType != ImageType.Type2D || storage.Backing.Samples != 1 || storage.Backing.MipLevels != 1 || storage.Backing.Layers != Backing.Layers || - storage.Backing.Extent.Width != Backing.Extent.Width || storage.Backing.Extent.Height != Backing.Extent.Height) + storage.Backing.Extent.Width > Backing.Extent.Width || storage.Backing.Extent.Height > Backing.Extent.Height) { throw SubmissionScheduler.Fatal("The stencil storage image does not match its attachment."); } + // Only the storage's region moves: the rest of the plane keeps its stencil values. if (writeBack) CopyThroughBuffer(storage, buffer, ImageAspectFlags.ColorBit, ImageAspectFlags.StencilBit); else @@ -619,8 +625,9 @@ private void CopyThroughBuffer(CachedImage source, GpuBuffer buffer, ImageAspect Transition(AccessFlags.TransferWriteBit, null, command); for (uint level = 0; level < levels; level++) { - var width = Math.Max(source.Backing.Extent.Width >> (int)level, 1); - var height = Math.Max(source.Backing.Extent.Height >> (int)level, 1); + // The copy covers the region both images have, from their top-left corner. + var width = Math.Max(Math.Min(source.Backing.Extent.Width, Backing.Extent.Width) >> (int)level, 1); + var height = Math.Max(Math.Min(source.Backing.Extent.Height, Backing.Extent.Height) >> (int)level, 1); var sourceDepth = source.Backing.ImageType == ImageType.Type3D ? Math.Max(source.Backing.Extent.Depth >> (int)level, 1) : source.Backing.Layers; var destinationDepth = Backing.ImageType == ImageType.Type3D ? Math.Max(Backing.Extent.Depth >> (int)level, 1) : Backing.Layers; var slices = Math.Min(sourceDepth, destinationDepth); diff --git a/src/SharpEmu.Libs/Gpu/Images/CachedImage.cs b/src/SharpEmu.Libs/Gpu/Images/CachedImage.cs index 6bf5792cc..9a69d6112 100644 --- a/src/SharpEmu.Libs/Gpu/Images/CachedImage.cs +++ b/src/SharpEmu.Libs/Gpu/Images/CachedImage.cs @@ -141,7 +141,7 @@ public CachedImage(GpuDeviceInfo device, SubmissionScheduler scheduler, IGuestBa Backing.Format = Description.PixelFormat; Backing.ImageType = HostImageType(Description.Type); - Backing.Extent = Description.Extent; + Backing.Extent = Description.HostExtent; Backing.GuestPitch = Description.Pitch; Backing.Layers = Description.IsVolume ? 1 : Description.Resources.Layers; Backing.MipLevels = Math.Min(Description.Resources.Levels, MipChainLevels(Backing.ImageType, Backing.Extent)); @@ -549,14 +549,25 @@ public bool Overlaps(ulong address, ulong size, bool pages = false) => pages public bool IsWatched => WatchBegin != 0 && WatchEnd != 0; - public ulong AccountedSize => Backing.Exists ? (Description.Data.Size + 1023) & ~1023UL : 0; + public ulong AccountedSize => Backing.Exists ? (Description.HeldGuestSize + 1023) & ~1023UL : 0; + + // The leading bytes of Description.Data the image's levels read from guest memory. An image of a + // streamed texture's resident levels reads only the part that holds them; the unmapped rest of + // its range is not read or hashed. Set by the upload that stages that part. + internal ulong GuestReadSize + { + get => _guestReadSize != 0 ? Math.Min(_guestReadSize, Description.Data.Size) : Description.Data.Size; + set => _guestReadSize = value; + } + + private ulong _guestReadSize; // Hashes the first and last partial tracker page of the guest data through the backing alias. public ulong HashGuestEdges() { const ulong pageMask = TrackerLayout.PageBytes - 1; var range = Description.Data; - var end = range.End; + var end = range.Address + GuestReadSize; var headEnd = Math.Min(end, (range.Address + pageMask) & ~pageMask); var tailBegin = Math.Max(range.Address, end & ~pageMask); var headSize = headEnd - range.Address; diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Lookup.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Lookup.cs index 29224d6b0..21a0bdf5b 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Lookup.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Lookup.cs @@ -252,7 +252,7 @@ private static bool SameDescription(in ImageDescription left, in ImageDescriptio left.GuestFormat != right.GuestFormat || left.Type != right.Type || left.Extent.Width != right.Extent.Width || left.Extent.Height != right.Extent.Height || left.Extent.Depth != right.Extent.Depth || left.Resources != right.Resources || - left.Pitch != right.Pitch || left.BytesPerBlock != right.BytesPerBlock || + left.Pitch != right.Pitch || left.BytesPerBlock != right.BytesPerBlock || left.FirstLevel != right.FirstLevel || left.Samples != right.Samples || left.TileMode != right.TileMode || left.Bgra16 != right.Bgra16) { return false; diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Metadata.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Metadata.cs index 58a66a9e8..19bd143ed 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Metadata.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Metadata.cs @@ -469,12 +469,21 @@ public bool IsMetadata(ulong address) return _surfaceMetadata.TryGetValue(address, out var found) && !found.Invalidated && found.Kind != SurfaceMetadataKind.PendingDcc; } + // DCC tracks its own slice count. HTile tracks any slice (SurfaceMetadata keeps the slices past 31 apart): a depth + // array can have more layers than 32 (a game can bind one of 36). CMask and FMask keep 32. + private static uint SliceLimit(SurfaceMetadata metadata) => metadata.Kind switch + { + SurfaceMetadataKind.Dcc => metadata.DccSliceCount, + SurfaceMetadataKind.HTile => uint.MaxValue, + _ => 32, + }; + public bool IsMetadataCleared(ulong address, uint slice, out uint fillValue) { fillValue = 0; using var held = _lock.Read(); if (!_surfaceMetadata.TryGetValue(address, out var found) || found.Invalidated || found.Kind == SurfaceMetadataKind.PendingDcc || - slice >= (found.Kind == SurfaceMetadataKind.Dcc ? found.DccSliceCount : 32)) + slice >= SliceLimit(found)) { return false; } @@ -674,7 +683,7 @@ public bool SetMetadataSlice(ulong address, uint slice, bool isClear) using var held = _lock.Hold(); if (!_surfaceMetadata.TryGetValue(address, out var found) || found.Invalidated || found.Kind == SurfaceMetadataKind.PendingDcc || - slice >= (found.Kind == SurfaceMetadataKind.Dcc ? found.DccSliceCount : 32)) + slice >= SliceLimit(found)) { return false; } diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Overlap.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Overlap.cs index 9e9bd15bd..2200b7e85 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Overlap.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Overlap.cs @@ -244,6 +244,13 @@ private void CopyIntoMip(ResourceSlotIdentifier destinationImageIdentifier, Reso var destination = _slots[destinationImageIdentifier]; var source = _slots[sourceImageIdentifier]; WatchImage(destinationImageIdentifier); + // A description can match the source at a level its backing does not hold (CachedImage keeps no more levels + // than the backing's extent has): the destination keeps what it read from the guest. + if (mip >= destination.Backing.MipLevels) + { + return; + } + if (source.IsBufferModified || source.Backing.Samples != destination.Backing.Samples) { throw SubmissionScheduler.Fatal($"The mip copy source ownership or sample count is invalid: bufferModified={source.IsBufferModified} sourceSamples={source.Backing.Samples} destinationSamples={destination.Backing.Samples}."); @@ -461,6 +468,21 @@ private OverlapResolution ResolveOverlap(in ImageDescription requested, ImageRol // in it is past the removal window in between. As in collection, an image used this frame is not stale. var usedThisFrame = cached.Registered && _recencyQueue.GetLastUseTick(cached.RecencyEntryIndex) >= _collectionTick; var safeToDelete = !usedThisFrame && currentTick - Math.Min(currentTick, cached.LastAccessTick) > TicksBeforeRemoval; + if (requested.FirstLevel != 0 || cachedInfo.FirstLevel != 0) + { + // An image of a streamed chain's resident levels shares only an identical chain (the + // same-backing match). It is a copy of guest memory that a lookup recreates cheaply, so + // another resource over its range replaces it; a request for resident levels over + // another image is a separate texture (the lookup took the whole chain when that image + // holds GPU contents). + if (cachedInfo.FirstLevel != 0 && !cached.IsGpuModified) + { + cached.Binding.NeedsRebind |= cached.Binding.IsBound || cached.Binding.IsTarget; + ReleaseImage(cachedImageIdentifier); + } + + return new OverlapResolution(mergedImageIdentifier); + } var requestedBlock = requested.BytesPerBlock * requested.Samples; var cachedBlock = cachedInfo.BytesPerBlock * cachedInfo.Samples; var requestedBlockExtent = requested.BlockExtent; diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.PieceUpload.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.PieceUpload.cs index c7e1570ad..4cd6369e8 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.PieceUpload.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.PieceUpload.cs @@ -58,7 +58,7 @@ public sealed partial class GuestImageCache var length = (int)Math.Min((ulong)chunk.Length, tile.TiledSize - done); var span = chunk.AsSpan(0, length); var pieceAddress = address + tile.TiledOffset + done; - if (!_backing.TryReadBacking(pieceAddress, span) && !KernelMemoryCompatExports.TryReadPrtBacking(_backing, pieceAddress, span)) + if (!ResidentImageBacking.TryRead(_backing, pieceAddress, span)) { Interlocked.Exchange(ref failed, 1); state.Stop(); diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Transfers.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Transfers.cs index 629bdf7f7..82682a5f6 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Transfers.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.Transfers.cs @@ -50,6 +50,31 @@ private static ulong LinearSizeOf(List tiles) return size; } + // The leading bytes of the image's guest range its levels read. A streamed texture's image holds + // only the levels from FirstLevel, and a tiled chain lays those at the start of the range with + // level 0 last, so the mapped prefix is all the upload needs: it neither reads nor invents the + // rest. Every other image reads its whole range. + private static ulong GuestReadSize(in ImageDescription info, ColorTransferPlan plan) + { + if (info.FirstLevel == 0 || !plan.Valid || !plan.Tiled || plan.Tiles.Count == 0) + { + return info.Data.Size; + } + + ulong end = 0; + foreach (var tile in plan.Tiles) + { + end = Math.Max(end, tile.TiledOffset + tile.TiledSize); + } + + return Math.Min(end, info.Data.Size); + } + + private static ulong GuestReadSize(CachedImage image, in ImageRequest request) => + image.Description.FirstLevel == 0 || request.Role == ImageRole.DepthTarget || image.DepthOwner.IsValid + ? image.Description.Data.Size + : GuestReadSize(image.Description, PlanColorTransfer(image, request.Role, TransferDirection.Upload)); + private static ColorTransferPlan PlanColorTransfer(CachedImage image, ImageRole role, TransferDirection direction) { ref readonly var info = ref image.Description; @@ -109,8 +134,10 @@ private static ColorTransferPlan PlanColorTransfer(CachedImage image, ImageRole plan.SwapBgra16 = info.Bgra16; } + // The layout covers the whole guest chain; the levels before FirstLevel are dropped below. + var guestLevels = info.FirstLevel + info.Resources.Levels; var rowPitch = direction == TransferDirection.Upload && role == ImageRole.Texture ? info.Pitch : 0u; - plan.Layout = TextureTransferLayout.Compute(format, info.Extent.Width, info.Extent.Height, info.Resources.Levels, layers, info.TileMode, info.Data.Size, allowDepthTile, volume, owner, rowPitch); + plan.Layout = TextureTransferLayout.Compute(format, info.Extent.Width, info.Extent.Height, guestLevels, layers, info.TileMode, info.Data.Size, allowDepthTile, volume, owner, rowPitch); plan.Regions = plan.Layout.BuildCopies(); if (info.IsDepth) { @@ -124,7 +151,7 @@ private static ColorTransferPlan PlanColorTransfer(CachedImage image, ImageRole plan.Tiled = plan.Layout.Surface.Description.TileMode != GuestTileMode.Linear; if (plan.Tiled) { - if (!plan.Layout.TryBuildTileTransfers(info.Data.Size, plan.Regions, info.Resources.Levels, out var tiles)) + if (!plan.Layout.TryBuildTileTransfers(info.Data.Size, plan.Regions, guestLevels, out var tiles)) { return plan; } @@ -132,6 +159,11 @@ private static ColorTransferPlan PlanColorTransfer(CachedImage image, ImageRole plan.Tiles = tiles; } + if (info.FirstLevel != 0) + { + KeepResidentLevels(plan, info.FirstLevel); + } + // Guest levels past the host mip chain (CachedImage.MipChainLevels) have no host level to move: // an upload leaves them out, a download leaves their guest bytes as they are. DropLevelsWithoutHostLevel(plan, image.Backing.MipLevels); @@ -174,6 +206,39 @@ private static void DropLevelsWithoutHostLevel(ColorTransferPlan plan, uint host plan.Tiles.RemoveAll(tile => !offsets.Contains(tile.LinearOffset)); } + // Only the resident levels have host levels: guest level L lands on host level L - firstLevel. + // The levels before it drop from the front; their tile transfers go by linear offset, as in + // DropLevelsWithoutHostLevel, and the remaining ones keep their linear offsets. + private static void KeepResidentLevels(ColorTransferPlan plan, uint firstLevel) + { + var kept = 0; + for (var index = 0; index < plan.Regions.Count; index++) + { + var region = plan.Regions[index]; + if (region.ImageSubresource.MipLevel < firstLevel) + { + continue; + } + + region.ImageSubresource.MipLevel -= firstLevel; + plan.Regions[kept++] = region; + } + + plan.Regions.RemoveRange(kept, plan.Regions.Count - kept); + if (!plan.Tiled) + { + return; + } + + var offsets = new HashSet(plan.Regions.Count); + foreach (var region in plan.Regions) + { + offsets.Add(region.BufferOffset); + } + + plan.Tiles.RemoveAll(tile => !offsets.Contains(tile.LinearOffset)); + } + private static Exception InvalidAttachmentUpload(in ImageDescription info, CachedImage image) => SubmissionScheduler.Fatal( $"The color-attachment upload is invalid: address=0x{info.Data.Address:X16} size=0x{info.Data.Size:X} layers={info.Resources.Layers} samples={info.Samples} backingSamples={image.Backing.Samples} compression={info.Metadata.Compression}."); @@ -182,7 +247,8 @@ private static ImageDownloadPlan PlanDownload(CachedImage image) { ref readonly var info = ref image.Description; var plan = new ImageDownloadPlan { Depth = info.IsDepth }; - if (info.Samples != 1 || image.Backing.Samples != 1) + // An image of a streamed texture's resident levels does not hold the guest chain it would write back. + if (info.Samples != 1 || image.Backing.Samples != 1 || info.FirstLevel != 0) { return plan; } @@ -387,10 +453,11 @@ private void UploadFromBuffer(CachedImage image, in ImageRequest request, GpuBuf if (plan.Tiled) plan.Tiles.RemoveRange(0, checked((int)firstLayer)); } - var linear = new TilerBufferSpan(source.Handle, sourceOffset, info.Data.Size); + var readSize = GuestReadSize(info, plan); + var linear = new TilerBufferSpan(source.Handle, sourceOffset, readSize); if (plan.Tiled) { - linear = _tiler.Detile(source.Handle, sourceOffset, info.Data.Size, plan.LinearSize, System.Runtime.InteropServices.CollectionsMarshal.AsSpan(plan.Tiles)); + linear = _tiler.Detile(source.Handle, sourceOffset, readSize, plan.LinearSize, System.Runtime.InteropServices.CollectionsMarshal.AsSpan(plan.Tiles)); } if (plan.SwapBgra16) @@ -510,7 +577,9 @@ private void PopulateFromGuest(ResourceSlotIdentifier imageIdentifier, in ImageR : null; var pieceHashes = piecePlan != null ? HashGuestPieces(image.Description.Data, piecePlan.Tiles) : null; var backingBytes = SnapshotVolumeBacking(image); - var (source, sourceOffset) = _bufferCache.ObtainBufferForImage(image.Description.Data.Address, image.Description.Data.Size); + var readSize = GuestReadSize(image, request); + image.GuestReadSize = readSize; + var (source, sourceOffset) = _bufferCache.ObtainBufferForImage(image.Description.Data.Address, readSize); sourceFinished = measureUpload ? System.Diagnostics.Stopwatch.GetTimestamp() : 0; UploadFromBuffer(image, request, source, sourceOffset, backingBytes, firstLayer); image.SetGuestPieceHashes(pieceHashes); diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.cs b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.cs index d2955903c..9c14dabca 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestImageCache.cs @@ -255,6 +255,11 @@ private ResourceSlotIdentifier LookUpImage(ref ImageRequest request, bool exactF $"cpuDirty={cached.IsCpuDirty} bufferDirty={cached.IsBufferModified} gpuDirty={cached.IsGpuModified} target={cached.Uses.RenderTarget}"); } } + if (request.Description.FirstLevel != 0 && HoldsWholeChain(request, candidates)) + { + request = ImageRequestBuilders.WithWholeMipChain(request); + } + foreach (var imageIdentifier in candidates) { if (HasSameBacking(_slots[imageIdentifier].Description, request.Description, exactFormat)) @@ -291,7 +296,10 @@ private ResourceSlotIdentifier LookUpImage(ref ImageRequest request, bool exactF { result = ResourceSlotIdentifier.Invalid; } - else if (resolved.Description.Resources < request.Description.Resources) + else if (resolved.Description.Resources < request.Description.Resources || + resolved.Description.FirstLevel > request.Description.FirstLevel || + resolved.Description.FirstLevel + resolved.Description.Resources.Levels < + request.Description.FirstLevel + request.Description.Resources.Levels) { ReleaseImage(result); result = ResourceSlotIdentifier.Invalid; @@ -387,6 +395,12 @@ private ResourceSlotIdentifier LookUpImage(ref ImageRequest request, bool exactF { request.View = request.View with { BaseLevel = (uint)viewMip }; } + else + { + // The image starts at an earlier guest level than the request (a texture of a streamed + // chain's resident levels found the whole chain): its view starts that many levels later. + request.View = ImageRequestBuilders.RebaseView(request.View, request.Description.FirstLevel - image.Description.FirstLevel); + } if (viewLayer >= 0) { @@ -404,6 +418,29 @@ private ResourceSlotIdentifier LookUpImage(ref ImageRequest request, bool exactF return result; } + // A texture of a chain's resident levels is the whole chain once that memory is all mapped + // (a fully loaded or rendered chain sampled from a lower mip), and whenever an image over its + // range holds GPU-written contents the guest memory does not show: the request then shares + // that image instead of reading guest memory into a separate one. + private bool HoldsWholeChain(in ImageRequest request, in ImageQueryResults candidates) + { + var range = request.Description.Data; + if (_backing.IsBackedRange(range.Address, range.Size)) + { + return true; + } + + foreach (var candidate in candidates) + { + if (_slots.TryGet(candidate) is { } image && (image.IsGpuModified || image.Uses.RenderTarget || image.Uses.Storage)) + { + return true; + } + } + + return false; + } + // Uploads guest changes of an image that was found earlier. public void RefreshImage(ResourceSlotIdentifier imageIdentifier) { @@ -427,6 +464,32 @@ public bool TryGetImage(ResourceSlotIdentifier imageIdentifier, out CachedImage return found != null; } + // Whether the texels of an image over this range could be read from the guest: the range is valid and its first page + // is mapped (ResidentImageBacking reads a mapped prefix). A descriptor read from a table the guest no longer uses may + // name memory it has unmapped since. + public bool IsBackedImageRange(GuestSpan data) => ImageDescription.IsValidRange(data) && _backing.IsBackedRange(data.Address, 1); + + // The registered depth image that owns the stencil plane starting at this span, with the + // newest GPU write when several do (a copied depth buffer shares its source's plane). + public bool TryFindStencilOwner(GuestSpan plane, out ResourceSlotIdentifier owner) + { + using var held = _lock.Hold(); + var best = ResourceSlotIdentifier.Invalid; + long bestWrite = -1; + _slots.ForEach((identifier, image) => + { + if (image.Registered && !image.DepthOwner.IsValid && image.Description.IsDepth && image.Description.HasStencil && + image.Description.Stencil.Address == plane.Address && image.Description.Stencil.Size >= plane.Size && + image.GpuWriteSequence > bestWrite) + { + best = identifier; + bestWrite = image.GpuWriteSequence; + } + }); + owner = best; + return best.IsValid; + } + public CachedImage GetImage(ResourceSlotIdentifier imageIdentifier) { var image = _slots[imageIdentifier]; diff --git a/src/SharpEmu.Libs/Gpu/Images/GuestPixelFormats.cs b/src/SharpEmu.Libs/Gpu/Images/GuestPixelFormats.cs index a65a4fa0e..b1aa624d0 100644 --- a/src/SharpEmu.Libs/Gpu/Images/GuestPixelFormats.cs +++ b/src/SharpEmu.Libs/Gpu/Images/GuestPixelFormats.cs @@ -307,8 +307,9 @@ private readonly record struct FormatFacts( [ new(GuestPixelFormat.Bits8UNorm, 1, 0, 1, true, false), new(GuestPixelFormat.Bits8UScaled, 1, 0, 1, true, false), - new(GuestPixelFormat.Bits8SNorm, 0, 0, 1, false, false), + new(GuestPixelFormat.Bits8SNorm, 1, 0, 1, true, false), new(GuestPixelFormat.Bits8UInt, 1, 0, 1, true, true), + new(GuestPixelFormat.Bits8SInt, 1, 0, 1, true, false, true), new(GuestPixelFormat.Bits16UNorm, 2, 0, 2, true, false), new(GuestPixelFormat.Bits16SNorm, 2, 0, 2, true, false), new(GuestPixelFormat.Bits16UInt, 2, 0, 2, true, true), @@ -430,7 +431,9 @@ private readonly record struct RenderTargetLayoutFacts( private static readonly (GuestPixelFormat Guest, Format Host)[] HostFormats = [ (GuestPixelFormat.Bits8UNorm, Format.R8Unorm), + (GuestPixelFormat.Bits8SNorm, Format.R8SNorm), (GuestPixelFormat.Bits8UInt, Format.R8Uint), + (GuestPixelFormat.Bits8SInt, Format.R8Sint), (GuestPixelFormat.Bits16UNorm, Format.R16Unorm), (GuestPixelFormat.Bits16SNorm, Format.R16SNorm), (GuestPixelFormat.Bits16UInt, Format.R16Uint), diff --git a/src/SharpEmu.Libs/Gpu/Images/ImageDescription.cs b/src/SharpEmu.Libs/Gpu/Images/ImageDescription.cs index efb4077d2..5694d475e 100644 --- a/src/SharpEmu.Libs/Gpu/Images/ImageDescription.cs +++ b/src/SharpEmu.Libs/Gpu/Images/ImageDescription.cs @@ -95,6 +95,42 @@ public struct ImageDescription public bool Bgra16; public MipLevelLayouts MipLayout; + // The first guest level the host image holds. A streamed texture maps only its resident + // mips and its descriptor starts at the first of them; its image starts there too, while + // Extent and MipLayout keep describing the whole guest chain the data is laid out in. + // Resources.Levels counts the host levels, from this one. + public uint FirstLevel; + + // The host extent of the image's first level. + public readonly Extent3D HostExtent => FirstLevel == 0 + ? Extent + : new Extent3D(Math.Max(Extent.Width >> (int)FirstLevel, 1u), Math.Max(Extent.Height >> (int)FirstLevel, 1u), Extent.Depth); + + // The bytes of the guest range the image's levels occupy: the whole range, or for an image of + // resident levels only the span of those levels (the levels before FirstLevel are not part of + // the image and take no memory in the working-set accounting). + public readonly ulong HeldGuestSize + { + get + { + if (FirstLevel == 0) + { + return Data.Size; + } + + var begin = ulong.MaxValue; + ulong end = 0; + for (var level = FirstLevel; level < FirstLevel + Resources.Levels && level < MaxLevels; level++) + { + var layout = MipLayout[(int)level]; + begin = Math.Min(begin, layout.Offset); + end = Math.Max(end, layout.Offset + layout.Size); + } + + return end > begin && end <= Data.Size ? end - begin : Data.Size; + } + } + public static ImageDescription Create() => new() { HtileClearMask = uint.MaxValue, @@ -159,7 +195,10 @@ public readonly int FindMatchingMipLevel(in ImageDescription container) // Return the matching slice in the containing mip level, or -1 if none matches. public readonly int FindMatchingArraySlice(in ImageDescription container, int mip) { - if (!IsCompatible(container) || TileMode != container.TileMode || Type != container.Type || IsVolume || + // A view inside another image's chain is found by guest level; an image holding only the + // resident tail of its chain numbers its levels from another one, so it never matches. + if (FirstLevel != 0 || container.FirstLevel != 0 || + !IsCompatible(container) || TileMode != container.TileMode || Type != container.Type || IsVolume || Resources.Levels != 1 || Resources.Layers == 0 || container.Resources.Layers == 0 || mip < 0 || (uint)mip >= container.Resources.Levels || container.Resources.Levels > MaxLevels || !IsValidRange(Data) || !IsValidRange(container.Data) || Data.Address < container.Data.Address || Data.End > container.Data.End) @@ -361,6 +400,11 @@ public readonly void Validate() throw SubmissionScheduler.Fatal($"The image type is not a base type: type={(uint)Type}."); } + if (FirstLevel != 0 && (Samples != 1 || IsVolume || FirstLevel + Resources.Levels > MaxLevels)) + { + throw SubmissionScheduler.Fatal($"A resident-mip image needs a single-sample 2D chain: firstLevel={FirstLevel} levels={Resources.Levels} samples={Samples} type={Type}."); + } + if (Samples > 1 && Resources.Levels != 1) { throw SubmissionScheduler.Fatal($"A multisampled image cannot have mip levels: samples={Samples} levels={Resources.Levels}."); diff --git a/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.DepthTarget.cs b/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.DepthTarget.cs index 2d0d15da5..cd5c3da6b 100644 --- a/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.DepthTarget.cs +++ b/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.DepthTarget.cs @@ -173,11 +173,6 @@ private sealed class DepthTargetMemo { throw SubmissionScheduler.Fatal($"The HTile metadata address is invalid: htile=0x{depthWords.HtileBase:X16}."); } - - if (depthWords.SliceMax >= 32) - { - throw SubmissionScheduler.Fatal($"HTile clear tracking supports at most 32 slices: last={depthWords.SliceMax}."); - } } if (!depthWords.DepthSizeValid) diff --git a/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.Texture.cs b/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.Texture.cs index 5179c3de7..763fda131 100644 --- a/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.Texture.cs +++ b/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.Texture.cs @@ -55,6 +55,23 @@ private static Exception InvalidDescriptor(string message) => Atomic: image.Atomic, Atomic64: image.NumericClass == ImageNumericClass.Uint64); + // The unsigned format of a signed-integer one: the view of a write-only signed storage image the program writes as + // unsigned bits (ResourceMaterializer). Undefined for any other format. + private static Format UnsignedOfSigned(Format format) => format switch + { + Format.R8Sint => Format.R8Uint, + Format.R8G8Sint => Format.R8G8Uint, + Format.R8G8B8A8Sint => Format.R8G8B8A8Uint, + Format.R16Sint => Format.R16Uint, + Format.R16G16Sint => Format.R16G16Uint, + Format.R16G16B16A16Sint => Format.R16G16B16A16Uint, + Format.R32Sint => Format.R32Uint, + Format.R32G32Sint => Format.R32G32Uint, + Format.R32G32B32A32Sint => Format.R32G32B32A32Uint, + Format.A2B10G10R10SintPack32 => Format.A2B10G10R10UintPack32, + _ => Format.Undefined, + }; + private static TextureNumericClass NumericClassOf(ImageResource image) => image.NumericClass switch { ImageNumericClass.Uint or ImageNumericClass.Uint64 => TextureNumericClass.Uint, @@ -164,13 +181,15 @@ public static void PopulateTextureMipLayout(ref ImageDescription description) // The view follows the compiled module: a volume, a layer window to the last layer, or one layer. private static ImageViewDescription TextureView( in TextureDescriptorWords descriptor, in ShaderImageShape shape, Format format, bool shaderConversion, uint viewLevels, uint imageLayers, - ulong shaderHash, int imageIndex) + ulong shaderHash, int imageIndex, uint firstLevel) { + // The image's levels count from its first resident guest level. + var baseLevel = descriptor.BaseLevel - firstLevel; var mapping = shape.Storage || shaderConversion ? default : ViewFormatRules.ComponentMapping(DestinationSwizzle(descriptor)); var usage = shape.Storage ? ImageUsageFlags.StorageBit : ImageUsageFlags.SampledBit; if (shape.Volume) { - return WithMinLod(new ImageViewDescription(format, ImageViewType.Type3D, ImageAspectFlags.ColorBit, descriptor.BaseLevel, viewLevels, 0, 1, mapping, usage), descriptor, shape); + return WithMinLod(new ImageViewDescription(format, ImageViewType.Type3D, ImageAspectFlags.ColorBit, baseLevel, viewLevels, 0, 1, mapping, usage), descriptor, shape, firstLevel); } var baseLayer = descriptor.BaseArray; @@ -187,15 +206,16 @@ private static ImageViewDescription TextureView( var type = shape.OneDimensional ? shape.Arrayed ? ImageViewType.Type1DArray : ImageViewType.Type1D : shape.Arrayed ? ImageViewType.Type2DArray : ImageViewType.Type2D; - return WithMinLod(new ImageViewDescription(format, type, ImageAspectFlags.ColorBit, descriptor.BaseLevel, viewLevels, baseLayer, layerCount, mapping, usage), descriptor, shape); + return WithMinLod(new ImageViewDescription(format, type, ImageAspectFlags.ColorBit, baseLevel, viewLevels, baseLayer, layerCount, mapping, usage), descriptor, shape, firstLevel); } // MIN_LOD (4.8 fixed point, absolute mip levels) keeps sampling off mips a streamed texture has not // loaded yet; ignoring it sampled the unloaded mip 0 of Astro Bot's stadium sky and bloom spread its // garbage HDR values over the screen. Storage views address levels explicitly and are not clamped. - private static ImageViewDescription WithMinLod(ImageViewDescription view, in TextureDescriptorWords descriptor, in ShaderImageShape shape) + private static ImageViewDescription WithMinLod(ImageViewDescription view, in TextureDescriptorWords descriptor, in ShaderImageShape shape, uint firstLevel) { - var minLod = descriptor.MinLod / 256f; + // The view's levels are host levels, which start at the image's first guest level. + var minLod = descriptor.MinLod / 256f - firstLevel; if (shape.Storage || minLod <= view.BaseLevel) { return view; @@ -204,6 +224,31 @@ private static ImageViewDescription WithMinLod(ImageViewDescription view, in Tex return view with { MinLod = Math.Min(minLod, view.BaseLevel + view.LevelCount - 1) }; } + // The same texture as an image of the whole guest mip chain, viewed from the descriptor's base + // level: the request a texture gets when its larger mips are mapped or another image holds them. + public static ImageRequest WithWholeMipChain(in ImageRequest request) + { + var firstLevel = request.Description.FirstLevel; + if (firstLevel == 0) + { + return request; + } + + var whole = request; + whole.Description.Resources = new SubresourceCount(request.Description.Resources.Levels + firstLevel, request.Description.Resources.Layers); + whole.Description.FirstLevel = 0; + whole.View = RebaseView(request.View, firstLevel); + return whole; + } + + // A view of an image whose first level is `levels` guest levels lower than the view was built for. + public static ImageViewDescription RebaseView(in ImageViewDescription view, uint levels) => + levels == 0 ? view : view with + { + BaseLevel = view.BaseLevel + levels, + MinLod = view.MinLod == 0 ? 0 : view.MinLod + levels, + }; + public static uint DestinationSwizzle(in TextureDescriptorWords descriptor) => ViewFormatRules.PackDestinationSelect(descriptor.DestinationSelectX, descriptor.DestinationSelectY, descriptor.DestinationSelectZ, descriptor.DestinationSelectW); @@ -335,7 +380,9 @@ private static TextureRequestResolution BuildTexture(ReadOnlySpan words, i size = TileGeometry.TextureTotalSize(format, width, height, volume ? depth : imageLayers, levels, tile, volume); } - if (size.Size == 0 || size.Align == 0 || (address & (size.Align - 1UL)) != 0) + // A T# encodes its byte address in 256-byte units. The layout alignment describes a new surface + // allocation, not an addressed view inside one, and tiled offsets are relative to this base. + if (size.Size == 0 || size.Align == 0 || (address & 0xFFUL) != 0) { throw InvalidDescriptor( $"The texture footprint or alignment is invalid: address=0x{address:X16} size=0x{size.Size:X} align=0x{size.Align:X} format={(uint)format} tile={(uint)tile}."); @@ -351,7 +398,10 @@ private static TextureRequestResolution BuildTexture(ReadOnlySpan words, i // 64-bit texel (32_32 UINT) is declared R64 and views the same texels as one 64-bit integer. var storageViewFormat = storage && shape.Atomic64 ? Format.R64Uint - : storage && (shape.Atomic || format == GuestPixelFormat.Bits32SInt) ? Format.R32Uint : ViewFormatRules.SrgbStorageFormat(pixelFormat); + : storage && (shape.Atomic || format == GuestPixelFormat.Bits32SInt) ? Format.R32Uint + : storage && shape.NumericClass == TextureNumericClass.Uint && UnsignedOfSigned(pixelFormat) is var unsigned and not Format.Undefined + ? unsigned + : ViewFormatRules.SrgbStorageFormat(pixelFormat); var viewFormat = storage && storageViewFormat != Format.Undefined ? storageViewFormat : pixelFormat; var blockBytes = GuestPixelFormats.BlockCompressedBytes(format); var description = ImageDescription.Create(); @@ -385,8 +435,22 @@ private static TextureRequestResolution BuildTexture(ReadOnlySpan words, i PopulateTextureMipLayout(ref description); } + // A sampled texture whose descriptor starts past mip 0 never reads the levels before it, and a + // streamed texture has not even mapped them: the request holds only the levels from there. + // The image cache returns it to the whole chain when that memory is mapped, so a texture view + // of a lower mip of a rendered or fully loaded chain stays the same image (WithWholeMipChain). + var firstLevel = !storage && !volume && samples == 1 && baseLevel > 0 && baseLevel < levels && + description.Metadata.Kind == MetadataKind.None && !description.IsDepth + ? baseLevel + : 0u; + if (firstLevel != 0) + { + description.FirstLevel = firstLevel; + description.Resources = new SubresourceCount(levels - firstLevel, imageLayers); + } + var view = TextureView(descriptor, shape, viewFormat, shaderConversion, viewLevels, description.Resources.Layers, - shaderHash, imageIndex); + shaderHash, imageIndex, firstLevel); if (!shape.R128 && descriptor.MetadataCompress && !description.IsDepth && !shaderConversion && tile == GuestTileMode.RenderTarget && levels == 1 && samples == 1 && type is GuestImageType.Color2D or GuestImageType.Color2DArray or GuestImageType.Color3D && diff --git a/src/SharpEmu.Libs/Gpu/Images/ResidentImageBacking.cs b/src/SharpEmu.Libs/Gpu/Images/ResidentImageBacking.cs new file mode 100644 index 000000000..80eadf57d --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/Images/ResidentImageBacking.cs @@ -0,0 +1,65 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using SharpEmu.Libs.Kernel; + +namespace SharpEmu.Libs.Gpu.Images; + +// A texture streamed into its address range maps only its resident mips. A tiled chain puts +// the mip tail and small levels at the start and level 0 at the end, so the resident part is +// a backed prefix. The GPU samples only resident levels; the unmapped rest reads as zero. +internal static class ResidentImageBacking +{ + private const ulong Page = 1UL << 12; + + // SHARPEMU_IMAGE_BACKING_HOLES=1 (default off): unmapped pages anywhere after the first are zero-filled instead of + // failing. Games sample images whose backing has a backed page after a hole, and that failure is + // fatal. + private static readonly bool AllowHoles = + Environment.GetEnvironmentVariable("SHARPEMU_IMAGE_BACKING_HOLES") == "1"; + + // Reads image bytes from CPU-visible backing or PRT backing. A streamed texture's image holds only its + // resident levels and its upload reads only their bytes, so an unmapped byte inside them is an error, + // not a level to zero; SHARPEMU_IMAGE_BACKING_HOLES=1 still zero-fills the unmapped pages instead. + internal static bool TryRead(IGuestBackedSpace backing, ulong address, Span destination) => + backing.TryReadBacking(address, destination) || + KernelMemoryCompatExports.TryReadPrtBacking(backing, address, destination) || + AllowHoles && TryReadResidentPrefix(backing, address, destination, allowHoles: true); + + // Copies the backed prefix page by page and zero-fills the unmapped tail. A backed page + // after a hole is not a mip chain, so it is rejected unless allowHoles. + internal static bool TryReadResidentPrefix(IGuestBackedSpace backing, ulong address, Span destination) => + TryReadResidentPrefix(backing, address, destination, AllowHoles); + + internal static bool TryReadResidentPrefix(IGuestBackedSpace backing, ulong address, Span destination, bool allowHoles) + { + var size = (ulong)destination.Length; + if (size == 0 || !backing.IsBackedRange(address, 1)) + { + return false; + } + + var resident = true; + for (ulong offset = 0; offset < size;) + { + var chunk = Math.Min(Page - ((address + offset) & (Page - 1)), size - offset); + var target = destination.Slice((int)offset, (int)chunk); + var backed = backing.IsBackedRange(address + offset, chunk); + if (backed && !resident && !allowHoles) + { + return false; + } + + resident = backed && backing.TryReadBacking(address + offset, target); + if (!resident) + { + target.Clear(); + } + + offset += chunk; + } + + return true; + } +} diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.Tessellation.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.Tessellation.cs index 70a0b03fa..85cc4a27d 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.Tessellation.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.Tessellation.cs @@ -47,7 +47,16 @@ private TessellationDrawPrograms PrepareTessellationHull(VertexStageRegisters ve var address = vertex.LocalAddress != 0 ? vertex.LocalAddress : vertex.HullAddress; var registered = _registry.Require(address, "merged-hull", vertex.HullUserScalars.Values); if (!registered.IsFused) - throw SubmissionScheduler.Fatal("The tessellation path requires a registered merged local/hull program."); + { + // A complete hull binary is bound as the local program alone; it reads its own + // user scalars in both halves and takes no separate hull table. + var combined = PrepareSource(address, ShaderStage.Compute, "merged-hull", + UserData(vertex.HullUserScalars, vertex.HullResource2.UserScalarCount, false, address, "merged-hull").ToArray(), + VertexUserDataBase, out _); + if (!Gen5TessellationLowering.TryFindCombinedHullEntry(_programs.Decode(combined), out var combinedEntry)) + throw SubmissionScheduler.Fatal("The tessellation path requires a registered merged local/hull program."); + return CompileTessellationHull(combined, registered, vertex, shaderInterface, tessellation, combinedEntry + 4); + } var count = vertex.HullResource2.UserScalarCount; // A merged front may consume more user data than the back's RSRC2. // Reading its own declared count preserves the guest's AGC header. diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index 3da151f0c..429974ad8 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -190,15 +190,16 @@ public GraphicsPrograms GetGraphicsPrograms( ReadOnlySpan targetExportMapping, bool pixelActive, bool depthBound) => - GetGraphicsProgramsCore(banks, targetExportMapping, pixelActive, depthBound, -1); + GetGraphicsProgramsCore(banks, targetExportMapping, pixelActive, depthBound, -1, -1); public GraphicsPrograms GetGraphicsPrograms( RegisterBanks banks, ReadOnlySpan targetExportMapping, bool pixelActive, bool depthBound, - int startInstanceUserData) => - GetGraphicsProgramsCore(banks, targetExportMapping, pixelActive, depthBound, startInstanceUserData); + int startInstanceUserData, + int baseVertexUserData = -1) => + GetGraphicsProgramsCore(banks, targetExportMapping, pixelActive, depthBound, startInstanceUserData, baseVertexUserData); public GraphicsPrograms GetMeshGraphicsPrograms( RegisterBanks banks, @@ -247,7 +248,7 @@ public GraphicsPrograms GetMeshGraphicsPrograms( return new GraphicsPrograms { Available = false }; } - return ResolveGraphicsPrograms(banks, targetExportMapping, pixelActive, depthBound, -1, + return ResolveGraphicsPrograms(banks, targetExportMapping, pixelActive, depthBound, -1, -1, banks.Stamp(RegisterStamp.ShaderPrograms), banks.Stamp(RegisterStamp.VertexUserData), banks.Stamp(RegisterStamp.PixelUserData), banks.Stamp(RegisterStamp.ColorTargets, RegisterStamp.ShaderInterface), null, mesh); } @@ -300,14 +301,15 @@ public static string TakeKeptProgramsReport() => private bool TryKeepGraphicsPrograms(RegisterBanks banks, KeptGraphicsPrograms kept, ulong programsStamp, ulong vertexUserDataStamp, ulong pixelUserDataStamp, ulong interfaceStamp, - ReadOnlySpan targetExportMapping, bool pixelActive, bool depthBound, int startInstanceUserData, out GraphicsPrograms programs) + ReadOnlySpan targetExportMapping, bool pixelActive, bool depthBound, int startInstanceUserData, int baseVertexUserData, + out GraphicsPrograms programs) { programs = null!; if (_registry.HasFrontend) return false; if (kept.Programs is not { } previous || kept.ProgramsStamp != programsStamp || kept.VertexUserDataStamp != vertexUserDataStamp || kept.PixelUserDataStamp != pixelUserDataStamp || kept.InterfaceStamp != interfaceStamp || kept.PixelActive != pixelActive || - kept.DepthBound != depthBound || kept.StartInstanceUserData != startInstanceUserData || + kept.DepthBound != depthBound || kept.StartInstanceUserData != startInstanceUserData || kept.BaseVertexUserData != baseVertexUserData || kept.Registrations != ShaderHeaderRegistry.Registrations || kept.ExportMappingCount != targetExportMapping.Length || !targetExportMapping.SequenceEqual(kept.ExportMapping.AsSpan(0, kept.ExportMappingCount))) { @@ -344,10 +346,11 @@ private static bool SameClipViewport(in ClipSpaceTransform clipSpace, in Viewpor private static void KeepGraphicsPrograms(KeptGraphicsPrograms kept, GraphicsPrograms programs, ulong programsStamp, ulong vertexUserDataStamp, ulong pixelUserDataStamp, ulong interfaceStamp, ulong pipelineStateStamp, uint outputBlend, ReadOnlySpan targetExportMapping, bool pixelActive, - bool depthBound, int startInstanceUserData, long registrations) + bool depthBound, int startInstanceUserData, int baseVertexUserData, long registrations) { kept.Programs = programs.Available ? programs : null; kept.StartInstanceUserData = startInstanceUserData; + kept.BaseVertexUserData = baseVertexUserData; kept.ProgramsStamp = programsStamp; kept.VertexUserDataStamp = vertexUserDataStamp; kept.PixelUserDataStamp = pixelUserDataStamp; @@ -366,20 +369,22 @@ private GraphicsPrograms GetGraphicsProgramsCore( ReadOnlySpan targetExportMapping, bool pixelActive, bool depthBound, - int startInstanceUserData) + int startInstanceUserData, + int baseVertexUserData) { var programsStamp = banks.Stamp(RegisterStamp.ShaderPrograms); var vertexUserDataStamp = banks.Stamp(RegisterStamp.VertexUserData); var pixelUserDataStamp = banks.Stamp(RegisterStamp.PixelUserData); var interfaceStamp = banks.Stamp(RegisterStamp.ColorTargets, RegisterStamp.ShaderInterface); var keptGraphics = _keptGraphics ??= new KeptGraphicsPrograms(); - if (TryKeepGraphicsPrograms(banks, keptGraphics, programsStamp, vertexUserDataStamp, pixelUserDataStamp, interfaceStamp, targetExportMapping, pixelActive, depthBound, startInstanceUserData, out var keptPrograms)) + if (TryKeepGraphicsPrograms(banks, keptGraphics, programsStamp, vertexUserDataStamp, pixelUserDataStamp, interfaceStamp, targetExportMapping, pixelActive, depthBound, startInstanceUserData, + baseVertexUserData, out var keptPrograms)) { _graphicsKept.Increment(); return keptPrograms; } - return ResolveGraphicsPrograms(banks, targetExportMapping, pixelActive, depthBound, startInstanceUserData, + return ResolveGraphicsPrograms(banks, targetExportMapping, pixelActive, depthBound, startInstanceUserData, baseVertexUserData, programsStamp, vertexUserDataStamp, pixelUserDataStamp, interfaceStamp, keptGraphics, null); } @@ -389,6 +394,7 @@ private GraphicsPrograms ResolveGraphicsPrograms( bool pixelActive, bool depthBound, int startInstanceUserData, + int baseVertexUserData, ulong programsStamp, ulong vertexUserDataStamp, ulong pixelUserDataStamp, @@ -423,7 +429,8 @@ private GraphicsPrograms ResolveGraphicsPrograms( VertexUserDataBase, ref pair.VertexHeader, out var vertexHeader, vertex.GeometryUserDataAddress); var vertexInfo = tessellated ? new VertexInputInfo { PositionExportControl = shaderInterface.VertexOutputControl } : mesh is null - ? PrepareVertexInput(vertexSource, vertexHeader, shaderInterface, context, _vertexInput = pair.VertexInput, startInstanceUserData) + ? PrepareVertexInput(vertexSource, vertexHeader, shaderInterface, context, _vertexInput = pair.VertexInput, startInstanceUserData, + baseVertexUserData) : new VertexInputInfo(); vertexInfo.IeeeMode = vertex.GeometryResource1.IeeeMode; ShaderSource? pixelSource = null; @@ -542,7 +549,7 @@ mesh is null { KeepGraphicsPrograms(keptGraphics, programs, programsStamp, vertexUserDataStamp, pixelUserDataStamp, interfaceStamp, blendDependent ? banks.Stamp(RegisterStamp.PipelineState) : 0, pixelActive ? PixelOutputBlend(context) : 0, targetExportMapping, pixelActive, - depthBound, startInstanceUserData, ShaderHeaderRegistry.Registrations); + depthBound, startInstanceUserData, baseVertexUserData, ShaderHeaderRegistry.Registrations); } return programs; @@ -595,9 +602,10 @@ private bool TryPreparePairProgram(ShaderSource source, StageCompileOptions opti ref uint pushDataCursor, out ShaderProgram program, out ShaderStageResources stage) { var startInstance = options.VertexInfo?.StartInstanceUserData ?? -1; + var baseVertex = options.VertexInfo?.BaseVertexUserData ?? -1; var ieeeMode = options.VertexInfo?.IeeeMode ?? options.PixelInfo?.IeeeMode ?? false; if (kept.Entry is { } entry && staticInputs is not null && ReferenceEquals(kept.StaticInputs, staticInputs) && kept.Hash == source.Hash && - kept.UserDataCount == source.UserData.Length && kept.RequiredOutputs == requiredOutputs && kept.StartInstance == startInstance && + kept.UserDataCount == source.UserData.Length && kept.RequiredOutputs == requiredOutputs && kept.StartInstance == startInstance && kept.BaseVertex == baseVertex && kept.IeeeMode == ieeeMode && kept.Registrations == ShaderHeaderRegistry.Registrations) { _pairEntryHits.Increment(); @@ -623,6 +631,7 @@ private bool TryPreparePairProgram(ShaderSource source, StageCompileOptions opti kept.UserDataCount = source.UserData.Length; kept.RequiredOutputs = requiredOutputs; kept.StartInstance = startInstance; + kept.BaseVertex = baseVertex; kept.IeeeMode = ieeeMode; kept.Registrations = ShaderHeaderRegistry.Registrations; return true; @@ -701,7 +710,7 @@ private static ulong Pack(ReadOnlySpan mappings) } private VertexInputInfo PrepareVertexInput(ShaderSource source, ShaderHeaderEntry header, ShaderInterfaceRegisters shaderInterface, - ContextRegisters context, KeptVertexInput kept, int startInstanceUserData) + ContextRegisters context, KeptVertexInput kept, int startInstanceUserData, int baseVertexUserData) { using var profileScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.VertexInputResolution); var clipSpace = ResolveClipSpace(context); @@ -712,11 +721,13 @@ private VertexInputInfo PrepareVertexInput(ShaderSource source, ShaderHeaderEntr { var copy = info.WithoutStage(); copy.StartInstanceUserData = startInstanceUserData; + copy.BaseVertexUserData = baseVertexUserData; return copy; } var resolved = VertexInputResolver.ResolveVertexInputs(_context, header.Shader, tables, source.UserData, control, clipSpace, out var words); resolved.StartInstanceUserData = startInstanceUserData; + resolved.BaseVertexUserData = baseVertexUserData; kept.Header = header; kept.Words = words; kept.PositionExportControl = control; @@ -1791,6 +1802,7 @@ internal sealed class KeptGraphicsPrograms public bool PixelActive; public bool DepthBound; public int StartInstanceUserData; + public int BaseVertexUserData; public int ExportMappingCount; public readonly ColorComponentMap[] ExportMapping = new ColorComponentMap[RenderingState.ColorAttachmentCapacity]; } @@ -1820,6 +1832,7 @@ internal sealed class GraphicsPairStage public int UserDataCount; public int RequiredOutputs; public int StartInstance; + public int BaseVertex; public bool IeeeMode; public long Registrations; } diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.Vertex.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.Vertex.cs index 59df3ee13..ed9d97337 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.Vertex.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.Vertex.cs @@ -28,6 +28,9 @@ internal sealed class VertexPrewarmRecord public uint? MeshOutputLocationMask { get; init; } public required ResourceSpecialization Specialization { get; init; } public bool DeviceRecordCounts { get; init; } + // The program's image table selects more images than a draw can bind, so its plan reads them from the bindless heap + // (ShaderProgramCache.PreferHeapRecords). The prewarm plans it the same way, or its compile would never be reused. + public bool PreferHeapRecords { get; init; } public (ulong Hash, uint CodeSize, ulong Address, ulong ContinuationAddressOffset) CodeKey => (Hash, CodeSize, Address, ContinuationAddressOffset); @@ -139,6 +142,7 @@ public IReadOnlyList LoadedGraphicsPrewarm() // Returns the record's identity, under which RecordPreRasterization records the program's states. public ulong RecordVertex(ShaderCodeCapture code, VertexPrewarmRecord record) { + NoteHeapRecords(record.PreferHeapRecords, record.Hash, record.CodeSize, record.ContinuationAddressOffset); var payload = SerializeVertex(record, record.Address); var identity = Identity(record); lock (_gate) @@ -180,6 +184,7 @@ private bool TryLoadGraphicsRecord(byte kind, byte[] payload) case VertexKind: if (TryDeserializeVertex(payload) is { } vertex && _vertices.Add(Identity(vertex))) { + NoteHeapRecords(vertex.PreferHeapRecords, vertex.Hash, vertex.CodeSize, vertex.ContinuationAddressOffset); _loadedVertices[Identity(vertex)] = vertex; } @@ -272,13 +277,19 @@ private static byte[] SerializeVertex(VertexPrewarmRecord record, ulong address) WriteSpecialization(writer, record.Specialization); writer.Write(record.DeviceRecordCounts); - // The user data register of the draw's start instance, last and only when the program reads one, so a record - // without one keeps its bytes and identity. - if (!record.Mesh && record.VertexInfo is { StartInstanceUserData: not -1 } startInstanceInfo) + // The user data registers of the draw's start instance and base vertex, last and only when the program reads + // one, so a record without them keeps its bytes and identity. + if (!record.Mesh && record.VertexInfo is { } drawInfo && (drawInfo.StartInstanceUserData != -1 || drawInfo.BaseVertexUserData != -1)) { - writer.Write(startInstanceInfo.StartInstanceUserData); + writer.Write(drawInfo.StartInstanceUserData); + if (drawInfo.BaseVertexUserData != -1) + { + writer.Write(drawInfo.BaseVertexUserData); + } } + // Last of all, one byte: the length tells it from the draw registers, which are whole dwords. + if (record.PreferHeapRecords) writer.Write((byte)1); writer.Flush(); return stream.ToArray(); } @@ -375,9 +386,28 @@ private static byte[] SerializeVertex(VertexPrewarmRecord record, ulong address) var specialization = ReadSpecialization(reader, payload.Length); var deviceRecordCounts = reader.ReadBoolean(); - if (vertexInfo is not null && reader.BaseStream.Length - reader.BaseStream.Position == sizeof(int)) + var trailing = reader.BaseStream.Length - reader.BaseStream.Position; + var preferHeapRecords = trailing % sizeof(int) == 1; + var drawParameters = trailing - (preferHeapRecords ? 1 : 0); + if (vertexInfo is not null && drawParameters is sizeof(int) or 2 * sizeof(int)) { vertexInfo.StartInstanceUserData = reader.ReadInt32(); + if (drawParameters == 2 * sizeof(int)) + { + vertexInfo.BaseVertexUserData = reader.ReadInt32(); + } + } + + if (preferHeapRecords && reader.BaseStream.Position + 1 == reader.BaseStream.Length) + { + if (reader.ReadByte() != 1) + { + return null; + } + } + else + { + preferHeapRecords = false; } if (reader.BaseStream.Position != reader.BaseStream.Length) @@ -401,6 +431,7 @@ private static byte[] SerializeVertex(VertexPrewarmRecord record, ulong address) MeshOutputLocationMask = hasOutputMask ? outputMask : null, Specialization = specialization, DeviceRecordCounts = deviceRecordCounts, + PreferHeapRecords = preferHeapRecords, }; } catch (Exception exception) when (exception is EndOfStreamException or ArgumentException or IOException) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.cs index 440ec220e..20854cac5 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmList.cs @@ -144,6 +144,9 @@ internal sealed class ComputePrewarmRecord public required ResourceSpecialization Specialization { get; init; } public LinkedShaderPrewarm? Linked { get; init; } public bool DeviceRecordCounts { get; init; } + // The program's image table selects more images than a draw can bind, so its plan reads them from the bindless heap + // (ShaderProgramCache.PreferHeapRecords). The prewarm plans it the same way, or its compile would never be reused. + public bool PreferHeapRecords { get; init; } public (ulong Hash, uint CodeSize, ulong Address, ulong ContinuationAddressOffset) CodeKey => (Hash, CodeSize, Address, ContinuationAddressOffset); @@ -167,6 +170,9 @@ internal sealed class PixelPrewarmRecord public required uint InputAddress { get; init; } public required ResourceSpecialization Specialization { get; init; } public bool DeviceRecordCounts { get; init; } + // The program's image table selects more images than a draw can bind, so its plan reads them from the bindless heap + // (ShaderProgramCache.PreferHeapRecords). The prewarm plans it the same way, or its compile would never be reused. + public bool PreferHeapRecords { get; init; } public (ulong Hash, uint CodeSize, ulong Address, ulong ContinuationAddressOffset) CodeKey => (Hash, CodeSize, Address, ContinuationAddressOffset); @@ -183,6 +189,7 @@ internal sealed class StagePrewarmRecord public required uint PushDataCursor { get; init; } public required StageCompileOptions Options { get; init; } public required ResourceSpecialization Specialization { get; init; } + public bool PreferHeapRecords { get; init; } } internal sealed class GraphicsPrewarmRecord @@ -387,6 +394,8 @@ internal sealed partial class ShaderPrewarmList : IDisposable private readonly HashSet<(ulong Hash, uint CodeSize, ulong Address, ulong ContinuationAddressOffset)> _extensionCodes = []; // The last recorded outcome of each linked program's module compile (true: it compiled for minutes). private readonly ConcurrentDictionary _linkedCompiles = new(); + // The programs a record says plan their image tables as heap records, by hash, code size and continuation offset. + private readonly ConcurrentDictionary<(ulong Hash, uint CodeSize, ulong ContinuationAddressOffset), byte> _heapRecordPrograms = new(); private readonly HashSet _computes = []; private readonly Dictionary _computeFirstUses = new(); private readonly Dictionary _computeCosts = new(); @@ -674,8 +683,22 @@ public void ClearProgress() private static string ProgressKey(string stamp) => XxHash3.HashToUInt64(Encoding.UTF8.GetBytes(stamp)).ToString("X16", CultureInfo.InvariantCulture); + // Whether a session found that the program must plan its image table as heap records, so a later session plans it so from + // the start instead of failing to materialize it first and replanning. + public bool PrefersHeapRecords(ulong hash, uint codeSize, ulong continuationAddressOffset) => + _heapRecordPrograms.ContainsKey((hash, codeSize, continuationAddressOffset)); + + private void NoteHeapRecords(bool preferHeapRecords, ulong hash, uint codeSize, ulong continuationAddressOffset) + { + if (preferHeapRecords) + { + _heapRecordPrograms[(hash, codeSize, continuationAddressOffset)] = 0; + } + } + public void RecordCompute(ShaderCodeCapture code, ComputePrewarmRecord record) { + NoteHeapRecords(record.PreferHeapRecords, record.Hash, record.CodeSize, record.ContinuationAddressOffset); var payload = SerializeCompute(record); var identity = Identity(record); var seconds = SessionSeconds(); @@ -735,6 +758,7 @@ private static byte[] IdentitySeconds(ulong identity, float seconds) public void RecordPixel(ShaderCodeCapture code, PixelPrewarmRecord record) { + NoteHeapRecords(record.PreferHeapRecords, record.Hash, record.CodeSize, record.ContinuationAddressOffset); var payload = SerializePixel(record, record.Address); var identity = Identity(record); lock (_gate) @@ -780,6 +804,7 @@ public void RecordLinkedCompile(ulong hash, bool slow, long milliseconds) public void RecordStage(ShaderCodeCapture code, ulong module, StagePrewarmRecord record) { + NoteHeapRecords(record.PreferHeapRecords, record.CodeKey.Hash, record.CodeKey.CodeSize, record.CodeKey.ContinuationAddressOffset); var payload = SerializeStage(record); var identity = XxHash3.HashToUInt64(payload); _stageByModule[module] = identity; @@ -989,6 +1014,7 @@ private bool TryLoadRecord(byte kind, byte[] payload, bool extension) // By the record's identity, not its bytes: records that differ only in a buffer's stride word load // as one. var record = DeserializeCompute(payload); + NoteHeapRecords(record.PreferHeapRecords, record.Hash, record.CodeSize, record.ContinuationAddressOffset); if (_computes.Add(Identity(record))) { _loadedComputes.Add(record); @@ -1002,7 +1028,13 @@ private bool TryLoadRecord(byte kind, byte[] payload, bool extension) // A pixel record of another schema is skipped, not refused, so the records after it still load. The // pixel records of a main list written before the side file existed have no first use. var (bytes, firstUse) = extension ? SplitFirstUse(payload) : (payload, 0f); - if (TryDeserializePixel(bytes) is { } pixel && _pixels.Add(Identity(pixel))) + var pixel = TryDeserializePixel(bytes); + if (pixel is not null) + { + NoteHeapRecords(pixel.PreferHeapRecords, pixel.Hash, pixel.CodeSize, pixel.ContinuationAddressOffset); + } + + if (pixel is not null && _pixels.Add(Identity(pixel))) { _loadedPixels.Add(pixel); _graphicsOrder.Add((PixelKind, _loadedPixels.Count - 1, firstUse)); @@ -1070,7 +1102,9 @@ private bool TryLoadPipelineRecord(byte kind, byte[] payload) var identity = XxHash3.HashToUInt64(payload); if (_stages.Add(identity)) { - _loadedStages[identity] = DeserializeStage(payload); + var stage = DeserializeStage(payload); + _loadedStages[identity] = stage; + NoteHeapRecords(stage.PreferHeapRecords, stage.CodeKey.Hash, stage.CodeKey.CodeSize, stage.CodeKey.ContinuationAddressOffset); } return true; @@ -1139,14 +1173,22 @@ internal static string SchemaText(params Type[] types) builder.Append(type.ToString()).Append('{'); foreach (var property in type.GetProperties().OrderBy(static property => property.Name, StringComparer.Ordinal)) { - // A vertex record holds neither: tessellated programs are not recorded, and the start instance register - // follows the record as an optional field (SerializeVertex), so the lists recorded before them still load. + // A vertex record holds none: tessellated programs are not recorded, and the start instance and base vertex + // registers follow the record as optional fields (SerializeVertex), so the lists recorded before them still load. if (vertexRecord && type == typeof(VertexInputInfo) && - property.Name is nameof(VertexInputInfo.Tessellation) or nameof(VertexInputInfo.StartInstanceUserData)) + property.Name is nameof(VertexInputInfo.Tessellation) or nameof(VertexInputInfo.StartInstanceUserData) + or nameof(VertexInputInfo.BaseVertexUserData)) { continue; } + // A pixel or vertex record's heap flag follows the record as an optional byte (SerializePixel, SerializeVertex), so + // the lists recorded before it still load. + if (type == typeof(PixelPrewarmRecord) || type == typeof(VertexPrewarmRecord)) + { + if (property.Name == nameof(PixelPrewarmRecord.PreferHeapRecords)) continue; + } + builder.Append(property.PropertyType.ToString()).Append(' ').Append(property.Name).Append(';'); } @@ -1287,8 +1329,10 @@ private static byte[] SerializeCompute(ComputePrewarmRecord record, ulong addres WriteSpecialization(writer, record.Specialization); writer.Write(record.Linked is not null); record.Linked?.Write(writer); - // Optional extension: old records retain their ordinary resource plan and byte identity. - if (record.DeviceRecordCounts) writer.Write((byte)1); + // Optional extension, a bit set (1: device record counts, 2: heap records): old records retain their ordinary + // resource plan and byte identity. + var extension = (record.DeviceRecordCounts ? 1 : 0) | (record.PreferHeapRecords ? 2 : 0); + if (extension != 0) writer.Write((byte)extension); writer.Flush(); return stream.ToArray(); @@ -1335,10 +1379,13 @@ private static ComputePrewarmRecord DeserializeCompute(byte[] payload) var specialization = ReadSpecialization(reader, payload.Length); var linked = reader.ReadBoolean() ? LinkedShaderPrewarm.Read(reader) : null; var deviceRecordCounts = false; + var preferHeapRecords = false; if (reader.BaseStream.Position + 1 == reader.BaseStream.Length) { - if (reader.ReadByte() != 1) throw new ArgumentException("Unknown prewarm compute extension."); - deviceRecordCounts = true; + var extension = reader.ReadByte(); + if (extension is 0 or > 3) throw new ArgumentException("Unknown prewarm compute extension."); + deviceRecordCounts = (extension & 1) != 0; + preferHeapRecords = (extension & 2) != 0; } if (reader.BaseStream.Position != reader.BaseStream.Length) throw new ArgumentException("Trailing prewarm compute data."); @@ -1357,6 +1404,7 @@ private static ComputePrewarmRecord DeserializeCompute(byte[] payload) Specialization = specialization, Linked = linked, DeviceRecordCounts = deviceRecordCounts, + PreferHeapRecords = preferHeapRecords, }; } @@ -1530,6 +1578,7 @@ private static byte[] SerializePixel(PixelPrewarmRecord record, ulong address) writer.Write(record.InputAddress); WriteSpecialization(writer, record.Specialization); writer.Write(record.DeviceRecordCounts); + if (record.PreferHeapRecords) writer.Write((byte)1); writer.Flush(); return stream.ToArray(); } @@ -1612,6 +1661,17 @@ private static byte[] SerializePixel(PixelPrewarmRecord record, ulong address) var inputAddress = reader.ReadUInt32(); var specialization = ReadSpecialization(reader, payload.Length); var deviceRecordCounts = reader.ReadBoolean(); + var preferHeapRecords = false; + if (reader.BaseStream.Position + 1 == reader.BaseStream.Length) + { + if (reader.ReadByte() != 1) + { + return null; + } + + preferHeapRecords = true; + } + if (reader.BaseStream.Position != reader.BaseStream.Length) { return null; @@ -1632,6 +1692,7 @@ private static byte[] SerializePixel(PixelPrewarmRecord record, ulong address) InputAddress = inputAddress, Specialization = specialization, DeviceRecordCounts = deviceRecordCounts, + PreferHeapRecords = preferHeapRecords, }; } catch (Exception exception) when (exception is EndOfStreamException or ArgumentException or IOException) @@ -1700,6 +1761,7 @@ private static byte[] SerializeStage(StagePrewarmRecord record) writer.Write(options.PixelInputAddress); writer.Write(options.DeviceRecordCounts); WriteSpecialization(writer, record.Specialization); + if (record.PreferHeapRecords) writer.Write((byte)1); writer.Flush(); return stream.ToArray(); } @@ -1771,6 +1833,14 @@ private static StagePrewarmRecord DeserializeStage(byte[] payload) throw new ArgumentException("The prewarm stage has no input info."); } + var specialization = ReadSpecialization(reader, limit); + var preferHeapRecords = false; + if (reader.BaseStream.Position + 1 == reader.BaseStream.Length) + { + if (reader.ReadByte() != 1) throw new ArgumentException("Unknown prewarm stage extension."); + preferHeapRecords = true; + } + return new StagePrewarmRecord { Stage = stage, @@ -1781,7 +1851,8 @@ private static StagePrewarmRecord DeserializeStage(byte[] payload) UserDataCount = userDataCount, PushDataCursor = pushDataCursor, Options = options, - Specialization = ReadSpecialization(reader, limit), + Specialization = specialization, + PreferHeapRecords = preferHeapRecords, }; } @@ -1822,6 +1893,7 @@ private static void WriteVertexInfo(BinaryWriter writer, VertexInputInfo info) writer.Write(clip.HalfExtentX); writer.Write(clip.HalfExtentY); writer.Write(info.StartInstanceUserData); + writer.Write(info.BaseVertexUserData); } private static VertexInputInfo ReadVertexInfo(BinaryReader reader, int limit) @@ -1859,6 +1931,7 @@ private static VertexInputInfo ReadVertexInfo(BinaryReader reader, int limit) reader.ReadBoolean(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()), StartInstanceUserData = reader.ReadInt32(), + BaseVertexUserData = reader.ReadInt32(), }; } diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index 01f641a33..7c61a24e1 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -141,7 +141,11 @@ internal sealed class ProgramPermutation // One decoded program with its resource plan and every permutation compiled from it. internal sealed class ProgramSourceEntry { - public required ShaderResourcePlan Plan { get; init; } + // Replaced once when an indirect image table proves too large to bind (see PreferHeapRecords). + public required ShaderResourcePlan Plan { get; set; } + + // Plans this program again with heap records by the policy that produced Plan: CreateEntry's, or a link's with its call records. + public Func? ReplanWithHeapRecords { get; init; } public required Gen5ShaderProgram Program { get; init; } public required bool HasBitwiseExclusiveOr { get; init; } public required bool HasShaderCalls { get; init; } @@ -176,6 +180,9 @@ internal sealed class ProgramSourceEntry public ProgramPermutation? LastPermutation; + // The permutations compiled from a replaced plan belong to a layout no draw can use again. + public void ClearPermutations() => Volatile.Write(ref _permutations, []); + public void AddPermutation(ProgramPermutation permutation) { var current = _permutations; @@ -720,6 +727,31 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa outcome = MaterializationTally.Outcome.Full; } + if (!materialized && materializationFailure is ResourceMaterializationFailure.IncompatibleImageCandidates or ResourceMaterializationFailure.ImageCapacityExceeded && + preparation is null && PreferHeapRecords(source, options, entry)) + { + // The table binds every image it can select, and this one selects more than a draw may bind. The + // heap records of the new plan read their descriptors at run time instead. + outcome = MaterializationTally.Outcome.Full; + materialized = ResourceMaterializer.Materialize(entry.Plan, inputs, ref snapshot, ref specialization, out materializationFailure, + captureIndirectImageFailure); + } + + if (!materialized && materializationFailure == ResourceMaterializationFailure.IncompatibleImageCandidates && + !entry.Plan.NullIncompatibleImageCandidates) + { + // No heap record serves the table, and an image of another kind cannot share its binding. That image + // reads as null, as main read a candidate it could not use, so the operation still runs instead of + // being skipped every time the table selects it. + Console.Error.WriteLine( + $"[GPU][INFO] Shader reads the images of another kind in its image table as null: stage={source.Label} " + + $"hash=0x{source.Hash:X16} shader=0x{source.Address:X16}."); + entry.Plan.NullIncompatibleImageCandidates = true; + outcome = MaterializationTally.Outcome.Full; + materialized = ResourceMaterializer.Materialize(entry.Plan, inputs, ref snapshot, ref specialization, out materializationFailure, + captureIndirectImageFailure); + } + MaterializationTally.Note(materialized ? outcome : MaterializationTally.Outcome.Failed, System.Diagnostics.Stopwatch.GetTimestamp() - started, materialized ? snapshot : null); if (!materialized) @@ -835,7 +867,7 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa { linked = LinkProgram(caller, library, source.Stage, source.Hash, source.UserDataBase, (uint)source.UserData.Length, waveSize, captureLinkedImages ? plan => failedLinkedPlan = plan : null, runtimeRecords, runtimeRecords && CalleeTiering, - _host.SupportsBindlessHeap, _host.ShaderPrewarm is not null, source.Registered.Frontend) ?? + _host.SupportsBindlessHeap, _host.ShaderPrewarm is not null, source.Registered.Frontend, PrefersHeapRecords(source)) ?? RefuseRuntimeCallRecords(source.Hash); failedLinkedPlan = null; } @@ -1077,21 +1109,36 @@ private ProgramKey BuildProgramKey(ShaderSource source) => // links a copy per record from then on (RefuseRuntimeCallRecords). private ProgramSourceEntry? LinkProgram(Gen5ShaderProgram caller, ShaderCallLibrary library, ShaderStage stage, ulong hash, uint userDataBase, uint userDataCount, uint waveSize, Action? beforeResourceTracking, bool runtimeRecords = false, - bool callMarks = false, bool bindlessHeap = false, bool capturePrewarm = false, IShaderFrontend? frontend = null) + bool callMarks = false, bool bindlessHeap = false, bool capturePrewarm = false, IShaderFrontend? frontend = null, + bool preferHeapRecords = false) { Gen5ShaderProgram program; ShaderResourcePlan plan; + Func replan; try { program = runtimeRecords ? ShaderCallLibrary.LinkLeavingOutUnlinkable(caller, ref library, failure => ReportLeftOutCallee(hash, failure)) : Gen5ShaderCallLinker.Link(caller, library.Calls, runtimeRecords); - plan = ShaderResourcePlan.Extract(program, stage, hash, userDataBase, userDataCount, - beforeResourceTracking: beforeResourceTracking, waveSize: waveSize, bindlessNullDescriptors: BindlessNullDescriptors, - bindlessHeap: bindlessHeap, callRecords: runtimeRecords, callMarks: callMarks, - normalizeBufferDescriptor: frontend?.NormalizeBufferDescriptor, - normalizeImageDescriptor: ImageNormalizer(frontend), - imageNormalizationVersion: frontend?.ImageNormalizationVersion); + var linkedProgram = program; + ShaderResourcePlan Extract(bool heapRecords, Action? beforeTracking) => + ShaderResourcePlan.Extract(linkedProgram, stage, hash, userDataBase, userDataCount, + beforeResourceTracking: beforeTracking, waveSize: waveSize, bindlessNullDescriptors: BindlessNullDescriptors, + bindlessHeap: bindlessHeap, callRecords: runtimeRecords, callMarks: callMarks, + normalizeBufferDescriptor: frontend?.NormalizeBufferDescriptor, + normalizeImageDescriptor: ImageNormalizer(frontend), + imageNormalizationVersion: frontend?.ImageNormalizationVersion, + preferHeapRecords: heapRecords); + replan = (_, _) => Extract(heapRecords: true, beforeTracking: null); + try + { + plan = Extract(preferHeapRecords, beforeResourceTracking); + } + catch (ResourcePlanException) when (preferHeapRecords) + { + // Only the heap attempt falls back, as CreateEntry's does; the plan without it refuses call records as before. + plan = Extract(heapRecords: false, beforeResourceTracking); + } } catch (Exception exception) when (runtimeRecords && exception is InvalidOperationException or ResourcePlanException) { @@ -1101,7 +1148,7 @@ private ProgramKey BuildProgramKey(ShaderSource source) => } ulong[] callTargets = runtimeRecords ? Gen5ShaderCallLinker.CallTargets(program) : []; - return new ProgramSourceEntry { Program = program, Plan = plan, RuntimeCallRecords = runtimeRecords, + return new ProgramSourceEntry { Program = program, Plan = plan, ReplanWithHeapRecords = replan, RuntimeCallRecords = runtimeRecords, CallTargets = callTargets, CallTargetCodes = [.. callTargets.Select(address => library.CodeHashes[address])], RuntimeCallees = runtimeRecords ? library.SiteCallees() : null, @@ -1402,9 +1449,10 @@ private ProgramSourceEntry TakeDeferredLink((ProgramKey Key, string Library) lin var bindlessHeap = _host.SupportsBindlessHeap; var capturePrewarm = _host.ShaderPrewarm is not null; var frontend = source.Registered.Frontend; + var preferHeapRecords = PrefersHeapRecords(source); _pendingLinks.Add(source.Hash, (linkedKey, Task.Run(() => LinkProgram(caller, library, stage, hash, userDataBase, userDataCount, waveSize, null, runtimeRecords, callMarks, bindlessHeap, - capturePrewarm, frontend)))); + capturePrewarm, frontend, preferHeapRecords)))); throw new ShaderProgramPendingException(); } @@ -1478,14 +1526,89 @@ private static void BuildStaticState(ShaderStage stage, StageCompileOptions opti } } + private ShaderResourcePlan ExtractPlan(ShaderSource source, StageCompileOptions options, Gen5ShaderProgram program, + EmbeddedVertexFetchPlan? fetch, bool preferHeapRecords, bool dumpPlanning) => + ShaderResourcePlan.Extract(program, source.Stage, source.Hash, source.UserDataBase, (uint)source.UserData.Length, + fetch?.Loads.Select(load => load.Pc).ToHashSet(), + beforeResourceTracking: dumpPlanning ? resourcePlan => ShaderPlanningDump.WriteGraph(source, resourcePlan) : null, + // Resource planning must use the guest wave size of shader compilation. + waveSize: source.Stage switch + { + ShaderStage.Mesh => options.MeshInfo!.Geometry.WaveSize, + ShaderStage.Compute => options.ComputeInfo?.WaveSize ?? 64u, + _ => 32u, + }, dynamicUserData: options.VertexInfo?.StartInstanceUserData ?? -1, + bindlessNullDescriptors: BindlessNullDescriptors, bindlessHeap: _host.SupportsBindlessHeap, + stableImageLimits: StableImageLimits(_host, source.Stage), + deviceRecordCounts: DeviceRecordCountPlan.Enabled && options.DeviceRecordCounts, + normalizeBufferDescriptor: source.Registered.Frontend?.NormalizeBufferDescriptor, + normalizeImageDescriptor: ImageNormalizer(source.Registered.Frontend), + imageNormalizationVersion: source.Registered.Frontend?.ImageNormalizationVersion, + preferHeapRecords: preferHeapRecords); + + // A program an earlier session had to replan (PreferHeapRecords) is planned so from the start, as its prewarm record is. + private bool PrefersHeapRecords(ShaderSource source) => + _host.SupportsBindlessHeap && + _host.ShaderPrewarm?.PrefersHeapRecords(source.Hash, source.CodeSize, source.ContinuationAddressOffset) == true; + + // An indirect image table binds every image it can select, and this program's selects more than a draw may bind. Plans + // it again so the sampled images the bindless heap can serve are heap records, read at run time through descriptor set 1, + // instead of table candidates. Only a program that gains a heap record changes; the permutations compiled from the old + // plan belong to a layout no draw can use again. Returns whether the plan was replaced, by this thread or another. + private bool PreferHeapRecords(ShaderSource source, StageCompileOptions options, ProgramSourceEntry entry) + { + if (!_host.SupportsBindlessHeap) + { + return false; + } + + lock (_gate) + { + if (entry.Plan.PreferredHeapRecords) + { + // Another thread replanned this program meanwhile; the caller materializes with its plan. + return true; + } + + ShaderResourcePlan plan; + try + { + if (entry.ReplanWithHeapRecords is not { } replan) + { + return false; + } + + plan = replan(source, options); + } + catch (ResourcePlanException) + { + return false; + } + + if (!plan.Info.UsesBindlessHeap || plan.HeapRecords.Count <= entry.Plan.HeapRecords.Count) + { + return false; + } + + Console.Error.WriteLine( + $"[GPU][INFO] Shader reads its image descriptors from the bindless heap at run time: stage={source.Label} hash=0x{source.Hash:X16} " + + $"shader=0x{source.Address:X16} (its image table selects more images than a draw can bind)."); + entry.Plan = plan; + entry.ClearPermutations(); + return true; + } + } + private ProgramSourceEntry CreateEntry(ShaderSource source, StageCompileOptions options) { using var planningScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramPlanning); var program = Decode(source); if (options.TessellationHull is not null && source.Registered.Frontend is null) { - program = Gen5TessellationLowering.PrepareMergedHull(program, - checked(source.UserDataBase + (uint)source.UserData.Length - 2)); + program = program.FusedContinuationPc is null + ? Gen5TessellationLowering.PrepareCombinedHull(program) + : Gen5TessellationLowering.PrepareMergedHull(program, + checked(source.UserDataBase + (uint)source.UserData.Length - 2)); } var dumpPlanning = CompiledShaderDump.ShouldWrite(source.Address, source.Hash); @@ -1498,25 +1621,18 @@ private ProgramSourceEntry CreateEntry(ShaderSource source, StageCompileOptions (uint)source.UserData.Length, source.Hash, source.Address); } + var preferHeapRecords = PrefersHeapRecords(source); ShaderResourcePlan plan; try { - plan = ShaderResourcePlan.Extract(program, source.Stage, source.Hash, source.UserDataBase, (uint)source.UserData.Length, - fetch?.Loads.Select(load => load.Pc).ToHashSet(), - beforeResourceTracking: dumpPlanning ? resourcePlan => ShaderPlanningDump.WriteGraph(source, resourcePlan) : null, - // Resource planning must use the guest wave size of shader compilation. - waveSize: source.Stage switch - { - ShaderStage.Mesh => options.MeshInfo!.Geometry.WaveSize, - ShaderStage.Compute => options.ComputeInfo?.WaveSize ?? 64u, - _ => 32u, - }, dynamicUserData: options.VertexInfo?.StartInstanceUserData ?? -1, - bindlessNullDescriptors: BindlessNullDescriptors, bindlessHeap: _host.SupportsBindlessHeap, - stableImageLimits: StableImageLimits(_host, source.Stage), - deviceRecordCounts: DeviceRecordCountPlan.Enabled && options.DeviceRecordCounts, - normalizeBufferDescriptor: source.Registered.Frontend?.NormalizeBufferDescriptor, - normalizeImageDescriptor: ImageNormalizer(source.Registered.Frontend), - imageNormalizationVersion: source.Registered.Frontend?.ImageNormalizationVersion); + try + { + plan = ExtractPlan(source, options, program, fetch, preferHeapRecords, dumpPlanning); + } + catch (ResourcePlanException) when (preferHeapRecords) + { + plan = ExtractPlan(source, options, program, fetch, preferHeapRecords: false, dumpPlanning); + } } catch (ResourcePlanException exception) { @@ -1540,6 +1656,8 @@ private ProgramSourceEntry CreateEntry(ShaderSource source, StageCompileOptions return new ProgramSourceEntry { Plan = plan, + ReplanWithHeapRecords = (replanSource, replanOptions) => + ExtractPlan(replanSource, replanOptions, program, fetch, preferHeapRecords: true, dumpPlanning: false), Program = program, HasBitwiseExclusiveOr = exclusiveOr, HasShaderCalls = program.Instructions.Any(instruction => instruction.Opcode == "SSwappcB64"), @@ -1922,6 +2040,7 @@ private ProgramPermutation CompilePermutation( InputAddress = options.PixelInputAddress, Specialization = specialization.Clone(), DeviceRecordCounts = plan.DeviceRecordCounts is not null, + PreferHeapRecords = plan.PreferredHeapRecords, }; pixelPrewarm.RecordPixel(pixelCapture, pixelRecord); } @@ -1949,6 +2068,7 @@ private ProgramPermutation CompilePermutation( MeshOutputLocationMask = options.MeshOutputLocationMask, Specialization = specialization.Clone(), DeviceRecordCounts = plan.DeviceRecordCounts is not null, + PreferHeapRecords = plan.PreferredHeapRecords, }); _host.VertexProgramRecorded(module, identity); } @@ -1972,6 +2092,7 @@ _host.ShaderPrewarm is { } prewarm && Specialization = specialization.Clone(), Linked = entry.LinkedPrewarm, DeviceRecordCounts = plan.DeviceRecordCounts is not null, + PreferHeapRecords = plan.PreferredHeapRecords, }); } @@ -1995,6 +2116,7 @@ _host.ShaderPrewarm is { } stagePrewarm && PushDataCursor = pushDataCursor, Options = options, Specialization = specialization, + PreferHeapRecords = plan.PreferredHeapRecords, }); } @@ -2033,6 +2155,7 @@ private static ShaderCompileRequest BuildVertexRequest(IShaderPipelineHost host, SupportsClipDistance = host.ClipDistanceEnabled, SupportsDrawParameters = host.ShaderDrawParametersSupported, StartInstanceUserData = info.StartInstanceUserData, + BaseVertexUserData = info.BaseVertexUserData, ClipSpace = new ShaderClipSpaceTransform( info.ClipSpace.Enabled, info.ClipSpace.ScaleX, @@ -2253,7 +2376,8 @@ internal static bool TryCompilePrewarm(ComputePrewarmRecord record, ShaderCodeCa deviceRecordCounts: record.DeviceRecordCounts, normalizeBufferDescriptor: frontend?.NormalizeBufferDescriptor, normalizeImageDescriptor: frontend?.NormalizeImageDescriptor, - imageNormalizationVersion: frontend?.ImageNormalizationVersion); + imageNormalizationVersion: frontend?.ImageNormalizationVersion, + preferHeapRecords: record.PreferHeapRecords); // A record's storage image selects as the session keeps them (RuntimeImageSwizzle.Canonical). var specialization = RuntimeImageSwizzle.Canonical(plan, record.Specialization); var resources = ResourceMaterializer.ApplyTo(plan, specialization); @@ -2295,7 +2419,8 @@ internal static bool TryCompilePixelPrewarm(PixelPrewarmRecord record, ShaderCod var plan = ShaderResourcePlan.Extract(program, ShaderStage.Pixel, record.Hash, record.UserDataBase, record.UserDataCount, waveSize: 32, bindlessNullDescriptors: BindlessNullDescriptors, bindlessHeap: host.SupportsBindlessHeap, stableImageLimits: host.GraphicsImageDescriptorLimits, - deviceRecordCounts: DeviceRecordCountPlan.Enabled && record.DeviceRecordCounts); + deviceRecordCounts: DeviceRecordCountPlan.Enabled && record.DeviceRecordCounts, + preferHeapRecords: record.PreferHeapRecords); // A record's storage image selects as the session keeps them (RuntimeImageSwizzle.Canonical). var specialization = RuntimeImageSwizzle.Canonical(plan, record.Specialization); var resources = ResourceMaterializer.ApplyTo(plan, specialization); @@ -2368,7 +2493,8 @@ internal static bool TryCompileVertexPrewarm(VertexPrewarmRecord record, ShaderC dynamicUserData: record.VertexInfo?.StartInstanceUserData ?? -1, bindlessNullDescriptors: BindlessNullDescriptors, bindlessHeap: host.SupportsBindlessHeap, stableImageLimits: host.GraphicsImageDescriptorLimits, - deviceRecordCounts: DeviceRecordCountPlan.Enabled && record.DeviceRecordCounts); + deviceRecordCounts: DeviceRecordCountPlan.Enabled && record.DeviceRecordCounts, + preferHeapRecords: record.PreferHeapRecords); // A record's storage image selects as the session keeps them (RuntimeImageSwizzle.Canonical). var specialization = RuntimeImageSwizzle.Canonical(plan, record.Specialization); var resources = ResourceMaterializer.ApplyTo(plan, specialization); diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/StageStaticKey.cs b/src/SharpEmu.Libs/Gpu/Pipelines/StageStaticKey.cs index 4c48ce58f..f06012d39 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/StageStaticKey.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/StageStaticKey.cs @@ -38,6 +38,7 @@ public static void Build(VertexInputInfo info, int requiredOutputCount, List targetExportMapping, bool pixelActive, bool depthBound, - int startInstanceUserData) => + int startInstanceUserData, + int baseVertexUserData = -1) => GetGraphicsPrograms(banks, targetExportMapping, pixelActive, depthBound); // taskLaunch: an automatic indirect draw launched by the task stage (MeshTaskLaunch). Providers without task launches diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.cs index 5c49a736f..a3fcf14fc 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.cs @@ -331,7 +331,7 @@ void TraceDisposition(string disposition) expandedIndices is null ? indexSize : (ulong)expandedIndices.Length, indexType); ref var state = ref record.State; - state.Begin(arguments.StartInstanceUserData); + state.Begin(arguments.StartInstanceUserData, arguments.BaseVertexUserData); if (!TryResolveDrawTargets(banks, in draw, ref state, record)) { TraceDisposition("no-targets"); @@ -522,7 +522,7 @@ private void DrawAutoCore(ulong submitId, RegisterBanks banks, in DrawAutoArgume ValidateChangedDrawRegisters(banks); var draw = new DrawCall("DrawAuto", RecordedOperation.DrawIndexAuto, arguments.VertexCount, arguments.InstanceCount, arguments.FirstInstance); ref var state = ref record.State; - state.Begin(arguments.StartInstanceUserData); + state.Begin(arguments.StartInstanceUserData, arguments.BaseVertexUserData); if (!TryResolveDrawTargets(banks, in draw, ref state, record)) { TraceDrawTargets(banks, "no-targets"); @@ -971,6 +971,10 @@ private static bool RequiresMeshExecution(uint stages) => private const uint TessellationStageBits = 0x7u; + // Whether the draw's vertex stage is a vertex program of its own: no tessellation, and no mesh stage the guest asks for. + internal static bool RunsPlainVertexProgram(uint stages) => + (stages & TessellationStageBits) == 0 && !RequiresMeshExecution(stages); + private bool UsesMeshExecution(RegisterBanks banks) => _pipelines.MeshShadersSupported && RequiresMeshExecution(banks.Context.ShaderStages) && banks.Shader.Vertex.ExportAddress != 0 && @@ -1023,7 +1027,8 @@ private void ResolveShaderPrograms(RegisterBanks banks, ref DrawState state, boo return; } - state.Programs = _pipelines.GetGraphicsPrograms(banks, targetExportMapping, state.PixelActive, state.Depth.HasTarget, state.StartInstanceUserData); + state.Programs = _pipelines.GetGraphicsPrograms(banks, targetExportMapping, state.PixelActive, state.Depth.HasTarget, state.StartInstanceUserData, + state.BaseVertexUserData); } [System.Runtime.CompilerServices.InlineArray(RenderingState.ColorAttachmentCapacity)] diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ResolvedCommands.cs b/src/SharpEmu.Libs/Gpu/Rendering/ResolvedCommands.cs index 80ee02064..f6b0f8cdd 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ResolvedCommands.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ResolvedCommands.cs @@ -33,11 +33,13 @@ internal struct DrawState public RenderingState Rendering; public GraphicsPrograms Programs; public int StartInstanceUserData; + public int BaseVertexUserData; - public static DrawState Create() => new() { PixelActive = true, Programs = null!, StartInstanceUserData = -1 }; + public static DrawState Create() => new() { PixelActive = true, Programs = null!, StartInstanceUserData = -1, BaseVertexUserData = -1 }; - public void Begin(int startInstanceUserData) + public void Begin(int startInstanceUserData, int baseVertexUserData = -1) { + BaseVertexUserData = baseVertexUserData; ColorCount = 0; Depth = default; DepthResolved = false; diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs b/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs index c6ed3f6cb..6e38b5742 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs @@ -237,6 +237,7 @@ public sealed class VertexInputInfo public uint PositionExportControl { get; init; } public ClipSpaceTransform ClipSpace { get; init; } public int StartInstanceUserData { get; set; } = -1; + public int BaseVertexUserData { get; set; } = -1; public ShaderStageResources Stage { get; set; } public VertexInputInfo WithoutStage() diff --git a/src/SharpEmu.Libs/PlayGo/PlayGoExports.cs b/src/SharpEmu.Libs/PlayGo/PlayGoExports.cs index aacb66db9..4fd1a53da 100644 --- a/src/SharpEmu.Libs/PlayGo/PlayGoExports.cs +++ b/src/SharpEmu.Libs/PlayGo/PlayGoExports.cs @@ -568,8 +568,18 @@ public static int PlayGoGetProgress(CpuContext ctx) TracePlayGo($"get_progress entries={numberOfEntries}"); Span progress = stackalloc byte[sizeof(ulong) * 2]; - BinaryPrimitives.WriteUInt64LittleEndian(progress, 0); - BinaryPrimitives.WriteUInt64LittleEndian(progress[sizeof(ulong)..], 0); + bool pgmChunks; + lock (_stateGate) + { + pgmChunks = _metadata.ChunkIdKnowledge == PlayGoChunkIdKnowledge.Assumed; + } + + // Every chunk is installed, so installed size equals total size. A title whose chunks come + // from playgo.pgm gets a non-zero pair, so progress / total reads 100%, not 0/0; every other + // title keeps the 0/0 it always read. + var size = pgmChunks ? 1ul : 0ul; + BinaryPrimitives.WriteUInt64LittleEndian(progress, size); + BinaryPrimitives.WriteUInt64LittleEndian(progress[sizeof(ulong)..], size); return ctx.Memory.TryWrite(outProgress, progress) ? (int)OrbisGen2Result.ORBIS_GEN2_OK : (int)OrbisGen2Result.ORBIS_GEN2_ERROR_MEMORY_FAULT; @@ -765,7 +775,7 @@ private static bool IsKnownChunkId(ushort chunkId) { lock (_stateGate) { - return _metadata.ChunkIdKnowledge == PlayGoChunkIdKnowledge.Unknown || + return _metadata.ChunkIdKnowledge != PlayGoChunkIdKnowledge.Authoritative || Array.BinarySearch(_metadata.ChunkIds, chunkId) >= 0; } } @@ -790,6 +800,7 @@ private static PlayGoMetadata LoadPlayGoMetadata() return CreateBaseChunkMetadata(PlayGoChunkIdKnowledge.Authoritative); } + var playGoPgm = GameFileOverlay.ResolveFile(Path.Combine(app0Root, "cache_ps5", "playgo.pgm")); var playGoDat = GameFileOverlay.ResolveFile(Path.Combine(app0Root, "sce_sys", "playgo-chunk.dat")); var scenarioJson = GameFileOverlay.ResolveFile(Path.Combine(app0Root, "sce_sys", "playgo-scenario.json")); var chunkDefsXml = GameFileOverlay.ResolveFile(Path.Combine(app0Root, "playgo-chunkdefs.xml")); @@ -816,6 +827,20 @@ private static PlayGoMetadata LoadPlayGoMetadata() // Ids outside the discovered set still return BAD_CHUNK_ID, so // title-side chunk enumeration still terminates. var installedChunkIds = DiscoverInstalledChunkIds(app0Root); + if (installedChunkIds.Length == 1) + { + // No pakchunk files either. PS5 titles ship cache_ps5/playgo.pgm, which carries the + // chunk count: Ghost of Yotei has nothing else, and with chunk 0 only its PlayGo + // queries failed and it exited at boot. + App0Archive.Extract(playGoPgm); + var pgmChunkIds = LoadPlayGoPgmChunkIds(playGoPgm); + if (pgmChunkIds.Length > 0) + { + TracePlayGo($"metadata_pgm chunks={pgmChunkIds.Length}"); + return new PlayGoMetadata(true, pgmChunkIds, PlayGoChunkIdKnowledge.Assumed); + } + } + TracePlayGo($"metadata_missing; fully-installed chunks=[{string.Join(',', installedChunkIds)}]"); return new PlayGoMetadata( true, @@ -844,6 +869,50 @@ private static PlayGoMetadata LoadPlayGoMetadata() PlayGoChunkIdKnowledge.Authoritative); } + // playgo.pgm header: "DMGP" magic at 0x00, little-endian chunk count at 0x10, + // header size 0x14. Chunk ids are 0..count-1. + private static ushort[] LoadPlayGoPgmChunkIds(string playGoPgm) + { + Span header = stackalloc byte[0x14]; + try + { + using var stream = File.OpenRead(playGoPgm); + if (stream.Length < header.Length) + { + return Array.Empty(); + } + + stream.ReadExactly(header); + } + catch (IOException) + { + return Array.Empty(); + } + catch (UnauthorizedAccessException) + { + return Array.Empty(); + } + + if (!header[..4].SequenceEqual("DMGP"u8)) + { + return Array.Empty(); + } + + var count = BinaryPrimitives.ReadUInt32LittleEndian(header[0x10..]); + if (count == 0 || count > (uint)ushort.MaxValue + 1u) + { + return Array.Empty(); + } + + var chunkIds = new ushort[checked((int)count)]; + for (var index = 0; index < chunkIds.Length; index++) + { + chunkIds[index] = (ushort)index; + } + + return chunkIds; + } + private static PlayGoMetadata CreateBaseChunkMetadata(PlayGoChunkIdKnowledge knowledge) => new( true, @@ -1017,6 +1086,9 @@ private enum PlayGoChunkIdKnowledge { Unknown, Authoritative, + // The list is derived rather than read (playgo.pgm gives only a count), so it is + // reported but an ID outside it is not rejected. + Assumed, } private sealed record PlayGoMetadata( diff --git a/src/SharpEmu.Libs/VideoOut/BindlessHeapViewTable.cs b/src/SharpEmu.Libs/VideoOut/BindlessHeapViewTable.cs new file mode 100644 index 000000000..07e7909db --- /dev/null +++ b/src/SharpEmu.Libs/VideoOut/BindlessHeapViewTable.cs @@ -0,0 +1,188 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.Libs.VideoOut; + +// The runs of set-1 elements the heap views of the draws hold (see BindlessHeap, HeapView): one run per heap V# and +// descriptor offset (BindlessHeapDescriptor.ViewKey), as long as its records. A view that is read again keeps its run, so the elements the shaders marked +// stay resolved. A new view takes over the run of a view of its shape that no pending command reads any more: a table the +// guest allocates for each frame is the same records at another address, and most of its elements stay as they are. +// Otherwise it takes free elements, then the elements of the views no pending command reads, least recently used first, +// and at last shares the run of a view of its shape that is still read, as one heap that moved (a title's whole texture +// heap, kept in two copies, is larger than half of set 1). +internal sealed class BindlessHeapViewTable(uint capacity) +{ + internal sealed class Region + { + // The heap whose records the run's elements hold now. + public required BindlessHeapDescriptor Heap { get; set; } + public required HeapView View { get; init; } + public ulong LastUsedTick; + + public bool Holds(uint element) => element >= View.First && element - View.First < View.Records; + + // The run's descriptors as a heap of their own, for reading them in guest memory: the first one's address, a + // stride apart, each of the size its heap reads (an R128 view's are 16 bytes). + public BindlessHeapDescriptor Descriptors => + Heap with { Base = View.DescriptorAddress(Heap, 0), Records = View.Records, Stride = View.Stride, Immediate = 0 }; + } + + // Sorted by first element; runs never overlap. + private readonly List _regions = []; + private readonly Dictionary _byHeap = []; + + public IReadOnlyList Regions => _regions; + + // The run of the heap view. A view without one takes over the run of a view of its shape last used at or before + // completedTick (moved: the run holds this heap's records from now on, and its elements are to be compared with them), + // or free elements, or those of the least recently used views no pending command reads (released sees each one before + // its elements are taken), or shares the run of a view of its shape that is still read (moved). Null when the view has + // no records or the table has no room for it. + public Region? Acquire(in BindlessHeapDescriptor descriptor, ulong tick, ulong completedTick, Action released, out bool moved) + { + moved = false; + var heap = descriptor.ViewKey; + if (_byHeap.TryGetValue(heap, out var region)) + { + region.LastUsedTick = tick; + return region; + } + + var records = Math.Min(heap.Records, capacity); + if (heap.Base == 0 || records == 0) + { + return null; + } + + var shape = HeapView.Of(heap, 0, records); + if (FindShape(heap, shape, tick, completedTick) is { } idle) + { + moved = true; + return Move(idle, heap, tick); + } + + int position; + uint first; + while (!TryFindGap(records, out position, out first)) + { + Region? oldest = null; + foreach (var candidate in _regions) + { + if (candidate.LastUsedTick <= completedTick && candidate.LastUsedTick < tick && + (oldest is null || candidate.LastUsedTick < oldest.LastUsedTick)) + { + oldest = candidate; + } + } + + if (oldest is null) + { + if (FindShape(heap, shape, ulong.MaxValue, ulong.MaxValue) is not { } shared) + { + return null; + } + + moved = true; + return Move(shared, heap, tick); + } + + Release(oldest, released); + } + + region = new Region { Heap = heap, View = HeapView.Of(heap, first, records), LastUsedTick = tick }; + _regions.Insert(position, region); + _byHeap.Add(heap, region); + return region; + } + + // The least recently used run of a view of this shape last used before tick and at or before completedTick. + private Region? FindShape(in BindlessHeapDescriptor heap, HeapView shape, ulong tick, ulong completedTick) + { + Region? found = null; + foreach (var candidate in _regions) + { + if (candidate.Heap.Sampler == heap.Sampler && candidate.Heap.R128 == heap.R128 && candidate.View with { First = 0 } == shape && + candidate.LastUsedTick <= completedTick && candidate.LastUsedTick < tick && + (found is null || candidate.LastUsedTick < found.LastUsedTick)) + { + found = candidate; + } + } + + return found; + } + + private Region Move(Region region, in BindlessHeapDescriptor heap, ulong tick) + { + _byHeap.Remove(region.Heap); + region.Heap = heap; + region.LastUsedTick = tick; + _byHeap.Add(heap, region); + return region; + } + + // The run that holds the element, or null. + public Region? Find(uint element) + { + var low = 0; + var high = _regions.Count - 1; + while (low <= high) + { + var middle = (low + high) >> 1; + var region = _regions[middle]; + if (element < region.View.First) + { + high = middle - 1; + } + else if (element - region.View.First >= region.View.Records) + { + low = middle + 1; + } + else + { + return region; + } + } + + return null; + } + + // Gives up the runs last used before idleBefore that no pending command reads. + public void ReleaseIdle(ulong idleBefore, ulong completedTick, Action released) + { + for (var index = _regions.Count - 1; index >= 0; index--) + { + var region = _regions[index]; + if (region.LastUsedTick < idleBefore && region.LastUsedTick <= completedTick) + { + Release(region, released); + } + } + } + + private void Release(Region region, Action released) + { + released(region); + _regions.Remove(region); + _byHeap.Remove(region.Heap); + } + + private bool TryFindGap(uint records, out int position, out uint first) + { + first = 0; + for (position = 0; position < _regions.Count; position++) + { + var region = _regions[position]; + if (region.View.First - first >= records) + { + return true; + } + + first = region.View.First + region.View.Records; + } + + return capacity - first >= records; + } +} diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.BindlessHeap.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.BindlessHeap.cs index 6f490bc33..acd44d60f 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.BindlessHeap.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.BindlessHeap.cs @@ -12,10 +12,12 @@ namespace SharpEmu.Libs.VideoOut; // Descriptor set 1: the bindless heaps a program reads at a record only its shader knows (see BindlessHeap). Every -// element starts as a null descriptor. The shader marks each record it reads in a feedback bitset; once the marking -// work completes, the host reads the record's T# or S# from the guest heap and writes its view or sampler. Records are -// read again periodically, and a heap image's contents and layout are made current before each command that reads -// set 1. +// element starts as a null descriptor. Each heap view of a draw (a heap V# and the offset of a descriptor in its records) +// holds a run of elements (BindlessHeapViewTable), which the draw's shader data names. The shader marks each element it +// reads in a feedback bitset; once the marking work completes, the host reads the record's T# or S# from the guest heap +// and writes its view or sampler. The records of a view are read again periodically while draws read the view, and a +// heap image's contents and layout are made current before each command that reads set 1. A record that holds an integer +// texture gets an integer view, and the feedback buffer tells the shader the element's numeric class. internal static unsafe partial class VulkanVideoPresenter { // Revalidation reads the heap records it compares in runs, one guest read per run of nearby records, instead of one @@ -78,12 +80,12 @@ internal interface IHeapRunVisitor internal static void VisitHeapRuns(ref T visitor, ReadOnlySpan indexes, int from, int to, bool sampler, Span buffer, Span scratch) where T : IHeapRunVisitor { - var bytes = sampler ? BindlessHeap.SamplerRecordBytes : BindlessHeap.ImageRecordBytes; indexes = indexes[..to]; var start = from; while (start < to) { var heap = visitor.Heap(sampler); + var bytes = heap.DescriptorBytes; if (heap.Base == 0 || indexes[start] >= heap.Records) { _ = visitor.Visit(start, ReadOnlySpan.Empty); @@ -91,10 +93,12 @@ internal static void VisitHeapRuns(ref T visitor, ReadOnlySpan indexes, continue; } - var end = HeapRecordRunEnd(indexes, start, bytes, heap.Records); + // The records of a heap are its stride apart; each holds the descriptor in its first bytes. + var stride = Math.Max(heap.Stride, bytes); + var end = HeapRecordRunEnd(indexes, start, stride, heap.Records); var first = indexes[start]; - var run = buffer[..checked((int)(((ulong)indexes[end - 1] - first + 1) * bytes))]; - if (!visitor.TryRead(heap.Base + (ulong)first * bytes, run)) + var run = buffer[..checked((int)(((ulong)indexes[end - 1] - first) * stride + bytes))]; + if (!visitor.TryRead(heap.Base + (ulong)first * stride, run)) { for (; start < end; start++) { @@ -106,7 +110,7 @@ internal static void VisitHeapRuns(ref T visitor, ReadOnlySpan indexes, while (start < end) { - var offset = checked((int)((indexes[start] - first) * bytes)); + var offset = checked((int)((indexes[start] - first) * stride)); var resolved = visitor.Visit(start, System.Runtime.InteropServices.MemoryMarshal.Cast(run.Slice(offset, (int)bytes))); start++; if (resolved) @@ -132,16 +136,23 @@ private sealed partial class Presenter private static ulong FeedbackBytes => (ulong)BindlessHeap.FeedbackWords * sizeof(uint); + // The mark bitsets, which are read back; the element classes after them are the host's own. + private static ulong MarkBytes => (ulong)BindlessHeap.MarkWords * sizeof(uint); + // One record the shaders marked: the words it was resolved from and what set 1 holds for it. private sealed class HeapEntry { public int Slot; public uint Index; + // The heap view whose run holds the element; null for a call record's element. + public BindlessHeapViewTable.Region? Region; public uint[] Words = []; public CachedImage? Image; public ResourceSlotIdentifier ImageIdentifier; public ImageRequest Request; public bool Resolved; + // The numeric class of the view a resolved image entry holds. + public ImageNumericClass NumericClass; } private bool _bindlessHeapSupported; @@ -154,20 +165,27 @@ private sealed class HeapEntry private int _heapFeedbackReady; private int _heapFeedbackCopyPending; private uint[] _heapMarked = []; + // The element classes the feedback buffer holds (BindlessHeap.ClassCode). + private uint[] _heapClasses = []; private readonly Dictionary<(int Slot, uint Index), HeapEntry> _heapEntries = new(); private readonly Dictionary> _heapEntriesByImage = new(ReferenceEqualityComparer.Instance); private readonly HashSet _heapChangedImages = new(ReferenceEqualityComparer.Instance); - private BindlessHeapDescriptor _textureHeap; - private BindlessHeapDescriptor _samplerHeap; + // The image arrays share their elements (a record has one element in each), and so do the two sampler arrays. + private readonly BindlessHeapViewTable _heapImageViews = new(BindlessHeap.CallRecordFirstIndex); + private readonly BindlessHeapViewTable _heapSamplerViews = new(BindlessHeap.CallRecordFirstIndex); + private Action? _heapRegionReleased; + // The entries of each view in record order, and when their records were last compared with the guest's. + private sealed class HeapRegionEntries + { + public readonly List Order = []; + public HeapEntry[]? Snapshot; + public uint[]? Records; + public ulong ValidatedTick; + } + + private readonly Dictionary _heapRegionEntries = new(ReferenceEqualityComparer.Instance); private ulong _heapRevalidatedTick; private object? _heapPreparedFor; - // Changes whenever _heapEntries does; the entries in record order (image heap, then sampler heap, each by - // index), their indexes and where the sampler heap's begin, as of _heapRunVersion; and the run buffer. - private long _heapEntriesVersion; - private long _heapRunVersion; - private HeapEntry[]? _heapRunOrder; - private uint[]? _heapRunIndexes; - private int _heapRunSamplerStart; private byte[]? _heapRunBytes; private Sampler _heapNullSampler; private Action? _heapImageChanged; @@ -293,7 +311,7 @@ private void EnsureBindlessHeap() SetDebugName(ObjectType.DescriptorSet, set.Handle, "SharpEmu bindless heap"); _heapFeedback = new GpuBuffer(_deviceInfo, _scheduler, GpuBufferUsage.DeviceLocal, 0, GpuBuffer.AllFlags, FeedbackBytes); - _heapFeedbackReadback = new GpuBuffer(_deviceInfo, _scheduler, GpuBufferUsage.Download, 0, GpuBuffer.AllFlags, FeedbackBytes); + _heapFeedbackReadback = new GpuBuffer(_deviceInfo, _scheduler, GpuBufferUsage.Download, 0, GpuBuffer.AllFlags, MarkBytes); var completedReadback = _heapFeedbackReadback; _heapFeedbackCopyCompleted = () => { @@ -303,7 +321,8 @@ private void EnsureBindlessHeap() }; _ = BeginBatchedGuestCommands(); _heapFeedback.Fill(0, FeedbackBytes, 0); - _heapMarked = new uint[BindlessHeap.FeedbackWords]; + _heapMarked = new uint[BindlessHeap.MarkWords]; + _heapClasses = new uint[BindlessHeap.ClassWords]; Span nullSampler = stackalloc uint[4]; _heapNullSampler = _samplerStore.GetSampler(new SamplerDescriptorWords(nullSampler), integerView: false); _heapImageChanged = image => @@ -313,6 +332,7 @@ private void EnsureBindlessHeap() _heapChangedImages.Add(image); } }; + _heapRegionReleased = ReleaseHeapRegion; // Every element is a null view or the null sampler until its record is read. var nullImages = new DescriptorImageInfo[BindlessHeap.Capacity]; @@ -363,7 +383,9 @@ private void DestroyBindlessHeap() _heapEntriesByImage.Clear(); _heapEntries.Clear(); - _heapEntriesVersion++; + _heapRegionEntries.Clear(); + _heapImageViews.ReleaseIdle(ulong.MaxValue, ulong.MaxValue, static _ => { }); + _heapSamplerViews.ReleaseIdle(ulong.MaxValue, ulong.MaxValue, static _ => { }); _callRecordEntries.Clear(); Array.Clear(_callRecordNext); _heapFeedback?.Dispose(); @@ -398,9 +420,13 @@ internal void ForgetHeapPreparation(object preparation) } } - // Before the images of a draw or dispatch that reads set 1 are found: the heap V#s, the records marked since the - // last look, records rewritten since they were read, and heap images whose contents or layout changed. - internal void PrepareBindlessHeap(object preparation, BindlessHeapDescriptor[] heaps) + // A view no draw has read for this many submission ticks gives its elements up: a table the guest allocates + // for each frame is a new view whenever it moves, and the memory of the old one holds other data by then. + private const ulong HeapIdleTicks = 256; + + // Before the images of a draw or dispatch that reads set 1 are found: the records marked since the last look, + // records rewritten since they were read, and heap images whose contents or layout changed. + internal void PrepareBindlessHeap(object preparation) { if (ReferenceEquals(_heapPreparedFor, preparation)) { @@ -409,32 +435,110 @@ internal void PrepareBindlessHeap(object preparation, BindlessHeapDescriptor[] h _heapPreparedFor = preparation; EnsureBindlessHeap(); - var revalidate = _scheduler.CurrentTick - _heapRevalidatedTick >= HeapRevalidationTicks; - foreach (var heap in heaps) + PollHeapFeedback(); + if (_scheduler.CurrentTick - _heapRevalidatedTick >= HeapRevalidationTicks) { - ref var current = ref heap.Sampler ? ref _samplerHeap : ref _textureHeap; - if (current == heap) + RevalidateHeapEntries(); + } + + RefreshChangedHeapImages(); + } + + // The runs of set-1 elements of a stage's heap views, as the stage's shader data (HeapView, two dwords each). + internal void WriteHeapViews(ReadOnlySpan heaps, Span words) + { + EnsureBindlessHeap(); + var tick = _scheduler.CurrentTick; + var completed = _scheduler.CompletedTick; + for (var index = 0; index < heaps.Length; index++) + { + ref readonly var heap = ref heaps[index]; + var region = (heap.Sampler ? _heapSamplerViews : _heapImageViews).Acquire(heap, tick, completed, _heapRegionReleased!, out var moved); + var view = region?.View ?? HeapView.None; + words[index * (int)HeapView.DwordCount] = view.Word0; + words[index * (int)HeapView.DwordCount + 1] = view.Word1; + if (region is null) { + if (heap.Base != 0 && heap.Records != 0 && _heapReports++ < 16) + { + Console.Error.WriteLine( + $"[GPU][WARN] Bindless heap view has no elements left: heap=0x{heap.Base:X16} records={heap.Records} stride={heap.Stride}; its records read as null."); + } + continue; } - if (current.Base != 0 && current.Base != heap.Base && _heapReports++ < 16) + // Only a view some draw reads is compared with the guest's records: an idle view's memory may hold + // anything, and is read again when a draw comes back to it. A run that moved to this heap is compared + // now: the records that are the same textures at the new address keep their elements. + if (_heapRegionEntries.TryGetValue(region, out var entries) && (moved || tick - entries.ValidatedTick >= HeapRevalidationTicks)) { - Console.Error.WriteLine( - $"[GPU][WARN] Bindless {(heap.Sampler ? "sampler" : "texture")} heap moved: from=0x{current.Base:X16} to=0x{heap.Base:X16} records={heap.Records}"); + RevalidateHeapRegion(region, entries); } - current = heap; - revalidate = true; } + } - PollHeapFeedback(); - if (revalidate) + private void AddHeapEntry(int slot, uint index, BindlessHeapViewTable.Region region) + { + var entry = new HeapEntry { Slot = slot, Index = index, Region = region }; + _heapEntries[(slot, index)] = entry; + if (!_heapRegionEntries.TryGetValue(region, out var entries)) { - RevalidateHeapEntries(); + entries = new HeapRegionEntries { ValidatedTick = _scheduler.CurrentTick }; + _heapRegionEntries.Add(region, entries); } - RefreshChangedHeapImages(); + var position = entries.Order.Count; + while (position > 0 && (entries.Order[position - 1].Index > index || + (entries.Order[position - 1].Index == index && entries.Order[position - 1].Slot > slot))) + { + position--; + } + + entries.Order.Insert(position, entry); + entries.Snapshot = null; + entries.Records = null; + entry.Words = ReadHeapRecord(entry); + ResolveHeapEntry(entry); + } + + // A view gives its elements up: they read null again, and a later view that takes them starts unmarked. + private void ReleaseHeapRegion(BindlessHeapViewTable.Region region) + { + var sampler = region.Heap.Sampler; + if (_heapRegionEntries.Remove(region, out var entries)) + { + foreach (var entry in entries.Order) + { + _heapEntries.Remove((entry.Slot, entry.Index)); + _heapMarked[entry.Slot * (int)BindlessHeap.FeedbackWordsPerArray + (int)(entry.Index >> 5)] &= ~(1u << (int)(entry.Index & 31)); + var released = DetachHeapEntry(entry); + if (sampler) + { + entry.Words = []; + WriteHeapSampler(entry); + } + else + { + WriteHeapImage(entry.Slot, entry.Index, default); + } + + released?.Invoke(); + } + } + + // The marks of the words the run touches: a neighbor's shader marks its element again when it reads it. + var firstSlot = sampler ? BindlessHeap.SamplerSlot : 0; + var endSlot = sampler ? BindlessHeap.ArrayCount : BindlessHeap.ImageKinds.Length; + var firstWord = region.View.First >> 5; + var endWord = (region.View.First + region.View.Records + 31) >> 5; + _ = BeginBatchedGuestCommands(); + for (var slot = firstSlot; slot < endSlot; slot++) + { + _heapFeedback!.Fill( + ((ulong)slot * BindlessHeap.FeedbackWordsPerArray + firstWord) * sizeof(uint), (ulong)(endWord - firstWord) * sizeof(uint), 0); + } } public void BindBindlessHeap(CommandBuffer command, PipelineBindPoint bindPoint, PipelineLayout layout) @@ -454,10 +558,10 @@ private void PollHeapFeedback() if (Interlocked.Exchange(ref _heapFeedbackReady, 0) != 0) { var completed = _heapFeedbackReadback!; - completed.Invalidate(0, FeedbackBytes); + completed.Invalidate(0, MarkBytes); // Keep the slot pending through consumption, including any reentrant preparation. No later GPU copy // may overwrite these mapped words until every marked record has been resolved. - ResolveMarkedRecords(MemoryMarshal.Cast(completed.Mapped[..(int)FeedbackBytes])); + ResolveMarkedRecords(MemoryMarshal.Cast(completed.Mapped[..(int)MarkBytes])); Volatile.Write(ref _heapFeedbackCopyPending, 0); } @@ -471,7 +575,7 @@ private void PollHeapFeedback() Volatile.Write(ref _heapFeedbackCopyPending, 1); _ = BeginBatchedGuestCommands(); readback.CopyFrom( - _scheduler.Current, feedback, 0, 0, FeedbackBytes, + _scheduler.Current, feedback, 0, 0, MarkBytes, AccessFlags.ShaderWriteBit | AccessFlags.MemoryWriteBit, AccessFlags.None, AccessFlags.ShaderReadBit | AccessFlags.ShaderWriteBit | AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit, AccessFlags.HostReadBit); @@ -501,11 +605,15 @@ private void ResolveMarkedRecords(ReadOnlySpan marked) continue; } - var entry = new HeapEntry { Slot = slot, Index = index }; - _heapEntries[(slot, index)] = entry; - _heapEntriesVersion++; - entry.Words = ReadHeapRecord(slot, index); - ResolveHeapEntry(entry); + // An element no view holds was marked before its view gave it up. + var sampler = slot >= BindlessHeap.ImageKinds.Length; + if ((sampler ? _heapSamplerViews : _heapImageViews).Find(index) is not { } region) + { + _heapMarked[word] &= ~(1u << (int)(index & 31)); + continue; + } + + AddHeapEntry(slot, index, region); } } } @@ -513,17 +621,10 @@ private void ResolveMarkedRecords(ReadOnlySpan marked) private void RevalidateHeapEntries() { _heapRevalidatedTick = _scheduler.CurrentTick; - Span scratch = stackalloc uint[8]; - if (HeapBulkReadsActive) + if (_heapRevalidatedTick > HeapIdleTicks) { - RevalidateHeapEntriesInRuns(scratch); - } - else - { - foreach (var entry in _heapEntries.Values) - { - RevalidateHeapEntry(entry, scratch[..ReadHeapRecord(entry.Slot, entry.Index, scratch)]); - } + _heapImageViews.ReleaseIdle(_heapRevalidatedTick - HeapIdleTicks, _scheduler.CompletedTick, _heapRegionReleased!); + _heapSamplerViews.ReleaseIdle(_heapRevalidatedTick - HeapIdleTicks, _scheduler.CompletedTick, _heapRegionReleased!); } // A call record entry is named by its words, which never change; its image stays in use. @@ -545,7 +646,19 @@ private bool RevalidateHeapEntry(HeapEntry entry, ReadOnlySpan words) _ = _imageCache.GetImage(entry.ImageIdentifier); } - if (words.SequenceEqual(entry.Words)) + // An R128 T# is its four words; the rest of the T# is zero. + Span extended = stackalloc uint[8]; + if (words.Length == 4 && entry.Region is { Heap: { Sampler: false, R128: true } }) + { + extended.Clear(); + words.CopyTo(extended); + words = extended; + } + + // A T# that had no image when it was last looked at (its texture was not mapped) is looked at again. + if (words.SequenceEqual(entry.Words) && + (entry.Resolved || entry.Slot >= BindlessHeap.ImageKinds.Length || + HeapRecordClass(entry, words) == ImageNumericClass.Unsupported)) { return false; } @@ -555,67 +668,70 @@ private bool RevalidateHeapEntry(HeapEntry entry, ReadOnlySpan words) return true; } - // The presenter's side of VisitHeapRuns, over the entries in record order. - private readonly struct HeapRunVisitor(Presenter owner, HeapEntry[] order) : IHeapRunVisitor + // The presenter's side of VisitHeapRuns, over the entries of one heap view in record order: the view's + // descriptors are its heap's records, a stride apart. + private readonly struct HeapRunVisitor(Presenter owner, HeapEntry[] order, BindlessHeapViewTable.Region region) : IHeapRunVisitor { - public BindlessHeapDescriptor Heap(bool sampler) => sampler ? owner._samplerHeap : owner._textureHeap; + public BindlessHeapDescriptor Heap(bool sampler) => region.Descriptors with { Sampler = sampler }; public bool TryRead(ulong address, Span destination) => owner._guestMemory.TryRead(address, destination); - public int ReadRecord(int position, Span words) => - owner.ReadHeapRecord(order[position].Slot, order[position].Index, words); + public int ReadRecord(int position, Span words) => owner.ReadHeapRecord(order[position], words); public bool Visit(int position, ReadOnlySpan words) => owner.RevalidateHeapEntry(order[position], words); } - // Every entry, in record order, compared with words read in runs (HeapRecordRunEnd). - private void RevalidateHeapEntriesInRuns(Span scratch) + // The entries of one view, in record order, compared with words read in runs (HeapRecordRunEnd). + private void RevalidateHeapRegion(BindlessHeapViewTable.Region region, HeapRegionEntries entries) { - if (_heapRunOrder is null || _heapRunIndexes is null || _heapRunVersion != _heapEntriesVersion) + entries.ValidatedTick = _scheduler.CurrentTick; + // The arrays are replaced, never changed, when the entries change: a nested preparation leaves these intact. + var order = entries.Snapshot ??= [.. entries.Order]; + var records = entries.Records ??= Array.ConvertAll(order, entry => entry.Index - region.View.First); + Span scratch = stackalloc uint[8]; + if (HeapBulkReadsActive) { - var order = _heapEntries.Values.ToArray(); - Array.Sort(order, static (left, right) => - { - var heap = (left.Slot >= BindlessHeap.ImageKinds.Length).CompareTo(right.Slot >= BindlessHeap.ImageKinds.Length); - return heap != 0 ? heap : left.Index != right.Index ? left.Index.CompareTo(right.Index) : left.Slot.CompareTo(right.Slot); - }); - _heapRunOrder = order; - _heapRunIndexes = Array.ConvertAll(order, static entry => entry.Index); - _heapRunSamplerStart = Array.FindIndex(order, static entry => entry.Slot >= BindlessHeap.ImageKinds.Length); - if (_heapRunSamplerStart < 0) _heapRunSamplerStart = order.Length; - _heapRunVersion = _heapEntriesVersion; - } - - // The arrays are replaced, never changed, when the entries change: a nested revalidation leaves these intact. - var runOrder = _heapRunOrder!; - var runIndexes = _heapRunIndexes!; - var samplerStart = _heapRunSamplerStart; - var visitor = new HeapRunVisitor(this, runOrder); - var buffer = (_heapRunBytes ??= new byte[HeapRunMaxBytes]).AsSpan(); - VisitHeapRuns(ref visitor, runIndexes, 0, samplerStart, sampler: false, buffer, scratch); - VisitHeapRuns(ref visitor, runIndexes, samplerStart, runOrder.Length, sampler: true, buffer, scratch); + var visitor = new HeapRunVisitor(this, order, region); + VisitHeapRuns(ref visitor, records, 0, order.Length, region.Heap.Sampler, (_heapRunBytes ??= new byte[HeapRunMaxBytes]).AsSpan(), scratch); + return; + } + + foreach (var entry in order) + { + RevalidateHeapEntry(entry, scratch[..ReadHeapRecord(entry, scratch)]); + } } - // The record's words, or none when the heap has no such record or it cannot be read. - private uint[] ReadHeapRecord(int slot, uint index) + // The words of the entry's record, or none when its heap has no such record or it cannot be read. + private uint[] ReadHeapRecord(HeapEntry entry) { Span words = stackalloc uint[8]; - return words[..ReadHeapRecord(slot, index, words)].ToArray(); + return words[..ReadHeapRecord(entry, words)].ToArray(); } // Revalidation compares current words in scratch; only a changed entry needs a new retained array. - private int ReadHeapRecord(int slot, uint index, Span words) + private int ReadHeapRecord(HeapEntry entry, Span words) { - var sampler = slot >= BindlessHeap.ImageKinds.Length; - var heap = sampler ? _samplerHeap : _textureHeap; - var bytes = sampler ? BindlessHeap.SamplerRecordBytes : BindlessHeap.ImageRecordBytes; - if (heap.Base == 0 || index >= heap.Records) + if (entry.Region is not { } region || !region.Holds(entry.Index)) + { + return 0; + } + + var count = checked((int)(region.Heap.DescriptorBytes / sizeof(uint))); + var address = region.View.DescriptorAddress(region.Heap, entry.Index - region.View.First); + if (!_guestMemory.TryRead(address, MemoryMarshal.AsBytes(words[..count]))) { return 0; } - var count = checked((int)(bytes / sizeof(uint))); - return _guestMemory.TryRead(heap.Base + (ulong)index * bytes, MemoryMarshal.AsBytes(words[..count])) ? count : 0; + if (region.Heap is { Sampler: false, R128: true }) + { + // An R128 T# is its four words; the rest of the T# is zero. + words[count..8].Clear(); + count = 8; + } + + return count; } private void ResolveHeapEntry(HeapEntry entry) @@ -628,9 +744,10 @@ private void ResolveHeapEntry(HeapEntry entry) else { ImageView view = default; - if (entry.Words.Length == 8 && ResourceMaterializer.IsFloatHeapImage(entry.Words)) + var numericClass = HeapRecordClass(entry, entry.Words); + if (numericClass != ImageNumericClass.Unsupported) { - view = AcquireHeapImage(entry); + view = AcquireHeapImage(entry, numericClass); } WriteHeapImage(entry.Slot, entry.Index, view); @@ -640,7 +757,17 @@ private void ResolveHeapEntry(HeapEntry entry) released?.Invoke(); } - private static ShaderImageShape HeapImageShape(int slot) + // The numeric class of the view an array of this slot holds for the record, or Unsupported when it holds none: + // every class holds float textures, and the ones with integer forms hold integer textures too. + private static ImageNumericClass HeapRecordClass(HeapEntry entry, ReadOnlySpan words) + { + var numericClass = words.Length == 8 + ? ResourceMaterializer.HeapImageNumericClass(words, entry.Region is { Heap.R128: true }) + : ImageNumericClass.Unsupported; + return numericClass == ImageNumericClass.Float || BindlessHeap.HoldsIntegers(entry.Slot) ? numericClass : ImageNumericClass.Unsupported; + } + + private static ShaderImageShape HeapImageShape(int slot, ImageNumericClass numericClass, bool r128) { var heapClass = BindlessHeap.ImageClasses[slot]; var dimension = heapClass.Dimension; @@ -650,8 +777,14 @@ private static ShaderImageShape HeapImageShape(int slot) Cube: heapClass.Cube, Storage: false, DynamicMip: false, - NumericClass: TextureNumericClass.Float, + NumericClass: numericClass switch + { + ImageNumericClass.Uint => TextureNumericClass.Uint, + ImageNumericClass.Sint => TextureNumericClass.Sint, + _ => TextureNumericClass.Float, + }, OneDimensional: dimension is ImageDimension.Dim1D or ImageDimension.Dim1DArray, + R128: r128, DepthCompare: heapClass.Compare); } @@ -659,14 +792,15 @@ private static bool IsDepthViewFormat(Format format) => format is Format.D16Unorm or Format.D32Sfloat or Format.D24UnormS8Uint or Format.D32SfloatS8Uint or Format.D16UnormS8Uint; // Finds the record's image the way a draw finds a texture, and leaves it in the general layout the heap reads. - private ImageView AcquireHeapImage(HeapEntry entry) + private ImageView AcquireHeapImage(HeapEntry entry, ImageNumericClass numericClass) { TextureRequestResolution resolution; try { using (ImageRequestBuilders.RejectInvalidDescriptors()) { - resolution = ImageRequestBuilders.Texture(entry.Words, HeapImageShape(entry.Slot)); + resolution = ImageRequestBuilders.Texture(entry.Words, + HeapImageShape(entry.Slot, numericClass, entry.Region is { Heap.R128: true })); } } catch (TextureDescriptorRejectedException) @@ -675,7 +809,10 @@ private ImageView AcquireHeapImage(HeapEntry entry) } var request = resolution.Request; - if (ImageDescription.IsEmptyRange(request.Description.Data)) + // The record of a table may hold no T# the guest uses (a record it has not filled, one whose memory it uses + // for other data by now, or the T# of a texture it has unloaded): words that name no mapped guest memory are + // no image for now. + if (ImageDescription.IsEmptyRange(request.Description.Data) || !_imageCache.IsBackedImageRange(request.Description.Data)) { return default; } @@ -690,8 +827,9 @@ private ImageView AcquireHeapImage(HeapEntry entry) _imageCache.ApplyNativeColorClear(identifier, resolution.Request); var image = _imageCache.GetImage(identifier); var viewDescription = resolution.Request.View; - // Depth-reference sampling needs a depth view; an integer view cannot stand in for the float class. - if (!image.SupportsViewType(viewDescription) || ViewFormatRules.IsIntegerFormat(viewDescription.Format) || + // Depth-reference sampling needs a depth view; the view has the numeric class the shader reads the element by. + if (!image.SupportsViewType(viewDescription) || + ViewFormatRules.IsIntegerFormat(viewDescription.Format) != (numericClass != ImageNumericClass.Float) || (BindlessHeap.ImageClasses[entry.Slot].Compare && !IsDepthViewFormat(viewDescription.Format))) { return default; @@ -703,6 +841,7 @@ private ImageView AcquireHeapImage(HeapEntry entry) entry.ImageIdentifier = identifier; entry.Request = resolution.Request; entry.Resolved = true; + entry.NumericClass = numericClass; if (!_heapEntriesByImage.TryGetValue(image, out var entries)) { entries = []; @@ -750,6 +889,33 @@ private void WriteHeapImage(int slot, uint index, ImageView view) PImageInfo = &info, }; _vk.UpdateDescriptorSets(_device, 1, &write, 0, null); + WriteHeapElementClass(index); + } + + // The numeric class of the element at index, for the shaders: that of the integer view an array holds there (the + // arrays hold views of one record at an index), or float. + private void WriteHeapElementClass(uint index) + { + var code = 0u; + for (var slot = 0; slot < BindlessHeap.ImageKinds.Length && code == 0; slot++) + { + if (_heapEntries.TryGetValue((slot, index), out var entry) && entry.Resolved) + { + code = BindlessHeap.ClassCode(entry.NumericClass); + } + } + + var word = (int)(index >> (int)BindlessHeap.ClassWordShift); + var shift = (int)((index & (BindlessHeap.ClassesPerWord - 1)) * BindlessHeap.ClassBits); + var classes = (_heapClasses[word] & ~(BindlessHeap.ClassMask << shift)) | (code << shift); + if (classes == _heapClasses[word]) + { + return; + } + + _heapClasses[word] = classes; + _ = BeginBatchedGuestCommands(); + _heapFeedback!.Fill((BindlessHeap.MarkWords + (ulong)word) * sizeof(uint), sizeof(uint), classes); } private void WriteHeapSampler(HeapEntry entry) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CachedImages.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CachedImages.cs index a90cd1109..bb253c1b8 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CachedImages.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.CachedImages.cs @@ -717,6 +717,17 @@ private void AcquireTextureViews(TextureResource[] bindings, IReadOnlyList + binding.IsStorage && ViewFormatRules.IsStencilViewFormat(binding.Request.View.Format) && + _imageCache.TryGetImage(binding.ImageIdentifier, out var image) && image.Description.HasStencil && + !FitsStencilPlane(binding.Request.Description, image) && + !_imageCache.TryFindStencilOwner(binding.Request.Description.Data, out _); + + private static bool FitsStencilPlane(in ImageDescription request, CachedImage attachment) => + request.Data.Address == attachment.Description.Stencil.Address && request.Data.Size <= attachment.Description.Stencil.Size; + private CachedImage AcquireStencilStorage(TextureResource binding, CachedImage attachment, bool writeBack = true) { if (_worker) @@ -724,15 +735,32 @@ private CachedImage AcquireStencilStorage(TextureResource binding, CachedImage a throw Serial("stencil storage", resumable: true); } + // The view can be smaller than the attachment (a dynamic-resolution pass writes only + // the region it renders); the storage image then has the view's size. var description = binding.Request.Description; + var attachmentIdentifier = binding.ImageIdentifier; + if (!FitsStencilPlane(description, attachment) && + _imageCache.TryFindStencilOwner(description.Data, out var owner)) + { + // The shader's view is the stencil plane of another depth surface, not the one the + // lookup returned: the owner of that plane carries the stencil. + attachmentIdentifier = owner; + attachment = _imageCache.GetImage(owner); + } + if (description.Data.Address != attachment.Description.Stencil.Address || description.Data.Size > attachment.Description.Stencil.Size || - description.Extent.Width != attachment.Backing.Extent.Width || description.Extent.Height != attachment.Backing.Extent.Height || + description.Extent.Width > attachment.Backing.Extent.Width || description.Extent.Height > attachment.Backing.Extent.Height || description.Resources.Levels != 1 || description.Resources.Layers != attachment.Backing.Layers) { - throw SubmissionScheduler.Fatal("The stencil storage request does not cover its attachment's stencil layout."); + throw SubmissionScheduler.Fatal( + $"The stencil storage request does not fit its attachment's stencil layout: " + + $"request=0x{description.Data.Address:X}+0x{description.Data.Size:X} {description.Extent.Width}x{description.Extent.Height} " + + $"levels={description.Resources.Levels} layers={description.Resources.Layers} " + + $"stencil=0x{attachment.Description.Stencil.Address:X}+0x{attachment.Description.Stencil.Size:X} " + + $"attachment={attachment.Backing.Extent.Width}x{attachment.Backing.Extent.Height} layers={attachment.Backing.Layers}."); } - if (writeBack && _hasBoundDepth && _boundDepth.Image == binding.ImageIdentifier && + if (writeBack && _hasBoundDepth && _boundDepth.Image == attachmentIdentifier && (_boundDepthLoadState.StencilTestEnabled || _boundDepthLoadState.StencilClearEnabled)) { throw SubmissionScheduler.Fatal("A stencil storage write cannot share an active stencil attachment."); @@ -742,6 +770,13 @@ private CachedImage AcquireStencilStorage(TextureResource binding, CachedImage a var stencilImages = preparation.StencilStorageImages ??= new(); if (stencilImages.TryGetValue(attachment, out var storage)) { + if (storage.Backing.Extent.Width != description.Extent.Width || storage.Backing.Extent.Height != description.Extent.Height) + { + throw SubmissionScheduler.Fatal( + $"Two stencil storage views of one attachment in a draw differ in size: " + + $"{storage.Backing.Extent.Width}x{storage.Backing.Extent.Height} and {description.Extent.Width}x{description.Extent.Height}."); + } + if (writeBack) { preparation.StencilStorageWriteBackImages ??= new(); @@ -757,13 +792,13 @@ private CachedImage AcquireStencilStorage(TextureResource binding, CachedImage a Role = ImageRole.Texture, View = binding.Request.View with { Usage = ImageUsageFlags.SampledBit }, }; - _imageCache.AcquireTextureView(binding.ImageIdentifier, sampledRequest); + _imageCache.AcquireTextureView(attachmentIdentifier, sampledRequest); if (writeBack) { - _imageCache.MarkGpuWritten(binding.ImageIdentifier); + _imageCache.MarkGpuWritten(attachmentIdentifier); } - storage = attachment.CreateStencilStorageImage(); + storage = attachment.CreateStencilStorageImage(description.Extent.Width, description.Extent.Height); stencilImages.Add(attachment, storage); storage.Binding.ShaderWrite = writeBack; if (writeBack) @@ -772,7 +807,7 @@ private CachedImage AcquireStencilStorage(TextureResource binding, CachedImage a preparation.StencilStorageWriteBackImages.Add(attachment); } attachment.CopyStencilStorage(storage, _bufferCache.GetUtilityBuffer(GpuBufferUsage.DeviceLocal), writeBack: false); - if (_hasBoundDepth && _boundDepth.Image == binding.ImageIdentifier) + if (_hasBoundDepth && _boundDepth.Image == attachmentIdentifier) { var writes = _boundDepthLoadState.AttachmentWriteAspects(attachment.Backing.Format); TransitionImage(attachment, diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs index d9b329bac..4451f3a64 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Descriptors.cs @@ -477,6 +477,13 @@ private uint[] AssembleShaderData(ShaderStageResources stage, ShaderProgramInfo shaderData[layout.ShaderBaseDword + 1] = (uint)(stage.ShaderBase >> 32); } + // A stage prepared without its heap views reads the null element. + for (var view = 0u; view < layout.HeapViewCount; view++) + { + shaderData[layout.HeapViewsDword + view * HeapView.DwordCount] = HeapView.None.Word0; + shaderData[layout.HeapViewsDword + view * HeapView.DwordCount + 1] = HeapView.None.Word1; + } + stage.WriteDispatchThreadLimits(shaderData); stage.WriteMeshDrawParameters(shaderData); stage.WriteTessellationData(shaderData); @@ -939,7 +946,20 @@ public IPreparedBindings PrepareBindings(ShaderStageResources stage) _presenter.ForgetHeapPreparation(preparation); } - _presenter.PrepareBindlessHeap(preparation, snapshot.Heaps); + _presenter.PrepareBindlessHeap(preparation); + } + + // Where the stage's heap views have their elements, found before the stage's own images: a run that moved + // to another heap gets the images of its records here. + Span heapViews = layout.HeapViewCount <= 32 ? stackalloc uint[(int)(layout.HeapViewCount * HeapView.DwordCount)] : new uint[layout.HeapViewCount * HeapView.DwordCount]; + if (layout.HeapViewCount != 0) + { + if (snapshot.Heaps.Length != layout.HeapViewCount) + { + throw SubmissionScheduler.Fatal($"The heap views do not match the layout: views={snapshot.Heaps.Length} layout={layout.HeapViewCount} hash=0x{program.Hash:X16}."); + } + + _presenter.WriteHeapViews(snapshot.Heaps, heapViews); } if (layout.Find(DescriptorBindingKind.CallMarks) is not null) @@ -1027,6 +1047,7 @@ public IPreparedBindings PrepareBindings(ShaderStageResources stage) } var shaderData = AssembleShaderData(stage, program, layout); + heapViews.CopyTo(shaderData.AsSpan((int)layout.HeapViewsDword)); prepared.ShaderData = shaderData; if (layout.Find(DescriptorBindingKind.GlobalDataShare) is not null) { @@ -1420,7 +1441,9 @@ private bool ReadsOnlyBoundedRanges(RenderPreparation preparation) private long _bdaSpanVersion = -1; private ulong _bdaSpanMapping; - private List DeviceAddressSpans(GuestGpuMemory memory) + internal ulong DeviceAddressSpanMapping => _bdaSpanMapping; + + internal List DeviceAddressSpans(GuestGpuMemory memory) { var version = memory.SpanVersion; if (_bdaSpans is { } cached && ReferenceEquals(_bdaSpanMemory, memory) && _bdaSpanVersion == version) @@ -1911,7 +1934,8 @@ private void BindImages(PreparedStageBindings prepared) var images = prepared.Descriptors.Images; var nulled = RefindStaleBindings( images.Length, - index => !images[index].IsHostMovie && IsStaleImage(images[index].ImageIdentifier, out _), + index => !images[index].IsHostMovie && + (IsStaleImage(images[index].ImageIdentifier, out _) || HoldsMovedStencilPlane(images[index])), (index, asNull) => { if (_imageCache.TryGetImage(images[index].ImageIdentifier, out var stale)) diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.GuestDraws.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.GuestDraws.cs index 9d96df896..672a5289c 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.GuestDraws.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.GuestDraws.cs @@ -93,7 +93,9 @@ internal static bool TryDecodeRenderTargetFormat( (5, 4, _) => Format.R16G16Uint, (5, 5, _) => Format.R16G16Sint, (5, 7, _) => Format.R16G16Sfloat, - (6, 7, _) or (7, 7, _) => Format.B10G11R11UfloatPack32, + // 11_11_10 holds unsigned floats whatever the number type; the image path maps its + // UNORM variant to the same host format (GuestPixelFormats.HostFormats). + (6, 7, _) or (7, 7, _) or (6, 0, _) => Format.B10G11R11UfloatPack32, (9, _, 1) => Format.A2R10G10B10UnormPack32, (9, _, _) => Format.A2B10G10R10UnormPack32, (10, 1, _) => Format.R8G8B8A8SNorm, @@ -115,6 +117,13 @@ internal static bool TryDecodeRenderTargetFormat( (13, 7, _) or (14, 7, _) => Format.R32G32B32A32Sfloat, (20, 0, _) => Format.R32Uint, (29, 0, _) or (4, 0, _) => Format.R32Sfloat, + // Narrow sRGB targets (number type 6, or 9 like RGBA8 sRGB above): the image path stands a same-width UNORM + // format in (GuestPixelFormats: Bits8Srgb, Bits8_8Srgb), and the pixel output is a float either way. + (1, 6 or 9, _) => Format.R8Unorm, + (3, 6 or 9, _) => Format.R8G8Unorm, + (1, 5, _) => Format.R8Sint, + (3, 4, _) => Format.R8G8Uint, + (3, 5, _) => Format.R8G8Sint, (1, 0, _) or (36, 0, _) => Format.R8Unorm, (1, 1, _) => Format.R8SNorm, (1, 4, _) or (49, 0, _) => Format.R8Uint, @@ -145,12 +154,12 @@ internal static bool TryDecodeRenderTargetFormat( var outputKind = format switch { - Format.R8Uint or Format.R16Uint or Format.R32Uint or Format.R16G16Uint or + Format.R8Uint or Format.R16Uint or Format.R32Uint or Format.R8G8Uint or Format.R16G16Uint or Format.R32G32Uint or Format.R8G8B8A8Uint or Format.R16G16B16A16Uint or Format.R32G32B32A32Uint => Gen5PixelOutputKind.Uint, - Format.R16Sint or Format.R32Sint or Format.R16G16Sint or Format.R32G32Sint or - Format.R8G8B8A8Sint or Format.R16G16B16A16Sint or Format.R32G32B32A32Sint => - Gen5PixelOutputKind.Sint, + Format.R8Sint or Format.R16Sint or Format.R32Sint or Format.R8G8Sint or Format.R16G16Sint or + Format.R32G32Sint or Format.R8G8B8A8Sint or Format.R16G16B16A16Sint or + Format.R32G32B32A32Sint => Gen5PixelOutputKind.Sint, _ => Gen5PixelOutputKind.Float, }; diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs index 4f75539ea..aa4fc6429 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Rendering.cs @@ -104,6 +104,25 @@ public bool TryResolveColorOutput( } } + // Shader writes reach every later consumer, including the argument read of an indirect draw whose + // arguments a graphics or compute stage wrote (GPU-driven culling). + internal static MemoryBarrierRequest ShaderWriteBarrierRequest( + PipelineStageFlags sourceStages, bool meshShader, bool taskShader, bool tessellation) => new( + sourceStages, + PipelineStageFlags.DrawIndirectBit | PipelineStageFlags.ComputeShaderBit | PipelineStageFlags.VertexInputBit | + PipelineStageFlags.VertexShaderBit | PipelineStageFlags.FragmentShaderBit | PipelineStageFlags.TransferBit | + PipelineStageFlags.ColorAttachmentOutputBit | + (meshShader ? PipelineStageFlags.MeshShaderBitExt : PipelineStageFlags.None) | + (taskShader ? PipelineStageFlags.TaskShaderBitExt : PipelineStageFlags.None) | + (tessellation + ? PipelineStageFlags.TessellationControlShaderBit | PipelineStageFlags.TessellationEvaluationShaderBit + : PipelineStageFlags.None), + AccessFlags.ShaderWriteBit, + AccessFlags.IndirectCommandReadBit | AccessFlags.ShaderReadBit | AccessFlags.ShaderWriteBit | + AccessFlags.VertexAttributeReadBit | AccessFlags.IndexReadBit | AccessFlags.UniformReadBit | + AccessFlags.TransferReadBit | AccessFlags.TransferWriteBit | + AccessFlags.ColorAttachmentReadBit | AccessFlags.ColorAttachmentWriteBit); + private sealed partial class RecordingHost : IRenderHost { // Keep each new stream allocation intact until the draw is recorded. @@ -672,7 +691,7 @@ private void PrepareStencilFeedback(TextureResource[] bindings) { if (binding.IsHostMovie || binding.CachedImage is not { } image || !ReferenceEquals(image, depthImage) || !ViewFormatRules.IsStencilViewFormat(binding.Request.View.Format) || - !ViewsOverlap(binding.Request.View, attachmentView)) + !ViewsOverlap(binding.Request.View, attachmentView) || !FitsStencilPlane(binding.Request.Description, image)) { continue; } @@ -1717,19 +1736,9 @@ private void RecordMemoryBarrier(PipelineStageFlags sourceStages, PipelineStageF public void ShaderWriteBarrier(PipelineStageFlags sourceStages) { NoteShaderMayWriteMappedMemory(); - RecordMemoryBarrier( - sourceStages, - PipelineStageFlags.ComputeShaderBit | PipelineStageFlags.VertexInputBit | PipelineStageFlags.VertexShaderBit | - PipelineStageFlags.FragmentShaderBit | PipelineStageFlags.TransferBit | PipelineStageFlags.ColorAttachmentOutputBit | - (_presenter._supportsMeshShader ? PipelineStageFlags.MeshShaderBitExt : PipelineStageFlags.None) | - (_presenter._supportsTaskShader ? PipelineStageFlags.TaskShaderBitExt : PipelineStageFlags.None) | - (_presenter._supportsTessellation - ? PipelineStageFlags.TessellationControlShaderBit | PipelineStageFlags.TessellationEvaluationShaderBit - : PipelineStageFlags.None), - AccessFlags.ShaderWriteBit, - AccessFlags.ShaderReadBit | AccessFlags.ShaderWriteBit | AccessFlags.VertexAttributeReadBit | AccessFlags.IndexReadBit | - AccessFlags.UniformReadBit | AccessFlags.TransferReadBit | AccessFlags.TransferWriteBit | - AccessFlags.ColorAttachmentReadBit | AccessFlags.ColorAttachmentWriteBit); + var request = ShaderWriteBarrierRequest( + sourceStages, _presenter._supportsMeshShader, _presenter._supportsTaskShader, _presenter._supportsTessellation); + RecordMemoryBarrier(request.SourceStages, request.DestinationStages, request.SourceAccess, request.DestinationAccess); } private static readonly MemoryBarrierRequest ShaderWriteHazardRequest = new( diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.ShaderPrewarm.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.ShaderPrewarm.cs index 05fcc1ae2..ef4f8f9b9 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.ShaderPrewarm.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.ShaderPrewarm.cs @@ -438,6 +438,7 @@ private string BuildShaderPrewarmStamp(Type compilerType, string driverSignature Environment.GetEnvironmentVariable("SHARPEMU_WAVE64_HALF_MASKS"), Environment.GetEnvironmentVariable("SHARPEMU_WAVE64_LANE_LOCAL"), Environment.GetEnvironmentVariable("SHARPEMU_WAVE64_PAIRED"), + Environment.GetEnvironmentVariable("SHARPEMU_GRAPHICS_PARTIAL_LANES"), Environment.GetEnvironmentVariable("SHARPEMU_SHADER_MAX_STEPS"), Environment.GetEnvironmentVariable("SHARPEMU_STRUCTURED_CF"), Environment.GetEnvironmentVariable("SHARPEMU_STRUCTURED_FORWARD_BLOCKS"), diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs index 3cc6b1096..a0429dacf 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.Slices.cs @@ -829,7 +829,17 @@ private void RecordSlicePrologue(SliceRequests requests) { if (requests.NeedsBdaSweep && requests.BdaSpans is { } spans) { - _bufferCache.PrepareBda(spans, requests.BdaMapping); + // A worker captured these spans before this thread ran the relay's mapping changes between items. + // A guest munmap among them marks the buffers it covered CPU-dirty, and sweeping the captured spans + // then reads memory that is gone. Sweep the spans current at the join. + var mapping = requests.BdaMapping; + if (GuestGpuMemoryHook.Current is { } memory) + { + spans = Recording.DeviceAddressSpans(memory); + mapping = Recording.DeviceAddressSpanMapping; + } + + _bufferCache.PrepareBda(spans, mapping); } else if (requests.NeedsBdaTouch && requests.BdaSpans is { } touched) { diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Alu.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Alu.cs index 842053955..90cc93803 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Alu.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Alu.cs @@ -4488,6 +4488,13 @@ private bool TryEmitScalar64( { value = _module.AddInstruction(SpirvOp.Not, _ulongType, left); } + else if (instruction.Opcode == "SBrevB64") + { + // Vulkan limits OpBitReverse to 32-bit operands: reverse each half and swap them. + var low = _module.AddInstruction(SpirvOp.BitReverse, _uintType, Narrow(ShiftRightLogical64(left, ULong(32)))); + var high = _module.AddInstruction(SpirvOp.BitReverse, _uintType, Narrow(left)); + value = _module.AddInstruction(SpirvOp.BitwiseOr, _ulongType, Widen(low), ShiftLeftLogical64(Widen(high), ULong(32))); + } else { if (instruction.Sources.Count < 2) @@ -4746,6 +4753,17 @@ private uint ApplyDpp8Source(Gen5Dpp8Control control, uint value) var targetLane = IAdd(BitwiseAnd(lane, UInt(0xFFFF_FFF8)), selector); targetLane = BitwiseAnd(targetLane, UInt(NativeLaneMask)); + if (HostSubgroupMayBePartial) + { + if (control.FetchInactive) + { + return ReadGraphicsLane(value, targetLane, out _); + } + + var graphicsValue = ReadGraphicsLaneIfActive(value, targetLane, out var usable); + return _module.AddInstruction(SpirvOp.Select, _uintType, usable, graphicsValue, UInt(0)); + } + var shuffled = ShuffleLane(value, targetLane); if (control.FetchInactive) { @@ -4770,6 +4788,27 @@ private uint ApplyDpp8Source(Gen5Dpp8Control control, uint value) private uint ApplyDppSource(Gen5DppControl control, uint value) { + if (HostSubgroupMayBePartial) + { + GetDppSourceLane(control, out var targetLane, out var inRange); + var graphicsTarget = BitwiseAnd( + _module.AddInstruction(SpirvOp.Select, _uintType, inRange, targetLane, GuestWaveLane()), + UInt(NativeLaneMask)); + if (control.FetchInactive) + { + return _module.AddInstruction( + SpirvOp.Select, _uintType, inRange, ReadGraphicsLane(value, graphicsTarget, out _), UInt(0)); + } + + var graphicsValue = ReadGraphicsLaneIfActive(value, graphicsTarget, out var usable); + return _module.AddInstruction( + SpirvOp.Select, + _uintType, + _module.AddInstruction(SpirvOp.LogicalAnd, _boolType, inRange, usable), + graphicsValue, + UInt(0)); + } + GetDppSource(control, out var safeTarget, out var valid); var shuffled = _pairedMeshLanes ? ShufflePairedValue(_pairedDppSources[0], _pairedDppSources[1], safeTarget) @@ -5005,7 +5044,23 @@ private uint IsDppWriteEnabled(Gen5DppControl control) UInt(control.BankMask), ShiftLeftLogical(UInt(1), bank))); var sourceAllowsWrite = _module.ConstantBool(true); - if (!control.BoundControl) + if (!control.BoundControl && HostSubgroupMayBePartial) + { + // ISA: with BOUND_CTRL clear, a lane whose source is out of range or disabled keeps its + // old destination. A graphics source lane the host never launched is disabled unless + // whole-wave code turned it on. + GetDppSourceLane(control, out var sourceLane, out var inRange); + sourceAllowsWrite = inRange; + if (!control.FetchInactive) + { + var safeSource = BitwiseAnd( + _module.AddInstruction(SpirvOp.Select, _uintType, inRange, sourceLane, lane), + UInt(NativeLaneMask)); + sourceAllowsWrite = _module.AddInstruction( + SpirvOp.LogicalAnd, _boolType, inRange, IsGraphicsLaneUsable(safeSource)); + } + } + else if (!control.BoundControl) { GetDppSource(control, out _, out sourceAllowsWrite); } @@ -5935,6 +5990,13 @@ private bool TryEmitReadlane( var broadcast = BroadcastWaveLane(sourceValue, selectedLane); StoreS(destination, ReadLaneSpillSlot(instruction, selectedLane, broadcast)); } + else if (HostSubgroupMayBePartial) + { + // The selected lane of the invocation's own graphics wave, whatever its EXEC state; a lane + // the host never launched reads as the reading lane. + var read = ReadGraphicsLane(sourceValue, selectedLane, out _); + StoreS(destination, ReadLaneSpillSlot(instruction, selectedLane, read)); + } else { // Fallback: no subgroup ops, read current lane's value, or the @@ -6013,8 +6075,29 @@ private uint EmitPermlane16( var targetLane = IAdd(rowBase, selector); targetLane = BitwiseAnd(targetLane, UInt(NativeLaneMask)); - var shuffled = ShuffleLane(value, targetLane); var fetchInactive = (control.OperandSelect & 1) != 0; + if (HostSubgroupMayBePartial) + { + if (fetchInactive) + { + return ReadGraphicsLane(value, targetLane, out _); + } + + // ISA: a disabled source lane gives zero with BOUND_CTRL (OP_SEL[1]) set and keeps the old + // destination with it clear. + var graphicsValue = ReadGraphicsLaneIfActive(value, targetLane, out var usable); + var boundControl = (control.OperandSelect & 2) != 0; + return _module.AddInstruction( + SpirvOp.Select, + _uintType, + usable, + graphicsValue, + boundControl || instruction.Destinations.Count == 0 + ? UInt(0) + : LoadV(instruction.Destinations[0].Value)); + } + + var shuffled = ShuffleLane(value, targetLane); if (fetchInactive) { return shuffled; diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.PairedLanes.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.PairedLanes.cs index c4013460b..1673ea8dc 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.PairedLanes.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.PairedLanes.cs @@ -5,12 +5,25 @@ namespace SharpEmu.ShaderCompiler.Vulkan; public static partial class Gen5SpirvTranslator { + // Which wave64 compute workgroups on 32-lane host subgroups run as paired lanes (one host invocation per guest lane + // pair, both halves in one subgroup) instead of the emulated lowering (one host subgroup per half). A one-wave + // workgroup paired runs on a single subgroup that executes both halves in turn, while emulated its halves run as two + // subgroups side by side; with more than one wave the paired lowering is faster, because the emulated waves meet at + // rendezvous counters. Ghost of Yotei 02.002 on an RTX 3080: one-wave kernels ran 23% and 34% faster emulated, + // 512- and 1024-thread workgroups 17% and 80% slower. Unset (or =1) pairs every workgroup, =small pairs only + // workgroups of more than one wave, =0 none. The one-wave split is opt-in because it has been measured on one title. + public static bool PairsWave64Lanes(string? mode, ulong workgroupThreads) => mode switch + { + "0" => false, + "small" => workgroupThreads > 64, + _ => true, + }; + private sealed partial class CompilationContext { private const uint PairedHalfLaneCount = 32; - private static readonly bool PairedWave64Enabled = !string.Equals( - Environment.GetEnvironmentVariable("SHARPEMU_WAVE64_PAIRED"), "0", StringComparison.Ordinal); + private static readonly string? PairedWave64Mode = Environment.GetEnvironmentVariable("SHARPEMU_WAVE64_PAIRED"); private readonly bool _pairedLanes; private int _laneHalf; diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Resources.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Resources.cs index d7defaef8..53354406e 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Resources.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.Resources.cs @@ -164,7 +164,7 @@ private sealed partial class CompilationContext private readonly bool _compactMemoryAccess; private readonly Dictionary _imageClasses = []; private readonly Dictionary _indirectKeyScratch = []; - private readonly Dictionary _heapArrays = []; + private readonly Dictionary<(int Slot, ImageNumericClass NumericClass), uint> _heapArrays = []; private uint _heapFeedback; private uint _pushData; private uint _shaderData; @@ -246,6 +246,7 @@ instruction.Opcode is "BufferLoadDwordx2" or "BufferStoreDwordx2" && _stage == Gen5SpirvStage.Pixel && PixelLiveExec && request.Program.Instructions.Any(static instruction => instruction.Opcode is "DsAppend" or "DsConsume"); _enableGraphicsSubgroupOperations = _stage is Gen5SpirvStage.Compute or Gen5SpirvStage.Mesh || request.EnableGraphicsSubgroupOperations; + _graphicsPartialSubgroupLanes = request.GraphicsPartialSubgroupLanes; _waveLaneCount = request.WaveSize == 64 ? 64u : 32u; _pairedMeshLanes = _stage == Gen5SpirvStage.Mesh && _waveLaneCount == 64 && request.Mesh?.DeviceSubgroupLaneCount == 32; @@ -288,7 +289,8 @@ instruction.Opcode is "BufferLoadDwordx2" or "BufferStoreDwordx2" && { _waveLowering = new HalfWave64Lowering(this); } - else if (_stage == Gen5SpirvStage.Compute && request.HostComputeSubgroup32 && PairedWave64Enabled) + else if (_stage == Gen5SpirvStage.Compute && request.HostComputeSubgroup32 && + PairsWave64Lanes(PairedWave64Mode, (ulong)_localSizeX * _localSizeY * _localSizeZ)) { _pairedLanes = true; _waveLowering = new PairedWave64Lowering(this); @@ -2414,7 +2416,8 @@ private bool TryResolveLayoutImage( out uint dstSelect, out string error, (uint Resource, uint Element)? fixedElement = null, - bool heapVolumeLayers = false) + bool heapVolumeLayers = false, + ImageNumericClass heapNumericClass = ImageNumericClass.Float) { error = string.Empty; resource = default; @@ -2486,7 +2489,13 @@ private bool TryResolveLayoutImage( uint imageValue; if (fromHeap) { - (elementPointer, imageValue) = LoadHeapElement(heapImageSlot, imageClass.ImageType, HeapRecordIndex(heapImage)); + if (heapNumericClass != ImageNumericClass.Float) + { + imageClass = HeapIntegerClass(imageClass, heapNumericClass); + } + + (elementPointer, imageValue) = LoadHeapElement(heapImageSlot, imageClass.ImageType, + HeapImageIndex(heapImage, heapImageSlot, heapNumericClass), numericClass: heapNumericClass); } else if (fixedElement is null && heapImageSlot >= 0 && request.CallRecordImageByMemoryIndex.TryGetValue(memoryIndex, out var recordImage)) @@ -2588,22 +2597,75 @@ private LayoutImageClass VolumeLayerClass() ImageComponentKind.Float, IsStorage: false, Arrayed: true, Cube: false, Multisampled: false, SpirvImageDim.Dim2D, []); } - // The record a heap read picks: the dynamic offset its key read kept plus the read's immediate, in records. - private uint HeapRecordIndex(HeapRecordUse use) + // The integer form of a float class of set 1: the same binding, declared with unsigned or signed texels. + private LayoutImageClass HeapIntegerClass(LayoutImageClass floatClass, ImageNumericClass numericClass) { - var key = _indirectKeyScratch.TryGetValue(use.KeyMemoryIndex, out var scratch) ? Load(_uintType, scratch) : UInt(0); - var shift = use.RecordBytes == BindlessHeap.SamplerRecordBytes ? 4u : 5u; - var record = ShiftRightLogical(IAdd(key, UInt(use.Immediate)), UInt(shift)); - // Set 1 holds the heap's records below CallRecordFirstIndex (call records own the elements above); any other record - // reads the null element. - var inHeap = _module.AddInstruction(SpirvOp.ULessThan, _boolType, record, UInt(BindlessHeap.CallRecordFirstIndex)); - return _module.AddInstruction(SpirvOp.Select, _uintType, inHeap, record, UInt(BindlessHeap.CallRecordNullIndex)); + var signed = numericClass == ImageNumericClass.Sint; + var componentType = signed ? _intType : _uintType; + var imageType = _module.TypeImage(componentType, floatClass.Dimension, depth: false, floatClass.Arrayed, multisampled: false, + sampled: 1u, SpirvImageFormat.Unknown); + return floatClass with + { + Variable = 0, + ImageType = imageType, + ElementPointer = _module.TypePointer(SpirvStorageClass.UniformConstant, imageType), + ComponentType = componentType, + Kind = signed ? ImageComponentKind.Sint : ImageComponentKind.Uint, + Resources = [], + }; + } + + // The numeric class of a set-1 image element (BindlessHeap.ClassCode), which the host keeps after the mark bitsets. + private uint HeapElementClass(uint index) + { + var word = IAdd(UInt(BindlessHeap.MarkWords), ShiftRightLogical(index, UInt(BindlessHeap.ClassWordShift))); + var shift = _module.AddInstruction(SpirvOp.IMul, _uintType, + BitwiseAnd(index, UInt(BindlessHeap.ClassesPerWord - 1)), UInt(BindlessHeap.ClassBits)); + return BitwiseAnd(ShiftRightLogical(Load(_uintType, BlockWordPointer(HeapFeedback(), word)), shift), UInt(BindlessHeap.ClassMask)); } - // One runtime array of set 1, declared at its first use. - private uint HeapArray(int slot, uint elementType) + // The element an image read takes through the declaration of one numeric class: the record's element when it + // holds a texture of that class and the null element otherwise, so no declaration reads a view of another class. + // A class without integer forms holds float views only. + private uint HeapImageIndex(HeapRecordUse use, int slot, ImageNumericClass numericClass = ImageNumericClass.Float) { - if (_heapArrays.TryGetValue(slot, out var variable)) + var index = HeapRecordIndex(use); + if (!BindlessHeap.HoldsIntegers(slot)) + { + return index; + } + + var ofClass = _module.AddInstruction(SpirvOp.IEqual, _boolType, HeapElementClass(index), UInt(BindlessHeap.ClassCode(numericClass))); + return _module.AddInstruction(SpirvOp.Select, _uintType, ofClass, index, UInt(BindlessHeap.CallRecordNullIndex)); + } + + // The element of set 1 a heap read picks: the dynamic offset its key read kept plus the read's immediate is a + // byte offset in the heap, whose record the draw's heap view (HeapView, two dwords of shader data) has an element + // for. A read the view has no element for (past its records, or not at its descriptor's offset in a record) + // reads the null element. + private uint HeapRecordIndex(HeapRecordUse use) + { + var key = _indirectKeyScratch.TryGetValue(use.KeyMemoryIndex, out var scratch) ? Load(_uintType, scratch) : UInt(0); + var offset = IAdd(key, UInt(use.Immediate)); + var viewDword = _request.Bindings.HeapViewsDword + (uint)use.View * HeapView.DwordCount; + var word0 = LoadShaderDataDword(UInt(viewDword)); + var word1 = LoadShaderDataDword(UInt(viewDword + 1)); + var first = BitwiseAnd(word0, UInt(HeapView.ElementMask)); + var stride = ShiftRightLogical(word0, UInt(HeapView.ElementBits)); + var records = BitwiseAnd(word1, UInt(HeapView.ElementMask)); + var fieldOffset = ShiftRightLogical(word1, UInt(HeapView.ElementBits)); + // The host never gives a view a stride of zero. + var record = _module.AddInstruction(SpirvOp.UDiv, _uintType, offset, stride); + var atField = _module.AddInstruction(SpirvOp.IEqual, _boolType, + _module.AddInstruction(SpirvOp.ISub, _uintType, offset, _module.AddInstruction(SpirvOp.IMul, _uintType, record, stride)), fieldOffset); + var inView = LogicalAnd(atField, _module.AddInstruction(SpirvOp.ULessThan, _boolType, record, records)); + return _module.AddInstruction(SpirvOp.Select, _uintType, inView, IAdd(first, record), UInt(BindlessHeap.CallRecordNullIndex)); + } + + // One runtime array of set 1, declared at its first use. The integer declarations of an image array share its binding. + private uint HeapArray(int slot, uint elementType, ImageNumericClass numericClass) + { + if (_heapArrays.TryGetValue((slot, numericClass), out var variable)) { return variable; } @@ -2618,18 +2680,19 @@ private uint HeapArray(int slot, uint elementType) variable = _module.AddGlobalVariable( _module.TypePointer(SpirvStorageClass.UniformConstant, _module.TypeRuntimeArray(elementType)), SpirvStorageClass.UniformConstant); - _module.AddName(variable, $"heapArray{slot}"); + _module.AddName(variable, numericClass == ImageNumericClass.Float ? $"heapArray{slot}" : $"heapArray{slot}{numericClass}"); _module.AddDecoration(variable, SpirvDecoration.DescriptorSet, BindlessHeap.DescriptorSet); _module.AddDecoration(variable, SpirvDecoration.Binding, (uint)slot); _interfaces.Add(variable); - _heapArrays[slot] = variable; + _heapArrays[(slot, numericClass)] = variable; return variable; } // Loads one element of a set-1 array; a heap record is marked in the feedback bitset, so the host gives it a view. - private (uint Pointer, uint Value) LoadHeapElement(int slot, uint elementType, uint index, bool mark = true) + private (uint Pointer, uint Value) LoadHeapElement(int slot, uint elementType, uint index, bool mark = true, + ImageNumericClass numericClass = ImageNumericClass.Float) { - var array = HeapArray(slot, elementType); + var array = HeapArray(slot, elementType, numericClass); var pointer = _module.AddInstruction( SpirvOp.AccessChain, _module.TypePointer(SpirvStorageClass.UniformConstant, elementType), array, index); _module.AddDecoration(pointer, SpirvDecoration.NonUniform); @@ -2773,14 +2836,8 @@ uint Clamped(uint index) => _module.AddInstruction(SpirvOp.Select, _uintType, return _module.AddInstruction(SpirvOp.Select, _uintType, found, element, UInt(BindlessHeap.CallRecordNullIndex)); } - // The records marked since the last branch, by slot, index and EXEC value (0: EXEC known full), and the block the - // last of those marks ended in. - private readonly HashSet<(int Slot, uint Index, uint Exec)> _markedHeapRecords = []; - private uint _markedHeapRecordsBlock; - - // Sets the record's bit in its array's feedback words; a plain read first keeps marked records from repeating the atomic. - // A record marked again under the same EXEC value with no branch since finds its bit set, so that mark is left out. - private void MarkHeapRecord(int slot, uint index) + // The feedback buffer of set 1, declared at its first use. + private uint HeapFeedback() { if (_heapFeedback == 0) { @@ -2795,6 +2852,19 @@ private void MarkHeapRecord(int slot, uint index) _interfaces.Add(_heapFeedback); } + return _heapFeedback; + } + + // The records marked since the last branch, by slot, index and EXEC value (0: EXEC known full), and the block the + // last of those marks ended in. + private readonly HashSet<(int Slot, uint Index, uint Exec)> _markedHeapRecords = []; + private uint _markedHeapRecordsBlock; + + // Sets the record's bit in its array's feedback words; a plain read first keeps marked records from repeating the atomic. + // A record marked again under the same EXEC value with no branch since finds its bit set, so that mark is left out. + private void MarkHeapRecord(int slot, uint index) + { + var feedback = HeapFeedback(); if (_module.CurrentBlock != _markedHeapRecordsBlock) { _markedHeapRecords.Clear(); @@ -2809,7 +2879,7 @@ private void MarkHeapRecord(int slot, uint index) var word = IAdd(UInt((uint)slot * BindlessHeap.FeedbackWordsPerArray), ShiftRightLogical(index, UInt(5))); var bit = ShiftLeftLogical(UInt(1), BitwiseAnd(index, UInt(31))); - var pointer = BlockWordPointer(_heapFeedback, word); + var pointer = BlockWordPointer(feedback, word); var unmarked = _module.AddInstruction(SpirvOp.IEqual, _boolType, BitwiseAnd(Load(_uintType, pointer), bit), UInt(0)); if (exec != 0) { diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.cs index ed26026ed..658b60041 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.cs @@ -80,6 +80,7 @@ private sealed partial class CompilationContext private static readonly bool PixelLiveExec = !string.Equals( Environment.GetEnvironmentVariable("SHARPEMU_PS_LIVE_EXEC"), "0", StringComparison.Ordinal); private readonly bool _enableGraphicsSubgroupOperations; + private readonly bool _graphicsPartialSubgroupLanes; private readonly uint _waveLaneCount; private readonly IWaveLowering _waveLowering; private bool _guestLaneFromSubgroup; @@ -219,6 +220,7 @@ private sealed partial class CompilationContext private uint _vertexIndexInput; private uint _instanceIndexInput; private uint _baseInstanceInput; + private uint _baseVertexInput; private uint _fragCoordInput; private uint _localInvocationIdInput; private uint _localInvocationIndexInput; @@ -957,6 +959,17 @@ private void DeclareStageInterface() (uint)SpirvBuiltIn.BaseInstance); _interfaces.Add(_baseInstanceInput); _module.AddCapability(SpirvCapability.DrawParameters); + if (_request.BaseVertexUserData >= 0) + { + _baseVertexInput = _module.AddGlobalVariable( + _module.TypePointer(SpirvStorageClass.Input, _uintType), + SpirvStorageClass.Input); + _module.AddDecoration( + _baseVertexInput, + SpirvDecoration.BuiltIn, + (uint)SpirvBuiltIn.BaseVertex); + _interfaces.Add(_baseVertexInput); + } } var outputPointer = @@ -1322,7 +1335,17 @@ private void EmitInitialState() { if (_stage == Gen5SpirvStage.Vertex) { - StoreV(_request.Program.VertexIndexRegister, Load(_uintType, _vertexIndexInput), guardWithExec: false); + // A base vertex the indirect draw names in user data reaches the program there, and the vertex + // index counts from it, as the CP's base_vtx_loc write does. + var vertexIndex = Load(_uintType, _vertexIndexInput); + if (_baseVertexInput != 0) + { + var baseVertex = Load(_uintType, _baseVertexInput); + vertexIndex = ISubU(vertexIndex, baseVertex); + StoreS(_request.UserDataBase + (uint)_request.BaseVertexUserData, baseVertex); + } + + StoreV(_request.Program.VertexIndexRegister, vertexIndex, guardWithExec: false); var instanceIndex = Load(_uintType, _instanceIndexInput); if (_baseInstanceInput != 0) instanceIndex = ISubU(instanceIndex, Load(_uintType, _baseInstanceInput)); @@ -3971,7 +3994,8 @@ void EmitDwordAtomics() } EmitExecConditional(() => TryEmitBufferFormatStore(bindingIndex, byteAddress, control, descriptorWord3, descriptorFormat, - storedHalves, component => LoadBufferD16Component(control.VectorData, component, storedNumberFormat))); + storedHalves, component => LoadBufferD16Component(control.VectorData, + component + (IsFormatD16High(instruction.Opcode) ? 1u : 0u), storedNumberFormat))); return true; } @@ -4075,7 +4099,8 @@ void EmitDwordAtomics() var (_, loadedNumberFormat) = DecodeGfx10BufferFormat( BitwiseAnd(ShiftRightLogical(descriptorWord3, UInt(12)), UInt(0x7F))); StoreBufferD16Components(control.VectorData, - BufferFormatLoadValues(bindingIndex, byteAddress, descriptorWord3, loadedHalves), loadedNumberFormat); + BufferFormatLoadValues(bindingIndex, byteAddress, descriptorWord3, loadedHalves), loadedNumberFormat, + IsFormatD16High(instruction.Opcode)); return true; } @@ -4270,7 +4295,8 @@ private bool TryEmitDeviceDescriptorBufferMemory( var (_, deviceNumberFormat) = DecodeGfx10BufferFormat( BitwiseAnd(ShiftRightLogical(descriptorWord3, UInt(12)), UInt(0x7F))); StoreBufferD16Components(control.VectorData, - DeviceBufferFormatLoadValues(baseAddress, size, byteAddress, descriptorWord3, deviceHalves), deviceNumberFormat); + DeviceBufferFormatLoadValues(baseAddress, size, byteAddress, descriptorWord3, deviceHalves), deviceNumberFormat, + IsFormatD16High(instruction.Opcode)); return true; } @@ -4998,7 +5024,7 @@ private uint[] BufferFormatLoadValues( // The components a D16 format operation transfers (X to XYZW), or 0 for any other operation. private static uint FormatD16Components(string opcode) => opcode switch { - "BufferLoadFormatD16X" or "BufferStoreFormatD16X" => 1u, + "BufferLoadFormatD16X" or "BufferStoreFormatD16X" or "BufferLoadFormatD16HiX" or "BufferStoreFormatD16HiX" => 1u, "BufferLoadFormatD16Xy" or "BufferStoreFormatD16Xy" => 2u, "BufferLoadFormatD16Xyz" or "BufferStoreFormatD16Xyz" => 3u, "BufferLoadFormatD16Xyzw" or "BufferStoreFormatD16Xyzw" => 4u, @@ -5007,8 +5033,9 @@ private uint[] BufferFormatLoadValues( // A D16 load returns its components as 16-bit values, two to a register with the first in the low half: halves for // the float and normalized formats, the low 16 bits for UINT and SINT (number formats 4 and 5). An odd last - // component leaves the high half zero. - private void StoreBufferD16Components(uint vectorData, uint[] values, uint numberFormat) + // component leaves the high half zero. The D16_HI form (highHalf) writes its one component to bits 16..31 and keeps + // bits 0..15 of the register. + private void StoreBufferD16Components(uint vectorData, uint[] values, uint numberFormat, bool highHalf = false) { var integer = _module.AddInstruction(SpirvOp.LogicalOr, _boolType, _module.AddInstruction(SpirvOp.IEqual, _boolType, numberFormat, UInt(4)), @@ -5020,10 +5047,20 @@ private void StoreBufferD16Components(uint vectorData, uint[] values, uint numbe var halves = Ext(58, _uintType, _module.AddInstruction(SpirvOp.CompositeConstruct, _vec2Type, Bitcast(_floatType, low), Bitcast(_floatType, high))); var integers = BitwiseOr(BitwiseAnd(low, UInt(0xFFFF)), ShiftLeftLogical(BitwiseAnd(high, UInt(0xFFFF)), UInt(16))); - StoreV(vectorData + (uint)(index / 2), _module.AddInstruction(SpirvOp.Select, _uintType, integer, integers, halves)); + var packed = _module.AddInstruction(SpirvOp.Select, _uintType, integer, integers, halves); + if (highHalf) + { + packed = BitwiseOr(BitwiseAnd(LoadV(vectorData), UInt(0xFFFF)), ShiftLeftLogical(packed, UInt(16))); + } + + StoreV(vectorData + (uint)(index / 2), packed); } } + // BUFFER_LOAD_FORMAT_D16_HI_X and BUFFER_STORE_FORMAT_D16_HI_X move their one component through bits 16..31. + private static bool IsFormatD16High(string opcode) => + opcode is "BufferLoadFormatD16HiX" or "BufferStoreFormatD16HiX"; + // The 32-bit register value one component of a D16 store stands for: its half widened to a float for the float and // normalized formats, its 16 bits (sign-extended for SINT) for the integer ones. private uint LoadBufferD16Component(uint vectorData, uint component, uint numberFormat) @@ -6279,6 +6316,11 @@ private bool TryEmitImage( return false; } + if (IsHeapLoad(instruction, out var heapLoad)) + { + return TryEmitHeapLoad(instruction, image, heapLoad, out error); + } + if (IsHeapVolumeRead(instruction, out var heapVolume, out var volumeType)) { return TryEmitHeapVolumeRead(instruction, image, heapVolume, volumeType, out error); @@ -6298,6 +6340,57 @@ private bool TryEmitImage( return EmitImageOperation(instruction, image, resource, imageObject, dstSelect, mipLevel, out error); } + // A heap record can hold an integer texture, which shaders read with loads and size queries: the instruction is the + // same whatever the format, and its result is the texel's bits. A load of a class with integer forms reads the + // record through the declaration of the element's numeric class. + private bool IsHeapLoad(Gen5ShaderInstruction instruction, out HeapRecordUse heapImage) + { + heapImage = default; + if (instruction.Opcode is not ("ImageLoad" or "ImageLoadMip" or "ImageGetResinfo") || + !_request.Memory.TryGetIndex(instruction.Pc, 0, out var memoryIndex) || + !_request.HeapImageByMemoryIndex.TryGetValue(memoryIndex, out heapImage)) + { + return false; + } + + var entry = _request.Memory[memoryIndex]; + var info = _request.Resources.Info; + return entry.Resource < (uint)info.Images.Count && + ImageDescriptorBinding.ForImage(info.Images[(int)entry.Resource]) is { } kind && + BindlessHeap.HoldsIntegers(BindlessHeap.ImageSlot(kind)); + } + + private bool TryEmitHeapLoad(Gen5ShaderInstruction instruction, Gen5ImageControl image, HeapRecordUse heapImage, out string error) + { + var elementClass = HeapElementClass(HeapRecordIndex(heapImage)); + var emitted = true; + var branchError = string.Empty; + foreach (var numericClass in new[] { ImageNumericClass.Float, ImageNumericClass.Uint, ImageNumericClass.Sint }) + { + if (!emitted) + { + break; + } + + EmitConditional(_module.AddInstruction(SpirvOp.IEqual, _boolType, elementClass, UInt(BindlessHeap.ClassCode(numericClass))), () => + { + if (numericClass == ImageNumericClass.Float && IsHeapVolumeRead(instruction, out var heapVolume, out var volumeType)) + { + emitted = TryEmitHeapVolumeRead(instruction, image, heapVolume, volumeType, out branchError); + return; + } + + emitted = TryResolveLayoutImage(instruction, image, out var resource, out var imageObject, out var dstSelect, out branchError, + heapNumericClass: numericClass) && + EmitImageOperation(instruction, image, resource, imageObject, dstSelect, + HeapReadMipLevel(instruction, image, resource), out branchError); + }); + } + + error = branchError; + return emitted; + } + // A heap record a 3D read picks can hold a 2D texture, whose 3D element stays null; the hardware then takes the // third coordinate as the array layer. Reads that place their operands alike in both shapes (no gradients) try // the 3D element and, when it is null, the record's 2D-array element. @@ -6335,7 +6428,7 @@ private bool TryEmitHeapVolumeRead(Gen5ShaderInstruction instruction, Gen5ImageC // A null descriptor reports no levels. Each branch builds its sampled image in the block that samples it, so the // query loads the 3D element on its own. _module.AddCapability(SpirvCapability.ImageQuery); - var (_, volumeImage) = LoadHeapElement(BindlessHeap.VolumeSlot, volumeType, HeapRecordIndex(heapImage)); + var (_, volumeImage) = LoadHeapElement(BindlessHeap.VolumeSlot, volumeType, HeapImageIndex(heapImage, BindlessHeap.VolumeSlot)); var levels = _module.AddInstruction(SpirvOp.ImageQueryLevels, _uintType, volumeImage); _module.AddDecoration(levels, SpirvDecoration.NonUniform); var isVolume = _module.AddInstruction(SpirvOp.INotEqual, _boolType, levels, UInt(0)); @@ -6999,6 +7092,25 @@ instruction.Opcode is not ("ImageLoad" or "ImageLoadMip")) goto GatherComplete; } + if (GatherCompareLod && + instruction.Opcode == "ImageGather4CL" && + resource.Dimension == SpirvImageDim.Dim2D) + { + // OpImageDrefGather has no level operand either; compare the four texels at the requested level. + sampled = EmitGatherAtLevel( + image, + resource, + imageObject, + coordinates, + LoadImageFloatAddress( + image, + addressCursor + (int)coordinateComponentCount), + reference, + resource.EmulatedCompareFunction); + writeAllComponents = true; + goto GatherComplete; + } + var operands = new List { imageObject, @@ -7225,12 +7337,21 @@ private uint EmitOneDimensionalGatherLz( // The four texels a gather reads, (i, j+1), (i+1, j+1), (i+1, j) and (i, j), taken from one level of // detail. Each is sampled at its centre, so the sampler still applies its addressing and its level clamp. + // image_gather4_c_l gathers at its LOD instead of the base level (SHARPEMU_GATHER_COMPARE_LOD=0 reads the base level, + // for bisecting). A terrain occlusion test gathers its HiZ pyramid at the patch's footprint level; at the base + // level it tests a 2x2-texel corner of the footprint, so patches behind a thin occluder (a character's legs) drop out of the list. + private static readonly bool GatherCompareLod = Environment.GetEnvironmentVariable("SHARPEMU_GATHER_COMPARE_LOD") != "0"; + + // reference != 0: each texel is the depth comparison against it (in the sampler, or emulated when + // emulatedCompare >= 0), as image_gather4_c* returns. private uint EmitGatherAtLevel( Gen5ImageControl image, SpirvImageResource resource, uint sampledImage, uint coordinates, - uint lod) + uint lod, + uint reference = 0, + int emulatedCompare = -1) { var imageValue = _module.AddInstruction( SpirvOp.Image, @@ -7310,6 +7431,19 @@ private uint EmitGatherAtLevel( layer); } + if (reference != 0 && emulatedCompare < 0) + { + values[index] = _module.AddInstruction( + SpirvOp.ImageSampleDrefExplicitLod, + _floatType, + sampledImage, + centre, + reference, + 2u, + levelFloat); + continue; + } + var texel = _module.AddInstruction( SpirvOp.ImageSampleExplicitLod, resource.VectorType, @@ -7322,6 +7456,10 @@ private uint EmitGatherAtLevel( resource.ComponentType, texel, component); + if (reference != 0) + { + values[index] = EmulatedDepthCompare(reference, values[index], emulatedCompare); + } } return _module.AddInstruction( @@ -9927,6 +10065,102 @@ private uint ShuffleLane(uint value, uint lane) => ? BitwiseAnd(lane, UInt(PairedHalfLaneCount - 1)) : lane); + // A graphics host subgroup (a fragment one above all) can be partly empty: the lanes past the quads + // the rasterizer packed into it were never launched. The PS5 wave behind it still has those lanes, + // dead but with registers, and whole-wave code (S_ORN2_SAVEEXEC/S_OR_SAVEEXEC of EXEC) turns them on + // after filling them with a reduction's identity. A shuffle from an invocation that does not exist is + // undefined, so DPP, DPP8, PERMLANE and V_READLANE reads of such a lane go through ReadGraphicsLane. + // Compute and mesh subgroups are full. Opt-in (ShaderCompileRequest.GraphicsPartialSubgroupLanes). + private bool HostSubgroupMayBePartial => + _graphicsPartialSubgroupLanes && _subgroupInvocationIdInput != 0 && !_pairedLanes && !_pairedMeshLanes && + _stage is not (Gen5SpirvStage.Compute or Gen5SpirvStage.Mesh); + + // The host invocation of a guest lane of a graphics wave. A graphics wave is one group of up to 32 + // host lanes (GuestWaveLane), so the lane is at its position within the reading invocation's group; + // the upper half of an emulated wave64 has no host lanes and maps onto the same positions. A native + // wave64 is its subgroup. + private uint GraphicsHostLane(uint guestLane) + { + if (_guestLaneFromSubgroup) + { + return BitwiseAnd(guestLane, UInt(63)); + } + + var group = BitwiseAnd(Load(_uintType, _subgroupInvocationIdInput), UInt(~31u)); + return BitwiseOr(group, BitwiseAnd(guestLane, UInt(31))); + } + + // Whether the host invocation exists: its bit in a ballot of true. + private uint IsHostLanePresent(uint hostLane) + { + _module.AddCapability(SpirvCapability.GroupNonUniformBallot); + var ballot = _module.AddInstruction( + SpirvOp.GroupNonUniformBallot, _uvec4Type, UInt(3), _module.ConstantBool(true)); + var word = _module.AddInstruction( + SpirvOp.VectorExtractDynamic, _uintType, ballot, ShiftRightLogical(hostLane, UInt(5))); + return IsNotZero(BitwiseAnd(ShiftRightLogical(word, BitwiseAnd(hostLane, UInt(31))), UInt(1))); + } + + // A guest lane's bit in the guest EXEC mask, which keeps the bits of the lanes the host never launched. + private uint IsGuestLaneExecSet(uint guestLane) + { + uint word; + uint bit; + if (_waveLaneCount == 32) + { + word = LoadS(126); + bit = BitwiseAnd(guestLane, UInt(31)); + } + else + { + var lane = BitwiseAnd(guestLane, UInt(63)); + word = _module.AddInstruction( + SpirvOp.Select, + _uintType, + _module.AddInstruction(SpirvOp.ULessThan, _boolType, lane, UInt(32)), + LoadS(126), + LoadS(127)); + bit = BitwiseAnd(lane, UInt(31)); + } + + return IsNotZero(BitwiseAnd(ShiftRightLogical(word, bit), UInt(1))); + } + + // Reads a guest lane's register in a graphics wave whatever its EXEC state. present reports whether + // the lane's host invocation exists. An absent lane has no register on the host and no value is + // right; it reads as the caller's own value, which keeps the min/max/and/or reductions that + // whole-wave code runs across dead lanes exact (a wave-minimum loop). + private uint ReadGraphicsLane(uint value, uint guestLane, out uint present) + { + var hostLane = GraphicsHostLane(guestLane); + present = IsHostLanePresent(hostLane); + var sourceLane = _module.AddInstruction( + SpirvOp.Select, + _uintType, + present, + hostLane, + Load(_uintType, _subgroupInvocationIdInput)); + return ShuffleLane(value, sourceLane); + } + + // The fetch-inactive-off read of a graphics lane: usable is the source lane's EXEC state, judged by + // the guest EXEC bit for a lane the host never launched (set means whole-wave code turned the dead + // lane on). The caller applies the ISA's invalid-source result where usable is false. + private uint ReadGraphicsLaneIfActive(uint value, uint guestLane, out uint usable) + { + usable = IsGraphicsLaneUsable(guestLane); + return ReadGraphicsLane(value, guestLane, out _); + } + + private uint IsGraphicsLaneUsable(uint guestLane) + { + var activeWord = _module.AddInstruction( + SpirvOp.Select, _uintType, Load(_boolType, _exec), UInt(1), UInt(0)); + var hostActive = IsNotZero(ReadGraphicsLane(activeWord, guestLane, out var present)); + return _module.AddInstruction( + SpirvOp.Select, _boolType, present, hostActive, IsGuestLaneExecSet(guestLane)); + } + private uint CurrentLaneBit() => _waveLowering.CurrentLaneBit(); @@ -10069,8 +10303,11 @@ private bool UsesSubgroupOperations() => UsesSubgroupShuffle() || UsesSubgroupBroadcast() || UsesWaveControl() || + // These need the invocation's lane in the guest wave. V_WRITELANE picks its lane by it: without the lane + // inputs every invocation is lane 0, and a write to any other lane was dropped. _request.Program.Instructions.Any(static instruction => - instruction.Opcode is "VMbcntLoU32B32" or "VMbcntHiU32B32" or "DsWriteAddtidB32" or "DsReadAddtidB32")); + instruction.Opcode is "VMbcntLoU32B32" or "VMbcntHiU32B32" or "DsWriteAddtidB32" or "DsReadAddtidB32" or + "VWritelaneB32")); private static bool IsWaveMaskOperand(Gen5Operand operand) => operand.Kind == Gen5OperandKind.ScalarRegister && diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/SpirvModuleBuilder.cs b/src/SharpEmu.ShaderCompiler.Vulkan/SpirvModuleBuilder.cs index 1d9434d47..bfdf69047 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/SpirvModuleBuilder.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/SpirvModuleBuilder.cs @@ -330,6 +330,7 @@ public enum SpirvBuiltIn : uint PatchVertices = 14, VertexIndex = 42, InstanceIndex = 43, + BaseVertex = 4424, BaseInstance = 4425, FragCoord = 15, BaryCoordKhr = 5286, diff --git a/src/SharpEmu.ShaderCompiler/Gen5ShaderTranslator.cs b/src/SharpEmu.ShaderCompiler/Gen5ShaderTranslator.cs index 6aff5ad2a..10a5614d2 100644 --- a/src/SharpEmu.ShaderCompiler/Gen5ShaderTranslator.cs +++ b/src/SharpEmu.ShaderCompiler/Gen5ShaderTranslator.cs @@ -731,6 +731,7 @@ private static bool DecodeSop1(uint word, out string name, out uint sizeDwords, 0x09 => "SWqmB32", 0x0A => "SWqmB64", 0x0B => "SBrevB32", + 0x0C => "SBrevB64", 0x0F => "SBcnt1I32B32", 0x10 => "SBcnt1I32B64", 0x13 => "SFF1I32B32", @@ -1782,6 +1783,8 @@ public static string MubufOpcodeName(uint opcode) 0x23 => "BufferLoadSbyteD16Hi", 0x24 => "BufferLoadShortD16", 0x25 => "BufferLoadShortD16Hi", + 0x26 => "BufferLoadFormatD16HiX", + 0x27 => "BufferStoreFormatD16HiX", 0x30 => "BufferAtomicSwap", 0x31 => "BufferAtomicCmpswap", 0x32 => "BufferAtomicAdd", @@ -1834,7 +1837,10 @@ private static bool DecodeFlat( out string error) { var segment = (word >> 14) & 0x3; - var opcode = ((word >> 18) & 0x7F) | ((word & 1) << 7); + // GFX10 FLAT has a 7-bit opcode in bits 18..24. Bit 0 belongs to the + // offset; unlike MIMG it is not an opcode bit, so an odd offset must not + // change the opcode. + var opcode = (word >> 18) & 0x7F; sizeDwords = 2; error = string.Empty; var prefix = segment switch @@ -2021,6 +2027,7 @@ public static string MimgOpcodeName(uint opcode) 0x44 => "ImageGather4L", 0x47 => "ImageGather4Lz", 0x48 => "ImageGather4C", + 0x4C => "ImageGather4CL", 0x4E => "ImageGather4CBCl", 0x4F => "ImageGather4CLz", 0x57 => "ImageGather4LzO", @@ -2912,7 +2919,8 @@ _ when IsDataShareAtomic(opcode) && sourceVectorRegister, destinationVectorRegister, usesFlatAddress ? uint.MaxValue : scalarAddress, - SignExtend(word & 0x1FFF, 13), + // GFX10 FLAT offsets are 12-bit signed; bit 12 is DLC. + SignExtend(word & 0xFFF, 12), globallyCoherent, ((word >> 17) & 1) != 0, usesFlatAddress); @@ -2937,7 +2945,8 @@ _ when IsDataShareAtomic(opcode) && "BufferStoreFormatXyzw" => 4u, // The D16 forms hold two components in each register. "BufferLoadFormatD16X" or "BufferLoadFormatD16Xy" or - "BufferStoreFormatD16X" or "BufferStoreFormatD16Xy" => 1u, + "BufferStoreFormatD16X" or "BufferStoreFormatD16Xy" or + "BufferLoadFormatD16HiX" or "BufferStoreFormatD16HiX" => 1u, "BufferLoadFormatD16Xyz" or "BufferLoadFormatD16Xyzw" or "BufferStoreFormatD16Xyz" or "BufferStoreFormatD16Xyzw" => 2u, "BufferLoadUbyte" or diff --git a/src/SharpEmu.ShaderCompiler/Gen5TessellationLowering.cs b/src/SharpEmu.ShaderCompiler/Gen5TessellationLowering.cs index 8c57936f0..29d4b084d 100644 --- a/src/SharpEmu.ShaderCompiler/Gen5TessellationLowering.cs +++ b/src/SharpEmu.ShaderCompiler/Gen5TessellationLowering.cs @@ -59,4 +59,53 @@ public static Gen5ShaderProgram PrepareMergedHull(Gen5ShaderProgram program, uin } return new(program.Address, instructions) { FusedContinuationPc = checked(continuation + 8) }; } + + // A complete hull binary (AGC shader type HS) holds both halves in one code object, + // with no jump between two code objects to mark the boundary. The local half runs for + // the lanes below the low byte of the wave counts; the hull half then re-opens every + // lane and keeps those below the second byte. That re-open is the hull entry. + public static bool TryFindCombinedHullEntry(Gen5ShaderProgram program, out uint hullEntryPc) + { + hullEntryPc = 0; + if (program.TessellationRegisters.HullWaveCountScalar is not { } counts) return false; + var instructions = program.Instructions; + var gate = 0; + while (gate < instructions.Count && !(instructions[gate].Opcode.StartsWith("VCmpx", StringComparison.Ordinal) && + instructions[gate].Control is Gen5SdwaControl { Source1Select: 1 } && + instructions[gate].Sources.Contains(Gen5Operand.Scalar(counts)))) gate++; + if (gate == instructions.Count) return false; + for (var index = gate - 1; index >= 0 && !Ir.Gen5IrBranchResolver.Instance.IsBranch(instructions[index]); index--) + { + var instruction = instructions[index]; + if (instruction.Opcode != "SMovB64" || instruction.Destinations.Count != 1 || instruction.Sources.Count != 1 || + instruction.Destinations[0] != Gen5Operand.Scalar(126) || instruction.Sources[0] != Gen5Operand.Source(193)) continue; + hullEntryPc = instruction.Pc; + return true; + } + return false; + } + + // Both halves of a complete hull binary share one set of user scalars, and the hull + // half may read registers the local half left. It needs only the barrier that + // publishes the local half's writes; the local half's skip lands on that barrier. + public static Gen5ShaderProgram PrepareCombinedHull(Gen5ShaderProgram program) + { + if (!TryFindCombinedHullEntry(program, out var entry)) + throw new ArgumentException("A combined hull shader requires its local and hull wave-count gates.", nameof(program)); + var instructions = new List(program.Instructions.Count + 1); + foreach (var instruction in program.Instructions) + { + if (Ir.Gen5IrBranchResolver.Instance.TryGetBranchTarget(instruction, out var target) && + target != entry && (instruction.Pc < entry) != (target < entry)) + throw new NotSupportedException("A branch crosses the combined hull entry."); + if (instruction.Pc == entry) + instructions.Add(new(entry, Gen5ShaderEncoding.Sopp, "SBarrier", [0u], [], [], null)); + instructions.Add(instruction.Pc < entry ? instruction : instruction with + { + Pc = checked(instruction.Pc + 4), + AddressOffset = instruction.ProgramOffset, + }); + } + return new(program.Address, instructions); + } } diff --git a/src/SharpEmu.ShaderCompiler/Ir/Gen5WaveLaneLocalAnalysis.cs b/src/SharpEmu.ShaderCompiler/Ir/Gen5WaveLaneLocalAnalysis.cs index c44e27ab0..ab49d8546 100644 --- a/src/SharpEmu.ShaderCompiler/Ir/Gen5WaveLaneLocalAnalysis.cs +++ b/src/SharpEmu.ShaderCompiler/Ir/Gen5WaveLaneLocalAnalysis.cs @@ -204,7 +204,7 @@ private sealed class Block private static readonly HashSet ScalarDestination64Opcodes = new(StringComparer.Ordinal) { - "SMovB64", "SNotB64", "SWqmB64", "SQuadmaskB64", "SBitreplicateB64B32", "SGetpcB64", + "SMovB64", "SNotB64", "SWqmB64", "SBrevB64", "SQuadmaskB64", "SBitreplicateB64B32", "SGetpcB64", "SAndB64", "SAndn2B64", "SOrB64", "SOrn2B64", "SXorB64", "SNandB64", "SNorB64", "SXnorB64", "SLshlB64", "SLshrB64", "SAshrI64", "SBfeU64", "SBfeI64", "SBfmB64", "SCselectB64", "SBitset0B64", "SBitset1B64", @@ -223,7 +223,7 @@ private sealed class Block private static readonly HashSet SccKeepers = new(StringComparer.Ordinal) { - "SMovB32", "SMovB64", "SMovkI32", "SCselectB32", "SCselectB64", "SBrevB32", "SFF1I32B32", "SFF1I32B64", + "SMovB32", "SMovB64", "SMovkI32", "SCselectB32", "SCselectB64", "SBrevB32", "SBrevB64", "SFF1I32B32", "SFF1I32B64", "SFlbitI32B32", "SFlbitI32B64", "SBitset0B32", "SBitset1B32", "SBitset0B64", "SBitset1B64", "SMulI32", "SMulHiU32", "SMulHiI32", "SMulkI32", "SBfmB32", "SBfmB64", "SPackLlB32B16", "SPackLhB32B16", "SPackHhB32B16", "SGetpcB64", diff --git a/src/SharpEmu.ShaderCompiler/Resources/BindingLayout.cs b/src/SharpEmu.ShaderCompiler/Resources/BindingLayout.cs index 0b92bea1d..78ed569a2 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/BindingLayout.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/BindingLayout.cs @@ -390,6 +390,9 @@ public sealed class BindingLayout : IEquatable public uint StorageImageSwizzleCount { get; init; } // The program reads bindless heap records through descriptor set 1 (see BindlessHeap). public bool UsesBindlessHeap { get; init; } + + // Where the elements of each heap view of the program are for the draw (HeapView), two dwords each. + public uint HeapViewCount { get; init; } public IReadOnlyList UserDataRegisters { get; init; } = []; public IReadOnlyList Descriptors { get; init; } = []; @@ -420,7 +423,9 @@ public sealed class BindingLayout : IEquatable public uint StorageImageSwizzlesDword => BufferStridesDword + (BufferStrideCount + 1) / 2; - public uint ShaderDataDwordCount => StorageImageSwizzlesDword + (StorageImageSwizzleCount + 1) / 2; + public uint HeapViewsDword => StorageImageSwizzlesDword + (StorageImageSwizzleCount + 1) / 2; + + public uint ShaderDataDwordCount => HeapViewsDword + HeapViewCount * HeapView.DwordCount; public bool UsesPushData => PushDataStartDword != PushData.NoStart; @@ -691,7 +696,7 @@ public static BindingLayout Allocate( var shaderDataDwords = memoryOffsetDword + (usesTableBlock ? 2u : (memoryOffsetCount + 3) / 4) + (usesBufferLengths ? memoryOffsetCount : 0) + (usesDispatchThreadLimits ? 3u : 0u) + mipStatisticsCount + (usesMeshDrawParameters ? 6u : 0u) + (usesTessellationData ? Gen5TessellationData.DwordCount : 0u) + callArgumentCount * 2 + callTargetCount * 2 + - (bufferStrideCount + 1) / 2 + (storageImageSwizzleCount + 1) / 2; + (bufferStrideCount + 1) / 2 + (storageImageSwizzleCount + 1) / 2 + info.HeapViewCount * HeapView.DwordCount; var pushStart = usesTessellationData ? PushData.NoStart : pushDataAtTop ? PushData.TopFor(pushDataStartDword, shaderDataDwords) : PushData.StartFor(pushDataStartDword, shaderDataDwords); @@ -805,6 +810,7 @@ public static BindingLayout Allocate( BufferStrideCount = bufferStrideCount, StorageImageSwizzleCount = storageImageSwizzleCount, UsesBindlessHeap = info.UsesBindlessHeap, + HeapViewCount = info.HeapViewCount, UserDataRegisters = userDataRegisters, Descriptors = descriptors, }; @@ -831,6 +837,7 @@ other is not null && BufferStrideCount == other.BufferStrideCount && StorageImageSwizzleCount == other.StorageImageSwizzleCount && UsesBindlessHeap == other.UsesBindlessHeap && + HeapViewCount == other.HeapViewCount && UserDataRegisters.SequenceEqual(other.UserDataRegisters) && Descriptors.Count == other.Descriptors.Count && Descriptors.Zip(other.Descriptors).All(pair => pair.First.Kind == pair.Second.Kind && pair.First.Resources.SequenceEqual(pair.Second.Resources)); diff --git a/src/SharpEmu.ShaderCompiler/Resources/BindlessHeap.cs b/src/SharpEmu.ShaderCompiler/Resources/BindlessHeap.cs index cd50ffcf1..af9f2ccc7 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/BindlessHeap.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/BindlessHeap.cs @@ -3,22 +3,36 @@ namespace SharpEmu.ShaderCompiler.Resources; -// The descriptor heaps a bindless shader indexes at run time: a texture heap of 32-byte T# records and a sampler heap of -// 16-byte S# records, each read at a record only the shader knows. Descriptor set 1 holds one array per supported image -// class and two sampler arrays (plain and depth compare), indexed by the record number, and a bitset per array in which -// the shader marks every record it reads, so that the host can give that record a view. +// The descriptor heaps a bindless shader indexes at run time: buffers of records that hold 32-byte T#s or 16-byte S#s, +// each read at a record only the shader knows. Descriptor set 1 holds one array per supported image class and two sampler +// arrays (plain and depth compare), and a bitset per array in which the shader marks every element it reads, so that the +// host can give that element a view. A program may read several heaps, and a record may hold more than a descriptor +// (a material or terrain record with its textures among other fields), so the elements a read takes are those of its +// heap view (HeapView): the host gives each view its own run of elements for every draw. public static class BindlessHeap { public const uint DescriptorSet = 1; - public const uint Capacity = 65536; + // Every view of a draw has its own elements: a title that keeps two copies of a 46158-record texture heap beside its + // tables needs more than twice that. + public const uint Capacity = 131072; public const uint ImageRecordBytes = 32; + // A T# an R128 image instruction reads is its first four words. + public const uint R128RecordBytes = 16; public const uint SamplerRecordBytes = 16; public const uint FeedbackBinding = 63; public const uint FeedbackWordsPerArray = Capacity / 32; + // After the mark bitsets the feedback buffer holds the numeric class of every image element (ClassCode, ClassBits + // each), which the host writes with the element's view: the format of a record is unknown until the shader picks it. + public const uint ClassBits = 2; + public const uint ClassMask = (1u << (int)ClassBits) - 1; + public const uint ClassesPerWord = 32 / ClassBits; + public const uint ClassWordShift = 4; + public const uint ClassWords = Capacity >> (int)ClassWordShift; + // Set-1 elements from CallRecordFirstIndex on hold the views and samplers of call records (CallRecordSelector), which the // host assigns by their descriptor words; guest heap records use the elements below. CallRecordNullIndex stays null. - public const uint CallRecordFirstIndex = 49152; + public const uint CallRecordFirstIndex = Capacity - 16384; public const uint CallRecordNullIndex = Capacity - 1; // The call records buffer of a dispatch (DescriptorBindingKind.CallRecords): word 0 holds the row count N, then N rows of @@ -32,8 +46,9 @@ public static class BindlessHeap // The buffer holds at least this many words, so the lookup of an empty table reads inside it. public const uint CallRecordMinimumWords = 8; - // The image classes set 1 declares, in binding order; the sampler arrays follow them. A heap image is sampled as - // float, since its format is unknown until the shader picks its record. + // The image classes set 1 declares, in binding order; the sampler arrays follow them. An array holds float views and, + // when its class has integer forms (HoldsIntegers), the views of integer textures, which a shader reads through an + // unsigned or a signed declaration of the same binding: an element's numeric class says which declaration reads it. public static readonly HeapImageClass[] ImageClasses = BuildImageClasses(); public static readonly DescriptorBindingKind[] ImageKinds = ImageClasses.Select(static heapClass => heapClass.Kind).ToArray(); @@ -51,7 +66,20 @@ public static class BindlessHeap public static int ArrayCount => ImageKinds.Length + 2; - public static uint FeedbackWords => (uint)ArrayCount * FeedbackWordsPerArray; + public static uint MarkWords => (uint)ArrayCount * FeedbackWordsPerArray; + + public static uint FeedbackWords => MarkWords + ClassWords; + + // An integer texture is read by loads, which no cube or depth-compare class serves. + public static bool HoldsIntegers(int slot) => + (uint)slot < (uint)ImageClasses.Length && ImageClasses[slot] is { Cube: false, Compare: false }; + + public static uint ClassCode(ImageNumericClass numericClass) => numericClass switch + { + ImageNumericClass.Uint => 1, + ImageNumericClass.Sint => 2, + _ => 0, + }; // The binding of an image class in set 1, or -1 when set 1 has no array for it. public static int ImageSlot(DescriptorBindingKind kind) => Array.IndexOf(ImageKinds, kind); @@ -87,10 +115,13 @@ static HeapImageClass Class(ImageDimension dimension, bool cube = false, bool co // A descriptor the shader reads from a bindless heap at a record it picks at run time: the heap V# source, the scalar // read of the record's first dword (whose dynamic offset the shader keeps), that read's immediate offset and the record -// size. A cube image is sampled through a cube view. +// size. A cube image is sampled through a cube view. An R128 image instruction reads a 16-byte T#: the words after it in +// the heap are not the descriptor's. public sealed record HeapRecordSelector(uint HeapSource, int KeyMemoryIndex, uint Immediate, uint RecordBytes) { public bool Cube { get; init; } + + public bool R128 { get; init; } } // One image access whose image or sampler is a heap record. @@ -131,15 +162,77 @@ public sealed record CallRecordBufferWords(ScalarValue[] Words, bool Written); // reads itself. public sealed record CallRecordCallee(CallRecordField[] Fields, CallRecordBuffer[] Buffers, uint ArgumentBytes); -// A heap V# the plan evaluates for every draw, and whether it holds samplers. -public sealed record HeapRecordSource(uint Source, bool Sampler); +// A heap view of a program: the heap V# the plan evaluates for every draw, whether its records hold samplers, the +// immediate offset the program reads them at, and whether it reads them as 16-byte T#s (R128). +public sealed record HeapRecordSource(uint Source, bool Sampler, uint Immediate = 0, bool R128 = false); -// One heap V# a draw's bindless accesses read: its base address, record count and stride. -public readonly record struct BindlessHeapDescriptor(bool Sampler, ulong Base, uint Records, uint Stride) +// One heap view of a draw: the heap V#'s base address, record count and stride, the immediate offset of the view's reads, +// and whether its descriptors are 16-byte T#s. +public readonly record struct BindlessHeapDescriptor(bool Sampler, ulong Base, uint Records, uint Stride, uint Immediate = 0, bool R128 = false) { - public static BindlessHeapDescriptor FromWords(bool sampler, ReadOnlySpan words) => - new(sampler, words[0] | ((ulong)(words[1] & 0xFFFF) << 32), words[2], (words[1] >> 16) & 0x3FFF); + // The size of the view's descriptor in a record. + public uint DescriptorBytes => + Sampler ? BindlessHeap.SamplerRecordBytes : R128 ? BindlessHeap.R128RecordBytes : BindlessHeap.ImageRecordBytes; + + public static BindlessHeapDescriptor FromWords(bool sampler, ReadOnlySpan words, uint immediate = 0, bool r128 = false) => + new(sampler, words[0] | ((ulong)(words[1] & 0xFFFF) << 32), words[2], (words[1] >> 16) & 0x3FFF, immediate, r128); + + // The heap as its view sees it, which keys the view's run of elements (BindlessHeapViewTable). Packed descriptors + // (a stride of the descriptor's size or less) are one view at whatever immediate the shader reads them, since the + // read's whole offset picks the descriptor; their count is the V#'s bytes over the descriptor size (a raw V#, stride 0, + // counts bytes, a strided one records of its stride). A record view is keyed by the descriptor's offset in a record. + public BindlessHeapDescriptor ViewKey + { + get + { + if (Stride > DescriptorBytes) + { + return this with { Immediate = Immediate % Stride }; + } + + var bytes = Stride == 0 ? Records : (ulong)Records * Stride; + return this with { Records = (uint)Math.Min(bytes / DescriptorBytes, uint.MaxValue), Immediate = 0 }; + } + } } -// How the shader reads one heap record: the key read whose dynamic offset it kept, the immediate offset and the record size. -public readonly record struct HeapRecordUse(int KeyMemoryIndex, uint Immediate, uint RecordBytes); +// How the shader reads one heap record: the key read whose dynamic offset it kept, the immediate offset, the descriptor +// size and the program's heap view (its number among ShaderResourcePlan.HeapRecordSources). +public readonly record struct HeapRecordUse(int KeyMemoryIndex, uint Immediate, uint RecordBytes, int View = 0); + +// Where the elements of one heap view are for one draw, as the shader reads it from two dwords of shader data +// (BindingLayout.HeapViewsDword): the view's first element of set 1, the heap's record stride, the offset of the view's +// descriptor in a record, and how many records the view has elements for. The read at byte offset (key + immediate) of +// the heap takes element First + offset / Stride when offset % Stride is FieldOffset and that record is below Records; +// any other read takes the null element. +public readonly record struct HeapView(uint First, uint Stride, uint FieldOffset, uint Records) +{ + public const uint DwordCount = 2; + + // The stride and field offset are V# strides (14 bits); the first element and the count are below BindlessHeap.Capacity + // (18 bits). + public const uint StrideMask = 0x3FFF; + public const int ElementBits = 18; + public const uint ElementMask = (1u << ElementBits) - 1; + + // No element: every read of the view takes the null element. + public static HeapView None => new(0, 1, 0, 0); + + // The records of a heap V# are its elements when they can hold more than the descriptor: the shader's key picks the + // record and its immediate the field. A V# whose stride is the descriptor's size or less (a byte buffer, say) is + // read as packed descriptors, whichever part of the offset the shader keeps in its key. + public static HeapView Of(in BindlessHeapDescriptor heap, uint first, uint records) + { + var descriptorBytes = heap.DescriptorBytes; + return heap.Stride <= descriptorBytes + ? new HeapView(first, descriptorBytes, 0, records) + : new HeapView(first, heap.Stride, heap.Immediate % heap.Stride, records); + } + + // The guest address of the descriptor a record of the heap holds for this view. + public ulong DescriptorAddress(in BindlessHeapDescriptor heap, uint record) => heap.Base + (ulong)record * Stride + FieldOffset; + + public uint Word0 => (First & ElementMask) | ((Stride & StrideMask) << ElementBits); + + public uint Word1 => (Records & ElementMask) | ((FieldOffset & StrideMask) << ElementBits); +} diff --git a/src/SharpEmu.ShaderCompiler/Resources/GuestImageFormat.cs b/src/SharpEmu.ShaderCompiler/Resources/GuestImageFormat.cs index da109b66b..f919de442 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/GuestImageFormat.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/GuestImageFormat.cs @@ -35,7 +35,7 @@ public static class GuestImageFormat // is unsupported for sampling. private static readonly (uint Format, ImageNumericClass Class)[] SampledFormats = [ - (1, ImageNumericClass.Float), (Format8Uscaled, ImageNumericClass.Float), (5, ImageNumericClass.Uint), (7, ImageNumericClass.Float), (8, ImageNumericClass.Float), + (1, ImageNumericClass.Float), (Format8Uscaled, ImageNumericClass.Float), (5, ImageNumericClass.Uint), (6, ImageNumericClass.Sint), (7, ImageNumericClass.Float), (8, ImageNumericClass.Float), (11, ImageNumericClass.Uint), (12, ImageNumericClass.Sint), (13, ImageNumericClass.Float), (14, ImageNumericClass.Float), (15, ImageNumericClass.Float), (16, ImageNumericClass.Float), (18, ImageNumericClass.Uint), (19, ImageNumericClass.Sint), (20, ImageNumericClass.Uint), (21, ImageNumericClass.Sint), (22, ImageNumericClass.Float), (23, ImageNumericClass.Float), (24, ImageNumericClass.Float), diff --git a/src/SharpEmu.ShaderCompiler/Resources/IndirectSelectorBound.cs b/src/SharpEmu.ShaderCompiler/Resources/IndirectSelectorBound.cs new file mode 100644 index 000000000..a2213b490 --- /dev/null +++ b/src/SharpEmu.ShaderCompiler/Resources/IndirectSelectorBound.cs @@ -0,0 +1,178 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.ShaderCompiler.Resources; + +// Proves an inclusive unsigned upper bound for a material-table selector from the +// clamps and masks the shader itself applies (min, med3, and-mask, shifts, selects over +// bounded values). Anything not proven stays unbounded; there is no guess. +internal static class IndirectSelectorBound +{ + internal static uint? TryCreate(ShaderResourcePlan plan, ScalarValue selector) + { + if (selector.Kind != ScalarValueKind.FirstLane) return null; + var instruction = plan.Graph.Program.Instructions.FirstOrDefault(candidate => candidate.Pc == selector.Payload); + if (instruction is not { Opcode: "VReadfirstlaneB32", Sources.Count: 1 }) return null; + var bound = new Analyzer(plan).Read(instruction.Sources[0], instruction.Pc); + return bound is { } value && value <= uint.MaxValue ? (uint)value : null; + } + + private sealed class Analyzer(ShaderResourcePlan plan) + { + private readonly HashSet<(Gen5Operand Operand, uint Address)> _active = []; + private readonly Dictionary<(Gen5Operand Operand, uint Address), ulong?> _cache = []; + private int _requests; + + public ulong? Read(Gen5Operand operand, uint before) + { + var key = (operand, before); + if (_cache.TryGetValue(key, out var cached)) return cached; + if (++_requests > 512 || !_active.Add(key)) return null; + try { return _cache[key] = ReadCore(operand, before); } + finally { _active.Remove(key); } + } + + private ulong? ReadCore(Gen5Operand operand, uint before) + { + if (operand.Kind == Gen5OperandKind.LiteralConstant) return operand.Value; + if (operand.Kind == Gen5OperandKind.EncodedConstant) + return Gen5InlineConstants.TryDecode(operand.Value, out var constant) ? constant : null; + if (operand.Kind is not (Gen5OperandKind.ScalarRegister or Gen5OperandKind.VectorRegister)) return null; + var flow = plan.Graph.ControlFlow; + var initial = Enumerable.Range(0, flow.Blocks.Count).FirstOrDefault( + index => before >= flow.Blocks[index].StartPc && before < flow.Blocks[index].EndPc, -1); + if (initial < 0) return null; + var pending = new Queue<(int Block, uint Before)>(); + var visited = new HashSet<(int Block, uint Before)>(); + ulong result = 0; + var any = false; + pending.Enqueue((initial, before)); + while (pending.TryDequeue(out var position)) + { + if (!visited.Add(position)) continue; + var block = flow.Blocks[position.Block]; + var found = false; + foreach (var instruction in plan.Graph.Program.Instructions.Reverse()) + { + if (instruction.Pc < block.StartPc || instruction.Pc >= position.Before) continue; + if (instruction.Opcode.Contains("Movreld", StringComparison.Ordinal) || + instruction.Opcode.Contains("Movrelsd", StringComparison.Ordinal) || + instruction.Opcode.Contains("Swaprel", StringComparison.Ordinal) || + instruction.Opcode.Contains("GprIdx", StringComparison.Ordinal)) return null; + if (IndirectSelectorValues.WritesRegister(instruction, operand)) + { + if (Define(instruction, operand) is not { } definition) return null; + result = any ? Math.Max(result, definition) : definition; + any = true; + found = true; + break; + } + if (operand.Kind == Gen5OperandKind.VectorRegister && IndirectSelectorValues.MayExpandExecution(instruction)) return null; + } + if (found) continue; + // Entry state (user data or an undefined register) is not bounded by the shader. + if (position.Block == 0 || flow.Predecessors[position.Block].Count == 0) return null; + foreach (var predecessor in flow.Predecessors[position.Block]) + pending.Enqueue((predecessor, flow.Blocks[predecessor].EndPc)); + } + return any ? result : null; + } + + private ulong? Define(Gen5ShaderInstruction instruction, Gen5Operand destination) + { + if (!instruction.Destinations.Contains(destination)) return null; + if (instruction.Control is Gen5Vop3Control { AbsoluteMask: not 0 } or Gen5Vop3Control { NegateMask: not 0 } or + Gen5Vop3Control { Clamp: true } or Gen5Vop3Control { OutputModifier: not 0 } or Gen5Vop3Control { OperandSelect: not 0 } or + Gen5SdwaControl or Gen5DppControl or Gen5Dpp8Control or Gen5Vop3pControl) return null; + var sources = instruction.Sources; + ulong? Source(int index) => index < sources.Count ? Read(sources[index], instruction.Pc) : null; + bool Constant(int index, out uint value) + { + value = 0; + if (index >= sources.Count) return false; + if (sources[index].Kind == Gen5OperandKind.LiteralConstant) { value = sources[index].Value; return true; } + return sources[index].Kind == Gen5OperandKind.EncodedConstant && Gen5InlineConstants.TryDecode(sources[index].Value, out value); + } + // A bit field of the given width: at most the mask, and at most the shifted source. + static ulong Mask(uint width) => width >= 32 ? uint.MaxValue : (1ul << (int)width) - 1; + switch (instruction.Opcode) + { + case "SMovB32" or "VMovB32": + return Source(0); + case "VMinU32" or "SMinU32": + { + // min(a, b) <= either operand, so one proven bound suffices. + var (a, b) = (Source(0), Source(1)); + return a is null ? b : b is null ? a : Math.Min(a.Value, b.Value); + } + case "VMin3U32": + { + var bounds = new[] { Source(0), Source(1), Source(2) }.Where(bound => bound is not null).Select(bound => bound!.Value).ToArray(); + return bounds.Length == 0 ? null : bounds.Min(); + } + case "VMinI32" or "SMinI32": + { + // A signed minimum is an unsigned bound only when no operand can be negative. + var (a, b) = (Source(0), Source(1)); + return a is <= 0x7FFFFFFF && b is <= 0x7FFFFFFF ? Math.Min(a.Value, b.Value) : null; + } + case "VMed3U32": + { + // The median is at most the second largest of the operand bounds, an unbounded operand counting as the maximum. + var bounds = new[] { Source(0), Source(1), Source(2) }.Select(bound => bound ?? uint.MaxValue).ToArray(); + Array.Sort(bounds); + return bounds[1] == uint.MaxValue ? null : bounds[1]; + } + case "VMed3I32": + { + var bounds = new[] { Source(0), Source(1), Source(2) }; + if (bounds.Any(bound => bound is null or > 0x7FFFFFFF)) return null; + var sorted = bounds.Select(bound => bound!.Value).Order().ToArray(); + return sorted[1]; + } + case "VAndB32" or "SAndB32": + { + var (a, b) = (Source(0), Source(1)); + return a is null ? b : b is null ? a : Math.Min(a.Value, b.Value); + } + case "VCndmaskB32" or "SCselectB32": + { + var (a, b) = (Source(0), Source(1)); + return a is null || b is null ? null : Math.Max(a.Value, b.Value); + } + case "VLshrrevB32" when Constant(0, out var shift): + return Source(1) is { } reversed ? reversed >> (int)(shift & 31) : null; + case "SLshrB32" when Constant(1, out var shift): + return Source(0) is { } scalar ? scalar >> (int)(shift & 31) : null; + case "VBfeU32" when Constant(2, out var width) && Constant(1, out var offset): + { + var mask = Mask(width); + return Source(0) is { } field ? Math.Min(mask, field >> (int)(offset & 31)) : mask; + } + case "SBfeU32" when Constant(1, out var packed): + { + var mask = Mask((packed >> 16) & 0x7F); + return Source(0) is { } field ? Math.Min(mask, field >> (int)(packed & 31)) : mask; + } + case "SLshlB32" when Constant(1, out var shift): + return Source(0) is { } left && left << (int)(shift & 31) <= uint.MaxValue && (left << (int)(shift & 31)) >> (int)(shift & 31) == left ? + left << (int)(shift & 31) : null; + case "VLshlrevB32" when Constant(0, out var shift): + return Source(1) is { } right && right << (int)(shift & 31) <= uint.MaxValue && (right << (int)(shift & 31)) >> (int)(shift & 31) == right ? + right << (int)(shift & 31) : null; + case "SAddU32" or "VAddU32" or "SAddI32" or "VAddI32": + { + var (a, b) = (Source(0), Source(1)); + return a is not null && b is not null && a.Value + b.Value <= uint.MaxValue ? a.Value + b.Value : null; + } + case "VMulLoU32" or "SMulI32": + { + var (a, b) = (Source(0), Source(1)); + return a is not null && b is not null && (a.Value == 0 || b.Value <= uint.MaxValue / a.Value) ? a.Value * b.Value : null; + } + default: + return null; + } + } + } +} diff --git a/src/SharpEmu.ShaderCompiler/Resources/IndirectSelectorValues.cs b/src/SharpEmu.ShaderCompiler/Resources/IndirectSelectorValues.cs index ecfef13d7..341215171 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/IndirectSelectorValues.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/IndirectSelectorValues.cs @@ -87,6 +87,10 @@ bool ReadCapturedWord(ulong address, out uint word) return values.Length != 0; } + internal static bool WritesRegister(Gen5ShaderInstruction instruction, Gen5Operand register) => Builder.WritesRegister(instruction, register); + + internal static bool MayExpandExecution(Gen5ShaderInstruction instruction) => Builder.MayExpandExecution(instruction); + private sealed class Builder(ShaderResourcePlan plan) { private readonly HashSet<(Gen5Operand Operand, uint Address)> _active = []; @@ -183,7 +187,7 @@ private sealed class Builder(ShaderResourcePlan plan) return third is null ? null : new(Operation: ScalarOperation.IAdd32, Inputs: [result, third]); } - private static bool MayExpandExecution(Gen5ShaderInstruction instruction) + public static bool MayExpandExecution(Gen5ShaderInstruction instruction) { if (instruction.Opcode is "SAndSaveexecB64" or "SAndSaveexecB32") return false; return instruction.Opcode.Contains("Saveexec", StringComparison.Ordinal) || @@ -192,7 +196,7 @@ private static bool MayExpandExecution(Gen5ShaderInstruction instruction) WritesRegister(instruction, Gen5Operand.Scalar(126)) || WritesRegister(instruction, Gen5Operand.Scalar(127)); } - private static bool WritesRegister(Gen5ShaderInstruction instruction, Gen5Operand register) + public static bool WritesRegister(Gen5ShaderInstruction instruction, Gen5Operand register) { if (register.Kind == Gen5OperandKind.ScalarRegister && register.Value is 106 or 107 && instruction.Opcode.StartsWith('V')) return true; diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializationCache.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializationCache.cs index 7890b7193..5acb8d09a 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializationCache.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializationCache.cs @@ -1215,6 +1215,13 @@ private bool MaterializeCore( descriptorChanged = true; } + // The heaps are named by words the entry may have learned to move with a base: they are read again. + BindlessHeapDescriptor[] heaps = []; + if (validated && !ResourceMaterializer.TryEvaluateHeaps(plan, inputs, out heaps)) + { + validated = false; + } + if (validated) { if (previous is not null) @@ -1229,7 +1236,7 @@ private bool MaterializeCore( variant.VolatilePeriod = 0; Hits++; _totalHits.Increment(); - snapshot = rebase.Apply(WithCurrentUserData(variant.Snapshot, inputs.UserData), inputs.UserData); + snapshot = WithHeaps(rebase.Apply(WithCurrentUserData(variant.Snapshot, inputs.UserData), inputs.UserData), heaps); if (_statisticsDiffer) { snapshot = WithMipStatistics(snapshot, MipStatisticsOf(variant)); @@ -1288,7 +1295,7 @@ private bool MaterializeCore( _outcome = MaterializeOutcome.RebaseHit; Hits++; _totalHits.Increment(); - snapshot = rebased; + snapshot = WithCurrentHeaps(plan, inputs, rebased); specialization = refreshedFrom.Specialization; failure = default; return true; @@ -1320,7 +1327,7 @@ private bool MaterializeCore( _outcome = MaterializeOutcome.TableRefresh; TableRefreshes++; _totalRefreshes.Increment(); - snapshot = rebase.Apply(WithCurrentUserData(refreshed.Snapshot, inputs.UserData), inputs.UserData); + snapshot = WithCurrentHeaps(plan, inputs, rebase.Apply(WithCurrentUserData(refreshed.Snapshot, inputs.UserData), inputs.UserData)); specialization = refreshed.Specialization; failure = default; return true; @@ -1719,6 +1726,29 @@ private static ulong[] Union(ulong[]? learned, ulong[] used) // A cached snapshot is shared by every draw that hits it, so it keeps the user data of the draw // that built it; a draw whose unread words differ gets its own copy that carries its own. + // The snapshot with the heaps the draw's bindless records are read from now. A cached entry holds the heaps of the + // draw it was built for; the V# that names a heap can move with a base the entry rebases (a table the guest allocates + // per frame), and the host resolves the records of the heap it is told. + private static ResourceSnapshot WithHeaps(ResourceSnapshot snapshot, BindlessHeapDescriptor[] heaps) => + snapshot.Heaps.AsSpan().SequenceEqual(heaps) + ? snapshot + : new ResourceSnapshot + { + Buffers = snapshot.Buffers, + Images = snapshot.Images, + Samplers = snapshot.Samplers, + FlattenedResourceTable = snapshot.FlattenedResourceTable, + UserData = snapshot.UserData, + DeviceAddressRanges = snapshot.DeviceAddressRanges, + MipStatistics = snapshot.MipStatistics, + Heaps = heaps, + Origin = snapshot.Origin, + }; + + // A draw served from an entry reads its heap V#s again; one that cannot be read has no heap (its records read null). + private static ResourceSnapshot WithCurrentHeaps(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, ResourceSnapshot snapshot) => + WithHeaps(snapshot, ResourceMaterializer.TryEvaluateHeaps(plan, inputs, out var heaps) ? heaps : []); + private static ResourceSnapshot WithCurrentUserData(ResourceSnapshot cached, IReadOnlyList userData) { var words = cached.UserData; diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs index d8c7e7974..f57c2efea 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs @@ -962,28 +962,9 @@ private static bool MaterializeSnapshot(ShaderResourcePlan plan, ResourceRuntime snapshot.BufferCandidateTables.Add(candidateTable); } - // The heap V#s the bindless heap records are read from, for the host's descriptor set 1. - if (plan.HeapRecordSources.Count != 0) + if (!TryEvaluateHeaps(plan, inputs, out snapshot.Heaps)) { - var heapSources = new uint[plan.HeapRecordSources.Count]; - for (var index = 0; index < heapSources.Length; index++) - heapSources[index] = plan.HeapRecordSources[index].Source; - if (!RuntimeValueEvaluator.EvaluateSources(plan, heapSources, inputs, [], evaluateTable: false, out var heaps, out _) || - heaps.Count != heapSources.Length) - { - return false; - } - - snapshot.Heaps = new BindlessHeapDescriptor[heaps.Count]; - for (var index = 0; index < heaps.Count; index++) - { - if (heaps[index].DwordCount != 4) - { - return false; - } - - snapshot.Heaps[index] = BindlessHeapDescriptor.FromWords(plan.HeapRecordSources[index].Sampler, heaps[index].Dwords); - } + return false; } snapshot.UserData = inputs.UserData.ToArray(); @@ -1219,7 +1200,8 @@ private static bool ReservedImageBitsClear(ReadOnlySpan descriptor) { ReadOnlySpan reserved = [ - 0x00000000u, 0x20000000u, 0xf0003000u, 0x00000000u, + // GFX10/10.3 word 2 bit 31 is RESOURCE_LEVEL, not reserved. + 0x00000000u, 0x20000000u, 0x70003000u, 0x00000000u, 0xe000e000u, 0xf9000000u, 0x00007b00u, 0x00000000u, ]; for (var dword = 0; dword < reserved.Length; dword++) @@ -1295,18 +1277,57 @@ private static bool UsableImageCandidate(ReadOnlySpan candidate, bool r128 !NullImageDescriptor(candidate) && ValidImageDescriptor(candidate, r128) && ReservedImageBitsClear(candidate) && GuestImageFormat.SampledNumericClass(GuestImageFormat.FormatOf(candidate)) != ImageNumericClass.Unsupported; - // A bindless heap record the host can give a float view without a conversion in the shader: a valid sampled T# of a - // float format. A freed record (0xFEFEFEFE words) fails the reserved-bit check. - public static bool IsFloatHeapImage(ReadOnlySpan words) + // The heap V#s the bindless heap records of a draw are read from, for the host's descriptor set 1. They are read for + // every draw, also one whose other descriptors a cache entry still holds: a table the guest allocates per frame names + // its heaps at another address each time. + internal static bool TryEvaluateHeaps(ShaderResourcePlan plan, ResourceRuntimeInputs inputs, out BindlessHeapDescriptor[] heaps) { - if (words.Length < 8 || !UsableImageCandidate(words, r128: false)) + heaps = []; + if (plan.HeapRecordSources.Count == 0) + { + return true; + } + + var heapSources = new uint[plan.HeapRecordSources.Count]; + for (var index = 0; index < heapSources.Length; index++) + heapSources[index] = plan.HeapRecordSources[index].Source; + if (!RuntimeValueEvaluator.EvaluateSources(plan, heapSources, inputs, [], evaluateTable: false, out var words, out _) || + words.Count != heapSources.Length) { return false; } + heaps = new BindlessHeapDescriptor[words.Count]; + for (var index = 0; index < words.Count; index++) + { + if (words[index].DwordCount != 4) + { + return false; + } + + var view = plan.HeapRecordSources[index]; + heaps[index] = BindlessHeapDescriptor.FromWords(view.Sampler, words[index].Dwords, view.Immediate, view.R128); + } + + return true; + } + + // The numeric class of a bindless heap record the host can give a view without a conversion in the shader: a valid + // sampled T# of a float, unsigned or signed format. Any other record is Unsupported; a freed record (0xFEFEFEFE + // words) fails the reserved-bit check. The words of an R128 T# are its first four, the rest zero. + public static ImageNumericClass HeapImageNumericClass(ReadOnlySpan words, bool r128 = false) + { + if (words.Length < 8 || !UsableImageCandidate(words, r128)) + { + return ImageNumericClass.Unsupported; + } + var format = GuestImageFormat.FormatOf(words); - return GuestImageFormat.SampledNumericClass(format) == ImageNumericClass.Float && - ImageConversionFormat(format) == GuestImageFormat.Invalid; + var numericClass = GuestImageFormat.SampledNumericClass(format); + return numericClass is ImageNumericClass.Float or ImageNumericClass.Uint or ImageNumericClass.Sint && + ImageConversionFormat(format) == GuestImageFormat.Invalid + ? numericClass + : ImageNumericClass.Unsupported; } private static ulong ScalarBufferSize(ReadOnlySpan descriptor) @@ -1388,19 +1409,62 @@ private static bool MaterializeIndirectImage( } } var records = (ulong)material.Dwords[2]; - if (provenOffsets is null && (indirect.SharedSelector ? records : probeCount) > MaxIndirectImageProbes) + // A selector the shader clamps or masks reaches exactly selector * stride + offset for + // selector in [0, bound]; that set is proven, so it replaces the exhaustive enumeration + // of every residue + k * step (the product wraps modulo 2^32 for an unbounded selector). + IEnumerable offsets; + if (provenOffsets is not null) { - return false; + offsets = provenOffsets.Select(offset => (ulong)offset); } + else if (indirect.SelectorBound is { } bound) + { + var last = (ulong)bound; + if (last * indirect.SelectorStride + indirect.SelectorOffset <= uint.MaxValue) + { + last = indirect.SelectorOffset > limit ? 0 : Math.Min(last, (limit - indirect.SelectorOffset) / indirect.SelectorStride); + } - var keys = new List { 0 }; - var seen = new HashSet { 0 }; + if (last + 1 > MaxIndirectImageProbes) + { + failure = ResourceMaterializationFailure.ImageCapacityExceeded; + return false; + } + + if (diagnostic is not null) + { + diagnostic.SelectionMode = "clamp_bounded"; + } + + offsets = Enumerable.Range(0, (int)last + 1) + .Select(selector => unchecked((ulong)((uint)selector * indirect.SelectorStride + indirect.SelectorOffset))) + .Distinct(); + } // A loop counter walks the table record by record: the keys are the ones its records hold, not every dword // the stride lattice reaches. Anything past the last record reads as zero, which is key 0. - var offsets = provenOffsets is not null ? provenOffsets.Select(offset => (ulong)offset) : - indirect.SharedSelector ? - Enumerable.Range(0, (int)records).Select(index => (ulong)unchecked(indirect.SelectorOffset + (uint)index * materialStride)) : - Enumerable.Range(0, (int)probeCount).Select(index => residue + (ulong)index * step); + else if (indirect.SharedSelector && records <= MaxIndirectImageProbes) + { + offsets = Enumerable.Range(0, (int)records).Select(index => (ulong)unchecked(indirect.SelectorOffset + (uint)index * materialStride)); + } + else if (!indirect.SharedSelector && probeCount <= MaxIndirectImageProbes) + { + offsets = Enumerable.Range(0, (int)probeCount).Select(index => residue + (ulong)index * step); + } + else + { + // A table this large cannot be enumerated into bindings. The access reads the null image, as a heap record at + // an index the host cannot evaluate does (BindlessNullDescriptors), so the draw still runs instead of being + // rejected (fatal with strict shaders): a pixel shader reads its terrain + // material table through such a selector. + result.Descriptors.Add(DescriptorWords.Empty(8)); + result.Candidates.Add(0); + result.Keys.Add(0); + failure = ResourceMaterializationFailure.None; + return true; + } + + var keys = new List { 0 }; + var seen = new HashSet { 0 }; foreach (var offset in offsets) { if (!ReadScalarBufferWord(material.Dwords, (uint)offset, indirect.MaterialImmediate, inputs, out var key)) @@ -1963,8 +2027,11 @@ private static bool BuildSpecialization( image.IndirectRoot == DescriptorConstants.NoIndex; var shaderSwizzle = runtimeSwizzle ? DescriptorConstants.IdentityImageSwizzle : storage || conversionFormat != GuestImageFormat.Invalid ? descriptor[3] & 0xFFF : image.ShaderSwizzle; - var rawSintStorage = storage && format == GuestImageFormat.Format32Sint && baseImage.Written && !baseImage.Read && !baseImage.Atomic; var numericClass = GuestImageFormat.SampledNumericClass(format); + // A signed-integer storage image the program only writes stores the low bits of each register, which are the + // same bits as unsigned: it is compiled and viewed as the unsigned format of its width (ImageRequestBuilders). + // A compute shader can write a 16_SINT image. + var rawSintStorage = storage && numericClass == ImageNumericClass.Sint && baseImage.Written && !baseImage.Read && !baseImage.Atomic; if (storage) { if ((!rawSintStorage && numericClass == ImageNumericClass.Sint) || numericClass == ImageNumericClass.Unsupported) @@ -2051,7 +2118,8 @@ private static bool BuildSpecialization( var imageClass = images[(int)exemplar]; var separateSampledDimensions = info.Images[rootIndex].ResourceClass == ImageResourceClass.Sampled; - var sharedSelector = plan.DescriptorSources[(int)info.Images[rootIndex].Source].IndirectImage is { SharedSelector: true }; + var nullIncompatible = plan.NullIncompatibleImageCandidates || + plan.DescriptorSources[(int)info.Images[rootIndex].Source].IndirectImage is { SharedSelector: true }; for (var candidate = 0; candidate < images.Count; candidate++) { var image = images[candidate]; @@ -2061,7 +2129,8 @@ private static bool BuildSpecialization( } // A shared selector read such a table as null before it had one: a candidate of another class reads as null too. - if (sharedSelector && !NullImageDescriptor(snapshot.Images[candidate]) && + // So does one of a table the program cache could not read from the heap (NullIncompatibleImageCandidates). + if (nullIncompatible && !NullImageDescriptor(snapshot.Images[candidate]) && !CompatibleCandidates(image, imageClass, separateSampledDimensions)) { Array.Clear(snapshot.Images[candidate]); diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceTracker.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceTracker.cs index 64301f3e3..f3799f21b 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceTracker.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceTracker.cs @@ -25,6 +25,7 @@ public sealed partial class ResourceTracker private readonly bool _bindlessNullDescriptors; private readonly SortedSet _nullBindlessPcs = new(); private readonly bool _bindlessHeap; + private readonly bool _preferHeapRecords; private readonly bool _callRecordsEnabled; private readonly List _heapRecords = []; private readonly List _callRecords = []; @@ -63,11 +64,13 @@ public sealed record Result( IReadOnlyList HeapRecords, IReadOnlyList CallRecords); - private ResourceTracker(ShaderResourcePlan plan, bool bindlessNullDescriptors, bool bindlessHeap, bool callRecords) + private ResourceTracker(ShaderResourcePlan plan, bool bindlessNullDescriptors, bool bindlessHeap, bool callRecords, + bool preferHeapRecords) { _plan = plan; _bindlessNullDescriptors = bindlessNullDescriptors; _bindlessHeap = bindlessHeap; + _preferHeapRecords = preferHeapRecords && bindlessHeap; _callRecordsEnabled = callRecords; _graph = plan.Graph; var roots = new List(); @@ -115,12 +118,20 @@ private ResourceTracker(ShaderResourcePlan plan, bool bindlessNullDescriptors, b // record that the shader reads through descriptor set 1 (see BindlessHeap). // With callRecords, the images and samplers a callee linked with run-time arguments reads through its record are call // records (see CallRecordSelector), which descriptor set 1 holds. + // With preferHeapRecords (and the heap), a sampled image the heap can serve is planned as a heap record before the + // indirect-image planner may claim it as a table: a table binds every image it can select, so one that selects more than + // a draw may bind could not be materialized, while a heap record reads its descriptor at run time. public static Result Track(ShaderResourcePlan plan, bool bindlessNullDescriptors = false, bool bindlessHeap = false, - bool callRecords = false) => - new ResourceTracker(plan, bindlessNullDescriptors, bindlessHeap, callRecords).Run(); + bool callRecords = false, bool preferHeapRecords = false) => + new ResourceTracker(plan, bindlessNullDescriptors, bindlessHeap, callRecords, preferHeapRecords).Run(); private Result Run() { + if (_preferHeapRecords) + { + PlanHeapRecords(); + } + PlanIndirectImages(); PlanHeapRecords(); PlanCallRecords(); @@ -569,7 +580,8 @@ private uint InternRuntimeSource(ScalarValue handle, uint pc) private bool IsHostBufferHandle(ScalarValue? handle) => handle is { Kind: ScalarValueKind.BufferHandle, Operands.Length: 4 } && - handle.Operands.All(dword => dword.Type == ScalarValueType.U32 && _plan.ValidateRuntimeValue(dword)); + handle.Operands.All(dword => dword.Type == ScalarValueType.U32 && _plan.ValidateRuntimeValue(dword) && + !DependsOnLoopCarriedRead(dword)); private bool IsDeviceLoadedBufferHandle(ScalarValue? handle) => handle is { Kind: ScalarValueKind.BufferHandle, Operands.Length: 4 } && @@ -658,6 +670,56 @@ private bool DependsOnScalarMemoryWord(ScalarValue value) return false; } + // A value that a loop recomputes from memory it read on the previous iteration (a + // pointer walk) differs per iteration even when its phis look structurally invariant. + private bool DependsOnLoopCarriedRead(ScalarValue value) + { + var phis = new HashSet(); + var pending = new Stack(); + var visited = new HashSet(); + pending.Push(value); + while (pending.TryPop(out var current)) + { + if (!visited.Add(current)) + continue; + if (current.Kind == ScalarValueKind.Phi) + phis.Add(current); + foreach (var operand in Dependencies(current)) + pending.Push(operand); + } + + foreach (var phi in phis) + { + // Look for the phi again below a memory read reached from its own operands. + var stack = new Stack<(ScalarValue Value, bool ThroughRead)>(); + var seen = new HashSet<(ScalarValue, bool)>(); + foreach (var operand in phi.Operands) + stack.Push((operand, false)); + while (stack.TryPop(out var entry)) + { + if (!seen.Add(entry)) + continue; + if (ReferenceEquals(entry.Value, phi) && entry.ThroughRead) + return true; + if (ReferenceEquals(entry.Value, phi)) + continue; + var throughRead = entry.ThroughRead || + entry.Value.Kind is ScalarValueKind.ScalarAddressWord or ScalarValueKind.ScalarBufferWord or + ScalarValueKind.ResourceTableWord; + foreach (var operand in Dependencies(entry.Value)) + stack.Push((operand, throughRead)); + } + } + + return false; + } + + // A resource-table word stands for the flattened read it names. + private IEnumerable Dependencies(ScalarValue value) => + value.Kind == ScalarValueKind.ResourceTableWord && value.Payload < (ulong)_plan.TableReads.Count + ? [_plan.TableReads[(int)value.Payload].Value] + : value.Operands; + private uint GetHandleSource( ScalarValue? handle, ScalarValueKind expected, @@ -685,7 +747,7 @@ private uint GetHandleSource( // single source of truth instead of a narrower, ImageHandle-specific blanket ban. var badDword = 0u; var controlDependent = false; - if (nonContiguousImage || !ValidateSource(source, out badDword, out controlDependent)) + if (!ValidateSource(source, out badDword, out controlDependent)) { // A bindless image/sampler descriptor whose dwords resolve through a // control-dependent phi (e.g. a hash-table/linear-probe material lookup, as seen @@ -761,7 +823,8 @@ private string DescribeValueShape(ScalarValue value, int depth = 0) return $"{value.Kind}#{value.Id}"; } - // An image descriptor read from a scalar buffer must be one contiguous record. + // Whether an image descriptor read from a scalar buffer is one contiguous record. Any layout is valid when each word is + // a runtime value (the host evaluates the words one by one); a non-contiguous one with an SAndB32 hole reads as null. private bool IsContiguousScalarBufferRecord(DescriptorSource source) { if (!source.Dwords.Any(dword => dword.Kind == ScalarValueKind.ScalarBufferWord)) @@ -1193,6 +1256,22 @@ private void Collect(int index) return; } + // A V# chosen by control flow (a phi over several descriptors) has no single source + // to bind. Its SGPRs hold the selected descriptor when the access runs, so the + // access reads it there, as the hardware does, through the device-address table. + // A typed (tbuffer) access has no device lowering and keeps the plan error. + if (memory.Kind == MemoryResourceKind.Buffer && + access.Handle is { Kind: ScalarValueKind.BufferHandle, Operands.Length: 4 } && + !memory.Opcode.StartsWith("TBuffer", StringComparison.Ordinal) && + ((!ValidateSource(MakeSource(access.Handle, 4, false, false, memory.Pc), out _, out var controlDependent) && + controlDependent) || + access.Handle.Operands.Any(DependsOnLoopCarriedRead))) + { + memory.DeviceDescriptor = true; + _info.UsesDeviceAddresses = true; + return; + } + var source = GetHandleSource( access.Handle, ScalarValueKind.BufferHandle, @@ -1584,6 +1663,7 @@ private void TryPlanHeapRecord(ScalarValue handle, bool sampler, uint pc) Heap = new HeapRecordSelector(heapSource, memoryIndices[0], first.Offset, (uint)width * sizeof(uint)) { Cube = !sampler && instruction?.Control is Gen5ImageControl { Dimension: 3 }, + R128 = !sampler && instruction is { Control: Gen5ImageControl, Words.Count: > 0 } && ((instruction.Words[0] >> 15) & 1) != 0, }, }); _heapRecords.Add(new HeapRecordPlan @@ -1638,7 +1718,8 @@ private void PlanIndirectImages() { var memory = _plan.Memory[index]; if (memory.Kind != MemoryResourceKind.Image || _plan.Accesses[index]?.Handle is not { } handle || - _indirectImages.Any(plan => ReferenceEquals(plan.Handle, handle))) + _indirectImages.Any(plan => ReferenceEquals(plan.Handle, handle)) || + _preferHeapRecords && HeapRecordFor(handle, sampler: false) is not null) { continue; } @@ -1883,6 +1964,7 @@ private bool TryMakeIndirectImage(ScalarValue handle, uint pc, out IndirectImage IndirectImage = new IndirectImageSelector(materialSourceIndex, heapSourceIndex, selectorStride, selectorOffset, 0) { SelectorValues = IndirectSelectorValues.Create(_plan, selector), + SelectorBound = IndirectSelectorBound.TryCreate(_plan, selector), MaterialImmediate = materialMemory.Offset, SharedSelector = selector.Kind != ScalarValueKind.FirstLane, }, diff --git a/src/SharpEmu.ShaderCompiler/Resources/ScalarValueGraph.Builder.cs b/src/SharpEmu.ShaderCompiler/Resources/ScalarValueGraph.Builder.cs index bc57aa25b..89e6c2268 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ScalarValueGraph.Builder.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ScalarValueGraph.Builder.cs @@ -684,11 +684,14 @@ private void ApplyScalarAlu(Gen5ShaderInstruction instruction, RegisterState sta return; } - if (opcode is "SBcnt1I32B64" or "SFF1I32B64" or "SFlbitI32B64" or "SWqmB64" or "SBfeI64") + if (opcode is "SBcnt1I32B64" or "SFF1I32B64" or "SFlbitI32B64" or "SWqmB64" or "SBrevB64" or "SBfeI64") { var (low, high) = ReadPair(instruction.Sources[0], state); switch (opcode) { + case "SBrevB64": + state.WritePair(destinationRegister, Unary(ScalarOperation.BitReverse32, high), Unary(ScalarOperation.BitReverse32, low)); + break; case "SWqmB64": { var quadLow = Unary(ScalarOperation.QuadMask32, low); diff --git a/src/SharpEmu.ShaderCompiler/Resources/ShaderResourceInfo.cs b/src/SharpEmu.ShaderCompiler/Resources/ShaderResourceInfo.cs index 52d6853b7..267f0da52 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ShaderResourceInfo.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ShaderResourceInfo.cs @@ -187,6 +187,10 @@ public sealed class ShaderResourceInfo // Some image access reads its image or sampler from a bindless heap through descriptor set 1. public bool UsesBindlessHeap { get; set; } + // The heap views of those accesses (ShaderResourcePlan.HeapRecordSources); the layout carries where each one's + // elements are as shader data (BindingLayout.HeapViewsDword). + public uint HeapViewCount { get; set; } + // Some image access reads its image or sampler through a linked callee's record argument (see CallRecordSelector). public bool UsesCallRecords { get; set; } @@ -222,6 +226,7 @@ public sealed class ShaderResourceInfo HasBitwiseExclusiveOr = HasBitwiseExclusiveOr, UsesDeviceAddresses = UsesDeviceAddresses, UsesBindlessHeap = UsesBindlessHeap, + HeapViewCount = HeapViewCount, UsesCallRecords = UsesCallRecords, UsesCallMarks = UsesCallMarks, UsesDeviceAddressFallback = UsesDeviceAddressFallback, @@ -239,6 +244,9 @@ public sealed record IndirectImageSelector( uint KeyArgument) { public IndirectSelectorValues? SelectorValues { get; init; } + + // An inclusive upper bound the shader's own clamps prove for the selector, when one exists. + public uint? SelectorBound { get; init; } public IReadOnlyList? DirectCandidates { get; init; } public bool Dense { get; init; } public uint TableOffset { get; init; } diff --git a/src/SharpEmu.ShaderCompiler/Resources/ShaderResourcePlan.cs b/src/SharpEmu.ShaderCompiler/Resources/ShaderResourcePlan.cs index 6f7c0ccf1..b02574577 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ShaderResourcePlan.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ShaderResourcePlan.cs @@ -184,6 +184,28 @@ internal CompiledBranchTransaction? CompiledBranches public IReadOnlyList HeapRecords { get; private set; } = []; public IReadOnlyList HeapRecordSources { get; private set; } = []; + // The heap view a heap record access reads: its heap V#, descriptor kind and immediate offset. + public HeapRecordSource HeapRecordSourceOf(HeapRecordAccess record) + { + var heap = DescriptorSources[(int)record.Source].Heap!; + return new HeapRecordSource(heap.HeapSource, record.Sampler, heap.Immediate, heap.R128); + } + + // That view's number among HeapRecordSources. + public int HeapViewOf(HeapRecordAccess record) + { + var source = HeapRecordSourceOf(record); + for (var view = 0; view < HeapRecordSources.Count; view++) + { + if (HeapRecordSources[view] == source) + { + return view; + } + } + + throw new InvalidOperationException("A heap record access has no heap view."); + } + // The image accesses whose image or sampler a linked callee's call record holds, and what each callee reads through its // records' arguments besides them (by its slot among the program's call targets; empty unless linked with run-time // arguments). @@ -198,13 +220,21 @@ internal CompiledBranchTransaction? CompiledBranches // The accesses whose bindless image or sampler descriptor reads as null. public IReadOnlyList NullBindlessDescriptorPcs { get; private set; } = []; + // Planned with preferHeapRecords (see ResourceTracker.Track). + public bool PreferredHeapRecords { get; private set; } + + // An indirect image table candidate of another kind than the table's first image reads as null, as a shared + // selector's always does, instead of failing the materialization. Set once by the program cache when such a table + // cannot be read from the bindless heap; tables of one kind materialize the same either way. + public bool NullIncompatibleImageCandidates { get; set; } + public static ShaderResourcePlan Extract(Gen5ShaderProgram program, ShaderStage stage, ulong hash, uint userDataBase, uint userDataCount, IReadOnlySet? fixedFunctionVertexLoads = null, Action? beforeResourceTracking = null, uint waveSize = 64, bool bindlessNullDescriptors = false, bool bindlessHeap = false, bool callRecords = false, bool callMarks = false, int dynamicUserData = -1, BufferDescriptorNormalizer? normalizeBufferDescriptor = null, ImageDescriptorNormalizer? normalizeImageDescriptor = null, Func? imageNormalizationVersion = null, StableImageDescriptorLimits stableImageLimits = default, bool? scalarDataOnDevice = null, - bool? deviceRecordCounts = null, bool? runtimeImageSwizzles = null) + bool? deviceRecordCounts = null, bool? runtimeImageSwizzles = null, bool preferHeapRecords = false) { // Mesh system inputs are not uniform user data, even when a GS pointer occupies s0:s1. var graph = ScalarGraphDiskCache.Build(program, userDataBase, userDataCount, fixedFunctionVertexLoads, waveSize, @@ -253,16 +283,18 @@ ScalarValue RewriteRead(ScalarValue read) // Diagnostics observe rewritten values before descriptor validation. beforeResourceTracking?.Invoke(plan); - var tracked = ResourceTracker.Track(plan, bindlessNullDescriptors, bindlessHeap, callRecords); + var tracked = ResourceTracker.Track(plan, bindlessNullDescriptors, bindlessHeap, callRecords, preferHeapRecords); plan.DescriptorSources = tracked.Sources; plan.Info = tracked.Info; plan.NullBindlessDescriptorPcs = tracked.NullBindlessDescriptorPcs; + plan.PreferredHeapRecords = preferHeapRecords && bindlessHeap; plan.HeapRecords = tracked.HeapRecords; plan.CallRecords = tracked.CallRecords; plan.HeapRecordSources = tracked.HeapRecords - .Select(record => new HeapRecordSource(plan.DescriptorSources[(int)record.Source].Heap!.HeapSource, record.Sampler)) + .Select(record => plan.HeapRecordSourceOf(record)) .Distinct() .ToList(); + plan.Info.HeapViewCount = (uint)plan.HeapRecordSources.Count; if (program.Instructions.Any(instruction => instruction.Control is ShaderCallFaultControl)) plan.Info.UsesDeviceAddresses = true; // A program with shader calls, or a compute program with many device-address dwords (CompactMemoryAccessPolicy), diff --git a/src/SharpEmu.ShaderCompiler/ShaderCompileRequest.cs b/src/SharpEmu.ShaderCompiler/ShaderCompileRequest.cs index 5cf9f62f5..ddcade0e4 100644 --- a/src/SharpEmu.ShaderCompiler/ShaderCompileRequest.cs +++ b/src/SharpEmu.ShaderCompiler/ShaderCompileRequest.cs @@ -131,8 +131,9 @@ public ShaderCompileRequest(ShaderResourcePlan plan, SpecializedResourceInfo res foreach (var record in plan.HeapRecords) { var heap = plan.DescriptorSources[(int)record.Source].Heap!; + var view = plan.HeapViewOf(record); (record.Sampler ? heapSamplers : heapImages)[record.MemoryIndex] = - new HeapRecordUse(heap.KeyMemoryIndex, heap.Immediate, heap.RecordBytes); + new HeapRecordUse(heap.KeyMemoryIndex, heap.Immediate, heap.RecordBytes, view); } HeapImageByMemoryIndex = heapImages; @@ -310,6 +311,14 @@ [.. uses.Where(use => use.Callee == callee).Select(use => use.Field).Distinct() public uint ScratchDwords { get; init; } public bool EnableGraphicsSubgroupOperations { get; init; } = true; + // Graphics lane reads (DPP, DPP8, PERMLANE, V_READLANE) follow the ISA for lanes a partial host subgroup never + // launched, through a ballot and the guest EXEC mask. Off (main's lowering) unless SHARPEMU_GRAPHICS_PARTIAL_LANES=1: + // it changes every vertex and pixel shader with cross-lane operations, and was proven on Ghost of Yotei only. + public bool GraphicsPartialSubgroupLanes { get; init; } = DefaultGraphicsPartialSubgroupLanes; + + private static readonly bool DefaultGraphicsPartialSubgroupLanes = + Environment.GetEnvironmentVariable("SHARPEMU_GRAPHICS_PARTIAL_LANES") == "1"; + public bool MipStatisticsSubgroupReduction { get; init; } // The host subgroup of this stage is one guest wave32 and has arithmetic operations: wave32 MIN/MAX scans then @@ -364,6 +373,9 @@ [.. uses.Where(use => use.Callee == callee).Select(use => use.Field).Distinct() public bool SupportsClipDistance { get; init; } = true; public bool SupportsDrawParameters { get; init; } public int StartInstanceUserData { get; init; } = -1; + // The user data index an indirect draw names for its base vertex, or -1: the program then stores gl_BaseVertex there and + // counts its vertex index from it, so the draw can leave its arguments on the GPU. + public int BaseVertexUserData { get; init; } = -1; public ShaderClipSpaceTransform ClipSpace { get; init; } public MeshShaderConfiguration? Mesh { get; init; } diff --git a/tests/SharpEmu.Libs.Tests/Agc/AgcCommandBufferChainTests.cs b/tests/SharpEmu.Libs.Tests/Agc/AgcCommandBufferChainTests.cs index f3b87f954..d2cf715dc 100644 --- a/tests/SharpEmu.Libs.Tests/Agc/AgcCommandBufferChainTests.cs +++ b/tests/SharpEmu.Libs.Tests/Agc/AgcCommandBufferChainTests.cs @@ -167,6 +167,47 @@ public void AcbJump_EncodesCachePolicyAndSizeAndAlwaysChains(uint cachePolicy, u Assert.Equal(control, ReadUInt32(memory, FirstLinkAddress + 12)); } + // The ABI is (acb, cachePolicy, target, sizeDwords); the target follows the cache policy. + [Fact] + public void AcbJump_ReadsTargetAndSizeAfterTheCachePolicy() + { + var memory = new FakeCpuMemory(BaseAddress, MemorySize); + var ctx = new CpuContext(memory, Generation.Gen5); + + PointCommandBufferAt(memory, FirstLinkAddress); + ctx[CpuRegister.Rdi] = CommandBufferAddress; + ctx[CpuRegister.Rsi] = 2; + ctx[CpuRegister.Rdx] = SecondLinkAddress; + ctx[CpuRegister.Rcx] = 0x456; + + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, AgcExports.AcbJump(ctx)); + Assert.Equal(FirstLinkAddress, ctx[CpuRegister.Rax]); + Assert.Equal(unchecked((uint)SecondLinkAddress), ReadUInt32(memory, FirstLinkAddress + 4)); + Assert.Equal((uint)(SecondLinkAddress >> 32), ReadUInt32(memory, FirstLinkAddress + 8)); + var control = ReadUInt32(memory, FirstLinkAddress + 12); + Assert.Equal(2u, (control >> 28) & 0x3u); + Assert.Equal(1u, (control >> 20) & 0x1u); + Assert.Equal(0x456u, control & 0xFFFFFu); + } + + [Fact] + public void AcbJump_RejectsAnOutOfRangeCachePolicy() + { + var memory = new FakeCpuMemory(BaseAddress, MemorySize); + var ctx = new CpuContext(memory, Generation.Gen5); + + PointCommandBufferAt(memory, FirstLinkAddress); + ctx[CpuRegister.Rdi] = CommandBufferAddress; + ctx[CpuRegister.Rsi] = 4; + ctx[CpuRegister.Rdx] = SecondLinkAddress; + ctx[CpuRegister.Rcx] = 0x456; + + AgcExports.AcbJump(ctx); + + Assert.Equal(0ul, ctx[CpuRegister.Rax]); + Assert.Equal(0u, ReadUInt32(memory, FirstLinkAddress)); + } + [Fact] public void SubmittedDcb_ReturnsToParentAfterIndirectCall() { diff --git a/tests/SharpEmu.Libs.Tests/Agc/AgcCommandBufferConcurrencyTests.cs b/tests/SharpEmu.Libs.Tests/Agc/AgcCommandBufferConcurrencyTests.cs new file mode 100644 index 000000000..19b4c3a99 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Agc/AgcCommandBufferConcurrencyTests.cs @@ -0,0 +1,132 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using System.Text; +using SharpEmu.HLE; +using SharpEmu.Libs.Agc; +using Xunit; + +namespace SharpEmu.Libs.Tests.Agc; + +public sealed class AgcCommandBufferConcurrencyTests +{ + private const ulong BaseAddress = 0x1_0000_0000; + private const ulong CommandBufferAddress = BaseAddress + 0x100; + private const ulong MarkerStringAddress = BaseAddress + 0x200; + private const ulong PacketAddress = BaseAddress + 0x1000; + private const int PacketsPerThread = 1000; + private const int PacketBytes = 2 * sizeof(uint); + + // Both threads read the cursor, add their packet and store it back; without + // serialization they hand out the same address and one packet overwrites the other. + [Fact] + public void ConcurrentAppends_ToOneCommandBuffer_LoseNoPacket() + { + var memory = new FakeCpuMemory(BaseAddress, 0x10000); + var capacity = 2 * PacketsPerThread * PacketBytes; + WriteUInt64(memory, CommandBufferAddress + 0x10, PacketAddress); + WriteUInt64(memory, CommandBufferAddress + 0x18, PacketAddress + (ulong)capacity); + + using var start = new ManualResetEventSlim(); + var threads = new[] { 0x16u, 0x17u } + .Select(eventType => new Thread(() => + { + var ctx = new CpuContext(memory, Generation.Gen5); + start.Wait(); + for (var index = 0; index < PacketsPerThread; index++) + { + ctx[CpuRegister.Rdi] = CommandBufferAddress; + ctx[CpuRegister.Rsi] = eventType; + ctx[CpuRegister.Rdx] = 0; + AgcExports.DcbEventWrite(ctx); + } + })) + .ToArray(); + foreach (var thread in threads) + { + thread.Start(); + } + + start.Set(); + foreach (var thread in threads) + { + Assert.True(thread.Join(TimeSpan.FromSeconds(30))); + } + + var counts = new Dictionary(); + for (var index = 0; index < 2 * PacketsPerThread; index++) + { + var address = PacketAddress + (ulong)(index * PacketBytes); + Assert.Equal(0xC000_4600u, ReadUInt32(memory, address)); + var eventType = ReadUInt32(memory, address + 4); + counts[eventType] = counts.GetValueOrDefault(eventType) + 1; + } + + Assert.Equal(PacketsPerThread, counts[0x16]); + Assert.Equal(PacketsPerThread, counts[0x17]); + Assert.Equal(PacketAddress + (ulong)capacity, ReadUInt64(memory, CommandBufferAddress + 0x10)); + } + + [Fact] + public void PushMarker_FromAnotherWriter_DoesNotReserveSpaceInTheOwnersBuffer() + { + var memory = new FakeCpuMemory(BaseAddress, 0x10000); + WriteUInt64(memory, CommandBufferAddress + 0x10, PacketAddress); + WriteUInt64(memory, CommandBufferAddress + 0x18, PacketAddress + 0x400); + Assert.True(memory.TryWrite(MarkerStringAddress, Encoding.ASCII.GetBytes("marker\0"))); + + var owner = new CpuContext(memory, Generation.Gen5); + owner[CpuRegister.Rdi] = CommandBufferAddress; + owner[CpuRegister.Rsi] = 0x16; + owner[CpuRegister.Rdx] = 0; + AgcExports.DcbEventWrite(owner); + var cursorAfterOwner = ReadUInt64(memory, CommandBufferAddress + 0x10); + + var foreign = new CpuContext(memory, Generation.Gen5); + foreign[CpuRegister.Rdi] = CommandBufferAddress; + foreign[CpuRegister.Rsi] = MarkerStringAddress; + AgcExports.DcbPushMarker(foreign); + + Assert.Equal(0ul, foreign[CpuRegister.Rax]); + Assert.Equal(cursorAfterOwner, ReadUInt64(memory, CommandBufferAddress + 0x10)); + + // The owner's own marker is still written, and so is a marker once an ordinary + // export hands the buffer to the other writer. + owner[CpuRegister.Rdi] = CommandBufferAddress; + owner[CpuRegister.Rsi] = MarkerStringAddress; + AgcExports.DcbPushMarker(owner); + Assert.Equal(cursorAfterOwner, owner[CpuRegister.Rax]); + + foreign[CpuRegister.Rdi] = CommandBufferAddress; + foreign[CpuRegister.Rsi] = 0x17; + foreign[CpuRegister.Rdx] = 0; + AgcExports.DcbEventWrite(foreign); + Assert.NotEqual(0ul, foreign[CpuRegister.Rax]); + foreign[CpuRegister.Rdi] = CommandBufferAddress; + foreign[CpuRegister.Rsi] = MarkerStringAddress; + AgcExports.DcbPushMarker(foreign); + Assert.NotEqual(0ul, foreign[CpuRegister.Rax]); + } + + private static uint ReadUInt32(FakeCpuMemory memory, ulong address) + { + Span buffer = stackalloc byte[4]; + Assert.True(memory.TryRead(address, buffer)); + return BinaryPrimitives.ReadUInt32LittleEndian(buffer); + } + + private static ulong ReadUInt64(FakeCpuMemory memory, ulong address) + { + Span buffer = stackalloc byte[8]; + Assert.True(memory.TryRead(address, buffer)); + return BinaryPrimitives.ReadUInt64LittleEndian(buffer); + } + + private static void WriteUInt64(FakeCpuMemory memory, ulong address, ulong value) + { + Span buffer = stackalloc byte[8]; + BinaryPrimitives.WriteUInt64LittleEndian(buffer, value); + Assert.True(memory.TryWrite(address, buffer)); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Agc/Gen5VertexInstanceIdSpirvTests.cs b/tests/SharpEmu.Libs.Tests/Agc/Gen5VertexInstanceIdSpirvTests.cs index ff44abbc1..16ae33368 100644 --- a/tests/SharpEmu.Libs.Tests/Agc/Gen5VertexInstanceIdSpirvTests.cs +++ b/tests/SharpEmu.Libs.Tests/Agc/Gen5VertexInstanceIdSpirvTests.cs @@ -52,6 +52,48 @@ public void TheInstanceIdCountsFromTheDrawsBaseInstanceWhenTheDeviceExposesIt(bo loads.TryGetValue(instruction.Operands[3], out var right) && right == baseInstance); } + // A base vertex an indirect draw names in user data: the program stores gl_BaseVertex there and counts its vertex + // index from it, as the CP's base_vtx_loc write would leave them. + [Theory] + [InlineData(-1)] + [InlineData(2)] + public void TheVertexIdCountsFromTheDrawsBaseVertexWhenTheDrawNamesItsUserData(int baseVertexUserData) + { + var end = new Gen5ShaderInstruction(0, Gen5ShaderEncoding.Sopp, "SEndpgm", [], [], [], null); + var program = new Gen5ShaderProgram(0, [end]); + var plan = ShaderResourcePlan.Extract(program, ShaderStage.Vertex, 1, 8, 4); + var resources = ResourceMaterializer.ApplyTo(plan, ResourceSpecialization.Default(plan.Info)); + var layout = BindingLayout.Allocate(resources.Info, [], false, false, false, 0); + var request = new ShaderCompileRequest(plan, resources, layout) + { + SupportsDrawParameters = true, + BaseVertexUserData = baseVertexUserData, + }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + + var module = ParseModule(shader.Spirv); + var builtIns = module + .Where(instruction => instruction.Opcode == SpirvOp.Decorate && instruction.Operands.Length == 3 && + instruction.Operands[1] == (uint)SpirvDecoration.BuiltIn) + .ToDictionary(instruction => instruction.Operands[2], instruction => instruction.Operands[0]); + if (baseVertexUserData < 0) + { + Assert.False(builtIns.ContainsKey((uint)SpirvBuiltIn.BaseVertex)); + return; + } + + var loads = module.Where(instruction => instruction.Opcode == SpirvOp.Load).ToDictionary(instruction => instruction.Operands[1], instruction => instruction.Operands[2]); + var vertexIndex = builtIns[(uint)SpirvBuiltIn.VertexIndex]; + var baseVertex = builtIns[(uint)SpirvBuiltIn.BaseVertex]; + Assert.Equal(1, loads.Values.Count(pointer => pointer == baseVertex)); + Assert.Contains(module, instruction => instruction.Opcode == SpirvOp.ISub && + loads.TryGetValue(instruction.Operands[2], out var left) && left == vertexIndex && + loads.TryGetValue(instruction.Operands[3], out var right) && right == baseVertex); + // The loaded base vertex is stored once more: into the user data register. + var baseVertexValue = loads.Single(load => load.Value == baseVertex).Key; + Assert.Contains(module, instruction => instruction.Opcode == SpirvOp.Store && instruction.Operands[1] == baseVertexValue); + } + private static IReadOnlyList ParseModule(byte[] spirv) { var instructions = new List(); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Buffers/CacheHarness.cs b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/CacheHarness.cs index b1f30477d..0a40f2e53 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Buffers/CacheHarness.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Buffers/CacheHarness.cs @@ -202,6 +202,22 @@ public ulong MapBacked(ulong size, GuestPageProtection protection) return address; } + // A held range whose first `backed` bytes are mapped and registered; the rest stays a bare hole, + // as a streamed texture maps only the resident start of its chain. + public ulong MapBackedPrefix(ulong size, ulong backed) + { + var hole = HostViewTestSupport.AlignUp(size, _views.Granularity); + backed = HostViewTestSupport.AlignUp(backed, _views.Granularity); + Assert.True(backed < hole); + Assert.True(Memory.TryHoldRangeAtOrAbove(GuestBase, hole, _views.Granularity, out var address)); + Assert.True(Memory.TryMapBacked(address, backed, _nextBackingOffset, GuestPageProtection.Read | GuestPageProtection.Write, out _)); + _nextBackingOffset += hole; + Gpu.Register(address, backed, GuestPageProtection.Read | GuestPageProtection.Write); + return address; + } + + public ulong Granularity => _views.Granularity; + // Two backed granules around one that stays a bare hole: registered, but without backing. public (ulong First, ulong Granule, ulong Last) MapBackedSandwich() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/GpuCommandInterpreterDrawTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/GpuCommandInterpreterDrawTests.cs index b3e2cd0e8..fe23f8d03 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/GpuCommandInterpreterDrawTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/GpuCommandInterpreterDrawTests.cs @@ -99,14 +99,21 @@ public void DrawAuto_NativeWrappedAndMultiAuto() Assert.Contains("auto draw flags", runner.RunExpectingFatal(StreamRunner.Packet(PacketOpcode.DrawIndexAuto, 1, 0x1)).Message); } - [Fact] - public void IndirectDraws_ReadArgumentsFromMemoryAndKeepTheInstanceCount() + [Theory] + // By default a record read on the CPU passes its instance count on, as hardware CP indirect draws do. + [InlineData(null, 2u)] + [InlineData("1", 2u)] + // SHARPEMU_INDIRECT_INSTANCE_INHERIT=0: the direct draw after them keeps the explicit NUM_INSTANCES. + [InlineData("0", 4u)] + public void IndirectDraws_ReadArgumentsFromMemoryAndPassTheInstanceCountOn(string? mode, uint laterInstances) { var runner = new StreamRunner(); + runner.Interpreter.IndirectInstanceInherit = GpuCommandInterpreter.ParseIndirectInstanceInheritance(mode); runner.Host.WriteWords(Arguments, new uint[] { 9, 3, 1, 2 }); runner.Host.WriteWords(Arguments + 16, new uint[] { 50, 2, 4, 7, 1 }); runner.Run( + StreamRunner.Packet(PacketOpcode.NumInstances, 4), SetBase(Arguments, dispatch: false), StreamRunner.Packet(PacketOpcode.IndexBase, StreamRunner.Low(Indices), StreamRunner.High(Indices)), StreamRunner.Packet(PacketOpcode.IndexType, 0), @@ -121,7 +128,8 @@ public void IndirectDraws_ReadArgumentsFromMemoryAndKeepTheInstanceCount() Assert.Equal(40u, indexed.IndexCount); Assert.Equal(Indices + 8, indexed.IndexAddress); Assert.Equal(7, indexed.BaseVertex); - Assert.Equal(2u, runner.Host.AutoDraws[1].InstanceCount); + Assert.Equal(2u, indexed.InstanceCount); + Assert.Equal(laterInstances, runner.Host.AutoDraws[1].InstanceCount); Assert.Contains("initiator is not supported", runner.RunExpectingFatal(StreamRunner.Packet(PacketOpcode.DrawIndirect, 0, 0, 0, 3)).Message); Assert.Contains("arguments base is zero", new StreamRunner().RunExpectingFatal(StreamRunner.Packet(PacketOpcode.DrawIndirect, 0, 0, 0, 2)).Message); @@ -245,9 +253,10 @@ public void IndexedIndirectDraws_LeaveArgumentsOnTheGpuWhenTheHostCan() (indexed.IndexCount, indexed.IndexAddress, indexed.IndirectArgumentsAddress, indexed.OffsetSource)); Assert.DoesNotContain(runner.Host.GuestReads, address => address >= Arguments + 16 && address < Arguments + 36); - // A later draw that inherits the instance count reads it then. + // By default a later direct draw does not read a record resolved on the GPU and keeps its instance count. runner.Run(StreamRunner.Packet(PacketOpcode.DrawIndexAuto, 5, 0)); - Assert.Equal(2u, runner.Host.AutoDraws[0].InstanceCount); + Assert.Equal(1u, runner.Host.AutoDraws[0].InstanceCount); + Assert.DoesNotContain(runner.Host.GuestReads, address => address >= Arguments + 16 && address < Arguments + 36); // 8-bit indices are expanded on the CPU, so their counts are read at once. runner.Run( @@ -273,11 +282,51 @@ public void AutoIndirectDraws_LeaveArgumentsOnTheGpuWhenTheHostCan() Assert.Equal((Arguments, DrawOffsetSource.IndirectArguments), (auto.IndirectArgumentsAddress, auto.OffsetSource)); Assert.DoesNotContain(runner.Host.GuestReads, address => address >= Arguments && address < Arguments + 16); - // A later draw that inherits the instance count reads it then. + // By default a later direct draw does not read the record and keeps its instance count. + runner.Run(StreamRunner.Packet(PacketOpcode.DrawIndexAuto, 5, 0)); + Assert.Equal(1u, runner.Host.AutoDraws[1].InstanceCount); + } + + // SHARPEMU_INDIRECT_INSTANCE_INHERIT=1: a later draw inherits the count of a record resolved on the GPU, read from + // the record only then. + [Fact] + public void IndirectInstanceInherit_PassesTheGpuRecordCountToLaterDraws() + { + var runner = new StreamRunner(); + runner.Interpreter.IndirectInstanceInherit = GpuCommandInterpreter.IndirectInstanceInheritance.All; + runner.Host.ResolvesIndirectDrawOnGpu = true; + runner.Host.WriteWords(Arguments, new uint[] { 9, 3, 1, 2 }); + + runner.Run( + SetBase(Arguments, dispatch: false), + StreamRunner.Packet(PacketOpcode.DrawIndirect, 0, 0x280, 0, 2)); + Assert.DoesNotContain(runner.Host.GuestReads, address => address >= Arguments && address < Arguments + 16); + runner.Run(StreamRunner.Packet(PacketOpcode.DrawIndexAuto, 5, 0)); Assert.Equal(3u, runner.Host.AutoDraws[1].InstanceCount); } + // A record read on the CPU with no instances draws nothing, rather than NUM_INSTANCES instances. + [Fact] + public void IndirectDraws_WithZeroInstancesDrawNothing() + { + var runner = new StreamRunner(); + runner.Host.WriteWords(Arguments, new uint[] { 9, 0, 1, 2 }); + runner.Host.WriteWords(Arguments + 16, new uint[] { 50, 0, 4, 7, 1 }); + + runner.Run( + StreamRunner.Packet(PacketOpcode.NumInstances, 4), + SetBase(Arguments, dispatch: false), + StreamRunner.Packet(PacketOpcode.IndexBase, StreamRunner.Low(Indices), StreamRunner.High(Indices)), + StreamRunner.Packet(PacketOpcode.IndexType, 0), + StreamRunner.Packet(PacketOpcode.IndexBufferSize, 40), + StreamRunner.Packet(PacketOpcode.DrawIndirect, 0, 0, 0, 2), + StreamRunner.Packet(PacketOpcode.DrawIndexIndirect, 16, 0, 0, 0x22)); + + Assert.Empty(runner.Host.AutoDraws); + Assert.Empty(runner.Host.IndexedDraws); + } + [Fact] public void UnsizedIndexedIndirectDraws_LearnTheIndexRangeBeforeUsingTheGpu() { @@ -319,12 +368,12 @@ public void IndirectMulti_LoopsOverTheStrideAndTheCountAddress() Assert.Contains("stride is smaller", runner.RunExpectingFatal(StreamRunner.Packet(PacketOpcode.DrawIndirectMulti, 0, 0, 0, 0, 1, 0, 0, 8, 2)).Message); } - // A start instance in one of the vertex program's live user data registers stays the draw's first instance: the draw - // names that user data (the program stores its base instance there), the register is not written, and the host can - // keep the arguments on the GPU. A named base vertex still reads the arguments here, and a start instance in a - // register the program does not load is written as the CP would. + // A base vertex or start instance in one of the vertex program's live user data registers stays in the arguments: the + // draw names that user data (the program stores gl_BaseVertex or gl_BaseInstance there), the register is not written, + // and the host can keep the arguments on the GPU, where a shader may have written them. A value named in a register + // the program does not load is written as the CP would, so those draws read their arguments here. [Fact] - public void IndirectDraws_NameTheLiveUserRegisterOfTheirStartInstance() + public void IndirectDraws_NameTheLiveUserRegistersOfTheirBaseVertexAndStartInstance() { var runner = new StreamRunner(); runner.Host.ResolvesIndirectDrawOnGpu = true; @@ -341,24 +390,51 @@ public void IndirectDraws_NameTheLiveUserRegisterOfTheirStartInstance() StreamRunner.Packet(PacketOpcode.DrawIndirect, 0, gs0 + 3, gs0, 2), StreamRunner.Packet(PacketOpcode.DrawIndexIndirect, 16, 0x280, gs0 + 2, 0x22), StreamRunner.Packet(PacketOpcode.DrawIndexIndirect, 16, 0x280, gs0 + 9, 0x22), + StreamRunner.Packet(PacketOpcode.DrawIndirect, 0, gs0 + 9, 0x280, 2), StreamRunner.Packet(PacketOpcode.IndexType, 2), - StreamRunner.Packet(PacketOpcode.DrawIndexIndirect, 16, 0x280, gs0 + 1, 0x22)); - - var auto = Assert.Single(runner.Host.AutoDraws); - Assert.Equal((0ul, 0u, true), (auto.IndirectArgumentsAddress, auto.FirstVertex, auto.FirstVertexInRegister)); - Assert.Equal((2u, false, 0), (auto.FirstInstance, auto.FirstInstanceInRegister, auto.StartInstanceUserData)); + StreamRunner.Packet(PacketOpcode.DrawIndexIndirect, 16, gs0 + 3, gs0 + 1, 0x22)); + + Assert.Equal(2, runner.Host.AutoDraws.Count); + var gpu = runner.Host.AutoDraws[0]; + Assert.Equal((Arguments, false, 3), (gpu.IndirectArgumentsAddress, gpu.FirstVertexInRegister, gpu.BaseVertexUserData)); + Assert.Equal((false, 0), (gpu.FirstInstanceInRegister, gpu.StartInstanceUserData)); + // A base vertex in a register the program does not load: the arguments are read and the register written. + var written = runner.Host.AutoDraws[1]; + Assert.Equal((0ul, 0u, true, -1), (written.IndirectArgumentsAddress, written.FirstVertex, written.FirstVertexInRegister, written.BaseVertexUserData)); Assert.Equal(3, runner.Host.IndexedDraws.Count); var indexed = runner.Host.IndexedDraws; Assert.Equal((Arguments + 16, 0u, false, 2), (indexed[0].IndirectArgumentsAddress, indexed[0].FirstInstance, indexed[0].FirstInstanceInRegister, indexed[0].StartInstanceUserData)); Assert.Equal((0ul, 0u, true, -1), (indexed[1].IndirectArgumentsAddress, indexed[1].FirstInstance, indexed[1].FirstInstanceInRegister, indexed[1].StartInstanceUserData)); - // Byte indices have no GPU index range, so the arguments are read; the start instance still goes to the draw. + // Byte indices have no GPU index range, so the arguments are read; the base vertex and start instance still go to + // the draw, which names their user data. Assert.Equal((0ul, 1u, false, 1), (indexed[2].IndirectArgumentsAddress, indexed[2].FirstInstance, indexed[2].FirstInstanceInRegister, indexed[2].StartInstanceUserData)); + Assert.Equal((7, false, 3), (indexed[2].BaseVertex, indexed[2].BaseVertexInRegister, indexed[2].BaseVertexUserData)); var shader = runner.Interpreter.Registers.Shader; - Assert.False(shader.ContainsKey(gs0) || shader.ContainsKey(gs0 + 1) || shader.ContainsKey(gs0 + 2)); - Assert.Equal((1u, 1u), (shader[gs0 + 3], shader[gs0 + 9])); + Assert.False(shader.ContainsKey(gs0) || shader.ContainsKey(gs0 + 1) || shader.ContainsKey(gs0 + 2) || shader.ContainsKey(gs0 + 3)); + Assert.Equal(1u, shader[gs0 + 9]); + } + + // A tessellation or mesh stage reads the base vertex from its register, so a draw with one still writes it. + [Fact] + public void ATessellatedIndirectDraw_WritesTheBaseVertexRegisterInItsUserData() + { + var runner = new StreamRunner(); + runner.Host.ResolvesIndirectDrawOnGpu = true; + runner.Host.WriteWords(Arguments, new uint[] { 9, 3, 1, 2 }); + const uint gs0 = ShaderRegisterOffset.SpiShaderUserDataGs0; + + runner.Run( + StreamRunner.Packet(PacketOpcode.SetShaderRegister, ShaderRegisterOffset.SpiShaderPgmRsrc2Gs, 4u << 1), + StreamRunner.Packet(PacketOpcode.SetContextRegister, ContextRegisterOffset.VgtShaderStagesEn, 0x5), + SetBase(Arguments, dispatch: false), + StreamRunner.Packet(PacketOpcode.DrawIndirect, 0, gs0 + 3, 0x280, 2)); + + var auto = Assert.Single(runner.Host.AutoDraws); + Assert.Equal((0ul, true, -1), (auto.IndirectArgumentsAddress, auto.FirstVertexInRegister, auto.BaseVertexUserData)); + Assert.Equal(1u, runner.Interpreter.Registers.Shader[gs0 + 3]); } [Fact] diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/GpuTilerTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/GpuTilerTests.cs index 36371dfd4..6a97c4430 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Images/GpuTilerTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/GpuTilerTests.cs @@ -249,6 +249,38 @@ public void DetileAndTile_MatchTheCpuTwinAndInvertEachOther() harness.AssertNoValidationMessages(); } + // A 4 KiB tiled view may start half a block into an allocation (a T# is only 256-byte aligned); + // the swizzle is relative to the view base, so the bytes match the aligned CPU twin. + [Fact] + public void Standard4KB_TilesAndDetilesAtAnOffsetInsideTheBuffer() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new ImageTestHarness(_vulkan); + const ulong viewOffset = 0x800; + var tilerCase = TilerCases.Create(TileBlockKind.Standard4KB, 8, TilerCases.Shape.Blocks, 123)!; + var transfer = tilerCase.Transfer with { TiledOffset = viewOffset }; + var capacity = viewOffset + transfer.TiledSize; + var linear = harness.Upload(tilerCase.Linear); + var tiled = harness.CreateDeviceLocalBuffer(capacity); + harness.Run(() => + { + tiled.Fill(0, tiled.Size, 0); + harness.Tiler.Tile(linear.Handle, 0, linear.Size, tiled.Handle, 0, capacity, [transfer]); + }); + + var all = harness.ReadBack(tiled.Handle, 0, capacity); + Assert.True(all.AsSpan(0, (int)viewOffset).IndexOfAnyExcept((byte)0) < 0); + Assert.True(all.AsSpan((int)viewOffset).SequenceEqual(tilerCase.Tiled)); + + var detiled = harness.Run(() => harness.Tiler.Detile(tiled.Handle, 0, capacity, transfer.LinearSize, [transfer])); + var actual = harness.ReadBack(detiled.Buffer, detiled.Offset, transfer.LinearSize); + var expected = tilerCase.Linear.ToArray(); + MaskPadding(actual, transfer); + MaskPadding(expected, transfer); + Assert.Equal(expected, actual); + harness.AssertNoValidationMessages(); + } + // Bytes between the row width and the pitch are never transferred. private static void MaskPadding(byte[] bytes, in TileTransfer transfer) { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.HeapHold.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.HeapHold.cs index a837d98d0..f8180856b 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.HeapHold.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.HeapHold.cs @@ -11,6 +11,24 @@ namespace SharpEmu.Libs.Tests.Gpu.Images; public sealed partial class GuestImageCacheTests { + // A heap record can name a texture the guest has unloaded (a table it no longer reads keeps the T#): the heap asks + // whether the texels could be read before it finds the record's image, since an image of unmapped memory cannot + // be populated. A streamed texture maps only a prefix of its range, which is enough. + [Fact] + public void AnImageRangeIsBackedWhenItsFirstPageIsMapped() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var address = harness.MapBacked(65536, ReadWrite); + + Assert.True(harness.Images.IsBackedImageRange(new SharpEmu.HLE.GpuMemory.GuestSpan(address, 4096))); + Assert.True(harness.Images.IsBackedImageRange(new SharpEmu.HLE.GpuMemory.GuestSpan(address, 4 * 65536))); + Assert.False(harness.Images.IsBackedImageRange(new SharpEmu.HLE.GpuMemory.GuestSpan(address + 16 * 65536, 4096))); + Assert.False(harness.Images.IsBackedImageRange(new SharpEmu.HLE.GpuMemory.GuestSpan(0, 0))); + Assert.False(harness.Images.IsBackedImageRange(new SharpEmu.HLE.GpuMemory.GuestSpan(0x0000_2045_2881_9A00, 0x1000))); + harness.Shutdown(); + } + // An image deleted while the bindless heap names its view keeps its memory through completed ticks and is freed // after the tick in which the heap lets go of it; an image the heap does not name is freed after its tick. [Fact] diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.Metadata.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.Metadata.cs index c796df87a..1847896df 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.Metadata.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.Metadata.cs @@ -268,8 +268,12 @@ public void HtileEntries_ReportRegisteredAndClearedState() Assert.True(harness.Images.IsMetadataCleared(entries[2], 0, out var fill)); Assert.Equal(0xffffffffu, fill); Assert.False(harness.Images.IsMetadataCleared(entries[0], 0)); - Assert.False(harness.Images.IsMetadataCleared(entries[2], 32)); - Assert.False(harness.Images.SetMetadataSlice(entries[2], 32, true)); + // HTile tracks slices past 31 too (a depth array of more than 32 layers). + Assert.True(harness.Images.IsMetadataCleared(entries[2], 35)); + Assert.False(harness.Images.IsMetadataCleared(entries[0], 35)); + Assert.True(harness.Images.SetMetadataSlice(entries[2], 35, false)); + Assert.False(harness.Images.IsMetadataCleared(entries[2], 35)); + Assert.True(harness.Images.IsMetadataCleared(entries[2], 34)); Assert.False(harness.Images.IsMetadata(address + 0x3000)); Assert.False(harness.Images.ClearMetadata(address + 0x3000)); harness.Shutdown(); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.PartlyMapped.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.PartlyMapped.cs new file mode 100644 index 000000000..dac5c1008 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.PartlyMapped.cs @@ -0,0 +1,101 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.Libs.Tests.Gpu.Buffers; +using Silk.NET.Vulkan; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Images; + +// The shape of the Ghost of Yotei loading failure: a streamed texture's range is mapped at its start +// only (the resident levels) and its last bytes are unmapped. The upload reads the bytes of the levels +// the image holds and nothing else; it never invents the bytes of a level the image holds. +public sealed partial class GuestImageCacheTests +{ + private static (ulong Address, ulong Resident, byte[] Fill) MapStreamedPrefix(CacheHarness harness, byte value) + { + var layout = StreamedTexture(0x1_0000_0000, 1).Description; + // The tiled chain keeps level 0 at its end: everything before it is the resident prefix. + Assert.True(layout.MipLayout[0].Offset > layout.MipLayout[1].Offset); + var resident = layout.MipLayout[0].Offset / harness.Granularity * harness.Granularity; + Assert.True(resident >= layout.MipLayout[1].Offset + layout.MipLayout[1].Size); + var address = harness.MapBackedPrefix(layout.Data.Size, resident); + var fill = new byte[resident]; + Array.Fill(fill, value); + harness.Write(address, fill); + return (address, resident, fill); + } + + // Names no resident-level API, so it also runs against a cache that reads the whole chain, where + // the unmapped tail fails the upload. + [Fact] + public void PartlyMappedStreamedTexture_UploadsItsMappedLevels() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var (address, _, _) = MapStreamedPrefix(harness, 0x5A); + + var request = StreamedTexture(address, 1); + var identifier = harness.Acquire(ref request); + + // Every mapped byte is one value, so the first host level reads it whatever the tiling. + Assert.All(harness.ReadImageBytes(harness.Images.Owner(identifier)!), value => Assert.Equal(0x5A, value)); + } + + [Fact] + public void StreamedTexture_HoldsOnlyItsResidentLevels() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var (address, _, _) = MapStreamedPrefix(harness, 0x5A); + + var request = StreamedTexture(address, 1); + var identifier = harness.Acquire(ref request); + var image = harness.Images.Owner(identifier)!; + + Assert.Equal(1u, image.Description.FirstLevel); + Assert.Equal(new Extent3D(StreamedSize / 2, StreamedSize / 2, 1), image.Backing.Extent); + Assert.Equal(StreamedLevels - 1, image.Backing.MipLevels); + Assert.Equal(0u, request.View.BaseLevel); + // A quarter of the chain's level 0 alone: the unmapped level 0 has no host memory. + Assert.True(image.AccountedSize < (ulong)StreamedSize * StreamedSize * 4 / 2); + // The image reads the bytes that hold its levels, not the unmapped end of the range. + Assert.True(image.GuestReadSize < image.Description.Data.Size); + Assert.Equal(0x5A, harness.ReadImageBytes(image)[0]); + Assert.All(harness.ReadImageBytes(image), value => Assert.Equal(0x5A, value)); + } + + // The image hashes the head and tail of the guest bytes it reads; the unmapped end of the range + // is not among them. + [Fact] + public void StreamedTexture_HashesOnlyTheGuestBytesItReads() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var (address, _, _) = MapStreamedPrefix(harness, 0x5A); + + var request = StreamedTexture(address, 1); + var image = harness.Images.Owner(harness.Acquire(ref request))!; + + _ = image.HashGuestEdges(); + } + + // A byte of a level the image holds is never invented as zero: when the mapping stops inside the + // held levels the upload fails as it always has. + [Fact] + public void StreamedTexture_AnUnmappedByteOfAHeldLevelFailsTheUpload() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var fatal = new FatalScope(); + using var harness = new CacheHarness(_vulkan); + var layout = StreamedTexture(0x1_0000_0000, 1).Description; + var held = layout.MipLayout[1].Offset + layout.MipLayout[1].Size; + Assert.True(held > harness.Granularity); + var address = harness.MapBackedPrefix(layout.Data.Size, harness.Granularity); + + var request = StreamedTexture(address, 1); + Assert.ThrowsAny(() => harness.Acquire(ref request)); + Assert.Contains(fatal.Messages, message => message.Contains("Could not read the mapped guest image backing", StringComparison.Ordinal)); + } +} \ No newline at end of file diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.ResidentLevels.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.ResidentLevels.cs new file mode 100644 index 000000000..4b9e65c23 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestImageCacheTests.ResidentLevels.cs @@ -0,0 +1,94 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Images; +using SharpEmu.Libs.Tests.Gpu.Buffers; +using SharpEmu.ShaderCompiler.Resources; +using Silk.NET.Vulkan; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Images.ImageCacheTestSupport; + +namespace SharpEmu.Libs.Tests.Gpu.Images; + +// A streamed texture maps only the resident start of its tiled chain (the small levels; level 0 is +// last) and its descriptor starts at the first resident level. Its image holds only those levels. +public sealed partial class GuestImageCacheTests +{ + private const uint StreamedSize = 512; + private const uint StreamedLevels = 10; + + private static readonly ShaderImageShape StreamedShape = new(false, false, false, false, TextureNumericClass.Float); + + private static ImageRequest StreamedTexture(ulong address, uint baseLevel) => + ImageRequestBuilders.Texture( + RegisterWords.Texture(address, GuestPixelFormat.Bits8_8_8_8UNorm, StreamedSize, StreamedSize, tile: GuestTileMode.Standard64KB, + baseLevel: baseLevel, lastLevel: StreamedLevels - 1, maxMip: StreamedLevels - 1), + StreamedShape).Request; + + // The image counts the memory of its resident levels only, not of the unmapped chain before them. + [Fact] + public void StreamedTexture_AccountsOnlyItsResidentLevels() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var layout = StreamedTexture(0x1_0000_0000, 1).Description; + var resident = layout.MipLayout[0].Offset / harness.Granularity * harness.Granularity; + var address = harness.MapBackedPrefix(layout.Data.Size, resident); + + var request = StreamedTexture(address, 1); + var image = harness.Images.Owner(harness.Find(ref request))!; + + Assert.Equal(1u, image.Description.FirstLevel); + // Less than the chain's level 0 alone, which is not mapped. + Assert.True(image.AccountedSize < (ulong)StreamedSize * StreamedSize * 4 / 2); + Assert.True(image.AccountedSize >= layout.MipLayout[1].Size); + } + + // When the whole chain is mapped (or another image holds it), the request for resident levels + // is a view of the chain's image from the descriptor's base level, not a second image. + [Fact] + public void StreamedTexture_ViewsTheWholeChainWhenItIsMapped() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var size = StreamedTexture(0x1_0000_0000, 0).Description.Data.Size; + var address = harness.MapBacked(size, ReadWrite); + + var whole = StreamedTexture(address, 0); + var wholeIdentifier = harness.Find(ref whole); + var streamed = StreamedTexture(address, 2); + Assert.Equal(2u, streamed.Description.FirstLevel); + var streamedIdentifier = harness.Find(ref streamed); + + Assert.Equal(wholeIdentifier, streamedIdentifier); + Assert.Equal(0u, harness.Images.Owner(streamedIdentifier)!.Description.FirstLevel); + Assert.Equal(2u, streamed.View.BaseLevel); + Assert.Equal(StreamedLevels - 2, streamed.View.LevelCount); + } + + // A texture whose resident image starts later than a new request is replaced by one holding + // the requested levels; an earlier-starting one serves the later request through a view. + [Fact] + public void StreamedTexture_LoadingMoreLevelsReplacesTheImage() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + using var harness = new CacheHarness(_vulkan); + var layout = StreamedTexture(0x1_0000_0000, 1).Description; + var resident = layout.MipLayout[0].Offset / harness.Granularity * harness.Granularity; + var address = harness.MapBackedPrefix(layout.Data.Size, resident); + + var coarse = StreamedTexture(address, 3); + var coarseIdentifier = harness.Find(ref coarse); + Assert.Equal(3u, harness.Images.Owner(coarseIdentifier)!.Description.FirstLevel); + + var finer = StreamedTexture(address, 1); + var finerIdentifier = harness.Find(ref finer); + Assert.NotEqual(coarseIdentifier, finerIdentifier); + Assert.False(harness.Images.Contains(coarseIdentifier)); + Assert.Equal(1u, harness.Images.Owner(finerIdentifier)!.Description.FirstLevel); + + var coarseAgain = StreamedTexture(address, 3); + Assert.Equal(finerIdentifier, harness.Find(ref coarseAgain)); + Assert.Equal(2u, coarseAgain.View.BaseLevel); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestPixelFormatsTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestPixelFormatsTests.cs index 4e540e32f..99c6eefc5 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestPixelFormatsTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/GuestPixelFormatsTests.cs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: GPL-2.0-or-later using SharpEmu.Libs.Gpu.Images; +using SharpEmu.ShaderCompiler.Resources; using Silk.NET.Vulkan; using Xunit; @@ -15,7 +16,7 @@ public void ElementSizes_ComeFromTheFormatTable() Assert.Equal(4u, GuestPixelFormats.BytesPerElement(GuestPixelFormat.Bits8_8_8_8UNorm)); Assert.Equal(8u, GuestPixelFormats.BytesPerElement(GuestPixelFormat.Bits16_16_16_16Float)); Assert.Equal(2u, GuestPixelFormats.BytesPerElement(GuestPixelFormat.Bits8_8UScaled)); - Assert.Equal(0u, GuestPixelFormats.BytesPerElement(GuestPixelFormat.Bits8SNorm)); + Assert.Equal(1u, GuestPixelFormats.BytesPerElement(GuestPixelFormat.Bits8SNorm)); Assert.Equal(0u, GuestPixelFormats.BytesPerElement(GuestPixelFormat.Invalid)); Assert.Equal(0u, GuestPixelFormats.BytesPerElement((GuestPixelFormat)200)); Assert.Equal(0u, GuestPixelFormats.BytesPerElement((GuestPixelFormat)0xFFFF_FFFF)); @@ -37,7 +38,8 @@ public void Classes_AndRemaps_FollowTheReferenceRules() Assert.Equal(TextureNumericClass.Sint, GuestPixelFormats.SampledNumericClass(GuestPixelFormat.Bits8_8_8_8SInt)); Assert.Equal(TextureNumericClass.Float, GuestPixelFormats.SampledNumericClass(GuestPixelFormat.Bits8_8_8_8UNorm)); Assert.Equal(TextureNumericClass.Float, GuestPixelFormats.SampledNumericClass(GuestPixelFormat.Bits8_8UScaled)); - Assert.Equal(TextureNumericClass.Unsupported, GuestPixelFormats.SampledNumericClass(GuestPixelFormat.Bits8SNorm)); + Assert.Equal(TextureNumericClass.Float, GuestPixelFormats.SampledNumericClass(GuestPixelFormat.Bits8SNorm)); + Assert.Equal(Format.R8SNorm, GuestPixelFormats.HostFormat(GuestPixelFormat.Bits8SNorm)); Assert.Equal(GuestPixelFormat.Bits32UInt, GuestPixelFormats.RemapTextureFormat(GuestPixelFormat.Bits11_11_10UInt)); Assert.Equal(GuestPixelFormat.Bc7Srgb, GuestPixelFormats.RemapTextureFormat(GuestPixelFormat.Bc7Srgb)); Assert.Equal(Format.R8G8B8A8Unorm, GuestPixelFormats.HostFormat(GuestPixelFormat.Bits8_8_8_8UNorm)); @@ -49,6 +51,18 @@ public void Classes_AndRemaps_FollowTheReferenceRules() Assert.Equal(Format.Undefined, GuestPixelFormats.HostFormat((GuestPixelFormat)0xFFFF_FFFF)); } + // An 8-bit signed integer texture is sampled like the 16-bit and 32-bit ones: foliage passes load + // a 128x128 map of this format, which had no host format and read as null. + [Fact] + public void AnEightBitSignedIntegerTextureIsSampledAsSigned() + { + Assert.Equal(TextureNumericClass.Sint, GuestPixelFormats.SampledNumericClass(GuestPixelFormat.Bits8SInt)); + Assert.Equal(Format.R8Sint, GuestPixelFormats.HostFormat(GuestPixelFormat.Bits8SInt)); + Assert.Equal(1u, GuestPixelFormats.BytesPerElement(GuestPixelFormat.Bits8SInt)); + Assert.Equal(1u, GuestPixelFormats.RenderTargetBytesPerElement(GuestPixelFormat.Bits8SInt)); + Assert.Equal(ImageNumericClass.Sint, GuestImageFormat.SampledNumericClass((uint)GuestPixelFormat.Bits8SInt)); + } + [Fact] public void ComponentMaps_ComposeAndMask() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/ImageRequestBuildersTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/ImageRequestBuildersTests.cs index 4cbab3a91..ba6b7b157 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Images/ImageRequestBuildersTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/ImageRequestBuildersTests.cs @@ -364,17 +364,76 @@ public void Texture_LinearTwoDimensionalFromDescriptor() Assert.Equal(ImageRequestBuilders.DestinationSwizzle(new TextureDescriptorWords(words)), resolution.Swizzle); } + // A T# addresses memory in 256-byte units, so a view may start inside a larger allocation at an + // offset smaller than the layout alignment; the tiled offsets stay relative to that base. + [Theory] + [InlineData(0x5032B23800UL)] + [InlineData(0x5032B23100UL)] + [InlineData(0x5032B23000UL)] + public void Texture_Tiled4KBAcceptsAnyDescriptorAddress(ulong address) + { + var words = RegisterWords.Texture(address, GuestPixelFormat.Bits16_16_16_16Float, 32, 16, + GuestImageType.Color2D, GuestTileMode.Standard4KB); + + var description = ImageRequestBuilders.Texture(words, Sampled2D).Request.Description; + + Assert.Equal(address, description.Data.Address); + Assert.Equal(0x1000UL, description.Data.Size); + Assert.Equal(GuestTileMode.Standard4KB, description.TileMode); + Assert.Equal(0UL, description.MipLayout[0].Offset); + } + [Fact] public void Texture_MipWindowFollowsTheDescriptor() { var words = RegisterWords.Texture(Base, GuestPixelFormat.Bits8_8_8_8UNorm, 64, 64, baseLevel: 1, lastLevel: 2, maxMip: 2); var request = ImageRequestBuilders.Texture(words, Sampled2D).Request; - Assert.Equal(3u, request.Description.Resources.Levels); + // The image holds the levels from the descriptor's base; the layout still describes the chain. + Assert.Equal(1u, request.Description.FirstLevel); + Assert.Equal(2u, request.Description.Resources.Levels); Assert.True(request.Description.MipLayout[2].Size > 0); Assert.NotEqual(request.Description.MipLayout[1].Offset, request.Description.MipLayout[2].Offset); - Assert.Equal(1u, request.View.BaseLevel); + Assert.Equal(0u, request.View.BaseLevel); Assert.Equal(2u, request.View.LevelCount); + + var whole = ImageRequestBuilders.WithWholeMipChain(request); + Assert.Equal(0u, whole.Description.FirstLevel); + Assert.Equal(3u, whole.Description.Resources.Levels); + Assert.Equal(1u, whole.View.BaseLevel); + Assert.Equal(2u, whole.View.LevelCount); + } + + // A streamed 2048x2048 BC7 chain whose descriptor starts at mip 3 (as Ghost of Yotei's village + // textures are sampled) is a 256x256 image of nine levels, not the twelve-level chain. + [Fact] + public void Texture_StreamedChainHoldsOnlyItsResidentLevels() + { + var words = RegisterWords.Texture(Base, GuestPixelFormat.Bc7UNorm, 2048, 2048, tile: GuestTileMode.Standard4KB, + baseLevel: 3, lastLevel: 11, maxMip: 11); + var request = ImageRequestBuilders.Texture(words, Sampled2D).Request; + + Assert.Equal(3u, request.Description.FirstLevel); + Assert.Equal(new SubresourceCount(9, 1), request.Description.Resources); + Assert.Equal(new Extent3D(256, 256, 1), request.Description.HostExtent); + Assert.Equal(new Extent3D(2048, 2048, 1), request.Description.Extent); + Assert.Equal(0u, request.View.BaseLevel); + Assert.Equal(9u, request.View.LevelCount); + } + + // Storage, volume and level-0 views keep the whole chain: they write or address every level. + [Fact] + public void Texture_StorageAndBaseLevelZeroKeepTheWholeChain() + { + var words = RegisterWords.Texture(Base, GuestPixelFormat.Bits8_8_8_8UNorm, 64, 64, baseLevel: 1, lastLevel: 2, maxMip: 2); + var storage = ImageRequestBuilders.Texture(words, Sampled2D with { Storage = true }).Request; + Assert.Equal(0u, storage.Description.FirstLevel); + Assert.Equal(3u, storage.Description.Resources.Levels); + + var level0 = ImageRequestBuilders.Texture( + RegisterWords.Texture(Base, GuestPixelFormat.Bits8_8_8_8UNorm, 64, 64, lastLevel: 2, maxMip: 2), Sampled2D).Request; + Assert.Equal(0u, level0.Description.FirstLevel); + Assert.Equal(3u, level0.Description.Resources.Levels); } [Fact] diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/ResidentImageBackingTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/ResidentImageBackingTests.cs new file mode 100644 index 000000000..b8a86037d --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/ResidentImageBackingTests.cs @@ -0,0 +1,120 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using SharpEmu.HLE.Host; +using SharpEmu.Libs.Gpu.Images; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Images; + +public sealed class ResidentImageBackingTests +{ + private const ulong Base = 0x9A_0000_0000UL; + private const int Page = 0x1000; + + // Pages [0, backed) from the start of the range are mapped; the rest is not. + private sealed class PrefixBacking(ulong start, params (int FirstPage, int PageCount)[] runs) : IGuestBackedSpace + { + private bool Page_(ulong address) => runs.Any(run => + address >= start + (ulong)run.FirstPage * Page && address < start + (ulong)(run.FirstPage + run.PageCount) * Page); + + public bool IsBackedRange(ulong address, ulong size) + { + for (var page = address & ~(ulong)(Page - 1); page < address + size; page += Page) + { + if (!Page_(page)) + { + return false; + } + } + + return size != 0; + } + + public bool TryReadBacking(ulong address, Span data) + { + if (!IsBackedRange(address, (ulong)data.Length)) + { + return false; + } + + data.Fill(0xAB); + return true; + } + + public bool TryHoldRange(ulong address, ulong size) => false; + public bool TryHoldRangeAtOrAbove(ulong searchStart, ulong size, ulong alignment, out ulong address) { address = 0; return false; } + public bool TryMapBacked(ulong address, ulong size, ulong backingOffset, GuestPageProtection protection, out HostViewFailure failure) { failure = default; return false; } + public bool TryUnmapBacked(ulong address, ulong size) => false; + public bool TryClearBacking(ulong offset, ulong size) => false; + public bool IsBackedView(ulong address) => Page_(address); + public bool TryWriteBacking(ulong address, ReadOnlySpan data) => false; + } + + [Fact] + public void ResidentPrefixIsCopiedAndTheUnmappedTailIsZeroed() + { + var backing = new PrefixBacking(Base, (0, 3)); + var bytes = new byte[5 * Page]; + Array.Fill(bytes, (byte)0xFF); + + Assert.True(ResidentImageBacking.TryReadResidentPrefix(backing, Base, bytes)); + + Assert.All(bytes.AsSpan(0, 3 * Page).ToArray(), value => Assert.Equal(0xAB, value)); + Assert.All(bytes.AsSpan(3 * Page).ToArray(), value => Assert.Equal(0, value)); + } + + [Fact] + public void ABackedPageAfterAHoleIsRejected() + { + var backing = new PrefixBacking(Base, (0, 1), (2, 1)); + Assert.False(ResidentImageBacking.TryReadResidentPrefix(backing, Base, new byte[3 * Page], allowHoles: false)); + } + + // SHARPEMU_IMAGE_BACKING_HOLES: Games bind images whose backing has a backed page after a hole + // (first byte backed, last not). The holes read as zero and the backed pages as their bytes. + [Fact] + public void WithHolesAllowedEveryHoleIsZeroedAndEveryBackedPageCopied() + { + var backing = new PrefixBacking(Base, (0, 1), (2, 1)); + var bytes = new byte[4 * Page]; + Array.Fill(bytes, (byte)0xFF); + + Assert.True(ResidentImageBacking.TryReadResidentPrefix(backing, Base, bytes, allowHoles: true)); + + Assert.All(bytes.AsSpan(0, Page).ToArray(), value => Assert.Equal(0xAB, value)); + Assert.All(bytes.AsSpan(Page, Page).ToArray(), value => Assert.Equal(0, value)); + Assert.All(bytes.AsSpan(2 * Page, Page).ToArray(), value => Assert.Equal(0xAB, value)); + Assert.All(bytes.AsSpan(3 * Page).ToArray(), value => Assert.Equal(0, value)); + Assert.False(ResidentImageBacking.TryReadResidentPrefix(new PrefixBacking(Base, (1, 2)), Base, new byte[3 * Page], allowHoles: true)); + } + + [Fact] + public void AnUnmappedFirstByteIsRejected() + { + var backing = new PrefixBacking(Base, (1, 2)); + Assert.False(ResidentImageBacking.TryReadResidentPrefix(backing, Base, new byte[3 * Page])); + Assert.False(ResidentImageBacking.TryRead(backing, Base, new byte[3 * Page])); + } + + [Fact] + public void AFullyBackedRangeReadsThroughTheNormalPath() + { + var backing = new PrefixBacking(Base, (0, 2)); + var bytes = new byte[2 * Page]; + Assert.True(ResidentImageBacking.TryRead(backing, Base, bytes)); + Assert.All(bytes, value => Assert.Equal(0xAB, value)); + } + + [Fact] + public void TheTailIsZeroedWhenTheRangeStartsMidPage() + { + var backing = new PrefixBacking(Base, (0, 2)); + var bytes = new byte[2 * Page]; + Array.Fill(bytes, (byte)0xFF); + Assert.True(ResidentImageBacking.TryReadResidentPrefix(backing, Base + 0x800, bytes)); + Assert.Equal(0xAB, bytes[0x17FF]); + Assert.Equal(0, bytes[0x1800]); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Images/TextureTransferLayoutTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Images/TextureTransferLayoutTests.cs index 516bf593f..b8b090784 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Images/TextureTransferLayoutTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Images/TextureTransferLayoutTests.cs @@ -129,6 +129,72 @@ public void FmaskAndDepthTiles_AreRejectedWhereTheReferenceRejectsThem() Assert.Contains(fatal.Messages, message => message.Contains("upload format is unknown")); } + private static SharpEmu.ShaderCompiler.Gen5PixelOutputKind KindOf(Format host) + { + var name = host.ToString(); + return name.EndsWith("Uint", StringComparison.Ordinal) ? SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Uint + : name.EndsWith("Sint", StringComparison.Ordinal) ? SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Sint + : SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Float; + } + + // The host image of a render target and the pixel output decoding of the presenter must agree + // on the numeric class: an integer attachment needs an integer output, a normalized one a float. + [Theory] + [InlineData(ChannelLayout.Bits8, ChannelType.SNorm, Format.R8SNorm)] + [InlineData(ChannelLayout.Bits8, ChannelType.SInt, Format.R8Sint)] + [InlineData(ChannelLayout.Bits8, ChannelType.Srgb, Format.R8Unorm)] + [InlineData(ChannelLayout.Bits8_8, ChannelType.SNorm, Format.R8G8SNorm)] + [InlineData(ChannelLayout.Bits8_8, ChannelType.UInt, Format.R8G8Uint)] + [InlineData(ChannelLayout.Bits8_8, ChannelType.SInt, Format.R8G8Sint)] + [InlineData(ChannelLayout.Bits8_8, ChannelType.Srgb, Format.R8G8Unorm)] + [InlineData(ChannelLayout.Bits16_16, ChannelType.SNorm, Format.R16G16SNorm)] + [InlineData(ChannelLayout.Bits8_8_8_8, ChannelType.SNorm, Format.R8G8B8A8SNorm)] + [InlineData(ChannelLayout.Bits16_16_16_16, ChannelType.SNorm, Format.R16G16B16A16SNorm)] + [InlineData(ChannelLayout.Bits11_11_10, ChannelType.UNorm, Format.B10G11R11UfloatPack32)] + public void RenderTargetFormats_HaveAHostFormatAndAMatchingPixelOutput(ChannelLayout layout, ChannelType type, Format host) + { + var target = TextureTransferLayout.RenderTargetFormat(layout, type, ChannelOrder.Standard); + Assert.Equal(host, target.HostFormat); + + Assert.True(SharpEmu.Libs.VideoOut.VulkanVideoPresenter.TryDecodeRenderTargetFormat((uint)layout, (uint)type, 0, out var output)); + Assert.Equal(KindOf(host), output.OutputKind); + } + + // Every combination that both tables accept must agree on the numeric class of the attachment. + [Fact] + public void RenderTargetTables_AgreeOnTheNumericClassOfEveryCommonFormat() + { + using var fatal = new FatalScope(); + var checkedCount = 0; + foreach (var layout in Enum.GetValues()) + { + for (var type = 0u; type < 8; type++) + { + if (!SharpEmu.Libs.VideoOut.VulkanVideoPresenter.TryDecodeRenderTargetFormat((uint)layout, type, 0, out var output)) + { + continue; + } + + RenderTargetFormatInfo target; + try + { + target = TextureTransferLayout.RenderTargetFormat(layout, (ChannelType)type, ChannelOrder.Standard); + } + catch (SchedulerFatalException) + { + continue; + } + + Assert.True( + KindOf(target.HostFormat) == output.OutputKind, + $"layout={layout} type={type} host={target.HostFormat} output={output.OutputKind}"); + checkedCount++; + } + } + + Assert.True(checkedCount > 30); + } + [Fact] public void RenderTargetFormats_CombineHostSwizzleAndOrder() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/CapturedShaders.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/CapturedShaders.cs new file mode 100644 index 000000000..3cdc23f4a --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/CapturedShaders.cs @@ -0,0 +1,72 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +// Guest shader binaries captured from titles, kept as the words the guest holds. +internal static class CapturedShaders +{ + // The pixel shader of Ghost of Yotei that dies with ImageCapacityExceeded (hash 0x2A1E4953D280871C), as captured: a + // waterfall over the material index in an interpolant, a material record read at index * 0x74, and its T# read from a + // heap at key << 5. + public static readonly uint[] MaterialTablePixelShader = + [ + 0xBFA00003, 0xF40C0300, 0xFA000080, 0xBEFC030A, 0xBEA4047E, 0xBEFE0A7E, 0x7E041102, 0x7E061103, + 0xC82A0E02, 0xC85C0000, 0xC8600100, 0xC8460D02, 0xBF8CC07F, 0xF0000308, 0x00030502, 0x361014FF, + 0x00003FFF, 0x3014148E, 0xC85D0001, 0xC8610101, 0xC84A0F02, 0x7E100B08, 0x7E140B0A, 0xBE8A047E, + 0xD5410013, 0x03C210FF, 0x38000200, 0x102814FF, 0x38800200, 0x102A10FF, 0x38800200, 0x102C10FF, + 0x38000200, 0xBF8C3F70, 0x20100AF9, 0x06862680, 0x7C060AF0, 0xD5410005, 0x03CE10F4, 0x20100CF9, + 0x06862680, 0xD541000A, 0x03CE10F4, 0x061014F9, 0x36360605, 0x061010F2, 0xD557000B, 0x420210F2, + 0x021816F9, 0x1606060B, 0x7C060CF0, 0x060A0B0C, 0x020C16F9, 0x1606060B, 0xF4001A80, 0xFA0000AC, + 0x10160B05, 0x060C1506, 0x3E160D06, 0x3E161108, 0x7E145D0B, 0xBF8CC07F, 0x1010146A, 0xD51F0017, + 0x20021105, 0xD51F0018, 0x20021106, 0xBEEA140A, 0xD760002C, 0x0000D511, 0x7D8422F9, 0x0686A62C, + 0xBEA82426, 0xBF88012E, 0x936BFF2C, 0x00000074, 0xF40C0300, 0xFA000020, 0xBF8CC07F, 0xF4201A86, + 0xD6000030, 0xBF8CC07F, 0x8F2D9D6A, 0xF4280706, 0xD600003C, 0xBF8CC07F, 0xBF071C80, 0x7E120C1D, + 0x7E160C1E, 0x85AA807E, 0xBF08FF2D, 0x7FFFFFFF, 0xF4200B86, 0xD600004C, 0x85EA807E, 0x88EA2A6A, + 0xBF8600DE, 0x936AFF2C, 0x00000074, 0xBF08FF2D, 0x7FFFFFFF, 0xF4280806, 0xD4000050, 0xBF8C0070, + 0x7E0A0C20, 0x7E100C21, 0x8594807E, 0xBF071C80, 0xBF800000, 0x85EA807E, 0x8F1C851C, 0x87EA6A14, + 0xF42C0508, 0x38000000, 0xBF86006E, 0x10141105, 0x101C2508, 0x816AC121, 0x10342E22, 0x7E0E0C6A, + 0x7E14550A, 0x7E3244F9, 0x0016060E, 0xBEA00402, 0x101A1709, 0x1018250B, 0x061E250A, 0x816AC11E, + 0x7E140C6A, 0x7E1E410F, 0x10201F08, 0x7E10410E, 0x7E1E4110, 0x101C0B08, 0x7E2044F9, 0x00160610, + 0x06103307, 0x10323023, 0x100A0B0F, 0x7E1C490E, 0x060E2107, 0xD541000F, 0x04661023, 0x7E0A4905, + 0xD541000E, 0x046A1C22, 0x3E320E23, 0x3E340A22, 0xBEA20404, 0xBF8CC07F, 0xF0800308, 0x0105070E, + 0xF080030A, 0x0105051A, 0x00000019, 0x7E1E550D, 0x101C1B12, 0x061E250F, 0x7E32410E, 0x7E1C410C, + 0x7E1844F9, 0x0016060C, 0x7E1E410F, 0x081A32F2, 0x101C130E, 0x0618190A, 0x10161F0B, 0x7E1C490E, + 0x7E34410B, 0x7E3644F9, 0x0016060B, 0x1012131A, 0xBF8C3F71, 0xD541000F, 0x03CE0EF4, 0xBF8C3F70, + 0xD5410005, 0x03CE0AF4, 0xD5410008, 0x03CE10F4, 0xD5410007, 0x03CE0CF4, 0x0636370A, 0x10201EF9, + 0x0626060F, 0x101E0AF9, 0x06260605, 0x7E0A4909, 0xD541010B, 0x04421108, 0xD51F0210, 0x40021108, + 0x103416F9, 0x0606C614, 0xD541010B, 0x043E0F07, 0xD51F020F, 0x40020F07, 0x101020F9, 0x0606C614, + 0x10161714, 0x100E1F14, 0xD541000B, 0x846A16F0, 0xD541000F, 0x84220EF0, 0x3E34330B, 0x3E10330F, + 0xD5418009, 0x245E3519, 0xD5418007, 0x045E1B1A, 0xD541800A, 0x04621B08, 0xD5418008, 0x24621119, + 0x0612130E, 0x060A0F05, 0x060C370A, 0x060E1908, 0x101A121F, 0x101E0A1F, 0x10200C2E, 0x101C0E2E, + 0xBF820070, 0xBF04802D, 0xBF840020, 0x10141709, 0x816AC11E, 0x100A2E1F, 0x7E0E0C6A, 0x101C302E, + 0x7E10550A, 0x10181512, 0x06142508, 0x1010250B, 0x7E32410C, 0x7E14410A, 0x1016150B, 0x7E144108, + 0x7E1044F9, 0x00160608, 0x7E1A410B, 0x7E1844F9, 0x0016060B, 0x1016130D, 0x1012130A, 0x06141907, + 0x060E1107, 0x7E10490B, 0x7E124909, 0xD5410010, 0x043A142E, 0x3E1C0E2E, 0xD541000F, 0x0416101F, + 0xD541000D, 0x0416121F, 0xBF82003B, 0x100E2508, 0x100C250B, 0x816AC121, 0xBEA00402, 0x816BC11E, + 0x7E104107, 0x7E320315, 0x10100B08, 0x7E0A44F9, 0x00160607, 0x7E0E4106, 0x7E144908, 0x7E1044F9, + 0x00160606, 0x100E1307, 0x7E120C6B, 0x060C2F0A, 0x7E0E4907, 0x06101109, 0x10140C22, 0x7E0C0C6A, + 0x101A0E1F, 0x101C102E, 0x060A0B06, 0x060A0B18, 0x10160A23, 0xBEA20404, 0xBF8CC07F, 0xF0800308, + 0x0105050A, 0xBF8C3F70, 0xD5410009, 0x03CE0AF4, 0xD5410005, 0x03CE0CF4, 0x101212F9, 0x06260609, + 0xD5410106, 0x04260B05, 0xD51F0209, 0x40020B05, 0x100A0CF9, 0x0606C614, 0x100C12F9, 0x0606C614, + 0xD541800A, 0x045E0B13, 0xD5418009, 0x045E0B16, 0xD5418005, 0x04620D16, 0xD5418006, 0x04620D13, + 0xD541000F, 0x0436121F, 0xD5410010, 0x043A0A2E, 0x3E1A141F, 0x3E1C0C2E, 0xBF820012, 0xBF8C3F70, + 0x100E250B, 0x816AC11E, 0x7E320280, 0x7E0A0C6A, 0x7E0C4107, 0x7E0E44F9, 0x00160607, 0x100C1306, + 0x060A0F05, 0x7E0C4906, 0x060A0B18, 0x060C2F06, 0xBF8CC07F, 0x101C0A2E, 0x101A0C1F, 0x7E20030E, + 0x7E1E030D, 0x936AFF2C, 0x00000074, 0xF4201AC6, 0xD4000034, 0xBF8CC07F, 0x8F6A856B, 0xBF08FF2D, + 0x7FFFFFFF, 0xF42C0508, 0xD4000000, 0x85EA807E, 0x88EA2A6A, 0x87EA6A7E, 0xBF860014, 0xBE8C0406, + 0xBE8E0408, 0xBF8CC07F, 0xF0800F08, 0x0065090F, 0xF0800F08, 0x0065050D, 0xBF8C3F70, 0x081A110C, + 0x1018330C, 0x08120B09, 0x08140D0A, 0x08160F0B, 0x3E10330D, 0x7E1A5508, 0x10181B0C, 0x3E0A1909, + 0x3E0C190A, 0x3E0E190B, 0xBF820005, 0xBE8C0406, 0xBE8E0408, 0xBF8CC07F, 0xF0800F08, 0x0065050D, + 0x8A8A260A, 0xBEFE0428, 0xBF85FEC8, 0xC8260C02, 0xBEEA03FF, 0x3B008081, 0xBF8C3F70, 0x10101109, + 0x7C08106A, 0x8AA46A24, 0xBF84003C, 0xBEFE0A24, 0xF40C0100, 0xFA000060, 0xBF8CC07F, 0xF0000108, + 0x00010202, 0xC8240200, 0xC80C0300, 0xC8000400, 0xF4041A80, 0xFA0000A0, 0xBE8203FF, 0x42C80000, + 0xC8250201, 0xC80D0301, 0xC8010401, 0xF40000C0, 0xFA0000A8, 0x10021309, 0x3E020703, 0x3E020100, + 0x7E025D01, 0xBF8C0070, 0xD5410002, 0x01A8D702, 0x10000101, 0x7E0254F9, 0x00160602, 0x200000FF, + 0x3E4CCCCD, 0x06020304, 0x10000300, 0x7C060002, 0x8AA46A24, 0xBF840019, 0xBEFE0A24, 0xD5418003, + 0x03D200FF, 0xBCA3D70A, 0xC8120B02, 0xC80A0902, 0xC8060A02, 0xD52F0000, 0x00000680, 0x10061103, + 0x10080F04, 0x10040B02, 0x10020D01, 0x5E060680, 0xD52F0004, 0x00010104, 0x5E020302, 0xBEFE0424, + 0xF800140F, 0x00000301, 0xF800041F, 0x00000304, 0xF8000C2F, 0x00000300, 0xBF810000, 0xBEFE0480, + 0xF8001C00, 0x00000000, 0xBF810000, + ]; +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/GraphicsRejectionPolicyTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/GraphicsRejectionPolicyTests.cs index c23089054..979deb484 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/GraphicsRejectionPolicyTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/GraphicsRejectionPolicyTests.cs @@ -99,7 +99,7 @@ public void GraphicsCompilationUsesTheSameStrictSwitch(string? setting, bool pix [InlineData(true, false)] [InlineData(false, true)] [InlineData(true, true)] - public void PixelCandidateValidationHonorsCapacityAndStrictMode(bool strict, bool distinctCandidates) + public void PixelCandidateTableCompilesStrictOrNot(bool strict, bool distinctCandidates) { using var fatal = new FatalScope(); var guest = new PipelineTestGuest(); @@ -113,28 +113,11 @@ public void PixelCandidateValidationHonorsCapacityAndStrictMode(bool strict, boo var source = guest.Source(PixelAddress, ShaderStage.Pixel, [(uint)(TableAddress & uint.MaxValue), (uint)(TableAddress >> 32)]); var options = new StageCompileOptions { PixelInfo = new PixelInputInfo() }; var cursor = 7u; - if (distinctCandidates) - { - Assert.True(guest.Programs.TryGetProgram(source, options, strict, ref cursor, out var program, out _, out var rejection), rejection); - Assert.True(program.IsValid); - Assert.Single(guest.Compiler.Requests); - Assert.Single(guest.Host.Modules); - return; - } - if (strict) - { - var failure = Assert.Throws(() => guest.Programs.TryGetProgram( - source, options, true, ref cursor, out _, out _, out _)); - Assert.Contains("could not be materialized", failure.Message); - } - else - { - Assert.False(guest.Programs.TryGetProgram(source, options, false, ref cursor, out var program, out _, out var rejection)); - Assert.False(program.IsValid); - Assert.Contains("could not be materialized", rejection); - } - Assert.Equal(7u, cursor); - Assert.Empty(guest.Compiler.Requests); - Assert.Empty(guest.Host.Modules); + // Distinct candidates fit one binding. A 3D candidate among 2D ones cannot share it: with no heap to read the table + // from, it reads as null and the draw still runs, strict or not. + Assert.True(guest.Programs.TryGetProgram(source, options, strict, ref cursor, out var program, out _, out var rejection), rejection); + Assert.True(program.IsValid); + Assert.Single(guest.Compiler.Requests); + Assert.Single(guest.Host.Modules); } } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/HeapRecordPrewarmTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/HeapRecordPrewarmTests.cs new file mode 100644 index 000000000..2e785c6d9 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/HeapRecordPrewarmTests.cs @@ -0,0 +1,308 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +// A program whose image table is too large to bind is planned again with heap records (HeapRecordReplanTests). Its +// prewarm record keeps that, so a later launch compiles the plan the draw uses, and the draw plans it so from the start. +[Collection(SchedulingStateCollection.Name)] +public sealed class HeapRecordPrewarmTests : IDisposable +{ + private const ulong Code = PipelineTestGuest.MemoryBase + 0x1000; + private const ulong Header = PipelineTestGuest.MemoryBase + 0x8000; + private const ulong Srt = PipelineTestGuest.MemoryBase + 0x1_0000; + private const ulong Materials = PipelineTestGuest.MemoryBase + 0x2_0000; + private const ulong Heap = PipelineTestGuest.MemoryBase + 0x8_0000; + private const uint MaterialBytes = 0x74; + private const uint KeyOffset = 60; + private const uint ImageType2D = 9; + private const uint Format32Float = 22; + + private readonly FatalScope _fatal = new(); + private readonly string _directory = Path.Combine(Path.GetTempPath(), "SharpEmuTests", Guid.NewGuid().ToString("N")); + + public void Dispose() + { + _fatal.Dispose(); + if (Directory.Exists(_directory)) + { + Directory.Delete(_directory, recursive: true); + } + } + + private ShaderPrewarmList Open() => ShaderPrewarmList.Open(_directory) ?? throw new InvalidOperationException("The list did not open."); + + private static byte[] Compile(ShaderCompileRequest request) + { + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + return shader.Spirv; + } + + private static uint Low(ulong value) => unchecked((uint)value); + + private static uint High(ulong value) => (uint)(value >> 32); + + private static uint[] UserData() => + [Low(Srt), High(Srt), 0x880, 0x00FFF000, 0x0A503F44, 0, 0x880, 0x00FFF000, 0x0A503F44, 0]; + + private static void WriteScene(PipelineTestGuest guest, uint materialCount) + { + guest.WriteWords(Srt + 32, + Low(Materials), High(Materials) | (MaterialBytes << 16), materialCount, 0x00FFF000, + Low(Heap), High(Heap), materialCount * 32, 0x00FFF000); + var records = new uint[materialCount * (MaterialBytes / 4)]; + for (uint material = 0; material < materialCount; material++) + { + records[material * (MaterialBytes / 4) + KeyOffset / 4] = material; + } + + guest.WriteWords(Materials, records); + for (uint key = 0; key < materialCount; key++) + { + guest.WriteWords(Heap + key * 32, 0x2000 + key, Format32Float << 20, 0, 0xFAC | (ImageType2D << 28), 0, 0, 0, 0); + } + } + + private static StageCompileOptions PixelOptions() => new() + { + PixelInfo = new PixelInputInfo(), + PixelOutputs = [new Gen5PixelOutputBinding(0, 0, Gen5PixelOutputKind.Float)], + }; + + // One launch: the material table pixel program drawn with a table of the given size. Returns the host, what the + // draw's compile saw, and what the launch wrote to the error stream. + private (PipelineTestGuest Guest, ShaderCompileRequest Request, byte[] Spirv, string Log) Launch(ShaderPrewarmList list, uint materialCount) + { + var guest = new PipelineTestGuest(Compile); + guest.Host.SupportsBindlessHeap = true; + guest.Host.ShaderPrewarm = list; + guest.RegisterProgram(Code, Header, CapturedShaders.MaterialTablePixelShader); + WriteScene(guest, materialCount); + var original = Console.Error; + var log = new StringWriter(); + Console.SetError(log); + try + { + var cursor = 0u; + Assert.True(guest.Programs.TryGetProgram(guest.Source(Code, ShaderStage.Pixel, UserData()), PixelOptions(), + strictShaders: false, ref cursor, out _, out _, out var rejection), rejection); + } + finally + { + Console.SetError(original); + } + + return (guest, Assert.Single(guest.Compiler.Requests), Assert.Single(guest.Compiler.Shaders).Spirv, log.ToString()); + } + + private const string ReplanLog = "reads its image descriptors from the bindless heap"; + + [Fact] + public void AReplannedProgramIsRecordedForThePrewarmWithItsHeapPlan() + { + using (var list = Open()) + { + var (_, request, _, log) = Launch(list, materialCount: 200); + Assert.True(request.Resources.Info.UsesBindlessHeap); + Assert.Contains(ReplanLog, log); + } + + using var reloaded = Open(); + var (record, code, _) = Assert.IsType(Assert.Single(reloaded.LoadedGraphicsPrewarm())); + Assert.True(record.PreferHeapRecords); + Assert.True(reloaded.PrefersHeapRecords(record.Hash, record.CodeSize, record.ContinuationAddressOffset)); + Assert.Equal(code.Hash, record.Hash); + } + + [Fact] + public void AProgramWhoseTableFitsIsRecordedWithoutTheFlag() + { + using (var list = Open()) + { + var (_, request, _, _) = Launch(list, materialCount: 8); + Assert.False(request.Resources.Info.UsesBindlessHeap); + } + + using var reloaded = Open(); + var (record, _, _) = Assert.IsType(Assert.Single(reloaded.LoadedGraphicsPrewarm())); + Assert.False(record.PreferHeapRecords); + Assert.False(reloaded.PrefersHeapRecords(record.Hash, record.CodeSize, record.ContinuationAddressOffset)); + } + + // The prewarm compiles the plan the draw ran, so the draw finds it: the same request and the same translation. + [Fact] + public void ThePrewarmReplaysAFlaggedRecordWithTheDrawsPlan() + { + byte[] runtime; + IShaderPipelineHost host; + using (var list = Open()) + { + var (guest, _, spirv, _) = Launch(list, materialCount: 200); + host = guest.Host; + runtime = spirv; + } + + using var reloaded = Open(); + var (record, code, _) = Assert.IsType(Assert.Single(reloaded.LoadedGraphicsPrewarm())); + var compiler = new FakeShaderCompiler(Compile); + Assert.True(ShaderProgramCache.TryCompilePixelPrewarm(record, code, compiler, host, out var compiled, out var layout, out var error), error); + Assert.NotNull(layout); + Assert.True(Assert.Single(compiler.Requests).Resources.Info.UsesBindlessHeap); + Assert.Equal(runtime, Assert.IsType(compiled).Spirv); + } + + // A launch after the recording plans the program with heap records at once: it neither fails to materialize it nor + // plans it twice, and compiles the translation the first launch (and the prewarm) did. + [Fact] + public void ALaterLaunchPlansAKnownProgramWithHeapRecordsFromTheStart() + { + byte[] first; + using (var list = Open()) + { + first = Launch(list, materialCount: 200).Spirv; + } + + using var reloaded = Open(); + var (_, request, spirv, log) = Launch(reloaded, materialCount: 200); + Assert.True(request.Resources.Info.UsesBindlessHeap); + Assert.DoesNotContain(ReplanLog, log); + Assert.Equal(first, spirv); + } + + [Fact] + public void AHostWithoutTheHeapKeepsPlanningWithoutHeapRecords() + { + using (var list = Open()) + { + Launch(list, materialCount: 200); + } + + using var reloaded = Open(); + var guest = new PipelineTestGuest(Compile); + guest.Host.SupportsBindlessHeap = false; + guest.Host.ShaderPrewarm = reloaded; + guest.RegisterProgram(Code, Header, CapturedShaders.MaterialTablePixelShader); + WriteScene(guest, 8); + var cursor = 0u; + Assert.True(guest.Programs.TryGetProgram(guest.Source(Code, ShaderStage.Pixel, UserData()), PixelOptions(), + strictShaders: false, ref cursor, out _, out _, out var rejection), rejection); + Assert.False(Assert.Single(guest.Compiler.Requests).Resources.Info.UsesBindlessHeap); + } + + private static ComputePrewarmRecord ComputeRecord(bool deviceRecordCounts, bool preferHeapRecords) => new() + { + Hash = 0xC0DE, CodeSize = 12, Address = Code, UserDataBase = 0, UserDataCount = 4, PushDataCursor = 0, + Info = new ComputeInputInfo { ThreadsX = 64, ThreadsY = 1, ThreadsZ = 1, WaveSize = 64 }, + Specialization = new ResourceSpecialization(), + DeviceRecordCounts = deviceRecordCounts, + PreferHeapRecords = preferHeapRecords, + }; + + private static ShaderCodeCapture Capture(ulong hash, ulong continuationOffset = 0) => new() + { + Hash = hash, CodeSize = 12, Address = Code, Generation = Generation.Gen5, + Fused = continuationOffset == 0 ? null : new FusedCodeParts(Header, Code + continuationOffset, Header + 0x100), + Ranges = [new CodeRange(Code, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])], + }; + + // The compute extension byte is a bit set: 1, the only value written before the flag existed, still means device + // record counts. + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(true, true)] + public void AComputeRecordKeepsItsHeapFlagBesideItsDeviceCountFlag(bool deviceRecordCounts, bool preferHeapRecords) + { + var record = ComputeRecord(deviceRecordCounts, preferHeapRecords); + using (var list = Open()) list.RecordCompute(Capture(record.Hash), record); + + using var reloaded = Open(); + var (loaded, _) = Assert.Single(reloaded.LoadedComputes()); + Assert.Equal(deviceRecordCounts, loaded.DeviceRecordCounts); + Assert.Equal(preferHeapRecords, loaded.PreferHeapRecords); + Assert.Equal(preferHeapRecords, reloaded.PrefersHeapRecords(record.Hash, record.CodeSize, 0)); + Assert.Equal(ShaderPrewarmList.Identity(record), ShaderPrewarmList.Identity(loaded)); + } + + [Fact] + public void TheHeapFlagChangesARecordsIdentityOnlyWhenSet() + { + var plain = ComputeRecord(deviceRecordCounts: true, preferHeapRecords: false); + Assert.NotEqual(ShaderPrewarmList.Identity(plain), ShaderPrewarmList.Identity(ComputeRecord(true, true))); + + // The bytes of a record without the flag are what an earlier build wrote: the flag adds nothing to them. + Assert.Equal(ShaderPrewarmList.Identity(plain), ShaderPrewarmList.Identity(ComputeRecord(true, preferHeapRecords: false))); + } + + [Fact] + public void ThePixelAndVertexSchemasIgnoreTheHeapFlagSoRecordedListsStillLoad() + { + Assert.DoesNotContain(nameof(PixelPrewarmRecord.PreferHeapRecords), + ShaderPrewarmList.SchemaText(typeof(PixelPrewarmRecord), typeof(PixelInputInfo))); + Assert.DoesNotContain(nameof(VertexPrewarmRecord.PreferHeapRecords), + ShaderPrewarmList.SchemaText(typeof(VertexPrewarmRecord), typeof(VertexInputInfo))); + } + + [Theory] + [InlineData(-1, -1, false)] + [InlineData(-1, -1, true)] + [InlineData(5, -1, false)] + [InlineData(5, -1, true)] + [InlineData(5, 6, false)] + [InlineData(5, 6, true)] + public void AVertexRecordKeepsItsHeapFlagBesideItsDrawRegisters(int startInstance, int baseVertex, bool preferHeapRecords) + { + var code = Capture(0x7E57); + var record = new VertexPrewarmRecord + { + Hash = code.Hash, CodeSize = code.CodeSize, Address = code.Address, UserDataBase = 0, UserDataCount = 8, PushDataCursor = 0, + VertexInfo = new VertexInputInfo { StartInstanceUserData = startInstance, BaseVertexUserData = baseVertex }, + RequiredVertexOutputCount = 2, + Specialization = new ResourceSpecialization(), + PreferHeapRecords = preferHeapRecords, + }; + var state = new PreRasterizationState(0, 2, 1, false, false, true, false); + using (var list = Open()) list.RecordPreRasterization(list.RecordVertex(code, record), state); + + using var reloaded = Open(); + var item = Assert.IsType(Assert.Single(reloaded.LoadedGraphicsPrewarm())); + Assert.Equal(preferHeapRecords, item.Program.PreferHeapRecords); + Assert.Equal(startInstance, item.Program.VertexInfo!.StartInstanceUserData); + Assert.Equal(baseVertex, item.Program.VertexInfo.BaseVertexUserData); + Assert.Equal(preferHeapRecords, reloaded.PrefersHeapRecords(code.Hash, code.CodeSize, 0)); + } + + [Fact] + public void AStageRecordKeepsItsHeapFlag() + { + var code = Capture(0x57A6); + var record = new StagePrewarmRecord + { + Stage = ShaderStage.Pixel, + CodeKey = code.Key, + Registered = new RegisteredShader(code.Address, 0, code.CodeSize, 0, 0, 0, 0, 0, 0), + Hash = code.Hash, + UserDataBase = 0, + UserDataCount = 4, + PushDataCursor = 0, + Options = PixelOptions(), + Specialization = new ResourceSpecialization(), + PreferHeapRecords = true, + }; + using (var list = Open()) list.RecordStage(code, module: 1, record); + + using var reloaded = Open(); + Assert.True(reloaded.PrefersHeapRecords(code.Hash, code.CodeSize, 0)); + Assert.False(reloaded.PrefersHeapRecords(code.Hash + 1, code.CodeSize, 0)); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/HeapRecordReplanTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/HeapRecordReplanTests.cs new file mode 100644 index 000000000..86e4aa555 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/HeapRecordReplanTests.cs @@ -0,0 +1,164 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +// A material table selects its image through a record the shader indexes at run time. While the table is small the +// planner binds every image it can select, as it always did; when it selects more than a draw can bind, a host with the +// bindless heap plans the program again so the image is a heap record read at run time, and any other host rejects the draw. +[Collection(SchedulingStateCollection.Name)] +public sealed class HeapRecordReplanTests : IDisposable +{ + private const ulong Code = PipelineTestGuest.MemoryBase + 0x1000; + private const ulong Header = PipelineTestGuest.MemoryBase + 0x8000; + private const ulong Srt = PipelineTestGuest.MemoryBase + 0x1_0000; + private const ulong Materials = PipelineTestGuest.MemoryBase + 0x2_0000; + private const ulong Heap = PipelineTestGuest.MemoryBase + 0x8_0000; + private const uint MaterialBytes = 0x74; + private const uint KeyOffset = 60; + private const uint ImageType2D = 9; + private const uint Format32Float = 22; + private const uint Format32Uint = 20; + + private readonly FatalScope _fatal = new(); + private readonly PipelineTestGuest _guest = new(); + + public void Dispose() => _fatal.Dispose(); + + private static uint Low(ulong value) => unchecked((uint)value); + + private static uint High(ulong value) => (uint)(value >> 32); + + // The shader's user data: the pointer to its resource table, then two sampler descriptors. + private static uint[] UserData() => + [Low(Srt), High(Srt), 0x880, 0x00FFF000, 0x0A503F44, 0, 0x880, 0x00FFF000, 0x0A503F44, 0]; + + // The resource table the shader reads at fixed offsets (+32: the material V#, +48: the heap V#), the material + // records, and the heap of T#s they select by key. + private void WriteScene(uint materialCount, uint declaredCount = 0) + { + // The V#s may declare more records than the guest has mapped, as a game's pools do. + var declared = declaredCount == 0 ? materialCount : declaredCount; + _guest.WriteWords(Srt + 32, + Low(Materials), High(Materials) | (MaterialBytes << 16), declared, 0x00FFF000, + Low(Heap), High(Heap), declared * 32, 0x00FFF000); + var records = new uint[materialCount * (MaterialBytes / 4)]; + for (uint material = 0; material < materialCount; material++) + { + records[material * (MaterialBytes / 4) + KeyOffset / 4] = material; + } + + _guest.WriteWords(Materials, records); + for (uint key = 0; key < materialCount; key++) + { + // Every record holds a different image, so no two candidates share a binding. + _guest.WriteWords(Heap + key * 32, 0x2000 + key, Format32Float << 20, 0, 0xFAC | (ImageType2D << 28), 0, 0, 0, 0); + } + } + + // One record of the table holds an image of another kind than the others (an integer texture where they are float). + private void WriteImageOfAnotherKind(uint key) => + _guest.WriteWords(Heap + key * 32, 0x2000 + key, Format32Uint << 20, 0, 0xFAC | (ImageType2D << 28), 0, 0, 0, 0); + + private static StageCompileOptions PixelOptions() => new() + { + PixelInfo = new PixelInputInfo(), + PixelOutputs = [new Gen5PixelOutputBinding(0, 0, Gen5PixelOutputKind.Float)], + }; + + private bool TryCompile(out ShaderStageResources stage, out string rejection) + { + _guest.RegisterProgram(Code, Header, CapturedShaders.MaterialTablePixelShader); + var source = _guest.Source(Code, ShaderStage.Pixel, UserData()); + var cursor = 0u; + return _guest.Programs.TryGetProgram(source, PixelOptions(), strictShaders: false, ref cursor, out _, out stage, out rejection); + } + + [Fact] + public void ATableThatFitsStaysOnItsPlannedBinding() + { + _guest.Host.SupportsBindlessHeap = true; + WriteScene(materialCount: 8); + + Assert.True(TryCompile(out _, out var rejection), rejection); + + var request = Assert.Single(_guest.Compiler.Requests); + Assert.False(request.Resources.Info.UsesBindlessHeap); + Assert.Empty(request.HeapImageByMemoryIndex); + Assert.True(request.Resources.Info.Images.Count > 1); + } + + [Fact] + public void ATableTooLargeToBindIsRejectedWithoutTheHeap() + { + _guest.Host.SupportsBindlessHeap = false; + WriteScene(materialCount: 200); + + Assert.False(TryCompile(out _, out var rejection)); + + Assert.Contains("ImageCapacityExceeded", rejection); + Assert.Empty(_guest.Compiler.Requests); + } + + [Fact] + public void ATableTooLargeToBindIsReadFromTheHeapWhenTheHostHasOne() + { + _guest.Host.SupportsBindlessHeap = true; + WriteScene(materialCount: 200); + + Assert.True(TryCompile(out var stage, out var rejection), rejection); + + var request = Assert.Single(_guest.Compiler.Requests); + Assert.True(request.Resources.Info.UsesBindlessHeap); + Assert.NotEmpty(request.HeapImageByMemoryIndex); + // The material table is no longer enumerated: nothing but the fixed images is bound. + Assert.True(request.Resources.Info.Images.Count < 8); + Assert.Equal(request.Resources.Info.Images.Count, stage.Resources.Images.Length); + + // The program keeps its heap plan: another draw finds the permutation, whatever the table holds now. + WriteScene(materialCount: 3); + Assert.True(TryCompile(out _, out rejection), rejection); + Assert.Single(_guest.Compiler.Requests); + } + + // Demon's Souls (compute 0x9FB5CC274B5E4F82): "indirect image table ... has incompatible candidates", and the dispatch was + // skipped every frame. An image of another kind cannot share the table's binding. + [Fact] + public void ATableWithAnImageOfAnotherKindIsReadFromTheHeapWhenTheHostHasOne() + { + _guest.Host.SupportsBindlessHeap = true; + WriteScene(materialCount: 8); + WriteImageOfAnotherKind(key: 5); + + Assert.True(TryCompile(out _, out var rejection), rejection); + + var request = Assert.Single(_guest.Compiler.Requests); + Assert.True(request.Resources.Info.UsesBindlessHeap); + Assert.NotEmpty(request.HeapImageByMemoryIndex); + } + + [Fact] + public void ATableWithAnImageOfAnotherKindReadsItAsNullWithoutTheHeap() + { + _guest.Host.SupportsBindlessHeap = false; + WriteScene(materialCount: 8); + WriteImageOfAnotherKind(key: 5); + + Assert.True(TryCompile(out _, out var rejection), rejection); + + var request = Assert.Single(_guest.Compiler.Requests); + Assert.False(request.Resources.Info.UsesBindlessHeap); + Assert.True(request.Resources.Info.Images.Count > 1); + + // The program keeps reading such a candidate as null: a table of one kind again finds the permutation. + WriteScene(materialCount: 8); + Assert.True(TryCompile(out _, out rejection), rejection); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/LinkedHeapRecordReplanTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/LinkedHeapRecordReplanTests.cs new file mode 100644 index 000000000..f0552405c --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/LinkedHeapRecordReplanTests.cs @@ -0,0 +1,150 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +// A linked program plans its resources with the policy of its link (run-time call records and marks), not CreateEntry's. +// Replanning it with heap records, planning it so from the start, recording it and replaying its record all keep that policy. +// The fixture's callee reads no image table, so no heap record is gained here: PreferredHeapRecords and the unchanged call +// plan are what these cases observe; the gain itself is covered by HeapRecordReplanTests on a pixel program. +[Collection(SchedulingStateCollection.Name)] +public sealed class LinkedHeapRecordReplanTests : IDisposable +{ + private const ulong Caller = PipelineTestGuest.MemoryBase + 0x1000; + private const ulong Header = PipelineTestGuest.MemoryBase + 0x8000; + private const ulong Table = PipelineTestGuest.MemoryBase + 0x10000; + private const ulong Callee = PipelineTestGuest.MemoryBase + 0x20000; + private static readonly uint[] CallerCode = [0xF4280400, 125u << 25, 0xBF8C0000, 0xBE8E0310, 0xBE8F0311, + 0xBE900312, 0xBE910313, 0xBE8E210E, 0xBF810000]; + private readonly string _directory = Path.Combine(Path.GetTempPath(), "SharpEmuTests", Guid.NewGuid().ToString("N")); + + public void Dispose() + { + if (Directory.Exists(_directory)) Directory.Delete(_directory, recursive: true); + } + + private ShaderPrewarmList Open() => ShaderPrewarmList.Open(_directory) + ?? throw new InvalidOperationException("The synthetic prewarm list did not open."); + + private static byte[] CompileSpirv(ShaderCompileRequest request) + { + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + return shader.Spirv; + } + + private PipelineTestGuest CreateGuest(ShaderPrewarmList list, bool callMarks) + { + var guest = new PipelineTestGuest(CompileSpirv); + guest.Host.ShaderPrewarm = list; + guest.Host.SupportsBindlessHeap = true; + guest.Host.RuntimeCallRecordsSupported = true; + guest.Host.CallMarksSupported = callMarks; + guest.RegisterProgram(Caller, Header, CallerCode); + guest.WriteWords(Callee, 0xBF800000, 0xBE80200E); + guest.WriteWords(Table, unchecked((uint)Callee), (uint)(Callee >> 32), 0x3000, 0); + // Runtime linking loads kept callees before its first compile: a store under this test's directory keeps the + // user's shader cache out of it. + var path = Path.Combine(_directory, "callees.bin"); + var decoded = ShaderFunctionReader.Read(Callee, guest.Host.TryReadGuestWord); + Assert.True(decoded.Complete, decoded.Error); + var callee = new UnitedCallee(new ShaderCallTarget(Callee, 0, decoded.Program), + System.Security.Cryptography.SHA256.HashData(decoded.Bytes), decoded.Runs); + new ShaderCallUnionStore(path).Save(ShaderStage.Compute, Source(guest).Hash, new() { [28] = [callee] }); + var field = typeof(ShaderProgramCache).GetField("_callUnionStore", + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); + Assert.NotNull(field); + field.SetValue(guest.Programs, new ShaderCallUnionStore(path)); + return guest; + } + + private static ShaderSource Source(PipelineTestGuest guest) => + guest.Source(Caller, ShaderStage.Compute, PipelineTestGuest.BufferDescriptor(Table, 16, 1, 0)); + + private static void Compile(PipelineTestGuest guest) + { + var cursor = 0u; + guest.Programs.GetOrCompile(Source(guest), PipelineTestGuest.ComputeOptions(32), ref cursor, out _); + } + + private static ProgramSourceEntry LinkedEntry(PipelineTestGuest guest) => + Assert.Single(guest.Programs.Entries, entry => entry.RuntimeCallRecords); + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ReplanningALinkedProgramKeepsItsCallRecordPolicy(bool callMarks) + { + using var fatal = new FatalScope(); + using var list = Open(); + var guest = CreateGuest(list, callMarks); + Compile(guest); + var entry = LinkedEntry(guest); + Assert.False(entry.Plan.PreferredHeapRecords); + + var replan = Assert.IsType>(entry.ReplanWithHeapRecords); + var replanned = replan(Source(guest), PipelineTestGuest.ComputeOptions(32)); + + Assert.True(replanned.PreferredHeapRecords); + Assert.Equal(entry.Plan.CallRecords.Count, replanned.CallRecords.Count); + Assert.Equal(entry.Plan.CallRecordCallees.Count, replanned.CallRecordCallees.Count); + Assert.Equal(callMarks, replanned.Info.UsesCallMarks); + } + + // The launch after a replan: the prewarm list prefers heap records for the program, so its link plans with them at once + // and records itself with the flag and its linked callees, which the prewarm replays with the same plan. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ALinkedProgramThePrewarmPrefersIsPlannedRecordedAndReplayedWithHeapRecords(bool callMarks) + { + using var fatal = new FatalScope(); + ShaderCompileRequest runtime; + byte[] runtimeSpirv; + using (var list = Open()) + { + var guest = CreateGuest(list, callMarks); + var source = Source(guest); + list.RecordCompute(Capture(source), new ComputePrewarmRecord + { + Hash = source.Hash, CodeSize = source.CodeSize, Address = Caller, UserDataBase = 0, UserDataCount = 4, + PushDataCursor = 0, Info = new ComputeInputInfo { ThreadsX = 32, ThreadsY = 1, ThreadsZ = 1, WaveSize = 32 }, + Specialization = new ResourceSpecialization(), PreferHeapRecords = true, + }); + Compile(guest); + Assert.True(LinkedEntry(guest).Plan.PreferredHeapRecords); + runtime = Assert.Single(guest.Compiler.Requests); + runtimeSpirv = Assert.Single(guest.Compiler.Shaders).Spirv; + } + + using var restored = Open(); + var (record, code) = Assert.Single(restored.LoadedComputes(), item => item.Record.Linked is not null); + Assert.True(record.PreferHeapRecords); + Assert.True(record.Linked!.RuntimeRecords); + Assert.Equal(callMarks, record.Linked.CallMarks); + var compiler = new FakeShaderCompiler(CompileSpirv); + Assert.True(ShaderProgramCache.TryCompilePrewarm(record, code, compiler, false, true, false, + out var compiled, out var layout, out var error, bindlessHeap: true), error); + Assert.NotNull(layout); + var replay = Assert.Single(compiler.Requests); + Assert.Equal(runtime.Resources.Info.UsesCallMarks, replay.Resources.Info.UsesCallMarks); + Assert.Equal(runtime.Program.Instructions.Select(instruction => instruction.Control), + replay.Program.Instructions.Select(instruction => instruction.Control)); + Assert.Equal(runtimeSpirv, Assert.IsType(compiled).Spirv); + Assert.Equal(runtime.Bindings, layout); + } + + private static ShaderCodeCapture Capture(ShaderSource source) => new() + { + Hash = source.Hash, CodeSize = source.CodeSize, Address = Caller, Generation = Generation.Gen5, + Ranges = [new CodeRange(Caller, System.Runtime.InteropServices.MemoryMarshal.AsBytes(CallerCode).ToArray())], + }; +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PipelineTestSupport.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PipelineTestSupport.cs index 876cd627d..fea54045f 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PipelineTestSupport.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PipelineTestSupport.cs @@ -63,6 +63,8 @@ public uint[] NormalizeImageDescriptor(IShaderFrontend frontend, ReadOnlySpan false; + public bool SupportsBindlessHeap { get; set; } + public bool RuntimeCallRecordsSupported { get; set; } public bool CallMarksSupported { get; set; } @@ -259,6 +261,10 @@ public bool TryCompileProgram(ShaderCompileRequest request, out IGuestCompiledSh public void CountShaderCompilation() => Compilations++; + // The two fixed stages a tessellated draw adds; the fake host only counts their modules. + public (IGuestCompiledShader Vertex, IGuestCompiledShader Control) CompileTessellationBridge(BindingLayout layout, Gen5TessellationDomain domain) => + (new FakeCompiledShader(null!), new FakeCompiledShader(null!)); + public IGuestCompiledShader GetDepthOnlyFragmentShader() => throw Unsupported(); public void EnsureStarted(uint width, uint height) => throw Unsupported(); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheTests.cs index 3f8e7bd32..aeaf38f6c 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPipelineCacheTests.cs @@ -520,6 +520,63 @@ public void ComputePipelineKey_IsTheProgramId() public void MergedTessellationMask_DoesNotTakeOverOtherGraphicsPaths(uint mask, bool expected) => Assert.Equal(expected, ShaderPipelineCache.IsMergedTessellationMask(mask)); + // A game can bind a complete hull binary as the local program and never + // fuses two halves, so no continuation is registered and SPI_SHADER_PGM_LO_HS stays zero. + [Fact] + public void CombinedHull_BoundAsTheLocalProgramAloneCompilesWithItsOwnUserScalars() + { + var guest = new PipelineTestGuest(); + var hull = PipelineTestGuest.MemoryBase + 0x1000; + var domain = PipelineTestGuest.MemoryBase + 0x2000; + guest.RegisterProgram(hull, PipelineTestGuest.MemoryBase + 0x8000, SharpEmu.ShaderCompiler.Tests.Gen5TessellationTests.CombinedHullWords); + guest.RegisterProgram(domain, PipelineTestGuest.MemoryBase + 0x8100, PipelineTestGuest.EndProgram); + var cache = new ShaderPipelineCache(guest.Context, guest.Host, guest.Compiler, guest.Registry); + var banks = Banks(withPixel: false); + banks.Shader.Vertex.ExportAddress = domain; + banks.Shader.Vertex.LocalAddress = hull; + banks.Shader.Vertex.HullAddress = 0; + banks.Shader.Vertex.HullResource2 = HullResource2.Decode(0x00400090); + banks.Shader.Vertex.HullUserScalars.Set(2, 256, UserScalarKind.Unknown); + banks.Context.ShaderStages = 0x0200210D; + banks.Context.ShaderInterface.TessellationFactorParameter = 2u | (3u << 5); + banks.Context.ShaderInterface.LocalHullConfiguration = 32u | (2u << 8) | (4u << 14); + + var programs = cache.GetGraphicsPrograms(banks, [], pixelActive: false, depthBound: false); + + Assert.True(programs.Available); + var entry = SharpEmu.ShaderCompiler.Tests.Gen5TessellationTests.CombinedHullEntry; + Assert.Equal(new Gen5TessellationHullInfo(2, 4, 32, entry + 4), programs.Tessellation!.HullConfiguration); + var hullInput = programs.Tessellation.Hull.Input; + Assert.Equal((128u, 16u * 128), (hullInput.ThreadsX, hullInput.LocalDataShareDwords)); + var request = Assert.Single(guest.Compiler.Requests, request => request.TessellationHull is not null); + Assert.Equal("SBarrier", request.Program.Instructions.Single(instruction => instruction.Pc == entry).Opcode); + // Eight user scalars from RSRC2, none appended and none moved into s0:s1. + Assert.Equal(8, hullInput.Stage.Resources.UserData.Length); + Assert.Equal(256u, hullInput.Stage.Resources.UserData[2]); + Assert.Equal("SMovB64", request.Program.Instructions[0].Opcode); + Assert.Equal(Gen5Operand.Scalar(126), request.Program.Instructions[0].Destinations[0]); + } + + [Fact] + public void UnfusedLocalProgramWithoutAHullHalf_StopsTheTessellationDraw() + { + var guest = new PipelineTestGuest(); + var local = PipelineTestGuest.MemoryBase + 0x1000; + var domain = PipelineTestGuest.MemoryBase + 0x2000; + guest.RegisterProgram(local, PipelineTestGuest.MemoryBase + 0x8000, PipelineTestGuest.EndProgram); + guest.RegisterProgram(domain, PipelineTestGuest.MemoryBase + 0x8100, PipelineTestGuest.EndProgram); + var cache = new ShaderPipelineCache(guest.Context, guest.Host, guest.Compiler, guest.Registry); + var banks = Banks(withPixel: false); + banks.Shader.Vertex.ExportAddress = domain; + banks.Shader.Vertex.LocalAddress = local; + banks.Context.ShaderStages = 0x0200210D; + banks.Context.ShaderInterface.TessellationFactorParameter = 2u | (3u << 5); + banks.Context.ShaderInterface.LocalHullConfiguration = 32u | (2u << 8) | (4u << 14); + + var error = Assert.Throws(() => cache.GetGraphicsPrograms(banks, [], pixelActive: false, depthBound: false)); + Assert.Contains("merged local/hull program", error.Message); + } + [Fact] public void GraphicsPipelineKey_SeparatesTessellationFromRectanglesAndIncludesBothStages() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPrewarmListTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPrewarmListTests.cs index 1b8e1a847..340e77f8c 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPrewarmListTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPrewarmListTests.cs @@ -248,7 +248,7 @@ public void TheSchemaFingerprintsKeepTheValuesOfTheRecordedLists() Assert.Equal(0x24DB2A98u, ShaderPrewarmList.SchemaFingerprint); Assert.Equal(0x31C0D60Du, ShaderPrewarmList.PixelSchemaFingerprint); Assert.Equal(0x31C5863Bu, ShaderPrewarmList.VertexSchemaFingerprint); - Assert.Equal(0xD15F4A8Du, ShaderPrewarmList.GraphicsSchemaFingerprint); + Assert.Equal(0x25C0DD56u, ShaderPrewarmList.GraphicsSchemaFingerprint); } private sealed class SchemaSample diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ResolvedCommandReplayTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ResolvedCommandReplayTests.cs index aaaf95793..305073f6f 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ResolvedCommandReplayTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/ResolvedCommandReplayTests.cs @@ -113,6 +113,7 @@ public void AResetRecordStartsFromAnEmptyDrawState() record.State.DepthResolved = true; record.State.PixelActive = false; record.State.StartInstanceUserData = 4; + record.State.BaseVertexUserData = 3; record.State.Programs = Programs(); record.State.Rendering.ColorAttachmentCount = 3; @@ -122,7 +123,7 @@ public void AResetRecordStartsFromAnEmptyDrawState() Assert.False(record.State.DepthResolved); Assert.False(record.State.Depth.HasTarget); Assert.True(record.State.PixelActive); - Assert.Equal(-1, record.State.StartInstanceUserData); + Assert.Equal((-1, -1), (record.State.StartInstanceUserData, record.State.BaseVertexUserData)); Assert.Null(record.State.Programs); Assert.Equal(0u, record.State.Rendering.ColorAttachmentCount); } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/BufferLoadFormatD16HiDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/BufferLoadFormatD16HiDeviceTests.cs new file mode 100644 index 000000000..4efe155b3 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/BufferLoadFormatD16HiDeviceTests.cs @@ -0,0 +1,119 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.Libs.Tests.Gpu.Vulkan; + +// BUFFER_LOAD_FORMAT_D16_HI_X converts the formatted X component to 16 bits and writes it +// into bits 16..31 of VDATA, keeping bits 0..15. +public sealed class BufferLoadFormatD16HiDeviceTests(HeadlessVulkanFixture fixture) : IClassFixture +{ + private const uint Threads = 64; + private const uint Stride = 16; + private const uint Previous = 0xDEADBEEFu; + private const uint IdentitySwizzle = 4u | (5u << 3) | (6u << 6) | (7u << 9); + + public static IEnumerable Formats() + { + for (uint format = 1; format < 128; format++) + { + if (Gfx10UnifiedFormat.TryDecode(format, out var dataFormat, out var numberFormat) && + ((numberFormat is 4 or 5) || (dataFormat == 4 && numberFormat == 7))) + { + yield return [format]; + } + } + } + + [Theory] + [MemberData(nameof(Formats))] + public void HiHalfTakesTheConvertedComponentAndKeepsTheLowHalf(uint format) + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan, shaderInt64: true)) return; + Gfx10UnifiedFormat.TryDecode(format, out _, out var numberFormat); + var isFloat = numberFormat == 7; + var data = new byte[Threads * Stride]; + if (isFloat) + { + // Exactly representable in half, so the conversion has a single answer. + for (var index = 0; index < data.Length / 4; index++) + { + BitConverter.GetBytes(index * 0.5f - 7.0f).CopyTo(data, index * 4); + } + } + else + { + data = ImageTestHarness.Pattern((int)(Threads * Stride), seed: format); + } + + var component = Run(vulkan, data, format, "BufferLoadFormatX", preload: false); + var actual = Run(vulkan, data, format, "BufferLoadFormatD16HiX", preload: true); + for (var thread = 0; thread < Threads; thread++) + { + var value = BitConverter.ToUInt32(component, thread * (int)Stride); + var half = isFloat + ? BitConverter.HalfToUInt16Bits((Half)BitConverter.UInt32BitsToSingle(value)) + : value & 0xFFFFu; + var expected = (Previous & 0xFFFFu) | (half << 16); + Assert.True(expected == BitConverter.ToUInt32(actual, thread * (int)Stride), + $"format={format} thread={thread} expected=0x{expected:X8} actual=0x{BitConverter.ToUInt32(actual, thread * (int)Stride):X8}"); + } + } + + // v1 = v0 * 16; [v4 = previous;] v4 = load(s[8:11], v1); store v4 to s[4:7] at v1. + private static byte[] Run(HeadlessVulkan vulkan, byte[] data, uint format, string loadOpcode, bool preload) + { + var instructions = new List + { + Vop2(0, "VLshlrevB32", 1, Operand(4), Gen5Operand.Vector(0)), + }; + var pc = 4u; + if (preload) + { + instructions.Add(MoveVector(pc, 4, Previous)); + pc += 8; + } + + instructions.Add(BufferAccess(pc, loadOpcode, 8, 0, 1, vectorData: 4, offsetEnabled: true, vectorAddress: 1)); + pc += 8; + instructions.Add(BufferAccess(pc, "BufferStoreDword", 4, 0, 1, vectorData: 4, offsetEnabled: true, vectorAddress: 1)); + pc += 8; + instructions.Add(EndProgram(pc)); + var (plan, resources, layout) = Prepare(Program([.. instructions])); + var loadResource = MemoryAccessInfo.NoResource; + for (var index = 0; index < plan.Memory.Count; index++) + { + if (plan.Memory[index].Opcode == loadOpcode) loadResource = plan.Memory[index].Resource; + } + + resources.Info.Buffers[(int)loadResource].DescriptorFormat = format; + resources.Info.Buffers[(int)loadResource].DescriptorSwizzle = IdentitySwizzle; + var request = new ShaderCompileRequest(plan, resources, layout) { LocalSizeX = Threads }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + using var harness = new ImageTestHarness(vulkan); + using var runner = new LayoutComputeRunner(harness, request, shader.Spirv); + var input = runner.CreateBuffer(data); + var output = runner.CreateBuffer(Threads * Stride); + var buffers = new GpuBuffer[Math.Max(resources.Info.Buffers.Count, 2)]; + for (var index = 0; index < buffers.Length; index++) + { + buffers[index] = index == (int)loadResource ? input : output; + } + + var registers = new uint[256]; + registers[6] = Threads * Stride; + registers[10] = Threads * Stride; + registers[11] = (format << 12) | IdentitySwizzle; + harness.Run(() => runner.Dispatch(registers, new Dictionary { [DescriptorBindingKind.Buffers] = buffers }, 1)); + harness.AssertNoValidationMessages(); + return runner.ReadBack(output, 0, Threads * Stride); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/BufferStoreFormatD16HiDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/BufferStoreFormatD16HiDeviceTests.cs new file mode 100644 index 000000000..c436c05b8 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/BufferStoreFormatD16HiDeviceTests.cs @@ -0,0 +1,84 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.Libs.Tests.Gpu.Vulkan; + +// BUFFER_STORE_FORMAT_D16_HI_X stores the 16-bit component held in bits 16..31 of VDATA. +public sealed class BufferStoreFormatD16HiDeviceTests(HeadlessVulkanFixture fixture) : IClassFixture +{ + private const uint Threads = 64; + private const uint Stride = 16; + private const uint IdentitySwizzle = 4u | (5u << 3) | (6u << 6) | (7u << 9); + + // 16-bit UINT, SINT and FLOAT formats. + public static IEnumerable Formats() + { + for (uint format = 1; format < 128; format++) + { + if (Gfx10UnifiedFormat.TryDecode(format, out var dataFormat, out var numberFormat) && + dataFormat == 2 && numberFormat is 4 or 5 or 7) + { + yield return [format]; + } + } + } + + [Theory] + [MemberData(nameof(Formats))] + public void StoresTheHighHalfOfTheRegister(uint format) + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan, shaderInt64: true)) return; + + // The high half is 1.0 as a half float, and a plain 16-bit integer otherwise; the low half must not be stored. + const uint value = 0x3C00_1234u; + var output = Run(vulkan, format, value); + for (var thread = 0; thread < Threads; thread++) + { + var stored = BitConverter.ToUInt32(output, thread * (int)Stride); + Assert.True(stored == value >> 16, $"format={format} thread={thread} stored=0x{stored:X8}"); + } + } + + // v1 = v0 * 16; v4 = value; store_format_d16_hi_x v4 to s[8:11] at v1. + private static byte[] Run(HeadlessVulkan vulkan, uint format, uint value) + { + var instructions = new List + { + Vop2(0, "VLshlrevB32", 1, Operand(4), Gen5Operand.Vector(0)), + MoveVector(4, 4, value), + BufferAccess(12, "BufferStoreFormatD16HiX", 8, 0, 1, vectorData: 4, offsetEnabled: true, vectorAddress: 1), + EndProgram(20), + }; + var (plan, resources, layout) = Prepare(Program([.. instructions])); + var storeResource = MemoryAccessInfo.NoResource; + for (var index = 0; index < plan.Memory.Count; index++) + { + if (plan.Memory[index].Opcode == "BufferStoreFormatD16HiX") storeResource = plan.Memory[index].Resource; + } + + resources.Info.Buffers[(int)storeResource].DescriptorFormat = format; + resources.Info.Buffers[(int)storeResource].DescriptorSwizzle = IdentitySwizzle; + var request = new ShaderCompileRequest(plan, resources, layout) { LocalSizeX = Threads }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + using var harness = new ImageTestHarness(vulkan); + using var runner = new LayoutComputeRunner(harness, request, shader.Spirv); + var output = runner.CreateBuffer(Threads * Stride); + var buffers = new GpuBuffer[Math.Max(resources.Info.Buffers.Count, 1)]; + Array.Fill(buffers, output); + var registers = new uint[256]; + registers[10] = Threads * Stride; + registers[11] = (format << 12) | IdentitySwizzle; + harness.Run(() => runner.Dispatch(registers, new Dictionary { [DescriptorBindingKind.Buffers] = buffers }, 1)); + harness.AssertNoValidationMessages(); + return runner.ReadBack(output, 0, Threads * Stride); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/GlobalMemoryShaderTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/GlobalMemoryShaderTests.cs index 89425f5b1..f3c873cdf 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/GlobalMemoryShaderTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/GlobalMemoryShaderTests.cs @@ -169,6 +169,80 @@ public void FormattedLoads_CheckOnlySelectedComponentsOnTheDevice( Assert.Equal(expected, RunOnce(vulkan, shader, initial)); } + // A branch the plan cannot evaluate (its selector is a scalar load through a lane-derived + // offset) picks the V#: from memory when the selector is non-zero, otherwise one built from + // a lane value. The load reads whichever descriptor the registers hold when it runs, and + // each dword past the descriptor's size reads as zero. + [Theory] + [InlineData(1u, 0u, 40u)] + [InlineData(0u, 0u, 40u)] + [InlineData(1u, 32u, 40u)] + [InlineData(0u, 32u, 40u)] + [InlineData(0u, 8u, 12u)] + public void ControlFlowSelectedDescriptor_DwordLoadReadsTheSelectedBuffer(uint selector, uint offset, uint size) + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan, shaderInt64: true)) return; + + const int selectorOffset = 100; + const uint memoryBase = 16; + var initial = CreateInput(); + WriteWord(initial, selectorOffset, selector); + WriteWord(initial, DescriptorOffset, (uint)((BufferAddress + memoryBase) & uint.MaxValue)); + WriteWord(initial, DescriptorOffset + 4, (uint)((BufferAddress + memoryBase) >> 32)); + WriteWord(initial, DescriptorOffset + 8, size); + WriteWord(initial, DescriptorOffset + 12, 0); + + var words = new List + { + // v_readfirstlane_b32 s20, v0: a lane-derived offset the plan cannot resolve. + 0x7E000000u | (20u << 17) | (2u << 9) | 256u, + // s_buffer_load_dword s21, s[0:3], s20 offset:selectorOffset + 0xF4000000u | (8u << 18) | (21u << 6), (20u << 25) | selectorOffset, + 0xBF8CC07F, + // s_cmp_eq_u32 s21, 0 ; s_cbranch_scc1 +4 (to the lane-built descriptor) + 0xBF068015, + 0xBF850000u | 4, + // s_buffer_load_dwordx4 s[16:19], s[0:3], s20 offset:DescriptorOffset + 0xF4000000u | (10u << 18) | (16u << 6), (20u << 25) | DescriptorOffset, + 0xBF8CC07F, + // s_branch +7 (to the access) + 0xBF820000u | 7, + // v_add_nc_u32 v1, BufferAddress.lo, v0 ; v_readfirstlane_b32 s16, v1 + 0x4A0200FF, (uint)(BufferAddress & uint.MaxValue), + 0x7E000000u | (16u << 17) | (2u << 9) | 257u, + // s_mov_b32 s17, BufferAddress.hi ; s_mov_b32 s18, size ; s_mov_b32 s19, 0 + 0xBE910382, + 0xBE9203FF, size, + 0xBE930380, + // buffer_load_dwordx3 v[4:6], v0, s[16:19], 0 offset:offset + 0xE0000000u | (15u << 18) | offset, 0x80040400, + // buffer_store_dwordx3 v[4:6], v0, s[0:3], 0 offset:MemoryOffset + 0xE0000000u | (31u << 18) | MemoryOffset, 0x80000400, + 0xBF810000, + }; + var program = DecodeProgram(words); + var listing = string.Join(' ', program.Instructions.Select(instruction => instruction.Opcode)); + var load = program.Instructions.SingleOrDefault(instruction => instruction.Opcode == "BufferLoadDwordx3") + ?? throw new Xunit.Sdk.XunitException(listing); + Assert.Equal(3u, Assert.IsType(load.Control).DwordCount); + Assert.True(program.Instructions.Any(instruction => instruction.Opcode == "BufferStoreDwordx3"), listing); + var shader = CompileProgram(program, BaseScalars()); + Assert.Contains(shader.Plan.Memory.Entries, memory => memory.Pc == load.Pc && memory.DeviceDescriptor); + Assert.DoesNotContain(shader.Plan.Info.Buffers, buffer => buffer.FirstUsePc == load.Pc); + + var sourceBase = selector != 0 ? memoryBase : 0u; + var expected = (byte[])initial.Clone(); + for (var index = 0u; index < 3; index++) + { + var at = offset + index * 4; + WriteWord(expected, MemoryOffset + (int)index * 4, + at + 4 <= size ? ReadWord(initial, (int)(sourceBase + at)) : 0u); + } + + Assert.Equal(expected, RunOnce(vulkan, shader, initial)); + } + [Theory] [InlineData(1u, 188u, true)] [InlineData(2u, 184u, true)] diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/RenderTargetFormatSupportDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/RenderTargetFormatSupportDeviceTests.cs new file mode 100644 index 000000000..e5235287d --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/RenderTargetFormatSupportDeviceTests.cs @@ -0,0 +1,41 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Images; +using SharpEmu.Libs.Tests.Gpu.Images; +using Silk.NET.Vulkan; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Vulkan; + +// Optional Vulkan formats the guest can bind as colour targets: the device must offer them as +// colour attachments that can also be sampled, or the target cannot be created. +public sealed class RenderTargetFormatSupportDeviceTests(HeadlessVulkanFixture fixture) : IClassFixture +{ + [Theory] + [InlineData(ChannelLayout.Bits8, ChannelType.SNorm)] + [InlineData(ChannelLayout.Bits8, ChannelType.SInt)] + [InlineData(ChannelLayout.Bits8_8, ChannelType.SNorm)] + [InlineData(ChannelLayout.Bits8_8, ChannelType.UInt)] + [InlineData(ChannelLayout.Bits8_8, ChannelType.SInt)] + [InlineData(ChannelLayout.Bits16_16, ChannelType.SNorm)] + [InlineData(ChannelLayout.Bits8_8_8_8, ChannelType.SNorm)] + [InlineData(ChannelLayout.Bits16_16_16_16, ChannelType.SNorm)] + [InlineData(ChannelLayout.Bits11_11_10, ChannelType.UNorm)] + [InlineData(ChannelLayout.Bits8, ChannelType.Srgb)] + [InlineData(ChannelLayout.Bits8_8, ChannelType.Srgb)] + public void TheHostFormatIsASampledColourAttachment(ChannelLayout layout, ChannelType type) + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan)) return; + var host = TextureTransferLayout.RenderTargetFormat(layout, type, ChannelOrder.Standard).HostFormat; + + vulkan.Vk.GetPhysicalDeviceFormatProperties(vulkan.Physical, host, out var properties); + + const FormatFeatureFlags Required = FormatFeatureFlags.ColorAttachmentBit | FormatFeatureFlags.SampledImageBit | + FormatFeatureFlags.TransferSrcBit | FormatFeatureFlags.TransferDstBit; + Assert.True( + (properties.OptimalTilingFeatures & Required) == Required, + $"{host} for layout={layout} type={type} lacks {Required & ~properties.OptimalTilingFeatures} on this device."); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/TessellationWaveDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/TessellationWaveDeviceTests.cs index e987888ad..ca119dc75 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/TessellationWaveDeviceTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/TessellationWaveDeviceTests.cs @@ -55,6 +55,50 @@ public void MergedHull_BackAddressIsUploadedAndSurvivesLocalUserRegisterReuse() harness.AssertNoValidationMessages(); } + // Every hull lane reads the LDS word a wave 0 local lane wrote, and every local lane + // keeps the v13 its local half left. With two input and four output control points on + // 32 patches the 64 local lanes fill wave 0, so wave 1 skips the local half and meets + // wave 0 at the barrier. Four of each on 63 patches is a shape real hull shaders use. + [Theory] + [InlineData(2u, 32u)] + [InlineData(4u, 63u)] + public void CombinedHull_HullHalfReadsLocalWritesAcrossWavesAndRegistersTheLocalHalfLeft(uint inputPoints, uint patches) + { + var vulkan = fixture.Vulkan; + if (!GatePrerequisites.Ready(vulkan, shaderInt64: true)) return; + var entry = SharpEmu.ShaderCompiler.Tests.Gen5TessellationTests.CombinedHullEntry; + var program = Gen5TessellationLowering.PrepareCombinedHull( + SharpEmu.ShaderCompiler.Tests.DecodeHarness.Decode(SharpEmu.ShaderCompiler.Tests.Gen5TessellationTests.CombinedHullWords)); + var plan = ShaderResourcePlan.Extract(program, ShaderStage.Compute, Hash, 8, 8, waveSize: 64); + var resources = ResourceMaterializer.ApplyTo(plan, ResourceSpecialization.Default(plan.Info)); + var layout = BindingLayout.Allocate(resources.Info, BindingLayout.CollectUserDataRegisters(program, 8, 8), + false, false, false, usesTessellationData: true); + var request = new ShaderCompileRequest(plan, resources, layout) + { + LocalSizeX = (patches * 4 + 63) & ~63u, WaveSize = 64, CooperativeWave64Workgroup = true, LocalDataShareDwords = 256, + TessellationHull = new(inputPoints, 4, patches, entry + 4), + }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + SharpEmu.ShaderCompiler.Tests.Gen5MipStatisticsTests.ValidateWhenAvailable(shader.Spirv); + using var harness = new ImageTestHarness(vulkan); + using var runner = new LayoutComputeRunner(harness, request, shader.Spirv); + var buffer = runner.CreateBuffer(2048); + var scalar = new uint[16]; scalar[10] = 2048; + var data = new uint[Gen5TessellationData.DwordCount]; + data[Gen5TessellationData.PatchCount] = patches; + data[Gen5TessellationData.VertexOffset] = 11; + harness.Run(() => runner.Dispatch(scalar, + new Dictionary { [DescriptorBindingKind.Buffers] = [buffer] }, 1, + tessellationData: data)); + var bytes = runner.ReadBack(buffer, 0, 2048); + for (var lane = 0; lane < patches * 4; lane++) + { + Assert.Equal((uint)(lane & 63) + 11, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(lane * 8))); + if (lane < patches * inputPoints) Assert.Equal(37u, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(lane * 8 + 4))); + } + harness.AssertNoValidationMessages(); + } + [Theory] [InlineData(128u)] [InlineData(256u)] diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/Wave64HalfMaskDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/Wave64HalfMaskDeviceTests.cs index 04ef2d2eb..5451ea7a3 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/Wave64HalfMaskDeviceTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/Wave64HalfMaskDeviceTests.cs @@ -75,7 +75,8 @@ protected uint[] Run(uint localDataShareDwords = 0, uint sizeX = 8, uint sizeY = if (HostSubgroup32 && laneLocal is { } oneLanePerInvocation) { var halfWavesEnabled = Environment.GetEnvironmentVariable("SHARPEMU_WAVE64_LANE_LOCAL") != "0"; - Assert.Equal(oneLanePerInvocation && halfWavesEnabled ? sizeX : (threads + 63) / 64 * 32, LocalSizeX(shader.Spirv)); + var paired = Gen5SpirvTranslator.PairsWave64Lanes(Environment.GetEnvironmentVariable("SHARPEMU_WAVE64_PAIRED"), threads); + Assert.Equal((oneLanePerInvocation && halfWavesEnabled) || !paired ? sizeX : (threads + 63) / 64 * 32, LocalSizeX(shader.Spirv)); } Assert.NotNull(fixture.Vulkan); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/WaveLaneTransferDeviceTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/WaveLaneTransferDeviceTests.cs index 1cdf6ead8..26eb00af8 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/WaveLaneTransferDeviceTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Vulkan/WaveLaneTransferDeviceTests.cs @@ -231,6 +231,9 @@ private void Run(uint waveSize, uint selector, bool disableExecution, bool write { var vulkan = fixture.Vulkan; if (!GatePrerequisites.Ready(vulkan, shaderInt64: true)) return; + // A one-wave workgroup runs as two host subgroups (Gen5SpirvTranslator.PairsWave64Lanes); two waves are paired. + var waves = pairedLanes ? 2u : 1u; + var threads = waves * waveSize; var instructions = new List(); uint programCounter = 0; void Add(Gen5ShaderInstruction instruction) @@ -274,7 +277,7 @@ void Add(Gen5ShaderInstruction instruction) var (plan, resources, layout) = Prepare(Program([.. instructions])); var request = new ShaderCompileRequest(plan, resources, layout) { - LocalSizeX = 8, LocalSizeY = waveSize / 8, ThreadCountX = 8, ThreadCountY = waveSize / 8, + LocalSizeX = 8, LocalSizeY = threads / 8, ThreadCountX = 8, ThreadCountY = threads / 8, WaveSize = waveSize, HostComputeSubgroup32 = pairedLanes, HostWave64Supported = false, }; @@ -288,7 +291,7 @@ void Add(Gen5ShaderInstruction instruction) if ((instruction & 0xffff) == 16 && BinaryPrimitives.ReadUInt32LittleEndian(shader.Spirv.AsSpan(offset + 8)) == 17) { - Assert.Equal(32u, BinaryPrimitives.ReadUInt32LittleEndian(shader.Spirv.AsSpan(offset + 12))); + Assert.Equal(32u * waves, BinaryPrimitives.ReadUInt32LittleEndian(shader.Spirv.AsSpan(offset + 12))); found = true; } offset += checked((int)(instruction >> 16) * 4); @@ -297,17 +300,17 @@ void Add(Gen5ShaderInstruction instruction) } using var harness = new ImageTestHarness(vulkan); using var runner = new LayoutComputeRunner(harness, request, shader.Spirv); - var output = runner.CreateBuffer(256); + var output = runner.CreateBuffer(threads * 4); var registers = new uint[256]; - registers[6] = 256; + registers[6] = threads * 4; harness.Run(() => runner.Dispatch(registers, new Dictionary { [DescriptorBindingKind.Buffers] = [output] }, 1)); - var bytes = runner.ReadBack(output, 0, 256); + var bytes = runner.ReadBack(output, 0, threads * 4); var selectedLane = selector % waveSize; - for (uint lane = 0; lane < waveSize; lane++) + for (uint lane = 0; lane < threads; lane++) { var expected = savedLane ? (overwriteVector ? 0x87654321u : 0x12345678u) - : writeLane ? (lane == selectedLane ? 0x12345678u : 1000 + lane) : 1000 + selectedLane; + : writeLane ? (lane % waveSize == selectedLane ? 0x12345678u : 1000 + lane) : 1000 + lane / waveSize * waveSize + selectedLane; Assert.Equal(expected, BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan((int)lane * 4))); } harness.AssertNoValidationMessages(); diff --git a/tests/SharpEmu.Libs.Tests/PlayGo/PlayGoExportsTests.cs b/tests/SharpEmu.Libs.Tests/PlayGo/PlayGoExportsTests.cs index 4405a4ae4..820dd67f6 100644 --- a/tests/SharpEmu.Libs.Tests/PlayGo/PlayGoExportsTests.cs +++ b/tests/SharpEmu.Libs.Tests/PlayGo/PlayGoExportsTests.cs @@ -27,6 +27,7 @@ public sealed class PlayGoExportsTests : IDisposable private const ulong HandleAddress = MemoryBase + 0x200; private const ulong ChunkIdsAddress = MemoryBase + 0x300; private const ulong LociAddress = MemoryBase + 0x400; + private const ulong ProgressAddress = MemoryBase + 0x500; private readonly string? _originalApp0Root; private readonly string? _originalDisableMetadataFallback; @@ -212,6 +213,103 @@ public void GetLocus_AllEntriesSentinel_DoesNotReadChunksOrWriteLoci() Assert.Equal(new byte[] { 0xA5 }, ReadLoci(1)); } + [Fact] + public void GetLocus_PgmChunkCount_ReportsAllChunksAndStaysPermissivePastThem() + { + WritePgm(3); + var handle = InitializeAndOpen(); + + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, GetLocus(handle, [0, 1, 2])); + Assert.Equal(new byte[] { LocusLocalFast, LocusLocalFast, LocusLocalFast }, ReadLoci(3)); + + // Assumed ids are not authoritative: an id past the count is not rejected. + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, GetLocus(handle, [9])); + } + + [Fact] + public void GetLocus_ChunkDefinitionsTakePrecedenceOverPgm() + { + WritePgm(2); + File.WriteAllText( + Path.Combine(_app0Root, "playgo-chunkdefs.xml"), + ""); + var handle = InitializeAndOpen(); + + // The title's own chunk list stays exact: the pgm count does not add chunk 1. + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, GetLocus(handle, [5])); + Assert.Equal(BadChunkId, GetLocus(handle, [1])); + Assert.Equal((0ul, 0ul), GetProgress(handle, [5])); + } + + [Fact] + public void GetLocus_PakChunksTakePrecedenceOverPgm() + { + WritePgm(2); + File.WriteAllBytes(Path.Combine(_app0Root, "pakchunk7-PS5.pak"), []); + var handle = InitializeAndOpen(); + + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, GetLocus(handle, [0, 7])); + Assert.Equal(BadChunkId, GetLocus(handle, [1])); + } + + [Fact] + public void GetProgress_PgmChunks_ReportsAFullyInstalledTitle() + { + WritePgm(3); + var handle = InitializeAndOpen(); + + Assert.Equal((1ul, 1ul), GetProgress(handle, [0, 1, 2])); + } + + [Fact] + public void GetProgress_WithoutPgm_ReportsZeroOfZero() + { + var handle = InitializeAndOpen(); + + Assert.Equal((0ul, 0ul), GetProgress(handle, [0])); + } + + [Theory] + [InlineData("BAD!", 4u)] + [InlineData("DMGP", 0u)] + public void GetLocus_InvalidPgm_FallsBackToAuthoritativeDefault(string magic, uint count) + { + WritePgm(count, magic); + var handle = InitializeAndOpen(); + + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, GetLocus(handle, [0])); + Assert.Equal(BadChunkId, GetLocus(handle, [1])); + } + + [Fact] + public void GetLocus_TruncatedPgm_FallsBackToAuthoritativeDefault() + { + var cache = Directory.CreateDirectory(Path.Combine(_app0Root, "cache_ps5")); + File.WriteAllBytes(Path.Combine(cache.FullName, "playgo.pgm"), "DMGP"u8.ToArray()); + var handle = InitializeAndOpen(); + + Assert.Equal(BadChunkId, GetLocus(handle, [1])); + } + + [Fact] + public void GetLocus_PakDiscoveryStillAppliesWithoutPgmOrSidecars() + { + File.WriteAllBytes(Path.Combine(_app0Root, "pakchunk4-PS5.pak"), []); + var handle = InitializeAndOpen(); + + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, GetLocus(handle, [0, 4])); + Assert.Equal(BadChunkId, GetLocus(handle, [1])); + } + + private void WritePgm(uint chunkCount, string magic = "DMGP") + { + var header = new byte[0x14]; + System.Text.Encoding.ASCII.GetBytes(magic, header); + BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(0x10), chunkCount); + var cache = Directory.CreateDirectory(Path.Combine(_app0Root, "cache_ps5")); + File.WriteAllBytes(Path.Combine(cache.FullName, "playgo.pgm"), header); + } + public void Dispose() { PlayGoExports.ResetForTests(); @@ -261,6 +359,16 @@ private int GetLocus(uint handle, ushort[] chunkIds, byte? fill = null) return PlayGoExports.PlayGoGetLocus(_ctx); } + private (ulong Installed, ulong Total) GetProgress(uint handle, ushort[] chunkIds) + { + WriteChunkIds(chunkIds); + SetGetLocusArguments(handle, ChunkIdsAddress, (uint)chunkIds.Length, ProgressAddress); + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, PlayGoExports.PlayGoGetProgress(_ctx)); + var progress = new byte[sizeof(ulong) * 2]; + Assert.True(_memory.TryRead(ProgressAddress, progress)); + return (BinaryPrimitives.ReadUInt64LittleEndian(progress), BinaryPrimitives.ReadUInt64LittleEndian(progress.AsSpan(sizeof(ulong)))); + } + private void WriteChunkIds(ushort[] chunkIds) { var bytes = new byte[chunkIds.Length * sizeof(ushort)]; diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/BdaSweepUnmapTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/BdaSweepUnmapTests.cs new file mode 100644 index 000000000..1c6f11019 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/BdaSweepUnmapTests.cs @@ -0,0 +1,74 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later +using System.Reflection; +using System.Runtime.CompilerServices; +using SharpEmu.HLE.GpuMemory; +using SharpEmu.Libs.Tests.Gpu.Buffers; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.Libs.Tests.Gpu.Vulkan; +using SharpEmu.Libs.VideoOut; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Images.ImageCacheTestSupport; + +namespace SharpEmu.Libs.Tests.VideoOut; + +// Launches 341/342 (02.002, ezo40) failed fast in RecordSlicePrologue -> PrepareBda -> FlushSweepUploads reading a +// buffer over memory the guest had unmapped. A guest unmap marks the buffers it covers CPU-dirty, so any device-address +// sweep that still includes the range afterwards reads memory that is gone. +[Collection(SchedulingStateCollection.Name)] +public sealed class BdaSweepUnmapTests(HeadlessVulkanFixture fixture) : IClassFixture +{ + private static readonly Type SegmentType = typeof(VulkanVideoPresenter).GetNestedType("SliceSegment", BindingFlags.NonPublic)!; + private const BindingFlags Members = PresenterUnderTest.InstanceMembers; + + // A worker captured the GPU spans for a slice's sweep, the render thread then ran the guest munmap from the relay + // between items, and the join swept the captured spans. + [Fact] + public void ASegmentJoinedAfterAGuestUnmapDoesNotSweepTheUnmappedRange() + { + if (!GatePrerequisites.Ready(fixture.Vulkan)) return; + using var fatal = new FatalScope(); + using var p = new PresenterUnderTest(fixture.Vulkan!); + var h = p.Harness; + GuestGpuMemoryHook.Attach(h.Gpu); + try + { + var kept = h.MapBacked(0x20000, ReadWrite); + var gone = h.MapBacked(0x20000, ReadWrite); + var (keptBuffer, keptOffset) = p.Run(() => h.Cache.ObtainBuffer(kept, 0x8000, isWritten: false)); + p.Run(() => h.Cache.ObtainBuffer(gone, 0x8000, isWritten: false)); + + // What PrepareDeviceAddresses records on a worker. + var segment = Activator.CreateInstance(SegmentType, nonPublic: true)!; + var requests = SegmentType.GetField("Requests")!.GetValue(segment)!; + var host = RuntimeHelpers.GetUninitializedObject(PresenterUnderTest.RecordingHostType); + var spans = PresenterUnderTest.RecordingHostType.GetMethod("DeviceAddressSpans", Members)!.Invoke(host, [h.Gpu])!; + var mapping = PresenterUnderTest.RecordingHostType.GetField("_bdaSpanMapping", Members)!.GetValue(host)!; + requests.GetType().GetField("NeedsBdaSweep")!.SetValue(requests, true); + requests.GetType().GetField("BdaSpans")!.SetValue(requests, spans); + requests.GetType().GetField("BdaMapping")!.SetValue(requests, mapping); + + // The guest unmaps before the render thread joins the segment. + h.Gpu.Unregister(gone, 0x20000); + Assert.True(h.Cache.HasCpuDirtyPages(gone, 0x8000)); + Assert.True(h.Memory.TryUnmapBacked(gone, 0x20000)); + Assert.False(h.Memory.TryRead(gone, new byte[16]), "unmapped read"); + + // The mapping that stays is still swept. + h.Write(kept + 0x4000, ImageTestHarness.Pattern(0x20, 3)); + Assert.True(h.Store.MarkCpuWrite(kept + 0x4000, 0x20)); + + p.Run(() => p.InvokeMethod("RecordSlicePrologue", requests)); + + Assert.Empty(fatal.Messages); + Assert.False(h.Cache.HasCpuDirtyPages(kept, 0x8000), "kept swept"); + Assert.Equal(ImageTestHarness.Pattern(0x20, 3), h.ReadBack(keptBuffer, keptOffset + 0x4000, 0x20)); + } + finally + { + GuestGpuMemoryHook.Attach(null); + h.Shutdown(); + } + } +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/BindlessHeapRunTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/BindlessHeapRunTests.cs index 2b7b3d6c1..3e33a39f2 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/BindlessHeapRunTests.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/BindlessHeapRunTests.cs @@ -73,7 +73,7 @@ public void RunsPartitionSortedIndexesWithinTheLimits(int seed, uint recordBytes private const ulong MemoryBase = 0x10000; // Guest memory as a byte array from MemoryBase, and one heap in it; every visit is kept with its words. - private sealed class FakeHeap(byte[] memory, ulong heapBase, uint records, uint[] indexes, bool sampler) + private sealed class FakeHeap(byte[] memory, ulong heapBase, uint records, uint[] indexes, bool sampler, bool r128 = false) : VulkanVideoPresenter.IHeapRunVisitor { public ulong Base = heapBase; @@ -84,9 +84,12 @@ private sealed class FakeHeap(byte[] memory, ulong heapBase, uint records, uint[ public readonly List<(int Position, uint[] Words)> Visits = new(); // Runs on each visit; true means the visit resolved. public Func OnVisit = _ => false; - public readonly uint RecordBytes = sampler ? BindlessHeap.SamplerRecordBytes : BindlessHeap.ImageRecordBytes; + public readonly uint RecordBytes = new BindlessHeapDescriptor(sampler, 0, 0, 0, 0, r128).DescriptorBytes; + // The records of a table are larger than the descriptor each one starts with. + private uint? _stride; + public uint Stride { get => _stride ?? RecordBytes; set => _stride = value; } - public BindlessHeapDescriptor Heap(bool samplerHeap) => new(samplerHeap, Base, Records, RecordBytes); + public BindlessHeapDescriptor Heap(bool samplerHeap) => new(samplerHeap, Base, Records, Stride, 0, r128); public bool TryRead(ulong address, Span destination) { @@ -100,7 +103,7 @@ public int ReadRecord(int position, Span words) var index = indexes[position]; var count = (int)(RecordBytes / sizeof(uint)); return Base != 0 && index < Records && - Read(Base + (ulong)index * RecordBytes, System.Runtime.InteropServices.MemoryMarshal.AsBytes(words[..count])) ? count : 0; + Read(Base + (ulong)index * Stride, System.Runtime.InteropServices.MemoryMarshal.AsBytes(words[..count])) ? count : 0; } public bool Visit(int position, ReadOnlySpan words) @@ -114,7 +117,7 @@ public uint[] RecordWords(uint index) { var words = new uint[RecordBytes / sizeof(uint)]; return Base != 0 && index < Records && - Read(Base + (ulong)index * RecordBytes, System.Runtime.InteropServices.MemoryMarshal.AsBytes(words.AsSpan())) ? words : []; + Read(Base + (ulong)index * Stride, System.Runtime.InteropServices.MemoryMarshal.AsBytes(words.AsSpan())) ? words : []; } private bool Read(ulong address, Span destination) @@ -159,6 +162,49 @@ public void RunsVisitEveryEntryOnceInOrderWithItsRecordWords(bool sampler) Assert.Equal(0, heap.RecordReads); } + // The descriptors of a heap view are a record stride apart (a table of 440-byte records, each starting with its T#): + // a run reads from the first record's descriptor to the last one's, and each entry takes its own record's words. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void RunsOverATablesRecordsReadEachRecordsDescriptor(bool sampler) + { + var memory = Pattern(0x40000, 17); + uint[] indexes = [0, 1, 2, 3, 5, 5, 8, 40, 47, 48]; + var heap = new FakeHeap(memory, MemoryBase + 0x40, 49, indexes, sampler) { Stride = 440 }; + Visit(heap, indexes, sampler, new byte[VulkanVideoPresenter.HeapRunMaxBytes]); + Assert.Equal(Enumerable.Range(0, indexes.Length), heap.Visits.Select(visit => visit.Position)); + for (var at = 0; at < indexes.Length; at++) + { + Assert.Equal(heap.RecordWords(indexes[at]), heap.Visits[at].Words); + } + + // Records 0..8 are one run; 40 and 47 are each more than the gap from the record before. + Assert.Equal(3, heap.RunReads); + Assert.Equal(0, heap.RecordReads); + } + + // A view of 16-byte T#s (R128) takes the four words of each record's descriptor, in a table and in a heap of packed + // descriptors, where the records are 16 bytes apart. + [Theory] + [InlineData(440u)] + [InlineData(16u)] + public void RunsOverR128DescriptorsReadSixteenBytesOfEachRecord(uint stride) + { + var memory = Pattern(0x40000, 23); + uint[] indexes = [0, 1, 2, 3, 5, 8, 47, 48]; + var heap = new FakeHeap(memory, MemoryBase + 0x40, 49, indexes, sampler: false, r128: true) { Stride = stride }; + Visit(heap, indexes, false, new byte[VulkanVideoPresenter.HeapRunMaxBytes]); + Assert.Equal(Enumerable.Range(0, indexes.Length), heap.Visits.Select(visit => visit.Position)); + for (var at = 0; at < indexes.Length; at++) + { + Assert.Equal(4, heap.Visits[at].Words.Length); + Assert.Equal(heap.RecordWords(indexes[at]), heap.Visits[at].Words); + } + + Assert.Equal(0, heap.RecordReads); + } + // A resolve may land bytes over later records of its run: the entries after it read them after it. [Fact] public void AResolveRereadsTheRestOfItsRun() diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/BindlessHeapViewTableTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/BindlessHeapViewTableTests.cs new file mode 100644 index 000000000..f341b6bb4 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/BindlessHeapViewTableTests.cs @@ -0,0 +1,236 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.VideoOut; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +// The runs of set-1 elements the heap views of the draws hold. A game can read several tables in one frame (terrain +// tile records, material records), each through its own program: every view needs elements no other view holds. +public sealed class BindlessHeapViewTableTests +{ + private static readonly Action Unreleased = region => + Assert.Fail($"A view gave its elements up: first={region.View.First}."); + + private static BindlessHeapDescriptor Table(ulong address, uint records, uint stride = 440, uint immediate = 0) => + new(false, address, records, stride, immediate); + + [Fact] + public void ViewsOfDifferentHeapsAndDescriptorsHoldDifferentElements() + { + var table = new BindlessHeapViewTable(1000); + + var terrain = table.Acquire(Table(0x1000, 49), tick: 1, completedTick: 0, Unreleased, out _)!; + var masks = table.Acquire(Table(0x1000, 49, immediate: 64), tick: 1, completedTick: 0, Unreleased, out _)!; + var materials = table.Acquire(Table(0x9000, 200, stride: 136, immediate: 48), tick: 1, completedTick: 0, Unreleased, out _)!; + + Assert.Equal(new HeapView(0, 440, 0, 49), terrain.View); + Assert.Equal(new HeapView(49, 440, 64, 49), masks.View); + Assert.Equal(new HeapView(98, 136, 48, 200), materials.View); + Assert.Same(terrain, table.Find(0)); + Assert.Same(terrain, table.Find(48)); + Assert.Same(masks, table.Find(49)); + Assert.Same(materials, table.Find(297)); + Assert.Null(table.Find(298)); + Assert.True(masks.Holds(97)); + Assert.False(masks.Holds(98)); + Assert.False(masks.Holds(48)); + } + + // The same view of a later draw reads the same elements: the records the shaders marked stay resolved. + // A packed heap is one view whatever immediate a shader reads it at: the whole offset picks the descriptor. A raw + // V# (stride 0) counts bytes, so its view has a record per descriptor. A record view at the same field one record + // further on is the same view. + [Fact] + public void ReadsOfOneHeapAtSeveralImmediatesShareOneView() + { + var table = new BindlessHeapViewTable(1000); + + var packed = table.Acquire(Table(0x1000, 100, stride: 32), tick: 1, completedTick: 0, Unreleased, out _)!; + Assert.Same(packed, table.Acquire(Table(0x1000, 100, stride: 32, immediate: 32), tick: 1, completedTick: 0, Unreleased, out _)); + Assert.Same(packed, table.Acquire(Table(0x1000, 100, stride: 32, immediate: 64), tick: 1, completedTick: 0, Unreleased, out _)); + Assert.Equal(new HeapView(0, 32, 0, 100), packed.View); + + var raw = table.Acquire(Table(0x8000, 3200, stride: 0, immediate: 96), tick: 1, completedTick: 0, Unreleased, out _)!; + Assert.Same(raw, table.Acquire(Table(0x8000, 3200, stride: 0), tick: 1, completedTick: 0, Unreleased, out _)); + Assert.Equal(new HeapView(100, 32, 0, 100), raw.View); + + var records = table.Acquire(Table(0x9000, 49, immediate: 64), tick: 1, completedTick: 0, Unreleased, out _)!; + Assert.Same(records, table.Acquire(Table(0x9000, 49, immediate: 440 + 64), tick: 1, completedTick: 0, Unreleased, out _)); + Assert.Equal(new HeapView(200, 440, 64, 49), records.View); + } + + [Fact] + public void AViewReadAgainKeepsItsElements() + { + var table = new BindlessHeapViewTable(1000); + var first = table.Acquire(Table(0x1000, 49), tick: 1, completedTick: 0, Unreleased, out _)!; + + var again = table.Acquire(Table(0x1000, 49), tick: 7, completedTick: 5, Unreleased, out _); + + Assert.Same(first, again); + Assert.Equal(7ul, again!.LastUsedTick); + Assert.Single(table.Regions); + } + + // A table the guest allocates for each frame is the same records at another address: the moved table takes over the run + // of the old one once no pending command reads it, so its elements stay resolved (the caller compares them with the + // records at the new address). While a command still reads the old one, the moved table gets free elements. + [Fact] + public void AMovedTableTakesOverTheRunOfTheOldOne() + { + var table = new BindlessHeapViewTable(1000); + var old = table.Acquire(Table(0x1000, 23), tick: 1, completedTick: 0, Unreleased, out var moved)!; + Assert.False(moved); + + var pending = table.Acquire(Table(0x5000, 23), tick: 2, completedTick: 0, Unreleased, out moved)!; + Assert.False(moved); + Assert.NotSame(old, pending); + Assert.Equal(23u, pending.View.First); + + var next = table.Acquire(Table(0x9000, 23), tick: 3, completedTick: 1, Unreleased, out moved)!; + Assert.True(moved); + Assert.Same(old, next); + Assert.Equal((0x9000ul, 0u, 3ul), (next.Heap.Base, next.View.First, next.LastUsedTick)); + Assert.Equal(2, table.Regions.Count); + // The old address is a new view when a draw comes back to it. + var back = table.Acquire(Table(0x1000, 23), tick: 3, completedTick: 1, Unreleased, out moved)!; + Assert.False(moved); + Assert.Equal(46u, back.View.First); + } + + // A view of 16-byte T#s (R128) and a view of 32-byte T#s over records of one shape resolve different descriptors: + // neither takes over the other's run. + [Fact] + public void AnR128ViewDoesNotTakeOverTheRunOfAViewOfWholeDescriptors() + { + var table = new BindlessHeapViewTable(1000); + var whole = table.Acquire(Table(0x1000, 23), tick: 1, completedTick: 0, Unreleased, out _)!; + + var r128 = table.Acquire(Table(0x5000, 23) with { R128 = true }, tick: 3, completedTick: 1, Unreleased, out var moved)!; + Assert.False(moved); + Assert.NotSame(whole, r128); + Assert.Equal(23u, r128.View.First); + + var next = table.Acquire(Table(0x9000, 23) with { R128 = true }, tick: 5, completedTick: 3, Unreleased, out moved)!; + Assert.True(moved); + Assert.Same(r128, next); + } + + // The records of a run are read again in guest memory where its heap holds their descriptors, each of the size the + // heap's reads take. Material records can hold 16-byte T#s several hundred bytes in: read as 32 bytes, + // the next T# followed each one, and the record lost its view the first time it was read again. + [Fact] + public void ARunsDescriptorsAreTheSizeItsHeapReads() + { + var table = new BindlessHeapViewTable(1000); + var r128 = table.Acquire(Table(0x1000, 257, 1016, 468) with { R128 = true }, tick: 1, completedTick: 0, Unreleased, out _)!; + var whole = table.Acquire(Table(0x1000, 257, 1016, 468), tick: 1, completedTick: 0, Unreleased, out _)!; + + Assert.Equal(new BindlessHeapDescriptor(false, 0x1000 + 468, 257, 1016, 0, R128: true), r128.Descriptors); + Assert.Equal(BindlessHeap.R128RecordBytes, r128.Descriptors.DescriptorBytes); + Assert.Equal(new BindlessHeapDescriptor(false, 0x1000 + 468, 257, 1016), whole.Descriptors); + Assert.Equal(BindlessHeap.ImageRecordBytes, whole.Descriptors.DescriptorBytes); + } + + // With no free elements left, a view takes those of the view used longest ago, but only one whose commands have all + // completed: a pending command still reads its elements. + [Fact] + public void AFullTableGivesANewViewTheElementsOfTheOldestCompletedOne() + { + var table = new BindlessHeapViewTable(100); + var oldest = table.Acquire(Table(0x1000, 40), tick: 1, completedTick: 0, Unreleased, out _)!; + var newer = table.Acquire(Table(0x2000, 40, immediate: 64), tick: 2, completedTick: 0, Unreleased, out _)!; + var released = new List(); + + // Nothing has completed: the view has no elements, and nothing is taken. + Assert.Null(table.Acquire(Table(0x3000, 40, immediate: 128), tick: 3, completedTick: 0, released.Add, out _)); + Assert.Empty(released); + + var moved = table.Acquire(Table(0x3000, 40, immediate: 128), tick: 3, completedTick: 1, released.Add, out _)!; + + Assert.Equal([oldest], released); + Assert.Equal(new HeapView(0, 440, 128, 40), moved.View); + Assert.Same(moved, table.Find(0)); + Assert.Same(newer, table.Find(40)); + Assert.Equal(2, table.Regions.Count); + // The view that gave its elements up is a new view when it is read again. + var back = table.Acquire(Table(0x1000, 20), tick: 4, completedTick: 1, Unreleased, out _)!; + Assert.Equal(80u, back.View.First); + } + + // A view larger than the gap between two others takes the elements of as many completed views as it needs. + [Fact] + public void ALargeViewTakesSeveralCompletedViews() + { + var table = new BindlessHeapViewTable(100); + var a = table.Acquire(Table(0x1000, 30), tick: 1, completedTick: 0, Unreleased, out _)!; + var b = table.Acquire(Table(0x2000, 30), tick: 2, completedTick: 0, Unreleased, out _)!; + var c = table.Acquire(Table(0x3000, 30), tick: 3, completedTick: 0, Unreleased, out _)!; + var released = new List(); + + var large = table.Acquire(Table(0x4000, 60), tick: 4, completedTick: 3, released.Add, out _)!; + + Assert.Equal([a, b], released); + Assert.Equal(0u, large.View.First); + Assert.Same(c, table.Find(60)); + Assert.Null(table.Find(95)); + } + + // A title's texture heap of packed descriptors can be larger than half of set 1, and the guest keeps two copies of it + // (46158 records each in a real title). The second copy finds no free run and shares the first one's, as a heap that + // moved: the caller compares the run's elements with the new copy's records. Tables keep their own runs. + [Fact] + public void AViewWithoutFreeElementsSharesTheRunOfAViewOfItsShape() + { + var table = new BindlessHeapViewTable(100); + var terrain = table.Acquire(Table(0x1000, 10), tick: 1, completedTick: 0, Unreleased, out _)!; + var heap = table.Acquire(new BindlessHeapDescriptor(false, 0x10000, 80, 32), tick: 1, completedTick: 0, Unreleased, out var moved)!; + Assert.False(moved); + + var copy = table.Acquire(new BindlessHeapDescriptor(false, 0x20000, 80, 32), tick: 1, completedTick: 0, Unreleased, out moved); + + Assert.Same(heap, copy); + Assert.True(moved); + Assert.Equal(0x20000ul, heap.Heap.Base); + Assert.Equal(new HeapView(10, 32, 0, 80), heap.View); + // Back to the first copy: the run moves again. + Assert.Same(heap, table.Acquire(new BindlessHeapDescriptor(false, 0x10000, 80, 32), tick: 2, completedTick: 0, Unreleased, out moved)); + Assert.True(moved); + // The copy it holds now is found as it is. + Assert.Same(heap, table.Acquire(new BindlessHeapDescriptor(false, 0x10000, 80, 32), tick: 3, completedTick: 0, Unreleased, out moved)); + Assert.False(moved); + // Another shape does not share: with nothing completed it has no elements. + Assert.Null(table.Acquire(new BindlessHeapDescriptor(false, 0x30000, 80, 32, 0) with { Records = 81 }, tick: 3, completedTick: 0, Unreleased, out _)); + Assert.Same(terrain, table.Find(0)); + } + + [Fact] + public void AViewHasNoMoreElementsThanTheTable() + { + var table = new BindlessHeapViewTable(100); + + Assert.Null(table.Acquire(Table(0x1000, 0), tick: 1, completedTick: 0, Unreleased, out _)); + Assert.Null(table.Acquire(Table(0, 16), tick: 1, completedTick: 0, Unreleased, out _)); + var cut = table.Acquire(Table(0x1000, 5000), tick: 1, completedTick: 0, Unreleased, out _)!; + + Assert.Equal(new HeapView(0, 440, 0, 100), cut.View); + } + + [Fact] + public void IdleViewsGiveTheirElementsUpOnceTheirCommandsCompleted() + { + var table = new BindlessHeapViewTable(100); + var idle = table.Acquire(Table(0x1000, 10), tick: 1, completedTick: 0, Unreleased, out _)!; + var pending = table.Acquire(Table(0x2000, 10), tick: 5, completedTick: 0, Unreleased, out _)!; + var used = table.Acquire(Table(0x3000, 10), tick: 9, completedTick: 0, Unreleased, out _)!; + var released = new List(); + + table.ReleaseIdle(idleBefore: 8, completedTick: 4, released.Add); + + Assert.Equal([idle], released); + Assert.Equal([pending, used], table.Regions); + } +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/PresenterImageBindingTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/PresenterImageBindingTests.cs index 199c60f9a..9a7741407 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/PresenterImageBindingTests.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/PresenterImageBindingTests.cs @@ -342,11 +342,120 @@ public void RepeatedNativeBindingConsumesNewMetadata(bool gpuWrite, bool alphaMo harness.Shutdown(); } + [Fact] + public void StencilStorage_OfAnotherDepthSurface_ResolvesToTheOwnerOfThatPlane() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + if (!_vulkan.StorageImageExtendedFormats || !_vulkan.SupportsDynamicRendering) + { + Assert.False(ReferenceShaders.Required, "Stencil storage tests need extended storage formats and dynamic rendering."); + return; + } + using var fatal = new FatalScope(); + using var presenter = new PresenterUnderTest(_vulkan); + presenter.LoadRenderingCommands(); + var harness = presenter.Harness; + var region = harness.MapBacked(0x200000, ReadWrite); + var depthAddressB = region + 0x100000; + var stencilAddressB = region + 0x180000; + CachedImage imageA = null!, imageB = null!; + CachedImage? storage = null; + presenter.Run(() => + { + object Depth(ulong depthAddress, ulong stencilAddress) + { + var target = new GuestDepthTarget(depthAddress, depthAddress, 64, 64, 3, 0, 1f, false, + Registers: RegisterWords.Depth(depthAddress, 64, 64, stencilBase: stencilAddress)); + var depth = presenter.InvokeMethod("DiscoverDepthTarget", target)!; + presenter.InvokeMethod("AcquireDepthAttachment", depth, GuestDepthState.Default); + return depth; + } + + // The surface that owns the plane is bound first; the other one is the current target. + var depthB = Depth(depthAddressB, stencilAddressB); + imageB = (CachedImage)GetFieldValue(depthB, "Image"); + var depthA = Depth(region, region + 0x80000); + imageA = (CachedImage)GetFieldValue(depthA, "Image"); + presenter.RenderHost.ResetBindings(); + + var shape = new ShaderImageShape(false, true, true, false, TextureNumericClass.Uint); + var texture = new GuestDrawTexture(stencilAddressB, 64, 64, 0, 0, [], false, true, + Descriptor: RegisterWords.Texture(stencilAddressB, GuestPixelFormat.Bits8UInt, 64, 64, + type: GuestImageType.Color2DArray, tile: GuestTileMode.Depth, layers: 1, baseArray: 0), Shape: shape); + var binding = presenter.InvokeMethod("ResolveTexture", texture)!; + // The lookup handed back the bound surface, not the one owning the plane. + binding.GetType().GetField("ImageIdentifier")!.SetValue(binding, GetFieldValue(depthA, "ImageIdentifier")); + using (presenter.RenderHost.BeginPreparation()) + { + storage = (CachedImage)presenter.InvokeMethod("AcquireStencilStorage", binding, imageA, true)!; + } + + presenter.RenderHost.ResetBindings(); + }); + + Assert.NotNull(storage); + Assert.Equal(Format.R8Uint, storage!.Backing.Format); + Assert.NotSame(imageA, imageB); + Assert.Empty(fatal.Messages); + harness.Finish(); + harness.Shutdown(); + } + + [Fact] + public void StencilStorage_OfAViewSmallerThanItsAttachment_HasTheViewSize() + { + if (!GatePrerequisites.Ready(_vulkan)) return; + if (!_vulkan.StorageImageExtendedFormats || !_vulkan.SupportsDynamicRendering) + { + Assert.False(ReferenceShaders.Required, "Stencil storage tests need extended storage formats and dynamic rendering."); + return; + } + using var fatal = new FatalScope(); + using var presenter = new PresenterUnderTest(_vulkan); + presenter.LoadRenderingCommands(); + var harness = presenter.Harness; + var region = harness.MapBacked(0x100000, ReadWrite); + var stencilAddress = region + 0x80000; + CachedImage image = null!; + CachedImage? storage = null; + presenter.Run(() => + { + var target = new GuestDepthTarget(region, region, 64, 64, 3, 0, 1f, false, + Registers: RegisterWords.Depth(region, 64, 64, stencilBase: stencilAddress)); + var depth = presenter.InvokeMethod("DiscoverDepthTarget", target)!; + presenter.InvokeMethod("AcquireDepthAttachment", depth, GuestDepthState.Default); + image = (CachedImage)GetFieldValue(depth, "Image"); + presenter.RenderHost.ResetBindings(); + + // A dynamic-resolution pass binds only the top-left 32x32 of the 64x64 stencil plane. + var shape = new ShaderImageShape(false, true, true, false, TextureNumericClass.Uint); + var texture = new GuestDrawTexture(stencilAddress, 32, 32, 0, 0, [], false, true, + Descriptor: RegisterWords.Texture(stencilAddress, GuestPixelFormat.Bits8UInt, 32, 32, + type: GuestImageType.Color2DArray, tile: GuestTileMode.Depth, layers: 1, baseArray: 0), Shape: shape); + var binding = presenter.InvokeMethod("ResolveTexture", texture)!; + binding.GetType().GetField("ImageIdentifier")!.SetValue(binding, GetFieldValue(depth, "ImageIdentifier")); + using (presenter.RenderHost.BeginPreparation()) + { + storage = (CachedImage)presenter.InvokeMethod("AcquireStencilStorage", binding, image, true)!; + Assert.Equal(32u, storage.Backing.Extent.Width); + Assert.Equal(32u, storage.Backing.Extent.Height); + } + + presenter.RenderHost.ResetBindings(); + }); + + Assert.NotNull(storage); + Assert.Equal(Format.R8Uint, storage!.Backing.Format); + Assert.Empty(fatal.Messages); + harness.Finish(); + harness.Shutdown(); + } + [Theory] - [InlineData(true, 1u, false)] - [InlineData(true, 2u, true)] - [InlineData(false, 1u, false)] - public unsafe void StencilStorage_PublishesRecordedWritesWithoutChangingDepth(bool recordDispatch, uint layers, bool sampledAlias) + [InlineData(true, 1u, false, 64u)] + [InlineData(true, 2u, true, 64u)] + [InlineData(false, 1u, false, 64u)] + public unsafe void StencilStorage_PublishesRecordedWritesWithoutChangingDepth(bool recordDispatch, uint layers, bool sampledAlias, uint viewSize) { if (!GatePrerequisites.Ready(_vulkan)) return; if (!_vulkan.StorageImageExtendedFormats || !_vulkan.SupportsDynamicRendering) @@ -365,8 +474,8 @@ public unsafe void StencilStorage_PublishesRecordedWritesWithoutChangingDepth(bo presenter.Run(() => { var shape = new ShaderImageShape(false, true, true, false, TextureNumericClass.Uint); - var texture = new GuestDrawTexture(stencilAddress, 64, 64, 0, 0, [], false, true, - Descriptor: RegisterWords.Texture(stencilAddress, GuestPixelFormat.Bits8UInt, 64, 64, + var texture = new GuestDrawTexture(stencilAddress, viewSize, viewSize, 0, 0, [], false, true, + Descriptor: RegisterWords.Texture(stencilAddress, GuestPixelFormat.Bits8UInt, viewSize, viewSize, type: GuestImageType.Color2DArray, tile: GuestTileMode.Depth, layers: layers, baseArray: layers - 1), Shape: shape); // The stencil range was a color image before the depth target took ownership. presenter.InvokeMethod("ResolveTexture", texture); @@ -413,6 +522,9 @@ public unsafe void StencilStorage_PublishesRecordedWritesWithoutChangingDepth(bo workingImages.Add(working); Assert.NotSame(attachment, working); Assert.Equal(Format.R8Uint, working.Backing.Format); + // A view smaller than the attachment (dynamic resolution) gets a storage image of the view's size. + Assert.Equal(viewSize, working.Backing.Extent.Width); + Assert.Equal(viewSize, working.Backing.Extent.Height); Assert.NotEqual(0, (int)(working.Backing.Usage & ImageUsageFlags.StorageBit)); Assert.Equal(0, (int)(attachment.Backing.Usage & ImageUsageFlags.StorageBit)); var invalidStorage = ImageViewDescription.Default with @@ -428,7 +540,7 @@ public unsafe void StencilStorage_PublishesRecordedWritesWithoutChangingDepth(bo if (sampledAlias) Assert.Same(working, GetFieldValue(textures.GetValue(0)!, "CachedImage")); presenter.RenderHost.BindPipeline(PipelineBindPoint.Compute, pipeline); - presenter.RenderHost.Dispatch(32, 64, 1); + presenter.RenderHost.Dispatch(viewSize / 2, viewSize, 1); presenter.RenderHost.ShaderAccessBarrier(); } else @@ -454,7 +566,7 @@ public unsafe void StencilStorage_PublishesRecordedWritesWithoutChangingDepth(bo for (var layer = 0; layer < layers; layer++) for (var row = 0; row < 64; row++) for (var column = 0; column < 64; column++) - Assert.Equal((byte)(recordDispatch && layer == layers - 1 && column < 32 ? 0x39 : 0x37), stencil[layer * 64 * 64 + row * 64 + column]); + Assert.Equal((byte)(recordDispatch && layer == layers - 1 && column < viewSize / 2 && row < viewSize ? 0x39 : 0x37), stencil[layer * 64 * 64 + row * 64 + column]); var depthBytes = harness.ReadImageBytes(attachment, ImageAspectFlags.DepthBit); for (var offset = 0; offset < depthBytes.Length; offset += sizeof(float)) Assert.Equal(0.25f, BitConverter.ToSingle(depthBytes, offset)); diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.WaveMinimum.cs b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.WaveMinimum.cs new file mode 100644 index 000000000..036c8b08e --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/RenderHostDeviceTests.WaveMinimum.cs @@ -0,0 +1,185 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Tests.Gpu.Images; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using static SharpEmu.Libs.Tests.Gpu.Images.ImageCacheTestSupport; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.Libs.Tests.VideoOut; + +// G-buffer pixel shaders scalarize a per-pixel +// byte ID with a wave64 minimum: whole-wave EXEC (S_ORN2_SAVEEXEC of EXEC), identity 0xFFFFFFFF for the lanes the +// wave did not start with, V_MIN_U32 DPP row_shr:1/2/4/8 with BOUND_CTRL clear, V_PERMLANEX16 with BOUND_CTRL set, +// V_READLANE 31 and 63, S_MIN_U32. A PS5 wave always has its dead lanes, which hold the identity. A host fragment +// subgroup of a small primitive does not: the lanes past its quads were never launched. Reading such a lane must not +// produce a value below every live ID, or the ID loop that follows never finishes. +public sealed unsafe partial class RenderHostDeviceTests +{ + [Theory] + [InlineData(false, 32u)] + [InlineData(true, 32u)] + [InlineData(false, 64u)] + [InlineData(true, 64u)] + public void WaveMinimum_PartialFragmentSubgroupFindsTheLiveMinimum(bool onePixel, uint waveSize) + { + if (!Ready()) return; + using var presenter = new PresenterUnderTest(_vulkan!); + presenter.LoadRenderingCommands(); + var harness = presenter.Harness; + var target = harness.MapBacked(0x10000, ReadWrite); + var vertices = harness.MapBacked(0x10000, ReadWrite); + var words = RegisterWords.Color(target, Size, Size); + // One pixel: the centre of pixel (32, 32) is at (1/64, 1/64) in clip space. + harness.Write(vertices, onePixel + ? Triangle(0f, 0f, 0.06f, 0f, 0f, 0.06f) + : Triangle(-1f, -1f, 3f, -1f, -1f, 3f)); + const uint id = 7; + var minusOne = Gen5Operand.Source(193); + var instructions = new List(); + uint pc = 0; + void Add(Gen5ShaderInstruction instruction) + { + instructions.Add(instruction with { Pc = pc }); + pc += 8; + } + + Gen5ShaderInstruction MinDpp(uint control) => + Vop2(0, "VMinU32", 5, Gen5Operand.Vector(5), Gen5Operand.Vector(5)) with + { + Control = new Gen5DppControl(control, false, false, 0, 0, 15, 15), + }; + + Add(MoveVector(0, 15, id)); + Add(MoveScalar(0, 26, uint.MaxValue)); + Add(MoveScalar(0, 27, uint.MaxValue)); + Add(Sop2(0, "SAndB64", 32, Gen5Operand.Scalar(126), Gen5Operand.Scalar(26))); + Add(Sop1(0, "SOrn2SaveexecB64", 106, Gen5Operand.Scalar(126))); + Add(Vop3(0, "VCndmaskB32", 5, minusOne, Gen5Operand.Vector(15), Gen5Operand.Scalar(32))); + Add(MinDpp(0x111)); + Add(MinDpp(0x112)); + Add(MinDpp(0x114)); + Add(MinDpp(0x118)); + Add(Vop3(0, "VPermlanex16B32", 2, Gen5Operand.Vector(5), minusOne, minusOne) with + { + Control = new Gen5Vop3Control(0, 0, 0, false, 2, null), + }); + Add(Vop2(0, "VMinU32", 5, Gen5Operand.Vector(5), Gen5Operand.Vector(2))); + Add(Sop1(0, "SMovB64", 126, Gen5Operand.Scalar(106))); + Add(ReadLane(0, 32, 5, 31)); + Add(ReadLane(0, 33, 5, 63)); + Add(Sop2(0, "SMinU32", 59, Gen5Operand.Scalar(32), Gen5Operand.Scalar(33))); + Add(Vopc(0, "VCmpEqU32", Gen5Operand.Scalar(59), 15)); + Add(Vop2(0, "VCndmaskB32", 2, Operand(0), Operand(0x3F800000))); + Add(MoveVector(0, 3, 0x3F800000)); + Add(new Gen5ShaderInstruction(0, Gen5ShaderEncoding.Exp, "Exp", [], + [Gen5Operand.Vector(2), Gen5Operand.Vector(2), Gen5Operand.Vector(2), Gen5Operand.Vector(3)], + [], new Gen5ExportControl(0, 15, false, true, true))); + Add(EndProgram(0)); + var (plan, resources, layout) = Prepare(Program([.. instructions]), ShaderStage.Pixel, userDataCount: 0); + var request = new ShaderCompileRequest(plan, resources, layout) + { + WaveSize = waveSize, + PixelOutputs = [new Gen5PixelOutputBinding(0, 0, Gen5PixelOutputKind.Float)], + EnableGraphicsSubgroupOperations = true, + GraphicsPartialSubgroupLanes = true, + }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + var provider = new FixedProgramProvider((IShaderPipelineHost)presenter.Instance, vertices, + interpolationShader: shader.Spirv); + var executor = new RenderExecutor(presenter.RenderHost, provider); + presenter.Run(() => executor.DrawAuto(1, Banks(words), Draw())); + presenter.Run(() => presenter.InvokeMethod("FlushBatchedGuestCommands")); + harness.Finish(); + var bytes = harness.ReadImageBytes(TargetImage(presenter, words)); + var covered = 0; + var wrong = new List(); + for (uint y = 0; y < Size; y++) + { + for (uint x = 0; x < Size; x++) + { + var pixel = Pixel(bytes, x, y); + if (pixel >> 24 == 0) continue; + covered++; + if (pixel != uint.MaxValue) wrong.Add($"({x},{y})=0x{pixel:X8}"); + } + } + + Assert.True(covered > 0, "the draw covered no pixel"); + Assert.True(wrong.Count == 0, $"{wrong.Count} of {covered} pixels saw a wave minimum other than {id}: " + + string.Join(' ', wrong.Take(8))); + harness.Shutdown(); + _vulkan!.AssertNoValidationMessages(); + } + + // The same G-buffer shaders take screen-space derivatives with quad DPP (quad_perm [0,0,0,0] and [1,1,1,1], + // BOUND_CTRL set). A one-pixel primitive's quad is one live lane and three helpers; the helpers are launched + // host invocations, so their values must still be read. + [Theory] + [InlineData(32u)] + [InlineData(64u)] + public void QuadDppDerivative_ReadsHelperLanesOfAPartialFragmentSubgroup(uint waveSize) + { + if (!Ready()) return; + using var presenter = new PresenterUnderTest(_vulkan!); + presenter.LoadRenderingCommands(); + var harness = presenter.Harness; + var target = harness.MapBacked(0x10000, ReadWrite); + var vertices = harness.MapBacked(0x10000, ReadWrite); + var words = RegisterWords.Color(target, Size, Size); + harness.Write(vertices, Triangle(0f, 0f, 0.06f, 0f, 0f, 0.06f)); + Gen5ShaderInstruction QuadRead(uint pc, uint destination, uint control) => + Vop1(pc, "VMovB32", destination, Gen5Operand.Vector(0)) with + { + Control = new Gen5DppControl(control, false, true, 0, 0, 15, 15), + }; + + // v0 = POS_X_FLOAT; ddx = x(quad lane 1) - x(quad lane 0) = 1. + var program = Program( + QuadRead(0, 3, 0x00), + QuadRead(8, 4, 0x55), + Vop2(16, "VSubF32", 2, Gen5Operand.Vector(4), Gen5Operand.Vector(3)), + MoveVector(24, 5, 0x3F800000), + new Gen5ShaderInstruction(32, Gen5ShaderEncoding.Exp, "Exp", [], + [Gen5Operand.Vector(2), Gen5Operand.Vector(2), Gen5Operand.Vector(2), Gen5Operand.Vector(5)], + [], new Gen5ExportControl(0, 15, false, true, true)), + EndProgram(40)); + var (plan, resources, layout) = Prepare(program, ShaderStage.Pixel, userDataCount: 0); + var request = new ShaderCompileRequest(plan, resources, layout) + { + WaveSize = waveSize, + PixelInputAddress = 1u << 8, + PixelInputEnable = 1u << 8, + PixelOutputs = [new Gen5PixelOutputBinding(0, 0, Gen5PixelOutputKind.Float)], + EnableGraphicsSubgroupOperations = true, + GraphicsPartialSubgroupLanes = true, + }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + var provider = new FixedProgramProvider((IShaderPipelineHost)presenter.Instance, vertices, + interpolationShader: shader.Spirv); + var executor = new RenderExecutor(presenter.RenderHost, provider); + presenter.Run(() => executor.DrawAuto(1, Banks(words), Draw())); + presenter.Run(() => presenter.InvokeMethod("FlushBatchedGuestCommands")); + harness.Finish(); + var bytes = harness.ReadImageBytes(TargetImage(presenter, words)); + var covered = new List(); + for (uint y = 0; y < Size; y++) + { + for (uint x = 0; x < Size; x++) + { + var pixel = Pixel(bytes, x, y); + if (pixel >> 24 != 0) covered.Add(pixel); + } + } + + Assert.NotEmpty(covered); + Assert.All(covered, pixel => Assert.Equal(uint.MaxValue, pixel)); + harness.Shutdown(); + _vulkan!.AssertNoValidationMessages(); + } +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/ShaderWriteBarrierTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/ShaderWriteBarrierTests.cs new file mode 100644 index 000000000..8a55853ea --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/VideoOut/ShaderWriteBarrierTests.cs @@ -0,0 +1,29 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.VideoOut; +using Silk.NET.Vulkan; +using Xunit; + +namespace SharpEmu.Libs.Tests.VideoOut; + +public sealed class ShaderWriteBarrierTests +{ + // A vertex or compute stage that writes the arguments of a later indirect draw (GPU-driven culling) + // must make them visible to the draw's argument read, or the draw reads stale arguments. + [Theory] + [InlineData(PipelineStageFlags.VertexShaderBit)] + [InlineData(PipelineStageFlags.FragmentShaderBit)] + [InlineData(PipelineStageFlags.ComputeShaderBit)] + public void ShaderWritesReachIndirectArgumentReads(PipelineStageFlags source) + { + var request = VulkanVideoPresenter.ShaderWriteBarrierRequest(source, meshShader: false, taskShader: false, tessellation: true); + + Assert.Equal(source, request.SourceStages); + Assert.Equal(AccessFlags.ShaderWriteBit, request.SourceAccess); + Assert.True(request.DestinationStages.HasFlag(PipelineStageFlags.DrawIndirectBit)); + Assert.True(request.DestinationAccess.HasFlag(AccessFlags.IndirectCommandReadBit)); + Assert.True(request.DestinationStages.HasFlag(PipelineStageFlags.TessellationControlShaderBit)); + Assert.False(request.DestinationStages.HasFlag(PipelineStageFlags.MeshShaderBitExt)); + } +} diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/VulkanPresentEncodeFormatTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/VulkanPresentEncodeFormatTests.cs index 2862056c1..d16c6bb7f 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/VulkanPresentEncodeFormatTests.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/VulkanPresentEncodeFormatTests.cs @@ -32,6 +32,10 @@ public void UnsignedRgba32TargetUsesUnsignedPixelOutput() [InlineData(13u, 5u, Format.R32G32B32A32Sint, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Sint)] [InlineData(14u, 5u, Format.R32G32B32A32Sint, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Sint)] [InlineData(14u, 7u, Format.R32G32B32A32Sfloat, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Float)] + // A game can bind an 8-bit sRGB colour target (slot 5, data format 1, number type 6). + [InlineData(1u, 6u, Format.R8Unorm, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Float)] + [InlineData(1u, 9u, Format.R8Unorm, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Float)] + [InlineData(3u, 6u, Format.R8G8Unorm, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Float)] public void FullWidthTargetsFollowTheirNumberType( uint dataFormat, uint numberType, @@ -226,6 +230,32 @@ public void TryDecodeRenderTargetFormat_SelectsRgb10HostOrder( Assert.True(decoded.ExportMapping.IsIdentity); } + // Narrow and signed-normalized targets: the pixel output kind must follow the number type. + [Theory] + [InlineData(1u, 1u, Format.R8SNorm, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Float)] + [InlineData(1u, 5u, Format.R8Sint, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Sint)] + [InlineData(1u, 6u, Format.R8Unorm, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Float)] + [InlineData(1u, 9u, Format.R8Unorm, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Float)] + [InlineData(3u, 1u, Format.R8G8SNorm, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Float)] + [InlineData(3u, 4u, Format.R8G8Uint, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Uint)] + [InlineData(3u, 5u, Format.R8G8Sint, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Sint)] + [InlineData(3u, 6u, Format.R8G8Unorm, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Float)] + [InlineData(5u, 1u, Format.R16G16SNorm, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Float)] + [InlineData(10u, 1u, Format.R8G8B8A8SNorm, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Float)] + [InlineData(12u, 1u, Format.R16G16B16A16SNorm, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Float)] + [InlineData(6u, 0u, Format.B10G11R11UfloatPack32, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Float)] + public void TryDecodeRenderTargetFormat_DecodesNarrowAndSignedTargets( + uint dataFormat, + uint numberType, + Format expected, + SharpEmu.ShaderCompiler.Gen5PixelOutputKind expectedKind) + { + Assert.True(VulkanVideoPresenter.TryDecodeRenderTargetFormat(dataFormat, numberType, 0, out var decoded)); + + Assert.Equal(expected, decoded.Format); + Assert.Equal(expectedKind, decoded.OutputKind); + } + [Fact] public void TryDecodeRenderTargetFormat_RejectsInvalidComponentSwap() { diff --git a/tests/SharpEmu.ShaderCompiler.Tests/DecodeHarness.cs b/tests/SharpEmu.ShaderCompiler.Tests/DecodeHarness.cs new file mode 100644 index 000000000..7967328bc --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/DecodeHarness.cs @@ -0,0 +1,68 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using System.Buffers.Binary; +using Xunit; + +namespace SharpEmu.ShaderCompiler.Tests; + +// Decodes raw instruction words through the public decoder entry point. +internal static class DecodeHarness +{ + private const ulong ShaderAddress = 0x1000; + + public static Gen5ShaderProgram Decode(params uint[] words) + { + var memory = new TestCpuMemory(ShaderAddress, 0x100); + var shader = new byte[words.Length * sizeof(uint)]; + for (var index = 0; index < words.Length; index++) + { + BinaryPrimitives.WriteUInt32LittleEndian(shader.AsSpan(index * sizeof(uint)), words[index]); + } + + Assert.True(memory.TryWrite(ShaderAddress, shader)); + var context = new CpuContext(memory, Generation.Gen5); + Assert.True(Gen5ShaderTranslator.TryDecodeProgram(context, ShaderAddress, out var program, out var error), error); + return program; + } + + private sealed class TestCpuMemory(ulong baseAddress, int size) : ICpuMemory + { + private readonly byte[] _storage = new byte[size]; + + public bool TryRead(ulong virtualAddress, Span destination) + { + if (!TryResolve(virtualAddress, destination.Length, out var offset)) + { + return false; + } + + _storage.AsSpan(offset, destination.Length).CopyTo(destination); + return true; + } + + public bool TryWrite(ulong virtualAddress, ReadOnlySpan source) + { + if (!TryResolve(virtualAddress, source.Length, out var offset)) + { + return false; + } + + source.CopyTo(_storage.AsSpan(offset, source.Length)); + return true; + } + + private bool TryResolve(ulong virtualAddress, int length, out int offset) + { + offset = 0; + if (virtualAddress < baseAddress || virtualAddress - baseAddress + (ulong)length > (ulong)_storage.Length) + { + return false; + } + + offset = (int)(virtualAddress - baseAddress); + return true; + } + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5FlatMemoryTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5FlatMemoryTests.cs index 3e1b2b4de..1c6d921da 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Gen5FlatMemoryTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5FlatMemoryTests.cs @@ -58,6 +58,80 @@ public void GlobalMemoryInstructions_KeepSeparateReadAndWriteRegisters(bool uses : [], instruction.Destinations); } + // A shipped compute shader: global_load_ubyte v2, v53, s[0:1] offset:217. + // Bit 0 of a FLAT word is offset bit 0, not an opcode bit (that is MIMG only). + [Fact] + public void GlobalLoadUbyteWithOddOffset_DecodesAsGlobalLoadUbyte() + { + var instruction = DecodeProgram(0xDC20_80D9, 0x0200_0035, SEndpgm).Instructions[0]; + + Assert.Equal("GlobalLoadUbyte", instruction.Opcode); + var control = Assert.IsType(instruction.Control); + Assert.Equal(1u, control.DwordCount); + Assert.Equal(0x35u, control.VectorAddress); + Assert.Equal(0u, control.ScalarAddress); + Assert.Equal(2u, control.DestinationVectorRegister); + Assert.Equal(0xD9, control.OffsetBytes); + Assert.False(control.Glc); + Assert.False(control.UsesFlatAddress); + Assert.Equal([Gen5Operand.Vector(0x35), Gen5Operand.Scalar(0)], instruction.Sources); + Assert.Equal([Gen5Operand.Vector(2)], instruction.Destinations); + } + + public static IEnumerable OddOffsetCases() + { + foreach (var segment in new uint[] { 0, 2 }) + foreach (var opcode in new uint[] { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 50, 56 }) + yield return [segment, opcode]; + } + + [Theory] + [MemberData(nameof(OddOffsetCases))] + public void OddOffset_KeepsTheOpcodeOfTheEvenOffset(uint segment, uint opcode) + { + var even = DecodeProgram(0xDC00_0000u | (opcode << 18) | (segment << 14) | 0x10, 0x0810_0309, SEndpgm).Instructions[0]; + var odd = DecodeProgram(0xDC00_0000u | (opcode << 18) | (segment << 14) | 0x11, 0x0810_0309, SEndpgm).Instructions[0]; + + Assert.Equal(even.Opcode, odd.Opcode); + Assert.Equal(0x11, Assert.IsType(odd.Control).OffsetBytes); + } + + // GFX10 FLAT word 0: OFFSET[11:0] (signed for global and scratch), DLC[12], LDS[13], SEG[15:14]. + [Theory] + [InlineData(0x000u, 0)] + [InlineData(0x0D9u, 0xD9)] + [InlineData(0x7FFu, 2047)] + [InlineData(0x800u, -2048)] + [InlineData(0xFFFu, -1)] + public void GlobalOffset_IsTwelveBitSignedAndIgnoresDlc(uint offsetField, int expected) + { + foreach (var dlc in new uint[] { 0, 1u << 12 }) + { + // global_load_dword v8, v9, s[16:17] offset: [dlc] + var instruction = DecodeProgram(0xDC30_8000u | dlc | offsetField, 0x0810_0009, SEndpgm).Instructions[0]; + Assert.Equal("GlobalLoadDword", instruction.Opcode); + Assert.Equal(expected, Assert.IsType(instruction.Control).OffsetBytes); + } + } + + [Fact] + public void GlobalLoadUbyteWithOddOffset_CompilesToADeviceAddressByteLoad() + { + // global_load_ubyte v1, v0, s[0:1] offset:217; s[0:1] is user data. + var program = DecodeProgram(0xDC20_80D9, 0x0100_0000, SEndpgm); + var instruction = Assert.Single(program.Instructions, item => item.Opcode == "GlobalLoadUbyte"); + + var (plan, resources, layout) = ResourceTestProgram.Prepare(program, userDataBase: 0, userDataCount: 2); + Assert.True(plan.Info.UsesDeviceAddresses); + Assert.True(plan.Memory.TryGetIndex(instruction.Pc, 0, out _)); + var request = new ShaderCompileRequest(plan, resources, layout); + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var compiled, out var error), error); + var opcodes = ReadSpirvOpcodes(compiled.Spirv); + Assert.Contains((ushort)SpirvOp.ConvertUToPtr, opcodes); + // An unsigned byte load is zero-extended, never sign-extracted. + Assert.DoesNotContain((ushort)SpirvOp.BitFieldSExtract, opcodes); + } + [Fact] public void ReturningAtomic_InvalidatesThePreviousFlatAddressDefinition() { diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5ImageGatherDecodeTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5ImageGatherDecodeTests.cs new file mode 100644 index 000000000..d0829ab28 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5ImageGatherDecodeTests.cs @@ -0,0 +1,27 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using Xunit; + +namespace SharpEmu.ShaderCompiler.Tests; + +public sealed class Gen5ImageGatherDecodeTests +{ + [Theory] + [InlineData(0x40u, "ImageGather4")] + [InlineData(0x44u, "ImageGather4L")] + [InlineData(0x47u, "ImageGather4Lz")] + [InlineData(0x48u, "ImageGather4C")] + [InlineData(0x4Cu, "ImageGather4CL")] + [InlineData(0x4Fu, "ImageGather4CLz")] + public void GatherOpcodesDecodeAsImageOperations(uint opcode, string expected) + { + // image_gather4* v[0:3], v[4:7], s[8:15], s[0:3] dmask:0xf + var program = DecodeHarness.Decode(0xF0000000u | (opcode << 18) | (0xFu << 8), 4u | (2u << 16), 0xBF810000u); + + var instruction = program.Instructions[0]; + Assert.Equal(Gen5ShaderEncoding.Mimg, instruction.Encoding); + Assert.Equal(expected, instruction.Opcode); + Assert.IsType(instruction.Control); + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5ScalarAddImmediateTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5ScalarAddImmediateTests.cs index b53d9b4eb..c8006a93c 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Gen5ScalarAddImmediateTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5ScalarAddImmediateTests.cs @@ -3,6 +3,8 @@ using System.Buffers.Binary; using SharpEmu.HLE; +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Tests.Resources; using SharpEmu.ShaderCompiler.Vulkan; using Xunit; using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; @@ -64,6 +66,41 @@ public void BitReverseLeavesSccAlone(uint source) Assert.Equal(Count(moved, SpirvOp.INotEqual), Count(reversed, SpirvOp.INotEqual)); } + // s_brev_b64 reverses all 64 bits: each half is reversed and the halves change places. + // Shaders build a 64-bit constant with it from a 32-bit literal. + [Fact] + public void BitReverse64SwapsTheReversedHalvesAndLeavesSccAlone() + { + const uint literal = 0x0A000000; + var instruction = DecodeProgram(0xBE840CFF, literal, SEndpgm).Instructions[0]; + Assert.Equal("SBrevB64", instruction.Opcode); + Assert.Equal(2u, instruction.DestinationWidth); + Assert.Equal(4u, instruction.Destinations[0].Value); + var reversed = CompiledOpcodes(0xBE840CFF, literal); + var moved = CompiledOpcodes(0xBE8404FF, literal); + Assert.Equal(2, Count(reversed, SpirvOp.BitReverse)); + Assert.Equal(Count(moved, SpirvOp.Store), Count(reversed, SpirvOp.Store)); + Assert.Equal(Count(moved, SpirvOp.INotEqual), Count(reversed, SpirvOp.INotEqual)); + } + + [Fact] + public void BitReverse64OfALiteralIsAKnownAddressForTheResourcePlan() + { + // brev64(0x0000_0000_0400_0000) = 0x0000_0020_0000_0000: the table the loads go through. + const ulong table = 0x20_0000_0000; + var memory = new TestWordMemory { Base = table, Words = new uint[16] }; + memory.At(table) = 0x6000; + memory.At(table + 8) = 128; + var program = Program( + Sop1(0, "SBrevB64", 10, Operand(0x04000000)), + ScalarLoad(8, 10, 16, 4), BufferLoad(16, 16), EndProgram(24)); + var plan = ShaderResourcePlan.Extract(program, ShaderStage.Compute, Hash, 8, 2, waveSize: 64); + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + Assert.True(ResourceMaterializer.Materialize(plan, Inputs(new uint[2], memory.Read), ref snapshot, ref specialization)); + Assert.Equal(0x6000u, snapshot.Buffers[0][0]); + } + private static int Count(IReadOnlyList opcodes, SpirvOp opcode) { var total = 0; @@ -78,9 +115,9 @@ private static int Count(IReadOnlyList opcodes, SpirvOp opcode) return total; } - private static IReadOnlyList CompiledOpcodes(uint word) + private static IReadOnlyList CompiledOpcodes(params uint[] words) { - var request = Request(DecodeProgram(word, SEndpgm), userDataCount: 0); + var request = Request(DecodeProgram([.. words, SEndpgm]), userDataCount: 0); Assert.True( Gen5SpirvTranslator.TryCompileProgram(request, out var compiled, out var error), error); diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5TessellationTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5TessellationTests.cs index 42241d2c3..45957c1ef 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Gen5TessellationTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5TessellationTests.cs @@ -3,6 +3,7 @@ using System.Buffers.Binary; using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Ir; using SharpEmu.ShaderCompiler.Resources; using SharpEmu.ShaderCompiler.Tests.Resources; using SharpEmu.ShaderCompiler.Vulkan; @@ -107,6 +108,106 @@ public void MergedHullLowering_PublishesLocalOutputsAndPreservesOriginalAddresse Assert.Throws(() => Gen5TessellationLowering.PrepareMergedHull(Program(EndProgram(0)), 14)); } + // A complete hull binary (AGC shader type HS) in the shape a shipped game uses. + // The local half runs for the lanes below the low byte of s3, writes LDS and leaves v13. + // The hull half runs for the lanes below the second byte, reads LDS and v13 and stores + // through the factor offset in s4. + internal const uint CombinedHullEntry = 0x30; + internal static readonly uint[] CombinedHullWords = + [ + 0xBEFE04C1, // 0x00 s_mov_b64 exec, -1 + 0xD7650000, 0x000100C1, // 0x04 v_mbcnt_lo_u32_b32 v0, -1, 0 + 0xD7660000, 0x000200C1, // 0x0C v_mbcnt_hi_u32_b32 v0, -1, v0 + 0x7DA206F9, 0x80060000, // 0x14 v_cmpx_lt_u32 v0, s3 (byte 0) + 0xBF880004, // 0x1C s_cbranch_execz 0x30 + 0x34140682, // 0x20 v_lshlrev_b32 v10, 2, v3 + 0xD8340000, 0x0000020A, // 0x24 ds_write_b32 v10, v2 + 0x7E1A02A5, // 0x2C v_mov_b32 v13, 37 + 0xBEFE04C1, // 0x30 s_mov_b64 exec, -1 + 0x7DA206F9, 0x81060000, // 0x34 v_cmpx_lt_u32 v0, s3 (byte 1) + 0xBF880009, // 0x3C s_cbranch_execz 0x64 + 0x361606BF, // 0x40 v_and_b32 v11, 63, v3 + 0x34161682, // 0x44 v_lshlrev_b32 v11, 2, v11 + 0xD8D80000, 0x0400000B, // 0x48 ds_read_b32 v4, v11 + 0x34180683, // 0x50 v_lshlrev_b32 v12, 3, v3 + 0xE0705000, 0x0402040C, // 0x54 buffer_store_dword v4, v12, s[8:11], s4 + 0xE0705004, 0x04020D0C, // 0x5C buffer_store_dword v13, v12, s[8:11], s4, offset 4 + 0xBF810000, // 0x64 s_endpgm + ]; + + [Fact] + public void CombinedHull_EntryIsWhereTheHullHalfReopensExec() + { + var program = DecodeHarness.Decode(CombinedHullWords); + Assert.Equal(["SMovB64", "VMbcntLoU32B32", "VMbcntHiU32B32", "VCmpxLtU32", "SCbranchExecz", "VLshlrevB32", "DsWriteB32", + "VMovB32", "SMovB64", "VCmpxLtU32", "SCbranchExecz", "VAndB32", "VLshlrevB32", "DsReadB32", "VLshlrevB32", + "BufferStoreDword", "BufferStoreDword", "SEndpgm"], program.Instructions.Select(i => i.Opcode)); + Assert.Null(program.FusedContinuationPc); + Assert.True(Gen5TessellationLowering.TryFindCombinedHullEntry(program, out var entry)); + Assert.Equal(CombinedHullEntry, entry); + + // Without a test of the second byte there is no hull half to enter. + var localOnly = CombinedHullWords.ToArray(); + localOnly[14] = 0x80060000; + Assert.False(Gen5TessellationLowering.TryFindCombinedHullEntry(DecodeHarness.Decode(localOnly), out _)); + // A mask restored from a register is a join inside one half, not the hull entry. + var restored = CombinedHullWords.ToArray(); + restored[12] = 0xBEFE0400; + Assert.False(Gen5TessellationLowering.TryFindCombinedHullEntry(DecodeHarness.Decode(restored), out _)); + Assert.False(Gen5TessellationLowering.TryFindCombinedHullEntry(Program(Nop(0), EndProgram(4)), out _)); + } + + [Fact] + public void CombinedHullLowering_PutsTheBarrierWhereTheLocalSkipLands() + { + var program = DecodeHarness.Decode(CombinedHullWords); + var lowered = Gen5TessellationLowering.PrepareCombinedHull(program); + Assert.Equal(program.Instructions.Count + 1, lowered.Instructions.Count); + // The hull half takes no separate table, so nothing is moved into s0:s1. + Assert.Equal(program.Instructions[0], lowered.Instructions[0]); + var barrier = Assert.Single(lowered.Instructions, i => i.Opcode == "SBarrier"); + Assert.Equal(CombinedHullEntry, barrier.Pc); + var skips = lowered.Instructions.Where(i => i.Opcode == "SCbranchExecz").ToArray(); + Assert.True(Gen5IrBranchResolver.Instance.TryGetBranchTarget(skips[0], out var target)); + Assert.Equal(barrier.Pc, target); + Assert.True(Gen5IrBranchResolver.Instance.TryGetBranchTarget(skips[1], out target)); + Assert.Equal("SEndpgm", lowered.Instructions.Single(i => i.Pc == target).Opcode); + var reopen = lowered.Instructions.Single(i => i.Pc == CombinedHullEntry + 4); + Assert.Equal("SMovB64", reopen.Opcode); + Assert.Equal((ulong)CombinedHullEntry, reopen.ProgramOffset); + Assert.Equal(0x20ul, lowered.Instructions.Single(i => i.Pc == 0x20).ProgramOffset); + + var plan = ShaderResourcePlan.Extract(lowered, ShaderStage.Compute, Hash, 8, 8, waveSize: 64); + Assert.Equal(plan.Memory.Find(0x58)!.Resource, Gen5TessellationLowering.FindFactorBuffer(plan, CombinedHullEntry + 4)); + Assert.Throws(() => Gen5TessellationLowering.PrepareCombinedHull(Program(EndProgram(0)))); + } + + [Fact] + public void CombinedHullLowering_RejectsABranchAcrossTheHullEntry() + { + // The local skip lands one instruction inside the hull half, past the barrier. + var words = CombinedHullWords.ToArray(); + words[7] = 0xBF880005; + Assert.Throws(() => Gen5TessellationLowering.PrepareCombinedHull(DecodeHarness.Decode(words))); + } + + [Fact] + public void CombinedHull_CompilesAsOneCooperativeWorkgroup() + { + var lowered = Gen5TessellationLowering.PrepareCombinedHull(DecodeHarness.Decode(CombinedHullWords)); + var plan = ShaderResourcePlan.Extract(lowered, ShaderStage.Compute, Hash, 8, 8, waveSize: 64); + var resources = ResourceMaterializer.ApplyTo(plan, ResourceSpecialization.Default(plan.Info)); + var layout = BindingLayout.Allocate(resources.Info, BindingLayout.CollectUserDataRegisters(lowered, 8, 8), + false, false, false, usesTessellationData: true); + var request = new ShaderCompileRequest(plan, resources, layout) + { + LocalSizeX = 128, WaveSize = 64, CooperativeWave64Workgroup = true, LocalDataShareDwords = 64, + TessellationHull = new(2, 4, 32, CombinedHullEntry + 4), + }; + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + Gen5MipStatisticsTests.ValidateWhenAvailable(shader.Spirv); + } + [Theory] [InlineData(32u, 128u)] [InlineData(64u, 63u)] diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5TypedBufferLoadDecodeTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5TypedBufferLoadDecodeTests.cs index 41e1aba45..4de30d7e3 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Gen5TypedBufferLoadDecodeTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5TypedBufferLoadDecodeTests.cs @@ -68,6 +68,21 @@ public void FormattedUntypedInstructions_CarryNoInstructionFormat() Assert.Equal(0u, control.TypedFormat); } + // buffer_load_format_d16_hi_x / buffer_store_format_d16_hi_x v26, v20, s[4:7], 0 idxen: one register, whose high half + // the component goes through (a shipped compute shader stores with 0x27). + [Theory] + [InlineData(0x26u, "BufferLoadFormatD16HiX")] + [InlineData(0x27u, "BufferStoreFormatD16HiX")] + public void UntypedD16HiX_DecodesAsOneRegisterFormatAccess(uint opcode, string expected) + { + var instruction = Decode([0xE0002000u | (opcode << 18), 0x80011A14u, 0xBF810000u]).Instructions[0]; + + Assert.Equal(expected, instruction.Opcode); + var control = Assert.IsType(instruction.Control); + Assert.Equal(1u, control.DwordCount); + Assert.Equal(26u, control.VectorData); + } + private static Gen5ShaderProgram Decode(uint[] words) { var context = WriteProgram(new TestCpuMemory(ShaderAddress, 0x100), words); diff --git a/tests/SharpEmu.ShaderCompiler.Tests/GraphicsPartialLanesSwitchTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/GraphicsPartialLanesSwitchTests.cs new file mode 100644 index 000000000..5f2cef30f --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/GraphicsPartialLanesSwitchTests.cs @@ -0,0 +1,42 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.ShaderCompiler.Tests; + +public sealed class GraphicsPartialLanesSwitchTests +{ + // A pixel V_READLANE keeps main's lowering unless the partial-subgroup lane reads are asked for + // (SHARPEMU_GRAPHICS_PARTIAL_LANES=1), which look the source lane up in a ballot and the guest EXEC mask. + [Fact] + public void PixelReadLaneKeepsMainsLoweringUnlessEnabled() + { + Assert.Equal(Compile(enabled: false), Compile(enabled: null)); + Assert.NotEqual(Compile(enabled: false), Compile(enabled: true)); + } + + private static byte[] Compile(bool? enabled) + { + var program = Program(ReadLane(0, 32, 5, 31), MoveVectorFromScalar(8, 6, 32), EndProgram(16)); + var (plan, resources, layout) = Prepare(program, ShaderStage.Pixel); + var request = new ShaderCompileRequest(plan, resources, layout) + { + PixelOutputs = [new Gen5PixelOutputBinding(0, 0, Gen5PixelOutputKind.Float)], + }; + if (enabled is { } value) + { + request = new ShaderCompileRequest(plan, resources, layout) + { + PixelOutputs = request.PixelOutputs, + GraphicsPartialSubgroupLanes = value, + }; + } + + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + return shader.Spirv; + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/BindlessHeapTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/BindlessHeapTests.cs index 02c019c5f..8c2ed5c17 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/BindlessHeapTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/BindlessHeapTests.cs @@ -11,8 +11,8 @@ namespace SharpEmu.ShaderCompiler.Tests.Resources; public sealed class BindlessHeapTests { // With the heap set (bindlessHeap), an image read from a heap V# at a lane-chosen offset is a heap record: its reads - // stay on the host, and the shader takes the record its key picks from descriptor set 1 and marks it for the host. A - // record past the heap's range (the call records' elements) reads null. + // stay on the host, and the shader takes the element of the record its key picks from descriptor set 1 and marks it + // for the host. The program has one heap view, whose elements the draw names in two dwords of shader data. [Fact] public void AnImageReadAtALaneChosenOffsetIsAHeapRecord() { @@ -33,9 +33,12 @@ public void AnImageReadAtALaneChosenOffsetIsAHeapRecord() } Assert.True(plan.Info.UsesBindlessHeap); + Assert.Equal(1u, plan.Info.HeapViewCount); var request = Request(program, bindlessHeap: true); Assert.True(request.UsesBindlessHeap); Assert.True(request.Bindings.UsesBindlessHeap); + Assert.Equal(1u, request.Bindings.HeapViewCount); + Assert.Equal(request.Bindings.ShaderDataDwordCount, request.Bindings.HeapViewsDword + HeapView.DwordCount); Assert.Contains(heap.KeyMemoryIndex, request.IndirectOffsetKeyMemoryIndices); var module = Compile(request); @@ -44,7 +47,7 @@ public void AnImageReadAtALaneChosenOffsetIsAHeapRecord() Assert.Contains((uint)SpirvDecoration.NonUniform, module.Decorations); Assert.Contains((uint)SpirvCapability.SampledImageArrayNonUniformIndexing, module.Capabilities); Assert.Contains(SpirvOp.ULessThan, module.Opcodes); - Assert.Contains(BindlessHeap.CallRecordFirstIndex, module.Constants); + Assert.Contains(SpirvOp.UDiv, module.Opcodes); Assert.Contains(BindlessHeap.CallRecordNullIndex, module.Constants); } @@ -130,38 +133,278 @@ public void AHeapVolumeReadFallsBackToTheRecordsLayers() Assert.Contains((uint)SpirvCapability.ImageQuery, module.Capabilities); } - // A heap read takes the element of its record when set 1 holds that record (below CallRecordFirstIndex) and the null - // element for any other record, however large: the range test reads the record itself, not a value cut to the set's - // size, so no record reads the element of another record. + // A heap read takes the element its draw's heap view has for the record it reads: the view's first element plus the + // record number, when the read is at the view's descriptor in a record the view holds. Any other read (past the + // view's records, between two descriptors, or of a view the draw gave no elements) takes the null element, so no read + // takes the element of another view. A terrain or material table has records larger than a descriptor (stride 440 + // here, with the T# 64 bytes in); a heap of packed descriptors has the descriptor's size as its stride. [Theory] [InlineData(false)] [InlineData(true)] - public void ARecordSetOneCannotHoldReadsTheNullElement(bool sampler) + public void AHeapReadTakesTheElementOfItsViewsRecord(bool sampler) { var program = sampler ? ResourceTrackerTests.LaneIndexedSamplerProgram() : ResourceTrackerTests.LaneIndexedImageProgram(); Assert.True(Gen5SpirvTranslator.TryCompileProgram(Request(program, ShaderStage.Pixel, bindlessHeap: true), out var shader, out var error), error); Gen5MipStatisticsTests.ValidateWhenAvailable(shader.Spirv); var module = new Expressions(shader.Spirv); - var recordBytes = sampler ? BindlessHeap.SamplerRecordBytes : BindlessHeap.ImageRecordBytes; - - var tested = module.ComparedWith(BindlessHeap.CallRecordFirstIndex).ToList(); - Assert.NotEmpty(tested); - Assert.All(tested, value => Assert.Equal(SpirvOp.ShiftRightLogical, module.Opcode(value))); - var indexes = module.ElementIndexes(sampler ? (uint)BindlessHeap.SamplerSlot : 0u); + var descriptorBytes = sampler ? BindlessHeap.SamplerRecordBytes : BindlessHeap.ImageRecordBytes; + var indexes = module.ElementIndexes(Assert.Single(module.Arrays(sampler ? (uint)BindlessHeap.SamplerSlot : 0u)).Array); Assert.NotEmpty(indexes); + var table = new HeapView(First: 1000, Stride: 440, FieldOffset: 64, Records: 49); + var packed = new HeapView(First: 7, Stride: descriptorBytes, FieldOffset: 0, Records: 4096); foreach (var index in indexes) { - var offset = module.ShiftedOperand(index, sampler ? 4u : 5u); - foreach (var record in new[] { 0u, 1234u, BindlessHeap.CallRecordFirstIndex - 1 }) + var (offset, word0, word1) = module.HeapViewInputs(index); + var values = new Dictionary(); + if (!sampler) { - Assert.Equal(record, module.Evaluate(index, offset, record * recordBytes)); + // Every element holds a float view. + values[module.HeapClassInput(index)] = 0; } - foreach (var record in new[] { BindlessHeap.CallRecordFirstIndex, BindlessHeap.Capacity, BindlessHeap.Capacity + 1234, 3 * BindlessHeap.Capacity + 7 }) + uint Element(HeapView view, uint byteOffset) => + module.Evaluate(index, new Dictionary(values) { [offset] = byteOffset, [word0] = view.Word0, [word1] = view.Word1 }); + + Assert.Equal(1000u, Element(table, 64)); + Assert.Equal(1003u, Element(table, 3 * 440 + 64)); + Assert.Equal(1048u, Element(table, 48 * 440 + 64)); + Assert.Equal(BindlessHeap.CallRecordNullIndex, Element(table, 49 * 440 + 64)); + Assert.Equal(BindlessHeap.CallRecordNullIndex, Element(table, 3 * 440)); + Assert.Equal(BindlessHeap.CallRecordNullIndex, Element(table, 3 * 440 + 96)); + Assert.Equal(BindlessHeap.CallRecordNullIndex, Element(table, uint.MaxValue)); + + Assert.Equal(7u, Element(packed, 0)); + Assert.Equal(7u + 1234, Element(packed, 1234 * descriptorBytes)); + Assert.Equal(7u + 4095, Element(packed, 4095 * descriptorBytes)); + Assert.Equal(BindlessHeap.CallRecordNullIndex, Element(packed, 4096 * descriptorBytes)); + Assert.Equal(BindlessHeap.CallRecordNullIndex, Element(packed, 1234 * descriptorBytes + 4)); + + Assert.Equal(BindlessHeap.CallRecordNullIndex, Element(HeapView.None, 0)); + Assert.Equal(BindlessHeap.CallRecordNullIndex, Element(HeapView.None, 5 * descriptorBytes)); + } + } + + // A table of records that hold more than a descriptor, read at a record the shader picks (a terrain + // pass reads each tile's height and mask textures from a table of 440-byte tile records): each descriptor of the + // record is a heap view of the program, and each draw evaluates the table V# for both, with the offset of the view's + // descriptor in a record. + [Fact] + public void EachDescriptorOfATablesRecordsIsAView() + { + var program = Program( + // The table V# in s16..s19 and the sampler in s24..s27 come from user data. + MoveScalarRegister(0, 16, 0), + MoveScalarRegister(4, 17, 1), + MoveScalarRegister(8, 18, 2), + MoveScalarRegister(12, 19, 3), + MoveScalarRegister(16, 24, 4), + MoveScalarRegister(20, 25, 5), + MoveScalarRegister(24, 26, 6), + MoveScalarRegister(28, 27, 7), + // s106 = readfirstlane(v7) * 440: the byte offset of the record the first lane asks for. + ReadFirstLane(32, 106, 7), + Sop2(36, "SMulI32", 106, Gen5Operand.Scalar(106), new Gen5Operand(Gen5OperandKind.LiteralConstant, 440)), + ScalarBufferLoad(44, 16, destination: 0, count: 8, dynamicOffsetRegister: 106), + ScalarBufferLoad(52, 16, destination: 8, count: 8, immediateOffset: 64, dynamicOffsetRegister: 106), + Image(60, "ImageSample", 0, 24), + Image(68, "ImageSample", 8, 24), + EndProgram(76)); + + var plan = Extract(program, stage: ShaderStage.Compute, bindlessHeap: true); + + Assert.Equal(2, plan.HeapRecords.Count); + Assert.Equal(2, plan.HeapRecordSources.Count); + Assert.Equal(plan.HeapRecordSources[0].Source, plan.HeapRecordSources[1].Source); + Assert.Equal([0u, 64u], plan.HeapRecordSources.Select(view => view.Immediate)); + Assert.Equal([0, 1], plan.HeapRecords.Select(plan.HeapViewOf)); + Assert.Equal(2u, plan.Info.HeapViewCount); + var request = Request(program, bindlessHeap: true); + Assert.Equal(2u, request.Bindings.HeapViewCount); + Assert.Equal([0, 1], request.HeapImageByMemoryIndex.Values.Select(use => use.View).Order()); + Assert.True(Gen5SpirvTranslator.TryCompileProgram(request, out var shader, out var error), error); + Gen5MipStatisticsTests.ValidateWhenAvailable(shader.Spirv); + + var userData = new uint[64]; + userData[0] = 0x0001_0000; + userData[1] = 440u << 16; + userData[2] = 49; + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + Assert.True(ResourceMaterializer.Materialize(plan, Inputs(userData), ref snapshot, ref specialization)); + Assert.Equal([new BindlessHeapDescriptor(false, 0x0001_0000, 49, 440), new BindlessHeapDescriptor(false, 0x0001_0000, 49, 440, 64)], snapshot.Heaps); + } + + // Where a view's descriptors are in guest memory. The records of a table are its elements: the T# 64 bytes into + // record 3 of a table of 440-byte records is at the heap's base + 3 * 440 + 64, whether the shader keeps 64 or a + // whole record more in its immediate. A heap whose stride is the descriptor's size or less is packed descriptors. + [Fact] + public void AViewsRecordsAreItsHeapsRecords() + { + var table = new BindlessHeapDescriptor(false, 0x0001_0000, 49, 440, 64); + var view = HeapView.Of(table, first: 1000, records: 49); + Assert.Equal(new HeapView(1000, 440, 64, 49), view); + Assert.Equal(0x0001_0000ul + 3 * 440 + 64, view.DescriptorAddress(table, 3)); + Assert.Equal(view, HeapView.Of(table with { Immediate = 440 + 64 }, first: 1000, records: 49)); + + var packed = new BindlessHeapDescriptor(false, 0x0002_0000, 4096, 32, 32); + Assert.Equal(new HeapView(0, 32, 0, 4096), HeapView.Of(packed, first: 0, records: 4096)); + Assert.Equal(0x0002_0000ul + 5 * 32, HeapView.Of(packed, 0, 4096).DescriptorAddress(packed, 5)); + var samplers = new BindlessHeapDescriptor(true, 0x0003_0000, 64, 4); + Assert.Equal(new HeapView(0, BindlessHeap.SamplerRecordBytes, 0, 64), HeapView.Of(samplers, first: 0, records: 64)); + + var words = new HeapView(1000, 440, 64, 49); + Assert.Equal((1000u | (440u << 18), 49u | (64u << 18)), (words.Word0, words.Word1)); + var last = new HeapView(BindlessHeap.CallRecordFirstIndex - 1, 0x3FFF, 0x3FFF, BindlessHeap.CallRecordFirstIndex); + Assert.Equal((last.First, last.Stride, last.Records, last.FieldOffset), + (last.Word0 & HeapView.ElementMask, last.Word0 >> HeapView.ElementBits, last.Word1 & HeapView.ElementMask, last.Word1 >> HeapView.ElementBits)); + } + + // A T# with RESOURCE_LEVEL set (word 2 bit 31, a GFX10 field) is a texture like any other: terrain + // tile records hold their R16 height textures that way, and the heap gave them no view, so the terrain cull sampled no + // height. A freed record (0xFEFEFEFE words) still has reserved bits set. + [Fact] + public void AHeapRecordWithItsResourceLevelSetIsAnImage() + { + uint[] height = [0x80689630, 0x00700000, 0x80800080, 0x9050024C, 0, 0, 0, 0]; + uint[] levelClear = [0x80689630, 0x00700000, 0x00800080, 0x9050024C, 0, 0, 0, 0]; + uint[] freed = [0xFEFEFEFE, 0xFEFEFEFE, 0xFEFEFEFE, 0xFEFEFEFE, 0xFEFEFEFE, 0xFEFEFEFE, 0xFEFEFEFE, 0xFEFEFEFE]; + + Assert.Equal(ImageNumericClass.Float, ResourceMaterializer.HeapImageNumericClass(height)); + Assert.Equal(ImageNumericClass.Float, ResourceMaterializer.HeapImageNumericClass(levelClear)); + Assert.Equal(ImageNumericClass.Unsupported, ResourceMaterializer.HeapImageNumericClass(freed)); + Assert.Equal(ImageNumericClass.Unsupported, + ResourceMaterializer.HeapImageNumericClass([0x80689630, 0x00700000, 0xC0800080, 0x9050024C, 0, 0, 0, 0])); + } + + // A record can hold an integer texture: terrain tile records can hold an 8-bit unsigned 513x513 mask + // 96 bytes in, next to the R16 height, and its foliage passes read an 8-bit signed 128x128 map. The heap gave such + // a record no view (its arrays were float), so those reads were null. The record's format names the numeric class + // of its view; a format the shader would have to convert has none. + [Fact] + public void AHeapRecordOfAnIntegerTextureHasItsNumericClass() + { + uint[] mask = [0x80813360, 0x00500000, 0x80800080, 0x90500924, 0, 0, 0, 0]; + uint[] signed = [0x80813360, 0xC0600000, 0x001FC01F, 0x90500924, 0, 0, 0, 0]; + uint[] scaled = [0x80813360, 0x00300000, 0x80800080, 0x90500924, 0, 0, 0, 0]; + + Assert.Equal(ImageNumericClass.Uint, ResourceMaterializer.HeapImageNumericClass(mask)); + Assert.Equal(ImageNumericClass.Sint, ResourceMaterializer.HeapImageNumericClass(signed)); + Assert.Equal(ImageNumericClass.Unsupported, ResourceMaterializer.HeapImageNumericClass(scaled)); + Assert.Equal(1u, BindlessHeap.ClassCode(ImageNumericClass.Uint)); + Assert.Equal(2u, BindlessHeap.ClassCode(ImageNumericClass.Sint)); + Assert.Equal(0u, BindlessHeap.ClassCode(ImageNumericClass.Float)); + // Loads read integer textures; the cube and depth-compare classes are sampled. + Assert.Equal([true, true, true, true, false, false, false, false], + Enumerable.Range(0, BindlessHeap.ImageClasses.Length).Select(BindlessHeap.HoldsIntegers).ToArray()); + Assert.Equal(BindlessHeap.Capacity * BindlessHeap.ClassBits, BindlessHeap.ClassWords * 32); + Assert.Equal(BindlessHeap.ClassesPerWord, 1u << (int)BindlessHeap.ClassWordShift); + } + + // An R128 image instruction reads a 16-byte T#: the words after it in the heap are another field of the record. + // Large material records can hold their textures as 16-byte T#s one after another (at offsets such as 468, 484 and + // 500 bytes in), so the 32 bytes at each were a T# followed by the next one, whose words set reserved bits of the + // first: every such record was refused. The view of an R128 read says so, and its descriptors are 16 bytes. + [Fact] + public void AnR128ImageReadFromAHeapIsASixteenByteDescriptor() + { + var plan = Extract(ResourceTrackerTests.LaneIndexedImageProgram(r128: true), stage: ShaderStage.Compute, bindlessHeap: true); + + var record = Assert.Single(plan.HeapRecords); + Assert.True(plan.DescriptorSources[(int)record.Source].Heap!.R128); + Assert.True(Assert.Single(plan.HeapRecordSources).R128); + Assert.False(Assert.Single(Extract(ResourceTrackerTests.LaneIndexedImageProgram(), stage: ShaderStage.Compute, bindlessHeap: true) + .HeapRecordSources).R128); + + var userData = new uint[64]; + userData[0] = 0x0001_0000; + userData[1] = 1016u << 16; + userData[2] = 257; + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + Assert.True(ResourceMaterializer.Materialize(plan, Inputs(userData), ref snapshot, ref specialization)); + var heap = Assert.Single(snapshot.Heaps); + Assert.Equal(new BindlessHeapDescriptor(false, 0x0001_0000, 257, 1016, 0, R128: true), heap); + Assert.Equal(BindlessHeap.R128RecordBytes, heap.DescriptorBytes); + Assert.Equal(BindlessHeap.ImageRecordBytes, (heap with { R128 = false }).DescriptorBytes); + Assert.Equal(BindlessHeap.SamplerRecordBytes, (heap with { Sampler = true, R128 = false }).DescriptorBytes); + // A heap of packed 16-byte T#s has one element for each. + Assert.Equal(new HeapView(5, 16, 0, 100), HeapView.Of(new BindlessHeapDescriptor(false, 0x1000, 100, 16, 0, R128: true), 5, 100)); + Assert.Equal(new HeapView(5, 32, 0, 100), HeapView.Of(new BindlessHeapDescriptor(false, 0x1000, 100, 16), 5, 100)); + + // Two of the material record's T#s, as the host reads them: 32 bytes at the first, and the first one's four words. + uint[] overlapped = [0xB3396E00, 0xCB500000, 0x003FC03F, 0x90580FAC, 0x900006E0, 0x0A900000, 0x00000000, 0x90500FAC]; + uint[] extended = [0xB3396E00, 0xCB500000, 0x003FC03F, 0x90580FAC, 0, 0, 0, 0]; + Assert.Equal(ImageNumericClass.Unsupported, ResourceMaterializer.HeapImageNumericClass(overlapped)); + Assert.Equal(ImageNumericClass.Float, ResourceMaterializer.HeapImageNumericClass(extended, r128: true)); + } + + // A load of a heap record reads the texel's bits whatever the texture's format, so it has a float, an unsigned and a + // signed declaration of its array, all at the array's binding. Each reads the record's element only when the host + // says the element holds a view of its numeric class (the class words after the mark bitsets), and the null element + // otherwise: no declaration reads a view of another class. + [Theory] + [InlineData("ImageLoad")] + [InlineData("ImageLoadMip")] + [InlineData("ImageGetResinfo")] + public void AHeapLoadReadsAnIntegerRecordThroughTheIntegerDeclarationsOfItsArray(string opcode) + { + var program = ResourceTrackerTests.LaneIndexedImageProgram(opcode: opcode); + Assert.True(Gen5SpirvTranslator.TryCompileProgram(Request(program, ShaderStage.Pixel, bindlessHeap: true), out var shader, out var error), error); + Gen5MipStatisticsTests.ValidateWhenAvailable(shader.Spirv); + var module = new Expressions(shader.Spirv); + + var arrays = module.Arrays(0); + Assert.Equal(["float", "int", "uint"], arrays.Select(array => array.SampledType).Order().ToArray()); + var view = new HeapView(First: 1000, Stride: 440, FieldOffset: 96, Records: 31); + foreach (var (array, sampledType) in arrays) + { + var code = sampledType switch { "uint" => 1u, "int" => 2u, _ => 0u }; + var indexes = module.ElementIndexes(array); + Assert.NotEmpty(indexes); + foreach (var index in indexes) { - Assert.Equal(BindlessHeap.CallRecordNullIndex, module.Evaluate(index, offset, record * recordBytes)); + var (offset, word0, word1) = module.HeapViewInputs(index); + var classes = module.HeapClassInput(index); + // Record 5 is element 1005: element 13 of its class word (1005 % 16), two bits each. + uint Element(uint elementClass) => module.Evaluate(index, new Dictionary + { + [offset] = 5 * 440 + 96, [word0] = view.Word0, [word1] = view.Word1, [classes] = 0xF3FFFFFF | (elementClass << 26), + }); + for (var elementClass = 0u; elementClass < 4; elementClass++) + { + Assert.Equal(elementClass == code ? 1005u : BindlessHeap.CallRecordNullIndex, Element(elementClass)); + } } } + + Assert.Equal(BindlessHeap.MarkWords + (1005u >> (int)BindlessHeap.ClassWordShift), module.HeapClassWord(module.ElementIndexes(arrays[0].Array)[0])); + } + + // A sampled read has the float declaration alone, and takes the null element of a record that holds an integer view. + [Fact] + public void AHeapSampleDoesNotReadAnIntegerRecord() + { + Assert.True(Gen5SpirvTranslator.TryCompileProgram( + Request(ResourceTrackerTests.LaneIndexedImageProgram(), ShaderStage.Pixel, bindlessHeap: true), out var shader, out var error), error); + var module = new Expressions(shader.Spirv); + + var (array, sampledType) = Assert.Single(module.Arrays(0)); + Assert.Equal("float", sampledType); + var view = new HeapView(First: 7, Stride: BindlessHeap.ImageRecordBytes, FieldOffset: 0, Records: 4096); + foreach (var index in module.ElementIndexes(array)) + { + var (offset, word0, word1) = module.HeapViewInputs(index); + var classes = module.HeapClassInput(index); + uint Element(uint classWord) => module.Evaluate(index, new Dictionary + { + [offset] = 2 * BindlessHeap.ImageRecordBytes, [word0] = view.Word0, [word1] = view.Word1, [classes] = classWord, + }); + // Record 2 is element 9: bits 18 and 19 of its class word. + Assert.Equal(9u, Element(0)); + Assert.Equal(9u, Element(~(3u << 18))); + Assert.Equal(BindlessHeap.CallRecordNullIndex, Element(1u << 18)); + Assert.Equal(BindlessHeap.CallRecordNullIndex, Element(2u << 18)); + } } // Without the heap set nothing changes: compute still rejects the lane-chosen image. @@ -229,6 +472,9 @@ private sealed class Expressions private readonly Dictionary _constants = []; private readonly Dictionary _bindings = []; private readonly List<(uint Base, uint Index)> _elementPointers = []; + private readonly Dictionary _types = []; + private readonly Dictionary _variableTypes = []; + private readonly Dictionary _loads = []; public Expressions(byte[] code) { @@ -256,9 +502,20 @@ public Expressions(byte[] code) break; case SpirvOp.AccessChain when operands.Length >= 4: _elementPointers.Add((operands[2], operands[3])); + _definitions[operands[1]] = (opcode, operands[2..]); + break; + case SpirvOp.TypeFloat or SpirvOp.TypeInt or SpirvOp.TypeImage or SpirvOp.TypeRuntimeArray or SpirvOp.TypePointer: + _types[operands[0]] = (opcode, operands[1..]); + break; + case SpirvOp.Variable: + _variableTypes[operands[1]] = operands[0]; + break; + case SpirvOp.Load: + _loads[operands[1]] = operands[2]; break; - case SpirvOp.IAdd or SpirvOp.ISub or SpirvOp.BitwiseAnd or SpirvOp.BitwiseOr or SpirvOp.ShiftLeftLogical or - SpirvOp.ShiftRightLogical or SpirvOp.ULessThan or SpirvOp.Select or SpirvOp.CopyObject or SpirvOp.Bitcast: + case SpirvOp.IAdd or SpirvOp.ISub or SpirvOp.IMul or SpirvOp.UDiv or SpirvOp.BitwiseAnd or SpirvOp.BitwiseOr or + SpirvOp.ShiftLeftLogical or SpirvOp.ShiftRightLogical or SpirvOp.ULessThan or SpirvOp.IEqual or SpirvOp.LogicalAnd or + SpirvOp.Select or SpirvOp.CopyObject or SpirvOp.Bitcast: _definitions[operands[1]] = (opcode, operands[2..]); break; } @@ -267,15 +524,62 @@ public Expressions(byte[] code) } } - // The indexes of the element pointers into the set-1 array at binding slot. - public List ElementIndexes(uint slot) + // The declarations of the set-1 array at binding slot, each with the sampled type of its images ("sampler" for + // a sampler array). + public List<(uint Array, string SampledType)> Arrays(uint slot) => + _bindings.Where(entry => entry.Value.Set == BindlessHeap.DescriptorSet && entry.Value.Binding == slot) + .Select(entry => (entry.Key, SampledType(entry.Key))).ToList(); + + private string SampledType(uint array) + { + if (!_types.TryGetValue(_types[_types[_variableTypes[array]].Operands[1]].Operands[0], out var element) || + element.Opcode != SpirvOp.TypeImage) + { + return "sampler"; + } + + var sampled = _types[element.Operands[0]]; + return sampled.Opcode == SpirvOp.TypeFloat ? "float" : sampled.Operands[1] != 0 ? "int" : "uint"; + } + + // The indexes of the element pointers into a set-1 array. + public List ElementIndexes(uint array) => + _elementPointers.Where(pointer => pointer.Base == array).Select(pointer => pointer.Index).ToList(); + + // The load of the class word an image element index is chosen by: the one value its computation shifts that is + // read from the feedback buffer. + public uint HeapClassInput(uint index) => + Assert.Single(Reachable(index).Select(id => _definitions[id]).Where(definition => + definition.Opcode == SpirvOp.ShiftRightLogical && _loads.TryGetValue(definition.Operands[0], out var pointer) && + _definitions.TryGetValue(pointer, out var chain) && chain.Opcode == SpirvOp.AccessChain && + _bindings.GetValueOrDefault(chain.Operands[0]) == (BindlessHeap.DescriptorSet, BindlessHeap.FeedbackBinding)) + .Select(definition => definition.Operands[0]).Distinct()); + + // The feedback word that load reads, for the element the view inputs of the tests above give (1005). + public uint HeapClassWord(uint index) + { + var pointer = _definitions[_loads[HeapClassInput(index)]]; + Assert.Equal(SpirvOp.AccessChain, pointer.Opcode); + var (offset, word0, word1) = HeapViewInputs(index); + var view = new HeapView(First: 1000, Stride: 440, FieldOffset: 96, Records: 31); + return Evaluate(pointer.Operands[^1], new Dictionary { [offset] = 5 * 440 + 96, [word0] = view.Word0, [word1] = view.Word1 }); + } + + // What a heap element index is computed from: the read's byte offset (the dividend of the division by the view's + // stride) and the two shader data dwords of its heap view (the stride and the record count are fields of them). + public (uint Offset, uint Word0, uint Word1) HeapViewInputs(uint index) { - var array = Assert.Single(_bindings, entry => entry.Value.Set == BindlessHeap.DescriptorSet && entry.Value.Binding == slot).Key; - return _elementPointers.Where(pointer => pointer.Base == array).Select(pointer => pointer.Index).ToList(); + var division = Assert.Single(Reachable(index).Where(id => _definitions[id].Opcode == SpirvOp.UDiv).Distinct()); + var (_, operands) = _definitions[division]; + var stride = _definitions[operands[1]]; + Assert.Equal(SpirvOp.ShiftRightLogical, stride.Opcode); + var bound = Assert.Single(Reachable(index).Where(id => _definitions[id].Opcode == SpirvOp.ULessThan).Distinct()); + var records = _definitions[_definitions[bound].Operands[1]]; + Assert.Equal(SpirvOp.BitwiseAnd, records.Opcode); + return (operands[0], stride.Operands[0], records.Operands[0]); } - // What the nearest logical right shift by amount under value shifts: the read's byte offset. - public uint ShiftedOperand(uint value, uint amount) + private IEnumerable Reachable(uint value) { var pending = new Queue(); pending.Enqueue(value); @@ -287,34 +591,20 @@ public uint ShiftedOperand(uint value, uint amount) continue; } - if (definition.Opcode == SpirvOp.ShiftRightLogical && - _constants.TryGetValue(definition.Operands[1], out var shift) && shift == amount) - { - return definition.Operands[0]; - } - + yield return id; foreach (var operand in definition.Operands) { pending.Enqueue(operand); } } - - throw new InvalidOperationException($"No right shift by {amount} feeds %{value}."); } - // The left operands of the unsigned comparisons with the constant bound. - public IEnumerable ComparedWith(uint bound) => - _definitions.Values - .Where(definition => definition.Opcode == SpirvOp.ULessThan && - _constants.TryGetValue(definition.Operands[1], out var value) && value == bound) - .Select(definition => definition.Operands[0]); - public SpirvOp Opcode(uint id) => _definitions.TryGetValue(id, out var definition) ? definition.Opcode : SpirvOp.Nop; - // The value of id when the value named offset holds value. - public uint Evaluate(uint id, uint offset, uint value) + // The value of id when the named values hold these. + public uint Evaluate(uint id, IReadOnlyDictionary values) { - if (id == offset) + if (values.TryGetValue(id, out var value)) { return value; } @@ -325,16 +615,20 @@ public uint Evaluate(uint id, uint offset, uint value) } var (opcode, operands) = _definitions[id]; - uint Operand(int index) => Evaluate(operands[index], offset, value); + uint Operand(int index) => Evaluate(operands[index], values); return opcode switch { SpirvOp.IAdd => Operand(0) + Operand(1), SpirvOp.ISub => Operand(0) - Operand(1), + SpirvOp.IMul => Operand(0) * Operand(1), + SpirvOp.UDiv => Operand(0) / Operand(1), SpirvOp.BitwiseAnd => Operand(0) & Operand(1), SpirvOp.BitwiseOr => Operand(0) | Operand(1), SpirvOp.ShiftLeftLogical => Operand(0) << (int)(Operand(1) & 31), SpirvOp.ShiftRightLogical => Operand(0) >> (int)(Operand(1) & 31), SpirvOp.ULessThan => Operand(0) < Operand(1) ? 1u : 0u, + SpirvOp.IEqual => Operand(0) == Operand(1) ? 1u : 0u, + SpirvOp.LogicalAnd => Operand(0) & Operand(1), SpirvOp.Select => Operand(0) != 0 ? Operand(1) : Operand(2), _ => Operand(0), }; diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceMaterializationCacheTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceMaterializationCacheTests.cs index 937792792..bdad6612b 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceMaterializationCacheTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceMaterializationCacheTests.cs @@ -302,6 +302,59 @@ public void AChangedTableOnlyWordRefreshesOnlyTheTable() Assert.Equal((1, 1, 1), (cache.Hits, cache.Misses, cache.TableRefreshes)); } + // A program that reads descriptors from a table of records (a bindless heap) takes the table's V# from its resource + // table. The guest allocates both per frame, so the resource table and the V# in it name other addresses from draw to + // draw while everything else stays the same, and the cache serves the draw from an entry it rebases or refreshes. The + // heap the draw reports is the table where it is now, not where the entry saw it: a terrain cull lost + // its tile heights this way after a few minutes (the host kept resolving the records of a table + // address 100 s old). + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ACachedDrawReportsTheHeapWhereItIsNow(bool resourceTableMoves) + { + var program = Program( + // The heap V# in s16..s19 comes from the resource table s0 points at; the sampler in s24..s27 from user data. + ScalarLoad(0, 0, 16, 4), + MoveScalarRegister(8, 24, 4), + MoveScalarRegister(12, 25, 5), + MoveScalarRegister(16, 26, 6), + MoveScalarRegister(20, 27, 7), + // A buffer the program writes through a V# of the same resource table. + ScalarLoad(24, 0, 32, 4, immediateOffset: 16), + BufferLoad(32, 32), + // The table of records is also a buffer the program reads other fields of. + BufferLoad(36, 16, offset: 320), + // s106 = readfirstlane(v7) * 440: the byte offset of the record the first lane asks for. + ReadFirstLane(44, 106, 7), + Sop2(48, "SMulI32", 106, Gen5Operand.Scalar(106), new Gen5Operand(Gen5OperandKind.LiteralConstant, 440)), + ScalarBufferLoad(56, 16, destination: 0, count: 8, dynamicOffsetRegister: 106), + Image(64, "ImageSample", 0, 24), + EndProgram(72)); + var plan = ShaderResourcePlan.Extract(program, ShaderStage.Compute, Hash, 0, 9, bindlessHeap: true, scalarDataOnDevice: true); + Assert.Single(plan.HeapRecordSources); + var memory = new TestWordMemory { Base = 0x10000, Words = new uint[0x4000] }; + var cache = new ResourceMaterializationCache(); + + for (var draw = 0; draw < 24; draw++) + { + var resourceTable = 0x10000u + (resourceTableMoves ? (uint)draw * 0x100u : 0u); + var heap = 0x0020_0000u + (uint)draw * 0x1000u; + var words = memory.Words.AsSpan((int)(resourceTable - 0x10000) / 4); + words[0] = heap; + words[1] = 440u << 16; + words[2] = 49; + words[4] = 0x0030_0000u + (uint)draw * 0x1000u; + words[6] = 256; + words[7] = 0x2_0000; + uint[] userData = [resourceTable, 0, 0, 0, 0, 0, 0, 0, 0]; + Assert.True(RunWords(cache, plan, memory, userData, out var snapshot)); + Assert.Equal([new BindlessHeapDescriptor(false, heap, 49, 440)], snapshot.Heaps); + } + + Assert.True(cache.Hits + cache.TableRefreshes > 0, $"hits={cache.Hits} misses={cache.Misses} refreshes={cache.TableRefreshes}"); + } + [Fact] public void AnUnreadableTableWordFallsBackToAFullWalk() { diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceMaterializerTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceMaterializerTests.cs index aa83b2140..8cfffab43 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceMaterializerTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceMaterializerTests.cs @@ -195,6 +195,71 @@ bool ReadWord(ulong address, out uint word) Assert.Equal(1u, Assert.Single(reads, read => read.ComponentIndex == 1).Value); } + // A 224-byte-stride material table of 10000 records: the exhaustive probe count (step 32) + // is over the cap, so only a selector the shader clamps can be materialized. Key 1 sits at + // the record the clamped selector reaches (4 + 224 * 3); key 2, whose descriptor is of + // another dimension, sits at a record the clamp excludes (4 + 224 * 2000). + private static (ShaderResourcePlan Plan, ResourceRuntimeInputs Inputs, uint[] Reachable) ClampedTable((string Opcode, uint Value)? clamp) + { + var plan = Extract(ResourceTrackerTests.IndirectImageProgram(false, selectorClamp: clamp)); + uint[] userData = [0x1000, 224 << 16, 10000, 0, 0x90000, 16 << 16, 16, 0, 7]; + var memory = new TestWordMemory { Words = new uint[0x100000 / 4] }; + var reachable = ResourceTrackerTests.ImageDescriptor(); + var excluded = reachable.ToArray(); + excluded[3] = (excluded[3] & 0x0FFFFFFF) | (10u << 28); + memory.At(0x1000 + 4 + 224 * 3) = 1; + memory.At(0x1000 + 4 + 224 * 2000) = 2; + ResourceTrackerTests.WriteImage(memory, 0x90000 + 32, reachable); + ResourceTrackerTests.WriteImage(memory, 0x90000 + 64, excluded); + return (plan, Inputs(userData, readCleanMemory: memory.Read), reachable); + } + + [Theory] + [InlineData("VMinU32", 5u)] + [InlineData("VMed3U32", 5u)] + [InlineData("VAndB32", 7u)] + public void ClampedSelectorProbesOnlyTheClampedRecords(string opcode, uint value) + { + var (plan, inputs, reachable) = ClampedTable((opcode, value)); + var selector = plan.DescriptorSources[(int)plan.Info.Images[0].Source].IndirectImage!; + Assert.Equal(value, selector.SelectorBound); + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + + Assert.True(ResourceMaterializer.Materialize(plan, inputs, ref snapshot, ref specialization)); + Assert.Equal(2, snapshot.Images.Length); + Assert.Contains(snapshot.Images, image => image.SequenceEqual(reachable)); + } + + // A table too large to enumerate reads as the null image instead of failing the draw. + [Fact] + public void UnclampedSelectorOverTheProbeCapReadsTheNullImage() + { + var (plan, inputs, _) = ClampedTable(null); + Assert.Null(plan.DescriptorSources[(int)plan.Info.Images[0].Source].IndirectImage!.SelectorBound); + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + + Assert.True(ResourceMaterializer.Materialize(plan, inputs, ref snapshot, ref specialization, out var failureKind)); + Assert.Equal(ResourceMaterializationFailure.None, failureKind); + } + + [Fact] + public void ClampedSelectorReportsTheClampBoundedMode() + { + var (plan, inputs, _) = ClampedTable(("VMinU32", 2000u)); + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + var captures = new List(); + + Assert.False(ResourceMaterializer.Materialize(plan, inputs, ref snapshot, ref specialization, + out var failureKind, captures.Add)); + Assert.Equal(ResourceMaterializationFailure.IncompatibleImageCandidates, failureKind); + var diagnostic = Assert.IsType(Assert.Single(captures).SelectorDiagnostic); + Assert.Equal("clamp_bounded", diagnostic.SelectionMode); + Assert.Equal([new SelectorKeyProbe(4 + 224 * 3, 1), new SelectorKeyProbe(4 + 224 * 2000, 2)], diagnostic.KeyProbes); + } + private static IEnumerable ImageWords(ref uint pc, uint register, uint address, uint format) { uint[] words = [address, format << 20, 3 | (3 << 14), 0xFAC | (ImageType2D << 28), 0, 0, 0, 0]; @@ -385,6 +450,26 @@ public void ScaledImage_MaterializesAsAFloatSampledImage() Assert.Equal(ImageNumericClass.Float, image.NumericClass); } + // A 16_SINT storage image the program only writes (as a shipped compute shader does) is compiled as + // unsigned bits: the stored low bits are the same. + [Fact] + public void WriteOnlySignedStorageImage_IsCompiledAsUnsignedBits() + { + const uint format16Sint = 12; + var instructions = new List(); + uint pc = 0; + instructions.AddRange(ImageWords(ref pc, 16, 0x1000, format16Sint)); + instructions.Add(Image(pc, "ImageStore", 16)); + instructions.Add(EndProgram(pc + 8)); + var plan = Extract(Program([.. instructions])); + var snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + + Assert.True(ResourceMaterializer.Materialize(plan, Inputs([]), ref snapshot, ref specialization)); + var image = Assert.Single(ResourceMaterializer.ApplyTo(plan, specialization).Info.Images); + Assert.Equal(ImageNumericClass.Uint, image.NumericClass); + } + // Three images share one sampler; the packed and signed ones need point filtering, // so the sampler splits and their accesses sample through the duplicate. [Fact] diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceTrackerTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceTrackerTests.cs index d682528d6..daef64b79 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceTrackerTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceTrackerTests.cs @@ -94,7 +94,8 @@ public void ADescriptorWordMergedThroughManyBranchesIsPlannedQuickly() } // Behind exec branches the same word is a web of phis, which the runtime-descriptor check walks for a memory read. - // A buffer base that differs per lane cannot be bound, so the plan is rejected, at once. + // The V# the branches choose has no single source to bind, so the load reads it from its registers when it runs; + // the walk still finishes at once. [Fact] public void ADescriptorWordMergedThroughManyExecBranchesIsPlannedQuickly() { @@ -143,8 +144,8 @@ public void ADescriptorWordMergedThroughManyExecBranchesIsPlannedQuickly() planning.Start(); Assert.True(planning.Join(TimeSpan.FromSeconds(30)), "planning did not finish"); - var rejection = Assert.IsType(failure); - Assert.Contains("BufferHandle dword 0 is not a valid runtime value", rejection.Message); + Assert.Null(failure); + Assert.True(Extract(program).Memory.Entries.Single(memory => memory.Pc == pc).DeviceDescriptor); } [Fact] @@ -361,6 +362,36 @@ public void ThePlanListsOnlyTheOptedInFallbacks() Assert.Empty(plan.NullBindlessDescriptorPcs); } + // A T# whose two halves a shader reads from one scalar buffer at a uniform record offset, but not next to each other + // (a terrain material pixel shader builds s88..s95 from record bytes 48..63 and 192..207): each + // word is a scalar buffer read the host evaluates when the draw is bound, so the image is a runtime descriptor. + [Fact] + public void AnImageAssembledFromTwoScalarBufferReadsIsEvaluatedPerWord() + { + var program = Program( + // The record table V# in s16..s19 and the record index in s4 come from user data. + MoveScalarRegister(0, 16, 0), + MoveScalarRegister(4, 17, 1), + MoveScalarRegister(8, 18, 2), + MoveScalarRegister(12, 19, 3), + Sop2(16, "SLshlB32", 106, Gen5Operand.Scalar(4), Operand(7)), + ScalarBufferLoad(20, 16, destination: 20, count: 4, immediateOffset: 16, dynamicOffsetRegister: 106), + ScalarBufferLoad(28, 16, destination: 24, count: 4, immediateOffset: 96, dynamicOffsetRegister: 106), + Image(36, "ImageLoad", 20), + EndProgram(44)); + var memory = new TestWordMemory { Base = 0x1000, Words = new uint[128] }; + for (var word = 0; word < memory.Words.Length; word++) + memory.Words[word] = 0xA000u + (uint)word; + + var plan = Extract(program, stage: ShaderStage.Pixel); + + var image = Assert.Single(plan.Info.Images); + Assert.True(RuntimeValueEvaluator.EvaluateDescriptorSource(plan, image.Source, + Inputs([0x1000, 0, 0x200, 0, 2], memory.Read), out var words)); + // Record 2 starts at byte 256 (word 64): words 4..7 and 24..27 of it. + Assert.Equal([0xA044u, 0xA045u, 0xA046u, 0xA047u, 0xA058u, 0xA059u, 0xA05Au, 0xA05Bu], words.Dwords.ToArray()); + } + internal static Gen5ShaderProgram LaneIndexedSamplerProgram() => Program( MoveScalarRegister(0, 16, 0), MoveScalarRegister(4, 17, 1), @@ -372,7 +403,7 @@ internal static Gen5ShaderProgram LaneIndexedSamplerProgram() => Program( Image(32, "ImageSample", 8, 24), EndProgram(40)); - internal static Gen5ShaderProgram LaneIndexedImageProgram(uint dimension = 1) => Program( + internal static Gen5ShaderProgram LaneIndexedImageProgram(uint dimension = 1, string opcode = "ImageSample", bool r128 = false) => Program( // The table V# in s16..s19 and the sampler in s24..s27 come from user data. MoveScalarRegister(0, 16, 0), MoveScalarRegister(4, 17, 1), @@ -386,7 +417,7 @@ internal static Gen5ShaderProgram LaneIndexedImageProgram(uint dimension = 1) => ReadFirstLane(32, 106, 7), Sop2(36, "SLshlB32", 106, Gen5Operand.Scalar(106), Operand(5)), ScalarBufferLoad(40, 16, destination: 0, count: 8, dynamicOffsetRegister: 106), - Image(48, "ImageSample", 0, 24, dimension: dimension), + Image(48, opcode, 0, 24, dimension: dimension, r128: r128), EndProgram(56)); // A shader that selects among states with v_cmpx and s_cbranch_execz sets a constant sampler up in the first state's block and samples // with it in a later state's block. The skip edge of the first branch reaches the join with the sampler registers unwritten, so the host @@ -610,7 +641,7 @@ [.. Enumerable.Range(0, 8).Select(index => MoveScalar((uint)index * 4, 16 + (uin // The material table s[0:3], the heap s[4:7], the key selector in s8; the image words // come from the heap record the key selects. - internal static Gen5ShaderProgram IndirectImageProgram(bool malformed, int materialImmediate = 0, bool memoryBackedMaterial = false) + internal static Gen5ShaderProgram IndirectImageProgram(bool malformed, int materialImmediate = 0, bool memoryBackedMaterial = false, bool laneKey = false, (string Opcode, uint Value)? selectorClamp = null) { var instructions = new List(); uint pc = 0x1000; @@ -624,7 +655,14 @@ internal static Gen5ShaderProgram IndirectImageProgram(bool malformed, int mater Add(At(current => ScalarLoad(current, 28, destination: 0))); } - Add(At(current => Vop1(current, "VMovB32", 1, Gen5Operand.Scalar(8)))); + Add(At(current => Vop1(current, "VMovB32", 1, laneKey ? Gen5Operand.Vector(0) : Gen5Operand.Scalar(8)))); + if (selectorClamp is { } clamp) + { + Add(At(current => clamp.Opcode == "VMed3U32" ? + Vop3(current, "VMed3U32", 1, Operand(0), Operand(clamp.Value), Gen5Operand.Vector(1)) : + Vop2(current, clamp.Opcode, 1, Operand(clamp.Value), Gen5Operand.Vector(1)))); + } + Add(At(current => ReadFirstLane(current, 9, 1))); Add(At(current => Sop2(current, "SMulI32", 10, Gen5Operand.Scalar(9), Operand(224)))); Add(At(current => Sop2(current, "SAddU32", 11, Gen5Operand.Scalar(10), Operand(4)))); @@ -795,11 +833,17 @@ public void IndirectImage_MemoryBackedMaterialReadsThroughTheCleanReader() Assert.Same(priorSpecialization, specialization); } + // A heap record whose last word is not next to the others is not an indirect heap image; its words are still scalar + // buffer reads at a uniform offset, so the host reads them one by one when the draw is bound. [Fact] - public void MalformedIndirectImage_IsRejected() + public void MalformedIndirectImage_IsReadWordByWord() { - var error = Assert.Throws(() => Extract(IndirectImageProgram(true))); - Assert.Contains("not a valid runtime value", error.Message); + var plan = Extract(IndirectImageProgram(true)); + + var image = Assert.Single(plan.Info.Images); + var source = plan.DescriptorSources[(int)image.Source]; + Assert.Null(source.IndirectImage); + Assert.All(source.Dwords, dword => Assert.Equal(ScalarValueKind.ScalarBufferWord, dword.Kind)); } [Fact] @@ -957,10 +1001,88 @@ public void PhiValidation() BufferLoad(32, 8), EndProgram(36)); - var error = Assert.Throws(() => Extract(program)); + // The unevaluated branch picks the V#, so the access reads it from its registers. + var plan = Extract(program); + Assert.Empty(plan.Info.Buffers); + Assert.True(plan.Memory.TryGetIndex(32, 0, out var index)); + Assert.True(plan.Memory[index].DeviceDescriptor); + } + + // A branch the plan cannot evaluate picks the V#: a descriptor loaded from memory, or one built from a lane value. + private static Gen5ShaderProgram PhiSelectedDescriptor(string opcode = "BufferLoadDwordx3") => Program( + Branch(0, "SCbranchScc1", 3), + ScalarLoad(4, 2, 8, count: 4), Branch(12, "SBranch", 4), + ReadFirstLane(16, 8, 0), MoveScalar(20, 9, 0), MoveScalar(24, 10, 64), MoveScalar(28, 11, 0), + BufferAccess(32, opcode, 8, dwords: 3), + EndProgram(40)); + + [Fact] + public void DescriptorChosenByControlFlow_ReadsThroughRegisters() + { + var plan = Extract(PhiSelectedDescriptor()); + + Assert.Empty(plan.Info.Buffers); + Assert.True(plan.Info.UsesDeviceAddresses); + Assert.True(plan.Memory.TryGetIndex(32, 0, out var index)); + Assert.True(plan.Memory[index].DeviceDescriptor); + } + + [Fact] + public void DescriptorWalkedByALoop_ReadsThroughRegisters() + { + // Each iteration loads the next V# through the base of the current one. + var plan = Extract(Program( + ScalarLoad(0, 2, 8, count: 4), + BufferLoad(8, 8, dwords: 3), + ScalarLoad(16, 8, 8, count: 4), + Branch(24, "SCbranchScc1", -5), + EndProgram(32))); + + Assert.Empty(plan.Info.Buffers); + Assert.True(plan.Info.UsesDeviceAddresses); + Assert.True(plan.Memory.TryGetIndex(8, 0, out var index)); + // main reads a V# loaded from scalar-buffer data through its registers (IsDeviceLoadedBufferHandle). + Assert.True(plan.Memory[index].DeviceDescriptor); + } + + [Fact] + public void DescriptorWalkedByALoopFromALaneValue_IsNeverBoundStatically() + { + var plan = Extract(Program( + ReadFirstLane(0, 8, 0), MoveScalar(4, 9, 0), MoveScalar(8, 10, 64), MoveScalar(12, 11, 0), + BufferLoad(16, 8, dwords: 3), + ScalarLoad(24, 8, 8, count: 4), + Branch(32, "SCbranchScc1", -5), + EndProgram(36))); + + Assert.Empty(plan.Info.Buffers); + Assert.True(plan.Memory.TryGetIndex(16, 0, out var index)); + Assert.True(plan.Memory[index].DeviceDescriptor || + plan.Memory[index].BufferDescriptor?.Provenance == BufferDescriptorProvenance.Runtime); + } + + [Fact] + public void DescriptorChosenByControlFlow_KeepsTypedAccessRejected() + { + var error = Assert.ThrowsAny(() => Extract(PhiSelectedDescriptor("TBufferLoadFormatXyz"))); Assert.Contains("not a valid runtime value", error.Message); } + [Fact] + public void StaticDescriptor_StaysHostBound() + { + var plan = Extract(Program( + MoveScalar(0, 8, 0x1000), MoveScalar(4, 9, 0), MoveScalar(8, 10, 256), MoveScalar(12, 11, 0), + BufferLoad(16, 8, dwords: 3), EndProgram(24))); + var userDataPlan = Extract(Program(BufferLoad(0, 0, dwords: 3), EndProgram(8))); + + foreach (var candidate in new[] { plan, userDataPlan }) + { + Assert.Single(candidate.Info.Buffers); + Assert.DoesNotContain(candidate.Memory.Entries, memory => memory.DeviceDescriptor); + } + } + [Fact] public void LoopCycleEnteredThroughRuntimeValue() { diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ScalarValueGraphTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ScalarValueGraphTests.cs index 5b6f25642..647b30557 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ScalarValueGraphTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ScalarValueGraphTests.cs @@ -156,8 +156,10 @@ public void InvariantAndDivergentPhi() Assert.True(RuntimeValueEvaluator.EvaluateDescriptorSource(invariant, invariant.Info.Buffers[0].Source, Inputs([]), out var result)); Assert.Equal(7u, result.Dwords[0]); - var error = Assert.Throws(() => Extract(PhiProgram(7, 9))); - Assert.Contains("not a valid runtime value", error.Message); + // A divergent phi has no single descriptor to bind: the access reads it from its registers. + var divergent = Extract(PhiProgram(7, 9)); + Assert.Empty(divergent.Info.Buffers); + Assert.Contains(divergent.Memory.Entries, memory => memory.DeviceDescriptor); } [Fact] diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Wave64LoweringChoiceTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Wave64LoweringChoiceTests.cs new file mode 100644 index 000000000..fa980d8a1 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Wave64LoweringChoiceTests.cs @@ -0,0 +1,27 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Vulkan; +using Xunit; + +namespace SharpEmu.ShaderCompiler.Tests; + +public sealed class Wave64LoweringChoiceTests +{ + [Theory] + // unset: every workgroup is paired, as before the one-wave split existed. + [InlineData(null, 32, true)] + [InlineData(null, 64, true)] + [InlineData(null, 1024, true)] + // small: a one-wave (or partial-wave) workgroup runs its halves as two host subgroups, a larger one is paired. + [InlineData("small", 32, false)] + [InlineData("small", 64, false)] + [InlineData("small", 65, true)] + [InlineData("small", 1024, true)] + [InlineData("1", 64, true)] + [InlineData("1", 1024, true)] + [InlineData("0", 64, false)] + [InlineData("0", 1024, false)] + public void PairedLanesFollowTheModeAndWorkgroupSize(string? mode, ulong threads, bool paired) => + Assert.Equal(paired, Gen5SpirvTranslator.PairsWave64Lanes(mode, threads)); +} From ce320fe67458ae94fa4cef85690be7a0c73c6b0d Mon Sep 17 00:00:00 2001 From: Foued Attar Date: Wed, 18 Nov 2026 20:01:51 +0100 Subject: [PATCH 054/134] fix(playgo): read playgo.pgm when the sidecar metadata lists no chunks (#1148) 984ec2c0 made cache_ps5/playgo.pgm the last fallback, read only when a title has no PlayGo sidecar at all. Ghost of Yotei 02.002 ships sce_sys/playgo-scenario.json, which holds its languages and scenarios but no chunk list, so the title got no chunk ids, called scePlayGoGetLocus with zero entries and its to-do list calls with null, and waited forever at boot. When the sidecars give no chunk definitions, the chunks now come from the same discovery as a title without sidecars: pakchunk files, then playgo.pgm. A chunk list from playgo-chunkdefs.xml or playgo-chunk.dat still wins. Tests: a title with only playgo-scenario.json reads its chunks from the pgm; its pakchunk files take precedence over the pgm. --- src/SharpEmu.Libs/PlayGo/PlayGoExports.cs | 53 +++++++++++++------ .../PlayGo/PlayGoExportsTests.cs | 32 +++++++++++ 2 files changed, 68 insertions(+), 17 deletions(-) diff --git a/src/SharpEmu.Libs/PlayGo/PlayGoExports.cs b/src/SharpEmu.Libs/PlayGo/PlayGoExports.cs index 4fd1a53da..0b04e2fad 100644 --- a/src/SharpEmu.Libs/PlayGo/PlayGoExports.cs +++ b/src/SharpEmu.Libs/PlayGo/PlayGoExports.cs @@ -826,26 +826,13 @@ private static PlayGoMetadata LoadPlayGoMetadata() // NotSupportPlayGo (fatal PS5-component init failure for UE titles). // Ids outside the discovered set still return BAD_CHUNK_ID, so // title-side chunk enumeration still terminates. - var installedChunkIds = DiscoverInstalledChunkIds(app0Root); - if (installedChunkIds.Length == 1) + var fallback = DiscoverFallbackChunks(app0Root, playGoPgm); + if (fallback.ChunkIdKnowledge == PlayGoChunkIdKnowledge.Authoritative) { - // No pakchunk files either. PS5 titles ship cache_ps5/playgo.pgm, which carries the - // chunk count: Ghost of Yotei has nothing else, and with chunk 0 only its PlayGo - // queries failed and it exited at boot. - App0Archive.Extract(playGoPgm); - var pgmChunkIds = LoadPlayGoPgmChunkIds(playGoPgm); - if (pgmChunkIds.Length > 0) - { - TracePlayGo($"metadata_pgm chunks={pgmChunkIds.Length}"); - return new PlayGoMetadata(true, pgmChunkIds, PlayGoChunkIdKnowledge.Assumed); - } + TracePlayGo($"metadata_missing; fully-installed chunks=[{string.Join(',', fallback.ChunkIds)}]"); } - TracePlayGo($"metadata_missing; fully-installed chunks=[{string.Join(',', installedChunkIds)}]"); - return new PlayGoMetadata( - true, - installedChunkIds, - PlayGoChunkIdKnowledge.Authoritative); + return fallback; } var chunkIds = LoadChunkIds(chunkDefsXml); @@ -854,6 +841,18 @@ private static PlayGoMetadata LoadPlayGoMetadata() chunkIds = LoadChunkDatChunkIds(playGoDat); } + if (chunkIds.Length == 0 && !disableMetadataFallback) + { + // A sidecar that carries no chunk list (Ghost of Yotei ships only + // playgo-scenario.json) says nothing about the chunks: use the same + // pakchunk then pgm discovery as a title without sidecars. + var fallback = DiscoverFallbackChunks(app0Root, playGoPgm); + if (fallback.ChunkIds.Length > 1 || fallback.ChunkIdKnowledge == PlayGoChunkIdKnowledge.Assumed) + { + return fallback; + } + } + if (chunkIds.Length == 0) { TracePlayGo("metadata_has_no_chunk_definitions; installed chunk ids unknown"); @@ -869,6 +868,26 @@ private static PlayGoMetadata LoadPlayGoMetadata() PlayGoChunkIdKnowledge.Authoritative); } + private static PlayGoMetadata DiscoverFallbackChunks(string app0Root, string playGoPgm) + { + var installedChunkIds = DiscoverInstalledChunkIds(app0Root); + if (installedChunkIds.Length == 1) + { + // No pakchunk files either. PS5 titles ship cache_ps5/playgo.pgm, which carries the + // chunk count: Ghost of Yotei has nothing else, and with chunk 0 only its PlayGo + // queries failed and it exited at boot. + App0Archive.Extract(playGoPgm); + var pgmChunkIds = LoadPlayGoPgmChunkIds(playGoPgm); + if (pgmChunkIds.Length > 0) + { + TracePlayGo($"metadata_pgm chunks={pgmChunkIds.Length}"); + return new PlayGoMetadata(true, pgmChunkIds, PlayGoChunkIdKnowledge.Assumed); + } + } + + return new PlayGoMetadata(true, installedChunkIds, PlayGoChunkIdKnowledge.Authoritative); + } + // playgo.pgm header: "DMGP" magic at 0x00, little-endian chunk count at 0x10, // header size 0x14. Chunk ids are 0..count-1. private static ushort[] LoadPlayGoPgmChunkIds(string playGoPgm) diff --git a/tests/SharpEmu.Libs.Tests/PlayGo/PlayGoExportsTests.cs b/tests/SharpEmu.Libs.Tests/PlayGo/PlayGoExportsTests.cs index 820dd67f6..aaf48f58b 100644 --- a/tests/SharpEmu.Libs.Tests/PlayGo/PlayGoExportsTests.cs +++ b/tests/SharpEmu.Libs.Tests/PlayGo/PlayGoExportsTests.cs @@ -301,6 +301,38 @@ public void GetLocus_PakDiscoveryStillAppliesWithoutPgmOrSidecars() Assert.Equal(BadChunkId, GetLocus(handle, [1])); } + [Fact] + public void GetLocus_ScenarioWithoutChunkList_UsesPgmChunks() + { + WritePgm(3); + WriteScenarioJson(); + var handle = InitializeAndOpen(); + + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, GetLocus(handle, [0, 1, 2])); + Assert.Equal(new byte[] { LocusLocalFast, LocusLocalFast, LocusLocalFast }, ReadLoci(3)); + Assert.Equal((1ul, 1ul), GetProgress(handle, [0, 1, 2])); + } + + [Fact] + public void GetLocus_ScenarioWithoutChunkList_PakChunksTakePrecedenceOverPgm() + { + WritePgm(2); + WriteScenarioJson(); + File.WriteAllBytes(Path.Combine(_app0Root, "pakchunk7-PS5.pak"), []); + var handle = InitializeAndOpen(); + + Assert.Equal((int)OrbisGen2Result.ORBIS_GEN2_OK, GetLocus(handle, [0, 7])); + Assert.Equal(BadChunkId, GetLocus(handle, [1])); + } + + private void WriteScenarioJson() + { + var sceSys = Directory.CreateDirectory(Path.Combine(_app0Root, "sce_sys")); + File.WriteAllText( + Path.Combine(sceSys.FullName, "playgo-scenario.json"), + "{\"languages\":[\"en\"],\"scenarios\":[]}"); + } + private void WritePgm(uint chunkCount, string magic = "DMGP") { var header = new byte[0x14]; From 0f071bdf18cc40a4bc00deb5d5a29dc7968aebad Mon Sep 17 00:00:00 2001 From: "Ainesh M." <236408161+Kuaryn@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:45:59 +0000 Subject: [PATCH 055/134] [SpirvTranslator] A program counter read keeps thread-addressed LDS in slot variables (#1149) CollectLaneLdsSlotKeys refused every program with s_getpc_b64, so such a program kept the 2048-dword Private lds array, zero-initialized for every invocation. s_getpc_b64 only reads the PC (shaders build a PC-relative constant buffer from it); only s_setpc_b64 and s_swappc_b64 jump to targets the scan cannot see, and those still refuse. Ghost of Yotei's terrain material pixel shader 4470D4F01A1E8469 (G-buffer, 6 targets, ~485k triangles per frame) spills through ds_write/read_addtid at constant M0 bases and reads one PC-relative constant buffer; it took ~55 ms of GPU per frame with the 8 KiB per-fragment array. Extends ParantezTech's slot variables (14d68762). Gen5DataShareLaneSlotTests.AProgramCounterReadKeepsTheSlotVariables (RED before). --- .../Gen5SpirvTranslator.LaneLdsSlots.cs | 3 ++- .../Gen5DataShareLaneSlotTests.cs | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.LaneLdsSlots.cs b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.LaneLdsSlots.cs index a5ea7e27e..d9abb5a8c 100644 --- a/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.LaneLdsSlots.cs +++ b/src/SharpEmu.ShaderCompiler.Vulkan/Gen5SpirvTranslator.LaneLdsSlots.cs @@ -56,7 +56,8 @@ private bool TryDeclareLaneLdsSlots() { targets.Add(instruction.Pc + sizeof(uint) + (uint)((short)(instruction.Words[0] & 0xFFFF) * sizeof(uint))); } - else if (instruction.Opcode is "SSetpcB64" or "SSwappcB64" or "SGetpcB64") + // A computed jump hides branch targets. s_getpc_b64 only reads the PC (a PC-relative constant buffer). + else if (instruction.Opcode is "SSetpcB64" or "SSwappcB64") { return null; } diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Gen5DataShareLaneSlotTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Gen5DataShareLaneSlotTests.cs index fb11f60fa..b6522deda 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Gen5DataShareLaneSlotTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Gen5DataShareLaneSlotTests.cs @@ -27,6 +27,24 @@ public void ThreadAddressedSpillsWithAConstantBaseUseOneVariablePerSlot(ShaderSt Assert.DoesNotContain("lds", names); } + // s_getpc_b64 only reads the program counter (a PC-relative constant buffer); it does not jump. + [Fact] + public void AProgramCounterReadKeepsTheSlotVariables() + { + var names = CompileNames(Decode( + [ + 0xBE8C1F00, + SetM0ToZero, + 0x7E1402FF, 0x3F800000, + 0xDAC00100, 0x00000A00, + 0xDAC40100, 0x04000000, + 0xBF810000, + ]), ShaderStage.Pixel); + + Assert.Contains("ldsLane64", names); + Assert.DoesNotContain("lds", names); + } + [Fact] public void ThreadAddressedSpillsWithARegisterBaseKeepTheLdsArray() { From b4b4ab44b5e5f634bb0172d05f2e4db583296f8f Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:08:12 +0300 Subject: [PATCH 056/134] [GPU] Avoid replaying metadata clears after a rendering scope break --- .../Gpu/Rendering/RenderRecorder.cs | 30 +++++++++++++++---- .../Gpu/Rendering/RenderExecutorStateTests.cs | 29 ++++++++++++++++++ .../Rendering/RenderExecutorTestSupport.cs | 9 +++++- 3 files changed, 61 insertions(+), 7 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs index aaf5e71f9..931be0ee9 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.cs @@ -122,7 +122,6 @@ private sealed class InPlaceDraw public readonly ImageView[] Views = new ImageView[RenderingState.ColorAttachmentCapacity]; public readonly uint[] Slots = new uint[RenderingState.ColorAttachmentCapacity]; public ImageView DepthView; - public bool DepthMetadataClear; public RenderingState Rendering; } @@ -223,7 +222,7 @@ private bool TryRestoreAttachments(ref DrawState state) if (state.Depth.HasTarget) { state.Depth.View = kept.DepthView; - state.Depth.MetadataClear = kept.DepthMetadataClear; + state.Depth.MetadataClear = false; _host.KeepDepthAttachment(in state.Depth); } @@ -268,10 +267,28 @@ private void KeepTargets(ResolvedDraw record, ref DrawState state) } kept.DepthView = state.Depth.View; - kept.DepthMetadataClear = state.Depth.MetadataClear; kept.Rendering = state.Rendering; } + private void BeginDrawRendering(ref DrawState state, bool reusedAttachments) + { + // Binding resources can end the scope after attachment reuse. Its metadata load clears + // already ran, so reopening the scope must preserve the pixels drawn since then. + if (reusedAttachments && _host.DrawScope.Scope != _inPlace.Token.Scope) + { + for (var index = 0; index < state.Rendering.ColorAttachmentCount; index++) + { + ref var color = ref state.Rendering.ColorAttachments[index]; + color = color with { IsClear = false }; + } + + ref var depth = ref state.Rendering.DepthStencilAttachment; + depth = depth with { DepthClear = state.Depth.Target.State.DepthClearEnabled }; + } + + _host.BeginRendering(in state.Rendering); + } + private struct VertexBufferRange { public ulong BaseAddress; @@ -637,7 +654,8 @@ private void RecordDrawCommands(ResolvedDraw record, ref DrawState state, bool i emission.Indexed ? RenderExecutor.IndexedIndirectArgumentsSize : RenderExecutor.AutoIndirectArgumentsSize, isWritten: false) : default; RenderExecutor.DropUnwrittenColorTargets(context, ref state, pixelProgram); - if (inPlace && TryRestoreAttachments(ref state)) + var reusedAttachments = inPlace && TryRestoreAttachments(ref state); + if (reusedAttachments) { _inPlaceDraws.Increment(); } @@ -720,7 +738,7 @@ private void RecordDrawCommands(ResolvedDraw record, ref DrawState state, bool i var imageSnapshot = _host.BeginImageSnapshot(pixelBindings); indirectMesh?.Prepare(); - _host.BeginRendering(in state.Rendering); + BeginDrawRendering(ref state, reusedAttachments); if (MeshDrawTrace.Active) MeshDrawTrace.Write("rendering", $"width={state.Rendering.Width} height={state.Rendering.Height} layers={state.Rendering.Layers} colors={state.ColorCount}"); _host.BindPipeline(PipelineBindPoint.Graphics, in pipeline); if (record.SetAutoDebug) @@ -1024,7 +1042,7 @@ private bool TryReplayDraw(ResolvedDraw record, ref DrawState state, bool inPlac } _host.SetDynamicState(in record.Dynamic); - _host.BeginRendering(in state.Rendering); + BeginDrawRendering(ref state, reusedAttachments: true); _host.BindPipeline(PipelineBindPoint.Graphics, in pipeline); if (record.SetAutoDebug) { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorStateTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorStateTests.cs index 937e3dc6b..7e94013af 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorStateTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorStateTests.cs @@ -384,6 +384,35 @@ public void Attachments_AnHtileMetadataClearLoadsADepthClearWithoutTouchingTheDe Assert.Contains($"transition_depth 2 {ImageAspectFlags.DepthBit} loadClear=True", _host.Calls); } + [Fact] + public void Attachments_AScopeBreakDuringBindingDoesNotRepeatMetadataClears() + { + _host.Scope = new DrawScopeToken(1, 1, 1); + _host.ColorMetadataClears[ColorBase] = new ClearColorValue(); + _host.DepthMetadataClear = true; + var banks = Banks(withDepth: true); + _executor.DrawIndexed(1, banks, Indexed(3)); + Assert.True(_host.BegunRenderings[0].ColorAttachments[0].IsClear); + Assert.True(_host.BegunRenderings[0].DepthStencilAttachment.DepthClear); + + _host.ColorMetadataClears.Clear(); + _host.DepthMetadataClear = false; + _host.EndScopeOnBindingCommit = true; + _host.Calls.Clear(); + _executor.DrawIndexed(2, banks, Indexed(3)); + + Assert.Contains("keep_depth 2", _host.Calls); + Assert.False(_host.BegunRenderings[1].ColorAttachments[0].IsClear); + Assert.False(_host.BegunRenderings[1].DepthStencilAttachment.DepthClear); + + _host.EndScopeOnBindingCommit = false; + _host.ColorMetadataClears[ColorBase] = new ClearColorValue(); + _host.DepthMetadataClear = true; + _executor.DrawIndexed(3, banks, Indexed(3)); + Assert.True(_host.BegunRenderings[2].ColorAttachments[0].IsClear); + Assert.True(_host.BegunRenderings[2].DepthStencilAttachment.DepthClear); + } + [Fact] public void Attachments_AReadOnlyDepthTargetWritesNoAspect() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs index f5f05e722..23c6afae3 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs @@ -220,6 +220,7 @@ public ResourceSlotIdentifier FindImage(ref ImageRequest request, bool exactForm public void ResetBindings() => Calls.Add("reset_bindings"); public DrawScopeToken Scope { get; set; } + public bool EndScopeOnBindingCommit { get; set; } public DrawScopeToken DrawScope => Scope; @@ -342,8 +343,14 @@ public IPreparedBindings PrepareBindings(ShaderStageResources stage) public void BindResources(IPreparedBindings prepared) => Calls.Add($"bind_resources {((RecordedBindings)prepared).Id}"); - public void CommitBindings(PipelineBindPoint bindPoint, in PipelineHandle pipeline, ReadOnlySpan stages) => + public void CommitBindings(PipelineBindPoint bindPoint, in PipelineHandle pipeline, ReadOnlySpan stages) + { Calls.Add($"commit {bindPoint} {pipeline.Pipeline:X} [{string.Join(",", stages.ToArray().Select(s => ((RecordedBindings)s).Id))}]"); + if (EndScopeOnBindingCommit) + { + Scope = default; + } + } public void SetDynamicState(in DynamicDrawState state) { From a29a6be9af2724715d5f824dcbe2998db2aa7508 Mon Sep 17 00:00:00 2001 From: ParantezTech <12572227+par274@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:08:27 +0300 Subject: [PATCH 057/134] [GPU] Keep bindless heap views resident across guest frames --- .../VideoOut/BindlessHeapViewTable.cs | 19 ++++++++++-------- .../VulkanVideoPresenter.BindlessHeap.cs | 20 ++++++++++++------- .../VideoOut/BindlessHeapViewTableTests.cs | 16 +++++++++++++++ 3 files changed, 40 insertions(+), 15 deletions(-) diff --git a/src/SharpEmu.Libs/VideoOut/BindlessHeapViewTable.cs b/src/SharpEmu.Libs/VideoOut/BindlessHeapViewTable.cs index 07e7909db..eee2dcb22 100644 --- a/src/SharpEmu.Libs/VideoOut/BindlessHeapViewTable.cs +++ b/src/SharpEmu.Libs/VideoOut/BindlessHeapViewTable.cs @@ -20,6 +20,7 @@ internal sealed class Region public required BindlessHeapDescriptor Heap { get; set; } public required HeapView View { get; init; } public ulong LastUsedTick; + public long LastUsedFrame; public bool Holds(uint element) => element >= View.First && element - View.First < View.Records; @@ -40,13 +41,14 @@ internal sealed class Region // or free elements, or those of the least recently used views no pending command reads (released sees each one before // its elements are taken), or shares the run of a view of its shape that is still read (moved). Null when the view has // no records or the table has no room for it. - public Region? Acquire(in BindlessHeapDescriptor descriptor, ulong tick, ulong completedTick, Action released, out bool moved) + public Region? Acquire(in BindlessHeapDescriptor descriptor, ulong tick, ulong completedTick, Action released, out bool moved, long frame = 0) { moved = false; var heap = descriptor.ViewKey; if (_byHeap.TryGetValue(heap, out var region)) { region.LastUsedTick = tick; + region.LastUsedFrame = frame; return region; } @@ -60,7 +62,7 @@ internal sealed class Region if (FindShape(heap, shape, tick, completedTick) is { } idle) { moved = true; - return Move(idle, heap, tick); + return Move(idle, heap, tick, frame); } int position; @@ -85,13 +87,13 @@ internal sealed class Region } moved = true; - return Move(shared, heap, tick); + return Move(shared, heap, tick, frame); } Release(oldest, released); } - region = new Region { Heap = heap, View = HeapView.Of(heap, first, records), LastUsedTick = tick }; + region = new Region { Heap = heap, View = HeapView.Of(heap, first, records), LastUsedTick = tick, LastUsedFrame = frame }; _regions.Insert(position, region); _byHeap.Add(heap, region); return region; @@ -114,11 +116,12 @@ internal sealed class Region return found; } - private Region Move(Region region, in BindlessHeapDescriptor heap, ulong tick) + private Region Move(Region region, in BindlessHeapDescriptor heap, ulong tick, long frame) { _byHeap.Remove(region.Heap); region.Heap = heap; region.LastUsedTick = tick; + region.LastUsedFrame = frame; _byHeap.Add(heap, region); return region; } @@ -149,13 +152,13 @@ private Region Move(Region region, in BindlessHeapDescriptor heap, ulong tick) return null; } - // Gives up the runs last used before idleBefore that no pending command reads. - public void ReleaseIdle(ulong idleBefore, ulong completedTick, Action released) + // Gives up runs idle in both submission ticks and guest frames, once no pending command reads them. + public void ReleaseIdle(ulong idleBefore, ulong completedTick, Action released, long idleBeforeFrame = long.MaxValue) { for (var index = _regions.Count - 1; index >= 0; index--) { var region = _regions[index]; - if (region.LastUsedTick < idleBefore && region.LastUsedTick <= completedTick) + if (region.LastUsedTick < idleBefore && region.LastUsedTick <= completedTick && region.LastUsedFrame < idleBeforeFrame) { Release(region, released); } diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.BindlessHeap.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.BindlessHeap.cs index acd44d60f..87eb4a9a8 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.BindlessHeap.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.BindlessHeap.cs @@ -420,9 +420,10 @@ internal void ForgetHeapPreparation(object preparation) } } - // A view no draw has read for this many submission ticks gives its elements up: a table the guest allocates - // for each frame is a new view whenever it moves, and the memory of the old one holds other data by then. + // A heavy frame can take hundreds of submission ticks. Keep its heap views resident across frames + // so a once-per-frame pass can read them before the next feedback copy resolves any missing entries. private const ulong HeapIdleTicks = 256; + private const long HeapIdleFrames = 2; // Before the images of a draw or dispatch that reads set 1 are found: the records marked since the last look, // records rewritten since they were read, and heap images whose contents or layout changed. @@ -450,10 +451,11 @@ internal void WriteHeapViews(ReadOnlySpan heaps, Span marked) private void RevalidateHeapEntries() { _heapRevalidatedTick = _scheduler.CurrentTick; - if (_heapRevalidatedTick > HeapIdleTicks) - { - _heapImageViews.ReleaseIdle(_heapRevalidatedTick - HeapIdleTicks, _scheduler.CompletedTick, _heapRegionReleased!); - _heapSamplerViews.ReleaseIdle(_heapRevalidatedTick - HeapIdleTicks, _scheduler.CompletedTick, _heapRegionReleased!); + var frame = Volatile.Read(ref _guestFlipVersionSequence); + if (_heapRevalidatedTick > HeapIdleTicks && frame > HeapIdleFrames) + { + var idleBefore = _heapRevalidatedTick - HeapIdleTicks; + var idleBeforeFrame = frame - HeapIdleFrames; + var completed = _scheduler.CompletedTick; + _heapImageViews.ReleaseIdle(idleBefore, completed, _heapRegionReleased!, idleBeforeFrame); + _heapSamplerViews.ReleaseIdle(idleBefore, completed, _heapRegionReleased!, idleBeforeFrame); } // A call record entry is named by its words, which never change; its image stays in use. diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/BindlessHeapViewTableTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/BindlessHeapViewTableTests.cs index f341b6bb4..aac4b41d4 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/BindlessHeapViewTableTests.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/BindlessHeapViewTableTests.cs @@ -233,4 +233,20 @@ public void IdleViewsGiveTheirElementsUpOnceTheirCommandsCompleted() Assert.Equal([idle], released); Assert.Equal([pending, used], table.Regions); } + + [Fact] + public void AViewReadEachFrameSurvivesMoreThanTheIdleTickLimitBetweenReads() + { + var table = new BindlessHeapViewTable(1024); + var heap = new BindlessHeapDescriptor(false, 0x10000, 256, 32); + var view = table.Acquire(heap, tick: 100, completedTick: 90, Unreleased, out _, frame: 20)!; + var released = new List(); + + table.ReleaseIdle(idleBefore: 113, completedTick: 360, released.Add, idleBeforeFrame: 19); + Assert.False(released.Count != 0, "A view used in the previous frame was released."); + Assert.Same(view, table.Acquire(heap, tick: 369, completedTick: 360, Unreleased, out _, frame: 21)); + + table.ReleaseIdle(idleBefore: 449, completedTick: 700, released.Add, idleBeforeFrame: 22); + Assert.Equal([view], released); + } } From f1af467a656d0a14b1f05a332e2757f5523a1489 Mon Sep 17 00:00:00 2001 From: Usif <19160089+Im-Usif@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:06:47 +0300 Subject: [PATCH 058/134] [GPU] Keep a growing texture heap in one bindless heap view (#1152) Heap views (#1147) keyed a packed descriptor heap by the record count its V# names. A texture heap the guest streams more textures into names a larger count from frame to frame, so each count made a new view whose textures read as null until the shaders marked them again. Marvel's Wolverine had a visual regression in its opening cutscene. A packed heap is now one view at any count. A view that outgrows its run takes a larger one with room to grow, its resolved elements move along, and the old run stays until no pending command reads it. Shaders read up to the most records a draw has named, never past them. --- .../VideoOut/BindlessHeapViewTable.cs | 84 +++++++++++++++---- .../VulkanVideoPresenter.BindlessHeap.cs | 32 ++++++- .../Resources/BindlessHeap.cs | 17 ++-- .../VideoOut/BindlessHeapViewTableTests.cs | 34 ++++++++ 4 files changed, 145 insertions(+), 22 deletions(-) diff --git a/src/SharpEmu.Libs/VideoOut/BindlessHeapViewTable.cs b/src/SharpEmu.Libs/VideoOut/BindlessHeapViewTable.cs index eee2dcb22..b97a41ed6 100644 --- a/src/SharpEmu.Libs/VideoOut/BindlessHeapViewTable.cs +++ b/src/SharpEmu.Libs/VideoOut/BindlessHeapViewTable.cs @@ -18,11 +18,16 @@ internal sealed class Region { // The heap whose records the run's elements hold now. public required BindlessHeapDescriptor Heap { get; set; } - public required HeapView View { get; init; } + // The shader reads up to View.Records, the most records a draw has named for the heap; the run holds Size elements, + // at least that many, so a heap that grows keeps its run until it outgrows the room. + public required HeapView View { get; set; } + public uint Size { get; init; } public ulong LastUsedTick; public long LastUsedFrame; - public bool Holds(uint element) => element >= View.First && element - View.First < View.Records; + public uint Extent => Math.Max(Size, View.Records); + + public bool Holds(uint element) => element >= View.First && element - View.First < Extent; // The run's descriptors as a heap of their own, for reading them in guest memory: the first one's address, a // stride apart, each of the size its heap reads (an R128 view's are 16 bytes). @@ -41,25 +46,48 @@ internal sealed class Region // or free elements, or those of the least recently used views no pending command reads (released sees each one before // its elements are taken), or shares the run of a view of its shape that is still read (moved). Null when the view has // no records or the table has no room for it. - public Region? Acquire(in BindlessHeapDescriptor descriptor, ulong tick, ulong completedTick, Action released, out bool moved, long frame = 0) + public Region? Acquire(in BindlessHeapDescriptor descriptor, ulong tick, ulong completedTick, Action released, out bool moved, long frame = 0) => + Acquire(descriptor, tick, completedTick, released, out moved, out _, frame); + + // grownFrom is the run a packed heap outgrew: the view's new run holds the same records from the same first record on, + // so the caller can give it that run's elements at once. + public Region? Acquire(in BindlessHeapDescriptor descriptor, ulong tick, ulong completedTick, Action released, out bool moved, + out Region? grownFrom, long frame = 0) { moved = false; + grownFrom = null; var heap = descriptor.ViewKey; + var records = Math.Min(descriptor.ViewRecords, capacity); + var size = records; if (_byHeap.TryGetValue(heap, out var region)) { - region.LastUsedTick = tick; - region.LastUsedFrame = frame; - return region; + if (region.Extent >= records) + { + // A heap that grew within its run's room: the shader reads its new records from now on. + if (records > region.View.Records) + { + region.View = region.View with { Records = records }; + } + + region.LastUsedTick = tick; + region.LastUsedFrame = frame; + return region; + } + + // The guest grew the heap past the run (a texture heap it streams more textures into). The run stays for the + // commands that read it until it is idle; the view takes a run with room to grow again. + grownFrom = region; + _byHeap.Remove(heap); + size = Math.Min(records + records / 8, capacity); } - var records = Math.Min(heap.Records, capacity); if (heap.Base == 0 || records == 0) { return null; } var shape = HeapView.Of(heap, 0, records); - if (FindShape(heap, shape, tick, completedTick) is { } idle) + if (grownFrom is null && FindShape(heap, shape, tick, completedTick) is { } idle) { moved = true; return Move(idle, heap, tick, frame); @@ -67,12 +95,12 @@ internal sealed class Region int position; uint first; - while (!TryFindGap(records, out position, out first)) + while (!TryFindGap(size, out position, out first)) { Region? oldest = null; foreach (var candidate in _regions) { - if (candidate.LastUsedTick <= completedTick && candidate.LastUsedTick < tick && + if (candidate != grownFrom && candidate.LastUsedTick <= completedTick && candidate.LastUsedTick < tick && (oldest is null || candidate.LastUsedTick < oldest.LastUsedTick)) { oldest = candidate; @@ -81,6 +109,23 @@ internal sealed class Region if (oldest is null) { + if (grownFrom is not null) + { + if (size > records) + { + size = records; + continue; + } + + // No room for a larger run: the view keeps the one it has. + _byHeap.Add(heap, grownFrom); + grownFrom.LastUsedTick = tick; + grownFrom.LastUsedFrame = frame; + var kept = grownFrom; + grownFrom = null; + return kept; + } + if (FindShape(heap, shape, ulong.MaxValue, ulong.MaxValue) is not { } shared) { return null; @@ -93,7 +138,7 @@ internal sealed class Region Release(oldest, released); } - region = new Region { Heap = heap, View = HeapView.Of(heap, first, records), LastUsedTick = tick, LastUsedFrame = frame }; + region = new Region { Heap = heap, View = HeapView.Of(heap, first, records), Size = size, LastUsedTick = tick, LastUsedFrame = frame }; _regions.Insert(position, region); _byHeap.Add(heap, region); return region; @@ -118,7 +163,7 @@ internal sealed class Region private Region Move(Region region, in BindlessHeapDescriptor heap, ulong tick, long frame) { - _byHeap.Remove(region.Heap); + ForgetHeap(region); region.Heap = heap; region.LastUsedTick = tick; region.LastUsedFrame = frame; @@ -139,7 +184,7 @@ private Region Move(Region region, in BindlessHeapDescriptor heap, ulong tick, l { high = middle - 1; } - else if (element - region.View.First >= region.View.Records) + else if (element - region.View.First >= region.Extent) { low = middle + 1; } @@ -169,7 +214,16 @@ private void Release(Region region, Action released) { released(region); _regions.Remove(region); - _byHeap.Remove(region.Heap); + ForgetHeap(region); + } + + // A run a grown heap left behind no longer names the heap: the heap's current run does. + private void ForgetHeap(Region region) + { + if (_byHeap.TryGetValue(region.Heap, out var current) && current == region) + { + _byHeap.Remove(region.Heap); + } } private bool TryFindGap(uint records, out int position, out uint first) @@ -183,7 +237,7 @@ private bool TryFindGap(uint records, out int position, out uint first) return true; } - first = region.View.First + region.View.Records; + first = region.View.First + region.Extent; } return capacity - first >= records; diff --git a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.BindlessHeap.cs b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.BindlessHeap.cs index 87eb4a9a8..cc6de2f9d 100644 --- a/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.BindlessHeap.cs +++ b/src/SharpEmu.Libs/VideoOut/VulkanVideoPresenter.BindlessHeap.cs @@ -455,7 +455,13 @@ internal void WriteHeapViews(ReadOnlySpan heaps, Span heaps, Span> 5)] |= 1u << (int)(index & 31); + AddHeapEntry(entry.Slot, index, to); + } + } + private void AddHeapEntry(int slot, uint index, BindlessHeapViewTable.Region region) { var entry = new HeapEntry { Slot = slot, Index = index, Region = region }; @@ -534,7 +562,7 @@ private void ReleaseHeapRegion(BindlessHeapViewTable.Region region) var firstSlot = sampler ? BindlessHeap.SamplerSlot : 0; var endSlot = sampler ? BindlessHeap.ArrayCount : BindlessHeap.ImageKinds.Length; var firstWord = region.View.First >> 5; - var endWord = (region.View.First + region.View.Records + 31) >> 5; + var endWord = (region.View.First + region.Extent + 31) >> 5; _ = BeginBatchedGuestCommands(); for (var slot = firstSlot; slot < endSlot; slot++) { diff --git a/src/SharpEmu.ShaderCompiler/Resources/BindlessHeap.cs b/src/SharpEmu.ShaderCompiler/Resources/BindlessHeap.cs index af9f2ccc7..12c87abda 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/BindlessHeap.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/BindlessHeap.cs @@ -179,19 +179,26 @@ public static BindlessHeapDescriptor FromWords(bool sampler, ReadOnlySpan // The heap as its view sees it, which keys the view's run of elements (BindlessHeapViewTable). Packed descriptors // (a stride of the descriptor's size or less) are one view at whatever immediate the shader reads them, since the - // read's whole offset picks the descriptor; their count is the V#'s bytes over the descriptor size (a raw V#, stride 0, - // counts bytes, a strided one records of its stride). A record view is keyed by the descriptor's offset in a record. - public BindlessHeapDescriptor ViewKey + // read's whole offset picks the descriptor, and at whatever count: a texture heap the guest streams more textures into + // grows from frame to frame and stays one view (ViewRecords is the count a draw names). A record view is keyed by the + // descriptor's offset in a record. + public BindlessHeapDescriptor ViewKey => Stride > DescriptorBytes + ? this with { Immediate = Immediate % Stride } + : this with { Records = 0, Immediate = 0 }; + + // How many records the view of this heap needs elements for: packed descriptors count the V#'s bytes over the + // descriptor size (a raw V#, stride 0, counts bytes, a strided one records of its stride). + public uint ViewRecords { get { if (Stride > DescriptorBytes) { - return this with { Immediate = Immediate % Stride }; + return Records; } var bytes = Stride == 0 ? Records : (ulong)Records * Stride; - return this with { Records = (uint)Math.Min(bytes / DescriptorBytes, uint.MaxValue), Immediate = 0 }; + return (uint)Math.Min(bytes / DescriptorBytes, uint.MaxValue); } } } diff --git a/tests/SharpEmu.Libs.Tests/VideoOut/BindlessHeapViewTableTests.cs b/tests/SharpEmu.Libs.Tests/VideoOut/BindlessHeapViewTableTests.cs index aac4b41d4..dfa99644a 100644 --- a/tests/SharpEmu.Libs.Tests/VideoOut/BindlessHeapViewTableTests.cs +++ b/tests/SharpEmu.Libs.Tests/VideoOut/BindlessHeapViewTableTests.cs @@ -207,6 +207,40 @@ public void AViewWithoutFreeElementsSharesTheRunOfAViewOfItsShape() Assert.Same(terrain, table.Find(0)); } + // A texture heap the guest streams more textures into names more records from frame to frame, and a draw prepared + // earlier still names fewer. It stays one view: a draw that names more records than the run holds gives the view a + // larger run with room to grow (the caller moves the resolved elements over), a draw that names fewer reads what the + // view holds, and the shader reads up to the most records a draw named, never into the spare room. + [Fact] + public void AGrowingPackedHeapStaysOneViewAndReadsUpToTheMostRecordsADrawNamed() + { + var table = new BindlessHeapViewTable(1000); + var heap = new BindlessHeapDescriptor(false, 0x10000, 100, 32); + var view = table.Acquire(heap, tick: 1, completedTick: 0, Unreleased, out _, out var grownFrom)!; + Assert.Null(grownFrom); + Assert.Equal(new HeapView(0, 32, 0, 100), view.View); + + var grown = table.Acquire(heap with { Records = 160 }, tick: 2, completedTick: 0, Unreleased, out var moved, out grownFrom)!; + Assert.False(moved); + Assert.Same(view, grownFrom); + Assert.Equal(new HeapView(100, 32, 0, 160), grown.View); + Assert.Equal(180u, grown.Extent); + // The outgrown run stays for the commands that read it. + Assert.Equal(2, table.Regions.Count); + + Assert.Same(grown, table.Acquire(heap with { Records = 170 }, tick: 3, completedTick: 0, Unreleased, out _, out grownFrom)); + Assert.Null(grownFrom); + Assert.Equal(new HeapView(100, 32, 0, 170), grown.View); + Assert.Same(grown, table.Acquire(heap, tick: 4, completedTick: 0, Unreleased, out _, out _)); + Assert.Equal(170u, grown.View.Records); + + // Released once idle, the outgrown run leaves the heap's current run in place. + var released = new List(); + table.ReleaseIdle(idleBefore: 3, completedTick: 4, released.Add); + Assert.Equal([view], released); + Assert.Same(grown, table.Acquire(heap, tick: 5, completedTick: 4, Unreleased, out _, out _)); + } + [Fact] public void AViewHasNoMoreElementsThanTheTable() { From 78c2cb86292baf918e351a7c0927ed6d91c05c1b Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 22:25:35 +0000 Subject: [PATCH 059/134] [GPU] Index the command thread's queued items by page for stream reads Port of upstream a7ef0c0a6 (index queued stores by page for overlay reads), 9e1eed213 (read guest memory without the store lock when the page has no pending store) and b13a98086 (post owned store data without copying it again) to the command thread the Metal host uses (DeferredCommandThread, a copy of the Vulkan presenter's old command thread that none of the three reached). On Metal the queued stores the stream reads through are range items (PostWrite of known bytes, PostQwords, PostFill, PostRange); every read the stream made (ReadOnCommandThread, ReadWaitOperandOnCommandThread) took the write lock the worker takes to retire each item and walked every queued range. Queued stores and range items (labels excluded: no stream read waits for one) now enter a per-page index under the same lock they enter the queue: a read whose pages no queued item touches answers without the lock, a one-page read looks only at the items on its page plus the few wide ones (over 64 pages), in queue order. PostWrite(address, span) posts through PostOwnedWrite, which queues the caller's array. On Metal the queued command-processor write's array is also what a write the GPU cannot make lands from, instead of a second copy. Tests: DeferredCommandPageIndexTests (lock-free reads of other pages, the last item over the bytes across page and wide items, store order on one page and across pages, a wide store between page stores). --- .../DeferredCommandThread.PageIndex.cs | 163 ++++++++++++++++++ .../Gpu/GpuCommands/DeferredCommandThread.cs | 148 +++++++++++++--- .../V2/MetalCommandStream.cs | 14 +- .../DeferredCommandPageIndexTests.cs | 126 ++++++++++++++ 4 files changed, 427 insertions(+), 24 deletions(-) create mode 100644 src/SharpEmu.Libs/Gpu/GpuCommands/DeferredCommandThread.PageIndex.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/DeferredCommandPageIndexTests.cs diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredCommandThread.PageIndex.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredCommandThread.PageIndex.cs new file mode 100644 index 000000000..eeba9ff6a --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredCommandThread.PageIndex.cs @@ -0,0 +1,163 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Scheduling; + +namespace SharpEmu.Libs.Gpu.GpuCommands; + +// The queued stores, fills and copies by guest page (upstream's "Index queued stores by page for overlay +// reads" and "Read guest memory without the store lock when the page has no pending store", ported from the +// Vulkan presenter's command thread). Every read the stream makes asks whether a queued item writes its +// bytes (ReadOverlay, TryReadQueuedFill, WaitForPendingRange); before the index each such read took the +// write lock the worker also takes for every item it retires, and walked every queued item. Now a read +// whose pages no queued item touches answers without the lock, and a read inside one page looks only at the +// items on that page. +// +// What is indexed: a store (PostWrite of bytes) and a range item a stream read waits for or is answered by +// (PostRange, PostFill, PostWrite of known bytes, PostQwords). Labels are not: no stream read waits for one. +// An item over more than MaxIndexedPages pages is listed as wide; while one is queued every read takes the +// locked walk, as before the index. +// +// Ordering: items enter the index under _writeLock when they are queued and leave it under the same lock +// once the worker has run them, so the page lists keep the queue's order (PostOrder). A read on the +// stream's own thread sees every item the stream queued before it; a stale count (an item the worker is +// retiring) only sends the read to the locked walk, which answers as before. +public sealed partial class DeferredCommandThread +{ + private const int PendingPageShift = 12; + private const ulong MaxIndexedPages = 64; + private const int PendingPageFilterBits = 14; + private const int MaxSparePageLists = 4096; + + // Indexed items per hashed page; changed under _writeLock, read without it. A collision only sends a + // read to the locked walk. + private readonly int[] _pendingPageFilter = new int[1 << PendingPageFilterBits]; + private readonly Dictionary> _pendingByPage = new(); + private readonly Stack> _sparePageLists = new(); + private readonly List _widePending = new(); + private volatile int _widePendingCount; + private long _postOrder; + private long _lockedPendingReads; + + /// Stream reads that had to take the write lock to find the queued items over their bytes. + internal long LockedPendingReads => Interlocked.Read(ref _lockedPendingReads); + + private static int PendingPageSlot(ulong page) => + (int)((page * 0x9E3779B97F4A7C15UL) >> (64 - PendingPageFilterBits)); + + private static ulong IndexedSize(Item item) => item.Kind == Kind.Write ? (ulong)item.Data!.Length : item.RangeSize; + + private static bool IsIndexed(Item item) => item.Kind == Kind.Write ? item.Data!.Length != 0 : item.RangeSize != 0 && !item.IsLabel; + + // Under _writeLock. + private void IndexPending(Item item, bool add) + { + if (!IsIndexed(item)) + { + return; + } + + if (add) + { + item.PostOrder = ++_postOrder; + } + + var first = item.Address >> PendingPageShift; + var last = (item.Address + IndexedSize(item) - 1) >> PendingPageShift; + if (last - first >= MaxIndexedPages) + { + if (add) + { + _widePending.Add(item); + } + else + { + _widePending.Remove(item); + } + + _widePendingCount = _widePending.Count; + return; + } + + for (var page = first; page <= last; page++) + { + ref var count = ref _pendingPageFilter[PendingPageSlot(page)]; + if (add) + { + if (!_pendingByPage.TryGetValue(page, out var queued)) + { + queued = _sparePageLists.Count != 0 ? _sparePageLists.Pop() : new List(); + _pendingByPage.Add(page, queued); + } + + queued.Add(item); + Volatile.Write(ref count, count + 1); + continue; + } + + if (_pendingByPage.TryGetValue(page, out var listed) && listed.Remove(item)) + { + Volatile.Write(ref count, count - 1); + if (listed.Count == 0) + { + _pendingByPage.Remove(page); + if (_sparePageLists.Count < MaxSparePageLists) + { + _sparePageLists.Push(listed); + } + } + } + else + { + throw GpuFatal.Fatal("The command stream's queued item index lost an item."); + } + } + } + + // Without the lock: whether a queued store, fill or copy may write a byte of the range. + private bool MayHavePendingItem(ulong address, ulong size) + { + if (size == 0) + { + return false; + } + + if (_widePendingCount != 0) + { + return true; + } + + var first = address >> PendingPageShift; + var last = (address + size - 1) >> PendingPageShift; + if (last - first >= MaxIndexedPages) + { + return true; + } + + for (var page = first; page <= last; page++) + { + if (Volatile.Read(ref _pendingPageFilter[PendingPageSlot(page)]) != 0) + { + return true; + } + } + + return false; + } + + // Under _writeLock: the indexed items listed on the read's single page, or null when the read + // spans pages (the caller walks every queued item then). Wide items are not in the list. + private List? PendingOnPage(ulong address, ulong size) + { + _lockedPendingReads++; + var page = address >> PendingPageShift; + if (page != (address + size - 1) >> PendingPageShift) + { + return null; + } + + return _pendingByPage.TryGetValue(page, out var queued) ? queued : EmptyItems; + } + + private static readonly List EmptyItems = new(); +} diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredCommandThread.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredCommandThread.cs index ada3eaf86..f0ea715a4 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredCommandThread.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/DeferredCommandThread.cs @@ -77,6 +77,8 @@ private sealed class Item // What kind of item this is, for the draws its gate holds (ParallelProgramPrefetch.NoteGateItem). public ParallelProgramPrefetch.GateItemKind GateKind; public bool Sync; + // The item's place in the queue among the indexed ones (DeferredCommandThread.PageIndex). + public long PostOrder; public volatile bool Done; public Exception? Failure; } @@ -295,16 +297,20 @@ public T Run(Func function) return result; } - public void PostWrite(ulong address, ReadOnlySpan data) + public void PostWrite(ulong address, ReadOnlySpan data) => PostOwnedWrite(address, data.ToArray()); + + // A store whose bytes the caller hands over: they are queued as they are, not copied again. + public void PostOwnedWrite(ulong address, byte[] data) { var item = RentAsyncItem(Kind.Write); item.Address = address; - item.Data = data.ToArray(); + item.Data = data; item.GateKind = ParallelProgramPrefetch.GateItemKind.CommandProcessorWrite; lock (_writeLock) { _pendingWrites.Enqueue(item); _pendingWriteCount = _pendingWrites.Count; + IndexPending(item, add: true); } Enqueue(item); @@ -330,6 +336,7 @@ public void PostRange(Action action, ulong address, ulong size, bool ungated = f _pendingRanges.Add(item); _pendingRangeCount = _pendingRanges.Count; PublishUngatedRange(item, add: true); + IndexPending(item, add: true); } } @@ -355,6 +362,7 @@ public void PostLabel(Action action, ulong address, ulong size, bool ungated = f _pendingRanges.Add(item); _pendingRangeCount = _pendingRanges.Count; PublishUngatedRange(item, add: true); + IndexPending(item, add: true); } } @@ -381,6 +389,7 @@ public void PostFill(Action action, ulong address, ulong size, uint value, bool _pendingRanges.Add(item); _pendingRangeCount = _pendingRanges.Count; PublishUngatedRange(item, add: true); + IndexPending(item, add: true); } } @@ -424,6 +433,7 @@ private void PostKnownRange(Action action, ulong address, ulong size, bool ungat _pendingRanges.Add(item); _pendingRangeCount = _pendingRanges.Count; PublishUngatedRange(item, add: true); + IndexPending(item, add: true); } } @@ -485,29 +495,46 @@ public bool TryReadQueuedFill(ulong address, Span destination) } var size = (ulong)destination.Length; + if (!MayHavePendingItem(address, size)) + { + return false; + } + lock (_writeLock) { + var onPage = PendingOnPage(address, size); Item? last = null; - foreach (var pending in _pendingRanges) + foreach (var pending in onPage ?? _pendingRanges) { - if (!pending.IsLabel && address < pending.Address + pending.RangeSize && pending.Address < address + size) + if (pending.Kind != Kind.Write && !pending.IsLabel && address < pending.Address + pending.RangeSize && + pending.Address < address + size) { last = pending; } } + if (onPage is not null) + { + // A wide item queued after the page's last one decides the bytes instead. + foreach (var pending in _widePending) + { + if (pending.Kind != Kind.Write && address < pending.Address + pending.RangeSize && + pending.Address < address + size && (last is null || pending.PostOrder > last.PostOrder)) + { + last = pending; + } + } + } + if (last is null || address < last.Address || address + size > last.Address + last.RangeSize || !(last.IsFill || last.RangeBytes is not null || last.IsQwords)) { return false; } - foreach (var write in _pendingWrites) + if (OverlapsQueuedStoreLocked(onPage, address, size)) { - if (address < write.Address + (ulong)write.Data!.Length && write.Address < address + size) - { - return false; - } + return false; } // The last item over the bytes stores every one of them, so it alone decides them; a byte @@ -618,11 +645,59 @@ private void NoteDrainSite(ulong address, ulong size) private bool OverlapsPendingRange(ulong address, ulong size) { + if (!MayHavePendingItem(address, size)) + { + return false; + } + lock (_writeLock) { - foreach (var pending in _pendingRanges) + var onPage = PendingOnPage(address, size); + foreach (var pending in onPage ?? _pendingRanges) { - if (!pending.IsLabel && address < pending.Address + pending.RangeSize && pending.Address < address + size) + if (pending.Kind != Kind.Write && !pending.IsLabel && address < pending.Address + pending.RangeSize && + pending.Address < address + size) + { + return true; + } + } + + if (onPage is not null) + { + foreach (var pending in _widePending) + { + if (pending.Kind != Kind.Write && address < pending.Address + pending.RangeSize && pending.Address < address + size) + { + return true; + } + } + } + + return false; + } + } + + // Under _writeLock: whether a queued store overlaps the range; onPage is PendingOnPage's answer. + private bool OverlapsQueuedStoreLocked(List? onPage, ulong address, ulong size) + { + if (_pendingWrites.Count == 0) + { + return false; + } + + if (onPage is not null) + { + foreach (var write in onPage) + { + if (write.Kind == Kind.Write && address < write.Address + (ulong)write.Data!.Length && write.Address < address + size) + { + return true; + } + } + + foreach (var write in _widePending) + { + if (write.Kind == Kind.Write && address < write.Address + (ulong)write.Data!.Length && write.Address < address + size) { return true; } @@ -630,13 +705,24 @@ private bool OverlapsPendingRange(ulong address, ulong size) return false; } + + foreach (var write in _pendingWrites) + { + if (address < write.Address + (ulong)write.Data!.Length && write.Address < address + size) + { + return true; + } + } + + return false; } // Guest memory as the stream sees it: with its own stores applied, queued or not. public bool ReadOverlay(ulong address, Span destination) { WaitForPendingRange(address, (ulong)destination.Length); - if (_pendingWriteCount == 0) + // No queued store on the read's pages: memory is what the stream wrote, read without the lock. + if (_pendingWriteCount == 0 || !MayHavePendingItem(address, (ulong)destination.Length)) { return _memory.TryRead(address, destination); } @@ -649,24 +735,44 @@ public bool ReadOverlay(ulong address, Span destination) } var end = address + (ulong)destination.Length; - foreach (var write in _pendingWrites) + var onPage = PendingOnPage(address, (ulong)destination.Length); + if (onPage is null || _widePendingCount != 0) { - var writeEnd = write.Address + (ulong)write.Data!.Length; - if (write.Address >= end || writeEnd <= address) + // Every queued store, oldest first: a wide one interleaves with the page's in queue order. + foreach (var write in _pendingWrites) { - continue; + ApplyQueuedStore(write, address, end, destination); } - var start = Math.Max(address, write.Address); - var stop = Math.Min(end, writeEnd); - write.Data.AsSpan((int)(start - write.Address), (int)(stop - start)) - .CopyTo(destination[(int)(start - address)..]); + return true; + } + + foreach (var write in onPage) + { + if (write.Kind == Kind.Write) + { + ApplyQueuedStore(write, address, end, destination); + } } return true; } } + private static void ApplyQueuedStore(Item write, ulong address, ulong end, Span destination) + { + var writeEnd = write.Address + (ulong)write.Data!.Length; + if (write.Address >= end || writeEnd <= address) + { + return; + } + + var start = Math.Max(address, write.Address); + var stop = Math.Min(end, writeEnd); + write.Data.AsSpan((int)(start - write.Address), (int)(stop - start)) + .CopyTo(destination[(int)(start - address)..]); + } + // SHARPEMU_CT_ITEM_KINDS=1 (diagnostic): every two seconds, the non-draw items the stream handed over, by kind and // by the deferred work's type or the posted action's method. private static readonly bool TraceItemKinds = Environment.GetEnvironmentVariable("SHARPEMU_CT_ITEM_KINDS") == "1"; @@ -924,6 +1030,7 @@ private void Execute(Item item) _pendingRanges.Remove(item); _pendingRangeCount = _pendingRanges.Count; PublishUngatedRange(item, add: false); + IndexPending(item, add: false); } } @@ -951,6 +1058,7 @@ private void ApplyWrite(Item item) _pendingWrites.Dequeue(); _pendingWriteCount = _pendingWrites.Count; + IndexPending(item, add: false); if (!written) { throw GpuFatal.Fatal( diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index d194e09a3..795f2bfac 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -1483,11 +1483,11 @@ private void PostCommandProcessorWrite(ulong address, byte[] queued, string kind // Reads overlapping this queued write wait until the worker installed // its overlay. Unrelated packets can continue; prefetch's non-draw gate // still orders future resource reads after the write. - _commandThread!.PostWrite(() => RecordCommandProcessorWrite(address, queued, kind, causal), address, queued, UngatedWrites); + _commandThread!.PostWrite(() => RecordCommandProcessorWrite(address, queued, kind, causal, queued), address, queued, UngatedWrites); } else { - RunTagged(() => RecordCommandProcessorWrite(address, queued, kind, causal), nameof(RecordCommandProcessorWrite)); + RunTagged(() => RecordCommandProcessorWrite(address, queued, kind, causal, queued), nameof(RecordCommandProcessorWrite)); } } @@ -1495,7 +1495,13 @@ private void PostCommandProcessorWrite(ulong address, byte[] queued, string kind public void RecordCommandProcessorWrite(ulong address, ReadOnlySpan source, string kind) => RecordCommandProcessorWrite(address, source, kind, causal: true); - public void RecordCommandProcessorWrite(ulong address, ReadOnlySpan source, string kind, bool causal) + public void RecordCommandProcessorWrite(ulong address, ReadOnlySpan source, string kind, bool causal) => + RecordCommandProcessorWrite(address, source, kind, causal, owned: null); + + // owned: source's own array, which the caller hands over (the command thread's queued copy): a write the GPU + // cannot make lands from it, not from another copy (upstream b13a98086, "Post owned store data without copying it + // again"). + private void RecordCommandProcessorWrite(ulong address, ReadOnlySpan source, string kind, bool causal, byte[]? owned) { if (OnCommandThread) { @@ -1534,7 +1540,7 @@ public void RecordCommandProcessorWrite(ulong address, ReadOnlySpan source } Interlocked.Increment(ref _hostCommandProcessorWrites); - var bytes = source.ToArray(); + var bytes = owned is not null && owned.Length == source.Length ? owned : source.ToArray(); var landedKind = CommandProcessorWriteHistory.Enabled ? "landed:" + kind : null; var lazy = RidesNextCommit(clock: false); Interlocked.Increment(ref _owedHostLabels); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/DeferredCommandPageIndexTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/DeferredCommandPageIndexTests.cs new file mode 100644 index 000000000..7ee081363 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/DeferredCommandPageIndexTests.cs @@ -0,0 +1,126 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.Libs.Gpu.GpuCommands; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.GpuCommands; + +// The command thread's queued stores, fills and copies indexed by guest page (upstream a7ef0c0a6, +// 9e1eed213, b13a98086 ported to DeferredCommandThread). +[Collection(CommandStreamQueueStateCollection.Name)] +public sealed class DeferredCommandPageIndexTests +{ + private const ulong Base = RecordingCommandStreamHost.MemoryBase; + private static readonly Action Nothing = static () => { }; + + private static DeferredCommandThread NewThread(RecordingCommandStreamHost host) => + new(new CommandStreamQueue(host), host.Memory, _ => { }, null, Nothing, recycleAsyncItems: true); + + [Fact] + public void AReadOfAPageNoQueuedItemTouchesTakesNoLock() + { + var host = new RecordingCommandStreamHost(); + var thread = NewThread(host); + thread.PostFill(Nothing, Base + 0x1000, 0x10, 0xAABBCCDD, ungated: true); + thread.PostOwnedWrite(Base + 0x2000, [1, 2, 3, 4]); + thread.PostLabel(Nothing, Base + 0x4000, 8); + Span bytes = stackalloc byte[4]; + + // Another page, and the page of a queued label: nothing the stream reads waits for either. + Assert.False(thread.TryReadQueuedFill(Base + 0x3000, bytes)); + thread.WaitForPendingRange(Base + 0x3000, 4); + Assert.True(thread.ReadOverlay(Base + 0x3000, bytes)); + Assert.False(thread.TryReadQueuedFill(Base + 0x4000, bytes)); + Assert.True(thread.ReadOverlay(Base + 0x4000, bytes)); + Assert.Equal(0, thread.LockedPendingReads); + + // The pages that hold queued items are still answered from them. + Assert.True(thread.TryReadQueuedFill(Base + 0x1004, bytes)); + Assert.Equal(0xAABBCCDDu, BinaryPrimitives.ReadUInt32LittleEndian(bytes)); + Assert.True(thread.ReadOverlay(Base + 0x2000, bytes)); + Assert.Equal(new byte[] { 1, 2, 3, 4 }, bytes.ToArray()); + Assert.True(thread.LockedPendingReads > 0); + + // Once the worker ran them, their pages read without the lock again. + Assert.Equal(3, thread.RunBatch(long.MaxValue, 64, Nothing)); + var locked = thread.LockedPendingReads; + Assert.False(thread.TryReadQueuedFill(Base + 0x1004, bytes)); + Assert.True(thread.ReadOverlay(Base + 0x2000, bytes)); + Assert.Equal(new byte[] { 1, 2, 3, 4 }, bytes.ToArray()); + Assert.Equal(locked, thread.LockedPendingReads); + } + + [Fact] + public void TheLastQueuedItemOverTheBytesDecidesThemAcrossPageAndWideItems() + { + var host = new RecordingCommandStreamHost(); + var thread = NewThread(host); + Span bytes = stackalloc byte[4]; + + // A fill over 128 pages is listed as wide; a known-bytes write inside it on one page comes later. + thread.PostFill(Nothing, Base, 0x80000, 0x11111111, ungated: true); + thread.PostWrite(Nothing, Base + 0x5000, [0x22, 0x22, 0x22, 0x22], ungated: true); + Assert.True(thread.TryReadQueuedFill(Base + 0x5000, bytes)); + Assert.Equal(0x22222222u, BinaryPrimitives.ReadUInt32LittleEndian(bytes)); + Assert.True(thread.TryReadQueuedFill(Base + 0x6000, bytes)); + Assert.Equal(0x11111111u, BinaryPrimitives.ReadUInt32LittleEndian(bytes)); + + // A wide fill queued after the page's write decides the page again. + thread.PostFill(Nothing, Base, 0x80000, 0x33333333, ungated: true); + Assert.True(thread.TryReadQueuedFill(Base + 0x5000, bytes)); + Assert.Equal(0x33333333u, BinaryPrimitives.ReadUInt32LittleEndian(bytes)); + + // A queued store over the bytes keeps the read from being answered by a range item. + thread.PostOwnedWrite(Base + 0x5002, [9, 9]); + Assert.False(thread.TryReadQueuedFill(Base + 0x5000, bytes)); + Assert.Equal(4, thread.RunBatch(long.MaxValue, 64, Nothing)); + } + + [Fact] + public void QueuedStoresApplyInQueueOrderOnOnePageAndAcrossPages() + { + var host = new RecordingCommandStreamHost(); + var thread = NewThread(host); + var owned = new byte[] { 1, 1, 1, 1, 1, 1, 1, 1 }; + thread.PostOwnedWrite(Base + 0x1FFC, owned); + thread.PostOwnedWrite(Base + 0x1FFE, [2, 2, 2, 2]); + thread.PostWrite(Base + 0x2000, [3]); + // Owned bytes are queued as they are, not copied. + owned[0] = 7; + + var page = new byte[4]; + Assert.True(thread.ReadOverlay(Base + 0x1FFC, page)); + Assert.Equal(new byte[] { 7, 1, 2, 2 }, page); + var across = new byte[8]; + Assert.True(thread.ReadOverlay(Base + 0x1FFC, across)); + Assert.Equal(new byte[] { 7, 1, 2, 2, 3, 2, 1, 1 }, across); + + Assert.Equal(3, thread.RunBatch(long.MaxValue, 64, Nothing)); + Assert.True(host.Memory.TryRead(Base + 0x1FFC, across)); + Assert.Equal(new byte[] { 7, 1, 2, 2, 3, 2, 1, 1 }, across); + } + + [Fact] + public void AWideQueuedStoreInterleavesWithThePageStoresInQueueOrder() + { + var host = new RecordingCommandStreamHost(); + var thread = NewThread(host); + thread.PostOwnedWrite(Base + 0x8000, [5, 5, 5, 5]); + thread.PostOwnedWrite(Base, new byte[0x50000]); + thread.PostOwnedWrite(Base + 0x8002, [6]); + var bytes = new byte[4]; + Assert.True(thread.ReadOverlay(Base + 0x8000, bytes)); + Assert.Equal(new byte[] { 0, 0, 6, 0 }, bytes); + + // A wide range queued over a page makes the stream wait for it, as before the index. + thread.PostRange(Nothing, Base, 0x50000); + var ran = 0; + thread.Post(() => ran++); + Assert.Equal(5, thread.RunBatch(long.MaxValue, 64, Nothing)); + Assert.Equal(1, ran); + thread.WaitForPendingRange(Base + 0x8000, 4); + Assert.False(thread.HasWork); + } +} From c2575cd68988f73c661379681ab1d3ed049d192e Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 22:33:19 +0000 Subject: [PATCH 060/134] [Metal] Record end-of-pipe landings, deferred labels included Upstream's soft waits (SHARPEMU_END_OF_PIPE_SOFT_WAITS, EndOfPipeLandings) need the host to name the tick of the recording that holds a release (EndOfPipeLanding.Recorded) and the queue to hear that tick complete (CommandStreamQueue.NotifyCompletedGpuTick); otherwise a soft wait passes only at its 8 ms cap, on idle or at shutdown. The Metal host did neither. MetalCommandStream.RecordEndOfPipe now records a write's landing with the serial of the buffer the release is recorded into and queues that serial's completion to the queue (QueueOperandWake), on the worker where the release is recorded. The landing never leaves the GPU host process: the interpreter, its queue and the Metal host all run there in the two-process split, and no wire message carries an EndOfPipeWrite. Metal defers every label (DefersEndOfPipeLabel), and the interpreter forgot the landing of a deferred label. But another queue's wait is met by a deferred label at parse time through the queue's pending labels, long before the GPU reaches it: the case soft waits exist for. A host that records landings now says so (ICommandStreamHost.RecordsDeferredLabelLandings, default false, so the Vulkan presenter and every other host keep their behaviour); on such a host a deferred label takes a landing and a wait met by another queue's pending label is admitted against the pending value. Metal answers true; SHARPEMU_METAL_V2_DEFERRED_LABEL_LANDINGS=0 restores the old forget. Shared edits: EndOfPipeLanding.Recorded is public (the Metal assembly has no InternalsVisibleTo from Libs); the new interface member; PublishLabel and the wait admission gated on it. Tests: EndOfPipeSoftWaitTests (a deferred label takes a landing and its soft wait passes on completion; a host that does not record them keeps the old behaviour); EndOfPipeLandingSceneTests on the device (the landing names the serial and that serial's completion reaches the queue). --- .../Gpu/GpuCommands/EndOfPipeLandings.cs | 3 +- .../GpuCommandInterpreter.Labels.cs | 7 +- .../GpuCommandInterpreter.Waits.cs | 15 ++++- .../Gpu/GpuCommands/ICommandStreamHost.cs | 7 ++ .../V2/MetalCommandStream.cs | 29 ++++++++ .../Scenes/EndOfPipeLandingSceneTests.cs | 67 +++++++++++++++++++ .../GpuCommands/CommandStreamTestSupport.cs | 2 + .../Gpu/GpuCommands/EndOfPipeSoftWaitTests.cs | 42 ++++++++++++ 8 files changed, 165 insertions(+), 7 deletions(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/Scenes/EndOfPipeLandingSceneTests.cs diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/EndOfPipeLandings.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/EndOfPipeLandings.cs index fafca3450..3a8d9c69d 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/EndOfPipeLandings.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/EndOfPipeLandings.cs @@ -42,7 +42,8 @@ internal EndOfPipeLanding(int queue, ulong destination, int width, ulong value, // Render thread: the release is in the recording that Submit gives this tick (SubmissionScheduler reserves timeline // ticks only there, in order, so the current recording's tick is CurrentTick; QueueCompletionAction relies on the same). - internal void Recorded(ulong tick) => Volatile.Write(ref _tick, (long)tick); + // Public for hosts outside this assembly (the Metal host). + public void Recorded(ulong tick) => Volatile.Write(ref _tick, (long)tick); internal void Consume() => Volatile.Write(ref _consumed, 1); diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Labels.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Labels.cs index 2d591e9ed..2afe048ab 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Labels.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Labels.cs @@ -241,14 +241,15 @@ private void PublishLabel(in EndOfPipeWrite write, bool is64Bit) } if (completion.WaitForGpu) _host.SynchronizeGpu(); - // A label the host defers (DefersEndOfPipeLabel) is not in guest memory yet: it takes no soft-wait hint. - var deferredByHost = _host.DefersEndOfPipeLabel(write.Kind); + // A label the host defers (DefersEndOfPipeLabel) is not in guest memory yet: it takes a soft-wait hint only on a + // host that records the landings of deferred labels (another queue's wait reads it from the pending labels). + var takesNoLanding = _host.DefersEndOfPipeLabel(write.Kind) && !_host.RecordsDeferredLabelLandings; if (is64Bit) WriteEndOfPipeQword(write.Destination, write.Value, write.Kind); else WriteEndOfPipeDword(write.Destination, (uint)write.Value, write.Kind); // SHARPEMU_END_OF_PIPE_SOFT_WAITS: the label is visible now; the host names the tick its release completes at. if (Landings is { } landings) { - if (deferredByHost) + if (takesNoLanding) { landings.Forget(write.Destination); } diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Waits.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Waits.cs index 168873ac6..0bc857353 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Waits.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/GpuCommandInterpreter.Waits.cs @@ -91,10 +91,17 @@ internal void WaitOnMemory(uint compareFunction, ulong address, ulong reference, pendingAnswer = satisfied; } + // Met by another queue's label still pending on a host that records deferred labels' landings: the value the + // landing is admitted against (RecordsDeferredLabelLandings). + ulong? pendingLabelAnswer = null; if (!satisfied && PendingLabelLookup is { } pending && pending(address, is64Bit, out var labelValue)) { _ = WaitOperation.TryCompare(labelValue, reference, mask, compareFunction, out satisfied); pendingAnswer = satisfied; + if (satisfied && _host.RecordsDeferredLabelLandings) + { + pendingLabelAnswer = labelValue; + } } if (!satisfied && !deferred) @@ -125,9 +132,11 @@ internal void WaitOnMemory(uint compareFunction, ulong address, ulong reference, return; } - // Met by the label bytes in guest memory, not a deferred label, a pending label or this queue's own write. - if (!deferred && !causal && Landings is { } landings && _execution is { } execution && - landings.Admit(QueueId, address, is64Bit ? 8 : 4, compareFunction, reference, mask, value, CompletedGpuTick) is { } landing) + // Met by the label bytes in guest memory, not a deferred label, a pending label or this queue's own write; or by + // another queue's pending label on a host that records the landings of deferred labels. + if (!deferred && (!causal || pendingLabelAnswer is not null) && Landings is { } landings && _execution is { } execution && + landings.Admit(QueueId, address, is64Bit ? 8 : 4, compareFunction, reference, mask, pendingLabelAnswer ?? value, + CompletedGpuTick) is { } landing) { ResumeSoftWait(new SoftWait(execution, execution.Depth, _packetAddress, landing, System.Diagnostics.Stopwatch.GetTimestamp())); } diff --git a/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs b/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs index ccb329de1..53313ca7e 100644 --- a/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs +++ b/src/SharpEmu.Libs/Gpu/GpuCommands/ICommandStreamHost.cs @@ -302,6 +302,13 @@ void TraceWritersOf(string subject, ulong address, ulong size) { } /// bool DefersEndOfPipeLabel(EndOfPipeWriteKind kind) => DefersEndOfPipeLabels; + // SHARPEMU_END_OF_PIPE_SOFT_WAITS on a host that defers labels: a label this host defers still releases another + // queue's wait at parse time through the queue's pending labels, as an immediately written one does, so it takes a + // landing too. Only a host that names the tick of every landing it is handed (EndOfPipeLanding.Recorded) and reports + // that tick's completion (CommandStreamQueue.NotifyCompletedGpuTick) answers true; any other host's deferred labels + // take no landing, as before. + bool RecordsDeferredLabelLandings => false; + // A host that counts no occlusion samples (Metal). Its ZPASS_DUMP pairs are the // always-visible ones: every dump writes one value from a counter that only grows to // 16 depth blocks, and the counter select and reset events are ignored, so an end dump diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs index 795f2bfac..0e1b49bf5 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCommandStream.cs @@ -853,6 +853,11 @@ public void RecordEndOfPipe(in EndOfPipeWrite write) var contextId = write.ContextId; var requestId = write.FlipRequestId; var encoded = TryEncodeEndOfPipeLabel(in write); + if (write.Landing is { } landing) + { + RecordLanding(landing); + } + if (DsTrace.Gpu && DsTrace.Armed) { // DSTRACE §4.7 LENC. deferred: 0 copy encoded at the packet, 1 copy deferred to @@ -2704,6 +2709,30 @@ private void PublishClockAtCompletion(in EndOfPipeWrite label) Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_GPU_LABELS") != "0" && !SharpEmu.Libs.Gpu.GpuCommands.FrameOverlapProbe.Enabled; + // SHARPEMU_END_OF_PIPE_SOFT_WAITS: another queue's wait met by a label this host defers (read from the queue's + // pending labels at parse time, long before the GPU reaches the label) waits softly for the release as it would + // for a label written as parsed: the label takes a landing, RecordEndOfPipe names the serial the label rides and + // that serial's completion reaches the queue (RecordLanding). SHARPEMU_METAL_V2_DEFERRED_LABEL_LANDINGS=0 gives + // deferred labels no landing again (soft waits then only follow labels published as parsed). + private static readonly bool DeferredLabelLandings = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_DEFERRED_LABEL_LANDINGS") != "0"; + + public bool RecordsDeferredLabelLandings => DeferredLabelLandings; + + // Worker, where the release is recorded: the buffer being recorded holds it, so the release has completed once + // that serial has; its completion tells the queue (the soft wait then passes as complete, not at its cap). + private void RecordLanding(EndOfPipeLanding landing) + { + var serial = SubmissionSerial; + landing.Recorded(serial); + QueueOperandWake(serial); + Interlocked.Increment(ref _recordedLandings); + } + + private long _recordedLandings; + + internal long RecordedLandings => Interlocked.Read(ref _recordedLandings); + /// /// The interpreter must never publish label bytes itself on this host: it parses a /// packet long before the GPU runs the work the label reports, and a guest told that diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/EndOfPipeLandingSceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/EndOfPipeLandingSceneTests.cs new file mode 100644 index 000000000..bd64bda75 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/EndOfPipeLandingSceneTests.cs @@ -0,0 +1,67 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Reflection; +using SharpEmu.Libs.Gpu.GpuCommands; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests.Scenes; + +/// +/// SHARPEMU_END_OF_PIPE_SOFT_WAITS on Metal: the host names the serial a release rides +/// (EndOfPipeLanding.Recorded) and that serial's completion reaches the command stream queue, so a soft wait +/// passes when the release completes and not only at its cap (MetalCommandStream.RecordLanding). +/// +public sealed class EndOfPipeLandingSceneTests(ITestOutputHelper output) : SceneTestBase(output) +{ + private const ulong Label = SceneMemory.Base + 0x100; + + private static EndOfPipeLanding NewLanding(ulong destination, ulong value) => + (EndOfPipeLanding)typeof(EndOfPipeLanding) + .GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, [typeof(int), typeof(ulong), typeof(int), typeof(ulong), typeof(long)])! + .Invoke([1, destination, sizeof(uint), value, 1L]); + + private static ulong TickOf(EndOfPipeLanding landing) => + (ulong)typeof(EndOfPipeLanding).GetProperty("Tick", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(landing)!; + + private static ulong CompletedTickOf(CommandStreamQueue queue) => + (ulong)typeof(CommandStreamQueue).GetField("_lastCompletedGpuTick", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(queue)!; + + [Fact] + public void ARecordedReleaseNamesItsSerialAndItsCompletionReachesTheQueue() + { + using var rig = CreateRig(); + if (rig is null) return; + var host = rig.Host; + Assert.True(((ICommandStreamHost)host).RecordsDeferredLabelLandings); + var landing = NewLanding(Label, 0x1234); + + var serial = host.SubmissionSerial; + host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write32, 1, Label, 0x1234) { Landing = landing }); + Assert.Equal(1L, host.RecordedLandings); + Assert.Equal(serial, TickOf(landing)); + Assert.True(CompletedTickOf(host.CommandStream) < serial); + + host.FlushAndWaitForGpu(); + var deadline = Environment.TickCount64 + 10_000; + while (CompletedTickOf(host.CommandStream) < serial) + { + Assert.True(Environment.TickCount64 < deadline, $"The queue never heard serial {serial} complete."); + host.PollGpuCompletions(); + Thread.Sleep(1); + } + + Assert.Equal(0x1234u, BitConverter.ToUInt32(rig.Read(Label, sizeof(uint)))); + } + + [Fact] + public void AWriteWithoutALandingRecordsNone() + { + using var rig = CreateRig(); + if (rig is null) return; + rig.Host.RecordEndOfPipe(new EndOfPipeWrite(EndOfPipeWriteKind.Write32, 1, Label, 0x1234)); + rig.Host.FlushAndWaitForGpu(); + Assert.Equal(0L, rig.Host.RecordedLandings); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs index 3df5f5938..3ee00d44a 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/CommandStreamTestSupport.cs @@ -117,6 +117,8 @@ public void TraceWritersOf(string subject, ulong address, ulong size) => public bool DefersEndOfPipeLabel(EndOfPipeWriteKind kind) => DefersKind?.Invoke(kind) ?? DefersEndOfPipeLabels; + public bool RecordsDeferredLabelLandings { get; set; } + public bool FlipDone { get; set; } = true; public ulong NextFlipRequestId { get; set; } = 1; diff --git a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/EndOfPipeSoftWaitTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/EndOfPipeSoftWaitTests.cs index 2483d316a..3cc3698a1 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/EndOfPipeSoftWaitTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/GpuCommands/EndOfPipeSoftWaitTests.cs @@ -424,4 +424,46 @@ public void AnUnmetWaitIsStillBlocked() Assert.Equal(SliceResult.BlockedWithoutProgress, setup.Queue.ProcessOne()); Assert.Equal(1, setup.Queue.BlockedQueueCount); } + + // A host that defers labels (Metal) leaves the release out of guest memory; another queue's wait is met at once by + // the queue's pending label, as by a label written as parsed. A host that records deferred labels' landings gives it + // one, so the wait is soft and passes when the release's tick completes. + [Fact] + public void ADeferredLabelTakesALandingOnAHostThatRecordsItsTick() + { + var setup = NewQueue(); + setup.Host.DefersEndOfPipeLabels = true; + setup.Host.PendingLabelTick = 7; + setup.Host.RecordsDeferredLabelLandings = true; + setup.Host.EndOfPipeRecorded = write => write.Landing?.Recorded(7); + var landing = Published(setup, Release32(Label, 1)); + Assert.Equal(0u, setup.Host.ReadDword(Label)); + Graphics0(setup, 3, Wait32(3, Label, 1), Draw(7)); + OtherWork(setup); + + Assert.Equal(SliceResult.BlockedWithoutProgress, setup.Queue.ProcessOne()); + Assert.Equal(0, Draws(setup)); + + setup.Queue.NotifyCompletedGpuTick(7); + RunUntilIdle(setup); + + Assert.Equal(1, Draws(setup)); + Assert.Equal(EndOfPipeLandings.Release.Complete, landing.ReleasedBy); + } + + [Fact] + public void ADeferredLabelTakesNoLandingOnAHostThatDoesNotRecordIt() + { + var setup = NewQueue(); + setup.Host.DefersEndOfPipeLabels = true; + setup.Host.PendingLabelTick = 7; + Compute(setup, FirstCompute, ComputeA, 1, Release32(Label, 1)); + Assert.Equal(SliceResult.Completed, setup.Queue.ProcessOne()); + Assert.Null(setup.Host.EndOfPipeWrites[^1].Landing); + Graphics0(setup, 3, Wait32(3, Label, 1), Draw(7)); + OtherWork(setup); + + Assert.Equal(SliceResult.Completed, setup.Queue.ProcessOne()); + Assert.Equal(1, Draws(setup)); + } } From 94d03463e80a2b85086af08921df62f544719041 Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 22:36:55 +0000 Subject: [PATCH 061/134] [Shader] Count vertex and instance ids from the draw's bases and store them in named user data The MSL vertex entry reads [[base_vertex]]/[[base_instance]] (the rectangle-list wrapper and the mesh launch take them from the draw block) and stores the base an indirect packet names in user data, as the SPIR-V translator does under SupportsDrawParameters. The Metal host reports ShaderDrawParametersSupported; SHARPEMU_METAL_DRAW_PARAMETERS=0 restores the old ids. --- docs/macos/configuration.md | 1 + .../Gpu/Pipelines/ShaderCorpus.cs | 1 + .../Gpu/Pipelines/ShaderProgramCache.cs | 2 + .../Gen5MslMeshLaunch.cs | 5 +- .../Gen5MslRectangleList.cs | 23 +- .../Gen5MslTranslator.Mesh.cs | 13 +- .../Gen5MslTranslator.cs | 59 ++++- .../V2/MetalRenderHost.BufferWordVariants.cs | 3 +- .../V2/MetalRenderHost.RectangleRebase.cs | 38 +-- .../V2/MetalRenderHost.Rendering.cs | 3 +- .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 11 + .../Gen5ComputeFixtures.cs | 6 +- .../MetalNative.DrawParameters.cs | 73 ++++++ .../MetalNative.Patch.cs | 3 +- .../MetalNative.Vertex.cs | 15 +- .../MslDrawParameterTests.cs | 237 ++++++++++++++++++ 16 files changed, 459 insertions(+), 34 deletions(-) create mode 100644 tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.DrawParameters.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Metal.Tests/MslDrawParameterTests.cs diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index adb32c9e1..11916e9ad 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -65,6 +65,7 @@ them for measurements or to isolate a problem. | Variable | Default | Effect | | --- | --- | --- | | `SHARPEMU_METAL_MESH_SHADERS` | on | `0` disables mesh pipelines for primitive-shader draws. | +| `SHARPEMU_METAL_DRAW_PARAMETERS` | on | `0` turns off draw parameters in translated vertex programs. By default a vertex program's instance index counts from the draw's base instance, and when an indirect draw names a user-data register for its base vertex or start instance, the program counts its vertex index from the base vertex and stores both bases there (the command processor no longer writes those registers). `0` gives the program Metal's ids, which include both bases, and stores nothing. | | `SHARPEMU_METAL_MESHLETS` | on | `0` disables the meshlet cache. | | `SHARPEMU_METAL_V2_BINARY_ARCHIVE` | on | `0` disables the on-disk library and pipeline archives. | | `SHARPEMU_METAL_V2_BINARY_ARCHIVE_BUDGET_MB` | `8192` | Size bound of the archives on disk. | diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCorpus.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCorpus.cs index 17b3b62d4..b14d0711a 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCorpus.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCorpus.cs @@ -25,6 +25,7 @@ public sealed record ShaderCorpusHostFlags public bool ExecGuardElision { get; init; } public bool ComputeWave64SubgroupNative { get; init; } public bool ComputeRunsOn32LaneSubgroups { get; init; } + public bool DrawParameters { get; init; } } // One program as the translator was about to see it. Options is null when the guest code did not diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index 20b99fb3b..dda430a9e 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -777,6 +777,7 @@ private ShaderCodeCapture CaptureCode(ShaderSource source, RecordingCpuMemory re ExecGuardElision = _host.ExecGuardElisionEnabled, ComputeWave64SubgroupNative = _host.ComputeWave64SubgroupNative, ComputeRunsOn32LaneSubgroups = options?.ComputeInfo is { } compute && _host.ComputeRunsOn32LaneSubgroups(compute), + DrawParameters = _host.ShaderDrawParametersSupported, }; // What the code bytes held when they failed, and any command-processor write into @@ -3073,6 +3074,7 @@ private sealed class CorpusReplayHost(ShaderCorpusHostFlags flags) : IShaderPipe public bool ExecGuardElisionEnabled => flags.ExecGuardElision; public bool PerVertexPixelInputsSupported => flags.PerVertexPixelInputs; public bool ClipDistanceEnabled => flags.ClipDistance; + public bool ShaderDrawParametersSupported => flags.DrawParameters; public RenderHostLimits Limits => default; public GpuSampleCount NoAttachmentSampleCounts => default; diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslMeshLaunch.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslMeshLaunch.cs index 8d5172cc1..7bce5e7e3 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslMeshLaunch.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslMeshLaunch.cs @@ -144,7 +144,7 @@ public static void WriteMeshParameters( /// /// The parameters of one non-indexed rectangle-list slot: the kernel writes Gen5RectDraw - /// (vertex_base = firstVertex) and MTLDrawPatchIndirectArguments with one patch per + /// (vertex_base = base_vertex = firstVertex) and MTLDrawPatchIndirectArguments with one patch per /// rectangle, as the CPU draw does. /// public static void WriteRectangleParameters(Span parameters, ulong argumentsOffset, ulong maxThreadgroups) @@ -198,7 +198,7 @@ struct sharpemu_mesh_launch_params const ulong limit = ulong(p.max_threadgroups_low) | (ulong(p.max_threadgroups_high) << 32); // A non-indexed rectangle list: Gen5RectDraw (vertex_base, vertex_offset, - // index_type, first_index), then (patchCount, instanceCount, patchStart, + // index_type, first_index, base_vertex), then (patchCount, instanceCount, patchStart, // baseInstance), one patch per {{Gen5MslRectangleList.VerticesPerRectangle}} vertices. if (p.rectangle_list != 0u) { @@ -207,6 +207,7 @@ struct sharpemu_mesh_launch_params block[1] = 0u; block[2] = 0u; block[3] = 0u; + block[4] = arguments[2]; grid[0] = ulong(patches) * ulong(arguments[1]) > limit ? 0u : patches; grid[1] = arguments[1]; grid[2] = 0u; diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslRectangleList.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslRectangleList.cs index dbb520b01..7aa361304 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslRectangleList.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslRectangleList.cs @@ -34,8 +34,10 @@ public static partial class Gen5MslRectangleList public const int IndexBufferIndex = 29; /// Byte size of the per-draw block: vertex_base, vertex_offset, index_type - /// (0 none, 1 16-bit, 2 32-bit) and first_index, one dword each. - public const uint DrawInfoByteSize = 16; + /// (0 none, 1 16-bit, 2 32-bit), first_index and base_vertex (the draw's base vertex as + /// a vertex function's [[base_vertex]] gives it: the first vertex of an automatic draw, + /// the vertex offset of an indexed one), one dword each. + public const uint DrawInfoByteSize = 20; /// Guest vertices per rectangle. public const uint VerticesPerRectangle = 3; @@ -108,6 +110,14 @@ public static string BuildSource(Gen5MslShader shader) continue; } + // A post-tessellation function has no [[base_vertex]]; the draw block holds the + // base the vertex ids above count from. + if (parameter.Contains("[[base_vertex]]", StringComparison.Ordinal)) + { + arguments.Add("sharpemu_rect_base_vertex(sharpemu_rect_draw)"); + continue; + } + entryParameters.Add(parameter); arguments.Add(name); } @@ -231,6 +241,7 @@ struct Gen5RectDraw int vertex_offset; uint index_type; uint first_index; + uint base_vertex; }; // The guest vertex index of one corner of a rectangle: consecutive vertices from @@ -251,6 +262,14 @@ static inline uint sharpemu_rect_vertex_id(constant Gen5RectDraw& draw, device c return index + (uint)draw.vertex_offset; } + // The base vertex the draw's vertex ids count from. The block carries it apart from + // vertex_offset: an indirect draw rebased on the GPU folds its offset into the + // indices it hands over. + static inline uint sharpemu_rect_base_vertex(constant Gen5RectDraw& draw) + { + return draw.base_vertex; + } + // The corner the rectangle's two edges leave at right angles: it shares x with one // neighbour and y with the other. The fourth corner is opposite it. A rectangle // whose edges are not axis-aligned takes the first vertex, which is v1 + v2 - v0. diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Mesh.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Mesh.cs index 8fae93acd..79c65b189 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Mesh.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Mesh.cs @@ -703,9 +703,12 @@ private void EmitMeshInitialState(StringBuilder source) " const uint sharpemu_mesh_prim_slot = sharpemu_meshlets_on ? sharpemu_ml.z + sharpemu_tg_index : " + $"sharpemu_mesh_subgroup * {MeshDrawInfoName}.primitives_per_subgroup + sharpemu_tg_index;"); } + // With the base vertex in user data (BaseVertexUserData) the guest index counts + // from it and the user data holds it, as on the vertex path. + var baseVertexTerm = StoresBaseVertex ? string.Empty : $" + {MeshDrawInfoName}.base_vertex"; var plainVertexIndex = $"(uint)((int)sharpemu_mesh_index({MeshIndexBufferName}, " + - $"{MeshDrawInfoName}, sharpemu_mesh_vertex_slot) + {MeshDrawInfoName}.base_vertex)"; + $"{MeshDrawInfoName}, sharpemu_mesh_vertex_slot){baseVertexTerm})"; if (!mesh.HasGeometryHalf && !mesh.Amplified) { // A meshlet lists its vertices' raw index values; the lane past the meshlet's @@ -715,7 +718,7 @@ private void EmitMeshInitialState(StringBuilder source) source.AppendLine( " ? (sharpemu_tg_index < (sharpemu_ml.w & 0xFFFFu)"); source.AppendLine( - $" ? (uint)((int){MeshletBufferName}[{MeshDrawInfoName}.meshlet_vertex_base + sharpemu_ml.x + sharpemu_tg_index] + {MeshDrawInfoName}.base_vertex)"); + $" ? (uint)((int){MeshletBufferName}[{MeshDrawInfoName}.meshlet_vertex_base + sharpemu_ml.x + sharpemu_tg_index]{baseVertexTerm})"); source.AppendLine(" : 0u)"); source.AppendLine($" : {plainVertexIndex};"); } @@ -723,8 +726,10 @@ private void EmitMeshInitialState(StringBuilder source) { source.AppendLine($" const uint sharpemu_mesh_vertex_index = {plainVertexIndex};"); } - source.AppendLine( - $" const uint sharpemu_mesh_instance_index = {MeshDrawInfoName}.first_instance + sharpemu_mesh_instance;"); + source.AppendLine(UsesDrawParameters + ? " const uint sharpemu_mesh_instance_index = sharpemu_mesh_instance;" + : $" const uint sharpemu_mesh_instance_index = {MeshDrawInfoName}.first_instance + sharpemu_mesh_instance;"); + EmitDrawParameterStores(source, $"(uint){MeshDrawInfoName}.base_vertex", $"{MeshDrawInfoName}.first_instance"); source.AppendLine(); // Merged wave info: this wave's ES vertex count in bits 0-7, its GS primitive diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs index e9c48d470..d90445dca 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs @@ -574,6 +574,43 @@ static bool EndsInside(uint count, uint size) => /// functions only for kernel and fragment functions (MSL spec 6.10) and gives a /// vertex function no [[thread_index_in_simdgroup]], so there is no supported /// lane index to shuffle or ballot against. + /// The draw parameters of a vertex program (SupportsDrawParameters, as the SPIR-V + /// translator reads them): the guest's instance index counts from 0 and the draw's start + /// instance reaches it only through the user data an indirect packet names + /// (StartInstanceUserData); the vertex index counts from the draw's base vertex when an + /// indirect packet names user data for that (BaseVertexUserData), which then holds it. + /// Metal's vertex_id and instance_id include the draw's base vertex and base instance. + /// A domain program is a post-tessellation function with a launch of its own. + private bool UsesDrawParameters => + _request.SupportsDrawParameters && + _stage is Gen5MslStage.Vertex or Gen5MslStage.Mesh && + _request.Tessellation is not { Role: Gen5TessellationRole.Domain }; + + private bool StoresBaseVertex => UsesDrawParameters && _request.BaseVertexUserData >= 0; + + private bool StoresStartInstance => UsesDrawParameters && _request.StartInstanceUserData >= 0; + + // The user-data SGPR an indirect packet names, as the SPIR-V translator stores it + // (UserDataBase + index); one past the register file has nowhere to go. + private string? DrawParameterScalar(int userData) + { + var register = _request.UserDataBase + (uint)userData; + return register < ScalarRegisterFileCount ? $"s[{register}]" : null; + } + + private void EmitDrawParameterStores(StringBuilder source, string baseVertex, string baseInstance) + { + if (StoresBaseVertex && DrawParameterScalar(_request.BaseVertexUserData) is { } vertexScalar) + { + source.AppendLine($" {vertexScalar} = {baseVertex};"); + } + + if (StoresStartInstance && DrawParameterScalar(_request.StartInstanceUserData) is { } instanceScalar) + { + source.AppendLine($" {instanceScalar} = {baseInstance};"); + } + } + private bool HasRealWaveLanes => _stage is Gen5MslStage.Compute or Gen5MslStage.Mesh || (_stage == Gen5MslStage.Pixel && _request.EnableGraphicsSubgroupOperations); @@ -1063,6 +1100,15 @@ private void EmitModule(StringBuilder source, IReadOnlyList blocks) { source.AppendLine(" uint sharpemu_vertex_id [[vertex_id]],"); source.AppendLine(" uint sharpemu_instance_id [[instance_id]],"); + if (StoresBaseVertex) + { + source.AppendLine(" uint sharpemu_base_vertex [[base_vertex]],"); + } + + if (UsesDrawParameters) + { + source.AppendLine(" uint sharpemu_base_instance [[base_instance]],"); + } } else if (_stage == Gen5MslStage.Compute && IsWave64) { @@ -1668,9 +1714,16 @@ private void EmitInitialState(StringBuilder source) } else if (_stage == Gen5MslStage.Vertex) { - // Hardware-selected VGPRs for the vertex and instance indices. - source.AppendLine(" v[5] = sharpemu_vertex_id;"); - source.AppendLine(" v[8] = sharpemu_instance_id;"); + // Hardware-selected VGPRs for the vertex and instance indices. With draw + // parameters they count from the draw's base vertex (when user data holds it) + // and base instance, as Gen5SpirvTranslator's vertex entry does. + source.AppendLine(StoresBaseVertex + ? " v[5] = sharpemu_vertex_id - sharpemu_base_vertex;" + : " v[5] = sharpemu_vertex_id;"); + source.AppendLine(UsesDrawParameters + ? " v[8] = sharpemu_instance_id - sharpemu_base_instance;" + : " v[8] = sharpemu_instance_id;"); + EmitDrawParameterStores(source, "sharpemu_base_vertex", "sharpemu_base_instance"); } else if (_stage == Gen5MslStage.Mesh) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs index 10eba58a2..7722675cc 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs @@ -76,7 +76,8 @@ internal sealed partial class MetalRenderHost /// The translation switches that decide the MSL, for the stamps of what is stored by them. internal static string TranslationSwitchStamp => - $"portable={(PortableBuffers ? 1 : 0)},buffer_word_constants={(BufferWordConstants ? 1 : 0)}"; + $"portable={(PortableBuffers ? 1 : 0)},buffer_word_constants={(BufferWordConstants ? 1 : 0)}," + + $"draw_parameters={(DrawParameters ? 1 : 0)}"; /// Variants one pipeline entry keeps; a draw of another layout past them draws generic. internal const int MaxBufferWordVariantsPerPipeline = 16; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.RectangleRebase.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.RectangleRebase.cs index 23f448d55..07cc66266 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.RectangleRebase.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.RectangleRebase.cs @@ -61,10 +61,16 @@ internal sealed partial class MetalRenderHost private const string RectangleRebaseFunction = "sharpemu_rect_rebase"; + // The patch draw's Gen5RectDraw follows the patch arguments in the same allocation, at + // this dword, where the rebase draw writes its base vertex. + private const uint RebaseRectDrawWord = 8; + private const string RectangleRebaseSource = """ #include using namespace metal; + constant uint RectDrawWord = 8u; + struct SharpEmuRectRebase { uint index_limit; @@ -103,6 +109,9 @@ vertex void sharpemu_rect_rebase( patch_arguments[1] = record[1]; patch_arguments[2] = 0u; patch_arguments[3] = record[4]; + // Gen5RectDraw's base_vertex: the control points carry the vertex offset, so + // the patch draw's block has none, and the program's base vertex comes here. + patch_arguments[RectDrawWord + 4u] = base_instance; } } """; @@ -133,13 +142,19 @@ private void DrawRectanglesIndexedIndirect(MetalPipelineEntry entry, BufferBindi } var controlPoints = _guestMemory.Allocate(Math.Max(limit, 1u) * (ulong)sizeof(uint), 256, out _); - var patchArguments = _guestMemory.Allocate(4 * sizeof(uint), 256, out var patchArgumentBytes); + var patchArguments = _guestMemory.Allocate( + (RebaseRectDrawWord * 4u) + Gen5MslRectangleList.DrawInfoByteSize, 256, out var patchArgumentBytes); if (!controlPoints.IsValid || !patchArguments.IsValid) { throw Fatal($"An indirect rectangle list has no ring space for its control points: limit={limit}."); } patchArgumentBytes.Clear(); + // The patch draw's block: a 32-bit indexed draw from index 0 with no vertex offset + // (the control points carry it); the rebase draw fills in base_vertex. + var rectDraw = System.Runtime.InteropServices.MemoryMarshal.Cast(patchArgumentBytes) + .Slice((int)RebaseRectDrawWord, (int)(Gen5MslRectangleList.DrawInfoByteSize / sizeof(uint))); + rectDraw[2] = 2; var rebase = RectangleRebasePipeline(); MetalNative.SendVoid(_renderEncoder, SelSetRenderPipelineState, rebase); _boundRenderState = rebase; @@ -174,21 +189,12 @@ private void DrawRectanglesIndexedIndirect(MetalPipelineEntry entry, BufferBindi var state = RectangleState(entry, 2); MetalNative.SendVoid(_renderEncoder, SelSetRenderPipelineState, state); _boundRenderState = state; - Span draw = stackalloc uint[(int)(Gen5MslRectangleList.DrawInfoByteSize / sizeof(uint))]; - draw.Clear(); - draw[2] = 2; - unsafe - { - fixed (uint* words = draw) - { - MetalV2Native.SendSetBytes( - _renderEncoder, - SelSetVertexBytes, - (nint)words, - Gen5MslRectangleList.DrawInfoByteSize, - Gen5MslRectangleList.DrawInfoBufferIndex); - } - } + MetalNative.SendSetBuffer( + _renderEncoder, + SelSetVertexBuffer, + patchArguments.Buffer, + (nuint)patchArguments.Offset + (RebaseRectDrawWord * 4u), + Gen5MslRectangleList.DrawInfoBufferIndex); MetalNative.SendSetBuffer( _renderEncoder, diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs index a3de2eea6..cb8306aac 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Rendering.cs @@ -2380,12 +2380,13 @@ private void DrawRectangles( _boundVertexOffsets[binding] = (ulong)offset; } - // vertex_base, vertex_offset, index_type, first_index; see Gen5RectDraw. + // vertex_base, vertex_offset, index_type, first_index, base_vertex; see Gen5RectDraw. Span block = stackalloc uint[(int)(Gen5MslRectangleList.DrawInfoByteSize / sizeof(uint))]; block[0] = indexed ? 0 : firstVertex; block[1] = unchecked((uint)vertexOffset); block[2] = indexed ? index32 ? 2u : 1u : 0u; block[3] = indexed ? firstIndex : 0; + block[4] = indexed ? unchecked((uint)vertexOffset) : firstVertex; unsafe { fixed (uint* words = block) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index d6fc7ce7e..6642b91e9 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -316,6 +316,17 @@ internal ulong ReadCompletedSerial(bool useCompletedSnapshot) // Tessellated draws are emulated (hull kernel + post-tessellation vertex function), never native stages. public bool TessellationStagesSupported => false; + // A vertex function has [[base_vertex]] and [[base_instance]] on every Apple GPU, so the + // translator counts the guest's vertex and instance indices from the draw's base and stores + // the base an indirect packet names in user data there (ShaderCompileRequest.BaseVertexUserData, + // StartInstanceUserData), which the command processor then leaves unwritten. + // SHARPEMU_METAL_DRAW_PARAMETERS=0 keeps Metal's ids (which include both bases) and stores + // neither, as before. + public bool ShaderDrawParametersSupported => DrawParameters; + + internal static readonly bool DrawParameters = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_DRAW_PARAMETERS") != "0"; + public GpuSampleCount NoAttachmentSampleCounts => GpuSampleCount.Count1Bit; // Per-vertex pixel inputs are MSL 4.0's metal::vertex_value (macOS 26). The feature set diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ComputeFixtures.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ComputeFixtures.cs index 2fed3d96c..56dbabb58 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ComputeFixtures.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ComputeFixtures.cs @@ -886,7 +886,8 @@ public static ShaderCompileRequest RequestOrThrow(Gen5ShaderProgram program, Sha bool pixelStencilExportEnable = false, bool pixelSampleMaskExportEnable = false, uint floatMode = ShaderCompileRequest.DefaultFloatMode, bool dx10Clamp = true, bool pixelGuestWave32 = false, uint meshPerVertexParameterMask = 0, IReadOnlyList? vertexInterpolants = null, - Gen5TessellationLaunch? tessellation = null, bool pixelEarlyDepth = false) + Gen5TessellationLaunch? tessellation = null, bool pixelEarlyDepth = false, bool supportsDrawParameters = false, + int baseVertexUserData = -1, int startInstanceUserData = -1) { var plan = ShaderResourcePlan.Extract(program, stage, RequestHash, userDataBase, UserDataCount, excludedUserDataRegisters: excludedUserDataRegisters); @@ -930,6 +931,9 @@ public static ShaderCompileRequest RequestOrThrow(Gen5ShaderProgram program, Sha PixelSampleMaskExportEnable = pixelSampleMaskExportEnable, PixelEarlyDepth = pixelEarlyDepth, Tessellation = tessellation, + SupportsDrawParameters = supportsDrawParameters, + BaseVertexUserData = baseVertexUserData, + StartInstanceUserData = startInstanceUserData, }; } diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.DrawParameters.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.DrawParameters.cs new file mode 100644 index 000000000..14da13396 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.DrawParameters.cs @@ -0,0 +1,73 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.InteropServices; + +namespace SharpEmu.ShaderCompiler.Metal.Tests; + +/// +/// The draw calls that carry a base vertex and a base instance, directly and through an +/// indirect argument buffer, for 's draw callback. +/// +internal static partial class MetalNative +{ + private const nuint TrianglePrimitive = 3; + private const nuint IndexTypeUInt16 = 0; + + [LibraryImport(ObjCLibrary, EntryPoint = "objc_msgSend")] + private static partial void SendDrawPrimitivesBaseInstance(nint receiver, nint selector, nuint primitiveType, + nuint vertexStart, nuint vertexCount, nuint instanceCount, nuint baseInstance); + + [LibraryImport(ObjCLibrary, EntryPoint = "objc_msgSend")] + private static partial void SendDrawIndexedBaseVertex(nint receiver, nint selector, nuint primitiveType, + nuint indexCount, nuint indexType, nint indexBuffer, nuint indexBufferOffset, nuint instanceCount, + nint baseVertex, nuint baseInstance); + + [LibraryImport(ObjCLibrary, EntryPoint = "objc_msgSend")] + private static partial void SendDrawIndirect(nint receiver, nint selector, nuint primitiveType, + nint indirectBuffer, nuint indirectBufferOffset); + + [LibraryImport(ObjCLibrary, EntryPoint = "objc_msgSend")] + private static partial void SendDrawIndexedIndirect(nint receiver, nint selector, nuint primitiveType, + nuint indexType, nint indexBuffer, nuint indexBufferOffset, nint indirectBuffer, nuint indirectBufferOffset); + + /// A triangle list of vertices from + /// , one instance from . + public static Action DrawAuto(uint vertexStart, uint vertexCount, uint baseInstance) => encoder => + SendDrawPrimitivesBaseInstance(encoder, Selector("drawPrimitives:vertexStart:vertexCount:instanceCount:baseInstance:"), + TrianglePrimitive, vertexStart, vertexCount, 1, baseInstance); + + /// An indexed triangle list over 16-bit , one instance. + public static Action DrawIndexed(ushort[] indices, int baseVertex, uint baseInstance) => encoder => + SendDrawIndexedBaseVertex(encoder, + Selector("drawIndexedPrimitives:indexCount:indexType:indexBuffer:indexBufferOffset:instanceCount:baseVertex:baseInstance:"), + TrianglePrimitive, (nuint)indices.Length, IndexTypeUInt16, IndexBuffer(indices), 0, 1, baseVertex, baseInstance); + + /// The guest's automatic indirect record (vertexCount, instanceCount, firstVertex, + /// firstInstance), which is MTLDrawPrimitivesIndirectArguments. + public static Action DrawAutoIndirect(uint vertexStart, uint vertexCount, uint baseInstance) => encoder => + SendDrawIndirect(encoder, Selector("drawPrimitives:indirectBuffer:indirectBufferOffset:"), TrianglePrimitive, + SharedBuffer(Words(vertexCount, 1, vertexStart, baseInstance)), 0); + + /// The guest's indexed indirect record (indexCount, instanceCount, firstIndex, + /// vertexOffset, firstInstance), which is MTLDrawIndexedPrimitivesIndirectArguments. + public static Action DrawIndexedIndirect(ushort[] indices, int baseVertex, uint baseInstance) => encoder => + SendDrawIndexedIndirect(encoder, + Selector("drawIndexedPrimitives:indexType:indexBuffer:indexBufferOffset:indirectBuffer:indirectBufferOffset:"), + TrianglePrimitive, IndexTypeUInt16, IndexBuffer(indices), 0, + SharedBuffer(Words((uint)indices.Length, 1, 0, unchecked((uint)baseVertex), baseInstance)), 0); + + private static nint IndexBuffer(ushort[] indices) + { + var bytes = new byte[Math.Max((indices.Length * sizeof(ushort) + 3) & ~3, 16)]; + Buffer.BlockCopy(indices, 0, bytes, 0, indices.Length * sizeof(ushort)); + return SharedBuffer(bytes); + } + + private static byte[] Words(params uint[] words) + { + var bytes = new byte[words.Length * sizeof(uint)]; + Buffer.BlockCopy(words, 0, bytes, 0, bytes.Length); + return bytes; + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.Patch.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.Patch.cs index deae52055..d33b254aa 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.Patch.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.Patch.cs @@ -120,10 +120,11 @@ public static bool TryRenderRectanglePatches( SendSetBuffer(encoder, setVertexBuffer, SharedBuffer(positionBytes), 0, 2); } - // Gen5RectDraw: vertex_base, vertex_offset, index_type, first_index. + // Gen5RectDraw: vertex_base, vertex_offset, index_type, first_index, base_vertex. var drawBlock = new byte[Gen5MslRectangleList.DrawInfoByteSize]; BitConverter.TryWriteBytes(drawBlock.AsSpan(0), indices is null ? vertexBase : 0u); BitConverter.TryWriteBytes(drawBlock.AsSpan(8), indices is null ? 0u : 1u); + BitConverter.TryWriteBytes(drawBlock.AsSpan(16), indices is null ? vertexBase : 0u); SendSetBuffer(encoder, setVertexBuffer, SharedBuffer(drawBlock), 0, Gen5MslRectangleList.DrawInfoBufferIndex); var indexBytes = new byte[Math.Max(((indices?.Length ?? 0) * sizeof(ushort) + 3) & ~3, 16)]; if (indices is not null) diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.Vertex.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.Vertex.cs index f28e529b7..979fcd508 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.Vertex.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.Vertex.cs @@ -28,7 +28,7 @@ private static partial void SendDrawPrimitives(nint receiver, nint selector, nui /// Draws vertices as a triangle list into a /// width x height x layers RGBA32Float array target and returns its texels, layer after /// layer. The stage resources at buffer 0 are zero-filled; the viewports default to the - /// whole target. + /// whole target. , when given, encodes the draw instead. public static bool TryRenderVertices( nint library, string vertexEntryPoint, @@ -40,7 +40,8 @@ public static bool TryRenderVertices( uint layers, IReadOnlyList? viewports, out float[] pixels, - out string error) + out string error, + Action? draw = null) { pixels = []; error = string.Empty; @@ -115,7 +116,15 @@ public static bool TryRenderVertices( } } - SendDrawPrimitives(encoder, Selector("drawPrimitives:vertexStart:vertexCount:"), 3, 0, vertexCount); // Triangle + if (draw is null) + { + SendDrawPrimitives(encoder, Selector("drawPrimitives:vertexStart:vertexCount:"), 3, 0, vertexCount); // Triangle + } + else + { + draw(encoder); + } + SendVoid(encoder, Selector("endEncoding")); SendVoid(commandBuffer, Selector("commit")); SendVoid(commandBuffer, Selector("waitUntilCompleted")); diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslDrawParameterTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslDrawParameterTests.cs new file mode 100644 index 000000000..ecb453811 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslDrawParameterTests.cs @@ -0,0 +1,237 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.ShaderCompiler.Metal.Tests; + +/// +/// Draw parameters in a translated vertex program, as Gen5SpirvTranslator's vertex entry has +/// them (upstream 8ddf6601e, 99f9fe930): with SupportsDrawParameters the instance index counts +/// from the draw's base instance, and a user-data register an indirect packet names for the +/// base vertex (BaseVertexUserData) or the start instance (StartInstanceUserData) receives +/// that base, the vertex index then counting from the base vertex. The command processor +/// leaves such a register unwritten (GpuCommandInterpreter.DrawIndirectArguments), so without +/// the store the program would read whatever the register last held. +/// +public sealed class MslDrawParameterTests(ITestOutputHelper output) +{ + private const uint TargetSize = 8; + private const uint Pos0 = 12; + private const uint Param0 = 32; + private const int BaseVertexUserData = 1; + private const int StartInstanceUserData = 2; + private const int BaseVertex = 100; + private const uint BaseInstance = 7; + + // ---- structure ---- + + [Fact] + public void TheVertexEntryStoresBothBasesInTheNamedUserData() + { + var shader = Compile(ProbeProgram(), drawParameters: true, BaseVertexUserData, StartInstanceUserData); + Assert.Contains("uint sharpemu_base_vertex [[base_vertex]]", shader.Source); + Assert.Contains("uint sharpemu_base_instance [[base_instance]]", shader.Source); + Assert.Contains("v5 = sharpemu_vertex_id - sharpemu_base_vertex;", shader.Source); + Assert.Contains("v8 = sharpemu_instance_id - sharpemu_base_instance;", shader.Source); + Assert.Contains($"s{BaseVertexUserData} = sharpemu_base_vertex;", shader.Source); + Assert.Contains($"s{StartInstanceUserData} = sharpemu_base_instance;", shader.Source); + // The stores land after the user data is loaded, or the load would undo them. + var load = shader.Source.IndexOf($" s{BaseVertexUserData} = ", StringComparison.Ordinal); + var store = shader.Source.IndexOf($" s{BaseVertexUserData} = sharpemu_base_vertex;", StringComparison.Ordinal); + Assert.True(load >= 0 && store > load, "the user data load of s1 does not come first"); + } + + [Fact] + public void WithoutAUserDataRegisterOnlyTheInstanceCountsFromItsBase() + { + var shader = Compile(ProbeProgram(), drawParameters: true, -1, -1); + Assert.DoesNotContain("[[base_vertex]]", shader.Source); + Assert.Contains("v5 = sharpemu_vertex_id;", shader.Source); + Assert.Contains("v8 = sharpemu_instance_id - sharpemu_base_instance;", shader.Source); + Assert.DoesNotContain("= sharpemu_base_instance;", shader.Source); + } + + [Fact] + public void WithoutDrawParametersTheIdsAreMetals() + { + var shader = Compile(ProbeProgram(), drawParameters: false, BaseVertexUserData, StartInstanceUserData); + Assert.DoesNotContain("[[base_vertex]]", shader.Source); + Assert.DoesNotContain("[[base_instance]]", shader.Source); + Assert.Contains("v5 = sharpemu_vertex_id;", shader.Source); + Assert.Contains("v8 = sharpemu_instance_id;", shader.Source); + } + + [Fact] + public void ARectangleListTakesItsBaseVertexFromTheDrawBlock() + { + var shader = Compile(ProbeProgram(), drawParameters: true, BaseVertexUserData, StartInstanceUserData); + var source = Gen5MslRectangleList.BuildSource(shader); + Assert.Contains("sharpemu_rect_base_vertex(sharpemu_rect_draw)", source); + Assert.Contains("uint base_vertex;", source); + Assert.DoesNotContain("[[base_vertex]]", source); + Assert.Contains("[[base_instance]]", source); + if (MetalNative.IsAvailable) + { + Assert.True(MetalNative.TryCompileLibrary(source, out _, out var error), $"Metal rejected the rectangle form: {error}\n{source}"); + } + } + + [Fact] + public void AMeshStageStoresTheDrawBlocksBases() + { + // A primitive shader the host runs as a mesh pipeline is a plain vertex program to + // the command processor, so it gets the same user-data registers. + var userDataBase = Gen5NggFixtures.VertexUserDataBase; + var request = Gen5ComputeFixtures.RequestOrThrow(Gen5NggFixtures.CullingTriangle(), ShaderStage.Vertex, + requiredVertexOutputCount: 1, primitiveShader: Gen5NggFixtures.StageInfo, userDataBase: userDataBase, + supportsDrawParameters: true, baseVertexUserData: 4, startInstanceUserData: 5); + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error), error); + Assert.Equal(Gen5MslStage.Mesh, shader.Stage); + Assert.Contains($"s{userDataBase + 4} = (uint)sharpemu_draw.base_vertex;", shader.Source); + Assert.Contains($"s{userDataBase + 5} = sharpemu_draw.first_instance;", shader.Source); + Assert.Contains("const uint sharpemu_mesh_instance_index = sharpemu_mesh_instance;", shader.Source); + Assert.DoesNotContain("sharpemu_mesh_vertex_slot) + sharpemu_draw.base_vertex", shader.Source); + + var plain = Gen5NggFixtures.CompileOrThrow(Gen5NggFixtures.CullingTriangle()); + Assert.Contains("sharpemu_mesh_vertex_slot) + sharpemu_draw.base_vertex", plain.Source); + Assert.Contains("sharpemu_draw.first_instance + sharpemu_mesh_instance;", plain.Source); + if (MetalNative.IsAvailable) + { + Assert.True(MetalNative.TryCompileLibrary(shader.Source, out _, out var compileError), + $"Metal rejected the mesh stage: {compileError}"); + } + } + + // ---- on the device ---- + + public static TheoryData Draws => new() { "auto", "indexed", "auto-indirect", "indexed-indirect" }; + + [Theory] + [MemberData(nameof(Draws))] + public void TheProgramSeesTheDrawsBasesInItsUserData(string draw) + { + if (SkipWithoutMetalDevice($"the {draw} draw")) return; + + var pixel = Render(drawParameters: true, draw); + output.WriteLine($"{draw}: s1={pixel[0]} s2={pixel[1]} v8={pixel[2]} w={pixel[3]}"); + // The triangle is only on screen when the vertex index counts from the base vertex, + // and its colour is (s1, s2, v8): the base vertex, the start instance and instance 0. + Assert.Equal([BaseVertex, BaseInstance, 0f, 1f], pixel); + } + + [Fact] + public void WithoutDrawParametersTheUserDataKeepsItsValue() + { + if (SkipWithoutMetalDevice("the draw without draw parameters")) return; + + // Metal's vertex id includes the base, which puts the triangle off screen. + var pixel = Render(drawParameters: false, "indexed"); + Assert.Equal([0f, 0f, 0f, 0f], pixel); + } + + private float[] Render(bool drawParameters, string draw) + { + var shader = Compile(ProbeProgram(), drawParameters, BaseVertexUserData, StartInstanceUserData); + var source = shader.Source + FragmentSource; + Assert.True(MetalNative.TryCompileLibrary(source, out var library, out var compileError), $"{compileError}\n{source}"); + ushort[] indices = [0, 1, 2]; + var encode = draw switch + { + "auto" => MetalNative.DrawAuto(BaseVertex, 3, BaseInstance), + "indexed" => MetalNative.DrawIndexed(indices, BaseVertex, BaseInstance), + "auto-indirect" => MetalNative.DrawAutoIndirect(BaseVertex, 3, BaseInstance), + "indexed-indirect" => MetalNative.DrawIndexedIndirect(indices, BaseVertex, BaseInstance), + _ => throw new ArgumentOutOfRangeException(nameof(draw)), + }; + Assert.True( + MetalNative.TryRenderVertices(library, shader.EntryPoint, "gen5_draw_parameter_fs", shader.ArgumentLayout?.ByteSize ?? 0, + vertexCount: 3, TargetSize, TargetSize, layers: 1, viewports: null, out var pixels, out var renderError, encode), + renderError); + var center = ((TargetSize / 2) * TargetSize + (TargetSize / 2)) * 4; + return pixels[(int)center..(int)(center + 4)]; + } + + private static Gen5MslShader Compile(Gen5ShaderProgram program, bool drawParameters, int baseVertexUserData, int startInstanceUserData) + { + var request = Gen5ComputeFixtures.RequestOrThrow(program, ShaderStage.Vertex, requiredVertexOutputCount: 1, + supportsDrawParameters: drawParameters, baseVertexUserData: baseVertexUserData, startInstanceUserData: startInstanceUserData); + if (!Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error)) + { + throw new InvalidOperationException($"vertex emit failed: {error}"); + } + + return shader; + } + + // A triangle over the whole target from vertex indices 0, 1 and 2 ((index & 1, index >> 1) + // * 4 - 1), which indices from 100 put far above it; param 0 is (s1, s2, v8, 1). + private static Gen5ShaderProgram ProbeProgram() + { + var instructions = new List(); + var pc = 0u; + void Add(string opcode, Gen5ShaderEncoding encoding, Gen5Operand[] sources, + Gen5Operand[] destinations, Gen5InstructionControl? control = null) + { + instructions.Add(new Gen5ShaderInstruction(pc, encoding, opcode, [0u], sources, destinations, control)); + pc += sizeof(uint); + } + + Add("VAndB32", Gen5ShaderEncoding.Vop2, [Inline(1), Vector(5)], [Vector(10)]); + Add("VCvtF32U32", Gen5ShaderEncoding.Vop1, [Vector(10)], [Vector(11)]); + Add("VMulF32", Gen5ShaderEncoding.Vop2, [Literal(Bits(4.0f)), Vector(11)], [Vector(11)]); + Add("VAddF32", Gen5ShaderEncoding.Vop2, [Literal(Bits(-1.0f)), Vector(11)], [Vector(11)]); + Add("VLshrrevB32", Gen5ShaderEncoding.Vop2, [Inline(1), Vector(5)], [Vector(12)]); + Add("VCvtF32U32", Gen5ShaderEncoding.Vop1, [Vector(12)], [Vector(13)]); + Add("VMulF32", Gen5ShaderEncoding.Vop2, [Literal(Bits(4.0f)), Vector(13)], [Vector(13)]); + Add("VAddF32", Gen5ShaderEncoding.Vop2, [Literal(Bits(-1.0f)), Vector(13)], [Vector(13)]); + Add("VMovB32", Gen5ShaderEncoding.Vop1, [Inline(0)], [Vector(20)]); + Add("VMovB32", Gen5ShaderEncoding.Vop1, [Literal(Bits(1.0f))], [Vector(21)]); + Add("VCvtF32U32", Gen5ShaderEncoding.Vop1, [Scalar(BaseVertexUserData)], [Vector(30)]); + Add("VCvtF32U32", Gen5ShaderEncoding.Vop1, [Scalar(StartInstanceUserData)], [Vector(31)]); + Add("VCvtF32U32", Gen5ShaderEncoding.Vop1, [Vector(8)], [Vector(32)]); + Add("Exp", Gen5ShaderEncoding.Exp, [Vector(11), Vector(13), Vector(20), Vector(21)], [], + new Gen5ExportControl(Pos0, 0xF, false, false, false)); + Add("Exp", Gen5ShaderEncoding.Exp, [Vector(30), Vector(31), Vector(32), Vector(21)], [], + new Gen5ExportControl(Param0, 0xF, false, true, false)); + Add("SEndpgm", Gen5ShaderEncoding.Sopp, [], []); + return new Gen5ShaderProgram(0, instructions); + } + + private const string FragmentSource = """ + + struct Gen5DrawParameterIn + { + float4 position [[position]]; + float4 param0 [[user(locn0)]]; + }; + + fragment float4 gen5_draw_parameter_fs(Gen5DrawParameterIn in [[stage_in]]) + { + return in.param0; + } + """; + + private bool SkipWithoutMetalDevice(string activity) + { + if (MetalNative.IsAvailable) return false; + Assert.False( + OperatingSystem.IsMacOS() && Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") == "1", + $"The required gate cannot run {activity} without a Metal device."); + output.WriteLine($"No Metal device on this host; {activity} skipped."); + return true; + } + + private static uint Bits(float value) => BitConverter.SingleToUInt32Bits(value); + + private static Gen5Operand Literal(uint value) => new(Gen5OperandKind.LiteralConstant, value); + + private static Gen5Operand Inline(uint value) => new(Gen5OperandKind.EncodedConstant, 128 + value); + + private static Gen5Operand Vector(uint index) => Gen5Operand.Vector(index); + + private static Gen5Operand Scalar(int index) => new(Gen5OperandKind.ScalarRegister, (uint)index); +} From bf2056ab15e93f15893dd544606b39fa0b4f7d98 Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 22:37:02 +0000 Subject: [PATCH 062/134] [Tests] Pin a store after a copy landing after the copied bytes on Metal Upstream f484338f5 makes the Vulkan host apply the deferred read protection of earlier GPU copy writes before a command-stream store lands, so a guest that sees the store cannot read the bytes from before the copy. The Metal host has no deferred protection step: a command-processor copy writes guest memory itself, recorded in stream order ahead of the store, and the image bytes a label vouches for are written back before the label (PublishLinearGpuWrites). This test pins the order as the guest observes it, polling raw guest memory while the GPU runs a DMA_DATA copy followed by a WRITE_DATA flag, with queued and unqueued command-processor writes. Upstream's GPU-side claims on GuestWriteReservations (7cf0ac568) are not ported: see artifacts/agent-logs/port-notes.md (the Metal store hooks a reserved CPU write runs before it releases wait for fenced writebacks through the GPU worker, so a claim entered on the worker would invert that order). --- .../Scenes/StoreAfterCopySceneTests.cs | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/Scenes/StoreAfterCopySceneTests.cs diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/StoreAfterCopySceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/StoreAfterCopySceneTests.cs new file mode 100644 index 000000000..135bed2d1 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/StoreAfterCopySceneTests.cs @@ -0,0 +1,57 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests.Scenes; + +/// +/// Upstream f484338f5 ("block CPU reads of earlier GPU writes before a command-stream store lands"): a store the guest +/// polls after a command-processor copy tells it the copy is done, so a CPU read that sees the store must see the +/// copied bytes. The Vulkan host defers the read protection of GPU-written pages and applies it before the store; the +/// Metal host has no such step to defer, because the copy writes guest memory itself, in stream order ahead of the +/// store. This pins that order as the guest observes it: raw guest memory, polled while the GPU runs the stream. +/// +public sealed class StoreAfterCopySceneTests(ITestOutputHelper output) : SceneTestBase(output) +{ + private const uint Words = 256; + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AStoreAfterACopyIsNeverSeenBeforeTheCopiedBytes(bool queued) + { + using var rig = CreateRig(); + if (rig is null) return; + rig.Host.QueueCommandProcessorWrites = queued; + var source = rig.Memory.Allocate(Words * 4); + var destination = rig.Memory.Allocate(Words * 4); + var flag = rig.Memory.Allocate(16); + var pattern = Enumerable.Range(0, (int)Words).Select(word => 0xC0DE0000u | (uint)word).ToArray(); + rig.Memory.Write(source, pattern); + rig.Memory.Write(destination, new byte[Words * 4]); + rig.Memory.Write32(flag, 0); + + var stream = new ScenePm4() + // DMA_DATA, memory to memory, the whole source to the destination. + .Packet(0x50, 0u, (uint)source, (uint)(source >> 32), (uint)destination, (uint)(destination >> 32), Words * 4) + // WRITE_DATA of the flag the guest polls. + .Packet(ScenePm4.OpWriteData, 1u << 8, (uint)flag, (uint)(flag >> 32), 1u); + rig.Enqueue(stream.ToArray()); + rig.RecordPending(); + + var deadline = Environment.TickCount64 + 10_000; + while (BitConverter.ToUInt32(rig.Memory.ReadRaw(flag, 4)) != 1) + { + Assert.True(Environment.TickCount64 < deadline, "The store never landed."); + rig.Host.FlushAndWaitForGpu(); + rig.Host.PollGpuCompletions(); + } + + var copied = rig.Memory.ReadRaw(destination, (int)Words * 4); + Assert.Equal(pattern, Enumerable.Range(0, (int)Words).Select(word => BitConverter.ToUInt32(copied, word * 4))); + rig.Drain(); + Assert.Empty(rig.Fatals); + } +} From 687dccc01ad3ca593d6533e4f63e56be770edf14 Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 22:41:17 +0000 Subject: [PATCH 063/134] [Metal] Take a draw's stencil operations from its dynamic state Upstream fills DynamicDrawState.FrontStencilOperations/BackStencilOperations in the shared recorder (RenderExecutor.DynamicState) and the Vulkan presenter sets them per draw with vkCmdSetStencilOp. The Metal host built its MTLDepthStencilState from the bound pipeline's static parameters instead. Both come from the same DepthStencilState of the draw's depth target (ShaderPipelineCache resolves the pipeline's static parameters from depth.Target.State, the executor the dynamic state from depthTarget.State), and the static parameters are part of the pipeline key, so they agree for every draw whose pipeline was resolved for it. The Metal render pipeline itself does not depend on the operations (MetalPipelineStateKey leaves them out), so the depth/stencil state now reads them, and keys on them, from the draw's dynamic state, which no longer depends on which draw a pipeline handle was resolved for. SHARPEMU_METAL_V2_DYNAMIC_STENCIL_OPS=0 reads the pipeline's again. The dynamic state never crosses the split wire: the recorder and the Metal host both run in the GPU host process. Tests: MetalDynamicStencilTests (the draw's operations win over the pipeline's; draws differing only in front or back operations get their own depth/stencil states, on the device). --- .../V2/MetalRenderHost.Pipelines.cs | 43 ++++++++++---- .../MetalDynamicStencilTests.cs | 59 +++++++++++++++++++ 2 files changed, 90 insertions(+), 12 deletions(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalDynamicStencilTests.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs index 15b6fe335..4e9f1312a 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs @@ -1815,15 +1815,16 @@ private nint GetDepthStencilState(MetalPipelineEntry entry, in DynamicDrawState if (stencilEnabled) { + var (front, back) = StencilOperationsOf(entry.StaticParameters, in state); ConfigureStencil( descriptor, MetalNative.Selector("setFrontFaceStencil:"), - parameters!.StencilFront, + front, state.FrontStencil); ConfigureStencil( descriptor, MetalNative.Selector("setBackFaceStencil:"), - parameters.StencilBack, + back, state.BackStencil); } @@ -1885,6 +1886,23 @@ private void ConfigureStencil( } } + // The draw's stencil operations, as the shared recorder resolved them into its dynamic state (upstream keeps them + // dynamic and sets them with vkCmdSetStencilOp; here they go into the depth/stencil state). The pipeline's static + // parameters carry the same operations for the draw the pipeline was resolved for; the dynamic state is the + // draw's own. SHARPEMU_METAL_V2_DYNAMIC_STENCIL_OPS=0 reads the pipeline's again. + internal static (StencilOperations Front, StencilOperations Back) StencilOperationsOf( + PipelineStaticParameters? pipeline, in DynamicDrawState state) => + DynamicStencilOperations || pipeline is null + ? (state.FrontStencilOperations, state.BackStencilOperations) + : (pipeline.StencilFront, pipeline.StencilBack); + + // The depth/stencil state a draw with this pipeline state and dynamic state gets (tests). + internal nint DepthStencilStateForTest(bool hasDepth, bool hasStencil, PipelineStaticParameters parameters, in DynamicDrawState state) => + GetDepthStencilState(new MetalPipelineEntry { HasDepth = hasDepth, HasStencil = hasStencil, StaticParameters = parameters }, in state); + + private static readonly bool DynamicStencilOperations = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_DYNAMIC_STENCIL_OPS") != "0"; + private static ulong MixDepthStencilKey(MetalPipelineEntry entry, in DynamicDrawState state, bool stencilEnabled) { var hash = 14695981039346656037UL; @@ -1896,16 +1914,17 @@ private static ulong MixDepthStencilKey(MetalPipelineEntry entry, in DynamicDraw Mix(MetalV2Diagnostics.LoosensEqualFor(entry.VertexHash) ? 1UL : 0UL); Mix(MetalV2Diagnostics.PassesDepthFor(entry.VertexHash) ? 1UL : 0UL); Mix(stencilEnabled ? 1UL : 0UL); - if (stencilEnabled && entry.StaticParameters is { } parameters) - { - Mix((ulong)parameters.StencilFront.Compare); - Mix((ulong)parameters.StencilFront.FailOperation); - Mix((ulong)parameters.StencilFront.PassOperation); - Mix((ulong)parameters.StencilFront.DepthFailOperation); - Mix((ulong)parameters.StencilBack.Compare); - Mix((ulong)parameters.StencilBack.FailOperation); - Mix((ulong)parameters.StencilBack.PassOperation); - Mix((ulong)parameters.StencilBack.DepthFailOperation); + if (stencilEnabled && entry.StaticParameters is not null) + { + var (front, back) = StencilOperationsOf(entry.StaticParameters, in state); + Mix((ulong)front.Compare); + Mix((ulong)front.FailOperation); + Mix((ulong)front.PassOperation); + Mix((ulong)front.DepthFailOperation); + Mix((ulong)back.Compare); + Mix((ulong)back.FailOperation); + Mix((ulong)back.PassOperation); + Mix((ulong)back.DepthFailOperation); Mix(state.FrontStencil.CompareMask | ((ulong)state.FrontStencil.WriteMask << 32)); Mix(state.BackStencil.CompareMask | ((ulong)state.BackStencil.WriteMask << 32)); } diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalDynamicStencilTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalDynamicStencilTests.cs new file mode 100644 index 000000000..e03f86aa7 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalDynamicStencilTests.cs @@ -0,0 +1,59 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.Abstractions; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +// The stencil operations and compares a draw's depth/stencil state uses are the ones the shared recorder put into its +// dynamic state (DynamicDrawState.FrontStencilOperations / BackStencilOperations, upstream 7cf0ac568), not the ones of +// whatever draw the pipeline was resolved for. +public sealed class MetalDynamicStencilTests(Xunit.Abstractions.ITestOutputHelper output) : Scenes.SceneTestBase(output) +{ + private static readonly StencilOperations Replace = new(GpuStencilOp.Replace, GpuStencilOp.Replace, GpuStencilOp.Keep, GpuCompareOp.Always); + private static readonly StencilOperations Invert = new(GpuStencilOp.Keep, GpuStencilOp.Invert, GpuStencilOp.Zero, GpuCompareOp.Less); + + private static PipelineStaticParameters Pipeline() + { + var parameters = new PipelineStaticParameters { ColorCount = 1, Topology = GpuPrimitiveTopology.TriangleList, Samples = 1 }; + parameters.StencilTestEnable = true; + parameters.StencilFront = Replace; + parameters.StencilBack = Replace; + return parameters; + } + + private static DynamicDrawState Draw(StencilOperations front, StencilOperations back) => new( + 0, 0, 64, 64, 0, 1, new ScissorRectangle(0, 0, 64, 64), 1, + 0, 0, 0, 0, true, true, GpuCompareOp.Less, false, 0, 0, 0, false, 0, 1, true, + new StencilMasks(0xFF, 0xFF, 1), new StencilMasks(0xFF, 0xFF, 1), 1, 0xF, + FrontStencilOperations: front, BackStencilOperations: back); + + [Fact] + public void TheDrawsOwnStencilOperationsWinOverThePipelines() + { + var (front, back) = MetalRenderHost.StencilOperationsOf(Pipeline(), Draw(Invert, Replace)); + Assert.Equal(Invert, front); + Assert.Equal(Replace, back); + } + + [Fact] + public void DrawsThatDifferOnlyInStencilOperationsGetTheirOwnDepthStencilStates() + { + using var rig = CreateRig(); + if (rig is null) return; + var host = rig.Host; + var pipeline = Pipeline(); + var asPipeline = host.DepthStencilStateForTest(true, true, pipeline, Draw(Replace, Replace)); + var inverted = host.DepthStencilStateForTest(true, true, pipeline, Draw(Invert, Replace)); + var backInverted = host.DepthStencilStateForTest(true, true, pipeline, Draw(Replace, Invert)); + Assert.NotEqual(0, asPipeline); + Assert.NotEqual(asPipeline, inverted); + Assert.NotEqual(asPipeline, backInverted); + Assert.NotEqual(inverted, backInverted); + Assert.Equal(inverted, host.DepthStencilStateForTest(true, true, pipeline, Draw(Invert, Replace))); + } +} From d6de7e9f777feaf07dc9d3f995b475e3a8a52b8b Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 22:41:36 +0000 Subject: [PATCH 064/134] [Shader] Read storage image store channel maps from shader data in MSL The MSL translator no longer refuses RuntimeImageSwizzle: a store through a storage image picks each channel from the map the Metal host writes with the stage's shader data (WriteStageShaderData), so one module serves every destination select. The Metal host reports RuntimeImageSwizzlesSupported, the prewarm and static precompile pass the same flag, and corpus replay keeps the live host's draw parameter and swizzle answers. SHARPEMU_RUNTIME_IMAGE_SWIZZLE=0 bakes the select again; the compile-time MSL tests pin that mode and gain runtime twins, and a device test compares baked and runtime stores bit for bit. --- .../Gpu/Pipelines/ShaderCorpus.cs | 1 + .../Gpu/Pipelines/ShaderProgramCache.cs | 2 + .../Gen5MslTranslator.Pixel.cs | 35 ++++ .../Gen5MslTranslator.Resources.cs | 8 - .../V2/MetalRenderHost.BufferWordVariants.cs | 3 +- .../V2/MetalRenderHost.Descriptors.cs | 2 + .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 7 + .../V2/MetalShaderPrewarm.cs | 3 +- .../V2/MetalStaticPrecompile.cs | 3 +- .../MetalStoreChannelMapTests.cs | 83 ++++++++ .../Gen5ImageFixtures.cs | 8 +- .../MetalRuntimeImageSwizzleExecutionTests.cs | 180 ++++++++++++++++++ .../MslTranslationTests.cs | 66 ++++++- 13 files changed, 379 insertions(+), 22 deletions(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalStoreChannelMapTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalRuntimeImageSwizzleExecutionTests.cs diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCorpus.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCorpus.cs index b14d0711a..bd211a117 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCorpus.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCorpus.cs @@ -26,6 +26,7 @@ public sealed record ShaderCorpusHostFlags public bool ComputeWave64SubgroupNative { get; init; } public bool ComputeRunsOn32LaneSubgroups { get; init; } public bool DrawParameters { get; init; } + public bool RuntimeImageSwizzles { get; init; } } // One program as the translator was about to see it. Options is null when the guest code did not diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index dda430a9e..eb09aac8a 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -778,6 +778,7 @@ private ShaderCodeCapture CaptureCode(ShaderSource source, RecordingCpuMemory re ComputeWave64SubgroupNative = _host.ComputeWave64SubgroupNative, ComputeRunsOn32LaneSubgroups = options?.ComputeInfo is { } compute && _host.ComputeRunsOn32LaneSubgroups(compute), DrawParameters = _host.ShaderDrawParametersSupported, + RuntimeImageSwizzles = _host.RuntimeImageSwizzlesSupported, }; // What the code bytes held when they failed, and any command-processor write into @@ -3075,6 +3076,7 @@ private sealed class CorpusReplayHost(ShaderCorpusHostFlags flags) : IShaderPipe public bool PerVertexPixelInputsSupported => flags.PerVertexPixelInputs; public bool ClipDistanceEnabled => flags.ClipDistance; public bool ShaderDrawParametersSupported => flags.DrawParameters; + public bool RuntimeImageSwizzlesSupported => flags.RuntimeImageSwizzles; public RenderHostLimits Limits => default; public GpuSampleCount NoAttachmentSampleCounts => default; diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Pixel.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Pixel.cs index d2d535cc5..2fb8d92ec 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Pixel.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Pixel.cs @@ -164,6 +164,10 @@ private bool EmitImageOperation( return false; } } + else if (StoreChannelMapSlot(resourceIndex) is var slot && slot >= 0) + { + EmitRuntimeSwizzleStoreTexel(image, kind, slot, components); + } else { for (var component = 0; component < 4; component++) @@ -741,6 +745,37 @@ private string ImageStoreComponent(Gen5ImageControl image, string kind, uint com : low; } + // The slot of an image's store channel map in shader data (RuntimeImageSwizzle.Slot), or -1 when its stores + // follow the select the module was specialized with. + private int StoreChannelMapSlot(int resourceIndex) => + _request.Bindings.StorageImageSwizzleCount == 0 || resourceIndex < 0 + ? -1 + : RuntimeImageSwizzle.Slot(_request.Resources.Info.Images, resourceIndex); + + // A store's texel when the image's select is shader data (RuntimeImageSwizzle), as Gen5SpirvTranslator's + // RuntimeSwizzleStoreTexel builds it: the words of the components the dmask enables, in data-register order (zero + // for the others), each moved to the physical channel its slot's map names (a code xor its channel; 4 stores + // zero), which is where GetImageStoreSourceIndex places them for a select baked into the module. + private void EmitRuntimeSwizzleStoreTexel(Gen5ImageControl image, string kind, int slot, string[] components) + { + var dmask = (image.Dmask & 0xFu) == 0 ? 1u : image.Dmask & 0xFu; + var logical = new string[4]; + var source = 0u; + for (var component = 0; component < logical.Length; component++) + { + logical[component] = (dmask & (1u << component)) != 0 ? ImageStoreComponent(image, kind, source++) : "0u"; + } + + var words = Temp("uint4", $"uint4({string.Join(", ", logical)})"); + var map = Temp("uint", + $"{ShaderDataDword(_request.Bindings.StorageImageSwizzlesDword + (uint)slot / 2)} >> {(uint)slot % 2 * 16}u"); + for (var channel = 0u; channel < 4; channel++) + { + var code = Temp("uint", $"((({map}) >> {channel * 3}u) & 7u) ^ {channel}u"); + components[channel] = ImageTexelComponent(kind, $"({code} < 4u ? {words}[{code} & 3u] : 0u)"); + } + } + private static string ImageTexelComponent(string kind, string raw) => kind switch { "int" => $"as_type({raw})", diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs index e4aec1920..a8a5b82da 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs @@ -42,14 +42,6 @@ public static bool TryCompileProgram( return false; } - // A storage image whose stores take their channel map from shader data (RuntimeImageSwizzle) was specialized with - // the identity select; the MSL emitter does not read the map, so its stores would ignore the T#'s select. - if (request.Bindings.StorageImageSwizzleCount != 0) - { - error = "Metal does not support storage image channel maps in shader data (RuntimeImageSwizzle)."; - return false; - } - // The guest mesh stage (Vulkan's task/mesh path) has no MSL emission; the Metal mesh path // compiles NGG primitive shaders as Vertex requests with PrimitiveShader set instead. if (request.Stage == ShaderStage.Mesh) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs index 7722675cc..87e8d5fbe 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs @@ -77,7 +77,8 @@ internal sealed partial class MetalRenderHost /// The translation switches that decide the MSL, for the stamps of what is stored by them. internal static string TranslationSwitchStamp => $"portable={(PortableBuffers ? 1 : 0)},buffer_word_constants={(BufferWordConstants ? 1 : 0)}," + - $"draw_parameters={(DrawParameters ? 1 : 0)}"; + $"draw_parameters={(DrawParameters ? 1 : 0)}," + + $"runtime_image_swizzle={(RuntimeImageSwizzle.Enabled ? 1 : 0)}"; /// Variants one pipeline entry keeps; a draw of another layout past them draws generic. internal const int MaxBufferWordVariantsPerPipeline = 16; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs index 07f89eb48..a3b4aa121 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs @@ -634,6 +634,8 @@ internal static bool WriteStageShaderData(uint[] shaderData, ShaderProgramInfo p MipStatistics.WriteImageFields(shaderData, layout, info, snapshot.Images); } + // Each written image's store channel map, from its bound T# (RuntimeImageSwizzle). + RuntimeImageSwizzle.WriteStoreMaps(shaderData, layout, info.Images, snapshot.Images); return true; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index 6642b91e9..a877b53fe 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -305,6 +305,7 @@ internal ulong ReadCompletedSerial(bool useCompletedSnapshot) internal const bool PrewarmSharedInt64Atomics = false; internal const bool PrewarmSignedZeroInfNanPreserve = true; internal const bool PrewarmExecGuardElision = true; + internal const bool PrewarmRuntimeImageSwizzles = true; public ShaderPrewarmList? ShaderPrewarm => MetalShaderPrewarm.List; public GraphicsPrewarmList? GraphicsPrewarm => MetalShaderPrewarm.Graphics; @@ -327,6 +328,12 @@ internal ulong ReadCompletedSerial(bool useCompletedSnapshot) internal static readonly bool DrawParameters = Environment.GetEnvironmentVariable("SHARPEMU_METAL_DRAW_PARAMETERS") != "0"; + // The translator reads a storage image's store channel map from shader data, which the + // descriptor path writes from the bound T# (WriteStageShaderData), so one module serves every + // destination select. SHARPEMU_RUNTIME_IMAGE_SWIZZLE=0 bakes the select into the module again + // (ShaderProgramCache applies the switch on top of this answer). + public bool RuntimeImageSwizzlesSupported => PrewarmRuntimeImageSwizzles; + public GpuSampleCount NoAttachmentSampleCounts => GpuSampleCount.Count1Bit; // Per-vertex pixel inputs are MSL 4.0's metal::vertex_value (macOS 26). The feature set diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs index 39b788e3b..b04b58348 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs @@ -853,7 +853,8 @@ private static void PrewarmComputePipeline( MetalRenderHost.PrewarmSignedZeroInfNanPreserve, out var compiled, out _, - out var error)) + out var error, + runtimeImageSwizzles: MetalRenderHost.PrewarmRuntimeImageSwizzles)) { NoteFailure(record, error); return; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStaticPrecompile.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStaticPrecompile.cs index d8cb861c9..5b6c699ca 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStaticPrecompile.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStaticPrecompile.cs @@ -534,7 +534,8 @@ internal static List Translate(StaticShaderBuild build, IGuestGpu { if (ShaderPrewarmCompiler.TryCompilePrewarm(compute, build.ComputeCode!, compiler, MetalRenderHost.PrewarmSharedInt64Atomics, MetalRenderHost.PrewarmExecGuardElision, - MetalRenderHost.PrewarmSignedZeroInfNanPreserve, out var compiled, out _, out _) && + MetalRenderHost.PrewarmSignedZeroInfNanPreserve, out var compiled, out _, out _, + runtimeImageSwizzles: MetalRenderHost.PrewarmRuntimeImageSwizzles) && compiled is MetalCompiledGuestShader metal) { shaders.Add(metal.Shader); diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalStoreChannelMapTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalStoreChannelMapTests.cs new file mode 100644 index 000000000..20d12c495 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalStoreChannelMapTests.cs @@ -0,0 +1,83 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.Tests.Scenes; +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using ImageResourceClass = SharpEmu.ShaderCompiler.Resources.ImageResourceClass; + +namespace SharpEmu.Gpu.Metal.Tests; + +/// +/// A program translated with runtime image swizzles reads each written storage image's store channel map from its +/// shader data. The Metal host writes the maps from the bound T#s with the rest of the stage's shader data, on the +/// worker and in a binding packet alike, so one module stores through any destination select. +/// +public sealed class MetalStoreChannelMapTests +{ + private const uint Rgba8 = 56; + + [Fact] + public void TheHostReportsRuntimeImageSwizzles() + { + Assert.True(MetalRenderHost.PrewarmRuntimeImageSwizzles); + } + + [Fact] + public void TheShaderDataCarriesEachWrittenImagesStoreChannelMap() + { + // Two written storage images take slots 0 and 1; the sampled one between them takes none. + ImageResource[] images = [Storage(), Sampled(), Storage()]; + var info = new ShaderResourceInfo { Images = [.. images] }; + var resources = new SpecializedResourceInfo { Info = info }; + var layout = new BindingLayout + { + UserDataRegisters = [0], + MemoryOffsetDword = 8, + StorageImageSwizzleCount = 2, + }; + var program = new ShaderProgramInfo + { + Stage = ShaderStageKind.Compute, Resources = resources, Bindings = layout, UserDataBase = 0, + }; + const uint ZyxW = 0xF2E; + const uint X001 = 0x204; + var snapshot = new ResourceSnapshot + { + Images = [Texture(0x10_0000, ZyxW), Texture(0x20_0000, 0xFAC), Texture(0x30_0000, X001)], + Samplers = [], + UserData = [7], + }; + + var shaderData = new uint[layout.ShaderDataDwordCount]; + Assert.True(MetalRenderHost.WriteStageShaderData(shaderData, program, layout, info, snapshot, 0)); + var expected = RuntimeImageSwizzle.StoreChannelMap(ZyxW) | (RuntimeImageSwizzle.StoreChannelMap(X001) << 16); + Assert.Equal(expected, shaderData[layout.StorageImageSwizzlesDword]); + Assert.NotEqual(RuntimeImageSwizzle.StoreChannelMap(ZyxW), RuntimeImageSwizzle.StoreChannelMap(X001)); + Assert.Equal(7u, shaderData[0]); + + var packet = MetalRenderHost.BuildBindingPacket(program, resources, layout, snapshot, 0)!; + Assert.True(packet.HasShaderData); + Assert.Equal(shaderData, packet.ShaderData[..packet.ShaderDataCount]); + } + + private static uint[] Texture(ulong address, uint select) + { + var words = Descriptors.Texture(address, Rgba8, 16, 16); + words[3] = (words[3] & ~0xFFFu) | select; + return words; + } + + private static ImageResource Sampled() => new() + { + ResourceClass = ImageResourceClass.Sampled, NumericClass = ImageNumericClass.Float, Dimension = ImageDimension.Dim2D, + }; + + private static ImageResource Storage() => new() + { + ResourceClass = ImageResourceClass.Storage, NumericClass = ImageNumericClass.Float, Dimension = ImageDimension.Dim2D, + Written = true, + }; +} diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ImageFixtures.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ImageFixtures.cs index 0d28098b9..1f07a9e0a 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ImageFixtures.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ImageFixtures.cs @@ -77,7 +77,9 @@ public static bool TryCompile( bool unorm = false, uint[]? samplerWords = null, int resultRegisters = 4, - Func? configure = null) + Func? configure = null, + bool? runtimeImageSwizzles = null, + Action? inspect = null) { var isArray = arrayed ?? descriptorType is ImageType1DArray or ImageType2DArray or ImageTypeCube or ImageType2DMsaaArray; var dimension = instructionDimension ?? descriptorType switch @@ -154,7 +156,8 @@ public static bool TryCompile( instructions.Add(end with { Pc = pc }); var program = new Gen5ShaderProgram(ShaderAddress, instructions); - var plan = ShaderResourcePlan.Extract(program, stage, RequestHash, 0, UserDataCount); + var plan = ShaderResourcePlan.Extract(program, stage, RequestHash, 0, UserDataCount, + runtimeImageSwizzles: runtimeImageSwizzles); var userData = new uint[UserDataCount]; WriteDescriptor(userData, descriptorType, unifiedFormat, dstSelect); if (addressValues is not null) userData[18] = 1u << 26; @@ -183,6 +186,7 @@ public static bool TryCompile( PixelOutputs = stage == ShaderStage.Pixel ? [new Gen5PixelOutputBinding(0, 0, Gen5PixelOutputKind.Float)] : [], }; + inspect?.Invoke(request, snapshot); var compiled = Gen5MslTranslator.TryCompileProgram(request, out var result, out error); shader = compiled ? result : null; return compiled; diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalRuntimeImageSwizzleExecutionTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalRuntimeImageSwizzleExecutionTests.cs new file mode 100644 index 000000000..ae4d8a2e5 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalRuntimeImageSwizzleExecutionTests.cs @@ -0,0 +1,180 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.ShaderCompiler.Metal.Tests; + +/// +/// A store through a storage image whose destination select is shader data writes, bit for bit, +/// the texel an MSL module with the select baked in writes: every permutation of XYZW and a sample +/// of other selects, two dmasks, and common storage formats (8-bit unorm, 16-bit float with 32-bit +/// and D16 data, 32-bit uint and float). One module serves every select. The Metal twin of +/// RuntimeImageSwizzleDeviceTests (Vulkan). +/// +public sealed class MetalRuntimeImageSwizzleExecutionTests(ITestOutputHelper output) +{ + private const uint Size = 2; + + // X001, XYZ1, XXXX, 0000, 1111, ZYX0, XYXY. + private static readonly uint[] OtherSelects = [0x204, 0x3AC, 0x924, 0x000, 0x249, 0x12E, 0xB2C]; + + // Guest format, MTLPixelFormat, bytes per texel, D16 data. + public static TheoryData Formats() => new() + { + { 56, 70, 4, false }, // RGBA8Unorm + { 71, 115, 8, false }, // RGBA16Float + { 71, 115, 8, true }, + { 75, 123, 16, false }, // RGBA32Uint + { 77, 125, 16, false }, // RGBA32Float + }; + + [Theory] + [MemberData(nameof(Formats))] + public void RuntimeSelectStoresWriteTheBakedTexelBitForBit(uint guestFormat, uint pixelFormat, uint texelBytes, bool d16) + { + var device = DeviceGate(); + var selects = Permutations().Concat(OtherSelects).ToArray(); + var stores = 0; + foreach (var dmask in new[] { 0xFu, 0x5u }) + { + string? shared = null; + foreach (var select in selects) + { + var baked = Store(guestFormat, pixelFormat, texelBytes, d16, dmask, select, runtime: false, device); + var runtime = Store(guestFormat, pixelFormat, texelBytes, d16, dmask, select, runtime: true, device); + Assert.NotEqual(baked.Source, runtime.Source); + shared ??= runtime.Source; + Assert.Equal(shared, runtime.Source); + if (!device) + { + continue; + } + + Assert.Equal(Convert.ToHexString(baked.Texel), Convert.ToHexString(runtime.Texel)); + if (select == 0xF2E && dmask == 0xF) + { + // ZYXW: the X channel holds the third component. + Assert.Equal(Convert.ToHexString(Texel(guestFormat, dmask, select)), Convert.ToHexString(baked.Texel)); + } + + stores++; + } + } + + output.WriteLine($"Compared {stores} baked and runtime-select stores of format {guestFormat} (d16={d16})."); + } + + // The 24 orderings of X, Y, Z and W. + private static IEnumerable Permutations() + { + foreach (var x in new uint[] { 4, 5, 6, 7 }) + foreach (var y in new uint[] { 4, 5, 6, 7 }) + foreach (var z in new uint[] { 4, 5, 6, 7 }) + foreach (var w in new uint[] { 4, 5, 6, 7 }) + { + if (new[] { x, y, z, w }.Distinct().Count() == 4) + { + yield return x | (y << 3) | (z << 6) | (w << 9); + } + } + } + + // The data registers' values: distinct per component, exact in the format. + private static uint[] Data(uint guestFormat, bool d16) + { + if (d16) + { + return [Half(1.5f) | (Half(2.5f) << 16), Half(3.5f) | (Half(4.5f) << 16)]; + } + + return guestFormat switch + { + 56 => [Bits(0.2f), Bits(0.4f), Bits(0.6f), Bits(0.8f)], + 75 => [0x1111_1111, 0x2222_2222, 0x3333_3333, 0x4444_4444], + _ => [Bits(1.5f), Bits(2.5f), Bits(3.5f), Bits(4.5f)], + }; + + static uint Bits(float value) => BitConverter.SingleToUInt32Bits(value); + static uint Half(float value) => BitConverter.HalfToUInt16Bits((Half)value); + } + + // The bytes of the texel a store of every component through select writes. + private static byte[] Texel(uint guestFormat, uint dmask, uint select) + { + var bytes = new List(); + float[] floats = guestFormat == 56 ? [0.2f, 0.4f, 0.6f, 0.8f] : [1.5f, 2.5f, 3.5f, 4.5f]; + uint[] uints = [0x1111_1111, 0x2222_2222, 0x3333_3333, 0x4444_4444]; + for (var channel = 0; channel < 4; channel++) + { + var component = Gen5ShaderTranslator.GetImageStoreSourceIndex(select, dmask, channel); + switch (guestFormat) + { + case 56: + bytes.Add(component < 0 ? (byte)0 : (byte)Math.Round(floats[component] * 255)); + break; + case 71: + bytes.AddRange(BitConverter.GetBytes(component < 0 ? (ushort)0 : BitConverter.HalfToUInt16Bits((Half)floats[component]))); + break; + case 75: + bytes.AddRange(BitConverter.GetBytes(component < 0 ? 0u : uints[component])); + break; + default: + bytes.AddRange(BitConverter.GetBytes(component < 0 ? 0f : floats[component])); + break; + } + } + + return [.. bytes]; + } + + private static (byte[] Texel, string Source) Store(uint guestFormat, uint pixelFormat, uint texelBytes, bool d16, + uint dmask, uint select, bool runtime, bool device) + { + BindingLayout? layout = null; + ResourceSnapshot? snapshot = null; + ShaderCompileRequest? request = null; + Assert.True(Gen5ImageFixtures.TryCompile("ImageStore", Gen5ImageFixtures.ImageType2D, out var shader, out var error, + unifiedFormat: guestFormat, dstSelect: select, dmask: dmask, d16: d16, addressValues: [1, 0], + storeValues: Data(guestFormat, d16), runtimeImageSwizzles: runtime, + inspect: (compiled, resources) => (request, layout, snapshot) = (compiled, compiled.Bindings, resources)), error); + Assert.Equal(runtime ? 1u : 0u, layout!.StorageImageSwizzleCount); + if (!device) + { + return ([], shader!.Source); + } + + // The shader data the descriptor path writes (WriteStageShaderData): here only the store + // channel maps, which the fixture's compute kernel reads from push data. + var push = new byte[PushData.ByteSize]; + if (runtime) + { + Assert.True(layout.UsesPushData); + var shaderData = new uint[layout.ShaderDataDwordCount]; + RuntimeImageSwizzle.WriteStoreMaps(shaderData, layout, request!.Resources.Info.Images, snapshot!.Images); + Buffer.BlockCopy(shaderData, 0, push, (int)layout.PushDataStartDword * 4, shaderData.Length * 4); + } + + var initial = Enumerable.Repeat((byte)0xA5, (int)(Size * Size * texelBytes)).ToArray(); + var texture = MetalNative.CreateRawTexture(pixelFormat, Size, Size, texelBytes, initial); + Assert.True(MetalNative.TryCompileLibrary(shader!.Source, out var library, out error), error + shader.Source); + Assert.True(MetalNative.TryExecuteWithArgumentBuffer(library, shader.EntryPoint, new byte[16], push, + shader.ArgumentLayout!, 1, out _, out error, texture), error); + var bytes = MetalNative.ReadRawTexture(texture, Size, Size, texelBytes); + return (bytes.AsSpan((int)texelBytes, (int)texelBytes).ToArray(), shader.Source); + } + + private bool DeviceGate() + { + if (Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") != "1") + { + output.WriteLine("Texture execution requires the exclusive Metal device gate; only the sources are compared."); + return false; + } + + Assert.True(MetalNative.IsAvailable, "The required gate needs a Metal device."); + return true; + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslTranslationTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslTranslationTests.cs index d7440a13f..b1c44e1e3 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslTranslationTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslTranslationTests.cs @@ -987,7 +987,9 @@ public void ImageStoreAppliesInverseDescriptorSwizzle( uint dstSelect, string expectedComponents) { - var shader = CompileImageStore(dstSelect, dmask: 0xF); + // The select baked into the module (RuntimeImageSwizzle off); RuntimeSwizzleStorePicksTheChannelsFromShaderData + // is the shader-data twin. + var shader = CompileImageStore(dstSelect, dmask: 0xF, runtimeImageSwizzles: false); Assert.Contains( $".write(vec({expectedComponents}),", @@ -1000,7 +1002,8 @@ public void ImageStoreTreatsZeroDmaskAsX() { var shader = CompileImageStore( Gen5ShaderTranslator.IdentityImageDstSelect, - dmask: 0); + dmask: 0, + runtimeImageSwizzles: false); Assert.Contains( ".write(vec(as_type(v4), 0.0f, 0.0f, 0.0f),", @@ -1014,7 +1017,8 @@ public void ImageStoreMipAppliesInverseDescriptorSwizzle() var shader = CompileImageStore( 0x9F5u, dmask: 0xF, - opcode: "ImageStoreMip"); + opcode: "ImageStoreMip", + runtimeImageSwizzles: false); Assert.Contains( ".write(vec(as_type(v7), as_type(v4), as_type(v5), as_type(v6)),", @@ -1022,13 +1026,40 @@ public void ImageStoreMipAppliesInverseDescriptorSwizzle() StringComparison.Ordinal); } + // The shader-data twins of the tests above (RuntimeImageSwizzle on, upstream's default): the module keeps the + // identity select whatever the T# names, and a store reads its channel map from the image's slot of shader data + // (BindingLayout.StorageImageSwizzlesDword), as Gen5SpirvTranslator.RuntimeSwizzleStoreTexel does. + [Theory] + [InlineData(0xFACu, "ImageStore", 0xFu, 71u)] + [InlineData(0x9F5u, "ImageStore", 0xFu, 71u)] + [InlineData(0x9F5u, "ImageStoreMip", 0xFu, 71u)] + [InlineData(0xF2Eu, "ImageStore", 0xFu, 69u)] + [InlineData(0xFACu, "ImageStore", 0x0u, 71u)] + public void RuntimeSwizzleStorePicksTheChannelsFromShaderData(uint dstSelect, string opcode, uint dmask, uint unifiedFormat) + { + var shader = CompileImageStore(dstSelect, dmask, opcode, unifiedFormat, runtimeImageSwizzles: true, out var layout); + Assert.Equal(1u, layout.StorageImageSwizzleCount); + // One module for every select: the T#'s select does not reach the source. + var identity = CompileImageStore(0xFACu, dmask, opcode, unifiedFormat, runtimeImageSwizzles: true, out _); + Assert.Equal(identity.Source, shader.Source); + var kind = unifiedFormat == 69u ? "uint" : "float"; + var logical = dmask == 0 ? "uint4(v4, 0u, 0u, 0u)" : "uint4(v4, v5, v6, v7)"; + Assert.Contains($"= {logical};", shader.Source, StringComparison.Ordinal); + Assert.Contains($".write(vec<{kind}, 4>(", shader.Source, StringComparison.Ordinal); + for (var channel = 0u; channel < 4; channel++) + { + Assert.Contains($" >> {channel * 3}u) & 7u) ^ {channel}u;", shader.Source, StringComparison.Ordinal); + } + } + [Fact] public void UintImageStoreUsesUintTextureAndInverseDescriptorSwizzle() { var shader = CompileImageStore( 0xF2Eu, dmask: 0xF, - unifiedFormat: 69u); // FORMAT_16_16_16_16_UINT + unifiedFormat: 69u, // FORMAT_16_16_16_16_UINT + runtimeImageSwizzles: false); Assert.Contains( "texture2d", @@ -1549,7 +1580,17 @@ private static Gen5MslShader CompileImageStore( uint dstSelect, uint dmask, string opcode = "ImageStore", - uint unifiedFormat = 71u) + uint unifiedFormat = 71u, + bool? runtimeImageSwizzles = null) => + CompileImageStore(dstSelect, dmask, opcode, unifiedFormat, runtimeImageSwizzles, out _); + + private static Gen5MslShader CompileImageStore( + uint dstSelect, + uint dmask, + string opcode, + uint unifiedFormat, + bool? runtimeImageSwizzles, + out BindingLayout layout) { var control = new Gen5ImageControl( Dmask: dmask, @@ -1584,18 +1625,25 @@ private static Gen5MslShader CompileImageStore( userData[8] = 0x20; userData[9] = unifiedFormat << 20; userData[11] = (9u << 28) | dstSelect; - return CompileMaterialized(new Gen5ShaderProgram(0x1_0000_C000, [store, end]), userData); + return CompileMaterialized(new Gen5ShaderProgram(0x1_0000_C000, [store, end]), userData, out layout, + runtimeImageSwizzles: runtimeImageSwizzles); } + private static Gen5MslShader CompileMaterialized(Gen5ShaderProgram program, uint[] userData, - Gen5MslCodegenOptions? options = null) + Gen5MslCodegenOptions? options = null) => + CompileMaterialized(program, userData, out _, options); + + private static Gen5MslShader CompileMaterialized(Gen5ShaderProgram program, uint[] userData, out BindingLayout layout, + Gen5MslCodegenOptions? options = null, bool? runtimeImageSwizzles = null) { - var plan = ShaderResourcePlan.Extract(program, ShaderStage.Compute, 1, 0, (uint)userData.Length); + var plan = ShaderResourcePlan.Extract(program, ShaderStage.Compute, 1, 0, (uint)userData.Length, + runtimeImageSwizzles: runtimeImageSwizzles); var snapshot = new ResourceSnapshot(); var specialization = new ResourceSpecialization(); Assert.True(ResourceMaterializer.Materialize(plan, new ResourceRuntimeInputs { UserData = userData }, ref snapshot, ref specialization)); var resources = ResourceMaterializer.ApplyTo(plan, specialization); - var layout = BindingLayout.Allocate(resources.Info, + layout = BindingLayout.Allocate(resources.Info, BindingLayout.CollectUserDataRegisters(program, 0, (uint)userData.Length), false, ShaderCompileRequest.RequiresFlattenedTable(plan, resources), false); var request = new ShaderCompileRequest(plan, resources, layout); From 84c862a006c0c0abacca4ec890ea529a02a25e7a Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 22:41:45 +0000 Subject: [PATCH 065/134] [Docs] Document SHARPEMU_RUNTIME_IMAGE_SWIZZLE for the Metal build --- docs/macos/configuration.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 11916e9ad..7ba796a86 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -66,6 +66,7 @@ them for measurements or to isolate a problem. | --- | --- | --- | | `SHARPEMU_METAL_MESH_SHADERS` | on | `0` disables mesh pipelines for primitive-shader draws. | | `SHARPEMU_METAL_DRAW_PARAMETERS` | on | `0` turns off draw parameters in translated vertex programs. By default a vertex program's instance index counts from the draw's base instance, and when an indirect draw names a user-data register for its base vertex or start instance, the program counts its vertex index from the base vertex and stores both bases there (the command processor no longer writes those registers). `0` gives the program Metal's ids, which include both bases, and stores nothing. | +| `SHARPEMU_RUNTIME_IMAGE_SWIZZLE` | on | `0` bakes each storage image's destination select into the translated program, one program per select. By default a store reads the image's channel map from shader data, which the host writes from the bound descriptor. | | `SHARPEMU_METAL_MESHLETS` | on | `0` disables the meshlet cache. | | `SHARPEMU_METAL_V2_BINARY_ARCHIVE` | on | `0` disables the on-disk library and pipeline archives. | | `SHARPEMU_METAL_V2_BINARY_ARCHIVE_BUDGET_MB` | `8192` | Size bound of the archives on disk. | From 1a42bcc125e93eb8b3edd4c9cc1f64ae96b0deb0 Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 22:48:18 +0000 Subject: [PATCH 066/134] [Shader] Read lanes a fragment simdgroup never launched through the guest EXEC mask in MSL ShaderCompileRequest.GraphicsPartialSubgroupLanes (SHARPEMU_GRAPHICS_PARTIAL_LANES=1) now reaches the MSL translator: pixel DPP, DPP8, PERMLANE16 and V_READLANE reads of an absent lane read the reading lane's own value, and such a lane is active when the guest EXEC mask, kept unclamped beside the clamped one, has its bit. Off, the translation is unchanged. The Metal translation stamp names the switch when it is on. --- docs/macos/configuration.md | 1 + .../Gen5MslTranslator.Alu.cs | 57 ++++- .../Gen5MslTranslator.AluExtended.cs | 20 +- .../Gen5MslTranslator.PartialLanes.cs | 98 ++++++++ .../Gen5MslTranslator.Registers.cs | 1 + .../Gen5MslTranslator.cs | 14 ++ .../V2/MetalRenderHost.BufferWordVariants.cs | 4 +- .../Gen5ComputeFixtures.cs | 5 +- .../Gen5MslPartialLanesTests.cs | 221 ++++++++++++++++++ 9 files changed, 414 insertions(+), 7 deletions(-) create mode 100644 src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.PartialLanes.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslPartialLanesTests.cs diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 7ba796a86..23dec0b01 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -67,6 +67,7 @@ them for measurements or to isolate a problem. | `SHARPEMU_METAL_MESH_SHADERS` | on | `0` disables mesh pipelines for primitive-shader draws. | | `SHARPEMU_METAL_DRAW_PARAMETERS` | on | `0` turns off draw parameters in translated vertex programs. By default a vertex program's instance index counts from the draw's base instance, and when an indirect draw names a user-data register for its base vertex or start instance, the program counts its vertex index from the base vertex and stores both bases there (the command processor no longer writes those registers). `0` gives the program Metal's ids, which include both bases, and stores nothing. | | `SHARPEMU_RUNTIME_IMAGE_SWIZZLE` | on | `0` bakes each storage image's destination select into the translated program, one program per select. By default a store reads the image's channel map from shader data, which the host writes from the bound descriptor. | +| `SHARPEMU_GRAPHICS_PARTIAL_LANES` | off | `1` makes pixel-shader lane reads (DPP, DPP8, PERMLANE16, V_READLANE) of a lane the fragment simdgroup never launched read the reading lane's own value, and treats such a lane as active when the guest EXEC mask has its bit. Off by default, as upstream: it changes every pixel shader with cross-lane operations. | | `SHARPEMU_METAL_MESHLETS` | on | `0` disables the meshlet cache. | | `SHARPEMU_METAL_V2_BINARY_ARCHIVE` | on | `0` disables the on-disk library and pipeline archives. | | `SHARPEMU_METAL_V2_BINARY_ARCHIVE_BUDGET_MB` | `8192` | Size bound of the archives on disk. | diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Alu.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Alu.cs index 7f986e27e..9568edece 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Alu.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Alu.cs @@ -140,6 +140,14 @@ private bool TryEmitVectorAlu( } var lane = Temp("uint", $"({RawSource(instruction, 1)}) & 31u"); + if (HostSubgroupMayBePartial) + { + // The selected lane whatever its EXEC state; a lane the host never launched reads + // as the reading lane. + StoreScalar(instruction.Destinations[0].Value, ReadGraphicsLane(Temp("uint", value), lane)); + return true; + } + if (_stage == Gen5MslStage.Pixel && !IsSingleLaneStage) { // A fragment that was never launched has no thread to shuffle from @@ -1466,6 +1474,14 @@ private string ApplyDppSource(Gen5DppControl control, string value) var stored = Temp("uint", value); var (targetLane, inRange) = EmitDppSourceLane(control); var safeTarget = Temp("uint", $"(({inRange}) ? {targetLane} : sharpemu_lane) & 31u"); + if (HostSubgroupMayBePartial) + { + var read = ReadGraphicsLane(stored, safeTarget); + return control.FetchInactive + ? Temp("uint", $"({inRange}) ? {read} : 0u") + : Temp("uint", $"(({inRange}) && {IsGraphicsLaneUsable(safeTarget)}) ? {read} : 0u"); + } + var shuffled = Temp("uint", ShuffleLane(stored, safeTarget)); if (control.FetchInactive) { @@ -1485,6 +1501,12 @@ private string ApplyDpp8Source(Gen5Dpp8Control control, string value) "uint", $"({control.LaneSelectors}u >> ((sharpemu_lane & 7u) * 3u)) & 7u"); var targetLane = Temp("uint", $"((sharpemu_lane & 0xFFFFFFF8u) + {selector}) & 31u"); + if (HostSubgroupMayBePartial) + { + var read = ReadGraphicsLane(stored, targetLane); + return control.FetchInactive ? read : Temp("uint", $"{IsGraphicsLaneUsable(targetLane)} ? {read} : 0u"); + } + var shuffled = Temp("uint", ShuffleLane(stored, targetLane)); if (control.FetchInactive) { @@ -1516,6 +1538,10 @@ private string EmitDppWriteEnabled(Gen5DppControl control) ? "true" : control.FetchInactive ? inRange + // A graphics source lane the host never launched is disabled unless whole-wave code + // turned it on in the guest mask (HostSubgroupMayBePartial). + : HostSubgroupMayBePartial + ? $"({inRange}) && {IsGraphicsLaneUsable(Temp("uint", $"(({inRange}) ? {targetLane} : sharpemu_lane) & 31u"))}" // The ballot sits in its own statement: under the && only some lanes would run it. : $"({inRange}) && {Temp("bool", LaneActiveExpression(Temp("uint", $"(({inRange}) ? {targetLane} : sharpemu_lane) & 31u")))}"; return Temp("bool", $"({rowEnabled}) && ({bankEnabled}) && ({sourceAllows})"); @@ -1920,6 +1946,12 @@ private void EmitBallotStore(uint loRegister, string condition) Line($"s[{hiRegister}] = 0u;"); } + if (loRegister == ExecLoRegister) + { + // A compare's EXEC holds only lanes that ran it. + RecordGuestExec64($"(ulong)s[{ExecLoRegister}]"); + } + return; } @@ -1981,8 +2013,19 @@ private string EmitPermlane16(Gen5ShaderInstruction instruction, bool exchangeRo ? "((sharpemu_lane & 0xFFFFFFF0u) ^ 16u)" : "(sharpemu_lane & 0xFFFFFFF0u)"; var targetLane = Temp("uint", $"({rowBase} + {selector}) & 31u"); - var shuffled = Temp("uint", ShuffleLane(value, targetLane)); var fetchInactive = (control.OperandSelect & 1) != 0; + if (HostSubgroupMayBePartial) + { + // ISA: a disabled source lane gives zero with BOUND_CTRL (OP_SEL[1]) set and keeps the old + // destination with it clear. + var read = ReadGraphicsLane(value, targetLane); + return fetchInactive + ? read + : Temp("uint", $"{IsGraphicsLaneUsable(targetLane)} ? {read} : " + + $"{((control.OperandSelect & 2) != 0 ? "0u" : $"v[{DestinationVector(instruction)}]")}"); + } + + var shuffled = Temp("uint", ShuffleLane(value, targetLane)); if (fetchInactive) { return shuffled; @@ -2266,6 +2309,12 @@ private bool TryEmitScalarAlu( return false; } + if (HostSubgroupMayBePartial) + { + combined = Temp("uint", combined); + RecordGuestExecLow(combined); + } + var mask = Temp("uint", ClampExecToLanes(combined)); StoreScalar(destination, oldExec); Line($"s[{ExecLoRegister}] = {mask};"); @@ -2727,6 +2776,12 @@ private bool TryEmitScalar64( return false; } + if (HostSubgroupMayBePartial) + { + combined = Temp("ulong", combined); + RecordGuestExec64(combined); + } + var mask = Temp("ulong", ClampExecToLanes64(combined)); StoreScalar64(destination, oldExec); Line($"s[{ExecLoRegister}] = (uint){mask};"); diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.AluExtended.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.AluExtended.cs index 73b544d08..6d770ad06 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.AluExtended.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.AluExtended.cs @@ -856,9 +856,14 @@ private void EmitWriteExec(Gen5ShaderInstruction instruction, uint destination) { var source = Temp("ulong", RawSource64(instruction, 0)); var oldExec = Temp("ulong", Scalar64Expression(ExecLoRegister)); - var mask = Temp( - "ulong", - ClampExecToLanes64(andn1 ? $"(~{source} & {oldExec})" : $"({source} & ~{oldExec})")); + var written = andn1 ? $"(~{source} & {oldExec})" : $"({source} & ~{oldExec})"; + if (HostSubgroupMayBePartial) + { + written = Temp("ulong", written); + RecordGuestExec64(written); + } + + var mask = Temp("ulong", ClampExecToLanes64(written)); Line($"s[{ExecLoRegister}] = (uint){mask};"); Line(IsNarrowWave64 ? $"s[{ExecHiRegister}] = 0u;" @@ -871,7 +876,14 @@ private void EmitWriteExec(Gen5ShaderInstruction instruction, uint destination) var left = Temp("uint", RawSource(instruction, 0)); var old = Temp("uint", $"s[{ExecLoRegister}]"); - var narrow = Temp("uint", ClampExecToLanes(andn1 ? $"(~{left} & {old})" : $"({left} & ~{old})")); + var writtenLow = andn1 ? $"(~{left} & {old})" : $"({left} & ~{old})"; + if (HostSubgroupMayBePartial) + { + writtenLow = Temp("uint", writtenLow); + RecordGuestExecLow(writtenLow); + } + + var narrow = Temp("uint", ClampExecToLanes(writtenLow)); Line($"s[{ExecLoRegister}] = {narrow};"); Line($"s[{ExecHiRegister}] = 0u;"); Line($"exec = (({narrow} >> sharpemu_lane) & 1u) != 0u;"); diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.PartialLanes.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.PartialLanes.cs new file mode 100644 index 000000000..d9566096b --- /dev/null +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.PartialLanes.cs @@ -0,0 +1,98 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.ShaderCompiler.Metal; + +public static partial class Gen5MslTranslator +{ + // ShaderCompileRequest.GraphicsPartialSubgroupLanes (SHARPEMU_GRAPHICS_PARTIAL_LANES=1), as the SPIR-V + // translator lowers it (Gen5SpirvTranslator HostSubgroupMayBePartial, ReadGraphicsLane). A fragment + // simdgroup can be partly empty: the lanes past the quads the rasterizer packed into it were never + // launched. The PS5 wave behind it still has those lanes, dead but with registers, and whole-wave code + // (S_OR_SAVEEXEC of EXEC and the like) turns them on. A shuffle from a thread that does not exist is + // undefined, so DPP, DPP8, PERMLANE16 and V_READLANE reads of such a lane read the reading lane's own + // value, and the lane counts as active when the guest EXEC mask has its bit. The pixel stage clamps + // EXEC to the running lanes (ClampExecToLanes), so the guest mask, dead lanes' bits included, is kept + // beside it in sharpemu_guest_exec. Only the pixel stage has real lanes that can be absent: the vertex + // stage runs one lane per thread, and compute and mesh simdgroups are full. + private sealed partial class CompilationContext + { + private const string GuestExecName = "sharpemu_guest_exec"; + + private bool HostSubgroupMayBePartial => + _request.GraphicsPartialSubgroupLanes && _stage == Gen5MslStage.Pixel && !IsSingleLaneStage && !IsWave64; + + private void DeclareGuestExec(System.Text.StringBuilder source) + { + if (HostSubgroupMayBePartial) + { + source.AppendLine($" ulong {GuestExecName} = 0ul;"); + } + } + + // The entry mask: the launched lanes, as EXEC starts. + private void InitializeGuestExec(System.Text.StringBuilder source) + { + if (HostSubgroupMayBePartial) + { + source.AppendLine($" {GuestExecName} = (ulong)sharpemu_ballot(true);"); + } + } + + // A new EXEC low dword before the clamp to the running lanes. + private void RecordGuestExecLow(string unclamped) + { + if (HostSubgroupMayBePartial) + { + Line($"{GuestExecName} = ({GuestExecName} & 0xFFFFFFFF00000000ul) | (ulong)({unclamped});"); + } + } + + private void RecordGuestExecHigh(string value) + { + if (HostSubgroupMayBePartial) + { + Line($"{GuestExecName} = ({GuestExecName} & 0xFFFFFFFFul) | ((ulong)({value}) << 32);"); + } + } + + private void RecordGuestExec64(string unclamped) + { + if (HostSubgroupMayBePartial) + { + Line($"{GuestExecName} = {unclamped};"); + } + } + + // The host thread of a guest lane: its position in the simdgroup. The upper half of a guest wave64 + // has no threads and maps onto the same positions, as in the SPIR-V lowering. + private string GraphicsHostLane(string guestLane) => Temp("uint", $"({guestLane}) & 31u"); + + private string IsHostLanePresent(string hostLane) => + Temp("bool", $"((sharpemu_ballot(true) >> {hostLane}) & 1u) != 0u"); + + private string IsGuestLaneExecSet(string guestLane) => + Temp("bool", $"(({GuestExecName} >> (({guestLane}) & {(_waveLaneCount == 64 ? 63u : 31u)}u)) & 1ul) != 0ul"); + + // A guest lane's register whatever its EXEC state; a lane that was never launched reads as the + // reading lane's own value, which keeps the min/max/and/or reductions whole-wave code runs across + // dead lanes exact. + private string ReadGraphicsLane(string value, string guestLane) + { + var hostLane = GraphicsHostLane(guestLane); + var present = IsHostLanePresent(hostLane); + return Temp("uint", $"simd_shuffle({value}, (ushort)({present} ? {hostLane} : sharpemu_lane))"); + } + + // The fetch-inactive-off test of a source lane: its EXEC bit, from the running lanes' ballot for a + // launched lane and from the guest mask for one the host never launched. + private string IsGraphicsLaneUsable(string guestLane) + { + var hostLane = GraphicsHostLane(guestLane); + var present = IsHostLanePresent(hostLane); + var active = Temp("bool", $"((sharpemu_ballot(exec) >> {hostLane}) & 1u) != 0u"); + var guest = IsGuestLaneExecSet(guestLane); + return Temp("bool", $"{present} ? {active} : {guest}"); + } + } +} diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Registers.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Registers.cs index c2b1f7495..1fbd62fef 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Registers.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Registers.cs @@ -770,6 +770,7 @@ private void EmitRegisterFile(StringBuilder source, RegisterPlan plan, bool stru } source.AppendLine(" bool exec = true;"); + DeclareGuestExec(source); if (_usesPixelValidMask) { source.AppendLine(" bool pixel_valid_mask_active = true;"); diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs index d90445dca..981198ad8 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs @@ -1654,6 +1654,7 @@ private void EmitRegisterFile(StringBuilder source) source.AppendLine($" uint s[{ScalarRegisterFileCount}] = {{}};"); source.AppendLine($" uint v[{VectorRegisterFileCount}] = {{}};"); source.AppendLine(" bool exec = true;"); + DeclareGuestExec(source); if (_usesPixelValidMask) { source.AppendLine(" bool pixel_valid_mask_active = true;"); @@ -1751,6 +1752,7 @@ private void EmitInitialState(StringBuilder source) { source.AppendLine($" s[{ExecLoRegister}] = sharpemu_ballot(true);"); source.AppendLine($" s[{ExecHiRegister}] = 0u;"); + InitializeGuestExec(source); } } @@ -4807,6 +4809,12 @@ private void StoreScalar(uint register, string expression) case ExecLoRegister: { + if (HostSubgroupMayBePartial) + { + expression = Temp("uint", expression); + RecordGuestExecLow(expression); + } + var value = Temp("uint", ClampExecToLanes(expression)); Line($"s[{ExecLoRegister}] = {value};"); Line($"exec = {LowHalfWriteBit(value, "exec", ScalarExpression(ExecHiRegister))};"); @@ -4816,6 +4824,12 @@ private void StoreScalar(uint register, string expression) case VccHiRegister: case ExecHiRegister: { + if (register == ExecHiRegister && HostSubgroupMayBePartial) + { + expression = Temp("uint", expression); + RecordGuestExecHigh(expression); + } + var value = Temp("uint", register == ExecHiRegister && (ClampsExecToLanes || IsNarrowWave64) ? "0u" : expression); Line($"s[{register}] = {value};"); if (IsWave64) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs index 87e8d5fbe..b5334fd60 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs @@ -78,7 +78,9 @@ internal sealed partial class MetalRenderHost internal static string TranslationSwitchStamp => $"portable={(PortableBuffers ? 1 : 0)},buffer_word_constants={(BufferWordConstants ? 1 : 0)}," + $"draw_parameters={(DrawParameters ? 1 : 0)}," + - $"runtime_image_swizzle={(RuntimeImageSwizzle.Enabled ? 1 : 0)}"; + $"runtime_image_swizzle={(RuntimeImageSwizzle.Enabled ? 1 : 0)}" + + // ShaderCompileRequest.GraphicsPartialSubgroupLanes takes its default from this variable. + (Environment.GetEnvironmentVariable("SHARPEMU_GRAPHICS_PARTIAL_LANES") == "1" ? ",graphics_partial_lanes=1" : ""); /// Variants one pipeline entry keeps; a draw of another layout past them draws generic. internal const int MaxBufferWordVariantsPerPipeline = 16; diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ComputeFixtures.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ComputeFixtures.cs index 56dbabb58..b563a170d 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ComputeFixtures.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ComputeFixtures.cs @@ -887,7 +887,7 @@ public static ShaderCompileRequest RequestOrThrow(Gen5ShaderProgram program, Sha uint floatMode = ShaderCompileRequest.DefaultFloatMode, bool dx10Clamp = true, bool pixelGuestWave32 = false, uint meshPerVertexParameterMask = 0, IReadOnlyList? vertexInterpolants = null, Gen5TessellationLaunch? tessellation = null, bool pixelEarlyDepth = false, bool supportsDrawParameters = false, - int baseVertexUserData = -1, int startInstanceUserData = -1) + int baseVertexUserData = -1, int startInstanceUserData = -1, bool? graphicsPartialSubgroupLanes = null) { var plan = ShaderResourcePlan.Extract(program, stage, RequestHash, userDataBase, UserDataCount, excludedUserDataRegisters: excludedUserDataRegisters); @@ -934,6 +934,9 @@ public static ShaderCompileRequest RequestOrThrow(Gen5ShaderProgram program, Sha SupportsDrawParameters = supportsDrawParameters, BaseVertexUserData = baseVertexUserData, StartInstanceUserData = startInstanceUserData, + // Unset keeps the request's own default (SHARPEMU_GRAPHICS_PARTIAL_LANES). + GraphicsPartialSubgroupLanes = graphicsPartialSubgroupLanes ?? + new ShaderCompileRequest(plan, resources, layout).GraphicsPartialSubgroupLanes, }; } diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslPartialLanesTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslPartialLanesTests.cs new file mode 100644 index 000000000..b2f7734d3 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslPartialLanesTests.cs @@ -0,0 +1,221 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.ShaderCompiler.Metal.Tests; + +/// +/// ShaderCompileRequest.GraphicsPartialSubgroupLanes (SHARPEMU_GRAPHICS_PARTIAL_LANES=1) in MSL, as the SPIR-V +/// translator lowers it: a pixel lane read (DPP, DPP8, PERMLANE16, V_READLANE) of a lane the fragment simdgroup +/// never launched reads the reading lane's own value, and such a lane counts as active when the guest EXEC mask +/// has its bit (whole-wave code turned it on). Off, the translation is the one it always was. +/// +public sealed class Gen5MslPartialLanesTests(ITestOutputHelper output) +{ + private const uint TargetSize = 8; + private const uint Untouched = 0xEE; + + // Exported: r = lane | row_shl:4 after EXEC is restored << 8 | readlane 31 << 16 + // g = row_shl:4 with EXEC -1 (bound_ctrl clear) + // b = dpp8:[7,7,7,7,7,7,7,7] with EXEC -1 + // a = entry EXEC + private static readonly uint[] PartialLaneWords = + [ + 0xD7650000, 0x000100C1, // v_mbcnt_lo_u32_b32 v0, -1, 0 lane + 0xD5430001, 0x021D0700, // v_mad_u32_u24 v1, v0, 3, 7 value + 0xBE84037E, // s_mov_b32 s4, exec_lo + 0x7E0602FF, 0x000000EE, // v_mov_b32 v3, 0xee + 0x7E0802FF, 0x000000EE, // v_mov_b32 v4, 0xee + 0xBEFE03C1, // s_mov_b32 exec_lo, -1 lanes that may not exist + 0x7E0602FA, 0xFF010401, // v_mov_b32_dpp v3, v1 row_shl:4 + 0x7E0A02E9, 0xFFFFFF01, // v_mov_b32_dpp v5, v1 dpp8:[7,7,7,7,7,7,7,7] + 0xBEFE0304, // s_mov_b32 exec_lo, s4 + 0x7E0802FA, 0xFF010401, // v_mov_b32_dpp v4, v1 row_shl:4 + 0xD7600000, 0x00013F01, // v_readlane_b32 s0, v1, 31 + 0x7E0C0200, // v_mov_b32 v6, s0 + 0xD76F000B, 0x04011104, // v_lshl_or_b32 v11, v4, 8, v0 + 0xD76F000B, 0x042D2106, // v_lshl_or_b32 v11, v6, 16, v11 + 0x7E180204, // v_mov_b32 v12, s4 + 0xF800180F, 0x0C05030B, // exp mrt0 v11, v3, v5, v12 done vm + 0xBF810000, // s_endpgm + ]; + + private const string VertexSource = """ + + struct SharpEmuPartialLaneVertex + { + float4 position [[position]]; + }; + + vertex SharpEmuPartialLaneVertex sharpemu_partial_lane_vs( + uint id [[vertex_id]], + constant float2* positions [[buffer(0)]]) + { + SharpEmuPartialLaneVertex vertex_out; + vertex_out.position = float4(positions[id], 0.0f, 1.0f); + return vertex_out; + } + """; + + [Fact] + public void OffTheTranslationIsUnchanged() + { + var unset = Compile(Words(PartialLaneWords), ShaderStage.Pixel, null).Source; + Assert.Equal(unset, Compile(Words(PartialLaneWords), ShaderStage.Pixel, false).Source); + Assert.DoesNotContain("sharpemu_guest_exec", unset, StringComparison.Ordinal); + // The prelude defines the nearest-present-lane helper; off, V_READLANE calls it. + Assert.Equal(2, Occurrences(unset, "sharpemu_present_lane(")); + + var on = Compile(Words(PartialLaneWords), ShaderStage.Pixel, true).Source; + Assert.NotEqual(unset, on); + Assert.Contains("ulong sharpemu_guest_exec = 0ul;", on, StringComparison.Ordinal); + Assert.Equal(1, Occurrences(on, "sharpemu_present_lane(")); + } + + // The vertex stage runs one lane per thread and a compute simdgroup is full: no lane is absent. + [Fact] + public void OnlyThePixelStageReadsAbsentLanes() + { + var compute = Words(PartialLaneWords[..^4].Concat([0xBF810000u]).ToArray()); + Assert.Equal( + Compile(compute, ShaderStage.Compute, false).Source, + Compile(compute, ShaderStage.Compute, true).Source); + } + + [Fact] + public void ALaneTheSimdgroupNeverLaunchedReadsAsTheReader() + { + if (SkipWithoutMetalDevice("the partial-lane execution test")) return; + + // Covers only the center of pixel (1,1): its quad runs, the rest of the simdgroup does not. + var triangle = new[] { -0.8f, 0.8f, -0.4f, 0.8f, -0.8f, 0.4f }; + var on = Render(true, triangle); + var off = Render(false, triangle); + + var (r, g, b, running) = Texel(on, 1, 1); + var lane = r & 31u; + output.WriteLine($"pixel (1,1) ran on lane {lane}, wave lanes 0x{running:X8}"); + Assert.Equal(3u, lane & 3u); + Assert.Equal(Texel(off, 1, 1).A, running); + bool Runs(uint other) => ((running >> (int)other) & 1u) != 0; + + // row_shl:4 under EXEC -1: a source in the row that never ran is on in the guest mask. + var inRow = (lane & 15u) < 12u; + var target = lane + 4u; + var expectedShift = !inRow ? Untouched : Runs(target) ? Value(target) : Value(lane); + Assert.Equal(expectedShift, g); + // Off: the source is not a running lane, so it is EXEC-clear and the lane keeps v3. + Assert.Equal(!inRow ? Untouched : Runs(target) ? Value(target) : Untouched, Texel(off, 1, 1).G); + + // dpp8 lane 7 of the group of eight under EXEC -1; off, an absent source reads zero. + var group = (lane & ~7u) + 7u; + Assert.Equal(Runs(group) ? Value(group) : Value(lane), b); + Assert.Equal(Runs(group) ? Value(group) : 0u, Texel(off, 1, 1).B); + + // EXEC restored: the absent source's guest bit is clear, so v4 is kept in both translations. + var expectedRestored = !inRow ? Untouched : Runs(target) ? Value(target) : Untouched; + Assert.Equal(expectedRestored, (r >> 8) & 0xFFu); + Assert.Equal(expectedRestored, (Texel(off, 1, 1).R >> 8) & 0xFFu); + + // V_READLANE of lane 31: an absent lane reads as the reader. + Assert.Equal(Runs(31) ? Value(31) : Value(lane), (r >> 16) & 0xFFu); + } + + // V_PERMLANE16 with and without FI (OP_SEL[0]) takes the same lane reads; Metal accepts both translations. + [Fact] + public void Permlane16ReadsThroughTheGuestMask() + { + uint[] words = + [ + 0xD7650000, 0x000100C1, // v_mbcnt_lo_u32_b32 v0, -1, 0 + 0xD5430001, 0x021D0700, // v_mad_u32_u24 v1, v0, 3, 7 + 0xBE8003FF, 0x76543210, // s_mov_b32 s0, 0x76543210 + 0xBE8103FF, 0xFEDCBA98, // s_mov_b32 s1, 0xfedcba98 + 0x7E0602FF, 0x000000EE, // v_mov_b32 v3, 0xee + 0x7E0802FF, 0x000000EE, // v_mov_b32 v4, 0xee + 0xD7770003, 0x00040101, // v_permlane16_b32 v3, v1, s0, s1 + 0xD7770804, 0x00040101, // v_permlane16_b32 v4, v1, s0, s1 op_sel:[1,0] FI + 0xF800180F, 0x04030100, // exp mrt0 v0, v1, v3, v4 done vm + 0xBF810000, // s_endpgm + ]; + var off = Compile(Words(words), ShaderStage.Pixel, false).Source; + var on = Compile(Words(words), ShaderStage.Pixel, true).Source; + Assert.NotEqual(off, on); + Assert.Contains("sharpemu_guest_exec >> ", on, StringComparison.Ordinal); + if (SkipWithoutMetalDevice("the permlane16 compile")) return; + + Assert.True(MetalNative.TryCompileLibrary(on + VertexSource, out _, out var error), $"{error}\n{on}"); + Assert.True(MetalNative.TryCompileLibrary(off + VertexSource, out _, out error), error); + } + + private static uint Value(uint lane) => (3 * lane) + 7; + + private static int Occurrences(string source, string text) => + (source.Length - source.Replace(text, string.Empty, StringComparison.Ordinal).Length) / text.Length; + + private static Gen5ShaderProgram Words(uint[] words) => + Gen5ComputeFixtures.DecodeOrThrow(new Gen5ComputeFixture("pixel-partial-lanes", words, 0, 0)); + + private static Gen5MslShader Compile(Gen5ShaderProgram program, ShaderStage stage, bool? partialLanes) + { + Gen5PixelOutputBinding[] outputs = stage == ShaderStage.Pixel + ? [new Gen5PixelOutputBinding(0, 0, Gen5PixelOutputKind.Uint)] + : []; + var request = Gen5ComputeFixtures.RequestOrThrow(program, stage, + pixelOutputs: outputs, + enableGraphicsSubgroupOperations: true, + graphicsPartialSubgroupLanes: partialLanes); + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error), error); + return shader; + } + + private byte[] Render(bool partialLanes, float[] triangle) + { + var shader = Compile(Words(PartialLaneWords), ShaderStage.Pixel, partialLanes); + Assert.True( + MetalNative.TryCompileLibrary(shader.Source + VertexSource, out var library, out var error), + $"Metal rejected the partial-lane MSL: {error}\n{shader.Source}"); + + var positions = new byte[triangle.Length * sizeof(float)]; + Buffer.BlockCopy(triangle, 0, positions, 0, positions.Length); + var resources = new byte[Math.Max(shader.ArgumentLayout?.ByteSize ?? 0, 256)]; + Assert.True( + MetalNative.TryRenderTriangles( + library, + "sharpemu_partial_lane_vs", + shader.EntryPoint, + [(positions, 0)], + [(resources, (uint)Gen5MslArgumentLayout.ResourcesBufferIndex)], + 3, + TargetSize, + TargetSize, + MetalNative.Rgba32UintPixelFormat, + out var texels, + out error), + error); + return texels; + } + + private static (uint R, uint G, uint B, uint A) Texel(byte[] texels, uint x, uint y) + { + var offset = (int)(((y * TargetSize) + x) * 16); + return ( + BitConverter.ToUInt32(texels, offset), + BitConverter.ToUInt32(texels, offset + 4), + BitConverter.ToUInt32(texels, offset + 8), + BitConverter.ToUInt32(texels, offset + 12)); + } + + private bool SkipWithoutMetalDevice(string activity) + { + if (MetalNative.IsAvailable) return false; + Assert.False( + OperatingSystem.IsMacOS() && Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") == "1", + $"The required gate cannot run {activity} without a Metal device."); + output.WriteLine($"No Metal device on this host; {activity} skipped."); + return true; + } +} From 5b1d80960d5623086c02e90aa46a09d513fd1f6e Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 22:49:29 +0000 Subject: [PATCH 067/134] [Metal] Post a bounded word copy as a command-processor store at its stream position The executor resolves a Metal dispatch on the worker at its stream position, so a bounded word copy whose source is final and whose destination no image or metadata owns is recorded as an ordered command-processor write of the replicated words instead of a dispatch (IRenderHost.TryPostWordCopy, upstream 61e9ec8f3/5d4937c46). Identical and verified copies stay with the host kernel copy check. SHARPEMU_POSTED_WORD_COPY=0 runs them as dispatches. --- .../V2/MetalRenderHost.KernelFills.cs | 2 +- .../V2/MetalRenderHost.PostedWordCopy.cs | 159 ++++++++++++++++++ .../Scenes/PostedWordCopySceneTests.cs | 81 +++++++++ 3 files changed, 241 insertions(+), 1 deletion(-) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.PostedWordCopy.cs create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/Scenes/PostedWordCopySceneTests.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.KernelFills.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.KernelFills.cs index 41740b50f..73ae83703 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.KernelFills.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.KernelFills.cs @@ -217,7 +217,7 @@ internal string TakeKernelFillCounters() } } - return builder.Append(']').Append(TakeHostKernelCopyCounters()).ToString(); + return builder.Append(']').Append(TakeHostKernelCopyCounters()).Append(TakePostedWordCopyCounters()).ToString(); } // Whether a refused kernel's result is already in memory: every destination word holds diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.PostedWordCopy.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.PostedWordCopy.cs new file mode 100644 index 000000000..343ffac5e --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.PostedWordCopy.cs @@ -0,0 +1,159 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Rendering; + +namespace SharpEmu.Gpu.Metal.V2; + +// A bounded word copy kernel (dst[i] = src[i % sourceWords]) posted as a command-processor store at its +// stream position instead of running as a dispatch (IRenderHost.TryPostWordCopy, upstream 61e9ec8f3 and +// 5d4937c46; the Vulkan host posts it in VulkanVideoPresenter.KernelWrites.cs PostWordCopy). +// +// Where it runs: the Metal translation resolves whole dispatches on the worker at their stream position +// (CommandStreamTranslation._defersWholeWork), so the executor asks here with everything recorded before +// the dispatch already recorded and nothing after it. The source is read now, which is what the kernel +// would read only if no recorded GPU work still writes it; the replicated bytes are then recorded as a +// command-processor write (TryEncodeCommandProcessorWrite): an ordered copy from staging where the stream +// has reached, after every write recorded before it, with parse-time reads answered from the +// command-processor overlay until it lands. A store the GPU cannot make (no window, no staging, a label +// still owed by a completion) would land only when the submission completes, after later GPU readers, so +// the copy is refused then and runs as the dispatch it is. +// +// Refusals, in the Vulkan host's order (KernelWritePolicy.Check, then the input read): +// - unsupported: a null, unaligned, empty, overlapping or overflowing range, or one over 16 MiB +// (GuestBufferCache.MaxHostCopyWords); +// - thread: asked on the command thread rather than the worker; +// - image / metadata: an image may own the destination's pages, or surface metadata lies there (a +// store into either needs the image cache's bookkeeping, which the dispatch's storage binding does); +// - input: the source is not final (a recorded GPU write, a GPU-modified image, pending +// command-processor or label bytes), is surface metadata, or cannot be read; +// - encode: the store cannot be recorded on the GPU at this point; +// - host_kernel_copy: the Metal host's own kernel copy check takes it (an identical copy is consumed with +// nothing written; under verify the copy runs as its dispatch). +// SHARPEMU_POSTED_WORD_COPY=0 (RenderExecutor) turns it off for every host. +internal sealed partial class MetalRenderHost +{ + private const ulong MaxPostedCopyWords = 4 * 1024 * 1024; + + internal enum PostedWordCopyRefusal : byte + { + None, + Unsupported, + Thread, + Image, + Metadata, + Input, + Encode, + HostKernelCopy, + } + + private static readonly string[] PostedWordCopyRefusalNames = ["posted", "unsupported", "thread", "image", "metadata", "input", "encode", "host_kernel_copy"]; + + private readonly long[] _postedWordCopies = new long[PostedWordCopyRefusalNames.Length]; + + /// Posted word copies (index 0) and refusals by reason, since the host started. + internal long PostedWordCopies(PostedWordCopyRefusal outcome) => Interlocked.Read(ref _postedWordCopies[(int)outcome]); + + public bool TryPostWordCopy(ulong destination, ulong source, ulong sourceWords, ulong words) + { + var outcome = PostWordCopy(destination, source, sourceWords, words); + Interlocked.Increment(ref _postedWordCopies[(int)outcome]); + return outcome == PostedWordCopyRefusal.None; + } + + private PostedWordCopyRefusal PostWordCopy(ulong destination, ulong source, ulong sourceWords, ulong words) + { + if (destination == 0 || source == 0 || sourceWords == 0 || words == 0 || ((destination | source) & 3) != 0 || + words > MaxPostedCopyWords || sourceWords > MaxPostedCopyWords) + { + return PostedWordCopyRefusal.Unsupported; + } + + var size = words * sizeof(uint); + var sourceSize = Math.Min(sourceWords, words) * sizeof(uint); + if (size > ulong.MaxValue - destination || sourceSize > ulong.MaxValue - source || + (source < destination + size && destination < source + sourceSize)) + { + return PostedWordCopyRefusal.Unsupported; + } + + if (OnCommandThread) + { + return PostedWordCopyRefusal.Thread; + } + + if (_imageCache.MayOwn(destination, size)) + { + return PostedWordCopyRefusal.Image; + } + + if (_imageCache.OverlapsSurfaceMetadata(destination, size)) + { + return PostedWordCopyRefusal.Metadata; + } + + // Draws deferred before the dispatch record their writes first, so the source check sees them. + DrainDraws(); + + // The host's own handling of a refused copy kernel comes first (SHARPEMU_METAL_V2_HOST_KERNEL_COPY): a + // copy whose destination already holds its result is consumed there with nothing written, which a + // posted store cannot beat, and under verify the copy runs so both checks see it. + if (HostKernelCopyMode == MetalHostKernelCopyMode.Verify) + { + return PostedWordCopyRefusal.HostKernelCopy; + } + + if (HostKernelCopyMode == MetalHostKernelCopyMode.Identical && + EvaluateKernelCopyCore(destination, words, source, sourceWords, default) == KernelCopyOutcome.Identical) + { + return PostedWordCopyRefusal.HostKernelCopy; + } + + if (_imageCache.OverlapsSurfaceMetadata(source, sourceSize) || + !IsCopySourceFinal(source, sourceSize, CompletedSerial) || + (_labelOverlay.Count != 0 && + _labelOverlay.Coverage(source, sourceSize, _completedSerialReader ??= () => CompletedSerial) != MetalOverlayCoverage.None)) + { + return PostedWordCopyRefusal.Input; + } + + var data = GC.AllocateUninitializedArray((int)size); + if (!_memory.TryRead(source, data.AsSpan(0, (int)sourceSize))) + { + return PostedWordCopyRefusal.Input; + } + + for (var filled = (int)sourceSize; filled < data.Length;) + { + var count = Math.Min(filled, data.Length - filled); + data.AsSpan(0, count).CopyTo(data.AsSpan(filled)); + filled += count; + } + + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) + { + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteGpuWrite(destination, size, SharpEmu.HLE.GpuMemory.OverlapWrite.CpWrite); + } + + if (!TryEncodeCommandProcessorWrite(destination, data, "word copy", causal: true)) + { + return PostedWordCopyRefusal.Encode; + } + + Interlocked.Increment(ref _gpuTimedCommandProcessorWrites); + return PostedWordCopyRefusal.None; + } + + /// The posted word copy fields of the CHURN line; resets them. + private string TakePostedWordCopyCounters() + { + var text = new System.Text.StringBuilder(" word_copy=["); + for (var index = 0; index < PostedWordCopyRefusalNames.Length; index++) + { + text.Append(index == 0 ? string.Empty : ",").Append(PostedWordCopyRefusalNames[index]).Append('=') + .Append(Interlocked.Exchange(ref _postedWordCopies[index], 0)); + } + + return text.Append(']').ToString(); + } +} diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/PostedWordCopySceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/PostedWordCopySceneTests.cs new file mode 100644 index 000000000..90bd6db24 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/PostedWordCopySceneTests.cs @@ -0,0 +1,81 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.Rendering; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests.Scenes; + +/// +/// IRenderHost.TryPostWordCopy on Metal (upstream 61e9ec8f3/5d4937c46): the executor, resolving a bounded word copy +/// on the worker at its stream position, hands the copy to the host as a command-processor store and drops the +/// dispatch. The store lands in stream order with the writes around it, and reads before it lands see it. +/// +public sealed class PostedWordCopySceneTests(ITestOutputHelper output) : SceneTestBase(output) +{ + private const int SourceWords = 4; + private const int Words = 1024; + + private static uint[] Replicated(uint[] source, int words) => + Enumerable.Range(0, words).Select(word => source[word % source.Length]).ToArray(); + + private static uint[] Words32(byte[] bytes) => + Enumerable.Range(0, bytes.Length / 4).Select(word => BitConverter.ToUInt32(bytes, word * 4)).ToArray(); + + [Fact] + public void APostedCopyLandsInStreamOrderBetweenTheStoresAroundIt() + { + using var rig = CreateRig(); + if (rig is null) return; + var host = rig.Host; + var source = rig.Memory.Allocate(SourceWords * 4); + var destination = rig.Memory.Allocate(Words * 4); + uint[] pattern = [0x11111111, 0x22222222, 0x33333333, 0x44444444]; + rig.Memory.Write(source, pattern); + rig.Memory.Write(destination, new byte[Words * 4]); + + // A store before the copy is overwritten by it; a store after it overwrites it. + host.RecordCommandProcessorWrite(destination, BitConverter.GetBytes(0xDEADBEEFu), "test"); + Assert.True(((IRenderHost)host).TryPostWordCopy(destination, source, SourceWords, Words)); + host.RecordCommandProcessorWrite(destination + 8, BitConverter.GetBytes(0xFEEDFACEu), "test"); + Assert.Equal(1, host.PostedWordCopies(MetalRenderHost.PostedWordCopyRefusal.None)); + + var expected = Replicated(pattern, Words); + expected[2] = 0xFEEDFACE; + // Before the GPU ran it, a stream read sees the store as written. + Assert.Equal(expected, Words32(rig.Read(destination, Words * 4))); + + rig.Drain(); + Assert.Equal(expected, Words32(rig.Memory.ReadRaw(destination, Words * 4))); + Assert.Empty(rig.Fatals); + } + + [Fact] + public void ACopyIsRefusedAndLeftToItsDispatchWhenItsSourceIsNotFinalOrItsRangeIsUnsupported() + { + using var rig = CreateRig(); + if (rig is null) return; + var host = rig.Host; + var source = rig.Memory.Allocate(SourceWords * 4); + var destination = rig.Memory.Allocate(Words * 4); + rig.Memory.Write(destination, new byte[Words * 4]); + + // Source bytes a recorded store still owes: the kernel would read them on the GPU, the host cannot yet. + host.RecordCommandProcessorWrite(source, BitConverter.GetBytes(0x12345678u), "test"); + Assert.False(((IRenderHost)host).TryPostWordCopy(destination, source, SourceWords, Words)); + Assert.Equal(1, host.PostedWordCopies(MetalRenderHost.PostedWordCopyRefusal.Input)); + + // Overlapping, unaligned and oversized copies are not taken either. + Assert.False(((IRenderHost)host).TryPostWordCopy(destination, destination + 4, SourceWords, Words)); + Assert.False(((IRenderHost)host).TryPostWordCopy(destination + 2, source, SourceWords, Words)); + Assert.False(((IRenderHost)host).TryPostWordCopy(destination, source, SourceWords, 4 * 1024 * 1024 + 1)); + Assert.Equal(3, host.PostedWordCopies(MetalRenderHost.PostedWordCopyRefusal.Unsupported)); + + rig.Drain(); + // Nothing was stored for the refused copies. + Assert.Equal(new uint[Words], Words32(rig.Memory.ReadRaw(destination, Words * 4))); + Assert.Empty(rig.Fatals); + } +} From 96cd941057925dafcc1f8a401237e1bcc918feb5 Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 22:50:46 +0000 Subject: [PATCH 068/134] [Shader] Number hull instances from zero and narrow fma_mix NaNs to 0x7E00 in MSL With draw parameters the hull program's instance VGPR is the patch over the patches per instance, as the hardware numbers a draw's instances (upstream 7cf0ac568); a start instance reaches it only through its named user data. V_FMA_MIXLO/HI_F16 narrow a NaN to 0x7E00 with its sign; Metal's half() kept the payload (0x7E09 for 0x7FC12345, checked on device). --- .../Gen5MslTranslator.Alu.cs | 6 +++++- .../Gen5MslTranslator.cs | 11 ++++++++--- .../Gen5MslAluParityTests.cs | 6 ++++++ .../Gen5MslTessellationLaunchTests.cs | 19 +++++++++++++++---- 4 files changed, 34 insertions(+), 8 deletions(-) diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Alu.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Alu.cs index 9568edece..393381708 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Alu.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Alu.cs @@ -1274,7 +1274,11 @@ private string EmitFmaMix( return AsUInt($"({value})"); } - var packed = $"((uint)as_type(half({value})))"; + // A NaN narrows to 0x7E00 with its sign, whatever its payload (upstream 7cf0ac568); Metal's + // half() keeps the payload's top bits. + var wide = Temp("float", value); + var packed = $"(((as_type({wide}) & 0x7FFFFFFFu) > 0x7F800000u) " + + $"? (((as_type({wide}) >> 16) & 0x8000u) | 0x7E00u) : (uint)as_type(half({wide})))"; return instruction.Opcode == "VFmaMixloF16" ? $"((v[{destination}] & 0xFFFF0000u) | {packed})" : $"((v[{destination}] & 0x0000FFFFu) | ({packed} << 16))"; diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs index 981198ad8..a080c97c9 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs @@ -1674,7 +1674,7 @@ private void EmitInitialState(StringBuilder source) if (_stage == Gen5MslStage.Compute && _request.Tessellation is { Role: Gen5TessellationRole.Hull } hull) { - EmitHullLaunchState(source, hull); + EmitHullLaunchState(source, hull, _request.SupportsDrawParameters); } else if (_stage == Gen5MslStage.Compute) { @@ -1763,7 +1763,7 @@ private void EmitInitialState(StringBuilder source) // within its instance, v1 the patch within the group and the control point, v2 the local // half's vertex index, v3 its thread within the group (its LDS slot), v5 the instance. s[0:1] // and the user data come from the layout like any user data. - private static void EmitHullLaunchState(StringBuilder source, Gen5TessellationLaunch hull) + private static void EmitHullLaunchState(StringBuilder source, Gen5TessellationLaunch hull, bool instancesFromZero) { var patches = hull.PatchesPerGroup; var points = hull.ControlPoints; @@ -1783,7 +1783,12 @@ private static void EmitHullLaunchState(StringBuilder source, Gen5TessellationLa source.AppendLine(" v[2] = sharpemu_hull_lane < sharpemu_hull_points"); source.AppendLine($" ? sharpemu_hull_vertices[sharpemu_hull_instance_patch * {points}u + sharpemu_hull_lane % {points}u] : 0u;"); source.AppendLine(" v[3] = sharpemu_hull_lane;"); - source.AppendLine(" v[5] = sharpemu_hull_launch[1] + sharpemu_hull_patch / sharpemu_hull_instance_patches;"); + // The hardware numbers a draw's instances from zero; a start instance reaches the program only + // through the user data its draw packet names (upstream 7cf0ac568, Gen5SpirvTranslator.Tessellation). + // Without draw parameters (SHARPEMU_METAL_DRAW_PARAMETERS=0) the draw's first instance is added, as before. + source.AppendLine(instancesFromZero + ? " v[5] = sharpemu_hull_patch / sharpemu_hull_instance_patches;" + : " v[5] = sharpemu_hull_launch[1] + sharpemu_hull_patch / sharpemu_hull_instance_patches;"); source.AppendLine(" active = true;"); } diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslAluParityTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslAluParityTests.cs index 971be7f04..629759759 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslAluParityTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslAluParityTests.cs @@ -22,6 +22,12 @@ public sealed class Gen5MslAluParityTests(ITestOutputHelper output) new object[] { "VFmaMixhiF16", 0x00003E00u, 0x00004000u, 0x00003C00u, 0xABCD1234u, 0u, 7u, 0u, 0u, false, 0x44001234u }, new object[] { "VFmaMixF32", 0x0000BE00u, 0x00004000u, 0x3F800000u, 0u, 0u, 3u, 1u, 1u, false, 0xC0000000u }, // abs then negate: -1.5*2+1 = -2 new object[] { "VFmaMixloF16", 0x7FC00000u, 0x3F800000u, 0u, 0xABCDFFFFu, 0u, 0u, 0u, 0u, true, 0xABCD0000u }, // clamp NaN -> 0 + // A NaN narrows to 0x7E00 with its sign, whatever its payload (upstream 7cf0ac568, + // NativeFloat16ConversionDeviceTests): x * 1 + -0 of a quiet, a payload and a signalling NaN. + new object[] { "VFmaMixloF16", 0x7FC00000u, 0x3F800000u, 0x80000000u, 0xABCD1234u, 0u, 0u, 0u, 0u, false, 0xABCD7E00u }, + new object[] { "VFmaMixloF16", 0x7FC12345u, 0x3F800000u, 0x80000000u, 0xABCD1234u, 0u, 0u, 0u, 0u, false, 0xABCD7E00u }, + new object[] { "VFmaMixloF16", 0x7F800001u, 0x3F800000u, 0x80000000u, 0xABCD1234u, 0u, 0u, 0u, 0u, false, 0xABCD7E00u }, + new object[] { "VFmaMixhiF16", 0xFFC12345u, 0x3F800000u, 0x80000000u, 0xABCD1234u, 0u, 0u, 0u, 0u, false, 0xFE001234u }, new object[] { "VPkFmaF16", 0x3E003E00u, 0x3C013C01u, 0x80018001u, 0u, 0u, 7u, 0u, 0u, false, 0x3E013E01u }, // exact result just below midpoint; float fma + half incorrectly gives 3E02 new object[] { "VPkFmacF16", 0x3E003E00u, 0x3C013C01u, 0u, 0x80018001u, 0u, 0u, 0u, 0u, false, 0x3E013E01u }, new object[] { "VPkAddF16", 0x40003C00u, 0x44004200u, 0u, 0u, 0u, 3u, 0u, 0u, false, 0x46004400u }, // (1+3, 2+4) diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslTessellationLaunchTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslTessellationLaunchTests.cs index 3ba7d92e8..bf8453337 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslTessellationLaunchTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslTessellationLaunchTests.cs @@ -109,17 +109,28 @@ public void MetalCompilesBothStages(Gen5TessellationRole role, bool quad) Assert.True(MetalNative.TryCompileLibrary(shader.Source, out _, out var error), $"Metal rejected the {role} MSL: {error}\n{shader.Source}"); } - private static string Compile(ShaderStage stage, Gen5TessellationLaunch tessellation) + // With draw parameters the hull program's instance counts from zero, as the hardware numbers it (upstream + // 7cf0ac568): a start instance reaches it only through the user data its draw packet names. + [Fact] + public void WithDrawParametersTheHullInstanceCountsFromZero() + { + var source = Compile(ShaderStage.Compute, + new Gen5TessellationLaunch(Gen5TessellationRole.Hull, 21, 3, 0x8000, 16), supportsDrawParameters: true); + Assert.Contains("v5 = sharpemu_hull_patch / sharpemu_hull_instance_patches;", source, StringComparison.Ordinal); + Assert.DoesNotContain("sharpemu_hull_launch[1]", source, StringComparison.Ordinal); + } + + private static string Compile(ShaderStage stage, Gen5TessellationLaunch tessellation, bool supportsDrawParameters = false) { // Registers the program never indexes are emitted as locals (s2) rather than file entries (s[2]). - return Regex.Replace(CompileShader(stage, tessellation).Source, @"\b([sv])\[(\d+)\]", "$1$2"); + return Regex.Replace(CompileShader(stage, tessellation, supportsDrawParameters).Source, @"\b([sv])\[(\d+)\]", "$1$2"); } - private static Gen5MslShader CompileShader(ShaderStage stage, Gen5TessellationLaunch tessellation) + private static Gen5MslShader CompileShader(ShaderStage stage, Gen5TessellationLaunch tessellation, bool supportsDrawParameters = false) { var program = Gen5ComputeFixtures.DecodeOrThrow(new Gen5ComputeFixture("tessellation", EndProgram, 0, 0)); var request = Gen5ComputeFixtures.RequestOrThrow(program, stage, - waveLaneCount: 64, localSizeX: 64, tessellation: tessellation); + waveLaneCount: 64, localSizeX: 64, tessellation: tessellation, supportsDrawParameters: supportsDrawParameters); Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error), error); Assert.Same(tessellation, shader.Tessellation); return shader; From fdbf8da89e67c04b3d394db8db5edfc47708f087 Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 22:52:42 +0000 Subject: [PATCH 069/134] [Metal] Decode the narrow integer and UNORM 11_11_10 render targets upstream added R8Sint (1,5), RG8Uint (3,4), RG8Sint (3,5) and 11_11_10 with number type 0 decode to their Metal formats and integer pixel output kinds, as in upstream 99f9fe930's Vulkan table; before, a title that rendered to one stopped on a colour target with no pixel output kind. --- .../SharpEmu.Gpu.Metal/MetalGuestFormats.cs | 13 ++++++++++--- .../MetalRenderTargetFormatParityTests.cs | 17 +++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/MetalGuestFormats.cs b/src/graphics/SharpEmu.Gpu.Metal/MetalGuestFormats.cs index c698f0c69..7cb93c741 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/MetalGuestFormats.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/MetalGuestFormats.cs @@ -279,7 +279,9 @@ public static bool TryDecodeRenderTargetFormat( (5, 4, _) => MtlPixelFormat.Rg16Uint, (5, 5, _) => MtlPixelFormat.Rg16Sint, (5, 7, _) => MtlPixelFormat.Rg16Float, - (6, 7, _) or (7, 7, _) => MtlPixelFormat.Rg11B10Float, + // 11_11_10 holds unsigned floats whatever the number type; the image path maps its UNORM + // variant to the same host format (upstream 99f9fe930, GuestPixelFormats.HostFormats). + (6, 7, _) or (7, 7, _) or (6, 0, _) => MtlPixelFormat.Rg11B10Float, (9, _, 1) => MtlPixelFormat.Bgr10A2Unorm, (9, _, _) => MtlPixelFormat.Rgb10A2Unorm, (10, 1, _) => MtlPixelFormat.Rgba8Snorm, @@ -307,6 +309,10 @@ public static bool TryDecodeRenderTargetFormat( (1, 6 or 9, _) => GuestPixelFormats.NarrowSrgbFormats ? MtlPixelFormat.R8UnormSrgb : MtlPixelFormat.R8Unorm, (3, 6 or 9, _) => GuestPixelFormats.NarrowSrgbFormats ? MtlPixelFormat.Rg8UnormSrgb : MtlPixelFormat.Rg8Unorm, (1, 4, _) or (49, 0, _) => MtlPixelFormat.R8Uint, + // Narrow integer targets (upstream 99f9fe930): the image path gives them these formats. + (1, 5, _) => MtlPixelFormat.R8Sint, + (3, 4, _) => MtlPixelFormat.Rg8Uint, + (3, 5, _) => MtlPixelFormat.Rg8Sint, (1, 1, _) => MtlPixelFormat.R8Snorm, (3, 0, _) => MtlPixelFormat.Rg8Unorm, (3, 1, _) => MtlPixelFormat.Rg8Snorm, @@ -333,10 +339,11 @@ public static bool TryDecodeRenderTargetFormat( var outputKind = format switch { - MtlPixelFormat.R8Uint or MtlPixelFormat.R16Uint or MtlPixelFormat.R32Uint or + MtlPixelFormat.R8Uint or MtlPixelFormat.R16Uint or MtlPixelFormat.R32Uint or MtlPixelFormat.Rg8Uint or MtlPixelFormat.Rg16Uint or MtlPixelFormat.Rg32Uint or MtlPixelFormat.Rgba8Uint or MtlPixelFormat.Rgba16Uint or MtlPixelFormat.Rgba32Uint => Gen5PixelOutputKind.Uint, - MtlPixelFormat.R16Sint or MtlPixelFormat.R32Sint or MtlPixelFormat.Rg16Sint or + MtlPixelFormat.R8Sint or MtlPixelFormat.R16Sint or MtlPixelFormat.R32Sint or MtlPixelFormat.Rg8Sint or + MtlPixelFormat.Rg16Sint or MtlPixelFormat.Rg32Sint or MtlPixelFormat.Rgba8Sint or MtlPixelFormat.Rgba16Sint => Gen5PixelOutputKind.Sint, _ => Gen5PixelOutputKind.Float, diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalRenderTargetFormatParityTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalRenderTargetFormatParityTests.cs index 8ee88ea71..3686b52cb 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalRenderTargetFormatParityTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalRenderTargetFormatParityTests.cs @@ -87,6 +87,23 @@ public void AnEightBitUnsignedIntegerTargetDecodesToR8Uint() Assert.Equal(MtlPixelFormat.R8Uint, format.Format); } + // The narrow targets upstream 99f9fe930 added to the Vulkan table, with the format and pixel output kind each + // decodes to: an integer target written as a float would store garbage, and a refused one stops the title. + [Theory] + [InlineData(1u, 5u, (uint)MtlPixelFormat.R8Sint, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Sint)] + [InlineData(3u, 4u, (uint)MtlPixelFormat.Rg8Uint, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Uint)] + [InlineData(3u, 5u, (uint)MtlPixelFormat.Rg8Sint, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Sint)] + [InlineData(1u, 4u, (uint)MtlPixelFormat.R8Uint, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Uint)] + [InlineData(1u, 1u, (uint)MtlPixelFormat.R8Snorm, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Float)] + [InlineData(6u, 0u, (uint)MtlPixelFormat.Rg11B10Float, SharpEmu.ShaderCompiler.Gen5PixelOutputKind.Float)] + public void NarrowTargetsDecodeToTheirFormatAndOutputKind( + uint dataFormat, uint numberType, uint expected, SharpEmu.ShaderCompiler.Gen5PixelOutputKind kind) + { + Assert.True(MetalGuestFormats.TryDecodeRenderTargetFormat(dataFormat, numberType, 0, out var format)); + Assert.Equal((MtlPixelFormat)expected, format.Format); + Assert.Equal(kind, format.OutputKind); + } + // The two encodings Metal genuinely cannot represent: it has no scaled pixel formats, // where Vulkan has R16Uscaled and R16Sscaled. Listed so the gap stays deliberate and a // future reader does not take it for more drift. From 5c769d9c2773d93e12963d85df323b3f15feafc7 Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 22:54:22 +0000 Subject: [PATCH 070/134] [Tests] Check that every returning buffer atomic out of range returns zero in MSL --- .../Gen5MslBufferAtomicTests.cs | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslBufferAtomicTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslBufferAtomicTests.cs index 913fb33db..6d4ffe1e0 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslBufferAtomicTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslBufferAtomicTests.cs @@ -155,6 +155,27 @@ public void SwapCapturesAliasedAddressAndReplacementBeforeWritingReturnedVdata() Assert.Equal(expected, Execute(shader, initial)); } + // Upstream 7cf0ac568 (BufferAtomicRangeDeviceTests): a returning atomic past the buffer drops its operation and + // returns zero, for every operation, not only swap. + [Theory] + [InlineData(0x32u)] // add + [InlineData(0x33u)] // sub + [InlineData(0x36u)] // unsigned min + [InlineData(0x38u)] // unsigned max + [InlineData(0x3Au)] // or + [InlineData(0x3Cu)] // inc + [InlineData(0x40u)] // fmax + public void EveryReturningAtomicOutOfRangeReturnsZeroAndWritesNothing(uint opcode) + { + var fixture = Fixture(true, 0, 2048, 0, indexed: false, opcode); + var shader = Compile(fixture, 0); + if (!RequireDevice()) return; + + var expected = SentinelBuffer(32); + BinaryPrimitives.WriteUInt32LittleEndian(expected.AsSpan(48), 0u); + Assert.Equal(expected, Execute(shader, SentinelBuffer(32))); + } + [Theory] [InlineData(true, 1u, 8u, 4u, true, true, 32, true)] [InlineData(false, 1u, 8u, 4u, true, true, 32, true)] From 828b0a8716e266887748921abcc5a88f80375318 Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 22:57:32 +0000 Subject: [PATCH 071/134] [Metal] Wait for a draw's graphics pipeline outside the pipeline cache's lock With the compiler threads on, the Metal host answers WaitsForGraphicsPipelines: the cache starts a must-have draw's compile with TryCreateGraphicsPipeline, waits in WaitForGraphicsPipeline without its lock (built on the worker when no compiler thread took it, as CreateGraphicsPipeline did), and the re-ask with the first description finds the compile by its key. SHARPEMU_METAL_V2_GRAPHICS_WAIT_OFF_CACHE=0 builds under the lock. --- .../V2/MetalPipelineCompiler.cs | 21 ++++ .../V2/MetalRenderHost.Pipelines.cs | 39 ++++++++ .../MetalGraphicsWaitOffCacheTests.cs | 99 +++++++++++++++++++ .../SharpEmu.Gpu.Metal.Tests/MetalPassRig.cs | 8 +- 4 files changed, 166 insertions(+), 1 deletion(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalGraphicsWaitOffCacheTests.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalPipelineCompiler.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalPipelineCompiler.cs index 05b9774ba..eb3a98a56 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalPipelineCompiler.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalPipelineCompiler.cs @@ -216,6 +216,27 @@ public bool TryWait(object key, out Result? result) return TryTakeFinished(key, pending, out result); } + /// + /// Blocks until the compile started for this key is done, leaving its result for TryTake: built here and now + /// when no compiler thread has started it, waited for when one has. Nothing to wait for when there is none. + /// The pipeline cache waits here outside its lock and then asks again (IShaderPipelineHost.WaitForGraphicsPipeline). + /// + public void WaitFor(object key) + { + if (!_pending.TryGetValue(key, out var pending)) + { + return; + } + + if (Interlocked.CompareExchange(ref pending.Claimed, 1, 0) == 0) + { + Build(pending); + return; + } + + ((IAsyncResult)pending.Work).AsyncWaitHandle.WaitOne(); + } + // The finished result, if this caller removed it: one dropped as abandoned meanwhile was // released and is not handed out. private bool TryTakeFinished(object key, Pending pending, out Result? result) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs index 4e9f1312a..69134b88a 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs @@ -839,6 +839,45 @@ public bool TryCreateGraphicsPipeline(GraphicsPipelineDescription description, o return true; } + // SHARPEMU_METAL_V2_GRAPHICS_WAIT_OFF_CACHE=0 builds the pipeline of a draw that may not be left out under the + // pipeline cache's lock again (CreateGraphicsPipeline). + private static readonly bool GraphicsWaitsOffCacheDefault = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_GRAPHICS_WAIT_OFF_CACHE") != "0"; + + /// Whether a draw that must have its pipeline waits for it outside the pipeline cache's lock; tests set it. + internal bool GraphicsWaitsOffCache { get; set; } = GraphicsWaitsOffCacheDefault; + + /// + /// A draw that may not be left out waits for its pipeline outside the pipeline cache's lock (upstream's graphics + /// pipeline compiles off the cache lock): the cache starts the compile with TryCreateGraphicsPipeline, waits here + /// without the lock, and asks again with the description that started it, which finds the compile by its + /// GraphicsCompileKey and registers the states on the worker as before. Meanwhile the programs of later draws + /// resolve on the prefetch threads instead of queueing behind the lock for the whole compile. Only with the + /// compiler threads (AsynchronousGraphics): without them TryCreateGraphicsPipeline builds in place. + /// + public bool WaitsForGraphicsPipelines => GraphicsWaitsOffCache && AsynchronousGraphics; + + /// + /// Waits for the compile TryCreateGraphicsPipeline started for this description, as CreateGraphicsPipeline would: + /// a compile no compiler thread took yet is built on this thread, one a compiler thread runs is waited for. Inside + /// the draw's preparation, as the blocking build was: the store requests are not served here (the draw's + /// programs were waited for, serving them, in AwaitProgramsBeforePreparation). + /// + public void WaitForGraphicsPipeline(GraphicsPipelineDescription description) + { + // TryCreateGraphicsPipeline counted the draw as left out; it waits instead. + Interlocked.Decrement(ref _drawsSkippedCompiling); + Interlocked.Increment(ref _pipelineWaitsBlocking); + Interlocked.Increment(ref _graphicsWaitsOffCache); + NoteBlockingBuild(); + Compiler.WaitFor(GraphicsCompileKey(description)); + } + + private long _graphicsWaitsOffCache; + + /// Pipelines a draw waited for outside the pipeline cache's lock. + internal long GraphicsWaitsOffCacheCount => Interlocked.Read(ref _graphicsWaitsOffCache); + // What identifies a graphics compile: the parts of the description its states are built from. private static GraphicsPipelineKey GraphicsCompileKey(GraphicsPipelineDescription description) => new() { diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalGraphicsWaitOffCacheTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalGraphicsWaitOffCacheTests.cs new file mode 100644 index 000000000..db3eb25eb --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalGraphicsWaitOffCacheTests.cs @@ -0,0 +1,99 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.Abstractions; +using SharpEmu.Libs.Gpu.Pipelines; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests; + +/// +/// A draw that must have its pipeline waits for it outside the pipeline cache's lock +/// (IShaderPipelineHost.WaitsForGraphicsPipelines): the cache starts the compile with TryCreateGraphicsPipeline, +/// waits in WaitForGraphicsPipeline, and asks again with the description that started it. A second draw with an +/// equal description shares the compile, and the re-ask finds it done (the sync's notes-g3 "Needs a decision 2"). +/// Device work is behind the exclusive device gate. +/// +public sealed class MetalGraphicsWaitOffCacheTests(ITestOutputHelper output) +{ + private static readonly Lazy Device = new(MetalNative.MTLCreateSystemDefaultDevice); + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ADrawThatWaitsSharesTheCompileAndTheReaskTakesIt(bool compilerThreadRuns) + { + if (!RequireDevice()) return; + using var rig = new MetalPassRig(Device.Value, 1024 * 1024); + var host = rig.Host; + host.AsynchronousGraphics = true; + Assert.True(((IShaderPipelineHost)host).WaitsForGraphicsPipelines); + using var gate = new ManualResetEventSlim(false); + host.PipelineCompiler.Gate = gate; + _ = host.PipelineCompiler.TakeCounters(); + + var first = rig.PipelineDescription([GpuFormat.R8G8B8A8Unorm], ["float4(1.0f, 0.0f, 0.0f, 1.0f)"]); + // Another draw's description: other objects, the same pipeline. + var second = new GraphicsPipelineDescription + { + Rendering = first.Rendering, + VertexInput = first.VertexInput, + VertexInfo = first.VertexInfo, + VertexProgram = first.VertexProgram, + VertexStage = first.VertexStage, + PixelProgram = first.PixelProgram, + PixelStage = first.PixelStage, + StaticParameters = first.StaticParameters, + }; + + // The cache's first ask starts the compile; the second draw's shares it. + Assert.False(host.TryCreateGraphicsPipeline(first, out _)); + Assert.False(host.TryCreateGraphicsPipeline(second, out _)); + var (started, _, deduped, _) = host.PipelineCompiler.TakeCounters(); + Assert.Equal(1L, started); + Assert.Equal(1L, deduped); + + if (compilerThreadRuns) + { + gate.Set(); + } + + // Outside the cache's lock: built here when no compiler thread took it, waited for when one did. + ((IShaderPipelineHost)host).WaitForGraphicsPipeline(second); + Assert.True(host.TryCreateGraphicsPipeline(first, out var handle)); + Assert.NotEqual(0L, (long)handle.Pipeline); + Assert.Equal(1L, host.GraphicsWaitsOffCacheCount); + var (skipped, waits) = host.CompilingDrawCounters; + Assert.Equal(1L, skipped); + Assert.Equal(1L, waits); + gate.Set(); + } + + [Fact] + public void WithoutTheCompilerThreadsTheCacheKeepsTheBlockingBuild() + { + if (!RequireDevice()) return; + using var rig = new MetalPassRig(Device.Value, 1024 * 1024); + var host = rig.Host; + host.AsynchronousGraphics = false; + Assert.False(((IShaderPipelineHost)host).WaitsForGraphicsPipelines); + host.AsynchronousGraphics = true; + host.GraphicsWaitsOffCache = false; + Assert.False(((IShaderPipelineHost)host).WaitsForGraphicsPipelines); + } + + private bool RequireDevice() + { + if (Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") != "1") + { + output.WriteLine("Pipeline compiles run on the device only behind the exclusive device gate."); + return false; + } + + Assert.True(OperatingSystem.IsMacOS()); + Assert.NotEqual(0, Device.Value); + return true; + } +} diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalPassRig.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalPassRig.cs index 61e19affc..35544d0ad 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalPassRig.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalPassRig.cs @@ -104,6 +104,12 @@ public Target MakeTarget(ulong address, GpuFormat format, uint width, uint heigh /// , an MSL condition on in.position, discards the /// fragments it holds for. public PipelineHandle Pipeline( + GpuFormat[] formats, string[] outputs, float left = -1f, float right = 1f, bool knownPositions = false, bool mesh = false, + string? discardWhen = null) => + Host.CreateGraphicsPipeline(PipelineDescription(formats, outputs, left, right, knownPositions, mesh, discardWhen)); + + /// The description creates, with its programs' modules made. + public GraphicsPipelineDescription PipelineDescription( GpuFormat[] formats, string[] outputs, float left = -1f, float right = 1f, bool knownPositions = false, bool mesh = false, string? discardWhen = null) { @@ -241,7 +247,7 @@ fragment PixelOut fill_fs(PixelIn in [[stage_in]]) PixelStage = new ShaderProgramInfo { Stage = ShaderStageKind.Pixel, Hash = id + 1 }, StaticParameters = parameters, }; - return Host.CreateGraphicsPipeline(description); + return description; static string F(float value) => value.ToString("F4", CultureInfo.InvariantCulture) + "f"; } From 94725539fbcc6867658a0fb528d16db06fb7481d Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 22:57:55 +0000 Subject: [PATCH 072/134] [Docs] Document the Metal host port switches --- docs/macos/configuration.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index adb32c9e1..7f273c840 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -70,6 +70,7 @@ them for measurements or to isolate a problem. | `SHARPEMU_METAL_V2_BINARY_ARCHIVE_BUDGET_MB` | `8192` | Size bound of the archives on disk. | | `SHARPEMU_METAL_V2_ASYNC_PIPELINES` | on | `0` builds pipeline states on the GPU worker thread. | | `SHARPEMU_METAL_V2_ASYNC_LIBRARIES` | on | `0` compiles each shader library on the thread that needs it, not on the compile pool. | +| `SHARPEMU_METAL_V2_GRAPHICS_WAIT_OFF_CACHE` | on | A draw that cannot be left out while its pipeline compiles waits for the compile outside the shared pipeline cache's lock, so other draws' programs keep resolving. `0` builds the pipeline under the lock, as before. Only with `SHARPEMU_METAL_V2_ASYNC_GRAPHICS` on. | | `SHARPEMU_RESOLVE_SHARDS` | `1` | Threads that resolve draw and dispatch programs ahead of the GPU worker, 1 to 8. With more than one, each has its own queue and its own part of the resolve memo, and a draw always goes to the same one. `1` is the single resolver; `2` measured no frame-time gain in Demon's Souls for more resolver CPU. Logged once at start; per-thread counts and the shared-lock wait are in the `shards=(...)` field of the `[METAL-V2][PERF]` prefetch counters. | | `SHARPEMU_PREFETCH_EXACT_EFFECTS` | on | A dispatch or draw resolved ahead of a dispatch the host consumed as a kernel fill or copy is no longer refused for that alone: its take refuses it only when the fill's or copy's logged write covers what its resolution read (the same check as across any other dispatch). DCC and constant fills, image clears, metadata clears, image copies and CPU-predicted dispatches still refuse every dispatch and draw resolved ahead of them. The prefetch counters report `dispatch_effects=(...)` by kind and `exact_effects=(mode,refused,taken,draws,draw_refused,draw_taken)`, the jobs the old rule would have refused that the check refused or took. `dispatch` keeps the old rule for draws only; `0` refuses on every effect again. | | `SHARPEMU_RESOLVE_UNSHARED_COMPUTE` | on | With more than one resolve shard, a dispatch whose kept program still holds, or whose kept program only needs new user data on a fast plan with a permutation already made, is answered on its own thread without the shared lock. `0` sends every dispatch through the shared lock. The `shards=(...)` counters split the shared-lock takes and wait by reason (`shared_by=`, `shared_wait_by=`) and count the dispatches answered without it (`unshared_compute=`) and why a rebinding still took it (`rebind_shared_by=`). | @@ -114,6 +115,14 @@ undoes an optimization to isolate a miscompile: | `SHARPEMU_METAL_V2_BUFFER_WORD_COMPUTE` | on | The same variants for compute pipelines: a dispatch runs the generic pipeline until a background compile has made the one with its words folded in (same results). Off whenever `SHARPEMU_METAL_V2_BUFFER_WORD_CONSTANTS=0`. `0` keeps every compute dispatch on its generic pipeline while draws keep their variants, so the two can be measured apart; it does not change the MSL. The periodic counter line reports `buffer_words_compute=[...]` (`generic_off` counts dispatches the switch kept generic). | | `SHARPEMU_LOD_STATS` | guarded | `always` compiles the LOD statistics counters into every pixel pipeline. | +## GPU command stream + +| Variable | Default | Effect | +| --- | --- | --- | +| `SHARPEMU_METAL_V2_DEFERRED_LABEL_LANDINGS` | on | An end-of-pipe label that Metal defers to GPU completion still reports the submission it lands with, so another queue's soft wait (`SHARPEMU_END_OF_PIPE_SOFT_WAITS`) ends when that submission completes. `0` gives deferred labels no landing again: such a wait ends only at its cap. | +| `SHARPEMU_METAL_V2_DYNAMIC_STENCIL_OPS` | on | A draw's stencil operations and compare functions come from its own dynamic state, not from the draw its pipeline was first built for. `0` takes them from the pipeline again. | +| `SHARPEMU_POSTED_WORD_COPY` | on | A bounded word-copy kernel whose source is final and whose destination holds no image or surface metadata is recorded as a command-processor store of the copied words at its place in the stream, not as a dispatch. The counter line reports `word_copy=[posted=...,unsupported=...,image=...,...]`. `0` runs every such kernel as a dispatch. | + ## Diagnostics | Variable | Effect | From 457d3641f82645eb15b41c3bf9627e6a55b2865c Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 23:33:54 +0000 Subject: [PATCH 073/134] [Metal] Take upstream's resident-mip textures in the image cache Upstream (99f9fe930, 7cf0ac568) describes a sampled texture whose T# starts past mip 0 from that level (ImageDescription.FirstLevel / HostExtent) when ImageRequestBuilders.PartialMipChains is set, and reads image bytes through ResidentImageBacking. The merge kept the gate off on Metal because MetalImageCache ignored FirstLevel. The Metal cache already holds a sampled texture from its BASE_LEVEL with the whole guest chain as its description (MetalImageCache.BaseLevel.cs). One mechanism now covers both: - FindImage takes a resident-levels request as its whole chain (WithWholeMipChain), so it keys with every other request for those bytes and its view addresses guest levels; - the levels upstream leaves out become a floor on where the texture starts (ResidentFloor): while the guest has not mapped the chain and no image over it holds GPU contents, a texture never holds or grows into a level before the binding's base, whatever the base-level memory policy chooses (SHARPEMU_METAL_V2_BASE_LEVEL=0, or a block-compressed base it would move to an aligned level); shrinking stays the memory policy's; - image uploads read staged guest bytes with upstream's policy (MetalGuestMemory.ReadImageBacking: CPU-visible memory, else ResidentImageBacking with PRT/AMM and SHARPEMU_IMAGE_BACKING_HOLES), and stop with upstream's fatal on an unreadable byte instead of the binding's prefix-and-zeros. MetalGpuBackend.ConfigureSharedGpuCode turns the builder gate on in the process that composes the Metal backend (the GPU host with the split, which runs the builders and the cache alike). SHARPEMU_METAL_V2_PARTIAL_MIP_CHAINS=0 restores whole-chain requests and the old image read. ResidentImageBacking.TryRead is public (Metal has no InternalsVisibleTo), with an overload that takes the hole policy; Vulkan's calls are unchanged. Tests: MetalImageBudgetTests.ResidentLevels (device) - a texture held from its first resident level samples every level; a lower first level grows the same image with the new level and the old ones; all mapped takes the whole chain; a hole stops the upload, holes allowed zero it, the switch off reads the prefix; a BC1 chain resident from an unaligned level; the backend sets the builder gate. The test backing gains unmapped ranges. --- docs/macos/configuration.md | 1 + .../Images/ImageRequestBuilders.Texture.cs | 4 +- .../Gpu/Images/ResidentImageBacking.cs | 15 +- .../SharpEmu.Gpu.Metal/MetalGpuBackend.cs | 4 + .../SharpEmu.Gpu.Metal/V2/MetalGuestMemory.cs | 69 +++- .../V2/MetalImageCache.BaseLevel.cs | 28 +- .../V2/MetalImageCache.ConsumerRuns.cs | 2 +- .../V2/MetalImageCache.ResidentLevels.cs | 115 ++++++ .../V2/MetalImageCache.UploadPrelude.cs | 2 +- .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 11 +- .../MetalImageBudgetTests.ResidentLevels.cs | 341 ++++++++++++++++++ .../MetalImageBudgetTests.cs | 25 +- 12 files changed, 589 insertions(+), 28 deletions(-) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.ResidentLevels.cs create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalImageBudgetTests.ResidentLevels.cs diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 7f273c840..efe154d0b 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -54,6 +54,7 @@ them for measurements or to isolate a problem. | `SHARPEMU_METAL_V2_IMAGE_BUDGET_MB` | computed | Fixed byte budget for the detiled image cache, at least 256. By default the budget follows the memory the host has free. | | `SHARPEMU_METAL_V2_SINGLE_COPY` | on | `0` never releases guest memory that a clean texture's Metal copy duplicates. Requires the chunked guest backing. | | `SHARPEMU_METAL_V2_WHOLE_STALE_RELOAD` | on | `0` restores the old refusal: a GPU-written image whose every byte an alias has since written keeps its older texels instead of reloading them, and writes them back over the alias's bytes. For A/B comparisons only. | +| `SHARPEMU_METAL_V2_PARTIAL_MIP_CHAINS` | on | A streamed texture whose T# starts past mip 0 is described from that level (upstream's resident-mip textures, `ImageDescription.FirstLevel`). The image cache looks it up as its whole chain and, while the guest has not mapped that chain, never holds or reads a level before the binding's base level, whatever `SHARPEMU_METAL_V2_BASE_LEVEL` says. Image uploads read guest bytes as upstream does: every byte must be mapped (or partially resident PRT/AMM memory), else the GPU stops with `Could not read the mapped guest image backing`; `SHARPEMU_IMAGE_BACKING_HOLES=1` reads unmapped pages after a mapped first page as zero instead. `0` keeps whole-chain requests and reads image bytes as a binding does (the readable prefix, zeros after it). | | `SHARPEMU_METAL_V2_STAGED_CACHE_MB` | `256` | Budget of the staged-range cache. | | `SHARPEMU_METAL_V2_TRANSIENT_COMMIT_MB` | `256` | Transient staging a command buffer may hold before it is committed early. | | `SHARPEMU_METAL_V2_RESIDENCY_SET` | off | `1` puts every guest window in an `MTLResidencySet`. | diff --git a/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.Texture.cs b/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.Texture.cs index 15c3a7e0e..f62610e79 100644 --- a/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.Texture.cs +++ b/src/SharpEmu.Libs/Gpu/Images/ImageRequestBuilders.Texture.cs @@ -224,8 +224,8 @@ private static ImageViewDescription TextureView( } // Set by a backend whose image cache understands ImageDescription.FirstLevel (an image of the - // resident levels only, WithWholeMipChain). The Metal cache keeps its own base-level state - // (MetalImageCache.BaseLevel) and reads every texture request as a whole chain. + // resident levels only, WithWholeMipChain): Vulkan, and Metal unless SHARPEMU_METAL_V2_PARTIAL_MIP_CHAINS=0 + // (MetalImageCache.ResidentLevels takes the request as its whole chain and holds the texture from its level). // Requests cached under the other setting describe other images: a change drops every thread's cache at its next // lookup (_textureCacheSetting). public static bool PartialMipChains diff --git a/src/SharpEmu.Libs/Gpu/Images/ResidentImageBacking.cs b/src/SharpEmu.Libs/Gpu/Images/ResidentImageBacking.cs index 80eadf57d..67dad446f 100644 --- a/src/SharpEmu.Libs/Gpu/Images/ResidentImageBacking.cs +++ b/src/SharpEmu.Libs/Gpu/Images/ResidentImageBacking.cs @@ -9,7 +9,9 @@ namespace SharpEmu.Libs.Gpu.Images; // A texture streamed into its address range maps only its resident mips. A tiled chain puts // the mip tail and small levels at the start and level 0 at the end, so the resident part is // a backed prefix. The GPU samples only resident levels; the unmapped rest reads as zero. -internal static class ResidentImageBacking +// Public for the Metal image cache, which reads guest image bytes with the same policy (no InternalsVisibleTo +// for extracted backends). +public static class ResidentImageBacking { private const ulong Page = 1UL << 12; @@ -22,10 +24,17 @@ internal static class ResidentImageBacking // Reads image bytes from CPU-visible backing or PRT backing. A streamed texture's image holds only its // resident levels and its upload reads only their bytes, so an unmapped byte inside them is an error, // not a level to zero; SHARPEMU_IMAGE_BACKING_HOLES=1 still zero-fills the unmapped pages instead. - internal static bool TryRead(IGuestBackedSpace backing, ulong address, Span destination) => + public static bool TryRead(IGuestBackedSpace backing, ulong address, Span destination) => + TryRead(backing, address, destination, AllowHoles); + + // SHARPEMU_IMAGE_BACKING_HOLES as this process read it; a caller with its own test switch passes that instead. + public static bool HolesAllowed => AllowHoles; + + // TryRead with the hole policy given rather than read from the environment. + public static bool TryRead(IGuestBackedSpace backing, ulong address, Span destination, bool allowHoles) => backing.TryReadBacking(address, destination) || KernelMemoryCompatExports.TryReadPrtBacking(backing, address, destination) || - AllowHoles && TryReadResidentPrefix(backing, address, destination, allowHoles: true); + allowHoles && TryReadResidentPrefix(backing, address, destination, allowHoles: true); // Copies the backed prefix page by page and zero-fills the unmapped tail. A backed page // after a hole is not a mip chain, so it is rejected unless allowHoles. diff --git a/src/graphics/SharpEmu.Gpu.Metal/MetalGpuBackend.cs b/src/graphics/SharpEmu.Gpu.Metal/MetalGpuBackend.cs index d9112f4fe..69a731f95 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/MetalGpuBackend.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/MetalGpuBackend.cs @@ -32,6 +32,10 @@ public static class MetalGpuBackend internal static void ConfigureSharedGpuCode() { SharpEmu.Libs.Gpu.Images.ImageRequestBuilders.NativeColorClearMetadata = false; + // The image cache takes textures described from their first resident level (MetalImageCache.ResidentLevels.cs). + // This is the process that runs the request builders and the cache alike: the guest process with one process, + // the GPU host with two (GpuHostMain.ComposeMetal), which reads the same environment. + SharpEmu.Libs.Gpu.Images.ImageRequestBuilders.PartialMipChains = V2.MetalImageCache.PartialMipChains; SharpEmu.ShaderCompiler.Resources.ResourceMaterializer.CompiledTransactions = CompiledTransactionsDefault(); SharpEmu.ShaderCompiler.Resources.ResourceMaterializer.SpecializationGuards = false; SharpEmu.ShaderCompiler.Resources.ResourceTracker.UnvalidatedAddressWordsAreMemory = false; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGuestMemory.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGuestMemory.cs index 136163089..010520a74 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGuestMemory.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGuestMemory.cs @@ -714,7 +714,17 @@ private void ReleaseBuffer(MetalWindowPartition.Window window) /// when asks for it (a binding, which a prefix would cut short), /// otherwise only a prefix is handed back, which the caller has to check. /// - public MetalGuestRange Resolve(ulong gpuVa, ulong size, bool whole = false) + public MetalGuestRange Resolve(ulong gpuVa, ulong size, bool whole = false) => Resolve(gpuVa, size, whole, read: null); + + /// Fills a staging span with guest bytes; see . + public delegate void StagingRead(ulong gpuVa, Span destination); + + /// + /// whose staged copy, when the range is not read in place, is filled by + /// rather than : an image upload reads its guest bytes with + /// the resident-backing policy (MetalImageCache.ReadImageBacking), not as a readable prefix and zeros. + /// + public MetalGuestRange Resolve(ulong gpuVa, ulong size, bool whole, StagingRead? read) { if (size == 0 || gpuVa == 0 || size > ulong.MaxValue - gpuVa) { @@ -727,7 +737,7 @@ public MetalGuestRange Resolve(ulong gpuVa, ulong size, bool whole = false) return resolved; } - return Upload(gpuVa, size, whole); + return Upload(gpuVa, size, whole, read); } /// @@ -805,7 +815,7 @@ public bool IsInPlace(in MetalGuestRange range) /// A ring copy of the guest bytes the CPU sees now, whole up to the largest window. public MetalGuestRange Stage(ulong gpuVa, ulong size) => - size == 0 || gpuVa == 0 || size > ulong.MaxValue - gpuVa ? default : Upload(gpuVa, size, whole: true); + size == 0 || gpuVa == 0 || size > ulong.MaxValue - gpuVa ? default : Upload(gpuVa, size, whole: true, read: null); /// /// True when the whole range lives in the backing. A managed write to such a range @@ -1433,7 +1443,7 @@ public unsafe void FillStaging(ulong gpuVa, in MetalGuestRange staging) } /// Copies guest bytes into the ring; used for ranges no window covers. - private MetalGuestRange Upload(ulong gpuVa, ulong size, bool whole) + private MetalGuestRange Upload(ulong gpuVa, ulong size, bool whole, StagingRead? read) { if (size > _maxUploadBytes && whole && size <= Math.Min(_maxWindowBytes, MaxWholeStageBytes)) { @@ -1480,7 +1490,15 @@ private MetalGuestRange Upload(ulong gpuVa, ulong size, bool whole) } var range = Allocate(size, RingAlignment, out var span); - ReadForStaging(gpuVa, span); + if (read is null) + { + ReadForStaging(gpuVa, span); + } + else + { + read(gpuVa, span); + } + Interlocked.Add(ref _ringFallbackBytes, (long)size); Interlocked.Increment(ref _ringFallbacks); return range; @@ -1513,6 +1531,47 @@ public void ReadForStaging(ulong gpuVa, Span span) } } + private long _imageReadsResidentBacking; + + /// The hole policy of : SHARPEMU_IMAGE_BACKING_HOLES=1; tests switch it. + internal static bool ImageBackingHoles { get; set; } = SharpEmu.Libs.Gpu.Images.ResidentImageBacking.HolesAllowed; + + /// Staged image reads the CPU view could not serve whole and the resident-backing read did (PRT/AMM, holes). + public long ImageReadsResidentBacking => Interlocked.Read(ref _imageReadsResidentBacking); + + /// + /// The staged read of an image upload (), with the policy of upstream's Vulkan image caches + /// (): every byte is the guest's - CPU-visible guest memory, or partially resident + /// (PRT/AMM) memory whose reserved pages read as zero - or, with SHARPEMU_IMAGE_BACKING_HOLES=1, an unmapped page reads + /// as zero. Anything else stops the GPU, as upstream does: an image's upload reads only the levels its texture holds + /// (a streamed texture's resident levels, MetalImageCache.BaseLevel.cs), so an unmapped byte in them is not a level + /// to invent, and the readable prefix and zeros gives a binding would hide that. + /// Guest memory outside the shared backing (one process only) is still read through the CPU view first. + /// + public void ReadImageBacking(ulong gpuVa, Span span) + { + var size = (ulong)span.Length; + MetalGpuReferenceCensus.Mark(gpuVa, size, MetalRefKind.Staged); + SharpEmu.HLE.GuestMemory.SplitPrivateAccess.CheckGpuRead(_backing, gpuVa, size, "metal-image-read"); + if (_memory.TryRead(gpuVa, span)) + { + return; + } + + if (SharpEmu.Libs.Gpu.Images.ResidentImageBacking.TryRead(_backing, gpuVa, span, ImageBackingHoles)) + { + Interlocked.Increment(ref _imageReadsResidentBacking); + return; + } + + throw GpuFatal.Fatal( + $"Could not read the mapped guest image backing: address=0x{gpuVa:X16} size=0x{size:X16} " + + $"range_backed={_backing.IsBackedRange(gpuVa, size)} first_byte_backed={_backing.IsBackedRange(gpuVa, 1)} " + + $"last_byte_backed={_backing.IsBackedRange(gpuVa + size - 1, 1)} " + + $"split={SharpEmu.HLE.GuestMemory.SplitPrivateAccess.Enabled} (SHARPEMU_IMAGE_BACKING_HOLES=1 reads unmapped " + + "pages after a mapped first page as zero; SHARPEMU_METAL_V2_PARTIAL_MIP_CHAINS=0 restores the readable-prefix read)."); + } + /// A second ring copy of bytes already staged in the ring; invalid when the range is not a ring range. public unsafe MetalGuestRange Duplicate(in MetalGuestRange staged) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.BaseLevel.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.BaseLevel.cs index 6ead07ae9..a481d147b 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.BaseLevel.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.BaseLevel.cs @@ -48,7 +48,9 @@ namespace SharpEmu.Gpu.Metal.V2; // texture the title coarsens and stops binding keeps its levels until age retirement or the // budget takes the whole image. // -// SHARPEMU_METAL_V2_BASE_LEVEL=0 allocates every texture with its whole chain again. +// SHARPEMU_METAL_V2_BASE_LEVEL=0 allocates every texture with its whole chain again, except where upstream's +// resident levels keep the levels before BASE_LEVEL out because the guest has not mapped them +// (MetalImageCache.ResidentLevels.cs). internal sealed partial class MetalImageCache { // Finer levels that hold less than this are kept through a view rather than reallocated. @@ -108,16 +110,15 @@ internal static uint DesiredFirstLevel(in ImageDescription description, uint bas } // The same for an image the cache holds: only one that has been sampled and nothing else. - private static uint DesiredFirstLevel(MetalCachedImage image, uint baseLevel) + private static uint DesiredFirstLevel(MetalCachedImage image, uint baseLevel) => + HoldsGpuContents(image) ? 0 : DesiredFirstLevel(in image.Description, baseLevel); + + // An image that is a window view, or that something other than sampling used, holds its whole chain. + private static bool HoldsGpuContents(MetalCachedImage image) { var uses = image.Uses; - if (image.IsWindowLinearView || image.IsGpuModified || - uses.Storage || uses.RenderTarget || uses.DepthTarget || uses.VideoOut) - { - return 0; - } - - return DesiredFirstLevel(in image.Description, baseLevel); + return image.IsWindowLinearView || image.IsGpuModified || + uses.Storage || uses.RenderTarget || uses.DepthTarget || uses.VideoOut; } // The guest levels the image's texture holds, in the description's own level numbers. @@ -153,6 +154,12 @@ private void FitResidentLevelsLocked(MetalCachedImage image, in ImageViewDescrip var frame = _idleClock.Frames; var window = ShrinkWindowFrames << image.ShrinkBackoff; var desired = DesiredFirstLevel(image, view.BaseLevel); + if (desired < image.FirstLevel) + { + // Never grown into levels before the binding's that the guest has not mapped (ResidentLevels.cs). + desired = ResidentFloor(in image.Description, view.BaseLevel, desired, HoldsGpuContents(image)); + } + NoteNeededLevel(image, desired, frame, window); if (desired < image.FirstLevel) { @@ -170,8 +177,9 @@ private void FitResidentLevelsLocked(MetalCachedImage image, in ImageViewDescrip return; } + // Shrinking is the memory policy's; the resident-levels floor only ever keeps levels out. var needed = Math.Min(image.NeededLevel, image.NeededLevelBefore); - if (needed <= image.FirstLevel || frame - image.LevelsChangedFrame < window || + if (!BaseLevelAllocation || needed <= image.FirstLevel || frame - image.LevelsChangedFrame < window || LevelBytesBetween(in image.Description, image.FirstLevel, needed) < ShrinkMinimumBytes) { return; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.ConsumerRuns.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.ConsumerRuns.cs index ef7c89c69..11b3c15fe 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.ConsumerRuns.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.ConsumerRuns.cs @@ -208,7 +208,7 @@ private bool TryNarrowReloadRun(MetalCachedImage image, ulong staleStart, ulong return false; } - var source = _guestMemory.Resolve(description.Data.Address + runStart, runEnd - runStart); + var source = _guestMemory.Resolve(description.Data.Address + runStart, runEnd - runStart, whole: false, ImageRead); return source.IsValid && source.Size >= runEnd - runStart; } } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.ResidentLevels.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.ResidentLevels.cs new file mode 100644 index 000000000..8cc59ce20 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.ResidentLevels.cs @@ -0,0 +1,115 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.Gpu.Images; + +namespace SharpEmu.Gpu.Metal.V2; + +// Upstream's resident-mip images (ImageDescription.FirstLevel / HostExtent, ImageRequestBuilders.PartialMipChains, +// ResidentImageBacking), in the cache's one mechanism for a texture that holds part of its chain +// (MetalImageCache.BaseLevel.cs). +// +// Upstream describes a sampled texture whose T# starts past mip 0 from that level: Resources.Levels counts the levels +// from FirstLevel, the host image is HostExtent (Extent >> FirstLevel) with those levels, and a view's levels are +// host levels. A streamed texture maps only its resident mips (a tiled chain lays the small levels first and level 0 +// last, so they are a mapped prefix of the range), and its upload reads only their bytes, through ResidentImageBacking. +// Vulkan keeps such an image apart from the whole chain until the guest has mapped all of it (or another image over +// the range holds GPU contents), and makes a new one when the T# starts at a finer level. +// +// The Metal cache already holds a sampled texture from its BASE_LEVEL: the image's description stays the whole guest +// chain and only the texture, its upload and its page watch are cut (MetalCachedImage.FirstLevel, ResidentStart/End). +// That covers what upstream's image does - a texture of HostExtent with the levels from FirstLevel, viewed with guest +// level L as texture level L - FirstLevel, grown when a finer level is bound, never written back while cut - and more +// (a texture whose guest memory is all mapped is cut too, and a coarser binding shrinks it after a window of frames). +// So a resident-levels request is taken as the whole chain it is part of (ImageRequestBuilders.WithWholeMipChain: +// the view rebased onto guest levels), which keys it with every other request for those guest bytes, and the levels +// upstream would leave out become a floor on where the texture may start (ResidentFloor): while the guest has not +// mapped the chain, the texture never holds a level before the binding's BASE_LEVEL, whatever the memory policy +// (SHARPEMU_METAL_V2_BASE_LEVEL=0, a block-compressed base the policy would move to a block-aligned level) would +// choose. One mechanism decides the texture's levels; the request's FirstLevel is one of its inputs. +// +// SHARPEMU_METAL_V2_PARTIAL_MIP_CHAINS=0 (default on) leaves the request builders on whole chains, drops the floor and +// reads image bytes as before (a readable prefix, zeros after it) instead of through ResidentImageBacking. +internal sealed partial class MetalImageCache +{ + /// + /// Whether the cache takes upstream's resident-levels textures (and the backend asks the request builders for them: + /// MetalGpuBackend.ConfigureSharedGpuCode) and reads image bytes through . + /// Tests switch it. + /// + internal static bool PartialMipChains { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_PARTIAL_MIP_CHAINS") != "0"; + + private long _residentRequests; + private long _residentFloors; + private MetalGuestMemory.StagingRead? _imageRead; + + /// Requests described from a later level, and textures held from BASE_LEVEL because the chain is not mapped. + public (long Requests, long Floors) ResidentLevelCounters => + (Volatile.Read(ref _residentRequests), Volatile.Read(ref _residentFloors)); + + // The staged read of image bytes: ResidentImageBacking's policy, or the binding's prefix read with the switch off. + private MetalGuestMemory.StagingRead? ImageRead => PartialMipChains ? _imageRead ??= _guestMemory.ReadImageBacking : null; + + // A request described from its first resident level, as the whole guest chain it is part of: the same image as every + // other request for those bytes, viewed from the same guest level (BaseLevel.cs holds the texture from there). + private void TakeWholeChain(ref ImageRequest request) + { + if (request.Description.FirstLevel == 0) + { + return; + } + + request = ImageRequestBuilders.WithWholeMipChain(request); + Interlocked.Increment(ref _residentRequests); + } + + /// + /// Upstream's resident levels as a floor: a sampled texture whose binding starts at guest level + /// holds no level before it while the guest has not mapped the chain's whole range and + /// no image over it holds GPU contents (GuestImageCache.HoldsWholeChain), for any request the builder would describe + /// from that level (ImageRequestBuilders.Texture: no volume, multisample, metadata or depth). Returns + /// , the memory policy's choice (DesiredFirstLevel), raised to the base level when that holds. + /// Asked only when the policy chose a finer level than the binding's, which with the base-level cut on is a + /// block-compressed base it moved to a block-aligned level, and with it off is every texture bound past mip 0. + /// + private uint ResidentFloor(in ImageDescription description, uint baseLevel, uint level, bool gpuContents) + { + if (level >= baseLevel || !PartialMipChains || gpuContents || baseLevel >= description.Resources.Levels || + description.Resources.Levels > ImageDescription.MaxLevels || !ImageDescription.IsValidRange(description.Data) || + description.IsVolume || description.Samples != 1 || description.HasMetadata || description.IsDepth || + _backing.IsBackedRange(description.Data.Address, description.Data.Size)) + { + return level; + } + + Interlocked.Increment(ref _residentFloors); + return baseLevel; + } + + // Whether any image over a new texture's range holds what guest memory does not: upstream then takes the whole + // chain, sharing that image rather than reading guest memory into another. Asked before the overlaps are resolved, + // as upstream does, since resolving them may release those images. + private bool CandidatesHoldGpuContents(in ImageQueryResults candidates) + { + foreach (var candidate in candidates) + { + if (_slots.TryGet(candidate) is { } image && + (image.IsGpuModified || image.Uses.RenderTarget || image.Uses.Storage || image.Uses.DepthTarget)) + { + return true; + } + } + + return false; + } + + // The level a new sampled texture starts at: the memory policy, floored at the binding's base level while the + // guest has not mapped the chain. + private uint InsertFirstLevel(in ImageRequest request, bool gpuContents) + { + var baseLevel = request.View.BaseLevel; + var level = DesiredFirstLevel(in request.Description, baseLevel); + return level < baseLevel ? ResidentFloor(in request.Description, baseLevel, level, gpuContents) : level; + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.UploadPrelude.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.UploadPrelude.cs index a2697fe9d..bb164631f 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.UploadPrelude.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.UploadPrelude.cs @@ -82,7 +82,7 @@ private bool TryUploadInPrelude( return false; } - source = _guestMemory.Resolve(address, size); + source = _guestMemory.Resolve(address, size, whole: false, ImageRead); } if (!source.IsValid || source.Size < size) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index 822662bcc..4188ea8f3 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -259,6 +259,9 @@ private static bool IsValidRange(ulong address, ulong size) => /// public ResourceSlotIdentifier FindImage(ref ImageRequest request, bool exactFormat = false) { + // A texture described from its first resident level is looked up as its whole chain + // (MetalImageCache.ResidentLevels.cs); the request comes back that way, its view on guest levels. + TakeWholeChain(ref request); ValidateRequest(in request); if (ImageDescription.IsEmptyRange(request.Description.Data)) { @@ -290,6 +293,9 @@ public ResourceSlotIdentifier FindImage(ref ImageRequest request, bool exactForm private ResourceSlotIdentifier LookUpImageLocked(ref ImageRequest request, bool exactFormat) { var candidates = FindImagesInRange(request.Description.Data.Address, request.Description.Data.Size, pageOverlap: false); + // Whether a new sampled texture may start at its binding's level while the chain is not mapped (ResidentLevels.cs). + var gpuContents = request.Role == ImageRole.Texture && request.View.BaseLevel != 0 && PartialMipChains && + CandidatesHoldGpuContents(in candidates); var result = ResourceSlotIdentifier.Invalid; foreach (var candidate in candidates) { @@ -360,7 +366,7 @@ private ResourceSlotIdentifier LookUpImageLocked(ref ImageRequest request, bool var sampledOnly = request.Role == ImageRole.Texture; result = InsertImage( request.Description, sampledOnly, request.Role, - sampledOnly ? DesiredFirstLevel(in request.Description, request.View.BaseLevel) : 0, + sampledOnly ? InsertFirstLevel(in request, gpuContents) : 0, lossyAllowed: sampledOnly && ViewKeepsLossy(in request)); } @@ -3366,9 +3372,10 @@ internal static bool TryCoveringRun( // command buffers), a face came back as whatever the transient memory held before - stale bytes // read as half floats, NaN and Inf that the sky light and Lumen's history then kept, tinting the // characters of the Erlang cinematic white, purple, red, green or blue in about half the runs. + // A staged copy reads guest memory with the resident-backing policy (ImageRead, MetalImageCache.ResidentLevels.cs). private MetalGuestRange ResolveUploadSource(ulong address, ulong size, bool whole = false) { - var source = _guestMemory.Resolve(address, size, whole); + var source = _guestMemory.Resolve(address, size, whole, ImageRead); if (UploadGatherEnabled && source.IsValid && !_guestMemory.IsInPlace(source)) { var staged = Math.Min(size, source.Size); diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageBudgetTests.ResidentLevels.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageBudgetTests.ResidentLevels.cs new file mode 100644 index 000000000..5b9267ce2 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageBudgetTests.ResidentLevels.cs @@ -0,0 +1,341 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.HLE.GpuMemory; +using SharpEmu.Libs.Gpu.Abstractions; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Gpu.Images; +using SharpEmu.Libs.Gpu.Scheduling; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +/// +/// Upstream's resident-mip textures (ImageDescription.FirstLevel / HostExtent, ImageRequestBuilders.PartialMipChains, +/// ResidentImageBacking) on the Metal cache, through the real request builder: a streamed texture whose finer levels +/// the guest has not mapped is held from its first resident level and samples the right texels at each of them, grows +/// when more levels become resident, takes the whole chain once it is all mapped, and reads its guest bytes with the +/// Vulkan caches' hole policy. The base-level memory policy is switched off where a test is about the resident levels +/// alone, so only the port can keep the unmapped levels out (MetalImageCache.ResidentLevels.cs). +/// Mirrors upstream's ImageRequestBuildersTests.Texture_StreamedChainHoldsOnlyItsResidentLevels on the image cache. +/// +public sealed unsafe partial class MetalImageBudgetTests +{ + private const ulong StreamedAddress = GuestBase + 0x100000; + private const ulong ReferenceAddress = GuestBase + 0x200000; + + // ---- The capability ---------------------------------------------------------------- + + // The backend that composes the Metal cache asks the request builders for resident-levels textures, and + // SHARPEMU_METAL_V2_PARTIAL_MIP_CHAINS=0 keeps them on whole chains. + [Fact] + public void TheMetalBackendTurnsResidentLevelTexturesOnUnlessSwitchedOff() + { + var saved = (ImageRequestBuilders.PartialMipChains, ImageRequestBuilders.NativeColorClearMetadata, + SharpEmu.ShaderCompiler.Resources.ResourceMaterializer.CompiledTransactions, + SharpEmu.ShaderCompiler.Resources.ResourceMaterializer.SpecializationGuards, + SharpEmu.ShaderCompiler.Resources.ResourceTracker.UnvalidatedAddressWordsAreMemory, MetalImageCache.PartialMipChains); + try + { + MetalImageCache.PartialMipChains = true; + ImageRequestBuilders.PartialMipChains = false; + MetalGpuBackend.ConfigureSharedGpuCode(); + Assert.True(ImageRequestBuilders.PartialMipChains); + + MetalImageCache.PartialMipChains = false; + MetalGpuBackend.ConfigureSharedGpuCode(); + Assert.False(ImageRequestBuilders.PartialMipChains); + } + finally + { + (ImageRequestBuilders.PartialMipChains, ImageRequestBuilders.NativeColorClearMetadata, + SharpEmu.ShaderCompiler.Resources.ResourceMaterializer.CompiledTransactions, + SharpEmu.ShaderCompiler.Resources.ResourceMaterializer.SpecializationGuards, + SharpEmu.ShaderCompiler.Resources.ResourceTracker.UnvalidatedAddressWordsAreMemory, MetalImageCache.PartialMipChains) = saved; + } + } + + // ---- On the device ----------------------------------------------------------------- + + // A texture whose levels 0 and 1 are not mapped is described from level 2: a 64x64 texture of seven levels, whose + // view level k is guest level 2 + k, with the texels a whole chain of the same bytes has there. + [Fact] + public void AStreamedTextureIsHeldFromItsFirstResidentLevelAndSamplesEveryLevel() + { + if (!RequireDevice()) return; + using var scope = new ResidentLevelsScope(baseLevelCut: false); + using var rig = new Rig(Device.Value); + var reference = AcquireReference(rig, seed: 0x3D); + StreamIn(rig, StreamedAddress, residentFrom: 2, seed: 0x3D); + + var request = StreamedRequest(StreamedAddress, baseLevel: 2); + Assert.Equal(2u, request.Description.FirstLevel); + Assert.Equal(MipLevels - 2, request.Description.Resources.Levels); + Assert.Equal(MipSide >> 2, request.Description.HostExtent.Width); + Assert.Equal(0u, request.View.BaseLevel); + + var identifier = rig.Cache.FindImage(ref request); + // The request comes back as the whole chain it is part of, viewed from guest level 2. + Assert.Equal(0u, request.Description.FirstLevel); + Assert.Equal(MipLevels, request.Description.Resources.Levels); + Assert.Equal(2u, request.View.BaseLevel); + var view = rig.Cache.AcquireTextureView(identifier, request); + rig.Harness.Submit(); + rig.Harness.Begin(); + + var image = rig.Cache.GetImage(identifier); + Assert.Equal(2u, image.FirstLevel); + Assert.Equal(MipSide >> 2, image.Shape.Width); + Assert.Equal(MipSide >> 2, image.Shape.Height); + Assert.Equal(MipLevels - 2, image.Shape.MipLevels); + Assert.False(image.IsCpuDirty); + Assert.Equal(1L, rig.Cache.ResidentLevelCounters.Requests); + Assert.True(rig.Cache.ResidentLevelCounters.Floors >= 1); + Assert.Equal(image.AllocatedBytes + reference.AllocatedBytes, rig.Cache.TotalUsedMemory); + Assert.Equal(MipLevels - 2, (uint)MetalV2Native.SendValue(view, MetalNative.Selector("mipmapLevelCount"))); + for (uint level = 0; level < MipLevels - 2; level++) + { + Assert.Equal(ReadLevel(rig, reference.Texture, level + 2), ReadLevel(rig, view, level)); + } + } + + // The streamer maps a finer level and lowers the T#'s base: the same image grows to hold it, with the new level's + // texels and the old levels' unchanged; once the whole chain is mapped a texture bound past mip 0 holds it all. + [Fact] + public void ATextureWhoseFirstResidentLevelDropsGrowsWithTheNewLevelAndKeepsTheOld() + { + if (!RequireDevice()) return; + using var scope = new ResidentLevelsScope(baseLevelCut: false); + using var rig = new Rig(Device.Value); + var reference = AcquireReference(rig, seed: 0x52); + StreamIn(rig, StreamedAddress, residentFrom: 3, seed: 0x52); + + var (identifier, _) = AcquireStreamed(rig, StreamedAddress, baseLevel: 3); + var image = rig.Cache.GetImage(identifier); + Assert.Equal(3u, image.FirstLevel); + var before = image.AllocatedBytes; + + // Level 2 is mapped now (its bytes were laid out with the rest). + StreamIn(rig, StreamedAddress, residentFrom: 2, seed: 0x52, write: false); + var (grownId, grownView) = AcquireStreamed(rig, StreamedAddress, baseLevel: 2); + Assert.Equal(identifier, grownId); + Assert.Equal(2u, image.FirstLevel); + Assert.Equal(MipLevels - 2, image.Shape.MipLevels); + Assert.Equal(1, rig.Cache.BaseLevelCounters.Grows); + Assert.True(image.AllocatedBytes > before); + // The old texture is retired, not counted alongside. + Assert.Equal(image.AllocatedBytes + reference.AllocatedBytes, rig.Cache.TotalUsedMemory); + for (uint level = 0; level < MipLevels - 2; level++) + { + Assert.Equal(ReadLevel(rig, reference.Texture, level + 2), ReadLevel(rig, grownView, level)); + } + + // Everything mapped: a binding from level 1 takes the whole chain, as upstream's lookup does. + rig.GuestBacking.Unmapped.Clear(); + var (wholeId, wholeView) = AcquireStreamed(rig, StreamedAddress, baseLevel: 1); + Assert.Equal(identifier, wholeId); + Assert.Equal(0u, image.FirstLevel); + Assert.Equal(MipLevels, image.Shape.MipLevels); + Assert.Equal(ReadLevel(rig, reference.Texture, 1), ReadLevel(rig, wholeView, 0)); + Assert.Equal(ReadLevel(rig, reference.Texture, 2), ReadLevel(rig, wholeView, 1)); + } + + // An unmapped page inside the resident levels is not a level to invent: the upload stops as upstream's does, and + // with SHARPEMU_IMAGE_BACKING_HOLES=1 it reads the page as zero and uploads the rest. With the port switched off the + // read is the binding's readable prefix again. + [Fact] + public void AHoleInTheResidentLevelsStopsTheUploadUnlessHolesAreAllowed() + { + if (!RequireDevice()) return; + using var scope = new ResidentLevelsScope(baseLevelCut: false); + using var rig = new Rig(Device.Value); + var reference = AcquireReference(rig, seed: 0x64); + StreamIn(rig, StreamedAddress, residentFrom: 2, seed: 0x64); + var whole = StreamedRequest(StreamedAddress, baseLevel: 0).Description; + var holeOffset = (whole.MipLayout[2].Offset + whole.MipLayout[2].TailOffset) & ~0xFFFUL; + rig.GuestBacking.Unmapped.Add((StreamedAddress + holeOffset, 0x1000)); + + var request = StreamedRequest(StreamedAddress, baseLevel: 2); + var identifier = rig.Cache.FindImage(ref request); + // A fatal ends the process; on a speculative thread it abandons the work instead, which a test can see. + var refused = Assert.Throws( + () => GpuFatal.Speculatively(() => rig.Cache.AcquireTextureView(identifier, request))); + Assert.Contains("Could not read the mapped guest image backing", refused.Message); + var image = rig.Cache.GetImage(identifier); + Assert.Equal(2u, image.FirstLevel); + Assert.True(image.IsCpuDirty); + + MetalGuestMemory.ImageBackingHoles = true; + var view = rig.Cache.AcquireTextureView(identifier, request); + rig.Harness.Submit(); + rig.Harness.Begin(); + Assert.False(image.IsCpuDirty); + // The page held the start of level 2: zeros there, every later level as the guest has it. + Assert.NotEqual(ReadLevel(rig, reference.Texture, 2), ReadLevel(rig, view, 0)); + for (uint level = 1; level < MipLevels - 2; level++) + { + Assert.Equal(ReadLevel(rig, reference.Texture, level + 2), ReadLevel(rig, view, level)); + } + + MetalGuestMemory.ImageBackingHoles = false; + MetalImageCache.PartialMipChains = false; + _ = ((IGuestImageStore)rig.Cache).MarkCpuWrite(StreamedAddress + holeOffset, 8); + Assert.True(image.IsCpuDirty); + _ = rig.Cache.AcquireTextureView(identifier, request); + rig.Harness.Submit(); + rig.Harness.Begin(); + Assert.False(image.IsCpuDirty); + } + + // A block-compressed texture resident from a level that is not block-aligned (250x250 of a 1000x1000 BC1 chain) is + // held from that level: the memory policy would start at the 500x500 level, which the guest has not mapped. + [Fact] + public void ABlockCompressedTextureIsHeldFromAnUnalignedResidentLevel() + { + if (!RequireDevice()) return; + using var scope = new ResidentLevelsScope(baseLevelCut: true); + using var rig = new Rig(Device.Value); + const uint side = 1000; + const uint levels = 10; + var referenceRequest = StreamedRequest(ReferenceAddress, baseLevel: 0, GuestPixelFormat.Bc1UNorm, side, levels); + rig.WriteGuest(ReferenceAddress, MetalTileOracle.Pattern((int)referenceRequest.Description.Data.Size, 0x7A)); + var referenceId = rig.Cache.FindImage(ref referenceRequest); + _ = rig.Cache.AcquireTextureView(referenceId, referenceRequest); + var reference = rig.Cache.GetImage(referenceId); + + var whole = StreamedRequest(StreamedAddress, baseLevel: 0, GuestPixelFormat.Bc1UNorm, side, levels).Description; + Assert.Equal(1u, MetalImageCache.DesiredFirstLevel(in whole, 2)); + rig.WriteGuest(StreamedAddress, MetalTileOracle.Pattern((int)whole.Data.Size, 0x7A)); + Unmap(rig, StreamedAddress, in whole, residentFrom: 2); + // Level 1 lies past the mapped prefix, so only a texture from level 2 can be filled. + Assert.True(rig.Harness.Transfer.LevelBytes(in whole, 1).End > rig.GuestBacking.Unmapped[0].Start - StreamedAddress); + + var request = StreamedRequest(StreamedAddress, baseLevel: 2, GuestPixelFormat.Bc1UNorm, side, levels); + Assert.Equal(2u, request.Description.FirstLevel); + var identifier = rig.Cache.FindImage(ref request); + var view = rig.Cache.AcquireTextureView(identifier, request); + rig.Harness.Submit(); + rig.Harness.Begin(); + var image = rig.Cache.GetImage(identifier); + Assert.Equal(2u, image.FirstLevel); + Assert.Equal(side >> 2, image.Shape.Width); + Assert.Equal(levels - 2, image.Shape.MipLevels); + Assert.False(image.IsCpuDirty); + for (uint level = 0; level < levels - 2; level++) + { + Assert.Equal(ReadBlockLevel(rig, reference.Texture, side, level + 2), ReadBlockLevel(rig, view, side >> 2, level)); + } + } + + // ---- Helpers ----------------------------------------------------------------------- + + // Resident-levels requests from the builder, the port on, and the base-level memory policy as the test asks; + // everything as it was afterwards. + private sealed class ResidentLevelsScope : IDisposable + { + private readonly bool _builders = ImageRequestBuilders.PartialMipChains; + private readonly bool _cache = MetalImageCache.PartialMipChains; + private readonly bool _baseLevel = MetalImageCache.BaseLevelAllocation; + private readonly bool _holes = MetalGuestMemory.ImageBackingHoles; + + public ResidentLevelsScope(bool baseLevelCut) + { + ImageRequestBuilders.PartialMipChains = true; + MetalImageCache.PartialMipChains = true; + MetalImageCache.BaseLevelAllocation = baseLevelCut; + MetalGuestMemory.ImageBackingHoles = false; + } + + public void Dispose() + { + ImageRequestBuilders.PartialMipChains = _builders; + MetalImageCache.PartialMipChains = _cache; + MetalImageCache.BaseLevelAllocation = _baseLevel; + MetalGuestMemory.ImageBackingHoles = _holes; + } + } + + // The T# of a 64 KiB-swizzled 2D texture, by default the 256x256 RGBA8 nine-level chain of the base-level tests. + private static ImageRequest StreamedRequest( + ulong address, uint baseLevel, GuestPixelFormat format = GuestPixelFormat.Bits8_8_8_8UNorm, + uint side = MipSide, uint levels = MipLevels) + { + var words = new uint[8]; + var encoded = address >> 8; + words[0] = (uint)encoded; + words[1] = (uint)((encoded >> 32) & 0xFF) | ((uint)format << 20) | (((side - 1) & 0x3) << 30); + words[2] = ((side - 1) >> 2) | ((side - 1) << 14); + words[3] = 0xFAC | (baseLevel << 12) | ((levels - 1) << 16) | + ((uint)GuestTileMode.Standard64KB << 20) | ((uint)GuestImageType.Color2D << 28); + words[5] = (levels - 1) << 4; + return ImageRequestBuilders.Texture( + words, new ShaderImageShape(false, false, false, false, TextureNumericClass.Float)).Request; + } + + // Lays the chain's bytes out (a pattern of the seed) and unmaps the levels before residentFrom. + private static void StreamIn(Rig rig, ulong address, uint residentFrom, uint seed, bool write = true) + { + var whole = StreamedRequest(address, baseLevel: 0).Description; + if (write) + { + rig.WriteGuest(address, MetalTileOracle.Pattern((int)whole.Data.Size, seed)); + } + + Unmap(rig, address, in whole, residentFrom); + } + + // A tiled chain lays the small levels first: the levels from residentFrom are a prefix, the rest is unmapped. + private static void Unmap(Rig rig, ulong address, in ImageDescription whole, uint residentFrom) + { + Assert.True(address + whole.Data.Size <= ReferenceAddress, $"the chain (0x{whole.Data.Size:X}) reaches the reference"); + var (start, end) = rig.Harness.Transfer.LevelBytes(in whole, residentFrom); + Assert.Equal(0UL, start); + var mappedEnd = (end + 0xFFF) & ~0xFFFUL; + Assert.True(mappedEnd < whole.Data.Size); + rig.GuestBacking.Unmapped.Clear(); + rig.GuestBacking.Unmapped.Add((address + mappedEnd, whole.Data.Size - mappedEnd)); + } + + // The whole chain of the same bytes, at an address nothing unmaps. + private static MetalCachedImage AcquireReference(Rig rig, uint seed) + { + var request = StreamedRequest(ReferenceAddress, baseLevel: 0); + Assert.True(ReferenceAddress + request.Description.Data.Size <= GuestBase + Backing.Size); + rig.WriteGuest(ReferenceAddress, MetalTileOracle.Pattern((int)request.Description.Data.Size, seed)); + var identifier = rig.Cache.FindImage(ref request); + _ = rig.Cache.AcquireTextureView(identifier, request); + rig.Harness.Submit(); + rig.Harness.Begin(); + var image = rig.Cache.GetImage(identifier); + Assert.Equal(0u, image.FirstLevel); + return image; + } + + private static (ResourceSlotIdentifier Image, nint View) AcquireStreamed(Rig rig, ulong address, uint baseLevel) + { + var request = StreamedRequest(address, baseLevel); + var identifier = rig.Cache.FindImage(ref request); + var view = rig.Cache.AcquireTextureView(identifier, request); + rig.Harness.Submit(); + rig.Harness.Begin(); + return (identifier, view); + } + + // One level of a BC1 texture whose level 0 is `side` texels wide, as its 8-byte blocks. + private static byte[] ReadBlockLevel(Rig rig, nint texture, uint side, uint level) + { + var texels = Math.Max(side >> (int)level, 1); + var blocks = (texels + 3) / 4; + var rowBytes = (ulong)blocks * 8; + var buffer = rig.Harness.Buffer(rowBytes * blocks); + var blit = rig.Harness.Tiler.BeginBlit(rig.Harness); + MetalNative.SendCopyTextureToBufferOptions(blit, SelCopyLevelToBuffer, + texture, 0, level, default, new MtlSize { Width = texels, Height = texels, Depth = 1 }, + buffer, 0, (nuint)rowBytes, (nuint)(rowBytes * blocks), (nuint)MtlBlitOption.None); + MetalTiler.EndEncoding(blit); + rig.Harness.Submit(); + rig.Harness.Begin(); + return rig.Harness.Read(buffer, 0, rowBytes * blocks); + } +} diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageBudgetTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageBudgetTests.cs index 3cf9cbda3..496a4d66f 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageBudgetTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageBudgetTests.cs @@ -447,6 +447,23 @@ private sealed class Backing : IGuestBackedSpace, IDisposable private bool Contains(ulong address, ulong length) => address >= GuestBase && address - GuestBase + length <= Size; + // Guest ranges the guest has not mapped (a streamed texture's finer levels): not backed, not readable, no + // window. Writes still land, so a test lays its bytes out before it unmaps them. + public List<(ulong Start, ulong Bytes)> Unmapped { get; } = []; + + private bool Mapped(ulong address, ulong length) + { + foreach (var (start, bytes) in Unmapped) + { + if (address < start + bytes && start < address + length) + { + return false; + } + } + + return true; + } + // Guest memory the GPU has no window onto: nothing can be written back into it. public bool NoWindows { get; set; } @@ -490,14 +507,14 @@ private ulong SpanAt(ulong address) public bool TryMapBacked(ulong address, ulong size, ulong backingOffset, GuestPageProtection protection, out HostViewFailure failure) { failure = HostViewFailure.None; return false; } public bool TryUnmapBacked(ulong address, ulong size) => false; public bool TryClearBacking(ulong offset, ulong size) => false; - public bool IsBackedView(ulong address) => Contains(address, 1); - public bool IsBackedRange(ulong address, ulong size) => Contains(address, size); + public bool IsBackedView(ulong address) => Contains(address, 1) && Mapped(address, 1); + public bool IsBackedRange(ulong address, ulong size) => Contains(address, size) && Mapped(address, size); public (ulong Base, ulong Size) BackingAliasRange => ((ulong)_block, Size); public bool TryResolveBackingAlias(ulong address, ulong size, out ulong alias) { var hole = HoleBytes != 0 && address < HoleStart + HoleBytes && HoleStart < address + size; - alias = !NoWindows && !hole && Contains(address, size) && size <= SpanAt(address) + alias = !NoWindows && !hole && Contains(address, size) && Mapped(address, size) && size <= SpanAt(address) ? (ulong)_block + Offset(address) : 0; return alias != 0; @@ -521,7 +538,7 @@ public bool TryWriteBacking(ulong address, ReadOnlySpan data) public bool TryReadBacking(ulong address, Span data) { - if (!Contains(address, (ulong)data.Length)) return false; + if (!Contains(address, (ulong)data.Length) || !Mapped(address, (ulong)data.Length)) return false; for (var done = 0; done < data.Length;) { var length = (int)Math.Min((ulong)(data.Length - done), SpanAt(address + (ulong)done)); From 68dfc257b6a28f165819c049a5d2a6045d4ddf5b Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 23:44:10 +0000 Subject: [PATCH 074/134] [Metal] Replay repeated draws and dispatches on the Metal host Upstream f1af467a6 added draw and dispatch replay: the shared engine seals a draw or dispatch, and when the next command item repeats it in all but its user data (RenderRecorder.StageInputMismatch, SameVertexInput) it skips preparing and binding and asks the host to bind what the sealed item bound. Until now the Metal host kept the interface defaults (CurrentItemSequence 0), so the engine refused every seal there. MetalRenderHost.Replay.cs implements the host half on Metal's binding model: - CurrentItemSequence counts command-thread items. A batch boundary and relay commands run between items move it too, so they break the chain. - At the seal the host captures what the last CommitBindings bound: each stage's argument-buffer ring range, the used resources, the read-only buffer ranges, and the vertex streams mapped to the ranges they were obtained from. Stages with movie planes, storage images, unstamped textures, bindless tables, device addresses, written buffers (draws), or argument fields written per item are refused by name and never captured. - Before binding anything, a replay checks that what the capture stood on still holds: the same command buffer (the ring ranges), the same render pass (draws, upstream's scope rule), no PrepareBindings since on the stage object, the image cache's binding epoch and image set as at the stage's BindResources with no deferred refresh, and every read-only buffer and vertex stream still answered by the read-binding memo with the same range. Any miss is counted by name and the item takes the full path. - A replayed draw patches its own user data into the captured shader data. A replayed dispatch rebuilds its shader data from its own snapshot, thread limits and call data. A dispatch that writes runs BindResources' buffer loop again (BindStageStorageBuffer, extracted for this), so each written range's invalidation and write record still happen. If a range changed, the argument buffer is written again ("rebound"). - BufferOwnerGeneration stays 0 and RebindBuffers does nothing. Metal has no buffer owners. A window a move replaces stays alive until its submission completes, so no binding is retired while an item is being prepared. The push-data publication moved out of CommitBindings (PublishPushData) so a replay publishes its block the same way. The [METAL-V2][TBDR] line now reports replay_host=(...) and dispatch_replay_host=(...). Upstream's switches SHARPEMU_DRAW_REPLAY / SHARPEMU_DISPATCH_REPLAY (default on) turn it off. --- .../V2/MetalRenderHost.CommandThread.cs | 7 + .../V2/MetalRenderHost.Descriptors.cs | 289 ++--- .../V2/MetalRenderHost.Replay.cs | 1026 +++++++++++++++++ .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 12 +- 4 files changed, 1194 insertions(+), 140 deletions(-) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Replay.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CommandThread.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CommandThread.cs index 737efca9b..e6364fc09 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CommandThread.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CommandThread.cs @@ -67,6 +67,9 @@ private void RunCommandThreadBatch() Console.Error.WriteLine($"[METAL-V2][QOS] command_stream requested=UserInteractive applied={_commandThread.HasHostQos}."); } + // Whatever the worker did since the last batch is not an item: the first item of this one does not follow the + // last of the batch before (MetalRenderHost.Replay.cs). + _replayItemSequence++; var deadline = System.Diagnostics.Stopwatch.GetTimestamp() + System.Diagnostics.Stopwatch.Frequency / 100; int ran; using (SharpEmu.Libs.VideoOut.RenderPhaseProfile.Measure(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.CommandStream)) @@ -123,11 +126,15 @@ private void RequestIdleCommit() // held: they change the caches it reads. private void RunRelayBetweenCommandItems() { + // An item ended; relay commands run between items count as one more (MetalRenderHost.Replay.cs). + _replayItemSequence++; if (!_relay.HasPendingCommands) { return; } + _replayItemSequence++; + var prefetch = _translation?.Prefetch; prefetch?.Pause(); try diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs index 07f89eb48..f171d3e96 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs @@ -424,6 +424,7 @@ internal void ClearTextureMemo() private void RememberTexture(MetalStageBindings stage, int index, ResourceSlotIdentifier identifier, in ImageRequest request, in MetalImageCache.TextureMemoStamp stamp) { + NoteReplayStamped(stage, index); var key = stage.MemoKeys[index]; if (!_textureMemo.TryGetValue(key, out var entry)) { @@ -471,6 +472,7 @@ public IPreparedBindings PrepareBindings(ShaderStageResources stage) var shaderDwords = checked((int)layout.ShaderDataDwordCount); prepared.EnsureCapacity(info.Images.Count, info.Samplers.Count, info.Buffers.Count, shaderDwords); _preparedStageMask |= 1 << stageIndex; + _stagePrepares[stageIndex]++; var movie = FindHostMovieBindings(info, snapshot); prepared.MovieLuma = movie.Luma; prepared.MovieChroma = movie.Chroma; @@ -952,6 +954,7 @@ public void BindResources(IPreparedBindings prepared) var info = stage.Program.Resources!.Info; var snapshot = stage.StageResources.Resources; NoteBindShape(stage, snapshot); + NoteReplayBindStart(stage); // A staged label read checks the stage's other bindings for writes over it (MetalRenderHost.LabelStagedReads.cs). BeginLabelStagedStage(stage.Program.Stage == ShaderStageKind.Compute ? stage : null); for (var index = 0; index < stage.ImageCount; index++) @@ -1025,136 +1028,144 @@ public void BindResources(IPreparedBindings prepared) for (var index = 0; index < stage.BufferCount; index++) { - var words = snapshot.Buffers[index]; - if (words.Length < 4) - { - throw Fatal( - $"A buffer descriptor is too short: buffer={index} words={words.Length} hash=0x{stage.Program.Hash:X16}."); - } + BindStageStorageBuffer(stage, index, info, snapshot); + } - var descriptor = BufferDescriptorWords.From(words); - var requested = descriptor.Footprint() ?? throw Fatal( - $"A storage buffer descriptor footprint overflows: buffer={index} stride={descriptor.Stride} " + - $"records={descriptor.RecordCount} hash=0x{stage.Program.Hash:X16}."); - if (descriptor.Address == 0 || requested == 0) - { - stage.Buffers[index] = default; - stage.BufferLengths[index] = 0; - continue; - } + using (var deviceScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.BindingDeviceAddresses)) + { + BindDeviceAddressRanges(stage, info, snapshot); + } + if (snapshot.BindlessImages.Length != 0 || stage.Program.Bindings!.BindlessImageTableCount != 0) + { + BindBindlessImages(stage, info, snapshot); + } + } - var written = info.Buffers[index].Written; - var computeStage = stage.Program.Stage == ShaderStageKind.Compute; - using var overlapTag = SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Tag( - written ? SharpEmu.HLE.GpuMemory.OverlapTag.StorageWritten - : info.Buffers[index].Scalar ? SharpEmu.HLE.GpuMemory.OverlapTag.Constant - : SharpEmu.HLE.GpuMemory.OverlapTag.StorageRead); - if (written) - { - _writtenBufferBinds++; - } - else + // One storage buffer of a stage, as BindResources binds it: a read-only range the binding before it answered + // (MetalRenderHost.ReadBindingMemo.cs), or the whole chain (flush, resolve, and for a written range its + // invalidation and write record). A replayed dispatch that writes takes it again for every buffer (MetalRenderHost.Replay.cs). + private void BindStageStorageBuffer(MetalStageBindings stage, int index, ShaderResourceInfo info, ResourceSnapshot snapshot) + { + var words = snapshot.Buffers[index]; + if (words.Length < 4) + { + throw Fatal( + $"A buffer descriptor is too short: buffer={index} words={words.Length} hash=0x{stage.Program.Hash:X16}."); + } + + var descriptor = BufferDescriptorWords.From(words); + var requested = descriptor.Footprint() ?? throw Fatal( + $"A storage buffer descriptor footprint overflows: buffer={index} stride={descriptor.Stride} " + + $"records={descriptor.RecordCount} hash=0x{stage.Program.Hash:X16}."); + if (descriptor.Address == 0 || requested == 0) + { + stage.Buffers[index] = default; + stage.BufferLengths[index] = 0; + return; + } + + var written = info.Buffers[index].Written; + var computeStage = stage.Program.Stage == ShaderStageKind.Compute; + using var overlapTag = SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Tag( + written ? SharpEmu.HLE.GpuMemory.OverlapTag.StorageWritten + : info.Buffers[index].Scalar ? SharpEmu.HLE.GpuMemory.OverlapTag.Constant + : SharpEmu.HLE.GpuMemory.OverlapTag.StorageRead); + if (written) + { + _writtenBufferBinds++; + } + else + { + _readOnlyBufferBinds++; + // A range bound read-only before, whose binding still stands (MetalRenderHost.ReadBindingMemo.cs): + // mapped whole, nothing to flush or order, the same window. + if (TryReadBindingMemo(descriptor.Address, requested, computeStage, out var memo)) { - _readOnlyBufferBinds++; - // A range bound read-only before, whose binding still stands (MetalRenderHost.ReadBindingMemo.cs): - // mapped whole, nothing to flush or order, the same window. - if (TryReadBindingMemo(descriptor.Address, requested, computeStage, out var memo)) + if (ReadBindingMemoVerify) { - if (ReadBindingMemoVerify) - { - VerifyReadBinding(descriptor.Address, requested, computeStage, MetalWritebackCause.StorageDescriptor, memo); - } - - stage.Buffers[index] = memo; - stage.BufferLengths[index] = BoundBufferBytes(requested, memo); - continue; + VerifyReadBinding(descriptor.Address, requested, computeStage, MetalWritebackCause.StorageDescriptor, memo); } - } - // A range mapped whole - nearly every binding - is answered by one query; ClampMappedSize - // asks again from its first byte only for a range that runs past its mapping. - bool readable; - bool mappedWhole; - using (var checkScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.BindingBufferCheck)) - { - var inRange = requested <= ulong.MaxValue - descriptor.Address; - mappedWhole = inRange && _memory.CanRead(descriptor.Address, requested); - readable = mappedWhole || (inRange && _memory.CanRead(descriptor.Address, 1)); + stage.Buffers[index] = memo; + stage.BufferLengths[index] = BoundBufferBytes(requested, memo); + return; } + } - if (!readable) - { - var resource = info.Buffers[index]; - throw Fatal( - $"The buffer range starts in unmapped memory: address=0x{descriptor.Address:X16} size=0x{requested:X16} " + - $"stage={stage.Program.Stage} hash=0x{stage.Program.Hash:X16} shader=0x{stage.StageResources.ShaderBase:X16} " + - $"buffer={index} source={resource.Source} pc=0x{resource.FirstUsePc:X} written={resource.Written} " + - $"descriptor=[{string.Join(',', words.ToArray().Select(word => $"{word:X8}"))}] " + - $"user_data=[{string.Join(',', snapshot.UserData.ToArray().Select(word => $"{word:X8}"))}]."); - } + // A range mapped whole - nearly every binding - is answered by one query; ClampMappedSize + // asks again from its first byte only for a range that runs past its mapping. + bool readable; + bool mappedWhole; + using (var checkScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.BindingBufferCheck)) + { + var inRange = requested <= ulong.MaxValue - descriptor.Address; + mappedWhole = inRange && _memory.CanRead(descriptor.Address, requested); + readable = mappedWhole || (inRange && _memory.CanRead(descriptor.Address, 1)); + } - var size = mappedWhole ? requested : ClampMappedSize(descriptor.Address, requested); - var memoStamp = !written && mappedWhole && ReadBindingMemoEnabled ? ReadBindingStamp() : default; - var flushFoundImage = _imageCache.FlushGpuWrites(descriptor.Address, size, MetalWritebackCause.StorageDescriptor, written); - var range = ResolveStorageBuffer(descriptor.Address, size, written, computeStage, out var inPlaceAlias, out var inPlaceWindow); - if (!written && mappedWhole && ReadBindingMemoEnabled) + if (!readable) + { + var resource = info.Buffers[index]; + throw Fatal( + $"The buffer range starts in unmapped memory: address=0x{descriptor.Address:X16} size=0x{requested:X16} " + + $"stage={stage.Program.Stage} hash=0x{stage.Program.Hash:X16} shader=0x{stage.StageResources.ShaderBase:X16} " + + $"buffer={index} source={resource.Source} pc=0x{resource.FirstUsePc:X} written={resource.Written} " + + $"descriptor=[{string.Join(',', words.ToArray().Select(word => $"{word:X8}"))}] " + + $"user_data=[{string.Join(',', snapshot.UserData.ToArray().Select(word => $"{word:X8}"))}]."); + } + + var size = mappedWhole ? requested : ClampMappedSize(descriptor.Address, requested); + var memoStamp = !written && mappedWhole && ReadBindingMemoEnabled ? ReadBindingStamp() : default; + var flushFoundImage = _imageCache.FlushGpuWrites(descriptor.Address, size, MetalWritebackCause.StorageDescriptor, written); + var range = ResolveStorageBuffer(descriptor.Address, size, written, computeStage, out var inPlaceAlias, out var inPlaceWindow); + if (!written && mappedWhole && ReadBindingMemoEnabled) + { + StoreReadBinding(descriptor.Address, size, computeStage, memoStamp, flushFoundImage, inPlaceAlias, inPlaceWindow, range); + } + + // The text is built only when the trace is on: this runs per storage buffer per draw. + if (_traceBufferUserAddress != 0) + { + TraceBufferUser(stage, $"storage[{index}]{(written ? " written" : string.Empty)}", descriptor.Address, size); + } + + TraceRecordChain(stage, index, descriptor.Address, size); + TraceBufferAtCompletion(stage, index, descriptor.Address, size); + if (written) + { + using var writtenScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.BindingWrittenBuffer); + // The text is built only when the trace prints it: this runs per written buffer per draw. + if (MetalImageCache.TracesDccWriter(descriptor.Address, size)) { - StoreReadBinding(descriptor.Address, size, computeStage, memoStamp, flushFoundImage, inPlaceAlias, inPlaceWindow, range); + _imageCache.TraceDccWriter( + descriptor.Address, size, + $"program=0x{stage.Program.Hash:X16} buffer={index} stride={descriptor.Stride} records={descriptor.RecordCount} " + + $"format={descriptor.Format} buffers={stage.BufferCount} user_data=[{string.Join(',', snapshot.UserData.ToArray().Select(word => $"{word:X8}"))}]"); } - // The text is built only when the trace is on: this runs per storage buffer per draw. - if (_traceBufferUserAddress != 0) + using (var invalidateScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.BindingWrittenInvalidate)) { - TraceBufferUser(stage, $"storage[{index}]{(written ? " written" : string.Empty)}", descriptor.Address, size); + _imageCache.InvalidateMemoryFromGpu(descriptor.Address, size); } - TraceRecordChain(stage, index, descriptor.Address, size); - TraceBufferAtCompletion(stage, index, descriptor.Address, size); - if (written) + using (var noteScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.BindingWrittenNote)) { - using var writtenScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.BindingWrittenBuffer); - // The text is built only when the trace prints it: this runs per written buffer per draw. - if (MetalImageCache.TracesDccWriter(descriptor.Address, size)) - { - _imageCache.TraceDccWriter( - descriptor.Address, size, - $"program=0x{stage.Program.Hash:X16} buffer={index} stride={descriptor.Stride} records={descriptor.RecordCount} " + - $"format={descriptor.Format} buffers={stage.BufferCount} user_data=[{string.Join(',', snapshot.UserData.ToArray().Select(word => $"{word:X8}"))}]"); - } - - using (var invalidateScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.BindingWrittenInvalidate)) + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) { - _imageCache.InvalidateMemoryFromGpu(descriptor.Address, size); + SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.SetWriter(stage.Program.Hash); } - using (var noteScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.BindingWrittenNote)) - { - if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled) - { - SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.SetWriter(stage.Program.Hash); - } - - NoteGuestMemoryWrite(descriptor.Address, size, MetalGpuWriteOrigin.StorageBuffer); - } + NoteGuestMemoryWrite(descriptor.Address, size, MetalGpuWriteOrigin.StorageBuffer); } - - using var reportScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.BindingReport); - _slotTrap?.NoteBinding( - $"storage[{index}] hash=0x{stage.Program.Hash:X16}{(written ? " written" : string.Empty)}", - descriptor.Address, size, (ulong)range.Buffer, range.Offset, range.GpuAddress); - stage.Buffers[index] = range; - stage.BufferLengths[index] = BoundBufferBytes(size, range); - ReportBufferBinding(stage, index, in descriptor, requested, size, range); } - using (var deviceScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.BindingDeviceAddresses)) - { - BindDeviceAddressRanges(stage, info, snapshot); - } - if (snapshot.BindlessImages.Length != 0 || stage.Program.Bindings!.BindlessImageTableCount != 0) - { - BindBindlessImages(stage, info, snapshot); - } + using var reportScope = SharpEmu.Libs.VideoOut.RenderPhaseProfile.MeasureDetail(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.BindingReport); + _slotTrap?.NoteBinding( + $"storage[{index}] hash=0x{stage.Program.Hash:X16}{(written ? " written" : string.Empty)}", + descriptor.Address, size, (ulong)range.Buffer, range.Offset, range.GpuAddress); + stage.Buffers[index] = range; + stage.BufferLengths[index] = BoundBufferBytes(size, range); + ReportBufferBinding(stage, index, in descriptor, requested, size, range); } /// @@ -1641,36 +1652,46 @@ public void CommitBindings(GpuBindPoint bindPoint, in PipelineHandle pipeline, R if (hasPushData) { - var pushBytes = System.Runtime.InteropServices.MemoryMarshal.AsBytes(pushData); - MetalGuestRange range; - if (gpuLimitsPushDword >= 0) - { - range = _guestMemory.Allocate(PushData.ByteSize, 256, out var span); - pushBytes.CopyTo(span); - _threadLimitsTarget = range with - { - Offset = range.Offset + ((ulong)gpuLimitsPushDword * sizeof(uint)), - Size = 3 * sizeof(uint), - }; - } - else if (ArgumentBufferReuse && _pushRegions.TryFind(pushBytes, _submissionSerial, out var found)) + PublishPushData(pushData, gpuLimitsPushDword); + } + + CaptureBindingReplay(bindPoint, stages, gpuLimitsPushDword); + } + + // The push-data block of the committed stages as one buffer range (_pushBuffer, _pushOffset): one this command + // buffer already holds when its bytes are the same (ArgumentBufferReuse), else a new ring range. A dispatch whose + // thread limits the GPU writes gets a range of its own. A replayed draw or dispatch publishes its block here too. + private void PublishPushData(ReadOnlySpan pushData, int gpuLimitsPushDword) + { + var pushBytes = System.Runtime.InteropServices.MemoryMarshal.AsBytes(pushData); + MetalGuestRange range; + if (gpuLimitsPushDword >= 0) + { + range = _guestMemory.Allocate(PushData.ByteSize, 256, out var span); + pushBytes.CopyTo(span); + _threadLimitsTarget = range with { - range = found; - } - else + Offset = range.Offset + ((ulong)gpuLimitsPushDword * sizeof(uint)), + Size = 3 * sizeof(uint), + }; + } + else if (ArgumentBufferReuse && _pushRegions.TryFind(pushBytes, _submissionSerial, out var found)) + { + range = found; + } + else + { + range = _guestMemory.Allocate(PushData.ByteSize, 256, out var span); + pushBytes.CopyTo(span); + if (ArgumentBufferReuse) { - range = _guestMemory.Allocate(PushData.ByteSize, 256, out var span); - pushBytes.CopyTo(span); - if (ArgumentBufferReuse) - { - _pushRegions.Add(pushBytes, _submissionSerial, in range); - } + _pushRegions.Add(pushBytes, _submissionSerial, in range); } - - _pushBuffer = range.Buffer; - _pushOffset = range.Offset; - _hasPushData = true; } + + _pushBuffer = range.Buffer; + _pushOffset = range.Offset; + _hasPushData = true; } // The stage's Tier 2 argument buffer, mirroring the binding layout in descriptor order. diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Replay.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Replay.cs new file mode 100644 index 000000000..3e107809a --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Replay.cs @@ -0,0 +1,1026 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers; +using SharpEmu.Libs.Gpu.Abstractions; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.ShaderCompiler.Metal; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.Gpu.Metal.V2; + +/// +/// Draw and dispatch replay on the Metal host: the host half of RenderRecorder.TryReplayDraw and +/// RenderRecorder.TryReplayDispatch (the Vulkan presenter's is VulkanVideoPresenter.DrawReplay.cs). +/// +/// The engine seals a draw (dispatch) whose bindings a next item may repeat, and when the next item repeats the +/// previous one's programs, descriptor words, vertex input and targets (RenderRecorder.StageInputMismatch and +/// SameVertexInput, which compare everything but the user data and, for a dispatch, the thread limits) it skips +/// preparing and binding them and asks the host to bind what the sealed item bound. The host answers true only when +/// what it binds is exactly what PrepareBindings, BindResources, BindVertexBuffers and CommitBindings would have +/// bound for the item; every refusal is counted by name and comes before anything is changed, so a refused item +/// takes the full path as if replay did not exist. +/// +/// What the sealed item bound, and why it still stands: +/// +/// The argument buffer of each stage: ring ranges of the command buffer the item was recorded into. They hold +/// while the submission serial is the same (the ring is only reused after its command buffer completes), and their +/// bytes are what WriteArgumentBuffer would write while every resolved binding they name is unchanged (below) and +/// the argument plan names nothing else that moves: a stage whose plan has a pointer field (GDS, device-address +/// page table, fault buffer, flattened table, shader data, mip statistics), a word field other than the constant +/// fault-buffer word, or a bindless image table is never captured. +/// The textures: every image binding of the stage was a texture-memo hit or was memoised by its acquire, so +/// each had a stamp (MetalImageCache.TryStampTextureLocked: no DCC read, no stencil plane, bounded aliases), and +/// the image cache's binding epoch and image set did not move from the start of the stage's BindResources to the +/// commit. While they still have not moved, no deferred refresh waits and the submission serial is the same, +/// nothing a binding of a cached image resolves to has changed and each image already notes this submission's use +/// (the bindless table memo's rule, MetalRenderHost.BindlessImages.cs). Storage images, host-movie planes and +/// unstamped bindings are never captured: their acquire is not memoised. +/// The read-only storage buffers and vertex streams: each is looked up again in the read-binding memo +/// (MetalRenderHost.ReadBindingMemo.cs), which answers only while the full chain would do nothing and give the same +/// window range (remaps, window cuts, single-copy holes and traps, images over the range, deferred fills, label and +/// staged copies). A miss, or a hit on another range, refuses. A vertex stream's mapped size is clamped again. +/// Written storage buffers (dispatches only; a replayable draw writes nothing): their invalidation and write +/// record must run for every dispatch, so the replay takes the same chain BindResources takes +/// (BindStageStorageBuffer) after every refusal check has passed; a range other than the captured one rewrites the +/// stage's argument buffer instead of reusing it. +/// The push data: the captured stage's shader data with the new item's user data (a dispatch: its shader data +/// built again from its own snapshot, thread limits and call data), published as CommitBindings publishes it. +/// The stage objects themselves (MetalStageBindings, one per stage kind): no PrepareBindings may have run for +/// the stage kind since the capture. +/// +/// A draw is also refused when the render pass it was sealed in has ended (upstream's scope rule): binding state is +/// re-sent to whatever encoder is open, but a pass end can land copies and write-backs the captured state does not +/// see. The item sequence counts the command thread's items (MetalRenderHost.CommandThread.cs): a batch boundary or +/// relay commands between two items break the chain, and the slice mode (SHARPEMU_METAL_V2_COMMAND_THREAD=0) has +/// no sequence, so nothing replays there. +/// +/// Replay lives wholly in the GPU process: the shared engine and this host both run there (SplitGpuHost composes +/// MetalV2Backend in process B and runs the submitted command streams itself), so nothing of it crosses the split. +/// SHARPEMU_DRAW_REPLAY=0 / SHARPEMU_DISPATCH_REPLAY=0 (upstream's switches, read by the engine too) turn it off. +/// +internal sealed partial class MetalRenderHost +{ + internal bool DrawReplayEnabled { get; set; } = Environment.GetEnvironmentVariable("SHARPEMU_DRAW_REPLAY") != "0"; + + internal bool DispatchReplayEnabled { get; set; } = Environment.GetEnvironmentVariable("SHARPEMU_DISPATCH_REPLAY") != "0"; + + /// + /// Tests: runs when a replay is asked for (true for a dispatch), before any check, as work a completion or another + /// thread does between two items would. + /// + internal Action? ReplayProbe { get; set; } + + // Moves with every command-thread item, every relay run between items and every batch (MetalRenderHost.CommandThread.cs). + private long _replayItemSequence; + + // PrepareBindings calls per stage kind: a stage object is the captured one only while its count stands. + private readonly long[] _stagePrepares = new long[StageCount]; + + // Per stage kind, the image cache's binding epoch and image set when its last BindResources began, and the + // images whose acquire memoised a stamp in it (bit per image). + private readonly long[] _replayBindEpoch = new long[StageCount]; + private readonly long[] _replayBindImageSet = new long[StageCount]; + private readonly ulong[] _replayStamped = new ulong[StageCount]; + + // The last CommitBindings: its count, bind point, stages and whether each stage's images settled (the epoch and + // image set as at its BindResources' start, no refresh waiting). + private long _replayCommits; + private GpuBindPoint _replayCommitPoint; + private readonly MetalStageBindings?[] _replayCommitStages = new MetalStageBindings?[2]; + private int _replayCommitStageCount; + private readonly bool[] _replayCommitSettled = new bool[2]; + private int _replayCommitLimitsDword; + + // ClampMappedSize and ObtainBuffer since the last BindResources, for mapping the vertex streams to their ranges. + private readonly record struct ReplayClamp(ulong Address, ulong Requested, ulong Size); + + private readonly record struct ReplayObtain(ulong Address, ulong Size, bool Written, BufferBinding Binding); + + private const int ReplayRecordLimit = 64; + private readonly ReplayClamp[] _replayClamps = new ReplayClamp[ReplayRecordLimit]; + private readonly ReplayObtain[] _replayObtains = new ReplayObtain[ReplayRecordLimit]; + private int _replayClampCount; + private int _replayObtainCount; + private bool _replayRecordsOverflowed; + + private sealed class ReplayStage + { + public MetalStageBindings Bindings = null!; + public int StageIndex; + public long Prepares; + public long BindingEpoch; + public long ImageSet; + public nint ArgumentBuffer; + public ulong ArgumentOffset; + public bool ArgumentValid; + public bool UsesDeviceAddresses; + public BindingLayout Layout = null!; + public uint UserDataBase; + + // The read-only buffers: index, guest address, requested footprint and the range bound. + public int ReadCount; + public int[] ReadIndex = new int[8]; + public ulong[] ReadAddress = new ulong[8]; + public ulong[] ReadRequested = new ulong[8]; + public MetalGuestRange[] ReadRange = new MetalGuestRange[8]; + + // The written buffers (dispatch): index and the range bound. + public int WrittenCount; + public int[] WrittenIndex = new int[4]; + + public void AddRead(int index, ulong address, ulong requested, in MetalGuestRange range) + { + if (ReadCount == ReadIndex.Length) + { + Array.Resize(ref ReadIndex, ReadCount * 2); + Array.Resize(ref ReadAddress, ReadCount * 2); + Array.Resize(ref ReadRequested, ReadCount * 2); + Array.Resize(ref ReadRange, ReadCount * 2); + } + + ReadIndex[ReadCount] = index; + ReadAddress[ReadCount] = address; + ReadRequested[ReadCount] = requested; + ReadRange[ReadCount] = range; + ReadCount++; + } + + public void AddWritten(int index) + { + if (WrittenCount == WrittenIndex.Length) + { + Array.Resize(ref WrittenIndex, WrittenCount * 2); + } + + WrittenIndex[WrittenCount] = index; + WrittenCount++; + } + } + + private sealed class ReplayCapture + { + public bool Sealed; + public long Commit = -1; + public readonly ReplayStage[] Stages = [new(), new()]; + public int StageCount; + public nint[] Used = new nint[16]; + public nuint[] UsedUsage = new nuint[16]; + public int UsedCount; + public ulong Serial; + public long PassSerial; + + // Draws: the vertex slots (obtain index or -1 for the null buffer, offset past the obtained range's start), the + // obtains they come from with the size each was asked for before its clamp, and the slots as bound. + public int VertexCount; + public readonly int[] VertexObtain = new int[MaxVertexBufferSlots]; + public readonly ulong[] VertexDelta = new ulong[MaxVertexBufferSlots]; + public readonly nint[] VertexBuffers = new nint[MaxVertexBufferSlots]; + public readonly ulong[] VertexOffsets = new ulong[MaxVertexBufferSlots]; + public int ObtainCount; + public readonly ReplayObtain[] Obtains = new ReplayObtain[MaxVertexBufferSlots]; + public readonly ulong[] ObtainRequested = new ulong[MaxVertexBufferSlots]; + } + + private readonly ReplayCapture _drawReplay = new(); + private readonly ReplayCapture _dispatchReplay = new(); + + // Why a sealed item was not captured, and why a replay was refused (the [METAL-V2][TBDR] line's replay_host=...). + private enum ReplayRefusal + { + Commit, Stages, Movie, StorageImage, Unstamped, WideImages, Bindless, DeviceAddresses, Written, ArgumentField, + Traces, MemoOff, EpochMoved, VertexMap, Labels, ThreadLimits, NotInPlace, Bindings, Count, + } + + private enum ReplayMiss + { + Off, Unsealed, Serial, Scope, Stages, Images, Buffers, Vertex, Patch, Count, + } + + private static readonly string[] ReplayRefusalNames = + [ + "commit", "stages", "movie", "storage_image", "unstamped", "wide_images", "bindless", "device_addresses", "written", + "argument_field", "traces", "memo_off", "epoch_moved", "vertex_map", "labels", "thread_limits", "not_in_place", "bindings", + ]; + + private static readonly string[] ReplayMissNames = ["off", "unsealed", "serial", "scope", "stages", "images", "buffers", "vertex", "patch"]; + + private readonly long[] _drawCaptureRefusals = new long[(int)ReplayRefusal.Count]; + private readonly long[] _dispatchCaptureRefusals = new long[(int)ReplayRefusal.Count]; + private readonly long[] _drawReplayMisses = new long[(int)ReplayMiss.Count]; + private readonly long[] _dispatchReplayMisses = new long[(int)ReplayMiss.Count]; + private long _drawReplaysServed; + private long _dispatchReplaysServed; + private long _drawCaptures; + private long _dispatchCaptures; + private long _dispatchReplaysRebound; + + /// Draws and dispatches the host replayed, for tests. + internal (long Draws, long Dispatches, long DispatchesRebound) ReplayCounts => + (_drawReplaysServed, _dispatchReplaysServed, _dispatchReplaysRebound); + + /// A refusal count by name (capture refusals and replay misses of draws or dispatches), for tests. + internal long ReplayCount(bool dispatch, string name) + { + var refusal = Array.IndexOf(ReplayRefusalNames, name); + if (refusal >= 0) + { + return (dispatch ? _dispatchCaptureRefusals : _drawCaptureRefusals)[refusal]; + } + + var miss = Array.IndexOf(ReplayMissNames, name); + return miss >= 0 + ? (dispatch ? _dispatchReplayMisses : _drawReplayMisses)[miss] + : throw new ArgumentException($"No replay count is named {name}.", nameof(name)); + } + + private static string FormatReplayCounts(long[] counts, string[] names) + { + var parts = new List(); + for (var index = 0; index < counts.Length; index++) + { + if (counts[index] != 0) + { + parts.Add(FormattableString.Invariant($"{names[index]}:{counts[index]}")); + counts[index] = 0; + } + } + + return parts.Count == 0 ? "none" : string.Join(",", parts); + } + + // The [METAL-V2][TBDR] line's part: what the host replayed, captured, refused to capture and refused to replay. + private string TakeReplayHostReport() + { + var text = string.Create( + System.Globalization.CultureInfo.InvariantCulture, + $"replay_host=(draws={_drawReplaysServed},captured={_drawCaptures},capture_refused=[{FormatReplayCounts(_drawCaptureRefusals, ReplayRefusalNames)}],miss=[{FormatReplayCounts(_drawReplayMisses, ReplayMissNames)}]) dispatch_replay_host=(dispatches={_dispatchReplaysServed},rebound={_dispatchReplaysRebound},captured={_dispatchCaptures},capture_refused=[{FormatReplayCounts(_dispatchCaptureRefusals, ReplayRefusalNames)}],miss=[{FormatReplayCounts(_dispatchReplayMisses, ReplayMissNames)}])"); + _drawReplaysServed = _drawCaptures = _dispatchReplaysServed = _dispatchCaptures = _dispatchReplaysRebound = 0; + return text; + } + + public long CurrentItemSequence => + (DrawReplayEnabled || DispatchReplayEnabled) && UsesCommandThread && _commandThread is not null ? _replayItemSequence : 0; + + /// + /// Always 0. Upstream's buffer cache merges and unregisters buffer owners, retiring a binding made earlier in the + /// same draw. A Metal binding is a range of a guest-memory window or a ring copy, and nothing retires one under an + /// open submission: a window a move replaces waits in MetalGuestMemory._retired until the submission that used + /// it completes (MetalGuestMemory.RetireReplaced, ReleaseRetired), and ring ranges are reused only after their + /// command buffer completes. So no binding of a draw being prepared is ever bound again; that a binding made for + /// an earlier item still stands is the replay's question, answered by the read-binding memo (above). + /// + public long BufferOwnerGeneration => 0; + + /// Nothing to bind again: see , which never moves on Metal. + public void RebindBuffers(IPreparedBindings prepared) + { + } + + // ---- Recording what the full path bound (hooks in Descriptors, Rendering and the host) ---- + + private void NoteReplayBindStart(MetalStageBindings stage) + { + var stageIndex = StageIndexOf(stage.Program.Stage); + _replayBindEpoch[stageIndex] = _imageCache.Epochs.Binding; + _replayBindImageSet[stageIndex] = _imageCache.ImageSetVersion; + _replayStamped[stageIndex] = 0; + _replayClampCount = 0; + _replayObtainCount = 0; + _replayRecordsOverflowed = false; + } + + private void NoteReplayStamped(MetalStageBindings stage, int index) + { + if (index < 64) + { + _replayStamped[StageIndexOf(stage.Program.Stage)] |= 1UL << index; + } + } + + private ulong NoteReplayClamp(ulong address, ulong requested, ulong size) + { + if (_replayClampCount < ReplayRecordLimit) + { + _replayClamps[_replayClampCount++] = new ReplayClamp(address, requested, size); + } + else + { + _replayRecordsOverflowed = true; + } + + return size; + } + + private BufferBinding NoteReplayObtain(ulong address, ulong size, bool written, BufferBinding binding) + { + if (_replayObtainCount < ReplayRecordLimit) + { + _replayObtains[_replayObtainCount++] = new ReplayObtain(address, size, written, binding); + } + else + { + _replayRecordsOverflowed = true; + } + + return binding; + } + + // At the end of CommitBindings: which stages it committed and whether their images settled. + private void CaptureBindingReplay(GpuBindPoint bindPoint, ReadOnlySpan stages, int gpuLimitsPushDword) + { + _replayCommits++; + _replayCommitPoint = bindPoint; + _replayCommitStageCount = stages.Length <= 2 ? stages.Length : 0; + _replayCommitLimitsDword = gpuLimitsPushDword; + if (_replayCommitStageCount == 0) + { + return; + } + + var epoch = _imageCache.Epochs.Binding; + var imageSet = _imageCache.ImageSetVersion; + var refreshes = _imageCache.HasDeferredRefreshes; + for (var index = 0; index < _replayCommitStageCount; index++) + { + var stage = (MetalStageBindings)stages[index]; + var stageIndex = StageIndexOf(stage.Program.Stage); + _replayCommitStages[index] = stage; + _replayCommitSettled[index] = !refreshes && _replayBindEpoch[stageIndex] == epoch && _replayBindImageSet[stageIndex] == imageSet; + } + } + + private bool RefuseCapture(ReplayCapture capture, ReplayRefusal reason) + { + capture.Sealed = false; + capture.Commit = -1; + (ReferenceEquals(capture, _dispatchReplay) ? _dispatchCaptureRefusals : _drawCaptureRefusals)[(int)reason]++; + return false; + } + + // Captures the stages CommitBindings committed last, for the sealed item; false (counted) when they cannot be replayed. + private bool CaptureStages(ReplayCapture capture, bool compute) + { + if (_replayCommitPoint != (compute ? GpuBindPoint.Compute : GpuBindPoint.Graphics) || _replayCommitStageCount == 0) + { + return RefuseCapture(capture, ReplayRefusal.Commit); + } + + if (!ReadBindingTracesOff) + { + return RefuseCapture(capture, ReplayRefusal.Traces); + } + + if (!ReadBindingMemoEnabled) + { + return RefuseCapture(capture, ReplayRefusal.MemoOff); + } + + if (_bindlessDeclarations.Count != 0) + { + return RefuseCapture(capture, ReplayRefusal.Bindless); + } + + if (compute && (_replayCommitLimitsDword >= 0 || _replayCommitStageCount != 1)) + { + return RefuseCapture(capture, ReplayRefusal.ThreadLimits); + } + + if (compute && _labelStagedPending.Count != 0) + { + return RefuseCapture(capture, ReplayRefusal.Labels); + } + + for (var position = 0; position < _replayCommitStageCount; position++) + { + var bindings = _replayCommitStages[position]!; + var stageIndex = StageIndexOf(bindings.Program.Stage); + if (compute != (stageIndex == StageCompute)) + { + return RefuseCapture(capture, ReplayRefusal.Stages); + } + + if (!_replayCommitSettled[position]) + { + return RefuseCapture(capture, ReplayRefusal.EpochMoved); + } + + if (CaptureStage(capture.Stages[position], bindings, stageIndex, compute) is { } refusal) + { + return RefuseCapture(capture, refusal); + } + } + + capture.StageCount = _replayCommitStageCount; + if (capture.Used.Length < _usedResourceCount) + { + capture.Used = new nint[_usedResourceCount]; + capture.UsedUsage = new nuint[_usedResourceCount]; + } + + _usedResources.AsSpan(0, _usedResourceCount).CopyTo(capture.Used); + _usedResourceUsage.AsSpan(0, _usedResourceCount).CopyTo(capture.UsedUsage); + capture.UsedCount = _usedResourceCount; + capture.Commit = _replayCommits; + return true; + } + + private ReplayRefusal? CaptureStage(ReplayStage captured, MetalStageBindings stage, int stageIndex, bool compute) + { + var program = stage.Program; + var layout = program.Bindings!; + var info = program.Resources!.Info; + var snapshot = stage.StageResources.Resources; + if (stage.MovieLuma >= 0 || stage.MovieChroma >= 0) + { + return ReplayRefusal.Movie; + } + + if (layout.BindlessImageTableCount != 0 || snapshot.BindlessImages.Length != 0) + { + return ReplayRefusal.Bindless; + } + + if (program.UsesDeviceAddresses || info.WritesDeviceAddresses || snapshot.DeviceAddressRanges.Length != 0) + { + return ReplayRefusal.DeviceAddresses; + } + + if (stage.ImageCount > 64) + { + return ReplayRefusal.WideImages; + } + + if (compute && HasGpuThreadLimits(stage)) + { + return ReplayRefusal.ThreadLimits; + } + + // Fields whose bytes stand for the whole submission: the GDS buffer and its size, the LOD statistics bank (one + // resident buffer, made once), the shader-data size, the zero fault word, the step-report slot (a program keeps + // it for good) and the pair-lock table. Anything else (the device-address table, the flattened table, shader + // data uploaded out of line) is written per item. + foreach (var field in ArgumentPlanOf(layout).Fields) + { + var stands = field.FieldKind switch + { + MslArgumentFieldKind.Pointer => field.Kind is DescriptorBindingKind.GlobalDataShare or DescriptorBindingKind.MipStatistics, + MslArgumentFieldKind.Word => field.Kind is DescriptorBindingKind.GlobalDataShare or + DescriptorBindingKind.ShaderData or DescriptorBindingKind.FaultBuffer, + MslArgumentFieldKind.BindlessImageTables => false, + _ => true, + }; + if (!stands) + { + return ReplayRefusal.ArgumentField; + } + } + + var stamped = _replayStamped[stageIndex]; + for (var index = 0; index < stage.ImageCount; index++) + { + if (stage.IsStorage[index]) + { + return ReplayRefusal.StorageImage; + } + + if (stage.MemoHits[index] is null && (stamped & (1UL << index)) == 0) + { + return ReplayRefusal.Unstamped; + } + } + + captured.ReadCount = 0; + captured.WrittenCount = 0; + for (var index = 0; index < stage.BufferCount; index++) + { + var range = stage.Buffers[index]; + if (!range.IsValid) + { + continue; + } + + if (info.Buffers[index].Written) + { + if (!compute) + { + return ReplayRefusal.Written; + } + + if (!_guestMemory.IsInPlace(in range)) + { + return ReplayRefusal.NotInPlace; + } + + captured.AddWritten(index); + continue; + } + + if (!_guestMemory.IsInPlace(in range)) + { + return ReplayRefusal.NotInPlace; + } + + var descriptor = BufferDescriptorWords.From(snapshot.Buffers[index]); + if (descriptor.Footprint() is not { } requested) + { + return ReplayRefusal.Bindings; + } + + captured.AddRead(index, descriptor.Address, requested, in range); + } + + captured.Bindings = stage; + captured.StageIndex = stageIndex; + captured.Prepares = _stagePrepares[stageIndex]; + captured.BindingEpoch = _replayBindEpoch[stageIndex]; + captured.ImageSet = _replayBindImageSet[stageIndex]; + captured.ArgumentBuffer = _stageArgumentBuffers[stageIndex]; + captured.ArgumentOffset = _stageArgumentOffsets[stageIndex]; + captured.ArgumentValid = _stageArgumentValid[stageIndex]; + captured.UsesDeviceAddresses = _stageUsesDeviceAddresses[stageIndex]; + captured.Layout = layout; + captured.UserDataBase = program.UserDataBase; + return null; + } + + // The vertex streams BindVertexBuffers bound, each mapped to the one obtained range it lies in. + private bool CaptureVertexStreams(ReplayCapture capture) + { + if (_replayRecordsOverflowed) + { + return RefuseCapture(capture, ReplayRefusal.VertexMap); + } + + var nullBuffer = _guestMemory.NullBuffer; + capture.ObtainCount = 0; + capture.VertexCount = _vertexBufferCount; + for (var slot = 0; slot < _vertexBufferCount; slot++) + { + var buffer = _vertexBuffers[slot]; + var offset = _vertexOffsets[slot]; + capture.VertexBuffers[slot] = buffer; + capture.VertexOffsets[slot] = offset; + if (buffer == nullBuffer && offset == 0) + { + capture.VertexObtain[slot] = -1; + continue; + } + + var found = -1; + for (var index = 0; index < _replayObtainCount; index++) + { + ref readonly var obtain = ref _replayObtains[index]; + if ((nint)obtain.Binding.Handle != buffer || offset < obtain.Binding.Offset || offset - obtain.Binding.Offset >= obtain.Size) + { + continue; + } + + if (found >= 0 || obtain.Written) + { + // Two obtained ranges hold the stream, or it is written: which one AcquireVertexBuffers took is not known. + return RefuseCapture(capture, ReplayRefusal.VertexMap); + } + + found = index; + } + + if (found < 0) + { + return RefuseCapture(capture, ReplayRefusal.VertexMap); + } + + var obtained = _replayObtains[found]; + var position = Array.IndexOf(capture.Obtains, obtained, 0, capture.ObtainCount); + if (position < 0) + { + var requested = 0UL; + for (var index = 0; index < _replayClampCount; index++) + { + if (_replayClamps[index].Address == obtained.Address && _replayClamps[index].Size == obtained.Size) + { + requested = _replayClamps[index].Requested; + break; + } + } + + if (requested == 0 || capture.ObtainCount == capture.Obtains.Length) + { + return RefuseCapture(capture, ReplayRefusal.VertexMap); + } + + position = capture.ObtainCount++; + capture.Obtains[position] = obtained; + capture.ObtainRequested[position] = requested; + } + + capture.VertexObtain[slot] = position; + capture.VertexDelta[slot] = offset - obtained.Binding.Offset; + } + + return true; + } + + // ---- The IRenderHost members ---- + + public void SealDrawReplay() + { + var capture = _drawReplay; + capture.Sealed = false; + if (!DrawReplayEnabled || !_renderingActive) + { + return; + } + + // After a replay nothing was committed since the capture, which still stands; after a full draw its + // CommitBindings is the last one. + if (capture.Commit != _replayCommits) + { + if (!CaptureStages(capture, compute: false) || !CaptureVertexStreams(capture)) + { + return; + } + + _drawCaptures++; + } + + capture.Serial = _submissionSerial; + capture.PassSerial = _renderPassSerial; + capture.Sealed = true; + } + + public void SealDispatchReplay() + { + var capture = _dispatchReplay; + capture.Sealed = false; + if (!DispatchReplayEnabled) + { + return; + } + + if (capture.Commit != _replayCommits) + { + if (!CaptureStages(capture, compute: true)) + { + return; + } + + _dispatchCaptures++; + } + + capture.Serial = _submissionSerial; + capture.Sealed = true; + } + + private bool MissDraw(ReplayMiss miss) + { + _drawReplayMisses[(int)miss]++; + return false; + } + + private bool MissDispatch(ReplayMiss miss) + { + _dispatchReplayMisses[(int)miss]++; + return false; + } + + // What every captured stage needs before anything is bound: the stage object untouched, the images as settled. + private bool StagesStand(ReplayCapture capture, out ReplayMiss miss) + { + var epoch = _imageCache.Epochs.Binding; + var imageSet = _imageCache.ImageSetVersion; + for (var position = 0; position < capture.StageCount; position++) + { + var stage = capture.Stages[position]; + if (_stagePrepares[stage.StageIndex] != stage.Prepares) + { + miss = ReplayMiss.Stages; + return false; + } + + if (stage.BindingEpoch != epoch || stage.ImageSet != imageSet || _imageCache.HasDeferredRefreshes) + { + miss = ReplayMiss.Images; + return false; + } + } + + miss = ReplayMiss.Count; + return true; + } + + // Each read-only buffer still resolves, by the read-binding memo, to the range it was bound to. + private bool ReadBuffersStand(ReplayCapture capture, bool compute) + { + for (var position = 0; position < capture.StageCount; position++) + { + var stage = capture.Stages[position]; + for (var read = 0; read < stage.ReadCount; read++) + { + var address = stage.ReadAddress[read]; + var requested = stage.ReadRequested[read]; + if (!TryReadBindingMemo(address, requested, compute, out var range) || range != stage.ReadRange[read]) + { + return false; + } + + if (ReadBindingMemoVerify) + { + VerifyReadBinding(address, requested, compute, MetalWritebackCause.StorageDescriptor, range); + } + } + } + + return true; + } + + // The user-data registers of a push-data stage, from the item's own user data; false when one lies outside it. + private static bool PatchUserData(Span shaderData, BindingLayout layout, uint userDataBase, ReadOnlySpan userData) + { + var registers = layout.UserDataRegisters; + for (var index = 0; index < registers.Count; index++) + { + var userIndex = (long)registers[index] - userDataBase; + if (userIndex < 0 || userIndex >= userData.Length) + { + return false; + } + + shaderData[index] = userData[(int)userIndex]; + } + + return true; + } + + private static bool CanPatchUserData(BindingLayout layout, uint userDataBase, int userDataLength) + { + var registers = layout.UserDataRegisters; + for (var index = 0; index < registers.Count; index++) + { + var userIndex = (long)registers[index] - userDataBase; + if (userIndex < 0 || userIndex >= userDataLength) + { + return false; + } + } + + return true; + } + + // Puts a captured stage back as CommitBindings left it, BindResources' per-stage bookkeeping included. + private void RestoreStage(ReplayStage stage, bool compute) + { + var bindings = stage.Bindings; + var index = stage.StageIndex; + _stageArgumentBuffers[index] = stage.ArgumentBuffer; + _stageArgumentOffsets[index] = stage.ArgumentOffset; + _stageArgumentValid[index] = stage.ArgumentValid; + _stageUsesDeviceAddresses[index] = stage.UsesDeviceAddresses; + _preparedStageMask |= 1 << index; + BeginLabelStagedStage(compute ? bindings : null); + _writtenViewRanges.Clear(); + _readOnlyBufferBinds += stage.ReadCount; + var info = bindings.Program.Resources!.Info; + BindDeviceAddressRanges(bindings, info, bindings.StageResources.Resources); + bindings.Committed = true; + } + + private void RestoreUsedResources(ReplayCapture capture) + { + for (var index = 0; index < capture.UsedCount; index++) + { + NoteUsedResource(capture.Used[index], capture.UsedUsage[index]); + } + } + + // The committed stages' shader data as one push-data block, as CommitBindings builds it. + private void PublishReplayPushData(ReplayCapture capture) + { + Span pushData = stackalloc uint[(int)PushData.DwordCount]; + pushData.Clear(); + var hasPushData = false; + for (var position = 0; position < capture.StageCount; position++) + { + var stage = capture.Stages[position]; + var layout = stage.Layout; + if (layout.UsesPushData) + { + var shaderDwords = (int)layout.ShaderDataDwordCount; + stage.Bindings.ShaderData.AsSpan(0, shaderDwords).CopyTo(pushData[(int)layout.PushDataStartDword..]); + hasPushData = true; + } + } + + if (hasPushData) + { + PublishPushData(pushData, gpuLimitsPushDword: -1); + } + } + + public bool TryReplayDraw(in PipelineHandle pipeline, ReadOnlySpan vertexUserData, ReadOnlySpan pixelUserData) + { + var capture = _drawReplay; + if (!DrawReplayEnabled) + { + return MissDraw(ReplayMiss.Off); + } + + ReplayProbe?.Invoke(false); + + if (!capture.Sealed) + { + return MissDraw(ReplayMiss.Unsealed); + } + + capture.Sealed = false; + if (_commandBuffer == 0 || capture.Serial != _submissionSerial) + { + return MissDraw(ReplayMiss.Serial); + } + + if (capture.PassSerial != _renderPassSerial || !_renderingActive) + { + return MissDraw(ReplayMiss.Scope); + } + + if (!StagesStand(capture, out var miss)) + { + return MissDraw(miss); + } + + for (var position = 0; position < capture.StageCount; position++) + { + var stage = capture.Stages[position]; + var userData = stage.StageIndex == StageFragment ? pixelUserData : vertexUserData; + if (stage.Layout.UsesPushData && !CanPatchUserData(stage.Layout, stage.UserDataBase, userData.Length)) + { + return MissDraw(ReplayMiss.Patch); + } + } + + // The vertex streams' clamps are pure; the memo lookups below change nothing but their counters. + for (var index = 0; index < capture.ObtainCount; index++) + { + ref readonly var obtain = ref capture.Obtains[index]; + if (ClampMappedSize(obtain.Address, capture.ObtainRequested[index]) != obtain.Size) + { + return MissDraw(ReplayMiss.Vertex); + } + } + + if (!ReadBuffersStand(capture, compute: false)) + { + return MissDraw(ReplayMiss.Buffers); + } + + for (var index = 0; index < capture.ObtainCount; index++) + { + ref readonly var obtain = ref capture.Obtains[index]; + if (!TryReadBindingMemo(obtain.Address, obtain.Size, computeStage: false, out var range) || + (ulong)range.Buffer != obtain.Binding.Handle || range.Offset != obtain.Binding.Offset) + { + return MissDraw(ReplayMiss.Vertex); + } + + if (ReadBindingMemoVerify) + { + VerifyReadBinding(obtain.Address, obtain.Size, computeStage: false, MetalWritebackCause.BufferBinding, range); + } + } + + // Everything stands: bind what the sealed draw bound, with this draw's user data. + _ = RequirePipelineEntry(in pipeline); + for (var position = 0; position < capture.StageCount; position++) + { + var stage = capture.Stages[position]; + if (stage.Layout.UsesPushData) + { + _ = PatchUserData(stage.Bindings.ShaderData, stage.Layout, stage.UserDataBase, + stage.StageIndex == StageFragment ? pixelUserData : vertexUserData); + } + + RestoreStage(stage, compute: false); + } + + RestoreUsedResources(capture); + Span stages = capture.StageCount == 1 + ? [capture.Stages[0].Bindings] + : [capture.Stages[0].Bindings, capture.Stages[1].Bindings]; + NoteJoinStages(stages); + NoteBufferWordStages(stages); + PublishReplayPushData(capture); + capture.VertexBuffers.AsSpan(0, capture.VertexCount).CopyTo(_vertexBuffers); + capture.VertexOffsets.AsSpan(0, capture.VertexCount).CopyTo(_vertexOffsets); + _vertexBufferCount = capture.VertexCount; + _drawReplaysServed++; + return true; + } + + public bool TryReplayDispatch(in PipelineHandle pipeline, in ShaderStageResources stage) + { + var capture = _dispatchReplay; + if (!DispatchReplayEnabled) + { + return MissDispatch(ReplayMiss.Off); + } + + ReplayProbe?.Invoke(true); + + if (!capture.Sealed) + { + return MissDispatch(ReplayMiss.Unsealed); + } + + capture.Sealed = false; + if (_commandBuffer == 0 || capture.Serial != _submissionSerial) + { + return MissDispatch(ReplayMiss.Serial); + } + + if (!StagesStand(capture, out var miss)) + { + return MissDispatch(miss); + } + + var captured = capture.Stages[0]; + var bindings = captured.Bindings; + if (!ReferenceEquals(stage.Program, bindings.Program) || stage.ShaderBase != bindings.StageResources.ShaderBase) + { + return MissDispatch(ReplayMiss.Stages); + } + + var program = bindings.Program; + var layout = captured.Layout; + if (!CanPatchUserData(layout, program.UserDataBase, stage.Resources.UserData.Length)) + { + return MissDispatch(ReplayMiss.Patch); + } + + if (!ReadBuffersStand(capture, compute: true)) + { + return MissDispatch(ReplayMiss.Buffers); + } + + // Everything stands. The shader data is this dispatch's, built as PrepareBindings builds it. + var entry = RequirePipelineEntry(in pipeline); + var info = program.Resources!.Info; + bindings.StageResources = stage; + var shaderDwords = (int)layout.ShaderDataDwordCount; + Array.Clear(bindings.ShaderData, 0, shaderDwords); + if (!WriteStageShaderData(bindings.ShaderData, program, layout, info, stage.Resources, stage.ShaderBase)) + { + throw UserRegisterOutsideUserData(program, layout, stage.Resources); + } + + stage.WriteDispatchThreadLimits(bindings.ShaderData.AsSpan(0, shaderDwords)); + stage.WriteCallData(bindings.ShaderData.AsSpan(0, shaderDwords)); + _threadLimitsTarget = default; + RestoreStage(captured, compute: true); + + // A dispatch that writes takes BindResources' buffer loop again, every buffer in order, after every refusal: + // the invalidation and write record of a written buffer belong to this dispatch, and a read after it is + // looked up after it, as the full path looks it up. A range or length other than the captured one rewrites + // the argument buffer, and the next seal captures the stage again. + RestoreUsedResources(capture); + if (captured.WrittenCount != 0) + { + var count = bindings.BufferCount; + var before = ArrayPool.Shared.Rent(count); + var lengths = ArrayPool.Shared.Rent(count); + try + { + bindings.Buffers.AsSpan(0, count).CopyTo(before); + bindings.BufferLengths.AsSpan(0, count).CopyTo(lengths); + _readOnlyBufferBinds -= captured.ReadCount; + for (var index = 0; index < count; index++) + { + BindStageStorageBuffer(bindings, index, info, stage.Resources); + } + + var rebound = false; + for (var index = 0; index < count && !rebound; index++) + { + rebound = bindings.Buffers[index] != before[index] || bindings.BufferLengths[index] != lengths[index]; + } + + if (rebound) + { + WriteArgumentBuffer(bindings, StageCompute); + capture.Commit = -1; + _dispatchReplaysRebound++; + } + } + finally + { + ArrayPool.Shared.Return(before); + ArrayPool.Shared.Return(lengths); + } + } + + NoteBufferWordComputeStage(entry, [bindings]); + PublishReplayPushData(capture); + _dispatchReplaysServed++; + return true; + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index d6fc7ce7e..03d4cb87d 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -2669,7 +2669,7 @@ public ulong ClampMappedSize(ulong address, ulong size) if (_memory.CanRead(address, size)) { - return size; + return NoteReplayClamp(address, size, size); } var clamped = 1UL; @@ -2687,7 +2687,7 @@ public ulong ClampMappedSize(ulong address, ulong size) } } - return clamped; + return NoteReplayClamp(address, size, clamped); } public BufferBinding NullBuffer => new((ulong)_guestMemory.NullBuffer, 0); @@ -2729,7 +2729,7 @@ public BufferBinding ObtainBuffer(ulong address, ulong size, bool isWritten) VerifyReadBinding(address, size, computeStage: false, MetalWritebackCause.BufferBinding, memo); } - return new BufferBinding((ulong)memo.Buffer, memo.Offset); + return NoteReplayObtain(address, size, isWritten, new BufferBinding((ulong)memo.Buffer, memo.Offset)); } var memoStamp = !isWritten && ReadBindingMemoEnabled ? ReadBindingStamp() : default; @@ -2747,7 +2747,7 @@ public BufferBinding ObtainBuffer(ulong address, ulong size, bool isWritten) if (!range.IsValid) { - return NullBuffer; + return NoteReplayObtain(address, size, isWritten, NullBuffer); } if (!isWritten && ReadBindingMemoEnabled) @@ -2765,7 +2765,7 @@ public BufferBinding ObtainBuffer(ulong address, ulong size, bool isWritten) NoteGuestMemoryWrite(address, size, MetalGpuWriteOrigin.WrittenBinding); } - return new BufferBinding((ulong)range.Buffer, range.Offset); + return NoteReplayObtain(address, size, isWritten, new BufferBinding((ulong)range.Buffer, range.Offset)); } public BufferBinding UploadTransient(ReadOnlySpan data, uint alignment) @@ -3132,7 +3132,7 @@ public void ReportCounters() $"transfers=[{TakeTransferCauses()}] {TakePreludeText()}" + (CopiesShareCompute ? $" copies_in_encoder={_copiesInEncoder}" : "") + $" alias_writes_discarded={_imageCache.TakeAliasWritesDiscarded()} " + - SharpEmu.Libs.Gpu.Rendering.RenderRecorderStatistics.TakeInPlaceReport()); + SharpEmu.Libs.Gpu.Rendering.RenderRecorderStatistics.TakeInPlaceReport() + " " + TakeReplayHostReport()); if (_guard is not null) { Console.Error.WriteLine($"[METAL-V2][GUARD] {_guard.Report()}"); From 905117c3b5ddba7e07fc5350876917cf503a5874 Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 23:44:10 +0000 Subject: [PATCH 075/134] [Tests] Scene tests for Metal draw and dispatch replay The scenes run through the real command thread. They check that: - repeated draws that differ only in user data and scissor are replayed and produce the same target bytes as with replay off; - repeated dispatches are replayed and write the same bytes as with replay off; - each invalidation refuses the replay by name, and the item still renders or writes the right result: - a CPU write to a cached tiled texture (images), - a read binding the memo no longer answers (buffers, memo_off), - a command buffer committed between draws (serial), - a binding-epoch move between dispatches (images). ReplayProbe on the host lets a test make the change between two items, at the point where a completion or another thread would. --- .../Scenes/ReplaySceneTests.cs | 379 ++++++++++++++++++ 1 file changed, 379 insertions(+) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/Scenes/ReplaySceneTests.cs diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ReplaySceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ReplaySceneTests.cs new file mode 100644 index 000000000..2f2868064 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ReplaySceneTests.cs @@ -0,0 +1,379 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.InteropServices; +using SharpEmu.Gpu.Metal.V2; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests.Scenes; + +/// +/// Draw and dispatch replay on the Metal host (MetalRenderHost.Replay.cs): a draw or dispatch that repeats the one +/// before it in all but its user data binds what that one bound, patched with its own user data, and renders or +/// writes exactly what the full path does. What moves under a sealed item between two items refuses the replay by +/// name, and the item takes the full path. +/// +public sealed class ReplaySceneTests(ITestOutputHelper output) : SceneTestBase(output) +{ + private const uint Width = 16; + private const uint Rgba8 = 56; + private const uint TextureSize = 8; + + // MRT0 = the four user-data words s[0:3] as floats. + private static readonly uint[] ConstantColor = + [ + 0x7E040200, // v_mov_b32_e32 v2, s0 + 0x7E060201, // v_mov_b32_e32 v3, s1 + 0x7E080202, // v_mov_b32_e32 v4, s2 + 0x7E0A0203, // v_mov_b32_e32 v5, s3 + 0xF800180F, 0x05040302, // exp mrt0 v2, v3, v4, v5 done vm + 0xBF810000, // s_endpgm + ]; + + // MRT0 = the 2D image T# s[0:7] sampled through S# s[8:11] at PARAM0.xy (sixteen user SGPRs: m0 is s16). + private static readonly uint[] Sample = + [ + 0xBEFC0310, // s_mov_b32 m0, s16 + 0xC8080000, // v_interp_p1_f32_e32 v2, v0, attr0.x + 0xC8090001, // v_interp_p2_f32_e32 v2, v1, attr0.x + 0xC80C0100, // v_interp_p1_f32_e32 v3, v0, attr0.y + 0xC80D0101, // v_interp_p2_f32_e32 v3, v1, attr0.y + 0xC8100200, // v_interp_p1_f32_e32 v4, v0, attr0.z + 0xC8110201, // v_interp_p2_f32_e32 v4, v1, attr0.z + 0xF0800F08, 0x00400802, // image_sample v[8:11], v[2:3], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C3F70, // s_waitcnt vmcnt(0) + 0xF800180F, 0x0B0A0908, // exp mrt0 v8, v9, v10, v11 done vm + 0xBF810000, // s_endpgm + ]; + + // 64-thread groups; thread g writes the user-data word s4 to record g of the V# in s[0:3] (group id X is s5). + private static readonly uint[] StoreUserWord = + [ + 0x8F068605, // s_lshl_b32 s6, s5, 6 + 0x4A020006, // v_add_nc_u32_e32 v1, s6, v0 + 0x7E040204, // v_mov_b32_e32 v2, s4 + 0xE0702000, 0x80000201, // buffer_store_dword v2, v1, s[0:3], 0 idxen + 0xBF810000, // s_endpgm + ]; + + private static readonly SceneVertex[] Quad = + [ + SceneVertex.At(-1, -1, 0.5f, 0, 1, 0, 1), SceneVertex.At(1, -1, 0.5f, 1, 1, 0, 1), + SceneVertex.At(-1, 1, 0.5f, 0, 0, 0, 1), SceneVertex.At(-1, 1, 0.5f, 0, 0, 0, 1), + SceneVertex.At(1, -1, 0.5f, 1, 1, 0, 1), SceneVertex.At(1, 1, 0.5f, 1, 0, 0, 1), + ]; + + // One target and one mesh; each draw is a stripe of the target, its programs and user data emitted again. + private sealed class Stripes + { + private readonly SceneRig _rig; + private readonly uint[] _mesh; + private readonly ulong _vertex; + private readonly SceneState _state; + + public Stripes(SceneRig rig) + { + _rig = rig; + _mesh = rig.UploadMesh(Quad); + _vertex = rig.Program(ScenePrograms.FetchVertex); + Target = rig.ColorTarget(Width, Width, 16, 0xFF); + _state = new SceneState(Width, Width).ColorTarget(0, Target, Width, Width, format: 14, numberType: 7); + } + + public ulong Target { get; } + + public void Draw(ScenePm4 pm4, int left, int right, uint[] pixelProgram, uint[] pixelUserData) + { + _state.ScreenScissor(left, 0, right, (int)Width); + _state.VertexShader(_vertex, _mesh); + _state.PixelShader(_rig.Program(pixelProgram), pixelUserData); + _state.Emit(pm4); + pm4.NumInstances(1); + pm4.DrawAuto((uint)Quad.Length); + } + + public float[] Pixel(int x) + { + var pixels = MemoryMarshal.Cast(_rig.ReadImage(Target, Width, Width, 16)); + return pixels.Slice((int)((8 * Width + (uint)x) * 4), 4).ToArray(); + } + + public byte[] Image() => _rig.ReadImage(Target, Width, Width, 16); + } + + private static uint[] Colour(float r, float g, float b) => [SceneState.F(r), SceneState.F(g), SceneState.F(b), SceneState.F(1)]; + + // A tiled texture (64 KiB swizzle): a cached copy, not a view of the guest window, so a CPU write must reach it + // through the image cache. One colour throughout, so its bytes are the same in any tiling. + private const uint TiledMode = 27; + private const uint TextureBytes = 0x10000; + + private static uint[] TextureUserData(ulong texture) => + [.. Descriptors.Texture(texture, Rgba8, TextureSize, TextureSize, tileMode: TiledMode), .. Descriptors.Sampler(), 0, 0, 0, 0]; + + private static void FillTexture(SceneRig rig, ulong address, uint abgr) + { + var texels = new uint[TextureBytes / 4]; + Array.Fill(texels, abgr); + rig.Memory.Write(address, MemoryMarshal.AsBytes(texels.AsSpan())); + } + + private static ulong SolidTexture(SceneRig rig, uint abgr) + { + var address = rig.Memory.Allocate(TextureBytes, 0x10000); + FillTexture(rig, address, abgr); + return address; + } + + private static void AssertColour(string what, float[] actual, float r, float g, float b) + { + float[] expected = [r, g, b, 1]; + for (var channel = 0; channel < 4; channel++) + { + Assert.True( + MathF.Abs(actual[channel] - expected[channel]) <= 0.01f, + $"{what}: channel {channel} is {actual[channel]}, expected {expected[channel]}"); + } + } + + private static void AssertAbgr(string what, float[] actual, uint abgr) => + AssertColour(what, actual, (abgr & 0xFF) / 255f, ((abgr >> 8) & 0xFF) / 255f, ((abgr >> 16) & 0xFF) / 255f); + + private void Report(SceneRig rig, string what) + { + var (draws, dispatches, rebound) = rig.Host.ReplayCounts; + Output.WriteLine($"{what}: draws={draws} dispatches={dispatches} rebound={rebound} " + + $"draw_misses=[{string.Join(',', Names().Select(name => $"{name}:{rig.Host.ReplayCount(false, name)}"))}] " + + $"dispatch_misses=[{string.Join(',', Names().Select(name => $"{name}:{rig.Host.ReplayCount(true, name)}"))}]"); + static string[] Names() => + [ + "unsealed", "serial", "scope", "stages", "images", "buffers", "vertex", "patch", "commit", "epoch_moved", + "not_in_place", "argument_field", "unstamped", "vertex_map", "written", "traces", "memo_off", + ]; + } + + private static readonly (float R, float G, float B)[] StripeColours = + [ + (1, 0, 0), (1, 0, 0), (1, 0, 0), (0, 1, 0), (0, 1, 0), (0, 0, 1), (1, 0, 0), (0.25f, 0.5f, 0.75f), + ]; + + private byte[] DrawStripes(bool replay, out long replays) + { + using var rig = CreateRig()!; + rig.Host.DrawReplayEnabled = replay; + rig.Host.DispatchReplayEnabled = replay; + var stripes = new Stripes(rig); + var pm4 = new ScenePm4(); + for (var stripe = 0; stripe < StripeColours.Length; stripe++) + { + var (r, g, b) = StripeColours[stripe]; + stripes.Draw(pm4, stripe * 2, stripe * 2 + 2, ConstantColor, Colour(r, g, b)); + } + + rig.Submit(pm4); + for (var stripe = 0; stripe < StripeColours.Length; stripe++) + { + var (r, g, b) = StripeColours[stripe]; + AssertColour($"replay={replay} stripe {stripe}", stripes.Pixel(stripe * 2 + 1), r, g, b); + } + + Report(rig, $"replay={replay}"); + replays = rig.Host.ReplayCounts.Draws; + Assert.Empty(rig.Fatals); + return stripes.Image(); + } + + // Draws that differ only in their user data and scissor replay the one before them, each with its own user data, + // and the target is byte for byte what the full path renders. + [Fact] + public void RepeatedDrawsReplayWithTheirOwnUserDataAndRenderAsWithout() + { + if (CreateRig() is not { } probe) return; + probe.Dispose(); + var with = DrawStripes(replay: true, out var replays); + var without = DrawStripes(replay: false, out var none); + Assert.True(replays > 0, "no draw was replayed"); + Assert.Equal(0, none); + Assert.Equal(without, with); + } + + // A cached (tiled) texture the sealed draw sampled is written by the CPU between two draws: its binding epoch moves, + // the replay is refused (images) and the draw acquires the texture again, sampling the new texels. A replay here + // would bind the copy as it was, never refreshed. + [Fact] + public void ATextureWrittenBetweenDrawsRefusesTheReplayAndIsSampledNew() + { + using var rig = CreateRig(); + if (rig is null) return; + const uint red = 0xFF0000FF; + const uint green = 0xFF00FF00; + var texture = SolidTexture(rig, red); + var stripes = new Stripes(rig); + var calls = 0; + rig.Host.ReplayProbe = dispatch => + { + if (!dispatch && ++calls == 2) + { + var before = rig.Host.ImageCache.Epochs.Binding; + FillTexture(rig, texture, green); + rig.Host.ImageCache.InvalidateMemory(texture, TextureBytes); + Output.WriteLine($"epoch {before} -> {rig.Host.ImageCache.Epochs.Binding}"); + } + }; + var pm4 = new ScenePm4(); + for (var stripe = 0; stripe < 4; stripe++) + { + stripes.Draw(pm4, stripe * 4, stripe * 4 + 4, Sample, TextureUserData(texture)); + } + + rig.Submit(pm4); + Report(rig, "texture written"); + // Stripes 0 and 1 are not looked at: the CPU rewrote the texels under GPU work that was not finished. + AssertAbgr("stripe 2 (refused, full)", stripes.Pixel(10), green); + AssertAbgr("stripe 3", stripes.Pixel(14), green); + Assert.True(calls >= 2, $"the host was asked for {calls} replays"); + Assert.True(rig.Host.ReplayCount(false, "images") >= 1, "the moved epoch did not refuse the replay"); + Assert.True(rig.Host.ReplayCounts.Draws >= 1, "the draw before the refused one was not replayed"); + Assert.Empty(rig.Fatals); + } + + // A read-only binding of the sealed draw no longer answered by the read-binding memo refuses the replay (buffers): + // nothing then says the full chain would bind the same range. + [Fact] + public void AReadBindingTheMemoNoLongerAnswersRefusesTheReplay() + { + using var rig = CreateRig(); + if (rig is null) return; + var stripes = new Stripes(rig); + var calls = 0; + rig.Host.ReplayProbe = dispatch => + { + if (!dispatch && ++calls == 2) + { + rig.Host.ReadBindingMemoEnabled = false; + } + }; + var pm4 = new ScenePm4(); + for (var stripe = 0; stripe < 4; stripe++) + { + stripes.Draw(pm4, stripe * 4, stripe * 4 + 4, ConstantColor, Colour(0, stripe / 4f, 1)); + } + + rig.Submit(pm4); + Report(rig, "memo off"); + for (var stripe = 0; stripe < 4; stripe++) + { + AssertColour($"stripe {stripe}", stripes.Pixel(stripe * 4 + 2), 0, stripe / 4f, 1); + } + + Assert.Equal(1, rig.Host.ReplayCounts.Draws); + Assert.True(rig.Host.ReplayCount(false, "buffers") >= 1, "a read binding the memo did not answer was replayed"); + Assert.True(rig.Host.ReplayCount(false, "memo_off") >= 1, "a draw was captured with the memo off"); + Assert.Empty(rig.Fatals); + } + + // The command buffer goes out between two draws (a host read waiting for the GPU): the argument and push ranges + // the sealed draw bound belong to the old one, so the replay is refused (serial) and the draw binds in full. + [Fact] + public void ACommandBufferCommittedBetweenDrawsRefusesTheReplay() + { + using var rig = CreateRig(); + if (rig is null) return; + var stripes = new Stripes(rig); + var calls = 0; + rig.Host.ReplayProbe = dispatch => + { + if (!dispatch && ++calls == 2) + { + rig.Host.FlushAndWaitForGpu(); + } + }; + var pm4 = new ScenePm4(); + for (var stripe = 0; stripe < 4; stripe++) + { + stripes.Draw(pm4, stripe * 4, stripe * 4 + 4, ConstantColor, Colour(stripe / 4f, 1, 0.5f)); + } + + rig.Submit(pm4); + Report(rig, "flushed"); + for (var stripe = 0; stripe < 4; stripe++) + { + AssertColour($"stripe {stripe}", stripes.Pixel(stripe * 4 + 2), stripe / 4f, 1, 0.5f); + } + + Assert.True(rig.Host.ReplayCount(false, "serial") >= 1, "no replay was refused across a committed command buffer"); + Assert.True(rig.Host.ReplayCounts.Draws >= 1, "the draw before the refused one was not replayed"); + Assert.Empty(rig.Fatals); + } + + private uint[] StoreWords(bool replay, Action? probe, out long replays, out long imagesMisses) + { + using var rig = CreateRig()!; + rig.Host.DrawReplayEnabled = replay; + rig.Host.DispatchReplayEnabled = replay; + var calls = 0; + if (probe is not null) + { + rig.Host.ReplayProbe = dispatch => + { + if (dispatch && ++calls == 2) + { + probe(rig); + } + }; + } + + var first = rig.Memory.Allocate(64 * 4, 0x10000); + var second = rig.Memory.Allocate(64 * 4, 0x10000); + var pm4 = new ScenePm4(); + // Four dispatches into the first buffer, then three into the second: the last word of each run is what lands. + uint[] words = [1, 2, 3, 4]; + foreach (var word in words) + { + rig.Dispatch(pm4, StoreUserWord, [.. Descriptors.Buffer(first, 4, 64), word], 1); + } + + foreach (var word in words[..3]) + { + rig.Dispatch(pm4, StoreUserWord, [.. Descriptors.Buffer(second, 4, 64), word + 10], 1); + } + + rig.Submit(pm4); + Report(rig, $"dispatch replay={replay}"); + replays = rig.Host.ReplayCounts.Dispatches; + imagesMisses = rig.Host.ReplayCount(true, "images"); + Assert.Empty(rig.Fatals); + return [.. rig.Read(first, 64), .. rig.Read(second, 64)]; + } + + // Dispatches that differ only in their user data replay the one before them with their own shader data, and take + // their written buffer's chain again: the bytes written are those of the full path. + [Fact] + public void RepeatedDispatchesReplayWithTheirOwnUserDataAndWriteAsWithout() + { + if (CreateRig() is not { } probe) return; + probe.Dispose(); + var with = StoreWords(replay: true, probe: null, out var replays, out _); + var without = StoreWords(replay: false, probe: null, out var none, out _); + Assert.All(with[..64], word => Assert.Equal(4u, word)); + Assert.All(with[64..], word => Assert.Equal(13u, word)); + Assert.True(replays > 0, "no dispatch was replayed"); + Assert.Equal(0, none); + Assert.Equal(without, with); + } + + // An image-cache binding epoch that moves between two dispatches refuses the replay (images); the dispatch binds + // in full and writes what it would have. + [Fact] + public void AnEpochMovedBetweenDispatchesRefusesTheReplay() + { + if (CreateRig() is not { } probe) return; + probe.Dispose(); + var with = StoreWords(replay: true, rig => rig.Host.ImageCache.Epochs.NoteShapeChanged(), out var replays, out var imagesMisses); + Assert.True(imagesMisses >= 1, "the moved epoch did not refuse the replay"); + Assert.True(replays >= 1, "no dispatch was replayed around the refused one"); + Assert.All(with[..64], word => Assert.Equal(4u, word)); + Assert.All(with[64..], word => Assert.Equal(13u, word)); + } +} From 603d7a5d371d0a6d52a44edc7425a98a577356b5 Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 23:44:10 +0000 Subject: [PATCH 076/134] [GpuRemote] Test that the GPU host gets the replay switches Draw and dispatch replay run entirely in process B. The shared engine that seals and replays and the Metal host both run there, so no replay state crosses the channel. The switches are the only part that crosses: B reads SHARPEMU_DRAW_REPLAY and SHARPEMU_DISPATCH_REPLAY from the environment A starts it with. EnvironmentBlock is now internal so a test can check the block that posix_spawn receives. --- src/SharpEmu.GpuRemote/GpuProcessLauncher.cs | 3 +- .../GpuHostEnvironmentTests.cs | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 tests/SharpEmu.GpuRemote.Tests/GpuHostEnvironmentTests.cs diff --git a/src/SharpEmu.GpuRemote/GpuProcessLauncher.cs b/src/SharpEmu.GpuRemote/GpuProcessLauncher.cs index ba2b599c4..a32961c9c 100644 --- a/src/SharpEmu.GpuRemote/GpuProcessLauncher.cs +++ b/src/SharpEmu.GpuRemote/GpuProcessLauncher.cs @@ -111,7 +111,8 @@ public static int Spawn(string executable, IReadOnlyList arguments) private const string HeapCountVariable = "DOTNET_GCHeapCount"; private const string HostHeapCount = "4"; - private static List EnvironmentBlock() + // Internal for tests: process B reads its switches (SHARPEMU_DRAW_REPLAY and the rest) from this block. + internal static List EnvironmentBlock() { var block = new List(); var gen0Set = false; diff --git a/tests/SharpEmu.GpuRemote.Tests/GpuHostEnvironmentTests.cs b/tests/SharpEmu.GpuRemote.Tests/GpuHostEnvironmentTests.cs new file mode 100644 index 000000000..73c0dcecf --- /dev/null +++ b/tests/SharpEmu.GpuRemote.Tests/GpuHostEnvironmentTests.cs @@ -0,0 +1,33 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using Xunit; + +namespace SharpEmu.GpuRemote.Tests; + +/// +/// Draw and dispatch replay live wholly in the GPU host (process B): the shared engine that seals and replays and the +/// Metal host that binds both run there, so nothing of replay crosses the channel. What does cross is the switches: +/// B reads SHARPEMU_DRAW_REPLAY and SHARPEMU_DISPATCH_REPLAY from the environment A starts it with. +/// +public sealed class GpuHostEnvironmentTests +{ + [Theory] + [InlineData("SHARPEMU_DRAW_REPLAY")] + [InlineData("SHARPEMU_DISPATCH_REPLAY")] + public void TheGpuHostIsStartedWithTheReplaySwitch(string name) + { + var saved = Environment.GetEnvironmentVariable(name); + try + { + Environment.SetEnvironmentVariable(name, "0"); + Assert.Contains($"{name}=0", GpuProcessLauncher.EnvironmentBlock()); + Environment.SetEnvironmentVariable(name, null); + Assert.DoesNotContain(GpuProcessLauncher.EnvironmentBlock(), entry => entry.StartsWith($"{name}=", StringComparison.Ordinal)); + } + finally + { + Environment.SetEnvironmentVariable(name, saved); + } + } +} From 0d3f4c1a3753ffd510bb27881a9ccad0f4e66337 Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 23:44:10 +0000 Subject: [PATCH 077/134] [Docs] Document SHARPEMU_DRAW_REPLAY and SHARPEMU_DISPATCH_REPLAY on Metal Both are upstream's switches, read by the shared engine and now also by the Metal host's replay (MetalRenderHost.Replay.cs). Default on; 0 binds every draw or dispatch in full. --- docs/macos/configuration.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 7f273c840..d1645b524 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -121,6 +121,8 @@ undoes an optimization to isolate a miscompile: | --- | --- | --- | | `SHARPEMU_METAL_V2_DEFERRED_LABEL_LANDINGS` | on | An end-of-pipe label that Metal defers to GPU completion still reports the submission it lands with, so another queue's soft wait (`SHARPEMU_END_OF_PIPE_SOFT_WAITS`) ends when that submission completes. `0` gives deferred labels no landing again: such a wait ends only at its cap. | | `SHARPEMU_METAL_V2_DYNAMIC_STENCIL_OPS` | on | A draw's stencil operations and compare functions come from its own dynamic state, not from the draw its pipeline was first built for. `0` takes them from the pipeline again. | +| `SHARPEMU_DRAW_REPLAY` | on | A draw that repeats the command-thread item before it in all but its user data (same programs, descriptor words, vertex input and targets) binds what that draw bound, with its own user data patched into the push data, instead of preparing and binding again (`MetalRenderHost.Replay.cs`). The host refuses, and the draw takes the full path, when anything that binding stood on has moved: the command buffer, the render pass, the image cache's binding epoch or image set, a read-only buffer's or vertex stream's read-binding memo answer, or the stage object. Draws with written buffers, storage images, movie planes, bindless tables, device addresses or per-draw argument fields are never captured. The `[METAL-V2][TBDR]` line reports the engine's `draw_replays` / `replay_miss` and the host's `replay_host=(draws,captured,capture_refused=[...],miss=[...])`. Needs the command thread (`SHARPEMU_METAL_V2_COMMAND_THREAD`, on). `0` binds every draw in full. | +| `SHARPEMU_DISPATCH_REPLAY` | on | The same for a compute dispatch that repeats the one before it in all but its user data and thread limits: its shader data is built again from its own snapshot, and a dispatch that writes takes its buffers' whole binding chain again (a range other than the captured one rewrites the argument buffer, counted as `rebound`). Reported as `dispatch_replay_host=(...)` on the same line. `0` binds every dispatch in full. | | `SHARPEMU_POSTED_WORD_COPY` | on | A bounded word-copy kernel whose source is final and whose destination holds no image or surface metadata is recorded as a command-processor store of the copied words at its place in the stream, not as a dispatch. The counter line reports `word_copy=[posted=...,unsupported=...,image=...,...]`. `0` runs every such kernel as a dispatch. | ## Diagnostics From ca8aba529c80884fed81773acc5fa13707918ad0 Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 23:48:37 +0000 Subject: [PATCH 078/134] [Shader] Bound each selected component of a literal formatted load, wrapping past 2^32 Upstream 7cf0ac568 checks a formatted buffer load per selected component at (element address + component offset), with 32-bit wrap, and reads the destination constants only when a selected component is out of range. The Metal fetch, decoded, inline, GLC and function-constant paths and the device-descriptor path already did; the literal whole-dword path (TryEmitLiteralDwordFormatLoad) bounded the whole run, so an element whose selected components wrap to the buffer's start read constants. That path now keeps its one compare for an element that fits and, only when that fails, checks each selected component's dword (the words come from the per-dword wrapping slow path of sharpemu_load_words). SHARPEMU_METAL_FORMAT_LOAD_COMPONENT_BOUNDS=0 restores the whole-run bound; documented in docs/macos/configuration.md. sharpemu_load_word and sharpemu_load_word_coherent tested addr + 4 <= bytes, which wraps for addr 0xFFFFFFFC and read the buffer's last word index past its end; they now test (addr | 3) < bytes. Tests: MslFormatLoadWrapTests (moved in from the parked upstream port, plus packed, device-descriptor and word-at-the-top cases) and the run-time word 3 wrap theory over every other path. --- docs/macos/configuration.md | 1 + .../Gen5MslCodegenOptions.cs | 8 + .../Gen5MslTranslator.cs | 23 ++ .../Templates/coherent_load_prelude.msl | 2 +- .../Templates/prelude.msl | 6 +- .../Goldens/exec-store-layout.msl | 6 +- .../Goldens/fmac-layout.msl | 6 +- .../Goldens/lds-layout.msl | 6 +- .../Goldens/loop-layout.msl | 6 +- .../Goldens/muls-layout.msl | 6 +- .../Goldens/pixel-layout.msl | 6 +- .../Goldens/typed-load-layout.msl | 6 +- .../Goldens/typed-store-layout.msl | 6 +- .../Goldens/vertex-layout.msl | 6 +- .../MslFormatLoadWrapTests.cs | 219 ++++++++++++++++++ .../MslRuntimeFormatLoadTests.Wrap.cs | 75 ++++++ 16 files changed, 367 insertions(+), 21 deletions(-) create mode 100644 tests/SharpEmu.ShaderCompiler.Metal.Tests/MslFormatLoadWrapTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Metal.Tests/MslRuntimeFormatLoadTests.Wrap.cs diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 5a80e39b6..4e7a6aaf5 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -67,6 +67,7 @@ them for measurements or to isolate a problem. | `SHARPEMU_METAL_MESH_SHADERS` | on | `0` disables mesh pipelines for primitive-shader draws. | | `SHARPEMU_METAL_DRAW_PARAMETERS` | on | `0` turns off draw parameters in translated vertex programs. By default a vertex program's instance index counts from the draw's base instance, and when an indirect draw names a user-data register for its base vertex or start instance, the program counts its vertex index from the base vertex and stores both bases there (the command processor no longer writes those registers). `0` gives the program Metal's ids, which include both bases, and stores nothing. | | `SHARPEMU_RUNTIME_IMAGE_SWIZZLE` | on | `0` bakes each storage image's destination select into the translated program, one program per select. By default a store reads the image's channel map from shader data, which the host writes from the bound descriptor. | +| `SHARPEMU_METAL_FORMAT_LOAD_COMPONENT_BOUNDS` | on | `0` restores the old bound of a formatted buffer load whose format is fixed at translation: the whole element had to fit below the buffer's size. By default each selected component is checked at its own address, wrapping past 2^32 as on the hardware, so a component that wraps to the buffer's start is read, and the load reads its constants only when a selected component is out of range. An element that fits whole still takes one compare. Loads whose format is read at run time always check per component. | | `SHARPEMU_GRAPHICS_PARTIAL_LANES` | off | `1` makes pixel-shader lane reads (DPP, DPP8, PERMLANE16, V_READLANE) of a lane the fragment simdgroup never launched read the reading lane's own value, and treats such a lane as active when the guest EXEC mask has its bit. Off by default, as upstream: it changes every pixel shader with cross-lane operations. | | `SHARPEMU_METAL_MESHLETS` | on | `0` disables the meshlet cache. | | `SHARPEMU_METAL_V2_BINARY_ARCHIVE` | on | `0` disables the on-disk library and pipeline archives. | diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs index 174b1e05e..b80fa9a5d 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs @@ -237,6 +237,13 @@ public sealed record Gen5MslCodegenOptions( /// SHARPEMU_MSL_PACKED_FORMAT_LOADS=0 restores component loads; partial trailing elements retain the decoder. public bool PackedFormatLoads { get; init; } = true; + /// A BUFFER_LOAD_FORMAT_* whose word 3 is known at translate time bounds each selected component + /// at its own 32-bit address (elementAddress + offset, wrapping at 2^32) when the selected run does not + /// fit as a whole, as the hardware and upstream's SPIR-V do (7cf0ac568): a component past the top of the + /// byte space reads the binding's first bytes. The run that fits stays one compare. + /// SHARPEMU_METAL_FORMAT_LOAD_COMPONENT_BOUNDS=0 bounds the whole run again. + public bool FormatLoadComponentBounds { get; init; } = true; + /// A program with at least this many BUFFER_LOAD_FORMAT_* decodes the formats only known on the device /// through one helper (format_load_prelude.msl) instead of inline at every load, which Metal compiles in seconds /// instead of minutes for a program with hundreds. The whole-dword fast path stays inline. Below it the program is @@ -370,6 +377,7 @@ public sealed record Gen5MslCodegenOptions( LaneExactUnobservedWrites = Environment.GetEnvironmentVariable("SHARPEMU_MSL_UNOBSERVED_LANES") != "0", GeometryOutputCapacity = Environment.GetEnvironmentVariable("SHARPEMU_MSL_GEOMETRY_CAPACITY") == "1", PackedFormatLoads = Environment.GetEnvironmentVariable("SHARPEMU_MSL_PACKED_FORMAT_LOADS") != "0", + FormatLoadComponentBounds = Environment.GetEnvironmentVariable("SHARPEMU_METAL_FORMAT_LOAD_COMPONENT_BOUNDS") != "0", FormatFetch = Environment.GetEnvironmentVariable("SHARPEMU_MSL_FORMAT_FETCH") != "0", DecodedFormatLoadThreshold = int.TryParse( Environment.GetEnvironmentVariable("SHARPEMU_MSL_DECODED_FORMAT_LOADS"), out var decodedLoads) diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs index a080c97c9..03e6e752b 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs @@ -3215,6 +3215,29 @@ private bool TryEmitLiteralDwordFormatLoad( if (run > 0) { inBounds = ElementInBounds(bindingIndex, byteAddress, $"{run * sizeof(uint)}u"); + if (_options.FormatLoadComponentBounds) + { + // Each selected component is in range on its own, at its own 32-bit address + // (upstream 7cf0ac568): when the run does not fit, a component past the top of + // the byte space wraps to the binding's first bytes, which the run's per-dword + // path (sharpemu_load_word at addr + 4i) reads. A run that fits implies every + // component does, so the common case is the one compare before ||. + var bytes = BufferBytes(bindingIndex); + var selected = new SortedSet(); + for (uint destination = 0; destination < componentCount; destination++) + { + var selector = (word3 >> (int)(destination * 3)) & 7u; + if (selector >= 4 && selector - 4 < formatComponents) + { + selected.Add(selector - 4); + } + } + + var components = selected.Select(component => + $"({byteAddress} + {component * sizeof(uint)}u) <= {bytes} - 4u"); + inBounds = Temp("bool", $"{inBounds} || (4u <= {bytes} && {string.Join(" && ", components)})"); + } + _usesCoherentLoads |= glc; words = Temp( "uint4", diff --git a/src/SharpEmu.ShaderCompiler.Metal/Templates/coherent_load_prelude.msl b/src/SharpEmu.ShaderCompiler.Metal/Templates/coherent_load_prelude.msl index 073444aee..4b4d88bce 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Templates/coherent_load_prelude.msl +++ b/src/SharpEmu.ShaderCompiler.Metal/Templates/coherent_load_prelude.msl @@ -38,7 +38,7 @@ static inline uint sharpemu_load_word_coherent(device uint* b, uint bytes, uint { if ((addr & 3u) == 0u) { - return addr + 4u <= bytes ? sharpemu_coherent_word_at(b, addr >> 2) : sharpemu_load_tail_coherent(b, bytes, addr); + return (addr | 3u) < bytes ? sharpemu_coherent_word_at(b, addr >> 2) : sharpemu_load_tail_coherent(b, bytes, addr); } uint shift = (addr & 3u) * 8u; uint aligned = addr & ~3u; diff --git a/src/SharpEmu.ShaderCompiler.Metal/Templates/prelude.msl b/src/SharpEmu.ShaderCompiler.Metal/Templates/prelude.msl index 2fd64e6c6..49ae98585 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Templates/prelude.msl +++ b/src/SharpEmu.ShaderCompiler.Metal/Templates/prelude.msl @@ -17,12 +17,14 @@ static inline uint sharpemu_load_tail(device uint* b, uint bytes, uint aligned) // A dword a format access may straddle, assembled from the two it spans. Only the // format path needs this: a descriptor's stride is a byte count, so a component can -// start at any byte. +// start at any byte. A component address wraps at 2^32 (a component past the top of the byte +// space reads the binding's first bytes), so the in-range test of an aligned dword is +// (addr | 3) < bytes, its last byte: addr + 4 would wrap to 0 for the last dword of the space. static inline uint sharpemu_load_word(device uint* b, uint bytes, uint addr) { if ((addr & 3u) == 0u) { - return addr + 4u <= bytes ? b[addr >> 2] : sharpemu_load_tail(b, bytes, addr); + return (addr | 3u) < bytes ? b[addr >> 2] : sharpemu_load_tail(b, bytes, addr); } uint shift = (addr & 3u) * 8u; uint aligned = addr & ~3u; diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/exec-store-layout.msl b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/exec-store-layout.msl index b0addc273..7efa40be8 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/exec-store-layout.msl +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/exec-store-layout.msl @@ -321,12 +321,14 @@ static inline uint sharpemu_load_tail(device uint* b, uint bytes, uint aligned) // A dword a format access may straddle, assembled from the two it spans. Only the // format path needs this: a descriptor's stride is a byte count, so a component can -// start at any byte. +// start at any byte. A component address wraps at 2^32 (a component past the top of the byte +// space reads the binding's first bytes), so the in-range test of an aligned dword is +// (addr | 3) < bytes, its last byte: addr + 4 would wrap to 0 for the last dword of the space. static inline uint sharpemu_load_word(device uint* b, uint bytes, uint addr) { if ((addr & 3u) == 0u) { - return addr + 4u <= bytes ? b[addr >> 2] : sharpemu_load_tail(b, bytes, addr); + return (addr | 3u) < bytes ? b[addr >> 2] : sharpemu_load_tail(b, bytes, addr); } uint shift = (addr & 3u) * 8u; uint aligned = addr & ~3u; diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/fmac-layout.msl b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/fmac-layout.msl index e6c92d9dd..adc59979a 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/fmac-layout.msl +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/fmac-layout.msl @@ -319,12 +319,14 @@ static inline uint sharpemu_load_tail(device uint* b, uint bytes, uint aligned) // A dword a format access may straddle, assembled from the two it spans. Only the // format path needs this: a descriptor's stride is a byte count, so a component can -// start at any byte. +// start at any byte. A component address wraps at 2^32 (a component past the top of the byte +// space reads the binding's first bytes), so the in-range test of an aligned dword is +// (addr | 3) < bytes, its last byte: addr + 4 would wrap to 0 for the last dword of the space. static inline uint sharpemu_load_word(device uint* b, uint bytes, uint addr) { if ((addr & 3u) == 0u) { - return addr + 4u <= bytes ? b[addr >> 2] : sharpemu_load_tail(b, bytes, addr); + return (addr | 3u) < bytes ? b[addr >> 2] : sharpemu_load_tail(b, bytes, addr); } uint shift = (addr & 3u) * 8u; uint aligned = addr & ~3u; diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/lds-layout.msl b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/lds-layout.msl index 9fde62747..26be9c2a8 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/lds-layout.msl +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/lds-layout.msl @@ -321,12 +321,14 @@ static inline uint sharpemu_load_tail(device uint* b, uint bytes, uint aligned) // A dword a format access may straddle, assembled from the two it spans. Only the // format path needs this: a descriptor's stride is a byte count, so a component can -// start at any byte. +// start at any byte. A component address wraps at 2^32 (a component past the top of the byte +// space reads the binding's first bytes), so the in-range test of an aligned dword is +// (addr | 3) < bytes, its last byte: addr + 4 would wrap to 0 for the last dword of the space. static inline uint sharpemu_load_word(device uint* b, uint bytes, uint addr) { if ((addr & 3u) == 0u) { - return addr + 4u <= bytes ? b[addr >> 2] : sharpemu_load_tail(b, bytes, addr); + return (addr | 3u) < bytes ? b[addr >> 2] : sharpemu_load_tail(b, bytes, addr); } uint shift = (addr & 3u) * 8u; uint aligned = addr & ~3u; diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/loop-layout.msl b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/loop-layout.msl index 6dd265547..9b03f074a 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/loop-layout.msl +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/loop-layout.msl @@ -321,12 +321,14 @@ static inline uint sharpemu_load_tail(device uint* b, uint bytes, uint aligned) // A dword a format access may straddle, assembled from the two it spans. Only the // format path needs this: a descriptor's stride is a byte count, so a component can -// start at any byte. +// start at any byte. A component address wraps at 2^32 (a component past the top of the byte +// space reads the binding's first bytes), so the in-range test of an aligned dword is +// (addr | 3) < bytes, its last byte: addr + 4 would wrap to 0 for the last dword of the space. static inline uint sharpemu_load_word(device uint* b, uint bytes, uint addr) { if ((addr & 3u) == 0u) { - return addr + 4u <= bytes ? b[addr >> 2] : sharpemu_load_tail(b, bytes, addr); + return (addr | 3u) < bytes ? b[addr >> 2] : sharpemu_load_tail(b, bytes, addr); } uint shift = (addr & 3u) * 8u; uint aligned = addr & ~3u; diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/muls-layout.msl b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/muls-layout.msl index ec9122c76..9681b398e 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/muls-layout.msl +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/muls-layout.msl @@ -319,12 +319,14 @@ static inline uint sharpemu_load_tail(device uint* b, uint bytes, uint aligned) // A dword a format access may straddle, assembled from the two it spans. Only the // format path needs this: a descriptor's stride is a byte count, so a component can -// start at any byte. +// start at any byte. A component address wraps at 2^32 (a component past the top of the byte +// space reads the binding's first bytes), so the in-range test of an aligned dword is +// (addr | 3) < bytes, its last byte: addr + 4 would wrap to 0 for the last dword of the space. static inline uint sharpemu_load_word(device uint* b, uint bytes, uint addr) { if ((addr & 3u) == 0u) { - return addr + 4u <= bytes ? b[addr >> 2] : sharpemu_load_tail(b, bytes, addr); + return (addr | 3u) < bytes ? b[addr >> 2] : sharpemu_load_tail(b, bytes, addr); } uint shift = (addr & 3u) * 8u; uint aligned = addr & ~3u; diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/pixel-layout.msl b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/pixel-layout.msl index 89389c577..ac32393bb 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/pixel-layout.msl +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/pixel-layout.msl @@ -319,12 +319,14 @@ static inline uint sharpemu_load_tail(device uint* b, uint bytes, uint aligned) // A dword a format access may straddle, assembled from the two it spans. Only the // format path needs this: a descriptor's stride is a byte count, so a component can -// start at any byte. +// start at any byte. A component address wraps at 2^32 (a component past the top of the byte +// space reads the binding's first bytes), so the in-range test of an aligned dword is +// (addr | 3) < bytes, its last byte: addr + 4 would wrap to 0 for the last dword of the space. static inline uint sharpemu_load_word(device uint* b, uint bytes, uint addr) { if ((addr & 3u) == 0u) { - return addr + 4u <= bytes ? b[addr >> 2] : sharpemu_load_tail(b, bytes, addr); + return (addr | 3u) < bytes ? b[addr >> 2] : sharpemu_load_tail(b, bytes, addr); } uint shift = (addr & 3u) * 8u; uint aligned = addr & ~3u; diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/typed-load-layout.msl b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/typed-load-layout.msl index a94f36bbf..40cfab515 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/typed-load-layout.msl +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/typed-load-layout.msl @@ -493,12 +493,14 @@ static inline uint sharpemu_load_tail(device uint* b, uint bytes, uint aligned) // A dword a format access may straddle, assembled from the two it spans. Only the // format path needs this: a descriptor's stride is a byte count, so a component can -// start at any byte. +// start at any byte. A component address wraps at 2^32 (a component past the top of the byte +// space reads the binding's first bytes), so the in-range test of an aligned dword is +// (addr | 3) < bytes, its last byte: addr + 4 would wrap to 0 for the last dword of the space. static inline uint sharpemu_load_word(device uint* b, uint bytes, uint addr) { if ((addr & 3u) == 0u) { - return addr + 4u <= bytes ? b[addr >> 2] : sharpemu_load_tail(b, bytes, addr); + return (addr | 3u) < bytes ? b[addr >> 2] : sharpemu_load_tail(b, bytes, addr); } uint shift = (addr & 3u) * 8u; uint aligned = addr & ~3u; diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/typed-store-layout.msl b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/typed-store-layout.msl index 53ce3e6c7..c50845a82 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/typed-store-layout.msl +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/typed-store-layout.msl @@ -493,12 +493,14 @@ static inline uint sharpemu_load_tail(device uint* b, uint bytes, uint aligned) // A dword a format access may straddle, assembled from the two it spans. Only the // format path needs this: a descriptor's stride is a byte count, so a component can -// start at any byte. +// start at any byte. A component address wraps at 2^32 (a component past the top of the byte +// space reads the binding's first bytes), so the in-range test of an aligned dword is +// (addr | 3) < bytes, its last byte: addr + 4 would wrap to 0 for the last dword of the space. static inline uint sharpemu_load_word(device uint* b, uint bytes, uint addr) { if ((addr & 3u) == 0u) { - return addr + 4u <= bytes ? b[addr >> 2] : sharpemu_load_tail(b, bytes, addr); + return (addr | 3u) < bytes ? b[addr >> 2] : sharpemu_load_tail(b, bytes, addr); } uint shift = (addr & 3u) * 8u; uint aligned = addr & ~3u; diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/vertex-layout.msl b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/vertex-layout.msl index 38bb28880..4f667854c 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/vertex-layout.msl +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Goldens/vertex-layout.msl @@ -319,12 +319,14 @@ static inline uint sharpemu_load_tail(device uint* b, uint bytes, uint aligned) // A dword a format access may straddle, assembled from the two it spans. Only the // format path needs this: a descriptor's stride is a byte count, so a component can -// start at any byte. +// start at any byte. A component address wraps at 2^32 (a component past the top of the byte +// space reads the binding's first bytes), so the in-range test of an aligned dword is +// (addr | 3) < bytes, its last byte: addr + 4 would wrap to 0 for the last dword of the space. static inline uint sharpemu_load_word(device uint* b, uint bytes, uint addr) { if ((addr & 3u) == 0u) { - return addr + 4u <= bytes ? b[addr >> 2] : sharpemu_load_tail(b, bytes, addr); + return (addr | 3u) < bytes ? b[addr >> 2] : sharpemu_load_tail(b, bytes, addr); } uint shift = (addr & 3u) * 8u; uint aligned = addr & ~3u; diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslFormatLoadWrapTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslFormatLoadWrapTests.cs new file mode 100644 index 000000000..3126d3821 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslFormatLoadWrapTests.cs @@ -0,0 +1,219 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.ShaderCompiler.Metal.Tests; + +// A formatted load reads component c from byte (elementAddress + componentOffset) in 32 bits, and +// only the components a destination selects are bounds checked, each on its own. With the element +// at 2^32 - 4 (plus 0-3 bytes), Y, Z and W wrap to the buffer's first bytes; with only those +// selected the load reads them, aligned or not. The Metal twin of BufferFormatWrapDeviceTests +// (upstream 7cf0ac568). The run-time word 3 paths (fetch, decoder, inline, GLC, function +// constant) are in MslRuntimeFormatLoadTests.Wrap.cs. +public sealed class MslFormatLoadWrapTests(ITestOutputHelper output) +{ + private const int BufferBytes = 64; + private const uint Uint32x4 = 75; + private const uint Uint16x2 = 27; + // x = Y, y = Z, z = W, w = 0. + private const uint YzwZero = 5 | (6 << 3) | (7 << 6); + private const ulong GuestBase = 0x4000_0000; + private const int GuestBytes = 1 << 14; + private const int DeviceBufferOffset = 0x1000; + private const int BoundBytes = 1024; + + // The descriptor word 3 is a literal (the bound path's specialized word): a format of whole + // dwords loads its selected components as one run (TryEmitLiteralDwordFormatLoad). + [Theory] + [InlineData(0u)] + [InlineData(1u)] + [InlineData(3u)] + public void ComponentsPastTheTopOfTheByteSpaceWrapToTheBuffersStart(uint misalignment) + { + var shader = CompileLiteral(0xFFFF_FFFCu + misalignment, (Uint32x4 << 12) | YzwZero, components: 4); + if (!RequireDevice()) return; + + var bytes = Pattern(BufferBytes); + var result = Run(shader, bytes); + uint Bytes(uint first) => BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan((int)first)); + Assert.Equal([Bytes(misalignment), Bytes(misalignment + 4), Bytes(misalignment + 8), 0u], Words(result, 0, 4)); + } + + // An X component out of range still reads every destination as its constant when it is + // selected, wrapped neighbours or not: the selected components are all or nothing. + [Fact] + public void ASelectedComponentOutOfRangeZeroesTheWrappedOnes() + { + var shader = CompileLiteral(0xFFFF_FFFCu, (Uint32x4 << 12) | DescriptorConstants.IdentityDestinationSelect, components: 4); + if (!RequireDevice()) return; + + Assert.Equal([0u, 0u, 0u, 0u], Words(Run(shader, Pattern(BufferBytes)), 0, 4)); + } + + // A packed format with a literal word 3 (BeginLiteralPackedFormatLoad): the Y half of a 16_16 + // element two bytes below 2^32 is the buffer's first two bytes. + [Fact] + public void APackedComponentWrapsToTheBuffersStart() + { + var shader = CompileLiteral(0xFFFF_FFFEu, (Uint16x2 << 12) | 5u, components: 1); + if (!RequireDevice()) return; + + var bytes = Pattern(BufferBytes); + Assert.Equal((uint)BinaryPrimitives.ReadUInt16LittleEndian(bytes), Words(Run(shader, bytes), 0, 1)[0]); + } + + // The V# in scalar registers (read from guest memory, OOB_SELECT 3): the components are + // placed and checked at their own wrapped offsets from the descriptor's base. + [Theory] + [InlineData(0u)] + [InlineData(1u)] + [InlineData(3u)] + public void ADeviceDescriptorLoadWrapsItsComponentsToTheBuffersStart(uint misalignment) + { + var request = DeviceRequest(0xFFFF_FFFCu + misalignment); + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error), error); + if (!RequireDevice()) return; + + var guest = new byte[GuestBytes]; + var descriptor = new uint[] { (uint)(GuestBase + DeviceBufferOffset), 0, BufferBytes, (Uint32x4 << 12) | YzwZero | (3u << 28) }; + for (var word = 0; word < descriptor.Length; word++) + { + BinaryPrimitives.WriteUInt32LittleEndian(guest.AsSpan(word * 4), descriptor[word]); + } + + Pattern(BufferBytes).CopyTo(guest.AsSpan(DeviceBufferOffset)); + var bound = new byte[BoundBytes]; + BinaryPrimitives.WriteUInt32LittleEndian(bound.AsSpan(BoundBytes - 4), (uint)GuestBase); + var (tables, _) = MetalNative.CreateGuestMapping(GuestBase, guest, 0x1000); + Assert.True(MetalNative.TryCompileLibrary(shader!.Source, out var library, out var compileError), compileError); + try + { + Assert.True(MetalNative.TryExecuteWithArgumentBuffer(library, shader.EntryPoint, bound, + new byte[PushData.ByteSize], shader.ArgumentLayout!, 1, out var result, out _, out var runError, + tables: tables), runError); + uint Bytes(uint first) => + BinaryPrimitives.ReadUInt32LittleEndian(guest.AsSpan(DeviceBufferOffset + (int)first)); + Assert.Equal([Bytes(misalignment), Bytes(misalignment + 4), Bytes(misalignment + 8), 0u], Words(result, 0, 4)); + } + finally + { + MetalNative.ReleaseCollisionLibrary(library); + } + } + + // sharpemu_load_word at the last aligned dword of the byte space reads past the binding, + // so it reads zero; it must not take the in-range branch because addr + 4 wrapped to 0. + [Theory] + [InlineData(0xFFFF_FFFCu)] + [InlineData(0xFFFF_FFFDu)] + [InlineData(0xFFFF_FFFFu)] + public void AWordLoadAtTheTopOfTheByteSpaceReadsZero(uint address) + { + const string Kernel = @" +kernel void top_word_test(device uint* b [[buffer(0)]], uint t [[thread_position_in_threadgroup]]) +{ + uint addr = b[0]; + uint4 words = sharpemu_load_words<4>(b, 64u, addr); + b[1] = sharpemu_load_word(b, 64u, addr); + b[2] = words.x; +} +"; + if (!RequireDevice()) return; + + var prelude = Gen5NggFixtures.CompileOrThrow(Gen5NggFixtures.CullingTriangle()).Source; + Assert.True(MetalNative.TryCompileLibrary(prelude + Kernel, out var library, out var compileError), compileError); + var contents = Pattern(BufferBytes); + BinaryPrimitives.WriteUInt32LittleEndian(contents, address); + Assert.True(MetalNative.TryExecuteOnBuffer(library, "top_word_test", contents, 1, out var result, out var error), error); + // The bytes past 2^32 wrap to the binding's first ones; the bytes below it are past the end. + var shift = (int)((address & 3) * 8); + var expected = shift == 0 ? 0u : BinaryPrimitives.ReadUInt32LittleEndian(contents) << (32 - shift); + Assert.Equal([expected, expected], Words(result, 1, 2)); + } + + private bool RequireDevice() + { + if (MetalNative.IsAvailable) return true; + Assert.False( + OperatingSystem.IsMacOS() && Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") == "1", + "The required gate cannot run the format wrap test without a Metal device."); + output.WriteLine("No Metal device on this host; the format wrap test skipped."); + return false; + } + + private static byte[] Pattern(int length) => Enumerable.Range(0, length).Select(index => (byte)index).ToArray(); + + private static uint[] Words(byte[] bytes, int first, int count) => + Enumerable.Range(first, count).Select(index => BinaryPrimitives.ReadUInt32LittleEndian(bytes.AsSpan(index * 4))).ToArray(); + + private static byte[] Run(Gen5MslShader shader, byte[] bytes) + { + Assert.True(MetalNative.TryCompileLibrary(shader.Source, out var library, out var compileError), compileError); + Assert.True( + MetalNative.TryExecuteWithArgumentBuffer( + library, shader.EntryPoint, bytes, new byte[PushData.ByteSize], shader.ArgumentLayout!, 1, + out var result, out var runError), + runError); + return result; + } + + // v1 = the byte offset (OFFEN); buffer_load_format_x / _xyzw v[4:], v1, s[8:11], 0 offen; the + // loaded registers stored from byte 0. + private static Gen5MslShader CompileLiteral(uint offset, uint word3, uint components) + { + var fixture = new Gen5ComputeFixture( + "format-load-wrap", + [ + 0x7E0202FF, offset, // v_mov_b32 v1, offset + 0xE0001000 | ((components - 1) << 18), 0x80020401, // buffer_load_format v[4:], v1, s[8:11], 0 offen + components == 4 ? 0xE0780000 : 0xE0700000, 0x80020400, // buffer_store_dword(x4) v[4:], off, s[8:11], 0 + 0xBF810000, // s_endpgm + ], + 8, + BufferBytes); + var userData = new uint[16]; + userData[8] = 0x200000; + userData[9] = 0; + userData[10] = BufferBytes; + userData[11] = word3; + var request = Gen5ComputeFixtures.RequestOrThrow( + Gen5ComputeFixtures.DecodeOrThrow(fixture), + ShaderStage.Compute, + runtimeInputs: new ResourceRuntimeInputs { UserData = userData }); + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error), error); + return shader!; + } + + // s[12:15] = the V# at the guest address the bound buffer's last dword names; v1 = the byte + // offset; buffer_load_format_xyzw v[4:7], v1, s[12:15], 0 offen; v[4:7] stored at byte 0. + private static ShaderCompileRequest DeviceRequest(uint offset) + { + var fixture = new Gen5ComputeFixture( + "device-format-load-wrap", + [ + 0xE03003FC, 0x80020300, // buffer_load_dword v3, off, s[8:11], 0 offset:1020 + 0xBF8C3F70, // s_waitcnt vmcnt(0) + 0x7E080503, // v_readfirstlane_b32 s4, v3 + 0xBE850380, // s_mov_b32 s5, 0 + 0xF4080302, 0xFA000000, // s_load_dwordx4 s[12:15], s[4:5], 0x0 + 0xBF8CC07F, // s_waitcnt lgkmcnt(0) + 0x7E0202FF, offset, // v_mov_b32 v1, offset + 0xE00C1000, 0x80030401, // buffer_load_format_xyzw v[4:7], v1, s[12:15], 0 offen + 0xBF8C3F70, // s_waitcnt vmcnt(0) + 0xE0780000, 0x80020400, // buffer_store_dwordx4 v[4:7], off, s[8:11], 0 + 0xBF810000, // s_endpgm + ], + 8, + BoundBytes); + var userData = new uint[16]; + userData[8] = 0x200000; + userData[10] = BoundBytes; + userData[11] = DescriptorConstants.IdentityDestinationSelect; + return Gen5ComputeFixtures.RequestOrThrow(Gen5ComputeFixtures.DecodeOrThrow(fixture), ShaderStage.Compute, + localSizeX: 1, runtimeInputs: new ResourceRuntimeInputs { UserData = userData }); + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslRuntimeFormatLoadTests.Wrap.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslRuntimeFormatLoadTests.Wrap.cs new file mode 100644 index 000000000..553474866 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslRuntimeFormatLoadTests.Wrap.cs @@ -0,0 +1,75 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using Xunit; + +namespace SharpEmu.ShaderCompiler.Metal.Tests; + +// The run-time word 3 forms of a formatted load whose selected components wrap past 2^32 +// (upstream 7cf0ac568, BufferFormatWrapDeviceTests): the fetch helper, the called decoder, the +// inline decoder, the GLC (coherent, inline) form and the function-constant form each read +// [Y, Z, W, 0] of a 32_32_32_32 element at 2^32 - 4 + m as the buffer's bytes m, m + 4, m + 8. +public sealed partial class MslRuntimeFormatLoadTests +{ + private const uint WrapWord3 = (75u << 12) | 5u | (6u << 3) | (7u << 6); + + public static TheoryData WrapCases() + { + var cases = new TheoryData(); + foreach (var path in new[] { "fetch", "decoded", "inline", "glc", "constant" }) + { + foreach (var misalignment in new uint[] { 0, 1, 3 }) + { + cases.Add(path, misalignment); + } + } + + return cases; + } + + [Theory] + [MemberData(nameof(WrapCases))] + public void SelectedComponentsPastTheTopOfTheByteSpaceWrap(string path, uint misalignment) + { + var options = path switch + { + "fetch" => new Gen5MslCodegenOptions(ForceRegisterInitialization: true) { FormatFetch = true }, + "decoded" => new Gen5MslCodegenOptions(RuntimeDwordFormatLoads: false, ForceRegisterInitialization: true) + { + DecodedFormatLoadThreshold = 1, + FormatFetch = false, + }, + "constant" => ConstantOptions(true), + _ => new Gen5MslCodegenOptions(ForceRegisterInitialization: true) + { + DecodedFormatLoadThreshold = 0, + FormatFetch = false, + }, + }; + var (shader, layout) = Compile(Fixture(4, glc: path == "glc"), options); + var marker = path switch + { + "fetch" => "sharpemu_format_fetch(b", + "decoded" => "sharpemu_format_load_decoded(b", + "constant" => "sharpemu_format_fetch_constant(b", + "glc" => "sharpemu_load_word_coherent(", + _ => "sharpemu_format_layout(", + }; + Assert.Contains(marker, shader.Source); + if (!RequireDevice()) return; + + Assert.True(MetalNative.TryCompileLibrary(shader.Source, out var library, out var compileError), compileError); + var data = Enumerable.Range(0, BufferBytes).Select(i => (byte)(i * 37 + 11)).ToArray(); + IReadOnlyList<(uint Index, uint Value)>? constants = path == "constant" + ? [(Assert.Single(shader.BufferWordConstants).Index, WrapWord3)] + : null; + Assert.True(MetalNative.TryExecuteWithArgumentBuffer(library, shader.EntryPoint, data, + Push(layout, WrapWord3, 0xFFFF_FFFCu + misalignment), shader.ArgumentLayout!, 1, + out var result, out _, out var runError, constants: constants), runError); + uint Bytes(uint first) => BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan((int)first)); + Assert.Equal( + [Bytes(misalignment), Bytes(misalignment + 4), Bytes(misalignment + 8), 0u], + Enumerable.Range(0, 4).Select(index => BinaryPrimitives.ReadUInt32LittleEndian(result.AsSpan(index * 4))).ToArray()); + } +} From 1d6d6d74673faa4ae2ec97cbc3bfefea35d6e1e0 Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 23:48:42 +0000 Subject: [PATCH 079/134] [Shader] Carry a non-indexed mesh draw's first vertex as its base vertex FillDrawInfo wrote the first vertex into draw-info word 5 only for amplified non-indexed draws and the base vertex (0 for a non-indexed draw) otherwise, so a plain non-indexed mesh draw with a first vertex lost it: its vertex ids started at 0 where Metal's [[base_vertex]] and the hardware start at the first vertex. Word 5 is now the base vertex for an indexed draw and the first vertex for a non-indexed one, in FillDrawInfo and in the indirect launch kernel (arguments[2] of a non-indexed record). Tests: ANonIndexedDrawCarriesItsFirstVertexAsTheBaseVertex. In AnIndirectDrawWithGpuWrittenArgumentsRendersLikeTheCpuDraw the CPU reference draw now passes the record's first vertex for a non-indexed draw (it passed 0 while the GPU record carried 6, which encoded the dropped first vertex). --- .../Gen5MslMeshLaunch.cs | 12 +++++---- .../NggMeshIndirectLaunchTests.cs | 25 +++++++++++++++++-- 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslMeshLaunch.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslMeshLaunch.cs index 7bce5e7e3..b6a43f024 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslMeshLaunch.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslMeshLaunch.cs @@ -67,7 +67,8 @@ public static uint SubgroupCount(Gen5MslMeshInfo mesh, Gen5MslMeshInputTopology /// Writes the draw-info words of a draw of whole subgroups (no cached meshlets: words /// 16-18 stay zero). is /// dwords the caller has cleared. is 1 for 16-bit and 2 for - /// 32-bit indices; a non-indexed draw has no first index and no base vertex. + /// 32-bit indices; a non-indexed draw has no first index, and is its first + /// vertex, which word 5 (the base vertex) carries. /// public static void FillDrawInfo( Gen5MslMeshInfo mesh, @@ -86,9 +87,10 @@ public static void FillDrawInfo( words[2] = indexed ? count : 0; words[3] = indexed ? indexType : 0; words[4] = indexed ? firstIndex : 0; - // An amplified draw's workgroup index is its point's vertex index, so a non-indexed - // one counts on from the first vertex. - words[5] = mesh.Amplified && !indexed ? firstIndex : unchecked((uint)baseVertex); + // A non-indexed draw's vertex index counts on from its first vertex, which travels as + // the base vertex (an amplified draw's workgroup index is its point's vertex index too), + // as the vertex path's [[base_vertex]] is vertexStart for a non-indexed draw. + words[5] = indexed ? unchecked((uint)baseVertex) : firstIndex; words[6] = instanceCount; words[7] = firstInstance; // A GS half learns where each subgroup's share of input primitives starts and how @@ -256,7 +258,7 @@ struct sharpemu_mesh_launch_params block[2] = p.indexed != 0u ? count : 0u; block[3] = p.indexed != 0u ? p.index_type : 0u; block[4] = first_index; - block[5] = p.amplified != 0u && p.indexed == 0u ? arguments[2] : base_vertex; + block[5] = p.indexed != 0u ? base_vertex : arguments[2]; block[6] = instances; block[7] = first_instance; for (uint word = 8u; word < 13u; word++) diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/NggMeshIndirectLaunchTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/NggMeshIndirectLaunchTests.cs index 1757fe8ac..47e269a1f 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/NggMeshIndirectLaunchTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/NggMeshIndirectLaunchTests.cs @@ -90,6 +90,26 @@ public void TheLaunchKernelWritesWhatTheCpuDrawWrites() } } + // A non-indexed draw counts its vertices from its first vertex: the draw-info block's base + // vertex (word 5) carries it for every program, amplified or not, as [[base_vertex]] carries + // vertexStart on the vertex path; an indexed draw keeps its own base vertex there. + [Fact] + public void ANonIndexedDrawCarriesItsFirstVertexAsTheBaseVertex() + { + foreach (var (name, mesh) in Meshes()) + { + var words = new uint[Gen5MslMeshInfo.DrawInfoDwordCount]; + Gen5MslMeshLaunch.FillDrawInfo( + mesh, Gen5MslMeshInputTopology.TriangleList, words, 36, 1, indexed: false, 0, firstIndex: 100, baseVertex: 0, 0); + Assert.True(words[5] == 100u, $"[{name}] non-indexed base vertex {words[5]}"); + Assert.Equal(0u, words[4]); + Gen5MslMeshLaunch.FillDrawInfo( + mesh, Gen5MslMeshInputTopology.TriangleList, words, 36, 1, indexed: true, IndexType32, firstIndex: 100, baseVertex: -5, 0); + Assert.True(words[5] == unchecked((uint)-5), $"[{name}] indexed base vertex {words[5]}"); + Assert.Equal(100u, words[4]); + } + } + [Fact] public void TheLaunchKernelWritesARectangleListsPatchDraw() { @@ -151,9 +171,10 @@ public void AnIndirectDrawWithGpuWrittenArgumentsRendersLikeTheCpuDraw( Array.Fill(guestIndices, 3u); drawn.CopyTo(guestIndices, (int)firstIndex); - // The CPU draw: the counts read back, the indices bound from the first index on. + // The CPU draw: the counts read back, the indices bound from the first index on; a non-indexed draw counts + // its vertices from the record's first vertex, which the CPU draw passes as its own. var words = new uint[Gen5MslMeshInfo.DrawInfoDwordCount]; - Gen5MslMeshLaunch.FillDrawInfo(mesh, input, words, count, 1, indexed, IndexType32, 0, 0, 0); + Gen5MslMeshLaunch.FillDrawInfo(mesh, input, words, count, 1, indexed, IndexType32, indexed ? 0 : firstIndex, 0, 0); var subgroups = Gen5MslMeshLaunch.SubgroupCount(mesh, input, count); var cpu = Render(library, shader, mesh, Bytes(words), Bytes(drawn), subgroups, indirect: null); From 7c8cded640c4028e2a2667c73d5b1d3009407159 Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 23:48:51 +0000 Subject: [PATCH 080/134] [Tests] Pin formatted stores through a run-time V# and D16_HI_X stores on the device The Metal twins of upstream's DeviceFormatStoreDeviceTests and BufferStoreFormatD16HiDeviceTests (7cf0ac568), for a row judged equivalent by reading. A BUFFER_STORE_FORMAT_X through a V# loaded from guest memory encodes with that V#'s format (8, 8_8 and 8_8_8_8 UNORM, 8 SNORM, 16 FLOAT, 32 FLOAT) and leaves the rest of the dword alone; BUFFER_STORE_FORMAT_D16_HI_X stores the register's high half for every 16-bit UINT, SINT and FLOAT format, through a bound V# and a run-time one. Both pass on the existing translator. --- .../MslFormatStoreDeviceTests.cs | 185 ++++++++++++++++++ 1 file changed, 185 insertions(+) create mode 100644 tests/SharpEmu.ShaderCompiler.Metal.Tests/MslFormatStoreDeviceTests.cs diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslFormatStoreDeviceTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslFormatStoreDeviceTests.cs new file mode 100644 index 000000000..77ecc0477 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslFormatStoreDeviceTests.cs @@ -0,0 +1,185 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.ShaderCompiler.Metal.Tests; + +// Formatted stores executed on the device, the Metal twins of upstream's DeviceFormatStoreDeviceTests and +// BufferStoreFormatD16HiDeviceTests (7cf0ac568). A store through a V# in scalar registers (read from guest memory, +// so its format is only known when the store runs) encodes with that V#'s own format: 8, 8_8 and 8_8_8_8 UNORM, +// 8 SNORM, 16 FLOAT and 32 FLOAT each write their own bytes and leave the rest of the dword alone. A +// BUFFER_STORE_FORMAT_D16_HI_X stores the high half of its register, through a bound V# and a runtime one alike. +public sealed class MslFormatStoreDeviceTests(ITestOutputHelper output) +{ + private const int Lanes = 4; + private const int BoundBytes = 2048; + private const int ValueOffset = 1024; + private const ulong GuestBase = 0x4000_0000; + private const int GuestBytes = 1 << 14; + private const int DeviceBufferOffset = 0x1000; + private const uint Identity = 4 | (5 << 3) | (6 << 6) | (7 << 9); + private static readonly uint[] Values = [0x3F000000, 0x3F800000, 0xBF800000, 0x7FC00000]; + + [Theory] + [InlineData(1u, new uint[] { 0x80, 0xFF, 0x00, 0x00 }, 1)] + [InlineData(14u, new uint[] { 0x80, 0xFF, 0x00, 0x00 }, 1)] + [InlineData(56u, new uint[] { 0x80, 0xFF, 0x00, 0x00 }, 1)] + [InlineData(2u, new uint[] { 0x40, 0x7F, 0x81, 0x00 }, 1)] + [InlineData(13u, new uint[] { 0x3800, 0x3C00, 0xBC00 }, 2)] + [InlineData(22u, new uint[] { 0x3F000000, 0x3F800000, 0xBF800000, 0x7FC00000 }, 4)] + public void FormatsStoreTheirOwnEncodingThroughARuntimeDescriptor(uint format, uint[] expected, int elementBytes) + { + // buffer_store_format_x v4, v1, s[12:15], 0 offen + var stored = RunDevice(0xE0101000, format, Values); + if (stored is null) return; + var elementMask = elementBytes == 4 ? uint.MaxValue : (1u << (elementBytes * 8)) - 1; + for (var lane = 0; lane < expected.Length; lane++) + { + var dword = stored[lane]; + Assert.True(expected[lane] == (dword & elementMask), $"format {format} lane {lane}: 0x{dword:X8}"); + Assert.Equal(0xCCCCCCCCu & ~elementMask, dword & ~elementMask); + } + } + + // 16-bit UINT, SINT and FLOAT. + public static TheoryData D16HiCases() + { + var cases = new TheoryData(); + for (uint format = 1; format < 128; format++) + { + if (Gfx10UnifiedFormat.TryDecode(format, out var dataFormat, out var numberFormat) && + dataFormat == 2 && numberFormat is 4 or 5 or 7) + { + cases.Add(format, false); + cases.Add(format, true); + } + } + + return cases; + } + + // The high half is 1.0 as a half float and a plain 16-bit integer otherwise; the low half is not stored, nor is + // the dword's other half touched. + [Theory] + [MemberData(nameof(D16HiCases))] + public void AD16HiStoreWritesTheHighHalfOfTheRegister(uint format, bool runtimeDescriptor) + { + const uint value = 0x3C00_1234u; + var values = Enumerable.Repeat(value, Lanes).ToArray(); + // buffer_store_format_d16_hi_x v4, v1, s[...], 0 offen + var stored = runtimeDescriptor ? RunDevice(0xE09C1000, format, values) : RunBound(format, values); + if (stored is null) return; + for (var lane = 0; lane < Lanes; lane++) + { + Assert.True(stored[lane] == (0xCCCC0000u | (value >> 16)), $"format {format} lane {lane}: 0x{stored[lane]:X8}"); + } + } + + // v1 = lane * 4; v4 = the lane's value from the bound buffer at 1024; then the store under test at v1. + private static uint[] Words(uint storeWord, uint storeResource, uint offset) => + [ + 0x34020082, // v_lshlrev_b32 v1, 2, v0 + 0xE0301400, 0x80020401, // buffer_load_dword v4, v1, s[8:11], 0 offen offset:1024 + 0xBF8C3F70, // s_waitcnt vmcnt(0) + storeWord | offset, 0x80000401 | (storeResource / 4) << 16, // the store of v4 at v1 (+ offset) + 0xBF810000, // s_endpgm + ]; + + private uint[]? RunBound(uint format, uint[] values) + { + var userData = new uint[16]; + userData[8] = 0x200000; + userData[10] = BoundBytes; + userData[11] = Identity | (format << 12); + var fixture = new Gen5ComputeFixture("bound-format-store", Words(0xE09C1000, 8, 512), 8, BoundBytes); + var shader = Compile(fixture, userData); + if (!RequireDevice()) return null; + + var bound = Bound(values); + var result = Execute(shader, bound, tables: null); + return Enumerable.Range(0, Lanes).Select(lane => BinaryPrimitives.ReadUInt32LittleEndian(result.AsSpan(512 + lane * 4))).ToArray(); + } + + // s[12:15] = the V# at guest address 0 (the bound buffer's last dword names the guest base), OOB_SELECT 3. + private uint[]? RunDevice(uint storeWord, uint format, uint[] values) + { + uint[] words = + [ + 0xE03003FC, 0x80020300, // buffer_load_dword v3, off, s[8:11], 0 offset:1020 + 0xBF8C3F70, // s_waitcnt vmcnt(0) + 0x7E080503, // v_readfirstlane_b32 s4, v3 + 0xBE850380, // s_mov_b32 s5, 0 + 0xF4080302, 0xFA000000, // s_load_dwordx4 s[12:15], s[4:5], 0x0 + 0xBF8CC07F, // s_waitcnt lgkmcnt(0) + .. Words(storeWord, 12, 0), + ]; + var userData = new uint[16]; + userData[8] = 0x200000; + userData[10] = BoundBytes; + userData[11] = Identity | (20u << 12); + var shader = Compile(new Gen5ComputeFixture("device-format-store", words, 8, BoundBytes), userData); + if (!RequireDevice()) return null; + + var guest = Enumerable.Repeat((byte)0xCC, GuestBytes).ToArray(); + var descriptor = new uint[] { (uint)(GuestBase + DeviceBufferOffset), 0, 0x1000, Identity | (format << 12) | (3u << 28) }; + for (var word = 0; word < descriptor.Length; word++) + { + BinaryPrimitives.WriteUInt32LittleEndian(guest.AsSpan(word * 4), descriptor[word]); + } + + var bound = Bound(values); + BinaryPrimitives.WriteUInt32LittleEndian(bound.AsSpan(1020), (uint)GuestBase); + var (tables, _) = MetalNative.CreateGuestMapping(GuestBase, guest, 0x1000); + Execute(shader, bound, tables); + return MetalNative.ReadWords(tables[0].Residents[0], (DeviceBufferOffset / 4) + Lanes)[(DeviceBufferOffset / 4)..]; + } + + private static byte[] Bound(uint[] values) + { + var bound = Enumerable.Repeat((byte)0xCC, BoundBytes).ToArray(); + for (var lane = 0; lane < values.Length; lane++) + { + BinaryPrimitives.WriteUInt32LittleEndian(bound.AsSpan(ValueOffset + lane * 4), values[lane]); + } + + return bound; + } + + private static Gen5MslShader Compile(Gen5ComputeFixture fixture, uint[] userData) + { + var request = Gen5ComputeFixtures.RequestOrThrow(Gen5ComputeFixtures.DecodeOrThrow(fixture), ShaderStage.Compute, + localSizeX: Lanes, runtimeInputs: new ResourceRuntimeInputs { UserData = userData }); + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error), error); + return shader!; + } + + private static byte[] Execute(Gen5MslShader shader, byte[] initial, IReadOnlyList? tables) + { + Assert.True(MetalNative.TryCompileLibrary(shader.Source, out var library, out var compileError), compileError); + try + { + Assert.True(MetalNative.TryExecuteWithArgumentBuffer(library, shader.EntryPoint, initial, + new byte[PushData.ByteSize], shader.ArgumentLayout!, Lanes, out var result, out _, out var runError, + tables: tables), runError); + return result; + } + finally + { + MetalNative.ReleaseCollisionLibrary(library); + } + } + + private bool RequireDevice() + { + if (MetalNative.IsAvailable) return true; + Assert.False( + OperatingSystem.IsMacOS() && Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") == "1", + "The required gate cannot run the format store test without a Metal device."); + output.WriteLine("No Metal device on this host; the format store test skipped."); + return false; + } +} From dc2b1b8f1cb768dce1ae4915312f5be12e60e474 Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 23:48:51 +0000 Subject: [PATCH 081/134] [Shader] Load a BVH node only when every 64-byte unit of it is mapped Upstream 7cf0ac568 reads a ray-intersection node only when all of its units are mapped and otherwise returns what the hardware returns for no node: four invalid ids for a box, [+inf, 1.0, invalid, 0] for a triangle. The Metal sharpemu_bvh_fetch read each unmapped dword as zero, so a float32 box whose second unit straddles onto an unmapped page intersected half a node of zeros. sharpemu_bvh_fetch now reports whether every dword resolved (the slow path still records each fault) and sharpemu_bvh_intersect_ray returns the no-node result when it did not. Gen5BvhReference takes the mapping and applies the same rule; the device test compares every lane against it. New theory: a box32 straddling into the page after the guest, and a box16, box32 and triangle on an unmapped page, beside a mapped control node. --- .../Templates/bvh_prelude.msl | 42 +++++++++++++----- .../Gen5BvhReference.cs | 17 +++++--- .../Gen5MslBvhIntersectTests.cs | 43 ++++++++++++++++++- 3 files changed, 86 insertions(+), 16 deletions(-) diff --git a/src/SharpEmu.ShaderCompiler.Metal/Templates/bvh_prelude.msl b/src/SharpEmu.ShaderCompiler.Metal/Templates/bvh_prelude.msl index 98705b41e..516b8192c 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Templates/bvh_prelude.msl +++ b/src/SharpEmu.ShaderCompiler.Metal/Templates/bvh_prelude.msl @@ -53,11 +53,13 @@ static inline float sharpemu_bvh_min(float a, float b) } // The node's dwords, resolved once when the node sits inside one page and dword by -// dword (each through the page table) when it straddles one. An unmapped dword reads -// zero and records the page in the fault bitmap, like every device-address read. A node -// is 64-byte aligned, so one inside a page is read 16 bytes at a time: the dword-wise -// loads took a sixth of GTA V's traversal time. -static inline void sharpemu_bvh_fetch(device const Gen5AddressRange* ranges, uint range_count, device uint* faults, uint fault_words, thread Gen5RangeCache& cache, ulong address, uint count, thread uint* words) +// dword (each through the page table) when it straddles one. Whether every dword is +// mapped: a node with a unit on an unmapped page is not loaded (upstream 7cf0ac568 +// resolves a node's 64-byte units and loads only when all are mapped), and its words +// read zero; the page is recorded in the fault bitmap, like every device-address read. +// A node is 64-byte aligned, so one inside a page is read 16 bytes at a time: the +// dword-wise loads took a sixth of GTA V's traversal time. +static inline bool sharpemu_bvh_fetch(device const Gen5AddressRange* ranges, uint range_count, device uint* faults, uint fault_words, thread Gen5RangeCache& cache, ulong address, uint count, thread uint* words) { bool valid = false; device uint* span = sharpemu_resolve_device_span(ranges, range_count, faults, fault_words, cache, address, count * 4u, valid); @@ -72,12 +74,22 @@ static inline void sharpemu_bvh_fetch(device const Gen5AddressRange* ranges, uin words[quad * 4u + 2u] = value.z; words[quad * 4u + 3u] = value.w; } - return; + return true; } + bool mapped = true; for (uint index = 0u; index < count; index++) { - words[index] = valid ? span[index] : sharpemu_load_device_dword(ranges, range_count, faults, fault_words, cache, address + (ulong)index * 4ul); + if (valid) + { + words[index] = span[index]; + continue; + } + bool word_valid = false; + device uint* word = sharpemu_resolve_device_address(ranges, range_count, faults, fault_words, cache, address + (ulong)index * 4ul, word_valid); + words[index] = word_valid ? *word : 0u; + mapped = mapped && word_valid; } + return mapped; } // GPURT fast_intersect_bbox: the slab interval of one child box, clipped to [0, extent]. @@ -293,19 +305,29 @@ static inline uint4 sharpemu_bvh_intersect_ray(device const Gen5AddressRange* ra if (type <= 1u && index <= last) { uint node[16]; - sharpemu_bvh_fetch(ranges, range_count, faults, fault_words, cache, base + (index << 6), 16u, node); + // An unmapped triangle node returns no hit: t = +inf over 1, an invalid id. + if (!sharpemu_bvh_fetch(ranges, range_count, faults, fault_words, cache, base + (index << 6), 16u, node)) + { + return uint4(0x7F800000u, 0x3F800000u, 0xFFFFFFFFu, 0u); + } return sharpemu_bvh_triangle(node, type, barycentrics, origin, dir, inv_dir); } if (type == 4u && index <= last) { uint node[16]; - sharpemu_bvh_fetch(ranges, range_count, faults, fault_words, cache, base + (index << 6), 16u, node); + if (!sharpemu_bvh_fetch(ranges, range_count, faults, fault_words, cache, base + (index << 6), 16u, node)) + { + return uint4(0xFFFFFFFFu); + } return sharpemu_bvh_box(node, true, grow, sort, extent, origin, inv_dir); } if (type == 5u && index < last) { uint node[28]; - sharpemu_bvh_fetch(ranges, range_count, faults, fault_words, cache, base + (index << 6), 28u, node); + if (!sharpemu_bvh_fetch(ranges, range_count, faults, fault_words, cache, base + (index << 6), 28u, node)) + { + return uint4(0xFFFFFFFFu); + } return sharpemu_bvh_box(node, false, grow, sort, extent, origin, inv_dir); } return uint4(0xFFFFFFFFu); diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5BvhReference.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5BvhReference.cs index ed4de9fa0..9711a6ab4 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5BvhReference.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5BvhReference.cs @@ -26,7 +26,8 @@ public static uint[] Intersect( float extent, float[] origin, float[] direction, - float[] inverseDirection) + float[] inverseDirection, + Func? isMapped = null) { var baseAddress = (((ulong)(descriptor[1] & 0xFF) << 32) | descriptor[0]) << 8; var grow = (descriptor[1] >> 23) & 0xFF; @@ -36,21 +37,27 @@ public static uint[] Intersect( var type = (uint)nodePointer & 7; var index = nodePointer >> 3; - uint[] Fetch(int count) + // A node is loaded only when each of its 64-byte units is mapped (upstream 7cf0ac568's RayNode); null otherwise. + uint[]? Fetch(int count) { var words = new uint[count]; var address = baseAddress + (index << 6); + for (var unit = 0ul; unit * 16 < (ulong)count; unit++) + if (isMapped is not null && !isMapped(address + unit * 64)) + return null; for (var word = 0; word < count; word++) words[word] = readDword(address + (ulong)word * 4); return words; } if (type <= 1 && index <= last) - return Triangle(Fetch(16), type, barycentrics, origin, direction, inverseDirection); + return Fetch(16) is { } triangle + ? Triangle(triangle, type, barycentrics, origin, direction, inverseDirection) + : [0x7F80_0000, 0x3F80_0000, Invalid, 0]; if (type == 4 && index <= last) - return Box(Fetch(16), fp16: true, grow, sort, extent, origin, inverseDirection); + return Fetch(16) is { } box16 ? Box(box16, fp16: true, grow, sort, extent, origin, inverseDirection) : [Invalid, Invalid, Invalid, Invalid]; if (type == 5 && index < last) - return Box(Fetch(28), fp16: false, grow, sort, extent, origin, inverseDirection); + return Fetch(28) is { } box32 ? Box(box32, fp16: false, grow, sort, extent, origin, inverseDirection) : [Invalid, Invalid, Invalid, Invalid]; return [Invalid, Invalid, Invalid, Invalid]; } diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslBvhIntersectTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslBvhIntersectTests.cs index 382c86bed..3ee36c061 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslBvhIntersectTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslBvhIntersectTests.cs @@ -270,6 +270,47 @@ public void AZeroBaseTakesAbsolutePointersAndAnUnmappedNodeFaults() Assert.Equal(0u, faults[mappedPage >> 5] & (1u << (int)(mappedPage & 31))); } + // A node is loaded only when each of its 64-byte units is mapped (upstream 7cf0ac568): a float32 box whose second + // unit is on the unmapped page after the guest, and a box16 and a triangle on an unmapped page, return what the + // hardware returns for no node (four invalid ids; a triangle's +inf / 1 and an invalid id), not a node of zeros. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void ANodeWithAUnitOnAnUnmappedPageIsNotLoaded(bool bvh64) + { + var guest = BuildGuest(); + var node = guest.AsSpan((int)LastNode * 64, 64); + node.Clear(); + uint[] children = [0x10, 0x20, 0x30, 0x40]; + float[][] firstUnitBoxes = [[0f, 0f, 0f, 1f, 1f, 1f], [0f, 0f, 0f, 2f, 1f, 1f]]; + for (var child = 0; child < 4; child++) + BinaryPrimitives.WriteUInt32LittleEndian(node[(child * 4)..], children[child]); + for (var child = 0; child < 2; child++) + for (var component = 0; component < 6; component++) + BinaryPrimitives.WriteSingleLittleEndian(node[(16 + (child * 6 + component) * 4)..], firstUnitBoxes[child][component]); + + var descriptor = Descriptor(); + descriptor[2] = 2000; + const uint Unmapped = 1000; + var rays = new[] + { + AlongX(Pointer(LastNode, TypeBox32)), + AlongX(Pointer(Unmapped, TypeBox16)), + AlongX(Pointer(Unmapped, TypeBox32)), + new Ray(Pointer(Unmapped, 0), 100f, [0.25f, 0.25f, 2f], [0f, 0f, -1f]), + AlongX(Pointer(Box32, TypeBox32)), + }; + var results = Run(guest, new Variant(bvh64, false, descriptor), rays, out var faults); + if (results is null) return; + + for (var lane = 0; lane < 3; lane++) + Assert.Equal([Invalid, Invalid, Invalid, Invalid], results[lane]); + Assert.Equal([0x7F80_0000u, 0x3F80_0000u, Invalid, 0u], results[3]); + Assert.Equal([0x30u, 0x10u, 0x20u, Invalid], results[4]); + var page = (uint)((GuestBase + GuestBytes) >> DeviceAddressPaging.PageBits); + Assert.NotEqual(0u, faults[page >> 5] & (1u << (int)(page & 31))); + } + // Random boxes and triangles around the origin against random rays, some axis-aligned // (zero direction components, infinite inverse), in every variant. [Theory] @@ -540,7 +581,7 @@ uint ReadGuest(ulong address) for (var word = 0; word < words.Length; word++) BinaryPrimitives.WriteUInt32LittleEndian(input.AsSpan(lane * LaneBytes + word * 4), words[word]); expected[lane] = Gen5BvhReference.Intersect(ReadGuest, variant.Descriptor, rays[lane].Pointer, rays[lane].Extent, - rays[lane].Origin, direction, inverse); + rays[lane].Origin, direction, inverse, address => address >= GuestBase && address - GuestBase < GuestBytes); } if (!RequireDevice()) return null; From caa5a3a5c4ce62a6315f3d7f308e8c4db82ee245 Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 23:52:37 +0000 Subject: [PATCH 082/134] [Tests] Read a plain 2D texture through an array instruction via MetalRenderHost Upstream 7cf0ac568 (ResourceMaterializer.SampledArrayRead) specializes a 2D texture read by a 2D_ARRAY instruction as a one-layer 2D array, and the host binds a 2D-array view of the same texture. A scene test through the whole Metal host path (PM4 dispatch, image cache view, MetalRenderHost bindings) reads the same texture by a 2D load and then a 2D-array load of slice 0; both read every texel. It passes on the existing host: MetalCachedImage UsageNeededFor/GetOrCreateView already create the array view. --- .../Scenes/ImageViewSceneTests.cs | 89 +++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/Scenes/ImageViewSceneTests.cs diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ImageViewSceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ImageViewSceneTests.cs new file mode 100644 index 000000000..8a0aaf721 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ImageViewSceneTests.cs @@ -0,0 +1,89 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests.Scenes; + +/// +/// Image views the shared request builder asks of the Metal image cache for programs the materializer specializes +/// (upstream 7cf0ac568), run through MetalRenderHost: a plain 2D texture read by an array instruction through a +/// one-layer 2D-array view (ResourceMaterializer.SampledArrayRead). +/// +public sealed class ImageViewSceneTests(ITestOutputHelper output) : SceneTestBase(output) +{ + private const uint Size = 8; + private const uint Format32Uint = 20; + private const uint BufferFormat = 20; + + // image_load v4 at (x, y) of s[0:7] (2D, or 2D array with v2 = slice 0); stored at dword (y << 4 | x) of s[8:11]. + private static uint[] LoadToBuffer(bool array) => + [ + 0x7E040280, // v_mov_b32_e32 v2, 0 + array ? 0xF0001128 : 0xF0001108, 0x00000400, // image_load v4, v[0:2], s[0:7] dmask:0x1 dim:2D(_ARRAY) unorm + 0xBF8C3F70, // s_waitcnt vmcnt(0) + 0x340A0284, // v_lshlrev_b32_e32 v5, 4, v1 + 0x380A0105, // v_or_b32_e32 v5, v5, v0 + 0x340A0A82, // v_lshlrev_b32_e32 v5, 2, v5 + 0xE0701000, 0x80020405, // buffer_store_dword v4, v5, s[8:11], 0 offen + 0xBF810000, // s_endpgm + ]; + + /// + /// A plain 2D texture read by a 2D load and then by a 2D-array load (slice 0): the second program's image is a + /// one-layer 2D array, so the host has to bind a 2D-array view of the same texture; both read the texels. + /// + [Fact] + public void APlain2DTextureReadByAnArrayInstructionReadsItsTexels() + { + using var rig = CreateRig(); + if (rig is null) return; + var pitch = SceneDraws.LinearPitchBytes(Size, 4); + var texels = new uint[pitch / 4 * Size]; + for (var y = 0u; y < Size; y++) + for (var x = 0u; x < Size; x++) + { + texels[(y * (pitch / 4)) + x] = 0xC0DE0000u | (y << 8) | x; + } + + var image = rig.Memory.Upload(texels, 0x10000); + var plain = Fill(rig, 256, 0xDEADBEEF); + var arrayRead = Fill(rig, 256, 0xDEADBEEF); + var texture = Descriptors.Texture(image, Format32Uint, Size, Size); + var pm4 = new ScenePm4(); + Dispatch(rig, pm4, LoadToBuffer(array: false), [.. texture, .. Descriptors.Buffer(plain, 4, 256, BufferFormat)]); + CsFlush(pm4); + Dispatch(rig, pm4, LoadToBuffer(array: true), [.. texture, .. Descriptors.Buffer(arrayRead, 4, 256, BufferFormat)]); + CsFlush(pm4); + rig.Submit(pm4); + + var plainWords = rig.Read(plain, 256); + var arrayWords = rig.Read(arrayRead, 256); + for (var y = 0u; y < Size; y++) + for (var x = 0u; x < Size; x++) + { + var expected = 0xC0DE0000u | (y << 8) | x; + Assert.True(expected == plainWords[(y << 4) | x], $"2D ({x},{y}): 0x{plainWords[(y << 4) | x]:X8}"); + Assert.True(expected == arrayWords[(y << 4) | x], $"2D array ({x},{y}): 0x{arrayWords[(y << 4) | x]:X8}"); + } + } + + private static void Dispatch(SceneRig rig, ScenePm4 pm4, uint[] program, uint[] userData) + { + var state = new SceneState(1, 1); + state.Context.Clear(); + state.Uconfig.Clear(); + state.ComputeShader(rig.Program(program), Size, Size, 1, userData, true, threadIdComponents: 1); + state.Emit(pm4).DispatchDirect(1, 1, 1); + } + + private static ulong Fill(SceneRig rig, uint dwords, uint value) + { + var address = rig.Memory.Allocate(dwords * 4ul, 256); + rig.Memory.Write(address, Enumerable.Repeat(value, (int)dwords).ToArray()); + return address; + } + + private static ScenePm4 CsFlush(ScenePm4 pm4) => pm4.Event(ScenePm4.EventCsPartialFlush); +} From 4ec43b981dd3f6a135fc234611780d772b51d1b8 Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 23:52:51 +0000 Subject: [PATCH 083/134] [Metal] Keep the low bits of an integer image store, as a signed image stored unsigned Upstream 99f9fe930 (ImageRequestBuilders.UnsignedOfSigned) stores a write-only signed-integer storage image through its unsigned view, so the bits written are the register's low bits. Metal integer texture writes saturate instead: 0xFFFF8000 written to the R16Uint view stored 0xFFFF where the hardware stores 0x8000. The host now writes each written image's component width code (8, 16, 10_10_10_2 or 32 bits, Gen5MslTranslator.StoreComponentWidthCode of its T# format) into bits 12-13 of its run-time store channel map (MetalRenderHost.WriteStoreComponentWidths), and the run-time swizzle store narrows each integer channel to that width (extract_bits, sign-extending for signed kinds) before the write. View creation is unchanged: the unsigned view already came from MetalCachedImage UsageNeededFor / GetOrCreateView. Tests: ImageViewSceneTests.AWriteOnlySignedStorageImageStoresThroughItsUnsignedView through MetalRenderHost (memory holds the low halves; a signed load reads them sign-extended). MetalStoreChannelMapTests now expects the width code (1 for RGBA8) in bits 12-13 of each map, beside the unchanged 12-bit map. Left: an integer store without a run-time store map slot (SHARPEMU_RUNTIME_IMAGE_SWIZZLE=0, heap/indirect images) still saturates. --- .../Gen5MslTranslator.Pixel.cs | 49 +++++++++++++++++- .../V2/MetalRenderHost.Descriptors.cs | 28 ++++++++++ .../MetalStoreChannelMapTests.cs | 7 ++- .../Scenes/ImageViewSceneTests.cs | 51 ++++++++++++++++++- 4 files changed, 131 insertions(+), 4 deletions(-) diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Pixel.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Pixel.cs index 2fb8d92ec..db4ae2c7f 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Pixel.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Pixel.cs @@ -9,6 +9,37 @@ namespace SharpEmu.ShaderCompiler.Metal; public static partial class Gen5MslTranslator { + /// Bit position of a storage image's store width code in its store channel map (whose maps use 12 bits). + public const int StoreWidthCodeShift = 12; + + /// + /// The width code of an image store's components for a T# format, which the host puts in the image's store channel map + /// (MetalRenderHost.WriteStoreComponentWidths): 1 for 8-bit, 2 for 16-bit, 3 for 10_10_10_2 (X, Y, Z 10, W 2) + /// components; 0 for any other format, whose components the store passes whole. + /// + public static uint StoreComponentWidthCode(uint imageFormat) + { + if (!Gfx10UnifiedFormat.TryDecode(GuestImageFormat.Remap(imageFormat), out var dataFormat, out _)) + { + return 0; + } + + var count = Gfx10UnifiedFormat.ComponentCount(dataFormat); + var widths = new uint[count]; + for (var component = 0u; component < count; component++) + { + if (!Gfx10UnifiedFormat.TryGetComponentLayout(dataFormat, component, out _, out _, out widths[component])) + { + return 0; + } + } + + if (count == 0) return 0; + if (widths.All(width => width == 8)) return 1; + if (widths.All(width => width == 16)) return 2; + return count == 4 && widths[0] == 10 && widths[1] == 10 && widths[2] == 10 && widths[3] == 2 ? 3u : 0u; + } + private sealed partial class CompilationContext { @@ -769,10 +800,26 @@ private void EmitRuntimeSwizzleStoreTexel(Gen5ImageControl image, string kind, i var words = Temp("uint4", $"uint4({string.Join(", ", logical)})"); var map = Temp("uint", $"{ShaderDataDword(_request.Bindings.StorageImageSwizzlesDword + (uint)slot / 2)} >> {(uint)slot % 2 * 16}u"); + // An integer store keeps the low bits of each register, where a Metal write saturates: each component is + // narrowed to the width its T# format gives (the map's bits 12-13, StoreComponentWidthCode) first, a signed + // one sign-extended from it. + var width = kind == "float" ? null : Temp("uint", $"(({map}) >> {StoreWidthCodeShift}u) & 3u"); for (var channel = 0u; channel < 4; channel++) { var code = Temp("uint", $"((({map}) >> {channel * 3}u) & 7u) ^ {channel}u"); - components[channel] = ImageTexelComponent(kind, $"({code} < 4u ? {words}[{code} & 3u] : 0u)"); + var raw = $"({code} < 4u ? {words}[{code} & 3u] : 0u)"; + if (width is null) + { + components[channel] = ImageTexelComponent(kind, raw); + continue; + } + + var bits = Temp("uint", + $"{width} == 1u ? 8u : {width} == 2u ? 16u : {width} == 3u ? {(channel == 3 ? 2 : 10)}u : 32u"); + var value = Temp("uint", raw); + components[channel] = kind == "int" + ? $"({bits} == 32u ? as_type({value}) : extract_bits(as_type({value}), 0u, {bits}))" + : $"({bits} == 32u ? {value} : extract_bits({value}, 0u, {bits}))"; } } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs index a3b4aa121..93d7b02fc 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs @@ -636,9 +636,37 @@ internal static bool WriteStageShaderData(uint[] shaderData, ShaderProgramInfo p // Each written image's store channel map, from its bound T# (RuntimeImageSwizzle). RuntimeImageSwizzle.WriteStoreMaps(shaderData, layout, info.Images, snapshot.Images); + WriteStoreComponentWidths(shaderData, layout, info.Images, snapshot.Images); return true; } + // An integer image store keeps the low bits of each register (a write-only 16_SINT image is stored as unsigned bits + // through its R16Uint view, upstream 99f9fe930), where a Metal write saturates a value its format cannot hold. The + // MSL store narrows each component itself from the width code its T# gives (Gen5MslTranslator + // StoreComponentWidthCode), carried in bits 12-13 of the image's store channel map, above the map's 12 bits. + internal static void WriteStoreComponentWidths(uint[] shaderData, BindingLayout layout, IReadOnlyList images, + IReadOnlyList descriptors) + { + if (layout.StorageImageSwizzleCount == 0) + { + return; + } + + for (var index = 0; index < images.Count; index++) + { + var slot = RuntimeImageSwizzle.Slot(images, index); + if (slot < 0 || slot >= layout.StorageImageSwizzleCount || index >= descriptors.Count || + descriptors[index] is not { Length: >= 8 } words) + { + continue; + } + + var code = SharpEmu.ShaderCompiler.Metal.Gen5MslTranslator.StoreComponentWidthCode(GuestImageFormat.FormatOf(words)); + shaderData[(int)layout.StorageImageSwizzlesDword + (slot / 2)] |= + code << (SharpEmu.ShaderCompiler.Metal.Gen5MslTranslator.StoreWidthCodeShift + (slot % 2 * 16)); + } + } + private Exception UserRegisterOutsideUserData(ShaderProgramInfo program, BindingLayout layout, ResourceSnapshot snapshot) { foreach (var register in layout.UserDataRegisters) diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalStoreChannelMapTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalStoreChannelMapTests.cs index 20d12c495..19b5592d2 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalStoreChannelMapTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalStoreChannelMapTests.cs @@ -53,7 +53,12 @@ public void TheShaderDataCarriesEachWrittenImagesStoreChannelMap() var shaderData = new uint[layout.ShaderDataDwordCount]; Assert.True(MetalRenderHost.WriteStageShaderData(shaderData, program, layout, info, snapshot, 0)); - var expected = RuntimeImageSwizzle.StoreChannelMap(ZyxW) | (RuntimeImageSwizzle.StoreChannelMap(X001) << 16); + // Bits 12-13 of each map carry the image's component width code (1: every component 8 bits for RGBA8), which + // the store narrows integer channels by before Metal's saturating integer texture write. + var width = SharpEmu.ShaderCompiler.Metal.Gen5MslTranslator.StoreComponentWidthCode(GuestImageFormat.FormatOf(snapshot.Images[0])); + Assert.Equal(1u, width); + var expected = (RuntimeImageSwizzle.StoreChannelMap(ZyxW) | (width << SharpEmu.ShaderCompiler.Metal.Gen5MslTranslator.StoreWidthCodeShift)) | + ((RuntimeImageSwizzle.StoreChannelMap(X001) | (width << SharpEmu.ShaderCompiler.Metal.Gen5MslTranslator.StoreWidthCodeShift)) << 16); Assert.Equal(expected, shaderData[layout.StorageImageSwizzlesDword]); Assert.NotEqual(RuntimeImageSwizzle.StoreChannelMap(ZyxW), RuntimeImageSwizzle.StoreChannelMap(X001)); Assert.Equal(7u, shaderData[0]); diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ImageViewSceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ImageViewSceneTests.cs index 8a0aaf721..16fb16154 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ImageViewSceneTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ImageViewSceneTests.cs @@ -8,15 +8,28 @@ namespace SharpEmu.Gpu.Metal.Tests.Scenes; /// /// Image views the shared request builder asks of the Metal image cache for programs the materializer specializes -/// (upstream 7cf0ac568), run through MetalRenderHost: a plain 2D texture read by an array instruction through a -/// one-layer 2D-array view (ResourceMaterializer.SampledArrayRead). +/// (upstream 99f9fe930, 7cf0ac568), run through MetalRenderHost: a write-only signed-integer storage image stored +/// through its unsigned view (ImageRequestBuilders.UnsignedOfSigned), and a plain 2D texture read by an array +/// instruction through a one-layer 2D-array view (ResourceMaterializer.SampledArrayRead). /// public sealed class ImageViewSceneTests(ITestOutputHelper output) : SceneTestBase(output) { private const uint Size = 8; + private const uint Format16Sint = 12; private const uint Format32Uint = 20; private const uint BufferFormat = 20; + // v4 = 0xFFFF8000 | (y << 4 | x); image_store v4, v[0:1], s[0:7] dmask:0x1 dim:2D unorm. The program only writes + // the 16_SINT image, so it is compiled as unsigned bits and stores the register's low 16 bits. + private static readonly uint[] StoreSigned = + [ + 0x34080284, // v_lshlrev_b32_e32 v4, 4, v1 + 0x38080104, // v_or_b32_e32 v4, v4, v0 + 0x380808FF, 0xFFFF8000, // v_or_b32_e32 v4, 0xffff8000, v4 + 0xF0201108, 0x00000400, // image_store v4, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm + 0xBF810000, // s_endpgm + ]; + // image_load v4 at (x, y) of s[0:7] (2D, or 2D array with v2 = slice 0); stored at dword (y << 4 | x) of s[8:11]. private static uint[] LoadToBuffer(bool array) => [ @@ -30,6 +43,40 @@ private static uint[] LoadToBuffer(bool array) => 0xBF810000, // s_endpgm ]; + /// + /// The store writes the 16_SINT image through its R16Uint view; a later load of the same image as signed integers + /// (its own R16Sint format) reads each stored value sign-extended, and the bits written back to guest memory are + /// the registers' low halves. + /// + [Fact] + public void AWriteOnlySignedStorageImageStoresThroughItsUnsignedView() + { + using var rig = CreateRig(); + if (rig is null) return; + var imageBytes = (ulong)SceneDraws.LinearPitchBytes(Size, 2) * Size; + var image = rig.Memory.Allocate(imageBytes, 0x10000); + rig.Memory.Write(image, new byte[imageBytes]); + var loaded = Fill(rig, 256, 0xDEADBEEF); + var texture = Descriptors.Texture(image, Format16Sint, Size, Size); + var pm4 = new ScenePm4(); + Dispatch(rig, pm4, StoreSigned, texture); + CsFlush(pm4); + Dispatch(rig, pm4, LoadToBuffer(array: false), [.. texture, .. Descriptors.Buffer(loaded, 4, 256, BufferFormat)]); + CsFlush(pm4); + rig.Submit(pm4); + + var bits = rig.ReadImage(image, Size, Size); + var words = rig.Read(loaded, 256); + for (var y = 0u; y < Size; y++) + for (var x = 0u; x < Size; x++) + { + var expected = unchecked((short)(0x8000u | (y << 4) | x)); + Assert.True(expected == bits[(y * Size) + x], $"memory ({x},{y}): 0x{bits[(y * Size) + x]:X4} vs 0x{expected:X4}"); + var read = words[(y << 4) | x]; + Assert.True(unchecked((uint)(int)expected) == read, $"signed load ({x},{y}): 0x{read:X8} vs 0x{(int)expected:X8}"); + } + } + /// /// A plain 2D texture read by a 2D load and then by a 2D-array load (slice 0): the second program's image is a /// one-layer 2D array, so the host has to bind a 2D-array view of the same texture; both read the texels. From ea911a9e6f1ca01519ecb95db78f06769992fa71 Mon Sep 17 00:00:00 2001 From: kuba Date: Thu, 19 Nov 2026 23:52:51 +0000 Subject: [PATCH 084/134] [Metal] Refuse a device-address range past the address space, and test device data reads Upstream 7cf0ac568 leaves bounded scalar data a compute program only consumes on the GPU in the shader (ScalarDataReadPolicy) and lets the program load a raw buffer's record count itself (DeviceRecordCountPlan). A scene test through MetalRenderHost dispatches such a program twice with the same user data while the count and data words change in between, by WRITE_DATA in one submission and by the CPU between submissions; each dispatch reads the bytes current when it runs. That passed on the existing host: the guest windows are no-copy views and BindDeviceAddressRanges orders each range after pending writes. The Vulkan presenter (ObtainDeviceAddressRanges) refuses an evaluated range past the 2^40-byte space the caches track and lets an unmapped read-only range read zero. BindDeviceAddressRanges skipped both silently; it now refuses the first the same way ("A device-address range is outside the cache") and keeps reading an unmapped page in the space as zero, both covered by the scene test. --- .../V2/MetalRenderHost.Descriptors.cs | 15 +- .../Scenes/DeviceDataReadSceneTests.cs | 180 ++++++++++++++++++ 2 files changed, 194 insertions(+), 1 deletion(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/Scenes/DeviceDataReadSceneTests.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs index 93d7b02fc..36589a383 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs @@ -1263,9 +1263,22 @@ private void BindDeviceAddressRanges( continue; } + if (range.Size == 0) + { + continue; + } + + // An evaluated range past the guest address space the caches track is refused, as the + // Vulkan presenter refuses it (ObtainDeviceAddressRanges), not read as an unmapped page. + if (range.Base >= MetalImagePageOwners.AddressSpaceSize || range.Size > MetalImagePageOwners.AddressSpaceSize - range.Base) + { + throw Fatal($"A device-address range is outside the cache: handle={range.Handle} base=0x{range.Base:X16} " + + $"size=0x{range.Size:X} hash=0x{stage.Program.Hash:X16}."); + } + // A pointer to an unmapped page resolves to null in the shader, which drops // the access; there is nothing to publish, invalidate or wait for. - if (range.Size == 0 || range.Base == 0 || !_memory.CanRead(range.Base, 1)) + if (range.Base == 0 || !_memory.CanRead(range.Base, 1)) { continue; } diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DeviceDataReadSceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DeviceDataReadSceneTests.cs new file mode 100644 index 000000000..88c20082f --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/DeviceDataReadSceneTests.cs @@ -0,0 +1,180 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests.Scenes; + +/// +/// Guest data a compute program reads on the device (upstream 7cf0ac568), through MetalRenderHost: a scalar data word +/// the program only consumes on the GPU (ScalarDataReadPolicy leaves the s_load in the shader) and the record count of +/// a raw buffer that the program itself loads (DeviceRecordCountPlan). Both live in guest memory and change between +/// two dispatches with the same user data; each dispatch must read the bytes current when it runs, not those of the +/// earlier dispatch nor those written after it. +/// +public sealed class DeviceDataReadSceneTests(ITestOutputHelper output) : SceneTestBase(output) +{ + private const uint Threads = 8; + private const uint FirstCount = 6; + private const uint FirstData = 0xA1A1_0001; + private const uint SecondCount = 3; + private const uint SecondData = 0xB2B2_0002; + private const uint Untouched = 0xCCCC_CCCC; + + // s2 = the count dword (s_buffer_load through the V# in s[8:11]), s5 = the data dword at the address in s[6:7]; + // every lane stores s5 at index v0 through the V# in s[0:3] whose NUM_RECORDS is s2, so lanes at or past the count + // store nothing. + private static readonly uint[] Program = + [ + 0xF4200084, 0xFA000000, // s_buffer_load_dword s2, s[8:11], 0x0 + 0xF4000143, 0xFA000000, // s_load_dword s5, s[6:7], 0x0 + 0xBF8CC07F, // s_waitcnt lgkmcnt(0) + 0x7E080205, // v_mov_b32 v4, s5 + 0xE0702000, 0x80000400, // buffer_store_dword v4, v0, s[0:3], 0 idxen + 0xBF810000, // s_endpgm + ]; + + /// The program takes the two device-read paths this test is about. + [Fact] + public void TheProgramReadsItsCountAndDataOnTheDevice() + { + using var rig = CreateRig(); + if (rig is null) return; + var address = rig.Program(Program); + Assert.True(Gen5ShaderTranslator.TryDecodeProgram(new CpuContext(rig.Memory, Generation.Gen5), address, out var program, out var error), error); + var onDevice = ShaderResourcePlan.Extract(program, ShaderStage.Compute, 0xD47A, 0, 12, scalarDataOnDevice: true, deviceRecordCounts: true); + var onHost = ShaderResourcePlan.Extract(program, ShaderStage.Compute, 0xD47B, 0, 12, scalarDataOnDevice: false, deviceRecordCounts: true); + Assert.NotNull(onDevice.DeviceRecordCounts); + Assert.True(onDevice.TableReads.Count < onHost.TableReads.Count, + $"device reads {onDevice.TableReads.Count}, host-flattened reads {onHost.TableReads.Count}"); + } + + /// The command processor rewrites both words between the dispatches (WRITE_DATA), in one submission. + [Fact] + public void BothDispatchesReadTheWordsCurrentWhenTheyRunWithinOneSubmission() + { + using var rig = CreateRig(); + if (rig is null) return; + var (count, data, stored, userData) = Setup(rig); + var pm4 = new ScenePm4(); + Dispatch(rig, pm4, userData); + pm4.Event(ScenePm4.EventCsPartialFlush); + pm4.Packet(ScenePm4.OpWriteData, 1u << 8, (uint)count, (uint)(count >> 32), SecondCount); + pm4.Packet(ScenePm4.OpWriteData, 1u << 8, (uint)data, (uint)(data >> 32), SecondData); + Dispatch(rig, pm4, userData); + pm4.Event(ScenePm4.EventCsPartialFlush); + rig.Submit(pm4); + Check(rig, stored); + } + + /// The CPU rewrites both words between two submissions. + [Fact] + public void BothDispatchesReadTheWordsCurrentWhenTheCpuChangesThemBetweenSubmissions() + { + using var rig = CreateRig(); + if (rig is null) return; + var (count, data, stored, userData) = Setup(rig); + var first = new ScenePm4(); + Dispatch(rig, first, userData); + first.Event(ScenePm4.EventCsPartialFlush); + rig.Submit(first); + Assert.Equal([.. Enumerable.Repeat(FirstData, (int)FirstCount), .. Enumerable.Repeat(Untouched, (int)(Threads - FirstCount))], + rig.Read(stored, (int)Threads)); + + rig.Memory.Write(count, [SecondCount]); + rig.Memory.Write(data, [SecondData]); + var second = new ScenePm4(); + Dispatch(rig, second, userData); + second.Event(ScenePm4.EventCsPartialFlush); + rig.Submit(second); + Check(rig, stored); + } + + /// + /// A data word on an unmapped page of the address space reads zero through the page table, as on the Vulkan host + /// (VulkanVideoPresenter.ObtainDeviceAddressRanges: an unmapped read-only range resolves to zero), and nothing is + /// refused. + /// + [Fact] + public void ADataWordOnAnUnmappedPageReadsZero() + { + using var rig = CreateRig(); + if (rig is null) return; + var (_, _, stored, userData) = Setup(rig); + var unmapped = SceneMemory.Base + SceneMemory.Size + 0x10000; + userData[6] = (uint)unmapped; + userData[7] = (uint)(unmapped >> 32); + var pm4 = new ScenePm4(); + Dispatch(rig, pm4, userData); + pm4.Event(ScenePm4.EventCsPartialFlush); + rig.Submit(pm4); + Assert.Empty(rig.Fatals); + Assert.Equal([.. Enumerable.Repeat(0u, (int)FirstCount), .. Enumerable.Repeat(Untouched, (int)(Threads - FirstCount))], + rig.Read(stored, (int)Threads)); + } + + /// + /// A data word past the 2^40-byte guest address space the caches track is refused, as the Vulkan host refuses it + /// ("A device-address range is outside the cache"), instead of being read as an unmapped page. + /// + [Fact] + public void ADataWordOutsideTheAddressSpaceIsRefused() + { + using var rig = CreateRig(); + if (rig is null) return; + var (_, _, _, userData) = Setup(rig); + userData[6] = 0; + userData[7] = 1u << 9; // 2^41 + var pm4 = new ScenePm4(); + Dispatch(rig, pm4, userData); + pm4.Event(ScenePm4.EventCsPartialFlush); + Assert.Throws(() => rig.Submit(pm4)); + Assert.Contains(rig.Fatals, message => message.Contains("outside the cache", StringComparison.Ordinal)); + } + + private static (ulong Count, ulong Data, ulong Stored, uint[] UserData) Setup(SceneRig rig) + { + var count = rig.Memory.Allocate(256, 256); + rig.Memory.Write(count, [FirstCount, 0, 0, 0]); + var data = rig.Memory.Allocate(256, 256); + rig.Memory.Write(data, [FirstData, 0, 0, 0]); + var stored = rig.Memory.Allocate(Threads * 4ul, 256); + rig.Memory.Write(stored, Enumerable.Repeat(Untouched, (int)Threads).ToArray()); + uint[] userData = + [ + .. Descriptors.Buffer(stored, 4, 0, 20), // s[0:3]; NUM_RECORDS is replaced by the loaded count + 0, 0, // s[4:5] + (uint)data, (uint)(data >> 32), // s[6:7] + .. Descriptors.Buffer(count, 0, 16, 20), // s[8:11] + ]; + return (count, data, stored, userData); + } + + // The second dispatch stores the second data word into its first SecondCount records; the records past them keep + // what the first dispatch stored, and those past FirstCount are untouched. + private static void Check(SceneRig rig, ulong stored) + { + Assert.Empty(rig.Fatals); + uint[] expected = + [ + .. Enumerable.Repeat(SecondData, (int)SecondCount), + .. Enumerable.Repeat(FirstData, (int)(FirstCount - SecondCount)), + .. Enumerable.Repeat(Untouched, (int)(Threads - FirstCount)), + ]; + var words = rig.Read(stored, (int)Threads); + Assert.True(expected.SequenceEqual(words), string.Join(" ", words.Select(word => word.ToString("X8")))); + } + + private static void Dispatch(SceneRig rig, ScenePm4 pm4, uint[] userData) + { + var state = new SceneState(1, 1); + state.Context.Clear(); + state.Uconfig.Clear(); + state.ComputeShader(rig.Program(Program), Threads, 1, 1, userData, groupIdX: false, threadIdComponents: 1); + state.Emit(pm4).DispatchDirect(1, 1, 1); + } +} From e51d1040b61f00de5a70dc6aa5e0dbfdafe207d8 Mon Sep 17 00:00:00 2001 From: kuba Date: Fri, 20 Nov 2026 00:02:33 +0000 Subject: [PATCH 085/134] [Metal] Break the replay item chain on relay commands, not on batch starts CurrentItemSequence moved at every command-thread batch start. In scenes the worker often outruns the producer, so batches are short and most consecutive draws looked non-consecutive (about 290 replays in 1500 identical draws). Between two batches the worker does two things. Relay commands run arbitrary work posted from other threads. Coalesced commits change the command buffer, which the replay already checks. The sequence is now the number of items that have ended plus the number of relay commands the worker has run (MetalGpuWorkerRelay.CommandsRun), so only a relay command breaks the chain, as it does between two items of one batch. Upstream's Vulkan host counts executed items the same way. The scene tests now apply their change to the first sealed item that follows a replay, not to a fixed call number, so batch timing no longer decides whether they hit the case they test. ReplaySealed exposes the seal to the tests. --- .../SharpEmu.Gpu.Metal/V2/MetalGpuWorker.cs | 9 +++ .../V2/MetalRenderHost.CommandThread.cs | 7 +-- .../V2/MetalRenderHost.Replay.cs | 18 ++++-- .../Scenes/ReplaySceneTests.cs | 56 ++++++++++--------- 4 files changed, 53 insertions(+), 37 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWorker.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWorker.cs index 7b53635a0..f91fbbce4 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWorker.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalGpuWorker.cs @@ -112,6 +112,14 @@ public bool TryPost(Action work) return true; } + private long _commandsRun; + + /// + /// Relay commands the worker has run so far. Read on the worker: a command that ran between two items breaks + /// draw and dispatch replay's item chain (MetalRenderHost.Replay.cs). + /// + internal long CommandsRun => _commandsRun; + public void RunPendingCommands() { if (!IsGpuQueueThread) @@ -128,6 +136,7 @@ public void RunPendingCommands() Interlocked.Decrement(ref _pendingCount); } + _commandsRun++; command(); } } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CommandThread.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CommandThread.cs index e6364fc09..50dfb8cf2 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CommandThread.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CommandThread.cs @@ -67,9 +67,6 @@ private void RunCommandThreadBatch() Console.Error.WriteLine($"[METAL-V2][QOS] command_stream requested=UserInteractive applied={_commandThread.HasHostQos}."); } - // Whatever the worker did since the last batch is not an item: the first item of this one does not follow the - // last of the batch before (MetalRenderHost.Replay.cs). - _replayItemSequence++; var deadline = System.Diagnostics.Stopwatch.GetTimestamp() + System.Diagnostics.Stopwatch.Frequency / 100; int ran; using (SharpEmu.Libs.VideoOut.RenderPhaseProfile.Measure(SharpEmu.Libs.VideoOut.RenderPhaseProfile.Phase.CommandStream)) @@ -126,15 +123,13 @@ private void RequestIdleCommit() // held: they change the caches it reads. private void RunRelayBetweenCommandItems() { - // An item ended; relay commands run between items count as one more (MetalRenderHost.Replay.cs). + // An item ended (MetalRenderHost.Replay.cs: CurrentItemSequence). _replayItemSequence++; if (!_relay.HasPendingCommands) { return; } - _replayItemSequence++; - var prefetch = _translation?.Prefetch; prefetch?.Pause(); try diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Replay.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Replay.cs index 3e107809a..196ecdd57 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Replay.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Replay.cs @@ -52,9 +52,9 @@ namespace SharpEmu.Gpu.Metal.V2; /// /// A draw is also refused when the render pass it was sealed in has ended (upstream's scope rule): binding state is /// re-sent to whatever encoder is open, but a pass end can land copies and write-backs the captured state does not -/// see. The item sequence counts the command thread's items (MetalRenderHost.CommandThread.cs): a batch boundary or -/// relay commands between two items break the chain, and the slice mode (SHARPEMU_METAL_V2_COMMAND_THREAD=0) has -/// no sequence, so nothing replays there. +/// see. The item sequence counts the command thread's items (MetalRenderHost.CommandThread.cs) and the relay commands +/// the worker ran: a relay command between two items breaks the chain. The slice mode +/// (SHARPEMU_METAL_V2_COMMAND_THREAD=0) has no sequence, so nothing replays there. /// /// Replay lives wholly in the GPU process: the shared engine and this host both run there (SplitGpuHost composes /// MetalV2Backend in process B and runs the submitted command streams itself), so nothing of it crosses the split. @@ -72,7 +72,7 @@ internal sealed partial class MetalRenderHost /// internal Action? ReplayProbe { get; set; } - // Moves with every command-thread item, every relay run between items and every batch (MetalRenderHost.CommandThread.cs). + // Moves when a command-thread item ends (MetalRenderHost.CommandThread.cs); see CurrentItemSequence. private long _replayItemSequence; // PrepareBindings calls per stage kind: a stage object is the captured one only while its count stands. @@ -220,6 +220,9 @@ private enum ReplayMiss internal (long Draws, long Dispatches, long DispatchesRebound) ReplayCounts => (_drawReplaysServed, _dispatchReplaysServed, _dispatchReplaysRebound); + /// Whether a draw (dispatch) is sealed and captured, for tests. + internal bool ReplaySealed(bool dispatch) => (dispatch ? _dispatchReplay : _drawReplay).Sealed; + /// A refusal count by name (capture refusals and replay misses of draws or dispatches), for tests. internal long ReplayCount(bool dispatch, string name) { @@ -260,8 +263,13 @@ private string TakeReplayHostReport() return text; } + // The command-thread items that ended plus the relay commands the worker ran: two items are consecutive only when + // nothing another thread posted ran between them. What else the worker does between two batches either moves + // what the replay checks (a commit: the command buffer) or touches no binding (the counter report). public long CurrentItemSequence => - (DrawReplayEnabled || DispatchReplayEnabled) && UsesCommandThread && _commandThread is not null ? _replayItemSequence : 0; + (DrawReplayEnabled || DispatchReplayEnabled) && UsesCommandThread && _commandThread is not null + ? 1 + _replayItemSequence + _relay.CommandsRun + : 0; /// /// Always 0. Upstream's buffer cache merges and unregisters buffer owners, retiring a binding made earlier in the diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ReplaySceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ReplaySceneTests.cs index 2f2868064..f402cfc95 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ReplaySceneTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ReplaySceneTests.cs @@ -210,31 +210,29 @@ public void ATextureWrittenBetweenDrawsRefusesTheReplayAndIsSampledNew() const uint green = 0xFF00FF00; var texture = SolidTexture(rig, red); var stripes = new Stripes(rig); - var calls = 0; + var probed = false; rig.Host.ReplayProbe = dispatch => { - if (!dispatch && ++calls == 2) + // Once a draw was replayed, the next sealed one finds its texture rewritten. + if (!dispatch && !probed && rig.Host.ReplayCounts.Draws >= 1 && rig.Host.ReplaySealed(false)) { - var before = rig.Host.ImageCache.Epochs.Binding; + probed = true; FillTexture(rig, texture, green); rig.Host.ImageCache.InvalidateMemory(texture, TextureBytes); - Output.WriteLine($"epoch {before} -> {rig.Host.ImageCache.Epochs.Binding}"); } }; var pm4 = new ScenePm4(); - for (var stripe = 0; stripe < 4; stripe++) + for (var stripe = 0; stripe < 8; stripe++) { - stripes.Draw(pm4, stripe * 4, stripe * 4 + 4, Sample, TextureUserData(texture)); + stripes.Draw(pm4, stripe * 2, stripe * 2 + 2, Sample, TextureUserData(texture)); } rig.Submit(pm4); Report(rig, "texture written"); - // Stripes 0 and 1 are not looked at: the CPU rewrote the texels under GPU work that was not finished. - AssertAbgr("stripe 2 (refused, full)", stripes.Pixel(10), green); - AssertAbgr("stripe 3", stripes.Pixel(14), green); - Assert.True(calls >= 2, $"the host was asked for {calls} replays"); + Assert.True(probed, "no sealed draw followed a replayed one"); + // The stripes before the write are not looked at: the CPU rewrote the texels under unfinished GPU work. + AssertAbgr("last stripe", stripes.Pixel(15), green); Assert.True(rig.Host.ReplayCount(false, "images") >= 1, "the moved epoch did not refuse the replay"); - Assert.True(rig.Host.ReplayCounts.Draws >= 1, "the draw before the refused one was not replayed"); Assert.Empty(rig.Fatals); } @@ -246,28 +244,29 @@ public void AReadBindingTheMemoNoLongerAnswersRefusesTheReplay() using var rig = CreateRig(); if (rig is null) return; var stripes = new Stripes(rig); - var calls = 0; + var probed = false; rig.Host.ReplayProbe = dispatch => { - if (!dispatch && ++calls == 2) + if (!dispatch && !probed && rig.Host.ReplayCounts.Draws >= 1 && rig.Host.ReplaySealed(false)) { + probed = true; rig.Host.ReadBindingMemoEnabled = false; } }; var pm4 = new ScenePm4(); - for (var stripe = 0; stripe < 4; stripe++) + for (var stripe = 0; stripe < 8; stripe++) { - stripes.Draw(pm4, stripe * 4, stripe * 4 + 4, ConstantColor, Colour(0, stripe / 4f, 1)); + stripes.Draw(pm4, stripe * 2, stripe * 2 + 2, ConstantColor, Colour(0, stripe / 8f, 1)); } rig.Submit(pm4); Report(rig, "memo off"); - for (var stripe = 0; stripe < 4; stripe++) + for (var stripe = 0; stripe < 8; stripe++) { - AssertColour($"stripe {stripe}", stripes.Pixel(stripe * 4 + 2), 0, stripe / 4f, 1); + AssertColour($"stripe {stripe}", stripes.Pixel(stripe * 2 + 1), 0, stripe / 8f, 1); } - Assert.Equal(1, rig.Host.ReplayCounts.Draws); + Assert.True(probed, "no sealed draw followed a replayed one"); Assert.True(rig.Host.ReplayCount(false, "buffers") >= 1, "a read binding the memo did not answer was replayed"); Assert.True(rig.Host.ReplayCount(false, "memo_off") >= 1, "a draw was captured with the memo off"); Assert.Empty(rig.Fatals); @@ -281,27 +280,29 @@ public void ACommandBufferCommittedBetweenDrawsRefusesTheReplay() using var rig = CreateRig(); if (rig is null) return; var stripes = new Stripes(rig); - var calls = 0; + var probed = false; rig.Host.ReplayProbe = dispatch => { - if (!dispatch && ++calls == 2) + if (!dispatch && !probed && rig.Host.ReplayCounts.Draws >= 1 && rig.Host.ReplaySealed(false)) { + probed = true; rig.Host.FlushAndWaitForGpu(); } }; var pm4 = new ScenePm4(); - for (var stripe = 0; stripe < 4; stripe++) + for (var stripe = 0; stripe < 8; stripe++) { - stripes.Draw(pm4, stripe * 4, stripe * 4 + 4, ConstantColor, Colour(stripe / 4f, 1, 0.5f)); + stripes.Draw(pm4, stripe * 2, stripe * 2 + 2, ConstantColor, Colour(stripe / 8f, 1, 0.5f)); } rig.Submit(pm4); Report(rig, "flushed"); - for (var stripe = 0; stripe < 4; stripe++) + for (var stripe = 0; stripe < 8; stripe++) { - AssertColour($"stripe {stripe}", stripes.Pixel(stripe * 4 + 2), stripe / 4f, 1, 0.5f); + AssertColour($"stripe {stripe}", stripes.Pixel(stripe * 2 + 1), stripe / 8f, 1, 0.5f); } + Assert.True(probed, "no sealed draw followed a replayed one"); Assert.True(rig.Host.ReplayCount(false, "serial") >= 1, "no replay was refused across a committed command buffer"); Assert.True(rig.Host.ReplayCounts.Draws >= 1, "the draw before the refused one was not replayed"); Assert.Empty(rig.Fatals); @@ -312,13 +313,15 @@ private uint[] StoreWords(bool replay, Action? probe, out long replays using var rig = CreateRig()!; rig.Host.DrawReplayEnabled = replay; rig.Host.DispatchReplayEnabled = replay; - var calls = 0; + var probed = probe is null; if (probe is not null) { rig.Host.ReplayProbe = dispatch => { - if (dispatch && ++calls == 2) + // Once a dispatch was replayed, the next sealed one finds the change. + if (dispatch && !probed && rig.Host.ReplayCounts.Dispatches >= 1 && rig.Host.ReplaySealed(true)) { + probed = true; probe(rig); } }; @@ -343,6 +346,7 @@ private uint[] StoreWords(bool replay, Action? probe, out long replays Report(rig, $"dispatch replay={replay}"); replays = rig.Host.ReplayCounts.Dispatches; imagesMisses = rig.Host.ReplayCount(true, "images"); + Assert.True(probed, "no sealed dispatch followed a replayed one"); Assert.Empty(rig.Fatals); return [.. rig.Read(first, 64), .. rig.Read(second, 64)]; } From 57be1d2f921947c94adfa0b71aa9ae3ab1a0a150 Mon Sep 17 00:00:00 2001 From: kuba Date: Fri, 20 Nov 2026 00:17:00 +0000 Subject: [PATCH 086/134] [GPU] Mirror the kernel's PRT apertures and AMM area into the GPU process The GPU process of the split has no kernel, so ResidentImageBacking there never read a PRT/AMM hole as zero and stopped the upload where one process reads it. The guest process publishes each range change (PartiallyResidentRanges) and the split sends it with a ResidencyRange call before the kernel call returns; the GPU process zero-fills unmapped pages only inside a mirrored range and registers the lazily backed apertures with its GPU memory manager. Protocol version 8. --- src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs | 8 +- src/SharpEmu.GpuRemote/GpuSplitMessages.cs | 15 ++ src/SharpEmu.GpuSplit/SplitGpuHost.cs | 36 ++++ src/SharpEmu.GpuSplit/SplitGpuSession.cs | 40 +++++ .../GpuMemory/PartiallyResidentRanges.cs | 143 ++++++++++++++++ src/SharpEmu.Libs/Ampr/AmprExports.Amm.cs | 3 + .../Gpu/Images/ResidentImageBacking.cs | 48 ++++++ .../Kernel/KernelRuntimeCompatExports.cs | 2 + .../MetalImageBudgetTests.ResidentLevels.cs | 39 +++++ .../GpuRemoteChannelTests.cs | 3 +- .../SplitResidencyTests.cs | 155 ++++++++++++++++++ 11 files changed, 489 insertions(+), 3 deletions(-) create mode 100644 src/SharpEmu.HLE/GpuMemory/PartiallyResidentRanges.cs create mode 100644 tests/SharpEmu.GpuSplit.Tests/SplitResidencyTests.cs diff --git a/src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs b/src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs index fda4b01d4..1112d82a0 100644 --- a/src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs +++ b/src/SharpEmu.GpuRemote/GpuRemoteProtocol.cs @@ -12,8 +12,9 @@ public static class GpuRemoteProtocol /// 2: the B → A call table, the application block and the split's messages (GpuSplitMessages.cs). /// 3: . /// 4: frame-boundary messages. 5: input-change and display reservations. - /// 6: pending-writeback pages. 7: combined frame, input and writeback layout. - public const uint Version = 7; + /// 6: pending-writeback pages. 7: combined frame, input and writeback layout. + /// 8: . + public const uint Version = 8; } @@ -136,6 +137,9 @@ public enum GpuRemoteSyncOpcode : uint /// → : the waiting half of a split SubmitDone. WaitFrameBoundary = 11, + + /// → nothing: a PRT aperture or the AMM area changed in A. + ResidencyRange = 12, } /// Opcodes of the B → A synchronous call table: what B's GPU code asks of A's video-out state. diff --git a/src/SharpEmu.GpuRemote/GpuSplitMessages.cs b/src/SharpEmu.GpuRemote/GpuSplitMessages.cs index 359b55cb2..d331dd9e1 100644 --- a/src/SharpEmu.GpuRemote/GpuSplitMessages.cs +++ b/src/SharpEmu.GpuRemote/GpuSplitMessages.cs @@ -473,6 +473,21 @@ public struct SpanRequest public ulong BracketId; } +/// +/// A guest range whose unmapped pages GPU reads see as zero (a PRT aperture or the AMM area), set, moved or dropped +/// ( 0) by the guest process's kernel: PartiallyResidentRanges. +/// +[StructLayout(LayoutKind.Sequential)] +public struct ResidencyRangeRequest +{ + public ulong Address; + public ulong Size; + public int Id; + + /// 1: the kernel also registered the range as lazily backed GPU memory (GuestGpuMemoryHook.NoteLazyRange). + public uint LazilyBacked; +} + [StructLayout(LayoutKind.Sequential)] public struct QueryRequest { diff --git a/src/SharpEmu.GpuSplit/SplitGpuHost.cs b/src/SharpEmu.GpuSplit/SplitGpuHost.cs index 56a97e9df..0a74bcb5f 100644 --- a/src/SharpEmu.GpuSplit/SplitGpuHost.cs +++ b/src/SharpEmu.GpuSplit/SplitGpuHost.cs @@ -584,6 +584,10 @@ public int HandleCall(uint opcode, ReadOnlySpan request, Span respon return 0; } + case GpuRemoteSyncOpcode.ResidencyRange: + MirrorResidencyRange(GpuSplitWire.Read(request)); + return 0; + case GpuRemoteSyncOpcode.Query: return Query(GpuSplitWire.Read(request), response); @@ -600,6 +604,38 @@ public int HandleCall(uint opcode, ReadOnlySpan request, Span respon } } + // A PRT aperture or the AMM area the guest process's kernel set, moved or dropped (PartiallyResidentRanges): image + // reads here answer from it as the kernel answers there (ResidentImageBacking), and an aperture the kernel registered + // as lazily backed GPU memory is registered with this process's manager as GuestGpuMemoryHook.NoteLazyRange does + // there, so a managed write into it reaches the caches here and the ledger stays the guest process's. + private void MirrorResidencyRange(in ResidencyRangeRequest call) + { + var range = new PartiallyResidentRanges.Range(call.Id, call.Address, call.Size, call.LazilyBacked != 0); + _ = PartiallyResidentRanges.Mirror(range); + var memory = _memory!; + lock (_lazyRanges) + { + if (_lazyRanges.Remove(call.Id, out var lazy)) + { + memory.UnregisterLazyRange(lazy.Address, lazy.Size); + } + + if (range.LazilyBacked && GuestGpuMemoryHook.IsWithinGpuAddressSpace(range.Address, range.Size)) + { + _lazyRanges[call.Id] = (range.Address, range.Size); + memory.RegisterLazyRange(range.Address, range.Size); + } + } + + Interlocked.Increment(ref _residencyChanges); + } + + private readonly Dictionary _lazyRanges = []; + private long _residencyChanges; + + /// PRT/AMM range changes the guest process sent (). + internal long ResidencyChanges => Interlocked.Read(ref _residencyChanges); + private int BeginBracket(in BracketBeginRequest call, Span response, out int status) { status = GpuSplitStatus.Ok; diff --git a/src/SharpEmu.GpuSplit/SplitGpuSession.cs b/src/SharpEmu.GpuSplit/SplitGpuSession.cs index 79cb28b06..3923d735a 100644 --- a/src/SharpEmu.GpuSplit/SplitGpuSession.cs +++ b/src/SharpEmu.GpuSplit/SplitGpuSession.cs @@ -73,6 +73,7 @@ public sealed class SplitGpuSession : IDisposable private long _protectsApplied; private long _protectsSkipped; private bool _globalsInstalled; + private bool _residencyMirrored; internal SplitGpuSession(GpuRemoteChannel channel, object outboundLock, GuestGpuMemory memory, GuestViewTable viewTable, ISplitGuestSide guest, IDisposable? process = null, IDisposable? memoryServer = null) @@ -261,9 +262,43 @@ private void InstallGlobals() } HostWindowInput.Connect(new SplitGamepadOutput(Writer)); + MirrorResidencyRanges(); _globalsInstalled = true; } + /// + /// Sends the kernel's PRT apertures and AMM area to the GPU process, the current ones now and every change from + /// then on (): its image reads ask the same question of them as the kernel answers + /// here (ResidentImageBacking), and its GPU memory manager covers the lazily backed ones as this process's does. + /// + /// + /// A call, as span registrations are: it returns once the GPU process applied it, so a submission or a span change + /// this process makes after the kernel call that changed a range finds it applied there; and a span the kernel + /// registers inside an aperture after the aperture was set reaches the GPU process's ledger after the aperture's + /// lazy registration, in this process's order. One call per aperture or area change (the kernel's rare calls), none + /// per read. + /// + internal void MirrorResidencyRanges() + { + PartiallyResidentRanges.Attach(SendResidencyRange); + _residencyMirrored = true; + } + + private void SendResidencyRange(PartiallyResidentRanges.Range range) + { + if (!Call(GpuRemoteSyncOpcode.ResidencyRange, new ResidencyRangeRequest + { + Id = range.Id, + Address = range.Address, + Size = range.Size, + LazilyBacked = range.LazilyBacked ? 1u : 0u, + }, LongCallNanoseconds)) + { + Report($"The GPU process did not take PRT/AMM range {range.Id} (0x{range.Address:X16}+0x{range.Size:X}); " + + "its image reads there stop instead of reading unmapped pages as zero."); + } + } + private void SendFusedProgram(ulong entry, ulong entryHeader, ulong continuation, ulong continuationHeader) => _ = Writer.Write(GpuRemoteMessage.FusedProgram, new FusedProgramMessage { @@ -758,6 +793,11 @@ private void Detach() _memory.AttachGpuQueue(null, null); _memory.AttachStores(null, null); FrameOverlapDiagnostic.RemoteReadFault = null; + if (_residencyMirrored) + { + PartiallyResidentRanges.Attach(null); + } + if (_globalsInstalled) { AgcBackendServices.ShaderHeaderObserver = null; diff --git a/src/SharpEmu.HLE/GpuMemory/PartiallyResidentRanges.cs b/src/SharpEmu.HLE/GpuMemory/PartiallyResidentRanges.cs new file mode 100644 index 000000000..508f0e426 --- /dev/null +++ b/src/SharpEmu.HLE/GpuMemory/PartiallyResidentRanges.cs @@ -0,0 +1,143 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.HLE.GpuMemory; + +/// +/// Guest ranges a GPU read may find partly mapped, whose unmapped pages read as zero: the kernel's PRT apertures +/// (sceKernelSetPrtAperture) and the AMM area (Ampr). The kernel answers that question itself in the process that runs it +/// (KernelRuntimeCompatExports.ContainsPrtRange); the GPU process of the two-process split has no kernel, so the guest +/// process publishes each change here and the split mirrors it there (SplitGpuSession, SplitGpuHost). +/// +/// +/// Published (the guest process): the kernel's last value per range, and an observer the split attaches. +/// Attaching replays the current values through the observer under the same lock every later change takes, so the GPU +/// process never receives an older value after a newer one. +/// +/// Mirrored (the GPU process): what the split received. Read lock-free by image reads +/// (ResidentImageBacking); empty in a process with a kernel, so there it changes nothing. +/// +/// Only the extent of each range crosses. Which pages inside it are mapped is the shared view table's, which the +/// GPU process reads live; a range here only lets an unmapped page read as zero, it never makes a read of a page the +/// guest unmapped possible. +/// +public static class PartiallyResidentRanges +{ + /// The id of the AMM area; PRT apertures use their aperture id. + public const int AmmArea = 0x100; + + /// One range: 0 removes the range with that id. + /// The kernel also registered it as a lazily backed range of the GPU memory manager + /// (GuestGpuMemoryHook.NoteLazyRange), which the GPU process's manager has to know as well. + public readonly record struct Range(int Id, ulong Address, ulong Size, bool LazilyBacked); + + private static readonly object _gate = new(); + // Its own lock: the observer holds _gate while the GPU process mirrors the change, which in a test runs in this process. + private static readonly object _mirrorGate = new(); + private static readonly Dictionary _published = []; + private static readonly Dictionary _mirroredById = []; + private static Action? _observer; + private static Range[] _mirrored = []; + + /// The guest process: the kernel set, moved or (size 0) dropped a range. + public static void Publish(int id, ulong address, ulong size, bool lazilyBacked) + { + var range = new Range(id, address, size, lazilyBacked); + lock (_gate) + { + if (size == 0) + { + _ = _published.Remove(id); + } + else + { + _published[id] = range; + } + + // Under the lock: the observer sees the changes in the order the table took them. + _observer?.Invoke(range); + } + } + + /// + /// The guest process: sends every change to from now on, starting with the current + /// value of every range. Null detaches. + /// + public static void Attach(Action? observer) + { + lock (_gate) + { + _observer = observer; + if (observer is null) + { + return; + } + + foreach (var range in _published.Values.OrderBy(static range => range.Id)) + { + observer(range); + } + } + } + + /// The guest process: the ranges as the kernel last published them. + public static Range[] SnapshotPublished() + { + lock (_gate) + { + return [.. _published.Values.OrderBy(static range => range.Id)]; + } + } + + /// The GPU process: a change the guest process published. Returns the value it replaces (size 0: none). + public static Range Mirror(Range range) + { + lock (_mirrorGate) + { + _ = _mirroredById.Remove(range.Id, out var previous); + if (range.Size != 0) + { + _mirroredById[range.Id] = range; + } + + Volatile.Write(ref _mirrored, [.. _mirroredById.Values]); + return previous; + } + } + + /// The ranges this process mirrors (none in a process with a kernel). + public static Range[] Mirrored => Volatile.Read(ref _mirrored); + + /// + /// The GPU process: whether one mirrored range holds all of [address, address + size), as + /// KernelRuntimeCompatExports.ContainsPrtRange answers for an address the caller has translated. + /// + public static bool MirrorContains(ulong address, ulong size) + { + var ranges = Volatile.Read(ref _mirrored); + if (ranges.Length == 0 || size == 0 || address > ulong.MaxValue - size) + { + return false; + } + + foreach (var range in ranges) + { + if (address >= range.Address && size <= range.Size && address - range.Address <= range.Size - size) + { + return true; + } + } + + return false; + } + + /// Tests: forgets the mirrored ranges (a process with a kernel never has any). + public static void ResetMirror() + { + lock (_mirrorGate) + { + _mirroredById.Clear(); + Volatile.Write(ref _mirrored, []); + } + } +} diff --git a/src/SharpEmu.Libs/Ampr/AmprExports.Amm.cs b/src/SharpEmu.Libs/Ampr/AmprExports.Amm.cs index bda20831a..1993e5302 100644 --- a/src/SharpEmu.Libs/Ampr/AmprExports.Amm.cs +++ b/src/SharpEmu.Libs/Ampr/AmprExports.Amm.cs @@ -439,6 +439,9 @@ private static bool TryReserveAmmArea(CpuContext ctx) } _ammAreaReserved = true; + // The GPU process of the split has no kernel to ask (ContainsAmmRange): it is told instead. + SharpEmu.HLE.GpuMemory.PartiallyResidentRanges.Publish( + SharpEmu.HLE.GpuMemory.PartiallyResidentRanges.AmmArea, AmmAreaStart, AmmAreaEnd - AmmAreaStart, lazilyBacked: false); return true; } } diff --git a/src/SharpEmu.Libs/Gpu/Images/ResidentImageBacking.cs b/src/SharpEmu.Libs/Gpu/Images/ResidentImageBacking.cs index 67dad446f..946653c1c 100644 --- a/src/SharpEmu.Libs/Gpu/Images/ResidentImageBacking.cs +++ b/src/SharpEmu.Libs/Gpu/Images/ResidentImageBacking.cs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: GPL-2.0-or-later using SharpEmu.HLE; +using SharpEmu.HLE.GpuMemory; using SharpEmu.Libs.Kernel; namespace SharpEmu.Libs.Gpu.Images; @@ -34,8 +35,55 @@ public static bool TryRead(IGuestBackedSpace backing, ulong address, Span public static bool TryRead(IGuestBackedSpace backing, ulong address, Span destination, bool allowHoles) => backing.TryReadBacking(address, destination) || KernelMemoryCompatExports.TryReadPrtBacking(backing, address, destination) || + TryReadMirroredPrtBacking(backing, address, destination) || allowHoles && TryReadResidentPrefix(backing, address, destination, allowHoles: true); + // PRT backing in a process without the kernel (the GPU process of the two-process split): the guest process mirrors + // its PRT apertures and AMM area (PartiallyResidentRanges), and which pages are mapped is the shared view table's, + // which this process's backing reads. Same result as KernelMemoryCompatExports.TryReadPrtBacking: the address is + // translated as the kernel translates it, mapped 16 KiB chunks are read, and every other byte reads as zero. (The kernel + // reads a mapping that is backed whole in one piece; mappings are 16 KiB aligned, so that is the same bytes.) + // Empty, and so false at once, in a process that has the kernel. + internal static bool TryReadMirroredPrtBacking(IGuestBackedSpace backing, ulong address, Span destination) + { + if (PartiallyResidentRanges.Mirrored.Length == 0) + { + return false; + } + + var size = (ulong)destination.Length; + address = GuestVaHole.TranslateRange(address, size); + if (!PartiallyResidentRanges.MirrorContains(address, size)) + { + return false; + } + + destination.Clear(); + var end = address + size; + for (var chunk = address; chunk < end;) + { + var next = Math.Min(end, (chunk & ~(PrtProbeBytes - 1)) + PrtProbeBytes); + if (backing.IsBackedRange(chunk, next - chunk) && + !backing.TryReadBacking(chunk, destination.Slice((int)(chunk - address), (int)(next - chunk)))) + { + return false; + } + + chunk = next; + } + + Interlocked.Increment(ref _mirroredPrtReads); + return true; + } + + // The kernel's probe size for a partly backed mapping (KernelMemoryCompatExports.PrtResidencyProbeBytes). + private const ulong PrtProbeBytes = 0x4000; + + private static long _mirroredPrtReads; + + /// Image reads answered from the mirrored PRT/AMM ranges (the split's GPU process). + public static long MirroredPrtReads => Interlocked.Read(ref _mirroredPrtReads); + // Copies the backed prefix page by page and zero-fills the unmapped tail. A backed page // after a hole is not a mip chain, so it is rejected unless allowHoles. internal static bool TryReadResidentPrefix(IGuestBackedSpace backing, ulong address, Span destination) => diff --git a/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs b/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs index b0682ee3c..2b601398d 100644 --- a/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs +++ b/src/SharpEmu.Libs/Kernel/KernelRuntimeCompatExports.cs @@ -1104,6 +1104,8 @@ public static int KernelSetPrtAperture(CpuContext ctx) } SharpEmu.HLE.GpuMemory.GuestGpuMemoryHook.NoteLazyRange(apertureId, residentBase, apertureSize); + // The GPU process of the split has no kernel to ask (ContainsPrtRange): it is told instead. + SharpEmu.HLE.GpuMemory.PartiallyResidentRanges.Publish(apertureId, residentBase, apertureSize, lazilyBacked: true); Console.Error.WriteLine( $"[LOADER][TRACE] set_prt_aperture: id={apertureId} base=0x{apertureBase:X16} size=0x{apertureSize:X16}" + (residentBase != apertureBase ? $" relocated=0x{residentBase:X16}" : string.Empty)); diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageBudgetTests.ResidentLevels.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageBudgetTests.ResidentLevels.cs index 5b9267ce2..0c0bc45d7 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalImageBudgetTests.ResidentLevels.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalImageBudgetTests.ResidentLevels.cs @@ -188,6 +188,45 @@ public void AHoleInTheResidentLevelsStopsTheUploadUnlessHolesAreAllowed() Assert.False(image.IsCpuDirty); } + // The same hole inside a PRT aperture as the split's GPU process sees it: its backing has no kernel to ask (as this + // rig's has not), so the guest process's mirrored aperture (PartiallyResidentRanges) is what lets the upload read + // the unmapped page as zero, without SHARPEMU_IMAGE_BACKING_HOLES, as the kernel's PRT read does in one process. + [Fact] + public void AHoleInsideAMirroredPrtApertureReadsAsZeroWithoutTheHolePolicy() + { + if (!RequireDevice()) return; + using var scope = new ResidentLevelsScope(baseLevelCut: false); + using var rig = new Rig(Device.Value); + var reference = AcquireReference(rig, seed: 0x66); + StreamIn(rig, StreamedAddress, residentFrom: 2, seed: 0x66); + var whole = StreamedRequest(StreamedAddress, baseLevel: 0).Description; + var holeOffset = (whole.MipLayout[2].Offset + whole.MipLayout[2].TailOffset) & ~0xFFFUL; + rig.GuestBacking.Unmapped.Add((StreamedAddress + holeOffset, 0x1000)); + PartiallyResidentRanges.ResetMirror(); + try + { + _ = PartiallyResidentRanges.Mirror(new PartiallyResidentRanges.Range(1, StreamedAddress, whole.Data.Size, LazilyBacked: true)); + var request = StreamedRequest(StreamedAddress, baseLevel: 2); + var identifier = rig.Cache.FindImage(ref request); + var before = ResidentImageBacking.MirroredPrtReads; + var view = rig.Cache.AcquireTextureView(identifier, request); + rig.Harness.Submit(); + rig.Harness.Begin(); + var image = rig.Cache.GetImage(identifier); + Assert.False(image.IsCpuDirty); + Assert.True(ResidentImageBacking.MirroredPrtReads > before); + Assert.NotEqual(ReadLevel(rig, reference.Texture, 2), ReadLevel(rig, view, 0)); + for (uint level = 1; level < MipLevels - 2; level++) + { + Assert.Equal(ReadLevel(rig, reference.Texture, level + 2), ReadLevel(rig, view, level)); + } + } + finally + { + PartiallyResidentRanges.ResetMirror(); + } + } + // A block-compressed texture resident from a level that is not block-aligned (250x250 of a 1000x1000 BC1 chain) is // held from that level: the memory policy would start at the 500x500 level, which the guest has not mapped. [Fact] diff --git a/tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs b/tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs index e6ff1a193..53ddcf75a 100644 --- a/tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs +++ b/tests/SharpEmu.GpuRemote.Tests/GpuRemoteChannelTests.cs @@ -87,13 +87,14 @@ public void AttachRefusesAnotherProtocolVersion() [InlineData(4u)] [InlineData(5u)] [InlineData(6u)] + [InlineData(7u)] public void CombinedLayoutRefusesEveryIndependentRecoveryProtocol(uint version) { if (!OperatingSystem.IsMacOS()) return; using var host = GpuRemoteChannel.Create(SharedMemoryRegion.CreateUniqueName("setest")); using (var raw = SharedMemoryRegion.Open(host.Name)) ((RegionHeader*)raw.Pointer)->Version = version; - Assert.Equal(7u, GpuRemoteProtocol.Version); + Assert.Equal(8u, GpuRemoteProtocol.Version); Assert.Throws(() => GpuRemoteChannel.Attach(host.Name)); } diff --git a/tests/SharpEmu.GpuSplit.Tests/SplitResidencyTests.cs b/tests/SharpEmu.GpuSplit.Tests/SplitResidencyTests.cs new file mode 100644 index 000000000..7121d4d6f --- /dev/null +++ b/tests/SharpEmu.GpuSplit.Tests/SplitResidencyTests.cs @@ -0,0 +1,155 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE.GpuMemory; +using SharpEmu.HLE.Host; +using SharpEmu.Libs.Gpu.Images; +using Xunit; + +namespace SharpEmu.GpuSplit.Tests; + +/// +/// The kernel's PRT apertures and AMM area in the GPU process (PartiallyResidentRanges): published in the guest +/// process, mirrored by a call before the kernel call returns, and asked by image reads there as the kernel is asked here. +/// +[Collection(SplitCollection.Name)] +public sealed unsafe class SplitResidencyTests +{ + private const ulong Chunk = SharedGuestMemory.Chunk; + private const int ApertureId = 1; + + [MacOSFact] + public void AnApertureReachesTheGpuProcessBeforeTheKernelCallReturnsAndReadsItsHolesAsZero() + { + using var split = new InProcessSplit(); + PartiallyResidentRanges.ResetMirror(); + try + { + var guest = split.Guest; + var space = split.Host.AddressSpace!; + for (ulong offset = 0; offset < SharedGuestMemory.ViewBytes; offset += sizeof(ulong)) + { + *guest.Pointer(offset) = 0xA5A5_0000_0000_0000UL | offset; + } + + // A texture whose first 16 KiB are unmapped and whose other 32 KiB are the view's first bytes. + var address = guest.Address - 0x4000; + var bytes = new byte[0xC000]; + + // Without the aperture the GPU process has nothing to read the hole from: the upload stops (the caller's fatal). + Assert.False(ResidentImageBacking.TryRead(space, address, bytes, allowHoles: false)); + + split.Session.MirrorResidencyRanges(); + PartiallyResidentRanges.Publish(ApertureId, guest.Address - 4 * Chunk, SharedGuestMemory.ViewBytes + 8 * Chunk, lazilyBacked: true); + + // No wait: the call is answered once the GPU process applied it. + Assert.Equal(1, split.Host.ResidencyChanges); + Assert.True(PartiallyResidentRanges.MirrorContains(address, (ulong)bytes.Length)); + Assert.True(ResidentImageBacking.TryRead(space, address, bytes, allowHoles: false)); + Assert.All(bytes[..0x4000], value => Assert.Equal(0, value)); + Assert.Equal(0xA5A5_0000_0000_0000UL, BitConverter.ToUInt64(bytes, 0x4000)); + Assert.Equal(0xA5A5_0000_0000_0000UL | 0x7FF8, BitConverter.ToUInt64(bytes, 0xBFF8)); + + // A range past the aperture keeps the hole policy: no zeros without SHARPEMU_IMAGE_BACKING_HOLES. + var outside = guest.Address + SharedGuestMemory.ViewBytes + 3 * Chunk; + Assert.False(ResidentImageBacking.TryRead(space, outside, new byte[2 * Chunk], allowHoles: false)); + } + finally + { + PartiallyResidentRanges.Publish(ApertureId, 0, 0, lazilyBacked: true); + PartiallyResidentRanges.ResetMirror(); + } + } + + [MacOSFact] + public void UnmappingAndRemappingInsideAnApertureIsReadFromTheSharedViewTable() + { + using var split = new InProcessSplit(); + PartiallyResidentRanges.ResetMirror(); + var guest = split.Guest; + var second = guest.Address + Chunk; + try + { + split.Session.MirrorResidencyRanges(); + PartiallyResidentRanges.Publish(ApertureId, guest.Address, SharedGuestMemory.ViewBytes, lazilyBacked: true); + *guest.Pointer(Chunk) = 0x5EC0_0D00UL; + var space = split.Host.AddressSpace!; + var bytes = new byte[2 * Chunk]; + + Assert.True(ResidentImageBacking.TryRead(space, guest.Address, bytes, allowHoles: false)); + Assert.Equal(0x5EC0_0D00UL, BitConverter.ToUInt64(bytes, (int)Chunk)); + + // The guest unmaps the second chunk: the GPU process reads zeros there, never the old bytes. + Assert.True(guest.Views.Unmap(second, Chunk, out var holePreserved)); + Assert.True(ResidentImageBacking.TryRead(space, guest.Address, bytes, allowHoles: false)); + Assert.Equal(0UL, BitConverter.ToUInt64(bytes, (int)Chunk)); + + // And maps it again, over other backing: those bytes. + if (!holePreserved) + { + Assert.Equal(second, guest.Host.ReserveHole(second, Chunk)); + } + + Assert.True(guest.Views.TryMapReservedRange(second, Chunk, 40 * Chunk, HostPageProtection.ReadWrite, out _)); + *(ulong*)second = 0x0DD_BA11UL; + Assert.True(ResidentImageBacking.TryRead(space, guest.Address, bytes, allowHoles: false)); + Assert.Equal(0x0DD_BA11UL, BitConverter.ToUInt64(bytes, (int)Chunk)); + + // The kernel drops the aperture: the GPU process stops zero-filling there. + _ = guest.Views.Unmap(second, Chunk, out _); + PartiallyResidentRanges.Publish(ApertureId, 0, 0, lazilyBacked: true); + Assert.Equal(2, split.Host.ResidencyChanges); + Assert.False(PartiallyResidentRanges.MirrorContains(guest.Address, Chunk)); + Assert.False(ResidentImageBacking.TryRead(space, guest.Address, bytes, allowHoles: false)); + } + finally + { + PartiallyResidentRanges.Publish(ApertureId, 0, 0, lazilyBacked: true); + PartiallyResidentRanges.ResetMirror(); + if (!guest.Views.Contains(second, Chunk)) + { + // The view's own teardown unmaps the whole view: give it back its second chunk. + _ = guest.Host.ReserveHole(second, Chunk); + _ = guest.Views.TryMapReservedRange(second, Chunk, SharedGuestMemory.ViewOffset + Chunk, HostPageProtection.ReadWrite, out _); + } + } + } + + [MacOSFact] + public void RangesPublishedBeforeTheSessionAttachedAreSentAndTheLazyOnesCoverManagedWrites() + { + using var split = new InProcessSplit(); + PartiallyResidentRanges.ResetMirror(); + var guest = split.Guest; + try + { + // Published while nothing was attached (the kernel ran before the split started). + PartiallyResidentRanges.Publish(ApertureId, guest.Address, SharedGuestMemory.ViewBytes, lazilyBacked: true); + PartiallyResidentRanges.Publish(PartiallyResidentRanges.AmmArea, guest.Address + SharedGuestMemory.ViewBytes, 4 * Chunk, lazilyBacked: false); + var memory = split.Host.Memory!; + Assert.False(memory.MarkCpuWrite(guest.Address + 0x100, 8)); + + split.Session.MirrorResidencyRanges(); + Assert.Equal(2, split.Host.ResidencyChanges); + Assert.True(PartiallyResidentRanges.MirrorContains(guest.Address + SharedGuestMemory.ViewBytes, 4 * Chunk)); + + // The aperture is lazily backed GPU memory in the GPU process's manager too, as GuestGpuMemoryHook.NoteLazyRange + // makes it in the guest process's: a managed write there reaches the caches. The AMM area is not one. + Assert.True(memory.MarkCpuWrite(guest.Address + 0x100, 8)); + Assert.False(memory.MarkCpuWrite(guest.Address + SharedGuestMemory.ViewBytes + 0x100, 8)); + + // Moved: the old place is not covered any more. + PartiallyResidentRanges.Publish(ApertureId, guest.Address + Chunk, Chunk, lazilyBacked: true); + Assert.False(memory.MarkCpuWrite(guest.Address + 0x100, 8)); + Assert.True(memory.MarkCpuWrite(guest.Address + Chunk + 0x100, 8)); + PartiallyResidentRanges.Publish(ApertureId, 0, 0, lazilyBacked: true); + Assert.False(memory.MarkCpuWrite(guest.Address + Chunk + 0x100, 8)); + } + finally + { + PartiallyResidentRanges.Publish(ApertureId, 0, 0, lazilyBacked: true); + PartiallyResidentRanges.Publish(PartiallyResidentRanges.AmmArea, 0, 0, lazilyBacked: false); + PartiallyResidentRanges.ResetMirror(); + } + } +} From 922e964ede2e13880dcfb1fd7ddb04678c3831cd Mon Sep 17 00:00:00 2001 From: kuba Date: Fri, 20 Nov 2026 00:17:23 +0000 Subject: [PATCH 087/134] [Metal] Bind the null texture for a bindless entry over unmapped memory The Vulkan bindless heap skips a record whose image's first byte is unmapped (IsBackedImageRange); the Metal bindless tables uploaded it and stopped the GPU with the image-backing fatal. Such an entry now binds the null texture and is looked up again at every bind until the guest maps it. SHARPEMU_METAL_V2_BINDLESS_UNMAPPED_NULL=0 uploads it as before. --- .../V2/MetalImageCache.ResidentLevels.cs | 8 +++ .../V2/MetalRenderHost.BindlessImages.cs | 26 +++++++- .../MetalBindlessTableCostTests.cs | 62 ++++++++++++++++++- 3 files changed, 93 insertions(+), 3 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.ResidentLevels.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.ResidentLevels.cs index 8cc59ce20..f4c25405a 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.ResidentLevels.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.ResidentLevels.cs @@ -1,6 +1,7 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using SharpEmu.HLE.GpuMemory; using SharpEmu.Libs.Gpu.Images; namespace SharpEmu.Gpu.Metal.V2; @@ -51,6 +52,13 @@ internal sealed partial class MetalImageCache // The staged read of image bytes: ResidentImageBacking's policy, or the binding's prefix read with the switch off. private MetalGuestMemory.StagingRead? ImageRead => PartialMipChains ? _imageRead ??= _guestMemory.ReadImageBacking : null; + /// + /// Whether the texels of an image over this range could be read from the guest: the range is valid and its first + /// page is mapped (upstream's GuestImageCache.IsBackedImageRange). A descriptor read from a table the guest no longer + /// uses may name memory it has unmapped since. + /// + public bool IsBackedImageRange(GuestSpan data) => ImageDescription.IsValidRange(data) && _backing.IsBackedRange(data.Address, 1); + // A request described from its first resident level, as the whole guest chain it is part of: the same image as every // other request for those bytes, viewed from the same guest level (BaseLevel.cs holds the texture from there). private void TakeWholeChain(ref ImageRequest request) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessImages.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessImages.cs index f64287462..d76cfe279 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessImages.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessImages.cs @@ -370,6 +370,20 @@ private ResourceSlotIdentifier ResolveBindlessEntry(MetalStageBindings stage, Sh { lookedUp = true; var resolution = ResolveBindlessTexture(words, shape); + // A table entry whose T# names no mapped guest memory - one the title has not filled, one whose + // memory it uses for other data by now, the T# of a texture it has unloaded - is no image for now, as + // upstream's heap records are (VulkanVideoPresenter.BindlessHeap.cs, GuestImageCache.IsBackedImageRange): + // it reads the null texture instead of making an image whose upload has no guest bytes to read + // (MetalGuestMemory.ReadImageBacking stops the GPU there). It is looked at again at every bind + // (device.Images stays Invalid), so it takes its texture as soon as the guest maps it. + var unmapped = BindlessUnmappedNull && !ImageDescription.IsEmptyRange(resolution.Request.Description.Data) && + !_imageCache.IsBackedImageRange(resolution.Request.Description.Data); + if (unmapped) + { + BindlessUnmappedEntries++; + resolution = resolution with { Request = ImageRequestBuilders.NullTexture(in shape) }; + } + request = resolution.Request; pagesBefore = _imageCache.RequestPageVersions(in request); identifier = _imageCache.FindImage(ref request, resolution.ExactFormat); @@ -378,11 +392,11 @@ private ResourceSlotIdentifier ResolveBindlessEntry(MetalStageBindings stage, Sh identifier = ImageRequestBuilders.ValidateTextureOwner( _imageCache.GetImage(identifier).Description, ResourceSlotIdentifier.Invalid, identifier, resolution); // A DCC surface's lookup materializes a clear the GPU may have left since. - device.Images[index] = request.Description.Metadata.Kind == MetadataKind.Dcc + device.Images[index] = request.Description.Metadata.Kind == MetadataKind.Dcc || unmapped ? ResourceSlotIdentifier.Invalid : identifier; device.Requests[index] = request; - if (BindlessLookupMemo) + if (BindlessLookupMemo && !unmapped) { memo = NoteBindlessLookup(words, in shape, identifier, in request, imageSet); } @@ -462,6 +476,14 @@ private sealed class BindlessLookup } private readonly Dictionary _bindlessLookupMemo = new(); + + // SHARPEMU_METAL_V2_BINDLESS_UNMAPPED_NULL=0 makes an image for a table entry whose memory is not mapped, as before + // the upstream f1af467a6 port (its upload then stops the GPU unless the bytes are PRT/AMM or holes are allowed). + internal static bool BindlessUnmappedNull { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_BINDLESS_UNMAPPED_NULL") != "0"; + + /// Table entries bound as the null texture because their T# names unmapped memory. + internal long BindlessUnmappedEntries; private readonly List<(ulong Start, ulong End)>[] _lookupChanges = [new(), new(), new(), new()]; private readonly long[] _lookupChangesSince = [-1, -1, -1, -1]; private long _lookupChangesUntil = -1; diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalBindlessTableCostTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalBindlessTableCostTests.cs index 7938a439e..25ca1623f 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalBindlessTableCostTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalBindlessTableCostTests.cs @@ -11,6 +11,7 @@ using SharpEmu.Libs.Gpu.Buffers; using SharpEmu.Libs.Gpu.Images; using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Gpu.Scheduling; using SharpEmu.ShaderCompiler.Resources; using Xunit; using Xunit.Abstractions; @@ -198,6 +199,57 @@ public void APassAfterOneImageChangedResolvesOnlyThatEntryAgain() Assert.Equal(count - 1, rig.Host.BindlessIncrementalSkipped - skipped); } + // A table entry whose T# names memory the guest has not mapped binds the null texture, as upstream's heap records + // do, instead of an image whose upload would stop the GPU; it is looked at again at every bind and takes its texture + // once the memory is mapped. With SHARPEMU_METAL_V2_BINDLESS_UNMAPPED_NULL=0 the upload stops the GPU. + [Fact] + public void AnEntryOverUnmappedMemoryBindsTheNullTextureUntilTheMemoryIsMapped() + { + if (!RequireDevice()) return; + using var rig = new Rig(); + const int count = 8; + const int unmapped = 3; + var saved = MetalRenderHost.BindlessUnmappedNull; + try + { + MetalRenderHost.BindlessUnmappedNull = true; + rig.Hole = (Rig.TextureAddress(unmapped), TextureStride); + var table = rig.Table(count); + rig.Bind(table); + Assert.Equal(1, rig.Host.BindlessUnmappedEntries); + var images = rig.Field(table, "Images"); + Assert.False(images[unmapped].IsValid); + Assert.All(Enumerable.Range(0, count).Where(index => index != unmapped), index => Assert.True(images[index].IsValid)); + var ids = rig.ResourceIds(table); + Assert.DoesNotContain(0ul, ids); + Assert.Equal(count - 1, ids.Where((_, index) => index != unmapped).Distinct().Count()); + Assert.DoesNotContain(ids[unmapped], ids.Where((_, index) => index != unmapped)); + + // Bound again while unmapped: looked at again, still the null texture. + rig.Bind(table); + Assert.Equal(2, rig.Host.BindlessUnmappedEntries); + Assert.Equal(ids[unmapped], rig.ResourceIds(table)[unmapped]); + + // The guest maps it: the next bind finds its image. + rig.Hole = default; + rig.Bind(table); + Assert.Equal(2, rig.Host.BindlessUnmappedEntries); + Assert.True(rig.Field(table, "Images")[unmapped].IsValid); + Assert.NotEqual(ids[unmapped], rig.ResourceIds(table)[unmapped]); + + // Without the rule an unmapped entry makes an image whose upload has nothing to read: the GPU stops. + MetalRenderHost.BindlessUnmappedNull = false; + rig.Hole = (Rig.TextureAddress(count + 2), TextureStride); + var other = rig.Table(count + 4); + var stopped = Assert.ThrowsAny(() => GpuFatal.Speculatively(() => { rig.Bind(other); return 0; })); + Assert.Contains("Could not read the mapped guest image backing", stopped.ToString()); + } + finally + { + MetalRenderHost.BindlessUnmappedNull = saved; + } + } + private bool RequireDevice() { if (Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") == "1") @@ -246,6 +298,10 @@ public Rig() public MetalRenderHost Host { get; } + public (ulong Start, ulong Size) Hole { get => _backing.Hole; set => _backing.Hole = value; } + + public static ulong TextureAddress(int texture) => TextureBase + (ulong)texture * TextureStride; + // count distinct textures, one entry each. public BindlessImageTable Table(int count) { @@ -339,7 +395,11 @@ private sealed class Backing : IGuestBackedSpace, ICpuMemory, IDisposable private static ulong Offset(ulong address) => (address - GuestBase) % Size; private bool Contains(ulong address, ulong length) => - address >= GuestBase && address - GuestBase < Reach && Offset(address) + length <= Size; + address >= GuestBase && address - GuestBase < Reach && Offset(address) + length <= Size && + (Hole.Size == 0 || address + length <= Hole.Start || address >= Hole.Start + Hole.Size); + + // A range the guest has not mapped (none while Size is 0). + public (ulong Start, ulong Size) Hole { get; set; } public bool TryHoldRange(ulong address, ulong size) => false; public bool TryHoldRangeAtOrAbove(ulong searchStart, ulong size, ulong alignment, out ulong address) { address = 0; return false; } From 377b1e4cbcc0a92825634520919fbdc03a3c80ba Mon Sep 17 00:00:00 2001 From: kuba Date: Fri, 20 Nov 2026 00:17:23 +0000 Subject: [PATCH 088/134] [GPU] Take the managed-write lease only once a GPU claimant registered Only a backend that makes GPU claims (the Vulkan buffer cache) gives the lease a meaning; Metal never claims, so every managed write on macOS paid for a reservation nothing waited on. Registration raises the claimant flag, issues a process-wide barrier and waits out every write that started unleased, so no claim meets an unprotected write. The premark and partial-part marks stay. SHARPEMU_MANAGED_WRITE_LEASE_GATE=0 leases every write as upstream. --- src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs | 23 ++- .../GpuMemory/GuestWriteReservations.Gate.cs | 132 ++++++++++++++++++ .../GpuMemory/GuestWriteReservations.cs | 4 +- .../Buffers/GuestBufferCache.cs | 2 + .../GuestGpuManagedWriteLeaseTests.cs | 4 + .../GpuMemory/ManagedWriteLeaseGateTests.cs | 110 +++++++++++++++ 6 files changed, 271 insertions(+), 4 deletions(-) create mode 100644 src/SharpEmu.HLE/GpuMemory/GuestWriteReservations.Gate.cs create mode 100644 tests/SharpEmu.Libs.Tests/Memory/GpuMemory/ManagedWriteLeaseGateTests.cs diff --git a/src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs b/src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs index 74e19ba3f..130eb15b0 100644 --- a/src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs +++ b/src/SharpEmu.HLE/GpuMemory/GuestGpuMemory.cs @@ -242,7 +242,7 @@ AddressSpace is not IGuestBackedSpace backing || internal Action? ManagedWriteReservedForTest; internal readonly ref struct ManagedWriteLease(GuestGpuMemory memory, ulong address, ulong size, - GuestWriteReservations.CpuAttempt? attempt, bool emulatorWrite) + GuestWriteReservations.CpuAttempt? attempt, bool emulatorWrite, bool unleased = false) { public void Dispose() { @@ -254,7 +254,8 @@ public void Dispose() } finally { - attempt?.Dispose(); + if (unleased) GuestWriteReservations.ExitUnleasedWrite(); + else attempt?.Dispose(); } } } @@ -264,9 +265,25 @@ public void Dispose() internal ManagedWriteLease BeginManagedWrite(ulong address, ulong size, bool emulatorWrite = false) { var valid = address != 0 && size != 0 && new GuestSpan(address, size).IsValid; + // No backend makes GPU claims over these pages (GuestWriteReservations.Gate.cs): the write marks the stores before + // and after it lands, as it did before the lease, and its thread's depth lets a claimant that registers meanwhile + // wait for it to land. + var reservations = _pages.ManagedWrites; + if (valid && !reservations.LeasesWrites) + { + GuestImageWriteTracker.NotifyManagedWrite(address, size); + MarkManagedWriteParts(address, size, landed: false, emulatorWrite); + if (reservations.TryEnterUnleasedWrite()) + { + return new ManagedWriteLease(this, address, size, null, emulatorWrite, unleased: true); + } + + // A claimant registered after the check: the write takes the lease, and its premark repeats. + } + for (var retry = 0; ; retry++) { - GuestWriteReservations.CpuAttempt? attempt = valid ? _pages.ManagedWrites.BeginCpuAttempt(address, size) : null; + GuestWriteReservations.CpuAttempt? attempt = valid ? reservations.BeginCpuAttempt(address, size) : null; try { // Recovery can relay to the GPU; no reservation is held yet. diff --git a/src/SharpEmu.HLE/GpuMemory/GuestWriteReservations.Gate.cs b/src/SharpEmu.HLE/GpuMemory/GuestWriteReservations.Gate.cs new file mode 100644 index 000000000..6c08be71a --- /dev/null +++ b/src/SharpEmu.HLE/GpuMemory/GuestWriteReservations.Gate.cs @@ -0,0 +1,132 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.InteropServices; + +namespace SharpEmu.HLE.GpuMemory; + +// The managed-write lease guards a CPU write against a GPU claim over its pages, and only a backend that makes GPU claims +// (the Vulkan buffer cache) gives it a meaning: the Metal backend never claims (it orders its own guest-memory writes +// another way), so on macOS every managed write paid for a reservation nothing ever waited on. A managed write therefore +// takes the lease only once a claimant has registered with these reservations (RegisterClaimant: the Vulkan cache when it +// is constructed, and any first claim before it proceeds); until then it runs as it did before the lease existed, with +// one per-thread depth counter around its copy and landed notification. +// +// No claim can meet a write that started before registration unprotected. Registration first raises _claimant, then +// makes every thread either see it or show its depth (Interlocked.MemoryBarrierProcessWide), then waits until every +// unleased depth is zero, and only then lets a claim proceed (_registered). An unleased write raises its thread's depth +// after its premark and reads _claimant afterwards: either the read sees the claimant, and the write backs out and takes +// the lease (its premark repeats, which marks the same pages again), or its depth store precedes the barrier, and +// registration waits for the write to land and be marked. The write's own side needs no fence, as for the chunk marks of +// the lease's lock-free path. The premark stays outside the depth, as it stays outside the reservation (it may relay to +// the GPU, whose claim must not wait on it). +// +// SHARPEMU_MANAGED_WRITE_LEASE_GATE=0 makes every managed write take the lease, as upstream does. +public sealed partial class GuestWriteReservations +{ + /// False: every managed write takes the lease (SHARPEMU_MANAGED_WRITE_LEASE_GATE=0). Tests switch it. + public static bool GateEnabled { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_MANAGED_WRITE_LEASE_GATE") != "0"; + + private readonly object _registration = new(); + private int _claimant; + private int _registered; + + // Each thread's unleased writes in progress, padded so two threads never share a cache line. + [StructLayout(LayoutKind.Explicit, Size = 128)] + private struct UnleasedRecord + { + [FieldOffset(64)] public int Depth; + } + + private static readonly UnleasedRecord[] s_unleased = new UnleasedRecord[RecordCount]; + private static int s_unleasedTaken; + + // The thread's record: its index + 1, 0 before its first unleased write, -1 when every record is taken. + [ThreadStatic] private static int t_unleased; + + /// Whether a managed write over these reservations takes the lease: a claimant registered, or the gate is off. + public bool LeasesWrites => Volatile.Read(ref _claimant) != 0 || !GateEnabled; + + /// Whether a backend that makes GPU claims registered with these reservations. + public bool HasClaimant => Volatile.Read(ref _registered) != 0; + + /// + /// A backend that makes GPU claims (): every managed write from now on takes the lease, and + /// this returns once every write that started without one has landed. Idempotent; the first claim calls it too. + /// + public void RegisterClaimant() + { + if (Volatile.Read(ref _registered) != 0) + { + return; + } + + lock (_registration) + { + if (_registered != 0) + { + return; + } + + Volatile.Write(ref _claimant, 1); + // Every thread either reads the claimant from now on or has its depth store visible below. + Interlocked.MemoryBarrierProcessWide(); + var own = t_unleased; + var records = Math.Min(Volatile.Read(ref s_unleasedTaken), RecordCount); + for (var index = 0; index < records; index++) + { + if (index + 1 == own && Volatile.Read(ref s_unleased[index].Depth) != 0) + { + throw new InvalidOperationException("A managed CPU writer cannot register a GPU claimant inside its own write."); + } + + var spin = new SpinWait(); + while (Volatile.Read(ref s_unleased[index].Depth) != 0) + { + spin.SpinOnce(sleep1Threshold: -1); + } + } + + Volatile.Write(ref _registered, 1); + } + } + + /// + /// A managed write after its premark, with no claimant registered: counts it in the thread's depth. False when a + /// claimant registered meanwhile (or no record is left): the write takes the lease instead. + /// + internal bool TryEnterUnleasedWrite() + { + var index = t_unleased; + if (index == 0) + { + index = Interlocked.Increment(ref s_unleasedTaken); + t_unleased = index = index <= RecordCount ? index : -1; + } + + if (index < 0) + { + return false; + } + + ref var record = ref s_unleased[index - 1]; + var depth = record.Depth; + Volatile.Write(ref record.Depth, depth + 1); + // No fence: registration makes the depth store visible before it reads the depths. + if (Volatile.Read(ref _claimant) == 0) + { + return true; + } + + Volatile.Write(ref record.Depth, depth); + return false; + } + + /// The landed end of a write counted. + internal static void ExitUnleasedWrite() + { + ref var record = ref s_unleased[t_unleased - 1]; + Volatile.Write(ref record.Depth, record.Depth - 1); + } +} diff --git a/src/SharpEmu.HLE/GpuMemory/GuestWriteReservations.cs b/src/SharpEmu.HLE/GpuMemory/GuestWriteReservations.cs index 0594a5453..488f5b594 100644 --- a/src/SharpEmu.HLE/GpuMemory/GuestWriteReservations.cs +++ b/src/SharpEmu.HLE/GpuMemory/GuestWriteReservations.cs @@ -23,7 +23,7 @@ namespace SharpEmu.HLE.GpuMemory; // marks a chunk first makes every thread either see the mark or show its record (Interlocked.MemoryBarrierProcessWide) // and waits out every recorded write in the chunk. Writes on unmarked chunks do not exclude each other; each landed // notification marks its pages again. -public sealed class GuestWriteReservations +public sealed partial class GuestWriteReservations { private readonly object _gate = new(); private readonly List _cpu = []; @@ -305,6 +305,8 @@ private bool TryReserveFast(long token) public GpuClaim BeginGpuClaim(ulong address, ulong size) { if (size == 0) return default; + // Managed writes take leases only once a claimant registered (GuestWriteReservations.Gate.cs). + RegisterClaimant(); var (start, end) = Pages(address, size); var thread = Environment.CurrentManagedThreadId; RejectFastReservedReentry(); diff --git a/src/graphics/SharpEmu.Gpu.Vulkan/Buffers/GuestBufferCache.cs b/src/graphics/SharpEmu.Gpu.Vulkan/Buffers/GuestBufferCache.cs index fa82bf3f3..20852bb91 100644 --- a/src/graphics/SharpEmu.Gpu.Vulkan/Buffers/GuestBufferCache.cs +++ b/src/graphics/SharpEmu.Gpu.Vulkan/Buffers/GuestBufferCache.cs @@ -107,6 +107,8 @@ public GuestBufferCache( _bdaPageTable = new GpuBuffer(device, scheduler, GpuBufferUsage.DeviceLocal, 0, GpuBuffer.AllFlags, BdaPageTableSize); _tracker = new GuestPageTracker(pages); _managedWrites = pages.ManagedWrites; + // This cache makes GPU claims: managed writes over these pages take the lease from now on. + _managedWrites.RegisterClaimant(); _staging = new GpuRingBuffer(device, scheduler, GpuBufferUsage.Upload, 512 * MiB); // Up to three helper threads copy a large sweep's guest bytes with the render thread, and a large upload's. _sweepCopy = new ParallelGuestCopy(guest, Math.Clamp(Environment.ProcessorCount - 1, 0, 3)); diff --git a/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/GuestGpuManagedWriteLeaseTests.cs b/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/GuestGpuManagedWriteLeaseTests.cs index 9828d8e08..445a0b888 100644 --- a/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/GuestGpuManagedWriteLeaseTests.cs +++ b/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/GuestGpuManagedWriteLeaseTests.cs @@ -160,6 +160,8 @@ public void EmulatorWriteRetriesRecoveryAfterAnInterveningGpuClaim(bool lazy) memory.AttachStores(store, null); if (lazy) memory.RegisterLazyRange(0x10000, 0x4000); else memory.Register(0x10000, 0x4000, GuestPageProtection.Read | GuestPageProtection.Write); + // The claims below are a claiming backend's: writes take the lease from the start (GuestWriteReservations.Gate.cs). + memory.Pages.ManagedWrites.RegisterClaimant(); store.Calls.Clear(); var attempts = 0; memory.BeforeManagedWriteReservationForTest = retry => @@ -220,6 +222,8 @@ public void ReservedHookOrLandedExceptionReleasesAdmission(bool failLanded) var store = new Store(); memory.AttachStores(store, null); memory.Register(0x10000, 0x4000, GuestPageProtection.Read | GuestPageProtection.Write); + // The claim below is a claiming backend's: writes take the lease from the start (GuestWriteReservations.Gate.cs). + memory.Pages.ManagedWrites.RegisterClaimant(); // Registration reports the span to the store; arm the failure and count calls from the write on. store.Calls.Clear(); store.ThrowOnLanded = failLanded; diff --git a/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/ManagedWriteLeaseGateTests.cs b/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/ManagedWriteLeaseGateTests.cs new file mode 100644 index 000000000..26e8a1875 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Memory/GpuMemory/ManagedWriteLeaseGateTests.cs @@ -0,0 +1,110 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.HLE; +using SharpEmu.HLE.GpuMemory; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using Xunit; + +namespace SharpEmu.Libs.Tests.Memory.GpuMemory; + +// The managed-write lease is taken only once a backend that makes GPU claims registered (GuestWriteReservations.Gate.cs). +[Collection(GpuMemoryStateCollection.Name)] +public sealed class ManagedWriteLeaseGateTests +{ + private sealed class Store : IGuestBufferStore + { + internal readonly List<(bool Landed, ulong Address, ulong Size)> Calls = []; + public bool MayHoldGpuData(ulong address, ulong size) => true; + public bool NoteEmulatorWrite(ulong address, ulong size) => true; + public bool MarkCpuWrite(ulong address, ulong size) + { + lock (Calls) Calls.Add((false, address, size)); + return true; + } + + public void MarkCpuWriteLanded(ulong address, ulong size) + { + lock (Calls) Calls.Add((true, address, size)); + } + + public bool DownloadToCpu(ulong address, ulong size) => true; + } + + [Fact] + public void WithoutAClaimantAWriteTakesNoLeaseAndAClaimantWaitsForAWriteInFlight() + { + var saved = GuestWriteReservations.GateEnabled; + GuestWriteReservations.GateEnabled = true; + try + { + using var memory = new GuestGpuMemory(new RecordingAddressSpace()); + var store = new Store(); + memory.AttachStores(store, null); + memory.Register(0x10000, 0x4000, GuestPageProtection.Read | GuestPageProtection.Write); + store.Calls.Clear(); + var reservationAttempts = 0; + memory.BeforeManagedWriteReservationForTest = _ => reservationAttempts++; + var reservations = memory.Pages.ManagedWrites; + + // No claimant: no reservation, the stores hear of the write before and after it lands as before the lease. + Assert.False(reservations.LeasesWrites); + using (memory.BeginManagedWrite(0x10000, 16)) { } + Assert.Equal(0, reservationAttempts); + Assert.Equal(new (bool, ulong, ulong)[] { (false, 0x10000, 16), (true, 0x10000, 16) }, store.Calls); + + // A claim while a write that started unleased is in flight waits until that write landed and was marked. + Task claimed; + using (memory.BeginManagedWrite(0x10000, 16)) + { + claimed = Task.Run(() => + { + using var claim = reservations.BeginGpuClaim(0x10000, 16); + lock (store.Calls) return store.Calls.Count == 4 && store.Calls[3].Landed; + }); + Assert.False(claimed.Wait(200)); + Assert.True(reservations.LeasesWrites); + Assert.False(reservations.HasClaimant); + } + + Assert.True(claimed.Wait(5000)); + Assert.True(claimed.Result); + Assert.True(reservations.HasClaimant); + + // From now on every write takes the lease. + using (memory.BeginManagedWrite(0x10000, 16)) { } + Assert.Equal(1, reservationAttempts); + + // A write on these reservations can no longer go unleased, and a second registration returns at once. + reservations.RegisterClaimant(); + Assert.False(reservations.TryEnterUnleasedWrite()); + } + finally + { + GuestWriteReservations.GateEnabled = saved; + } + } + + // SHARPEMU_MANAGED_WRITE_LEASE_GATE=0: every write takes the lease, as upstream. + [Fact] + public void WithTheGateOffEveryWriteTakesTheLease() + { + var saved = GuestWriteReservations.GateEnabled; + GuestWriteReservations.GateEnabled = false; + try + { + using var memory = new GuestGpuMemory(new RecordingAddressSpace()); + memory.AttachStores(new Store(), null); + memory.Register(0x10000, 0x4000, GuestPageProtection.Read | GuestPageProtection.Write); + var reservationAttempts = 0; + memory.BeforeManagedWriteReservationForTest = _ => reservationAttempts++; + Assert.True(memory.Pages.ManagedWrites.LeasesWrites); + using (memory.BeginManagedWrite(0x10000, 16)) { } + Assert.Equal(1, reservationAttempts); + } + finally + { + GuestWriteReservations.GateEnabled = saved; + } + } +} From b62946b9bd99db0d9dc9079fb806efcd97fc40de Mon Sep 17 00:00:00 2001 From: kuba Date: Fri, 20 Nov 2026 00:26:35 +0000 Subject: [PATCH 089/134] [Metal] Refuse a posted word copy only over an image's bytes Upstream 90d306cb1 checks image bytes exactly before a kernel store lands; the Metal posted word copy refused any destination an image shared a page with. MetalImageCache.HasImageBytes answers the exact question and the image refusal uses it. SHARPEMU_METAL_V2_POSTED_WORD_COPY_EXACT_IMAGE=0 restores the page check. Documents this switch and the bindless-null and lease-gate switches. --- docs/macos/configuration.md | 3 + .../SharpEmu.Gpu.Metal/V2/MetalImageCache.cs | 23 +++++++ .../V2/MetalRenderHost.PostedWordCopy.cs | 14 +++- .../Scenes/PostedWordCopySceneTests.cs | 69 +++++++++++++++++++ 4 files changed, 107 insertions(+), 2 deletions(-) diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index efe154d0b..5bc7ac098 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -55,6 +55,8 @@ them for measurements or to isolate a problem. | `SHARPEMU_METAL_V2_SINGLE_COPY` | on | `0` never releases guest memory that a clean texture's Metal copy duplicates. Requires the chunked guest backing. | | `SHARPEMU_METAL_V2_WHOLE_STALE_RELOAD` | on | `0` restores the old refusal: a GPU-written image whose every byte an alias has since written keeps its older texels instead of reloading them, and writes them back over the alias's bytes. For A/B comparisons only. | | `SHARPEMU_METAL_V2_PARTIAL_MIP_CHAINS` | on | A streamed texture whose T# starts past mip 0 is described from that level (upstream's resident-mip textures, `ImageDescription.FirstLevel`). The image cache looks it up as its whole chain and, while the guest has not mapped that chain, never holds or reads a level before the binding's base level, whatever `SHARPEMU_METAL_V2_BASE_LEVEL` says. Image uploads read guest bytes as upstream does: every byte must be mapped (or partially resident PRT/AMM memory), else the GPU stops with `Could not read the mapped guest image backing`; `SHARPEMU_IMAGE_BACKING_HOLES=1` reads unmapped pages after a mapped first page as zero instead. `0` keeps whole-chain requests and reads image bytes as a binding does (the readable prefix, zeros after it). | +| `SHARPEMU_METAL_V2_BINDLESS_UNMAPPED_NULL` | on | A bindless texture table entry whose image's first byte the guest has not mapped binds the null texture and is looked up again at every bind until the memory is mapped, as the Vulkan bindless heap skips such a record. The counter `BindlessUnmappedEntries` counts them. `0` uploads the entry, which stops the GPU with `Could not read the mapped guest image backing` unless the bytes are partially resident PRT/AMM memory. | +| `SHARPEMU_MANAGED_WRITE_LEASE_GATE` | on | An emulator write into guest GPU memory takes the managed-write lease (`GuestWriteReservations`) only after a backend that makes GPU claims has registered. The Vulkan buffer cache registers when it is built; the Metal backend makes no claims, so on macOS a managed write marks its pages before and after the copy, as before the lease existed. `0` makes every managed write take the lease, as upstream does. | | `SHARPEMU_METAL_V2_STAGED_CACHE_MB` | `256` | Budget of the staged-range cache. | | `SHARPEMU_METAL_V2_TRANSIENT_COMMIT_MB` | `256` | Transient staging a command buffer may hold before it is committed early. | | `SHARPEMU_METAL_V2_RESIDENCY_SET` | off | `1` puts every guest window in an `MTLResidencySet`. | @@ -123,6 +125,7 @@ undoes an optimization to isolate a miscompile: | `SHARPEMU_METAL_V2_DEFERRED_LABEL_LANDINGS` | on | An end-of-pipe label that Metal defers to GPU completion still reports the submission it lands with, so another queue's soft wait (`SHARPEMU_END_OF_PIPE_SOFT_WAITS`) ends when that submission completes. `0` gives deferred labels no landing again: such a wait ends only at its cap. | | `SHARPEMU_METAL_V2_DYNAMIC_STENCIL_OPS` | on | A draw's stencil operations and compare functions come from its own dynamic state, not from the draw its pipeline was first built for. `0` takes them from the pipeline again. | | `SHARPEMU_POSTED_WORD_COPY` | on | A bounded word-copy kernel whose source is final and whose destination holds no image or surface metadata is recorded as a command-processor store of the copied words at its place in the stream, not as a dispatch. The counter line reports `word_copy=[posted=...,unsupported=...,image=...,...]`. `0` runs every such kernel as a dispatch. | +| `SHARPEMU_METAL_V2_POSTED_WORD_COPY_EXACT_IMAGE` | on | A posted word copy is refused for an image only when an image's guest bytes lie in its destination. Sharing a page with an image is not enough (upstream 90d306cb1). `0` refuses any destination an image shares a page with. | ## Diagnostics diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs index 4188ea8f3..c67d5dbb0 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageCache.cs @@ -2232,6 +2232,29 @@ public bool HasGpuModifiedImageBytes(ulong address, ulong size) return false; } + /// + /// True while a live image's guest bytes overlap the range, whatever its state: the exact answer behind + /// , which answers by page (upstream's QueryRegion(...).ImageBytes, 90d306cb1). + /// + public bool HasImageBytes(ulong address, ulong size) + { + if (!IsValidRange(address, size) || !_pageOwners.MayHaveOwners(address, size)) + { + return false; + } + + using var held = _lock.Hold(); + foreach (var imageIdentifier in FindImagesInRange(address, size, pageOverlap: false)) + { + if (_slots.TryGet(imageIdentifier) is not null) + { + return true; + } + } + + return false; + } + // Diagnostics (SHARPEMU_PREFETCH_DRAW_LOOKAHEAD=census): the live images over the range, with their extent and state. internal string DescribeRangeOwners(ulong address, ulong size) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.PostedWordCopy.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.PostedWordCopy.cs index 343ffac5e..0af0473c8 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.PostedWordCopy.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.PostedWordCopy.cs @@ -23,7 +23,7 @@ namespace SharpEmu.Gpu.Metal.V2; // - unsupported: a null, unaligned, empty, overlapping or overflowing range, or one over 16 MiB // (GuestBufferCache.MaxHostCopyWords); // - thread: asked on the command thread rather than the worker; -// - image / metadata: an image may own the destination's pages, or surface metadata lies there (a +// - image / metadata: an image's bytes lie in the destination, or surface metadata does (a // store into either needs the image cache's bookkeeping, which the dispatch's storage binding does); // - input: the source is not final (a recorded GPU write, a GPU-modified image, pending // command-processor or label bytes), is surface metadata, or cannot be read; @@ -51,6 +51,13 @@ internal enum PostedWordCopyRefusal : byte private readonly long[] _postedWordCopies = new long[PostedWordCopyRefusalNames.Length]; + /// + /// The image refusal asks for image bytes in the destination, not image pages (upstream 90d306cb1). + /// SHARPEMU_METAL_V2_POSTED_WORD_COPY_EXACT_IMAGE=0 refuses any destination an image shares a page with. + /// + internal static bool PostedWordCopyExactImageBytes { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_POSTED_WORD_COPY_EXACT_IMAGE") != "0"; + /// Posted word copies (index 0) and refusals by reason, since the host started. internal long PostedWordCopies(PostedWordCopyRefusal outcome) => Interlocked.Read(ref _postedWordCopies[(int)outcome]); @@ -82,7 +89,10 @@ private PostedWordCopyRefusal PostWordCopy(ulong destination, ulong source, ulon return PostedWordCopyRefusal.Thread; } - if (_imageCache.MayOwn(destination, size)) + // Exact (upstream 90d306cb1): only an image whose bytes the store meets refuses it, not one that merely shares + // a page with it; the store's GPU copy touches no byte such an image holds. + if (_imageCache.MayOwn(destination, size) && + (!PostedWordCopyExactImageBytes || _imageCache.HasImageBytes(destination, size))) { return PostedWordCopyRefusal.Image; } diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/PostedWordCopySceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/PostedWordCopySceneTests.cs index 90bd6db24..ecf33be37 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/PostedWordCopySceneTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/PostedWordCopySceneTests.cs @@ -78,4 +78,73 @@ public void ACopyIsRefusedAndLeftToItsDispatchWhenItsSourceIsNotFinalOrItsRangeI Assert.Equal(new uint[Words], Words32(rig.Memory.ReadRaw(destination, Words * 4))); Assert.Empty(rig.Fatals); } + + // Upstream 90d306cb1: the image refusal asks whether an image's bytes lie in the destination, not whether an image + // shares its pages. A copy into the bytes right after a render target, on the target's last page, is posted; one + // whose first word is the target's last is refused; with the exact check off, both are refused. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void OnlyACopyThatMeetsAnImagesBytesIsRefusedForTheImage(bool exact) + { + var saved = MetalRenderHost.PostedWordCopyExactImageBytes; + MetalRenderHost.PostedWordCopyExactImageBytes = exact; + try + { + using var rig = CreateRig(); + if (rig is null) return; + var host = rig.Host; + var cache = host.ImageCache; + const uint Side = 60; + var target = rig.Memory.Allocate(0x20000, 0x10000); + rig.Memory.Write(target, new byte[0x20000]); + var state = new SceneState(Side, Side).ColorTarget(0, target, Side, Side); + SceneVertex[] quad = + [ + SceneVertex.At(-1, -1, 0.5f, 1, 0, 0, 1), SceneVertex.At(1, -1, 0.5f, 1, 0, 0, 1), + SceneVertex.At(-1, 1, 0.5f, 1, 0, 0, 1), SceneVertex.At(-1, 1, 0.5f, 1, 0, 0, 1), + SceneVertex.At(1, -1, 0.5f, 1, 0, 0, 1), SceneVertex.At(1, 1, 0.5f, 1, 0, 0, 1), + ]; + var draw = new ScenePm4(); + rig.DrawMesh(draw, state, quad); + rig.Submit(draw); + + // Where the target's bytes end: the first word after them that no image holds. + var end = target; + while (cache.HasImageBytes(end, sizeof(uint))) + { + end += sizeof(uint); + } + + const int CopyWords = 16; + const ulong CopyBytes = CopyWords * sizeof(uint); + Assert.True(end > target && end < target + 0x10000); + // The boundary: the bytes after the target share its page, the bytes one word earlier hold its last word. + Assert.True(cache.MayOwn(end, CopyBytes)); + Assert.False(cache.HasImageBytes(end, CopyBytes)); + Assert.True(cache.HasImageBytes(end - sizeof(uint), CopyBytes)); + + var source = rig.Memory.Allocate(SourceWords * 4); + uint[] pattern = [0xC0FFEE01, 0xC0FFEE02, 0xC0FFEE03, 0xC0FFEE04]; + rig.Memory.Write(source, pattern); + + Assert.False(((IRenderHost)host).TryPostWordCopy(end - sizeof(uint), source, SourceWords, CopyWords)); + Assert.Equal(exact, ((IRenderHost)host).TryPostWordCopy(end, source, SourceWords, CopyWords)); + Assert.Equal(exact ? 1 : 2, host.PostedWordCopies(MetalRenderHost.PostedWordCopyRefusal.Image)); + Assert.Equal(exact ? 1 : 0, host.PostedWordCopies(MetalRenderHost.PostedWordCopyRefusal.None)); + + // The target reads as drawn (its first texel opaque; its last word is pitch padding the draw leaves), and the + // posted bytes beside it survive its read-back. + rig.Drain(); + var expected = exact ? Replicated(pattern, CopyWords) : new uint[CopyWords]; + Assert.Equal(0xFF, rig.Read(target, sizeof(uint))[3]); + Assert.Equal(expected, Words32(rig.Read(end, (int)CopyBytes))); + Assert.Equal(expected, Words32(rig.Memory.ReadRaw(end, (int)CopyBytes))); + Assert.Empty(rig.Fatals); + } + finally + { + MetalRenderHost.PostedWordCopyExactImageBytes = saved; + } + } } From 0e2023281d3487d306efbd52bc701678702e0672 Mon Sep 17 00:00:00 2001 From: kuba Date: Fri, 20 Nov 2026 00:40:36 +0000 Subject: [PATCH 090/134] [Tests] Skip the replay scenes when the engine's replay switches are off RenderRecorder reads SHARPEMU_DRAW_REPLAY and SHARPEMU_DISPATCH_REPLAY once, so a suite run with either set to 0 replays nothing and the replay scenes would fail on a switch, not a bug. They now say so and return, as the device gate does. --- .../Scenes/ReplaySceneTests.cs | 32 ++++++++++++++----- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ReplaySceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ReplaySceneTests.cs index f402cfc95..fddb161f6 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ReplaySceneTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ReplaySceneTests.cs @@ -16,6 +16,22 @@ namespace SharpEmu.Gpu.Metal.Tests.Scenes; /// public sealed class ReplaySceneTests(ITestOutputHelper output) : SceneTestBase(output) { + // The engine reads the same switches once (RenderRecorder); with either off there is nothing of it to test here. + private static readonly bool EngineReplayOff = + Environment.GetEnvironmentVariable("SHARPEMU_DRAW_REPLAY") == "0" || + Environment.GetEnvironmentVariable("SHARPEMU_DISPATCH_REPLAY") == "0"; + + private SceneRig? CreateReplayRig() + { + if (EngineReplayOff) + { + Output.WriteLine("SHARPEMU_DRAW_REPLAY=0 or SHARPEMU_DISPATCH_REPLAY=0: the engine replays nothing."); + return null; + } + + return CreateRig(); + } + private const uint Width = 16; private const uint Rgba8 = 56; private const uint TextureSize = 8; @@ -160,7 +176,7 @@ private static readonly (float R, float G, float B)[] StripeColours = private byte[] DrawStripes(bool replay, out long replays) { - using var rig = CreateRig()!; + using var rig = CreateReplayRig()!; rig.Host.DrawReplayEnabled = replay; rig.Host.DispatchReplayEnabled = replay; var stripes = new Stripes(rig); @@ -189,7 +205,7 @@ private byte[] DrawStripes(bool replay, out long replays) [Fact] public void RepeatedDrawsReplayWithTheirOwnUserDataAndRenderAsWithout() { - if (CreateRig() is not { } probe) return; + if (CreateReplayRig() is not { } probe) return; probe.Dispose(); var with = DrawStripes(replay: true, out var replays); var without = DrawStripes(replay: false, out var none); @@ -204,7 +220,7 @@ public void RepeatedDrawsReplayWithTheirOwnUserDataAndRenderAsWithout() [Fact] public void ATextureWrittenBetweenDrawsRefusesTheReplayAndIsSampledNew() { - using var rig = CreateRig(); + using var rig = CreateReplayRig(); if (rig is null) return; const uint red = 0xFF0000FF; const uint green = 0xFF00FF00; @@ -241,7 +257,7 @@ public void ATextureWrittenBetweenDrawsRefusesTheReplayAndIsSampledNew() [Fact] public void AReadBindingTheMemoNoLongerAnswersRefusesTheReplay() { - using var rig = CreateRig(); + using var rig = CreateReplayRig(); if (rig is null) return; var stripes = new Stripes(rig); var probed = false; @@ -277,7 +293,7 @@ public void AReadBindingTheMemoNoLongerAnswersRefusesTheReplay() [Fact] public void ACommandBufferCommittedBetweenDrawsRefusesTheReplay() { - using var rig = CreateRig(); + using var rig = CreateReplayRig(); if (rig is null) return; var stripes = new Stripes(rig); var probed = false; @@ -310,7 +326,7 @@ public void ACommandBufferCommittedBetweenDrawsRefusesTheReplay() private uint[] StoreWords(bool replay, Action? probe, out long replays, out long imagesMisses) { - using var rig = CreateRig()!; + using var rig = CreateReplayRig()!; rig.Host.DrawReplayEnabled = replay; rig.Host.DispatchReplayEnabled = replay; var probed = probe is null; @@ -356,7 +372,7 @@ private uint[] StoreWords(bool replay, Action? probe, out long replays [Fact] public void RepeatedDispatchesReplayWithTheirOwnUserDataAndWriteAsWithout() { - if (CreateRig() is not { } probe) return; + if (CreateReplayRig() is not { } probe) return; probe.Dispose(); var with = StoreWords(replay: true, probe: null, out var replays, out _); var without = StoreWords(replay: false, probe: null, out var none, out _); @@ -372,7 +388,7 @@ public void RepeatedDispatchesReplayWithTheirOwnUserDataAndWriteAsWithout() [Fact] public void AnEpochMovedBetweenDispatchesRefusesTheReplay() { - if (CreateRig() is not { } probe) return; + if (CreateReplayRig() is not { } probe) return; probe.Dispose(); var with = StoreWords(replay: true, rig => rig.Host.ImageCache.Epochs.NoteShapeChanged(), out var replays, out var imagesMisses); Assert.True(imagesMisses >= 1, "the moved epoch did not refuse the replay"); From c87713406c1dd6f484cc8b933b4daba9fbe262d4 Mon Sep 17 00:00:00 2001 From: kuba Date: Fri, 20 Nov 2026 00:52:49 +0000 Subject: [PATCH 091/134] [Tests] Give the slow linked compile test a record threshold a loaded runner cannot reach early The first dispatch waits 20 ms and must return before the 100 ms record threshold. A CI runner took over 100 ms for that wait (run 44645408183), so the program was recorded slow one dispatch early and Assert.Empty failed. The threshold is now 1 s, 50 times the wait; the test sleeps past it before the dispatches that record. --- .../Gpu/Rendering/RenderExecutorComputeTests.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorComputeTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorComputeTests.cs index 37ff17772..181b41c97 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorComputeTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorComputeTests.cs @@ -210,8 +210,10 @@ public void LinkedProgram_KnownSlowButReadyWithinTheShortBound_IsDispatched() [Fact] public void LinkedProgram_StillCompilingAfterTheRecordThreshold_IsRecordedSlowOnce() { + // The record threshold is 50 times the wait: the first dispatch returns before it even when a loaded machine + // stretches the 20 ms wait several times over (a CI runner took over 100 ms for it). _executor.LinkedCompileWait = System.Diagnostics.Stopwatch.Frequency / 50; - _executor.SlowLinkedCompileRecordTicks = System.Diagnostics.Stopwatch.Frequency / 10; + _executor.SlowLinkedCompileRecordTicks = System.Diagnostics.Stopwatch.Frequency; var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); _pipelines.PendingComputeCompletion = completion.Task; var program = new ShaderProgramInfo { Stage = ShaderStageKind.Compute, Hash = 0x1239, Bindings = new BindingLayout { CallTargetCount = 1 } }; @@ -220,7 +222,7 @@ public void LinkedProgram_StillCompilingAfterTheRecordThreshold_IsRecordedSlowOn AssertNotDispatched(); Assert.Empty(_pipelines.RecordedLinkedCompiles); - Thread.Sleep(150); + Thread.Sleep(1050); _executor.Dispatch(6, Banks(), 4, 2, 1, 0x41); _executor.Dispatch(7, Banks(), 4, 2, 1, 0x41); AssertNotDispatched(); From 914817ea64b094d319207aa22ca18fa31da68c49 Mon Sep 17 00:00:00 2001 From: kuba Date: Fri, 20 Nov 2026 00:55:07 +0000 Subject: [PATCH 092/134] [Shader] Read bindless heap image and sampler records in MSL A program that reads a T# or S# from a heap V# at a record only its shader knows (ResourceTracker.PlanHeapRecords) used to be refused by the MSL translator. It now reads the record's element the way the SPIR-V translator does (Gen5SpirvTranslator.Resources.cs heap paths): - the element index comes from the record offset and the draw's heap view words in shader data; an offset outside the view, or any index past the table, reads the null element (index clamped to CallRecordNullIndex); - the shader marks each element it reads in the feedback bitsets (plain read first, atomic OR only for an active lane whose bit is clear); - elements are 8-byte gpuResourceIDs in a device table (argument fields heap_elements and heap_feedback, only for programs with heap reads), read through typed structs per texture type, slot-major like Vulkan's set-1 arrays; - a zero image handle is Vulkan's null descriptor: the read is skipped and the destination registers are zero; - loads and size queries of integer-capable slots branch on the element's class code (float, uint, sint); other reads of those slots take the null element when the class differs; - a 3D read whose 3D element is null takes the record's 2D-array element. Call records stay refused (RuntimeCallRecordsSupported is still false). Programs without heap reads get the same layout and MSL as before (full suite without the device: 4922 passed, no golden change). --- .../Gen5MslArgumentLayout.cs | 17 + .../Gen5MslTranslator.BindlessHeap.cs | 346 +++++++++++++++ .../Gen5MslTranslator.Pixel.cs | 5 + .../Gen5MslTranslator.Resources.cs | 57 ++- .../MetalBindlessHeapTests.cs | 416 ++++++++++++++++++ .../MetalNative.Bindless.cs | 27 ++ .../MetalNative.cs | 12 +- 7 files changed, 874 insertions(+), 6 deletions(-) create mode 100644 src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.BindlessHeap.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalBindlessHeapTests.cs diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslArgumentLayout.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslArgumentLayout.cs index 6a5768ac5..dfe36a07c 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslArgumentLayout.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslArgumentLayout.cs @@ -30,6 +30,13 @@ public enum MslArgumentFieldKind // bindless slot (BindingLayout.BindlessImageTableCount). Each entry is 16 bytes: a // texture's gpuResourceID and the class variant that reads it (sharpemu_bindless_entry). BindlessImageTables, + // The bindless heap's element table (BindlessHeap): one 8-byte texture or sampler handle per element, slot-major + // (slot * BindlessHeap.Capacity + element); a zero image handle is the null element. Declared only by a program + // that reads heap records (BindingLayout.UsesBindlessHeap). + BindlessHeapElements, + // The bindless heap's feedback words (BindlessHeap.FeedbackWords): the mark bitsets the shader sets for every + // element it reads, then the numeric class of every image element, which the host writes. + BindlessHeapFeedback, } // One field of the stage argument buffer: its binding kind, id range and byte range. @@ -52,6 +59,10 @@ public sealed class Gen5MslArgumentLayout public const string StepReportName = "step_report"; public const string PairLocksName = "pair_locks"; public const string BindlessImagesName = "bindless_images"; + public const string HeapElementsName = "heap_elements"; + public const string HeapFeedbackName = "heap_feedback"; + /// The bytes of one bindless heap element: a texture's or sampler's gpuResourceID. + public const int HeapElementBytes = 8; public const string MipStatisticsName = "mip_stats"; /// The bytes of one bindless table entry: gpuResourceID, variant, reserved. @@ -144,6 +155,12 @@ public static Gen5MslArgumentLayout Build(BindingLayout layout) layout.BindlessImageTableCount, ResourceBytes); } + if (layout.UsesBindlessHeap) + { + Add(DescriptorBindingKind.Buffers, MslArgumentFieldKind.BindlessHeapElements, HeapElementsName, 1, ResourceBytes); + Add(DescriptorBindingKind.Buffers, MslArgumentFieldKind.BindlessHeapFeedback, HeapFeedbackName, 1, ResourceBytes); + } + // Always last, so adding them never moves a descriptor field. Add(DescriptorBindingKind.Buffers, MslArgumentFieldKind.StepReport, StepReportName, 1, ResourceBytes); Add(DescriptorBindingKind.Buffers, MslArgumentFieldKind.PairLocks, PairLocksName, 1, ResourceBytes); diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.BindlessHeap.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.BindlessHeap.cs new file mode 100644 index 000000000..5c125e44c --- /dev/null +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.BindlessHeap.cs @@ -0,0 +1,346 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Globalization; +using System.Numerics; +using System.Text; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.ShaderCompiler.Metal; + +// The bindless heap (BindlessHeap): an image or sampler the shader reads from a heap V# at a record only it knows is +// the element of that record in the heap's element table, one 8-byte handle per element, slot-major. The MSL form of +// the SPIR-V translator's set-1 arrays: the element a read takes is the one its draw's heap view (HeapView, two dwords +// of shader data) has for the record, or the null element; the shader marks every element it reads in the feedback +// bitsets so the host gives it a view, and an image element of a class with integer forms is read through the +// declaration of its numeric class, which the host keeps after the bitsets. A null image element is a zero handle: the +// read is skipped and its registers take zero, as a null descriptor reads (texel, size, levels all zero). +public static partial class Gen5MslTranslator +{ + private sealed partial class CompilationContext + { + private const string HeapSamplerStruct = "sharpemu_heap_sampler"; + + // The texture types heap elements are read as (each gets its typed element struct) and whether a sampler is. + private readonly SortedSet _heapTextureTypes = new(StringComparer.Ordinal); + private bool _usesHeapSamplers; + + // The element index of the heap image access being emitted (its view's record, before the class check) and + // the validity of the image element TryResolveLayoutImage read last. + private string? _heapRecordIndex; + private string? _heapImageValid; + + private static string HeapTypedStruct(string textureType) + { + var name = new StringBuilder("sharpemu_heap_"); + foreach (var character in textureType) + { + name.Append(char.IsAsciiLetterOrDigit(character) ? character : '_'); + } + + return name.ToString(); + } + + // One struct per texture type the heap is read as, the handle typed: an element is read by reinterpreting it. + private void EmitHeapElementStructs(StringBuilder source) + { + foreach (var textureType in _heapTextureTypes) + { + source.AppendLine($"struct {HeapTypedStruct(textureType)} {{ {textureType} texture; }};"); + } + + if (_usesHeapSamplers) + { + source.AppendLine($"struct {HeapSamplerStruct} {{ sampler state; }};"); + } + + source.AppendLine(); + } + + private static string HeapLiteral(uint value) => value.ToString(CultureInfo.InvariantCulture) + "u"; + + private string HeapFeedbackWord(string index) => + $"{ResourcesName}.{Gen5MslArgumentLayout.HeapFeedbackName}[{index}]"; + + // The element of the heap a read picks: the dynamic offset its key read kept plus the read's immediate is a byte + // offset in the heap, whose record the draw's heap view has an element for. A read the view has no element for + // (past its records, or not at its descriptor's offset in a record) takes the null element, and no index is past + // the table whatever the view's words say. + private string HeapRecordIndex(HeapRecordUse use) + { + var key = _indirectKeyScratch.TryGetValue(use.KeyMemoryIndex, out var scratch) ? scratch : "0u"; + var viewDword = _request.Bindings.HeapViewsDword + (uint)use.View * HeapView.DwordCount; + var offset = Temp("uint", $"{key} + {HeapLiteral(use.Immediate)}"); + var word0 = Temp("uint", ShaderDataDword(viewDword)); + var word1 = Temp("uint", ShaderDataDword(viewDword + 1)); + var elementBits = HeapLiteral((uint)HeapView.ElementBits); + var elementMask = HeapLiteral(HeapView.ElementMask); + var nullIndex = HeapLiteral(BindlessHeap.CallRecordNullIndex); + // The host never gives a view a stride of zero; a zero read from a short shader data block divides by one. + var stride = Temp("uint", $"max({word0} >> {elementBits}, 1u)"); + var record = Temp("uint", $"{offset} / {stride}"); + var inView = Temp("bool", + $"{offset} - {record} * {stride} == ({word1} >> {elementBits}) && {record} < ({word1} & {elementMask})"); + return Temp("uint", $"{inView} ? min(({word0} & {elementMask}) + {record}, {nullIndex}) : {nullIndex}"); + } + + // The numeric class of an image element (BindlessHeap.ClassCode), which the host keeps after the mark bitsets. + private string HeapElementClass(string index) + { + var word = HeapFeedbackWord($"{HeapLiteral(BindlessHeap.MarkWords)} + ({index} >> {HeapLiteral(BindlessHeap.ClassWordShift)})"); + return Temp("uint", + $"(atomic_load_explicit(&{word}, memory_order_relaxed) >> (({index} & {HeapLiteral(BindlessHeap.ClassesPerWord - 1)}) * " + + $"{HeapLiteral(BindlessHeap.ClassBits)})) & {HeapLiteral(BindlessHeap.ClassMask)}"); + } + + // The element a read takes through the declaration of one numeric class: the record's element when it holds a + // texture of that class and the null element otherwise. A class without integer forms holds float views only. + private string HeapImageIndex(string index, int slot, ImageNumericClass numericClass) + { + if (!BindlessHeap.HoldsIntegers(slot)) + { + return index; + } + + var elementClass = HeapElementClass(index); + return Temp("uint", + $"{elementClass} == {HeapLiteral(BindlessHeap.ClassCode(numericClass))} ? {index} : {HeapLiteral(BindlessHeap.CallRecordNullIndex)}"); + } + + // Sets the element's bit in its array's mark words, for the lanes the guest runs; a plain read first keeps marked + // elements from repeating the atomic. + private void MarkHeapElement(int slot, string index) + { + var word = Temp("uint", $"{HeapLiteral((uint)slot * BindlessHeap.FeedbackWordsPerArray)} + ({index} >> 5u)"); + var bit = Temp("uint", $"1u << ({index} & 31u)"); + var feedback = HeapFeedbackWord(word); + Line($"if ({ExecCondition($"(atomic_load_explicit(&{feedback}, memory_order_relaxed) & {bit}) == 0u")})"); + Line("{"); + _indent++; + Line($"atomic_fetch_or_explicit(&{feedback}, {bit}, memory_order_relaxed);"); + _indent--; + Line("}"); + } + + // The element of one array at index, marked; its handle's validity goes to _heapImageValid. + private string HeapTexture(int slot, string textureType, string index) + { + MarkHeapElement(slot, index); + var element = Temp("uint", $"{HeapLiteral((uint)slot * BindlessHeap.Capacity)} + {index}"); + var elements = $"{ResourcesName}.{Gen5MslArgumentLayout.HeapElementsName}"; + _heapImageValid = Temp("bool", $"{elements}[{element}] != 0ul"); + _heapTextureTypes.Add(textureType); + return Temp(textureType, $"((device const {HeapTypedStruct(textureType)}*){elements})[{element}].texture"); + } + + // A sampler element is never zero: the host fills the sampler arrays with the null sampler. + private string HeapSampler(int slot, HeapRecordUse use) + { + var index = HeapRecordIndex(use); + MarkHeapElement(slot, index); + _usesHeapSamplers = true; + var elements = $"{ResourcesName}.{Gen5MslArgumentLayout.HeapElementsName}"; + return Temp("sampler", + $"((device const {HeapSamplerStruct}*){elements})[{HeapLiteral((uint)slot * BindlessHeap.Capacity)} + {index}].state"); + } + + // The float 2D-array class a 3D heap read takes for a record that holds a 2D texture. + private static MslImageClass HeapVolumeLayerClass() => new( + string.Empty, + Gen5MslArgumentLayout.TextureType(ImageDimension.Dim2DArray, "float", null), + "float", + IsStorage: false, + DepthCompare: false, + Multisampled: false, + Arrayed: true, + Cube: false, + ImageDimension.Dim2DArray, + []); + + // The integer form of a float class of the heap: the same element, read with unsigned or signed texels. + private static MslImageClass HeapIntegerClass(MslImageClass floatClass, ImageNumericClass numericClass) + { + var componentKind = numericClass == ImageNumericClass.Sint ? "int" : "uint"; + return floatClass with + { + TextureType = Gen5MslArgumentLayout.TextureType(floatClass.Dimension, componentKind, null), + ComponentKind = componentKind, + Resources = [], + }; + } + + // The heap image an access reads: its record use, when its image is a heap record of a class the heap has. + private bool IsHeapImageAccess(Gen5ShaderInstruction instruction, out HeapRecordUse use, out int slot) + { + use = default; + slot = -1; + if (!_request.Memory.TryGetIndex(instruction.Pc, 0, out var memoryIndex) || + !_request.HeapImageByMemoryIndex.TryGetValue(memoryIndex, out use)) + { + return false; + } + + var entry = _request.Memory[memoryIndex]; + var info = _request.Resources.Info; + if (entry.Resource >= (uint)info.Images.Count || ImageDescriptorBinding.ForImage(info.Images[(int)entry.Resource]) is not { } kind) + { + return false; + } + + slot = BindlessHeap.ImageSlot(kind); + return slot >= 0; + } + + // A heap record can hold an integer texture, which shaders read with loads and size queries: a load of a class + // with integer forms reads the record through the declaration of the element's numeric class. + private static bool IsHeapLoad(Gen5ShaderInstruction instruction, int slot) => + instruction.Opcode is "ImageLoad" or "ImageLoadMip" or "ImageGetResinfo" && BindlessHeap.HoldsIntegers(slot); + + // A heap record a 3D read picks can hold a 2D texture, whose 3D element stays null; the hardware then takes the + // third coordinate as the array layer. Reads that place their operands alike in both shapes (no gradients) try + // the 3D element and, when it is null, the record's 2D-array element. + private static bool IsHeapVolumeRead(Gen5ShaderInstruction instruction, int slot) + { + var opcode = instruction.Opcode; + var sameOperands = opcode is "ImageLoad" or "ImageLoadMip" || opcode.StartsWith("ImageGather4", StringComparison.Ordinal) || + (opcode.StartsWith("ImageSample", StringComparison.Ordinal) && !opcode.Contains("SampleD", StringComparison.Ordinal) && + !opcode.Contains("SampleCD", StringComparison.Ordinal) && !opcode.Contains("SampleCd", StringComparison.Ordinal) && + !opcode.Contains("SampleCCd", StringComparison.Ordinal)); + return sameOperands && slot == BindlessHeap.VolumeSlot; + } + + // An image access whose image is a heap record. The record's element index is found once, outside the branches + // that read it through each numeric class or shape. + private bool TryEmitHeapImage(Gen5ShaderInstruction instruction, Gen5ImageControl image, HeapRecordUse use, int slot, out string error) + { + _heapRecordIndex = HeapRecordIndex(use); + try + { + if (!IsHeapLoad(instruction, slot)) + { + return IsHeapVolumeRead(instruction, slot) + ? TryEmitHeapVolumeRead(instruction, image, out error) + : TryEmitHeapRead(instruction, image, ImageNumericClass.Float, layers: false, out error); + } + + var elementClass = HeapElementClass(_heapRecordIndex); + foreach (var numericClass in new[] { ImageNumericClass.Float, ImageNumericClass.Uint, ImageNumericClass.Sint }) + { + Line($"if ({elementClass} == {HeapLiteral(BindlessHeap.ClassCode(numericClass))})"); + Line("{"); + _indent++; + var emitted = numericClass == ImageNumericClass.Float && IsHeapVolumeRead(instruction, slot) + ? TryEmitHeapVolumeRead(instruction, image, out error) + : TryEmitHeapRead(instruction, image, numericClass, layers: false, out error); + _indent--; + Line("}"); + if (!emitted) + { + return false; + } + } + + error = string.Empty; + return true; + } + finally + { + _heapRecordIndex = null; + _heapImageValid = null; + } + } + + // The 3D element when the record holds a volume, its 2D-array element otherwise. + private bool TryEmitHeapVolumeRead(Gen5ShaderInstruction instruction, Gen5ImageControl image, out string error) + { + if (!TryResolveLayoutImage(instruction, image, out var texture, out var samplerName, out var imageClass, out var dstSelect, + out var mipLevel, out var compareFunction, out var packedFormat, out var samplerInfo, out error, out var resourceIndex)) + { + return false; + } + + var isVolume = _heapImageValid!; + Line($"if ({isVolume})"); + Line("{"); + _indent++; + var emitted = EmitImageOperation(instruction, image, texture, samplerName, imageClass, dstSelect, mipLevel, compareFunction, + packedFormat, samplerInfo, resourceIndex, out error); + _indent--; + Line("}"); + if (!emitted) + { + return false; + } + + Line("else"); + Line("{"); + _indent++; + emitted = TryEmitHeapRead(instruction, image, ImageNumericClass.Float, layers: true, out error); + _indent--; + Line("}"); + return emitted; + } + + // One read of the record's element through one declaration; a null element reads zero. + private bool TryEmitHeapRead(Gen5ShaderInstruction instruction, Gen5ImageControl image, ImageNumericClass numericClass, bool layers, + out string error) + { + if (!TryResolveLayoutImage(instruction, image, out var texture, out var samplerName, out var imageClass, out var dstSelect, + out var mipLevel, out var compareFunction, out var packedFormat, out var samplerInfo, out error, out var resourceIndex, + heapVolumeLayers: layers, heapNumericClass: numericClass)) + { + return false; + } + + Line($"if ({_heapImageValid!})"); + Line("{"); + _indent++; + var emitted = EmitImageOperation(instruction, image, texture, samplerName, imageClass, dstSelect, mipLevel, compareFunction, + packedFormat, samplerInfo, resourceIndex, out error); + _indent--; + Line("}"); + if (!emitted) + { + return false; + } + + Line("else"); + Line("{"); + _indent++; + EmitNullImageResult(instruction, image); + _indent--; + Line("}"); + return true; + } + + // The registers an image read writes, zero: what a read of a null descriptor returns. + private void EmitNullImageResult(Gen5ShaderInstruction instruction, Gen5ImageControl image) + { + var opcode = instruction.Opcode; + int count; + if (opcode == "ImageGetResinfo") + { + count = BitOperations.PopCount(image.Dmask & 0xFu); + } + else if (opcode == "ImageGetLod") + { + count = BitOperations.PopCount((image.Dmask != 0 ? image.Dmask : 1u) & 0x3u); + } + else + { + count = opcode.StartsWith("ImageGather4", StringComparison.Ordinal) || opcode == "ImageMsaaLoad" + ? 4 + : BitOperations.PopCount(image.Dmask & 0xFu); + if (image.D16) + { + count = (count + 1) / 2; + } + } + + for (var index = 0; index < count; index++) + { + StoreVector(image.VectorData + (uint)index, "0u"); + } + } + } +} diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Pixel.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Pixel.cs index db4ae2c7f..fc1321b65 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Pixel.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Pixel.cs @@ -108,6 +108,11 @@ private bool TryEmitImage( return false; } + if (IsHeapImageAccess(instruction, out var heapImage, out var heapSlot)) + { + return TryEmitHeapImage(instruction, image, heapImage, heapSlot, out error); + } + if (!TryResolveLayoutImage(instruction, image, out texture, out samplerName, out imageClass, out dstSelect, out mipLevel, out compareFunction, out packedFormat, out samplerInfo, out error, out resourceIndex)) { return false; diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs index a8a5b82da..d6ad1ae8d 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs @@ -36,9 +36,11 @@ public static bool TryCompileProgram( Gen5MslCodegenOptions? options = null) { shader = default!; - if (request.UsesBindlessHeap) + // Call records are the elements a linked callee's records hold (CallRecordSelector), which only linked shader + // calls produce; those are refused below. Guest heap records read the heap (Gen5MslTranslator.BindlessHeap.cs). + if (request.CallRecordImageByMemoryIndex.Count != 0 || request.CallRecordSamplerByMemoryIndex.Count != 0) { - error = "Metal does not support bindless heap descriptors."; + error = "Metal does not support call record descriptors."; return false; } @@ -437,6 +439,11 @@ private void EmitResourceStruct(StringBuilder source) EmitBindlessEntryStructs(source); } + if (_argumentLayout!.Fields.Any(static field => field.FieldKind == MslArgumentFieldKind.BindlessHeapElements)) + { + EmitHeapElementStructs(source); + } + source.AppendLine($"struct {Gen5MslArgumentLayout.StructName}"); source.AppendLine("{"); foreach (var field in layout.Fields) @@ -467,6 +474,8 @@ private void EmitResourceStruct(StringBuilder source) MslArgumentFieldKind.Pointer => $"{PointerType(field.Kind)} {field.Name}", MslArgumentFieldKind.StepReport or MslArgumentFieldKind.PairLocks => $"device atomic_uint* {field.Name}", MslArgumentFieldKind.BindlessImageTables => $"array {field.Name}", + MslArgumentFieldKind.BindlessHeapElements => $"device const ulong* {field.Name}", + MslArgumentFieldKind.BindlessHeapFeedback => $"device atomic_uint* {field.Name}", _ => $"uint {field.Name}", }; source.AppendLine($" {declaration} [[id({field.FirstId})]];"); @@ -2335,7 +2344,9 @@ private bool TryResolveLayoutImage( out SamplerResource? samplerInfo, out string error, out int resourceIndex, - (uint Resource, uint Element)? fixedElement = null) + (uint Resource, uint Element)? fixedElement = null, + bool heapVolumeLayers = false, + ImageNumericClass heapNumericClass = ImageNumericClass.Float) { error = string.Empty; resourceIndex = -1; @@ -2397,6 +2408,30 @@ private bool TryResolveLayoutImage( return false; } + // A bindless heap image reads the element its key picks from the heap (Gen5MslTranslator.BindlessHeap.cs), + // not its null element in the class array: a 3D read of a 2D record reads the record's 2D-array element, and + // an integer element is read through the integer form of its class. + var heapSlot = bindingKind is { } heapKind ? BindlessHeap.ImageSlot(heapKind) : -1; + HeapRecordUse heapImage = default; + var fromHeap = fixedElement is null && heapSlot >= 0 && _heapRecordIndex is not null && + request.HeapImageByMemoryIndex.TryGetValue(memoryIndex, out heapImage); + if (heapVolumeLayers) + { + if (!fromHeap || heapSlot != BindlessHeap.VolumeSlot) + { + error = "only a 3D heap image read has a layered alternative"; + return false; + } + + heapSlot = BindlessHeap.VolumeLayerSlot; + imageClass = HeapVolumeLayerClass(); + } + + if (fromHeap && heapNumericClass != ImageNumericClass.Float) + { + imageClass = HeapIntegerClass(imageClass, heapNumericClass); + } + // A sampled mip load keeps its mip operand; a storage case is already its own mip view. // The mip is the address component right after the coordinates, so it moves with // the dimension (2 for 2D, 3 for a 2D array or a volume, 1 for 1D). @@ -2405,7 +2440,11 @@ private bool TryResolveLayoutImage( mipLevel = Temp("uint", ImageIntegerAddress(image, imageClass.CoordinateComponents)); } - if (imageInfo.BindlessSlot != DescriptorConstants.NoIndex) + if (fromHeap) + { + texture = HeapTexture(heapSlot, imageClass.TextureType, HeapImageIndex(_heapRecordIndex!, heapSlot, heapNumericClass)); + } + else if (imageInfo.BindlessSlot != DescriptorConstants.NoIndex) { if (fixedElement is null || _bindlessAccess is not { } bindless) { @@ -2423,7 +2462,15 @@ private bool TryResolveLayoutImage( } resolved = imageClass; - if (UsesSampler(instruction.Opcode)) + if (UsesSampler(instruction.Opcode) && fixedElement is null && + request.HeapSamplerByMemoryIndex.TryGetValue(memoryIndex, out var heapSampler)) + { + // A heap sampler is the element its key picks from the sampler array of its kind. + samplerName = HeapSampler(imageInfo.DepthCompare ? BindlessHeap.CompareSamplerSlot : BindlessHeap.SamplerSlot, heapSampler); + var heapSamplerIndex = request.Resources.SamplerByMemoryIndex.TryGetValue(memoryIndex, out var mapped) ? mapped : entry.Sampler; + samplerInfo = heapSamplerIndex < (uint)info.Samplers.Count ? info.Samplers[(int)heapSamplerIndex] : null; + } + else if (UsesSampler(instruction.Opcode)) { if (!_hasSamplers) { diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalBindlessHeapTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalBindlessHeapTests.cs new file mode 100644 index 000000000..17532d9f4 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalBindlessHeapTests.cs @@ -0,0 +1,416 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.ShaderCompiler.Metal.Tests; + +/// +/// The bindless heap on the GPU (BindlessHeap, Gen5MslTranslator.BindlessHeap.cs): an image or sampler read from a heap +/// V# at a lane-chosen record takes the element of that record in the draw's heap view, marks it in the feedback +/// bitsets, reads a null element as zero, reads an integer element through the declaration of its numeric class, and a +/// 3D read of a record that holds a 2D texture takes the record's layers. The MSL twins of the SPIR-V heap tests +/// (tests/SharpEmu.ShaderCompiler.Tests/Resources/BindlessHeapTests.cs). +/// +public sealed class MetalBindlessHeapTests(ITestOutputHelper output) +{ + // MetalBindlessImageTests' waterfall: per lane, s_buffer_load_dwordx8 of the T# at key * 32 through the table V# + // (user data block + 0x10), image_sample_l at (0.5, 0.5, layer 1.0, lod 0) dim:2D_ARRAY with the S# at +0x30, + // the texel stored at lane * 16. + private static readonly uint[] Sample = + [ + 0xF4080200, 0xFA000010, 0xF4080600, 0xFA000020, 0xF4080700, 0xFA000030, 0xBF8CC07F, 0x34020082, + 0x4A0202FF, 0x00014000, 0x34060084, 0xE0301000, 0x80060201, 0xBF8C3F70, 0x2C160484, 0x7E0802F0, + 0x7E0A02F0, 0x7E0C02F2, 0x7E0E0280, 0xBE86047E, 0x7E260281, 0x7EC8050B, 0xBE94047E, 0x7DA41664, + 0x8F648564, 0x7E260280, 0xF42C0304, 0xC8000000, 0xBF8CC07F, 0xF0900F28, 0x00E31404, 0xBEFE0414, + 0x7DAA2680, 0xBF89FFF3, 0xBEFE0406, 0xBF8C3F70, 0xE0781000, 0x80061403, 0xBF810000, + ]; + + // Variants, assembled with llvm-mc for gfx1030 and patched over the instructions they replace (same sizes): + // image_load v[20:23], v[4:6], s[12:19] dmask:0xf dim:2D_ARRAY unorm at (0, 0, layer 1). + private static uint[] Load() => Patch(Sample, (15, 0x7E080280), (16, 0x7E0A0280), (17, 0x7E0C0281), (29, 0xF0001F28), (30, 0x00031404)); + + // image_get_resinfo v[20:23], v4 (lod 0), s[12:19] dmask:0xf dim:2D_ARRAY. + private static uint[] SizeQuery() => Patch(Sample, (15, 0x7E080280), (29, 0xF0381F28), (30, 0x00031404)); + + // image_sample_l at (0.5, 0.5, 1.0, lod 0) dim:3D. + private static uint[] VolumeSample() => Patch(Sample, (29, 0xF0900F10)); + + // The T# from user data (s_load_dwordx8 s[12:19] at +0x40), the S# from the table at key * 16 + // (s_lshl_b32 s100, s100, 4; s_buffer_load_dwordx4 s[28:31], s[8:11], s100). + private static uint[] HeapSampler() => Patch(Sample, (4, 0xF40C0300), (5, 0xFA000040), (24, 0x8F648464), (26, 0xF4280704), (27, 0xC8000000)); + + private static uint[] Patch(uint[] words, params (int Index, uint Word)[] patches) + { + var patched = words.ToArray(); + foreach (var (index, word) in patches) + patched[index] = word; + return patched; + } + + private const ulong ResourceBlock = 0x1000; + private const ulong TableAddress = 0x10000; + private const int Entries = 4096; + private const int Lanes = 1024; + private const int KeyOffset = 0x14000; + private const uint UserDataCount = 16; + // The view's first element: the record e of the heap is element First + e. + private const uint First = 100; + + private const uint FloatFormat = 71; + private const uint Type2DArray = 13; + private const uint Type3D = 10; + + private static uint[] ImageWords(uint type) => + [0x100u, FloatFormat << 20, 0, (type << 28) | DescriptorConstants.IdentityImageSwizzle, 1, 0, 0, 0]; + + private static byte[] Guest(uint tableBytes, uint imageType) + { + var memory = new byte[0x40000]; + void Write(ulong address, uint[] words) + { + for (var index = 0; index < words.Length; index++) + BinaryPrimitives.WriteUInt32LittleEndian(memory.AsSpan((int)address + index * 4), words[index]); + } + + Write(ResourceBlock + 0x10, [(uint)TableAddress, 0, tableBytes, DescriptorConstants.IdentityDestinationSelect]); + Write(ResourceBlock + 0x20, [0x30000, 0, KeyOffset + Lanes * 4, 0x00038FAC]); + Write(ResourceBlock + 0x30, [0, 0, 0, 0]); + Write(ResourceBlock + 0x40, ImageWords(imageType)); + return memory; + } + + private static ShaderCompileRequest Request(uint[] words, bool bindlessHeap, out ResourceSnapshot snapshot, uint tableBytes = Entries * 32, + uint imageType = Type2DArray) + { + var guest = Guest(tableBytes, imageType); + bool Read(ulong address, out uint word) + { + word = 0; + if (address + 4 > (ulong)guest.Length) return false; + word = BinaryPrimitives.ReadUInt32LittleEndian(guest.AsSpan((int)address)); + return true; + } + + var program = Gen5ComputeFixtures.DecodeOrThrow(new Gen5ComputeFixture("bindless-heap", words, 0, 0)); + var plan = ShaderResourcePlan.Extract(program, ShaderStage.Compute, 0x4845_4150, 0, UserDataCount, bindlessHeap: bindlessHeap); + var userData = new uint[UserDataCount]; + userData[0] = (uint)ResourceBlock; + snapshot = new ResourceSnapshot(); + var specialization = new ResourceSpecialization(); + var inputs = new ResourceRuntimeInputs { UserData = userData, ReadMemory = Read, ReadCleanMemory = Read }; + Assert.True(ResourceMaterializer.Materialize(plan, inputs, ref snapshot, ref specialization, out var failure), $"materialize: {failure}"); + var resources = ResourceMaterializer.ApplyTo(plan, specialization); + var layout = BindingLayout.Allocate(resources.Info, BindingLayout.CollectUserDataRegisters(program, 0, UserDataCount), + false, ShaderCompileRequest.RequiresFlattenedTable(plan, resources), false); + return new ShaderCompileRequest(plan, resources, layout) { WaveSize = 32, LocalSizeX = Lanes }; + } + + [Fact] + public void AHeapRecordReadsItsElementThroughTheHeapAndMarksIt() + { + var request = Request(Sample, bindlessHeap: true, out var snapshot); + Assert.True(request.UsesBindlessHeap); + Assert.Single(request.HeapImageByMemoryIndex); + Assert.Equal([new BindlessHeapDescriptor(false, TableAddress, Entries * 32, 0)], snapshot.Heaps); + + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error), error); + var layout = shader.ArgumentLayout!; + Assert.Contains(layout.Fields, field => field.FieldKind == MslArgumentFieldKind.BindlessHeapElements); + Assert.Contains(layout.Fields, field => field.FieldKind == MslArgumentFieldKind.BindlessHeapFeedback); + Assert.Contains("device const ulong* heap_elements", shader.Source); + Assert.Contains("atomic_fetch_or_explicit(&sharpemu_resources.heap_feedback[", shader.Source); + Assert.Contains($"{BindlessHeap.CallRecordNullIndex}u", shader.Source); + Assert.Contains("struct sharpemu_heap_texture2d_array_float_ { texture2d_array texture; };", shader.Source); + // A sample of a class with integer forms reads only a float element. + Assert.Contains($"& {BindlessHeap.ClassMask}u", shader.Source); + } + + // Without the heap the same table is a V#-described bindless table, and the source has no heap at all. + [Fact] + public void WithoutTheHeapTheTableIsABindlessTable() + { + var request = Request(Sample, bindlessHeap: false, out var snapshot); + Assert.False(request.UsesBindlessHeap); + Assert.Single(snapshot.BindlessImages); + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error), error); + Assert.DoesNotContain("heap_", shader.Source); + Assert.DoesNotContain(shader.ArgumentLayout!.Fields, field => field.FieldKind is MslArgumentFieldKind.BindlessHeapElements or + MslArgumentFieldKind.BindlessHeapFeedback); + } + + [Fact] + public void AHeapSamplerReadsItsElementFromTheSamplerArray() + { + var request = Request(HeapSampler(), bindlessHeap: true, out _, tableBytes: Entries * 16); + Assert.Single(request.HeapSamplerByMemoryIndex); + Assert.Empty(request.HeapImageByMemoryIndex); + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error), error); + Assert.Contains("struct sharpemu_heap_sampler { sampler state; };", shader.Source); + Assert.Contains($"{(uint)BindlessHeap.SamplerSlot * BindlessHeap.Capacity}u", shader.Source); + } + + // ---------------------------------------------------------------- on the GPU + + private bool DeviceGate() + { + if (Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") == "1") + { + Assert.True(MetalNative.IsAvailable); + return true; + } + + output.WriteLine("Bindless heap execution requires the exclusive Metal device gate."); + return false; + } + + // Lane l reads record Key(l): every record of the heap over four passes, keys past the view in the fifth. + private static int Key(int pass, int lane) => pass < 4 ? (pass * Lanes + lane) * 1237 % Entries : Entries + lane * 13; + + private static uint Texel(int texture, int component) => BitConverter.SingleToUInt32Bits(texture * 4 + component + 0.25f); + + private static nint LayeredTexture(nuint format, uint[] texel) => + MetalNative.CreateTexelTexture(format, MetalNative.TextureType2DArray, 2, [.. Enumerable.Repeat(0xDEADu, 4), .. texel]); + + // Runs the program over five passes of keys with the given element table and class words; returns per pass the + // lanes' four result words and the feedback words after the pass. + private List<(int[] Keys, uint[] Result, uint[] Feedback)> Run(ShaderCompileRequest request, ResourceSnapshot snapshot, byte[] elements, + IReadOnlyList residents, uint[] classes, nint texture = 0, Func? textureOfClass = null) + { + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error), error); + Assert.True(MetalNative.TryCompileLibrary(shader!.Source, out var library, out error), error); + var layout = request.Bindings; + var shaderData = new uint[Math.Max(layout.ShaderDataDwordCount, 1)]; + for (var index = 0; index < layout.UserDataRegisters.Count; index++) + shaderData[index] = snapshot.UserData[(int)layout.UserDataRegisters[index]]; + var view = HeapView.Of(snapshot.Heaps[0], First, snapshot.Heaps[0].ViewRecords); + shaderData[layout.HeapViewsDword] = view.Word0; + shaderData[layout.HeapViewsDword + 1] = view.Word1; + var pushData = new byte[PushData.ByteSize]; + for (var index = 0; layout.UsesPushData && index < layout.ShaderDataDwordCount; index++) + BinaryPrimitives.WriteUInt32LittleEndian(pushData.AsSpan((int)(layout.PushDataStartDword + index) * 4), shaderData[index]); + + var heapElements = MetalNative.CreateHeapElements(elements, residents); + var runs = new List<(int[], uint[], uint[])>(); + for (var pass = 0; pass < 5; pass++) + { + var feedbackWords = new uint[BindlessHeap.FeedbackWords]; + classes.CopyTo(feedbackWords, (int)BindlessHeap.MarkWords); + var feedback = MetalNative.CreateHeapFeedback(feedbackWords); + var keys = Enumerable.Range(0, Lanes).Select(lane => Key(pass, lane)).ToArray(); + var data = new byte[KeyOffset + Lanes * 4]; + for (var lane = 0; lane < Lanes; lane++) + BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(KeyOffset + lane * 4), (uint)keys[lane] << 4); + Assert.True(MetalNative.TryExecuteWithArgumentBuffer(library, shader.EntryPoint, data, pushData, shader.ArgumentLayout!, Lanes, + out var result, out _, out error, texture: texture, sampler: MetalNative.CreatePointSampler(), + tables: [MetalNative.CreateWordTable(DescriptorBindingKind.ShaderData, shaderData)], textureOfClass: textureOfClass, + heap: (heapElements, feedback)), error); + var words = new uint[Lanes * 4]; + Buffer.BlockCopy(result, 0, words, 0, words.Length * 4); + runs.Add((keys, words, MetalNative.ReadWords(feedback))); + } + + return runs; + } + + private static void SetElement(byte[] elements, int slot, uint element, nint texture) => + BinaryPrimitives.WriteUInt64LittleEndian(elements.AsSpan((int)(((uint)slot * BindlessHeap.Capacity + element) * 8)), + texture == 0 ? 0 : MetalNative.ResourceId(texture)); + + // The elements a pass marks in one array: each in-view record's element, and the null element for keys past it. + private static void AssertMarks(uint[] feedback, int slot, IEnumerable elements, int pass) + { + var expected = new uint[BindlessHeap.FeedbackWordsPerArray]; + foreach (var element in elements) + expected[element >> 5] |= 1u << (int)(element & 31); + for (var word = 0; word < expected.Length; word++) + { + var actual = feedback[slot * (int)BindlessHeap.FeedbackWordsPerArray + word]; + Assert.True(expected[word] == actual, $"pass {pass} slot {slot} mark word {word}: expected 0x{expected[word]:X8}, marked 0x{actual:X8}"); + } + } + + private static uint ElementOf(int key) => key < Entries ? First + (uint)key : BindlessHeap.CallRecordNullIndex; + + private static void AssertLane(uint[] result, int pass, int lane, int key, uint[] expected) + { + for (var component = 0; component < 4; component++) + { + var actual = result[lane * 4 + component]; + Assert.True(expected[component] == actual, + $"pass {pass} lane {lane} key {key} component {component}: expected 0x{expected[component]:X8}, read 0x{actual:X8}"); + } + } + + // Record e holds texture (e * 37) % 64, except every seventh, whose element is null; keys past the view read the null + // element. Every read element is marked, and nothing else. + [Fact] + public void EveryLaneReadsTheElementOfItsRecordAndMarksIt() + { + if (!DeviceGate()) return; + + var request = Request(Sample, bindlessHeap: true, out var snapshot); + var slot = BindlessHeap.ImageSlot(ImageDescriptorBinding.ForImage(request.Resources.Info.Images[0])!.Value); + Assert.Equal(BindlessHeap.VolumeLayerSlot, slot); + var textures = Enumerable.Range(0, 64) + .Select(texture => LayeredTexture(MetalNative.PixelFormatRgba32Float, [.. Enumerable.Range(0, 4).Select(component => Texel(texture, component))])) + .ToArray(); + int TextureOf(int record) => record % 7 == 3 ? -1 : record * 37 % 64; + var elements = new byte[BindlessHeap.ArrayCount * BindlessHeap.Capacity * 8]; + for (var record = 0; record < Entries; record++) + SetElement(elements, slot, First + (uint)record, TextureOf(record) < 0 ? 0 : textures[TextureOf(record)]); + + var nullArray = LayeredTexture(MetalNative.PixelFormatRgba32Float, new uint[4]); + foreach (var (pass, (keys, result, feedback)) in Run(request, snapshot, elements, textures, [], nullArray).Index()) + { + for (var lane = 0; lane < Lanes; lane++) + { + var texture = keys[lane] < Entries ? TextureOf(keys[lane]) : -1; + AssertLane(result, pass, lane, keys[lane], texture < 0 ? new uint[4] : [.. Enumerable.Range(0, 4).Select(component => Texel(texture, component))]); + } + + AssertMarks(feedback, slot, keys.Select(ElementOf), pass); + } + } + + // A load of a class with integer forms reads each element through the declaration of the numeric class the host + // recorded for it (float, uint or sint texels, bit for bit); a null element of any class reads zero. + [Fact] + public void AnIntegerElementIsReadThroughItsNumericClass() + { + if (!DeviceGate()) return; + + var request = Request(Load(), bindlessHeap: true, out var snapshot); + var slot = BindlessHeap.ImageSlot(ImageDescriptorBinding.ForImage(request.Resources.Info.Images[0])!.Value); + Assert.True(BindlessHeap.HoldsIntegers(slot)); + const nuint Rgba32Sint = 124; + (ImageNumericClass Class, nuint Format)[] kinds = + [(ImageNumericClass.Float, MetalNative.PixelFormatRgba32Float), (ImageNumericClass.Uint, MetalNative.PixelFormatRgba32Uint), (ImageNumericClass.Sint, Rgba32Sint)]; + uint TexelOf(int record, int component) => 0x4000_0000u + (uint)(record * 4 + component); + ImageNumericClass? ClassOf(int record) => record % 5 == 4 ? null : kinds[record % 3].Class; + var elements = new byte[BindlessHeap.ArrayCount * BindlessHeap.Capacity * 8]; + var classes = new uint[BindlessHeap.ClassWords]; + var textures = new List(); + for (var record = 0; record < Entries; record++) + { + var element = First + (uint)record; + if (ClassOf(record) is not { } numericClass) + continue; + var texture = LayeredTexture(kinds[record % 3].Format, [.. Enumerable.Range(0, 4).Select(component => TexelOf(record, component))]); + textures.Add(texture); + SetElement(elements, slot, element, texture); + classes[element >> (int)BindlessHeap.ClassWordShift] |= + BindlessHeap.ClassCode(numericClass) << (int)((element & (BindlessHeap.ClassesPerWord - 1)) * BindlessHeap.ClassBits); + } + + var nullArray = LayeredTexture(MetalNative.PixelFormatRgba32Float, new uint[4]); + foreach (var (pass, (keys, result, feedback)) in Run(request, snapshot, elements, textures, classes, nullArray).Index()) + { + for (var lane = 0; lane < Lanes; lane++) + { + var key = keys[lane]; + var present = key < Entries && ClassOf(key) is not null; + AssertLane(result, pass, lane, key, present ? [.. Enumerable.Range(0, 4).Select(component => TexelOf(key, component))] : new uint[4]); + } + + AssertMarks(feedback, slot, keys.Select(ElementOf), pass); + } + } + + // The size query of an element reports its texture's extent, layers and levels; a null element reports zero. + [Fact] + public void ANullElementReportsNoSize() + { + if (!DeviceGate()) return; + + var request = Request(SizeQuery(), bindlessHeap: true, out var snapshot); + var slot = BindlessHeap.ImageSlot(ImageDescriptorBinding.ForImage(request.Resources.Info.Images[0])!.Value); + var texture = LayeredTexture(MetalNative.PixelFormatRgba32Float, new uint[4]); + var elements = new byte[BindlessHeap.ArrayCount * BindlessHeap.Capacity * 8]; + for (var record = 0; record < Entries; record += 2) + SetElement(elements, slot, First + (uint)record, texture); + + foreach (var (pass, (keys, result, _)) in Run(request, snapshot, elements, [texture], [], texture).Index()) + { + for (var lane = 0; lane < Lanes; lane++) + { + var key = keys[lane]; + AssertLane(result, pass, lane, key, key < Entries && key % 2 == 0 ? [1u, 1u, 2u, 1u] : new uint[4]); + } + } + } + + // A 3D read takes the record's 3D element; a record whose 3D element is null (it holds a 2D texture) is read through + // its 2D-array element, the third coordinate as the layer; a record null in both reads zero. Only the reads that fall + // back mark the 2D-array element. + [Fact] + public void AVolumeReadOfALayeredRecordReadsItsLayer() + { + if (!DeviceGate()) return; + + var request = Request(VolumeSample(), bindlessHeap: true, out var snapshot, imageType: Type3D); + Assert.Equal(BindlessHeap.VolumeSlot, BindlessHeap.ImageSlot(ImageDescriptorBinding.ForImage(request.Resources.Info.Images[0])!.Value)); + var volume = MetalNative.CreateFloatTexture(7, 1, 1, 1, 1, + [[.. Enumerable.Range(0, 4).SelectMany(component => BitConverter.GetBytes(Texel(1, component)))]]); + var layered = LayeredTexture(MetalNative.PixelFormatRgba32Float, [.. Enumerable.Range(0, 4).Select(component => Texel(2, component))]); + var elements = new byte[BindlessHeap.ArrayCount * BindlessHeap.Capacity * 8]; + for (var record = 0; record < Entries; record++) + { + if (record % 3 == 0) SetElement(elements, BindlessHeap.VolumeSlot, First + (uint)record, volume); + if (record % 3 == 1) SetElement(elements, BindlessHeap.VolumeLayerSlot, First + (uint)record, layered); + } + + foreach (var (pass, (keys, result, feedback)) in Run(request, snapshot, elements, [volume, layered], [], volume).Index()) + { + for (var lane = 0; lane < Lanes; lane++) + { + var key = keys[lane]; + var texture = key >= Entries ? -1 : key % 3 == 0 ? 1 : key % 3 == 1 ? 2 : -1; + AssertLane(result, pass, lane, key, texture < 0 ? new uint[4] : [.. Enumerable.Range(0, 4).Select(component => Texel(texture, component))]); + } + + AssertMarks(feedback, BindlessHeap.VolumeSlot, keys.Select(ElementOf), pass); + AssertMarks(feedback, BindlessHeap.VolumeLayerSlot, keys.Where(key => key >= Entries || key % 3 != 0).Select(ElementOf), pass); + } + } + + // The sampler a record names filters the read: records alternate a nearest and a linear sampler over a two-texel + // row, sampled at its middle. Keys past the view read the null sampler the host fills the array with (nearest). + [Fact] + public void AHeapSamplerFiltersWithTheSamplerItsRecordNames() + { + if (!DeviceGate()) return; + + var request = Request(HeapSampler(), bindlessHeap: true, out var snapshot, tableBytes: Entries * 16); + var left = Enumerable.Range(0, 4).Select(component => 2f + component).ToArray(); + var right = Enumerable.Range(0, 4).Select(component => 10f + component * 4).ToArray(); + var row = left.Concat(right).SelectMany(BitConverter.GetBytes).ToArray(); + var texture = MetalNative.CreateFloatTexture(3, 2, 1, 2, 1, [[.. new byte[row.Length], .. row]]); + var nearest = MetalNative.CreateFilterSampler(0); + var linear = MetalNative.CreateFilterSampler(1); + var elements = new byte[BindlessHeap.ArrayCount * BindlessHeap.Capacity * 8]; + for (var element = 0u; element < BindlessHeap.Capacity; element++) + { + var record = (int)element - (int)First; + var sampler = record >= 0 && record < Entries && record % 2 == 1 ? linear : nearest; + BinaryPrimitives.WriteUInt64LittleEndian(elements.AsSpan((int)(((uint)BindlessHeap.SamplerSlot * BindlessHeap.Capacity + element) * 8)), + MetalNative.ResourceId(sampler)); + } + + foreach (var (pass, (keys, result, feedback)) in Run(request, snapshot, elements, [], [], texture).Index()) + { + for (var lane = 0; lane < Lanes; lane++) + { + var key = keys[lane]; + var filtered = key < Entries && key % 2 == 1; + AssertLane(result, pass, lane, key, + [.. Enumerable.Range(0, 4).Select(component => BitConverter.SingleToUInt32Bits(filtered ? (left[component] + right[component]) / 2 : right[component]))]); + } + + AssertMarks(feedback, BindlessHeap.SamplerSlot, keys.Select(ElementOf), pass); + } + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.Bindless.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.Bindless.cs index 5e0f189bf..a314aa6c8 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.Bindless.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.Bindless.cs @@ -48,6 +48,33 @@ public static nint CreateTexelTexture(nuint pixelFormat, nuint textureType, uint public static DeviceTable CreateBindlessTable(byte[] entries, IReadOnlyList textures) => new(DescriptorBindingKind.Buffers, SharedBuffer(entries), (uint)(entries.Length / 16), textures); + /// The bindless heap's element table as the v2 host writes it: 8 bytes per element, slot-major. + public static DeviceTable CreateHeapElements(byte[] elements, IReadOnlyList residents) => + new(DescriptorBindingKind.Buffers, SharedBuffer(elements), (uint)(elements.Length / 8), residents); + + /// The bindless heap's feedback words (mark bitsets, then element classes), as given. + public static DeviceTable CreateHeapFeedback(uint[] words) => CreateWordTable(DescriptorBindingKind.Buffers, words); + + /// The words of a table's buffer as the GPU left them. + public static uint[] ReadWords(DeviceTable table) + { + var bytes = ReadSharedBuffer(table.Buffer, (int)table.Count * sizeof(uint)); + var words = new uint[table.Count]; + Buffer.BlockCopy(bytes, 0, words, 0, bytes.Length); + return words; + } + + /// A normalized-coordinate sampler with the given min/mag filter (0 nearest, 1 linear), clamped to edge. + public static nint CreateFilterSampler(nuint filter) + { + var descriptor = Send(Send(objc_getClass("MTLSamplerDescriptor"), Selector("alloc")), Selector("init")); + SendVoidBool(descriptor, Selector("setSupportArgumentBuffers:"), true); + SendInteger(descriptor, Selector("setNormalizedCoordinates:"), 1); + SendInteger(descriptor, Selector("setMinFilter:"), filter); + SendInteger(descriptor, Selector("setMagFilter:"), filter); + return Send(Device.Value, Selector("newSamplerStateWithDescriptor:"), descriptor); + } + /// A read-only table bound to one pointer field, holding the given words. public static DeviceTable CreateWordTable(DescriptorBindingKind kind, uint[] words) { diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.cs index a2de2ca58..186803985 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.cs @@ -236,7 +236,8 @@ public static bool TryExecuteWithArgumentBuffer( IReadOnlyList? tables = null, IReadOnlyList? bindlessTables = null, Func? textureOfClass = null, - IReadOnlyList<(uint Index, uint Value)>? constants = null) + IReadOnlyList<(uint Index, uint Value)>? constants = null, + (DeviceTable Elements, DeviceTable Feedback)? heap = null) { result = []; stepCapHits = 0; @@ -288,6 +289,12 @@ public static bool TryExecuteWithArgumentBuffer( BitConverter.TryWriteBytes(arguments.AsSpan((int)field.ByteOffset + (element * 8)), SendULong(sampler, Selector("gpuResourceID"))); break; + case MslArgumentFieldKind.BindlessHeapElements: + BitConverter.TryWriteBytes(arguments.AsSpan((int)field.ByteOffset), SendULong(heap!.Value.Elements.Buffer, Selector("gpuAddress"))); + break; + case MslArgumentFieldKind.BindlessHeapFeedback: + BitConverter.TryWriteBytes(arguments.AsSpan((int)field.ByteOffset), SendULong(heap!.Value.Feedback.Buffer, Selector("gpuAddress"))); + break; case MslArgumentFieldKind.BufferByteCounts: BitConverter.TryWriteBytes(arguments.AsSpan((int)field.ByteOffset + (element * 4)), (uint)bufferContents.Length); break; @@ -332,6 +339,9 @@ public static bool TryExecuteWithArgumentBuffer( .. texture == 0 ? Array.Empty() : [texture], .. (tables ?? []).SelectMany(static table => (nint[])[table.Buffer, .. table.Residents]), .. (bindlessTables ?? []).SelectMany(static table => (nint[])[table.Buffer, .. table.Residents]), + .. heap is { } heapTables + ? (nint[])[heapTables.Elements.Buffer, .. heapTables.Elements.Residents, heapTables.Feedback.Buffer] + : [], .. textureOfClass is null ? Array.Empty() : layout.Fields .Where(static field => field.FieldKind == MslArgumentFieldKind.Textures) .Select(field => textureOfClass(field.Kind)).Distinct(), From 47a6f51dd5e2dd322c53bcbe4216ec048070b18c Mon Sep 17 00:00:00 2001 From: kuba Date: Fri, 20 Nov 2026 01:22:41 +0000 Subject: [PATCH 093/134] [Metal] Resolve bindless heap records on the Metal host SupportsBindlessHeap is now true on Metal (SHARPEMU_METAL_BINDLESS_HEAP, default on; =0 restores the previous planning: bindless image tables, the 256-candidate indirect limit, off-class candidates reading null). MetalRenderHost.BindlessHeap.cs ports VulkanVideoPresenter.BindlessHeap.cs: - one shared element table (10 slots x 131072 x 8-byte gpuResourceIDs, the sampler slots pre-filled with the null sampler from an all-zero S#) and one shared feedback buffer (mark bitsets, then 2-bit class codes); - once per preparation, the marks of submissions completed since the last look become entries: the record's T# or S# is read from guest memory, the image found through the image cache (FindImage, ValidateTextureOwner, AcquireTextureViewForMemo) with the slot's shape and numeric class, the depth-view check for compare slots, and the handle and class written; - each heap view of a stage gets its run from the shared BindlessHeapViewTable (views stay resident across frames, idle runs are released after 256 submissions and 2 flips, a heap that outgrows its run copies its entries into the larger run); - a view's records are compared with guest memory every 16 submissions, and its textures are reacquired (memo stamp) and noted as used once per submission and again when the image cache's epochs move, which stands in for Vulkan's HeapChanged/DeferredErase hooks; - textures no pass writes go into the bindless residency set (the prune now counts the heap's textures as named); the others are declared to each encoder of a draw that reads the heap. The pass joins treat a program that reads the heap like one with bindless tables (it could sample any open attachment). SharpEmu.Libs gives SharpEmu.Gpu.Metal its internals, as it does Gpu.Vulkan, for the shared BindlessHeapViewTable. No split wire fields are needed: planning, the MSL compile and this host all run in the GPU process, which inherits the switch from the guest's environment. --- docs/macos/configuration.md | 1 + src/SharpEmu.Libs/SharpEmu.Libs.csproj | 2 + .../V2/MetalRenderHost.BindlessHeap.cs | 789 ++++++++++++++++++ .../V2/MetalRenderHost.BindlessImages.cs | 2 +- .../V2/MetalRenderHost.DepthOnlyJoin.cs | 4 +- .../V2/MetalRenderHost.Descriptors.cs | 26 + .../V2/MetalRenderHost.UnionPass.cs | 4 +- .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 1 + 8 files changed, 824 insertions(+), 5 deletions(-) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessHeap.cs diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 4e7a6aaf5..04b87d3c9 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -66,6 +66,7 @@ them for measurements or to isolate a problem. | --- | --- | --- | | `SHARPEMU_METAL_MESH_SHADERS` | on | `0` disables mesh pipelines for primitive-shader draws. | | `SHARPEMU_METAL_DRAW_PARAMETERS` | on | `0` turns off draw parameters in translated vertex programs. By default a vertex program's instance index counts from the draw's base instance, and when an indirect draw names a user-data register for its base vertex or start instance, the program counts its vertex index from the base vertex and stores both bases there (the command processor no longer writes those registers). `0` gives the program Metal's ids, which include both bases, and stores nothing. | +| `SHARPEMU_METAL_BINDLESS_HEAP` | on | `0` turns off the bindless heap. By default an image or sampler a program reads from a descriptor table at a record only the shader knows is read through the heap: the shader marks the records it reads, the host resolves each marked record's texture or sampler from guest memory, and the program reads it from a later draw on (the first read of a record returns zeros). `0` plans those tables as before (bindless image tables, at most 256 candidates, off-class candidates read null). | | `SHARPEMU_RUNTIME_IMAGE_SWIZZLE` | on | `0` bakes each storage image's destination select into the translated program, one program per select. By default a store reads the image's channel map from shader data, which the host writes from the bound descriptor. | | `SHARPEMU_METAL_FORMAT_LOAD_COMPONENT_BOUNDS` | on | `0` restores the old bound of a formatted buffer load whose format is fixed at translation: the whole element had to fit below the buffer's size. By default each selected component is checked at its own address, wrapping past 2^32 as on the hardware, so a component that wraps to the buffer's start is read, and the load reads its constants only when a selected component is out of range. An element that fits whole still takes one compare. Loads whose format is read at run time always check per component. | | `SHARPEMU_GRAPHICS_PARTIAL_LANES` | off | `1` makes pixel-shader lane reads (DPP, DPP8, PERMLANE16, V_READLANE) of a lane the fragment simdgroup never launched read the reading lane's own value, and treats such a lane as active when the guest EXEC mask has its bit. Off by default, as upstream: it changes every pixel shader with cross-lane operations. | diff --git a/src/SharpEmu.Libs/SharpEmu.Libs.csproj b/src/SharpEmu.Libs/SharpEmu.Libs.csproj index 95bdaad2e..ce33b0fa5 100644 --- a/src/SharpEmu.Libs/SharpEmu.Libs.csproj +++ b/src/SharpEmu.Libs/SharpEmu.Libs.csproj @@ -29,6 +29,8 @@ SPDX-License-Identifier: GPL-2.0-or-later + + diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessHeap.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessHeap.cs new file mode 100644 index 000000000..7e2a9afb9 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessHeap.cs @@ -0,0 +1,789 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Numerics; +using SharpEmu.Libs.Gpu.Abstractions; +using SharpEmu.Libs.Gpu.Buffers; +using SharpEmu.Libs.Gpu.Images; +using SharpEmu.Libs.VideoOut; +using SharpEmu.ShaderCompiler.Metal; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.Gpu.Metal.V2; + +// The bindless heap (see BindlessHeap): a program that reads an image or sampler from a heap V# at a record only its +// shader knows reads it through an element table, one 8-byte handle (a gpuResourceID) per element and heap array, +// slot-major (slot * Capacity + element), the arrays Vulkan keeps in descriptor set 1. Every element starts null: a zero +// image handle, which the shader reads as zeros without touching a texture, or the null sampler. Each heap view of a draw +// (a heap V# and the offset of a descriptor in its records) holds a run of elements (BindlessHeapViewTable), which the +// draw's shader data names. The shader marks each element it reads in a feedback bitset; once a submission completes, +// the host reads the record's T# or S# from guest memory and writes its texture or sampler. The records of a view are read +// again periodically while draws read the view, and the textures of a view are made current, and noted as used by the +// submission, before the first draw of each submission that reads it (and again when an image changed since). A record +// that holds an integer texture gets an integer view, and the feedback buffer tells the shader the element's numeric +// class. The port of VulkanVideoPresenter.BindlessHeap.cs. +// +// Both buffers are shared storage written by the CPU while command buffers may read them, as Vulkan's update-after-bind +// set is: a command in flight that reads an element being resolved reads the old (null) or the new handle. The textures +// no pass writes go into the bindless residency set; those a pass may write are declared to every encoder of a draw that +// reads the heap, as the bindless image tables' are (MetalRenderHost.BindlessImages.cs). +internal sealed partial class MetalRenderHost +{ + // SHARPEMU_METAL_BINDLESS_HEAP=0 leaves the heap off: programs are planned as before (bindless image tables, the + // 256-candidate indirect limit, off-class candidates read null). + internal static readonly bool BindlessHeapEnabled = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_BINDLESS_HEAP") != "0"; + + public bool SupportsBindlessHeap => BindlessHeapEnabled; + + // Records are read again after this many submissions, so a rewritten record gets its new texture. + private const ulong HeapRevalidationSerials = 16; + + // A heavy frame can take hundreds of submissions. Views stay resident across frames so a once-per-frame pass can read + // them before the next completed submission resolves any missing entries. + private const ulong HeapIdleSerials = 256; + private const long HeapIdleFrames = 2; + + private static ulong HeapElementTableBytes => + (ulong)BindlessHeap.ArrayCount * BindlessHeap.Capacity * Gen5MslArgumentLayout.HeapElementBytes; + + private static ulong HeapFeedbackBytes => (ulong)BindlessHeap.FeedbackWords * sizeof(uint); + + // One record the shaders marked: the words it was resolved from and what the element table holds for it. + private sealed class HeapEntry + { + public int Slot; + public uint Index; + public BindlessHeapViewTable.Region? Region; + public uint[] Words = []; + public bool Resolved; + public ImageNumericClass NumericClass; + public ResourceSlotIdentifier Image; + public ImageRequest Request; + public MetalImageCache.TextureMemoStamp? Stamp; + public nint Texture; + public ulong ResourceId; + // A texture some pass may write: declared to the encoders instead of made resident. + public bool Declared; + // A DCC surface's lookup materializes a clear the GPU may have left since: looked up on every pass. + public bool LookupEachPass; + } + + // The entries of each view in record order, and when they were last compared with the guest's records and made + // current. + private sealed class HeapRegionEntries + { + public readonly List Order = []; + public ulong ValidatedSerial; + public ulong CurrentSerial = ulong.MaxValue; + public long CurrentBinding = -1; + public long CurrentImageSet = -1; + } + + private nint _heapElements; + private nint _heapElementsContents; + private ulong _heapElementsAddress; + private nint _heapFeedback; + private nint _heapFeedbackContents; + private ulong _heapFeedbackAddress; + private ulong _heapNullSamplerId; + private uint[] _heapMarked = []; + private uint[] _heapClasses = []; + private readonly Dictionary<(int Slot, uint Index), HeapEntry> _heapEntries = new(); + // The image arrays share their elements (a record has one element in each), and so do the two sampler arrays. + private readonly BindlessHeapViewTable _heapImageViews = new(BindlessHeap.CallRecordFirstIndex); + private readonly BindlessHeapViewTable _heapSamplerViews = new(BindlessHeap.CallRecordFirstIndex); + private readonly Dictionary _heapRegionEntries = + new(ReferenceEqualityComparer.Instance); + private Action? _heapRegionReleased; + private ulong _heapPolledSerial = ulong.MaxValue; + private ulong _heapRevalidatedSerial; + private bool _heapPrepared; + private readonly List _heapStaleEntries = []; + // The heap's textures as one bindless device table: Textures names every one for the residency prune, Declared + // those declared to the encoders. + private readonly BindlessDeviceTable _heapTextures = new(); + private bool _heapTexturesChanged; + private int _heapReports; + + internal long HeapResolvedEntries, HeapReleasedRegions; + + private bool HeapCreated => _heapElements != 0; + + // The element table, its null elements and the feedback bitsets, made at the first draw that reads the heap. + private unsafe void EnsureBindlessHeap() + { + if (HeapCreated) + { + return; + } + + const nuint options = Mtl.ResourceStorageModeShared | Mtl.ResourceHazardTrackingModeUntracked; + var elements = MetalNative.SendNewBuffer(_device, SelBindlessNewBuffer, (nuint)HeapElementTableBytes, options); + var feedback = MetalNative.SendNewBuffer(_device, SelBindlessNewBuffer, (nuint)HeapFeedbackBytes, options); + if (elements == 0 || feedback == 0) + { + throw Fatal($"The bindless heap buffers could not be created: elements=0x{HeapElementTableBytes:X} feedback=0x{HeapFeedbackBytes:X}."); + } + + SetLabel(elements, "SharpEmu bindless heap elements"); + SetLabel(feedback, "SharpEmu bindless heap feedback"); + _heapElements = elements; + _heapElementsContents = MetalNative.Send(elements, SelBindlessContents); + _heapElementsAddress = MetalNative.SendGpuAddress(elements, SelGpuAddress); + _heapFeedback = feedback; + _heapFeedbackContents = MetalNative.Send(feedback, SelBindlessContents); + _heapFeedbackAddress = MetalNative.SendGpuAddress(feedback, SelGpuAddress); + new Span((void*)_heapElementsContents, checked((int)HeapElementTableBytes)).Clear(); + new Span((void*)_heapFeedbackContents, checked((int)HeapFeedbackBytes)).Clear(); + _heapMarked = new uint[BindlessHeap.MarkWords]; + _heapClasses = new uint[BindlessHeap.ClassWords]; + _heapRegionReleased = ReleaseHeapRegion; + + // Every sampler element is the null sampler (an all-zero S#) until its record is read. + Span nullSampler = stackalloc uint[4]; + _ = GetSampler(new SamplerDescriptorWords(nullSampler), integerView: false, out _heapNullSamplerId); + for (var slot = BindlessHeap.SamplerSlot; slot < BindlessHeap.ArrayCount; slot++) + { + ElementSpan(slot).Fill(_heapNullSamplerId); + } + + Console.Error.WriteLine( + $"[METAL-V2][INFO] Bindless heap: image_arrays={BindlessHeap.ImageKinds.Length} sampler_arrays=2 " + + $"capacity={BindlessHeap.Capacity} elements=0x{HeapElementTableBytes:X}"); + } + + private unsafe Span ElementSpan(int slot) => + new((void*)(_heapElementsContents + (nint)((ulong)slot * BindlessHeap.Capacity * sizeof(ulong))), (int)BindlessHeap.Capacity); + + private unsafe Span FeedbackWords => + new((void*)_heapFeedbackContents, (int)BindlessHeap.FeedbackWords); + + // Shutdown only, once every submission has drained; the image cache owns the textures. + private void DisposeBindlessHeap() + { + _heapEntries.Clear(); + _heapRegionEntries.Clear(); + _heapImageViews.ReleaseIdle(ulong.MaxValue, ulong.MaxValue, static _ => { }); + _heapSamplerViews.ReleaseIdle(ulong.MaxValue, ulong.MaxValue, static _ => { }); + if (_heapElements != 0) + { + MetalNative.SendVoid(_heapElements, SelRelease); + MetalNative.SendVoid(_heapFeedback, SelRelease); + } + + _heapElements = _heapFeedback = 0; + _heapElementsContents = _heapFeedbackContents = 0; + } + + // Once per preparation, before the images of the first stage that reads the heap are found: the records marked by + // submissions completed since the last look, and the views idle long enough to give up. + private void PrepareBindlessHeap() + { + if (_heapPrepared) + { + return; + } + + _heapPrepared = true; + EnsureBindlessHeap(); + var completed = CompletedSerial; + if (completed != _heapPolledSerial) + { + _heapPolledSerial = completed; + ResolveMarkedRecords(); + } + + var serial = SubmissionSerial; + if (serial - _heapRevalidatedSerial >= HeapRevalidationSerials) + { + ReleaseIdleHeapViews(serial); + } + } + + // The runs of elements of a stage's heap views, as the stage's shader data (HeapView, two dwords each), each view's + // records compared with the guest's when due, and its textures current for this submission. + private void WriteHeapViews(ReadOnlySpan heaps, Span words) + { + var serial = SubmissionSerial; + var completed = CompletedSerial; + var frame = Interlocked.Read(ref _flips); + for (var index = 0; index < heaps.Length; index++) + { + ref readonly var heap = ref heaps[index]; + var region = (heap.Sampler ? _heapSamplerViews : _heapImageViews).Acquire( + heap, serial, completed, _heapRegionReleased!, out var moved, out var grownFrom, frame); + if (region is not null && grownFrom is not null) + { + CopyHeapEntries(grownFrom, region); + } + + var view = region?.View ?? HeapView.None; + words[index * (int)HeapView.DwordCount] = view.Word0; + words[index * (int)HeapView.DwordCount + 1] = view.Word1; + if (region is null) + { + if (heap.Base != 0 && heap.Records != 0 && _heapReports++ < 16) + { + Console.Error.WriteLine( + $"[METAL-V2][WARN] Bindless heap view has no elements left: heap=0x{heap.Base:X16} records={heap.Records} " + + $"stride={heap.Stride}; its records read as null."); + } + + continue; + } + + if (!_heapRegionEntries.TryGetValue(region, out var entries)) + { + continue; + } + + // Only a view some draw reads is compared with the guest's records: an idle view's memory may hold anything, + // and is read again when a draw comes back to it. A run that moved to this heap is compared now: the records + // that are the same textures at the new address keep their elements. + if (moved || serial - entries.ValidatedSerial >= HeapRevalidationSerials) + { + RevalidateHeapRegion(entries, serial); + } + + if (!heap.Sampler) + { + MakeHeapRegionCurrent(entries, serial); + } + } + } + + // A heap that grew past its run takes a larger one: the records its shaders read through the old run get their + // elements in the new run now, so a draw reads them at once instead of null until the next marks come back. + private void CopyHeapEntries(BindlessHeapViewTable.Region from, BindlessHeapViewTable.Region to) + { + if (!_heapRegionEntries.TryGetValue(from, out var entries)) + { + return; + } + + foreach (var entry in entries.Order.ToArray()) + { + var index = to.View.First + (entry.Index - from.View.First); + if (!to.Holds(index) || _heapEntries.ContainsKey((entry.Slot, index))) + { + continue; + } + + _heapMarked[entry.Slot * (int)BindlessHeap.FeedbackWordsPerArray + (int)(index >> 5)] |= 1u << (int)(index & 31); + AddHeapEntry(entry.Slot, index, to); + } + } + + private void AddHeapEntry(int slot, uint index, BindlessHeapViewTable.Region region) + { + var entry = new HeapEntry { Slot = slot, Index = index, Region = region }; + _heapEntries[(slot, index)] = entry; + if (!_heapRegionEntries.TryGetValue(region, out var entries)) + { + entries = new HeapRegionEntries { ValidatedSerial = SubmissionSerial }; + _heapRegionEntries.Add(region, entries); + } + + var position = entries.Order.Count; + while (position > 0 && (entries.Order[position - 1].Index > index || + (entries.Order[position - 1].Index == index && entries.Order[position - 1].Slot > slot))) + { + position--; + } + + entries.Order.Insert(position, entry); + Span words = stackalloc uint[8]; + entry.Words = words[..ReadHeapRecord(entry, words)].ToArray(); + ResolveHeapEntry(entry); + } + + // A view gives its elements up: they read null again, and a later view that takes them starts unmarked. + private void ReleaseHeapRegion(BindlessHeapViewTable.Region region) + { + HeapReleasedRegions++; + var sampler = region.Heap.Sampler; + if (_heapRegionEntries.Remove(region, out var entries)) + { + foreach (var entry in entries.Order) + { + _heapEntries.Remove((entry.Slot, entry.Index)); + _heapMarked[entry.Slot * (int)BindlessHeap.FeedbackWordsPerArray + (int)(entry.Index >> 5)] &= ~(1u << (int)(entry.Index & 31)); + DetachHeapEntry(entry); + if (sampler) + { + ElementSpan(entry.Slot)[(int)entry.Index] = _heapNullSamplerId; + } + else + { + WriteHeapImage(entry.Slot, entry.Index, 0); + } + } + } + + // The marks of the words the run touches: a neighbour's shader marks its element again when it reads it. + var firstSlot = sampler ? BindlessHeap.SamplerSlot : 0; + var endSlot = sampler ? BindlessHeap.ArrayCount : BindlessHeap.ImageKinds.Length; + var firstWord = (int)(region.View.First >> 5); + var endWord = (int)((region.View.First + region.Extent + 31) >> 5); + var feedback = FeedbackWords; + for (var slot = firstSlot; slot < endSlot; slot++) + { + var start = slot * (int)BindlessHeap.FeedbackWordsPerArray; + for (var word = start + firstWord; word < start + endWord; word++) + { + Volatile.Write(ref feedback[word], 0); + } + } + } + + // The marks of the submissions completed since the last look: each fresh mark of an element a view holds becomes an + // entry, its record read and resolved. + private void ResolveMarkedRecords() + { + var marked = FeedbackWords[..(int)BindlessHeap.MarkWords]; + for (var word = 0; word < marked.Length; word++) + { + var fresh = Volatile.Read(ref marked[word]) & ~_heapMarked[word]; + if (fresh == 0) + { + continue; + } + + _heapMarked[word] |= fresh; + var slot = word / (int)BindlessHeap.FeedbackWordsPerArray; + var first = (uint)(word % (int)BindlessHeap.FeedbackWordsPerArray) * 32; + while (fresh != 0) + { + var index = first + (uint)BitOperations.TrailingZeroCount(fresh); + fresh &= fresh - 1; + if (index >= BindlessHeap.CallRecordFirstIndex) + { + // Call records own these elements; the shader reads a heap record past the heap's range as null. + continue; + } + + // An element no view holds was marked before its view gave it up. + var sampler = slot >= BindlessHeap.ImageKinds.Length; + if ((sampler ? _heapSamplerViews : _heapImageViews).Find(index) is not { } region) + { + _heapMarked[word] &= ~(1u << (int)(index & 31)); + continue; + } + + AddHeapEntry(slot, index, region); + } + } + } + + private void ReleaseIdleHeapViews(ulong serial) + { + _heapRevalidatedSerial = serial; + var frame = Interlocked.Read(ref _flips); + if (serial > HeapIdleSerials && frame > HeapIdleFrames) + { + var completed = CompletedSerial; + _heapImageViews.ReleaseIdle(serial - HeapIdleSerials, completed, _heapRegionReleased!, frame - HeapIdleFrames); + _heapSamplerViews.ReleaseIdle(serial - HeapIdleSerials, completed, _heapRegionReleased!, frame - HeapIdleFrames); + } + } + + // The entries of one view, in record order, compared with their records now: a changed record is resolved again. + private void RevalidateHeapRegion(HeapRegionEntries entries, ulong serial) + { + entries.ValidatedSerial = serial; + Span words = stackalloc uint[8]; + foreach (var entry in entries.Order.ToArray()) + { + if (entry.Region is null || !_heapEntries.TryGetValue((entry.Slot, entry.Index), out var current) || + !ReferenceEquals(current, entry)) + { + // Released by a resolve of an earlier entry (the view lost its run). + continue; + } + + var read = words[..ReadHeapRecord(entry, words)]; + // A T# that had no texture when it was last looked at (its memory was not mapped) is looked at again. + if (read.SequenceEqual(entry.Words) && + (entry.Resolved || entry.Slot >= BindlessHeap.ImageKinds.Length || + HeapRecordClass(entry, read) == ImageNumericClass.Unsupported)) + { + continue; + } + + entry.Words = read.ToArray(); + ResolveHeapEntry(entry); + } + } + + // Each texture of a view as an acquire now would give it, and noted as used by this submission (an image the cache + // drops is retired after the last submission that noted it): once per submission, and again when an image changed + // since the last pass. + private void MakeHeapRegionCurrent(HeapRegionEntries entries, ulong serial) + { + var binding = _imageCache.Epochs.Binding; + var imageSet = _imageCache.ImageSetVersion; + if (entries.CurrentSerial == serial && entries.CurrentBinding == binding && entries.CurrentImageSet == imageSet && + !_imageCache.HasDeferredRefreshes) + { + return; + } + + _heapStaleEntries.Clear(); + using (_imageCache.HoldForReacquire()) + { + foreach (var entry in entries.Order) + { + if (!entry.Resolved) + { + continue; + } + + if (entry.LookupEachPass || entry.Stamp is not { } stamp || + !_imageCache.TryReacquireTextureViewHeld(entry.Image, entry.Request, in stamp)) + { + _heapStaleEntries.Add(entry); + } + } + } + + foreach (var entry in _heapStaleEntries) + { + ResolveHeapEntry(entry); + } + + _heapStaleEntries.Clear(); + // What a pass may write moves the binding epoch: the entries are classified again. + if (entries.CurrentBinding != binding) + { + foreach (var entry in entries.Order) + { + if (entry.Resolved && entry.Declared != HeapTextureDeclared(entry.Image)) + { + entry.Declared = !entry.Declared; + _heapTexturesChanged = true; + } + } + } + + entries.CurrentSerial = serial; + entries.CurrentBinding = binding; + entries.CurrentImageSet = imageSet; + } + + private bool HeapTextureDeclared(ResourceSlotIdentifier identifier) + { + if (BindlessResidency is null) + { + return true; + } + + var cached = _imageCache.GetImage(identifier); + return cached.IsGpuModified || (cached.Shape.Usage & (Mtl.TextureUsageRenderTarget | Mtl.TextureUsageShaderWrite)) != 0; + } + + // The words of the entry's record (8 for an image, an R128 T# padded with zeros; 4 for a sampler), or none when its + // view has no such record or its memory cannot be read. + private int ReadHeapRecord(HeapEntry entry, Span words) + { + if (entry.Region is not { } region || !region.Holds(entry.Index) || entry.Index - region.View.First >= region.View.Records) + { + return 0; + } + + var count = checked((int)(region.Heap.DescriptorBytes / sizeof(uint))); + var address = region.View.DescriptorAddress(region.Heap, entry.Index - region.View.First); + var record = words[..count]; + if (!TryReadResidentGuestBytes(address, System.Runtime.InteropServices.MemoryMarshal.AsBytes(record), clean: true)) + { + // Bytes a recorded GPU write may still own: read word by word, which waits for the write. + for (var word = 0; word < count; word++) + { + if (!TryReadGuestWord(address + (ulong)word * sizeof(uint), out record[word])) + { + return 0; + } + } + } + + if (region.Heap is { Sampler: false, R128: true }) + { + // An R128 T# is its four words; the rest of the T# is zero. + words[count..8].Clear(); + count = 8; + } + + return count; + } + + private void ResolveHeapEntry(HeapEntry entry) + { + HeapResolvedEntries++; + DetachHeapEntry(entry); + if (entry.Slot >= BindlessHeap.ImageKinds.Length) + { + WriteHeapSampler(entry); + return; + } + + var numericClass = HeapRecordClass(entry, entry.Words); + var resourceId = numericClass != ImageNumericClass.Unsupported ? AcquireHeapImage(entry, numericClass) : 0; + WriteHeapImage(entry.Slot, entry.Index, resourceId); + } + + // The numeric class of the texture an array of this slot holds for the record, or Unsupported when it holds none: + // every class holds float textures, and the ones with integer forms hold integer textures too. + private static ImageNumericClass HeapRecordClass(HeapEntry entry, ReadOnlySpan words) + { + var numericClass = words.Length == 8 + ? ResourceMaterializer.HeapImageNumericClass(words, entry.Region is { Heap.R128: true }) + : ImageNumericClass.Unsupported; + return numericClass == ImageNumericClass.Float || BindlessHeap.HoldsIntegers(entry.Slot) ? numericClass : ImageNumericClass.Unsupported; + } + + private static ShaderImageShape HeapImageShape(int slot, ImageNumericClass numericClass, bool r128) + { + var heapClass = BindlessHeap.ImageClasses[slot]; + var dimension = heapClass.Dimension; + return new ShaderImageShape( + Volume: dimension == ImageDimension.Dim3D, + Arrayed: heapClass.Cube || dimension is ImageDimension.Dim1DArray or ImageDimension.Dim2DArray, + Cube: heapClass.Cube, + Storage: false, + DynamicMip: false, + NumericClass: numericClass switch + { + ImageNumericClass.Uint => TextureNumericClass.Uint, + ImageNumericClass.Sint => TextureNumericClass.Sint, + _ => TextureNumericClass.Float, + }, + OneDimensional: dimension is ImageDimension.Dim1D or ImageDimension.Dim1DArray, + R128: r128, + DepthCompare: heapClass.Compare); + } + + private static bool IsDepthViewFormat(GpuFormat format) => + format is GpuFormat.D16Unorm or GpuFormat.D32Sfloat or GpuFormat.D24UnormS8Uint or GpuFormat.D32SfloatS8Uint or GpuFormat.D16UnormS8Uint; + + // Finds the record's image the way a bindless table entry finds its texture (ResolveBindlessEntry); the texture's + // gpuResourceID, or 0 when the record names no texture this array can hold. + private ulong AcquireHeapImage(HeapEntry entry, ImageNumericClass numericClass) + { + TextureRequestResolution resolution; + try + { + using (ImageRequestBuilders.RejectInvalidDescriptors()) + { + resolution = ImageRequestBuilders.Texture(entry.Words, + HeapImageShape(entry.Slot, numericClass, entry.Region is { Heap.R128: true })); + } + } + catch (TextureDescriptorRejectedException) + { + return 0; + } + + var request = resolution.Request; + // The record of a table may hold no T# the guest uses (a record it has not filled, one whose memory it uses for + // other data by now, or the T# of a texture it has unloaded): words that name no mapped guest memory are no image + // for now. + var data = request.Description.Data; + if (ImageDescription.IsEmptyRange(data) || MappedDeviceAddressBytes(data.Address, data.Size) < data.Size) + { + return 0; + } + + var pagesBefore = _imageCache.RequestPageVersions(in request); + var identifier = _imageCache.FindImage(ref request, resolution.ExactFormat); + resolution = resolution with { Request = request }; + identifier = ImageRequestBuilders.ValidateTextureOwner( + _imageCache.GetImage(identifier).Description, ResourceSlotIdentifier.Invalid, identifier, resolution); + var image = _imageCache.GetImage(identifier); + var view = request.View; + // Depth-reference sampling needs a depth view; the view has the numeric class the shader reads the element by. + if (!image.SupportsViewType(in view) || + ViewFormatRules.IsIntegerFormat(view.Format) != (numericClass != ImageNumericClass.Float) || + (BindlessHeap.ImageClasses[entry.Slot].Compare && !IsDepthViewFormat(view.Format))) + { + return 0; + } + + var textureRequest = request with { Role = ImageRole.Texture }; + entry.Texture = _imageCache.AcquireTextureViewForMemo( + identifier, textureRequest, pagesBefore, out entry.ResourceId, out entry.Stamp); + if (entry.Texture == 0 || entry.ResourceId == 0) + { + entry.Texture = 0; + entry.ResourceId = 0; + entry.Stamp = null; + return 0; + } + + entry.Image = identifier; + entry.Request = textureRequest; + entry.Resolved = true; + entry.NumericClass = numericClass; + entry.Declared = HeapTextureDeclared(identifier); + entry.LookupEachPass = request.Description.Metadata.Kind == MetadataKind.Dcc; + _heapTexturesChanged = true; + return entry.ResourceId; + } + + private void DetachHeapEntry(HeapEntry entry) + { + if (entry.Texture != 0) + { + _heapTexturesChanged = true; + } + + entry.Image = ResourceSlotIdentifier.Invalid; + entry.Stamp = null; + entry.Texture = 0; + entry.ResourceId = 0; + entry.Resolved = false; + } + + // The element's handle, with its numeric class for the shaders: a handle is cleared before its class changes and + // written after, so a shader never reads a texture through the declaration of another class. + private void WriteHeapImage(int slot, uint index, ulong resourceId) + { + var elements = ElementSpan(slot); + Volatile.Write(ref elements[(int)index], 0UL); + WriteHeapElementClass(index); + if (resourceId != 0) + { + Interlocked.MemoryBarrier(); + Volatile.Write(ref elements[(int)index], resourceId); + } + } + + // The numeric class of the element at index: that of the integer view an array holds there (the arrays hold views of + // one record at an index), or float. + private void WriteHeapElementClass(uint index) + { + var code = 0u; + for (var slot = 0; slot < BindlessHeap.ImageKinds.Length && code == 0; slot++) + { + if (_heapEntries.TryGetValue((slot, index), out var entry) && entry.Resolved) + { + code = BindlessHeap.ClassCode(entry.NumericClass); + } + } + + var word = (int)(index >> (int)BindlessHeap.ClassWordShift); + var shift = (int)((index & (BindlessHeap.ClassesPerWord - 1)) * BindlessHeap.ClassBits); + var classes = (_heapClasses[word] & ~(BindlessHeap.ClassMask << shift)) | (code << shift); + if (classes == _heapClasses[word]) + { + return; + } + + _heapClasses[word] = classes; + Volatile.Write(ref FeedbackWords[(int)BindlessHeap.MarkWords + word], classes); + } + + private void WriteHeapSampler(HeapEntry entry) + { + var resourceId = _heapNullSamplerId; + if (entry.Words.Length == 4 && !(entry.Words[0] == 0xFEFEFEFE && entry.Words[1] == 0xFEFEFEFE)) + { + Span native = stackalloc uint[4] { entry.Words[0], entry.Words[1], entry.Words[2], entry.Words[3] }; + if (entry.Slot != BindlessHeap.CompareSamplerSlot) + { + native[0] &= ~(0x7u << 12); + } + + if (GetSampler(new SamplerDescriptorWords(native), integerView: false, out var found) != 0 && found != 0) + { + resourceId = found; + entry.Resolved = true; + } + } + + Volatile.Write(ref ElementSpan(entry.Slot)[(int)entry.Index], resourceId); + } + + // The stage's heap views, once its program's layout reads the heap: prepared before its images (PrepareBindings). + private void PrepareHeapViews(MetalStageBindings stage, BindingLayout layout, ResourceSnapshot snapshot) + { + if (!BindlessHeapEnabled) + { + throw Fatal($"A program reads bindless heap records with the heap off (SHARPEMU_METAL_BINDLESS_HEAP=0): hash=0x{stage.Program.Hash:X16}."); + } + + if (snapshot.Heaps.Length != layout.HeapViewCount) + { + throw Fatal( + $"The heap views do not match the layout: views={snapshot.Heaps.Length} layout={layout.HeapViewCount} " + + $"hash=0x{stage.Program.Hash:X16}."); + } + + PrepareBindlessHeap(); + var count = checked((int)(layout.HeapViewCount * HeapView.DwordCount)); + if (stage.HeapViews.Length < count) + { + stage.HeapViews = new uint[count]; + } + + WriteHeapViews(snapshot.Heaps, stage.HeapViews.AsSpan(0, count)); + } + + // The heap buffers named to the encoders, and its textures resident or declared, for a stage that reads the heap. + private void BindBindlessHeap() + { + NoteUsedResource(_heapElements, Mtl.ResourceUsageRead); + NoteUsedResource(_heapFeedback, Mtl.ResourceUsageRead | Mtl.ResourceUsageWrite); + if (_heapTexturesChanged) + { + _heapTexturesChanged = false; + var residency = BindlessResidency; + var textures = new List(); + _heapTextures.Declared.Clear(); + var signature = 0UL; + foreach (var entry in _heapEntries.Values) + { + if (entry.Texture == 0) + { + continue; + } + + textures.Add(entry.Texture); + if (entry.Declared || residency is null) + { + _heapTextures.Declared.Add(entry.Texture); + signature = (signature ^ (ulong)entry.Texture) * 0x100000001B3UL; + } + else + { + residency.Add(entry.Texture); + } + } + + _heapTextures.Textures = [.. textures]; + residency?.Commit(); + if (_heapTextures.DeclaredSignature != signature) + { + // The encoder has not been told about these yet. + _heapTextures.DeclaredSignature = signature; + _heapTextures.DeclaredEncoder = -1; + } + } + + if (!_bindlessDeclarations.Contains(_heapTextures)) + { + _bindlessDeclarations.Add(_heapTextures); + BindlessDeclaredTextures += _heapTextures.Declared.Count; + } + + BindlessResidency?.PruneIfDue(BindlessResidencyTables, SubmissionSerial, CompletedSerial); + } + + private ulong RequireHeapAddress(ulong address, MetalStageBindings stage) => + address != 0 + ? address + : throw Fatal($"A program reads bindless heap records before the heap exists: hash=0x{stage.Program.Hash:X16}."); + + // Every device table whose textures the residency set keeps: the bindless image tables', and the heap's. + private IEnumerable BindlessResidencyTables => + HeapCreated ? _bindlessTables.Values.Append(_heapTextures) : _bindlessTables.Values; +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessImages.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessImages.cs index f64287462..12a707072 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessImages.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessImages.cs @@ -231,7 +231,7 @@ private void BindBindlessImages(MetalStageBindings stage, ShaderResourceInfo inf _bindlessDescriptors += count; } - BindlessResidency?.PruneIfDue(_bindlessTables.Values, SubmissionSerial, CompletedSerial); + BindlessResidency?.PruneIfDue(BindlessResidencyTables, SubmissionSerial, CompletedSerial); _bindlessResolveTicks += Stopwatch.GetTimestamp() - started; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.DepthOnlyJoin.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.DepthOnlyJoin.cs index e6d04e30a..fb8f94f94 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.DepthOnlyJoin.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.DepthOnlyJoin.cs @@ -260,7 +260,7 @@ private bool HeldCopiesMayReachDeviceRanges(MetalStageBindings stage) } // Whether a texture the draw binds is one of the open pass's colour attachments, or a - // view of one. A program that reaches images through bindless tables could reach any. + // view of one. A program that reaches images through bindless tables or the bindless heap could reach any. private bool SamplesOpenColorAttachment() { foreach (var stage in _joinStages) @@ -270,7 +270,7 @@ private bool SamplesOpenColorAttachment() continue; } - if (stage.Program.Bindings is { BindlessImageTableCount: > 0 }) + if (stage.Program.Bindings is { BindlessImageTableCount: > 0 } or { UsesBindlessHeap: true }) { return true; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs index 36589a383..033bf1076 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs @@ -62,6 +62,8 @@ internal sealed class MetalStageBindings : IPreparedBindings public uint[] BufferLengths = []; public uint[] ShaderData = []; public ulong[] BindlessTableAddresses = []; + // The stage's heap views as shader data (MetalRenderHost.BindlessHeap.cs), found before its images. + public uint[] HeapViews = []; public int ImageCount; public int SamplerCount; public int BufferCount; @@ -240,6 +242,7 @@ public IResourcePreparation BeginPreparation() _preparedStageMask = 0; ResetUsedResources(); _bindlessDeclarations.Clear(); + _heapPrepared = false; Array.Clear(_stageArgumentValid); Array.Clear(_stageUsesDeviceAddresses); _hasPushData = false; @@ -476,6 +479,12 @@ public IPreparedBindings PrepareBindings(ShaderStageResources stage) prepared.MovieChroma = movie.Chroma; // The stage binding plan for these arrays (MetalRenderHost.StagePlan.cs), or whether to keep this one's answers. var plan = FindStagePlan(stageIndex, program, info, snapshot, movie, out var storePlan); + // Where the stage's heap views have their elements, found before the stage's own images, as Vulkan does. + if (layout.UsesBindlessHeap) + { + PrepareHeapViews(prepared, layout, snapshot); + } + if (storePlan && _stagePlanEntries.Length < info.Images.Count) { _stagePlanEntries = new TextureMemoEntry?[info.Images.Count]; @@ -580,6 +589,12 @@ public IPreparedBindings PrepareBindings(ShaderStageResources stage) } } + if (layout.HeapViewCount != 0) + { + prepared.HeapViews.AsSpan(0, checked((int)(layout.HeapViewCount * HeapView.DwordCount))) + .CopyTo(shaderData.AsSpan((int)layout.HeapViewsDword)); + } + stage.WriteDispatchThreadLimits(shaderData.AsSpan(0, shaderDwords)); stage.WriteCallData(shaderData.AsSpan(0, shaderDwords)); if (packet is not null) @@ -1185,6 +1200,11 @@ public void BindResources(IPreparedBindings prepared) { BindBindlessImages(stage, info, snapshot); } + + if (stage.Program.Bindings!.UsesBindlessHeap) + { + BindBindlessHeap(); + } } /// @@ -1815,6 +1835,12 @@ private void WriteArgumentBuffer(MetalStageBindings stage, int stageIndex) // reaching the same guest qword take the same lock. BinaryPrimitives.WriteUInt64LittleEndian(span, _guestMemory.PairLockTableGpuAddress); break; + case MslArgumentFieldKind.BindlessHeapElements: + BinaryPrimitives.WriteUInt64LittleEndian(span, RequireHeapAddress(_heapElementsAddress, stage)); + break; + case MslArgumentFieldKind.BindlessHeapFeedback: + BinaryPrimitives.WriteUInt64LittleEndian(span, RequireHeapAddress(_heapFeedbackAddress, stage)); + break; case MslArgumentFieldKind.BindlessImageTables: for (var index = 0; index < field.Count; index++) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.UnionPass.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.UnionPass.cs index 7a44c5e3e..97e532773 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.UnionPass.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.UnionPass.cs @@ -505,7 +505,7 @@ private void NoteUnionPassEnd(string cause) } // Whether a texture the next draw binds is this one or a view of it. A program that - // reaches images through bindless tables could reach any. + // reaches images through bindless tables or the bindless heap could reach any. private bool StagesSampleTexture(nint view, nint root) { foreach (var stage in _joinStages) @@ -515,7 +515,7 @@ private bool StagesSampleTexture(nint view, nint root) continue; } - if (stage.Program.Bindings is { BindlessImageTableCount: > 0 }) + if (stage.Program.Bindings is { BindlessImageTableCount: > 0 } or { UsesBindlessHeap: true }) { return true; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index a877b53fe..499d91247 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -3314,6 +3314,7 @@ public void Dispose() DisposeOcclusionAudit(); DisposeWriteFences(); DisposeHostMovie(); + DisposeBindlessHeap(); DisposeBindlessImages(); DisposePipelines(); (_transfer as IDisposable)?.Dispose(); From 2ebc2b118d0fdeedaa068ec86e195b8fb62107c1 Mon Sep 17 00:00:00 2001 From: kuba Date: Fri, 20 Nov 2026 01:22:41 +0000 Subject: [PATCH 094/134] [Tests] Bindless heap scenes on the Metal host A wave64 compute waterfall reads a T# (or S#) from a table V# at a per-lane record, which planning makes a heap record. The scenes check that the first dispatch reads null and marks, a later one reads each record's texture, the elements stay resolved across dispatches with no new resolves, a rewritten record takes its new texture once the view is compared again, a heap that grows past its run keeps the elements it had (new records resolve on the next dispatch), and heap sampler records filter with the S# they name. --- .../Scenes/BindlessHeapSceneTests.cs | 277 ++++++++++++++++++ 1 file changed, 277 insertions(+) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/Scenes/BindlessHeapSceneTests.cs diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/BindlessHeapSceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/BindlessHeapSceneTests.cs new file mode 100644 index 000000000..3d351de6f --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/BindlessHeapSceneTests.cs @@ -0,0 +1,277 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests.Scenes; + +/// +/// The bindless heap through the whole host (MetalRenderHost.BindlessHeap.cs): a compute program reads a T# from a table +/// V# at a record each lane loads, so planning makes it a heap record. The first dispatch reads null and marks the +/// records; a later one reads the textures the host resolved from the marked records. The elements stay resolved while +/// draws read the view, a rewritten record gets its new texture once the view is compared again, and a heap that grows +/// past its run keeps the elements it had. +/// +public sealed class BindlessHeapSceneTests(ITestOutputHelper output) : SceneTestBase(output) +{ + // MetalBindlessImageTests' waterfall (wave64): per lane, the key (<< 4) at +0x14000 + lane * 4 of the V# at block + 0x20, + // s_buffer_load_dwordx8 of the T# at key * 32 through the table V# at block + 0x10, image_sample_l at + // (0.5, 0.5, layer 1, lod 0) dim:2D_ARRAY with the S# at block + 0x30, the texel stored at lane * 16. + private static readonly uint[] Program = + [ + 0xF4080200, 0xFA000010, 0xF4080600, 0xFA000020, 0xF4080700, 0xFA000030, 0xBF8CC07F, 0x34020082, + 0x4A0202FF, 0x00014000, 0x34060084, 0xE0301000, 0x80060201, 0xBF8C3F70, 0x2C160484, 0x7E0802F0, + 0x7E0A02F0, 0x7E0C02F2, 0x7E0E0280, 0xBE86047E, 0x7E260281, 0x7EC8050B, 0xBE94047E, 0x7DA41664, + 0x8F648564, 0x7E260280, 0xF42C0304, 0xC8000000, 0xBF8CC07F, 0xF0900F28, 0x00E31404, 0xBEFE0414, + 0x7DAA2680, 0xBF89FFF3, 0xBEFE0406, 0xBF8C3F70, 0xE0781000, 0x80061403, 0xBF810000, + ]; + + // The T# from the block (s_load_dwordx8 s[12:19] at +0x40), the S# from the table at key * 16 + // (s_lshl_b32 s100, s100, 4; s_buffer_load_dwordx4 s[28:31], s[8:11], s100): a heap sampler record. + private static readonly uint[] SamplerProgram = Patch(Program, (4, 0xF40C0300), (5, 0xFA000040), (24, 0x8F648464), (26, 0xF4280704), (27, 0xC8000000)); + + private static uint[] Patch(uint[] words, params (int Index, uint Word)[] patches) + { + var patched = words.ToArray(); + foreach (var (index, word) in patches) + patched[index] = word; + return patched; + } + + private const int Lanes = 64; + private const uint KeyOffset = 0x14000; + private const uint RecordBytes = 32; + private const uint Rgba8 = 56; + private const uint Type2DArray = 13; + // Far enough apart that no texture's range (a linear layer is padded) reaches the next one. + private const int TextureBytes = 0x10000; + + private sealed class Heap + { + public ulong Block; + public ulong Table; + public ulong Output; + public ulong[] Textures = []; + } + + // Texture t is one colour in every texel of both layers, so the read does not depend on the layer layout. + private static uint Colour(int texture) => 0xFF000000u | ((uint)(7 + 3 * texture) << 16) | ((uint)(200 - texture) << 8) | (uint)(16 * texture + 1); + + private static float[] Expected(int texture) + { + var colour = Colour(texture); + return [(colour & 0xFF) / 255f, ((colour >> 8) & 0xFF) / 255f, ((colour >> 16) & 0xFF) / 255f, (colour >> 24) / 255f]; + } + + private static Heap Build(SceneRig rig, int textures, int records, int tableRecords) + { + var heap = new Heap + { + Block = rig.Memory.Allocate(0x100), + Table = rig.Memory.Allocate((ulong)tableRecords * RecordBytes), + Output = rig.Memory.Allocate(KeyOffset + Lanes * 4), + Textures = new ulong[textures], + }; + + for (var texture = 0; texture < textures; texture++) + { + heap.Textures[texture] = rig.Memory.Allocate(TextureBytes, TextureBytes); + rig.Memory.Write(heap.Textures[texture], Enumerable.Repeat(Colour(texture), TextureBytes / 4).ToArray()); + } + + rig.Memory.Write(heap.Table, new byte[tableRecords * RecordBytes]); + for (var record = 0; record < tableRecords; record++) + { + WriteRecord(rig, heap, record, record % textures); + } + + SetRecords(rig, heap, records); + rig.Memory.Write(heap.Block + 0x20, [Descriptors.Lo(heap.Output), Descriptors.Hi(heap.Output) & 0xFFFF, KeyOffset + Lanes * 4, 0x00038FAC]); + rig.Memory.Write(heap.Block + 0x30, Descriptors.Sampler()); + return heap; + } + + // The table V#: records * 32 bytes of T#s. + private static void SetRecords(SceneRig rig, Heap heap, int records) => + rig.Memory.Write(heap.Block + 0x10, + [Descriptors.Lo(heap.Table), Descriptors.Hi(heap.Table) & 0xFFFF, (uint)records * RecordBytes, 0x00038FAC]); + + private static void WriteRecord(SceneRig rig, Heap heap, int record, int texture) => + rig.Memory.Write(heap.Table + (ulong)record * RecordBytes, + Descriptors.Texture(heap.Textures[texture], Rgba8, 1, 1, type: Type2DArray, depthOrLastLayer: 1)); + + // One dispatch of a wave whose lane l reads record keys[l]; the four result words of each lane, as floats. + private static float[][] Pass(SceneRig rig, Heap heap, int[] keys, uint[]? program = null) + { + rig.Memory.Write(heap.Output, new uint[Lanes * 4]); + // The program reads each key shifted left by four (v_lshrrev_b32 v11, 4, v2). + rig.Memory.Write(heap.Output + KeyOffset, keys.Select(key => (uint)key << 4).ToArray()); + rig.Submit(rig.Dispatch(new ScenePm4(), program ?? Program, [Descriptors.Lo(heap.Block), Descriptors.Hi(heap.Block)], 1, threadsX: Lanes)); + var words = rig.Read(heap.Output, Lanes * 4); + return Enumerable.Range(0, Lanes).Select(lane => words.AsSpan(lane * 4, 4).ToArray()).ToArray(); + } + + private static void AssertTexel(float[] actual, float[] expected, string what) + { + for (var channel = 0; channel < 4; channel++) + { + Assert.True(MathF.Abs(actual[channel] - expected[channel]) <= 0.5f / 255f, + $"{what}: got ({string.Join(", ", actual)}) expected ({string.Join(", ", expected)})"); + } + } + + private static readonly float[] Zero = [0, 0, 0, 0]; + + [Fact] + public void TheFirstDispatchMarksAndALaterOneReadsTheTextureOfEachRecord() + { + using var rig = CreateRig(); + if (rig is null) return; + Assert.True(rig.Host.SupportsBindlessHeap); + const int textures = 8; + var heap = Build(rig, textures, records: 16, tableRecords: 16); + var keys = Enumerable.Range(0, Lanes).Select(lane => lane * 5 % 16).ToArray(); + + // Nothing is resolved before the marks of a completed dispatch come back: every lane reads the null element. + var first = Pass(rig, heap, keys); + for (var lane = 0; lane < Lanes; lane++) + { + AssertTexel(first[lane], Zero, $"first pass lane {lane} key {keys[lane]}"); + } + + Assert.Equal(0, rig.Host.HeapResolvedEntries); + var second = Pass(rig, heap, keys); + for (var lane = 0; lane < Lanes; lane++) + { + AssertTexel(second[lane], Expected(keys[lane] % textures), $"second pass lane {lane} key {keys[lane]}"); + } + + // Each of the 16 records was resolved (a record whose image a later record's lookup changed is resolved again + // once), and a dispatch that reads the same records resolves nothing more. + var resolved = rig.Host.HeapResolvedEntries; + Assert.InRange(resolved, 16, 32); + _ = Pass(rig, heap, keys); + Assert.Equal(resolved, rig.Host.HeapResolvedEntries); + // A key past the view reads null, and marks nothing. + var past = Pass(rig, heap, Enumerable.Range(0, Lanes).Select(lane => lane % 2 == 0 ? 16 + lane : lane % 16).ToArray()); + for (var lane = 0; lane < Lanes; lane++) + { + AssertTexel(past[lane], lane % 2 == 0 ? Zero : Expected(lane % 16 % textures), $"past pass lane {lane}"); + } + } + + [Fact] + public void ResolvedElementsStayAcrossDispatchesAndARewrittenRecordTakesItsNewTexture() + { + using var rig = CreateRig(); + if (rig is null) return; + const int textures = 4; + var heap = Build(rig, textures, records: 8, tableRecords: 8); + var lowKeys = Enumerable.Range(0, Lanes).Select(lane => lane % 4).ToArray(); + var highKeys = Enumerable.Range(0, Lanes).Select(lane => 4 + lane % 4).ToArray(); + _ = Pass(rig, heap, lowKeys); + _ = Pass(rig, heap, highKeys); + var resolved = rig.Host.HeapResolvedEntries; + + // Each set keeps its elements while the other is read: no null read, nothing resolved again. + for (var round = 0; round < 3; round++) + { + foreach (var keys in new[] { lowKeys, highKeys }) + { + var result = Pass(rig, heap, keys); + for (var lane = 0; lane < Lanes; lane++) + { + AssertTexel(result[lane], Expected(keys[lane] % textures), $"round {round} lane {lane} key {keys[lane]}"); + } + } + } + + Assert.Equal(resolved + 4, rig.Host.HeapResolvedEntries); + + // Record 1 now names texture 3: the view's records are compared again after a few submissions, and the lane that + // reads record 1 reads texture 3 from then on. + WriteRecord(rig, heap, 1, 3); + float[][] last = []; + for (var pass = 0; pass < 20; pass++) + { + last = Pass(rig, heap, lowKeys); + } + + for (var lane = 0; lane < Lanes; lane++) + { + AssertTexel(last[lane], Expected(lowKeys[lane] == 1 ? 3 : lowKeys[lane] % textures), $"rewritten lane {lane} key {lowKeys[lane]}"); + } + } + + [Fact] + public void AHeapThatGrowsPastItsRunKeepsTheElementsItHad() + { + using var rig = CreateRig(); + if (rig is null) return; + const int textures = 8; + var heap = Build(rig, textures, records: 8, tableRecords: 32); + var oldKeys = Enumerable.Range(0, Lanes).Select(lane => lane % 8).ToArray(); + _ = Pass(rig, heap, oldKeys); + _ = Pass(rig, heap, oldKeys); + + // The guest streams more records into the heap: the view outgrows its run and takes a larger one. The grown V# is + // in a new resource block (the scene's memory has no write tracking, so the old block would be read as before). + var block = rig.Memory.Allocate(0x100); + rig.Memory.Write(block, rig.Memory.ReadRaw(heap.Block, 0x100)); + heap.Block = block; + SetRecords(rig, heap, 32); + var keys = Enumerable.Range(0, Lanes).Select(lane => lane % 2 == 0 ? lane % 8 : 8 + lane % 24).ToArray(); + var grown = Pass(rig, heap, keys); + for (var lane = 0; lane < Lanes; lane++) + { + // The records the old run held read at once; the new ones read null until their marks come back. + AssertTexel(grown[lane], keys[lane] < 8 ? Expected(keys[lane] % textures) : Zero, $"grown pass lane {lane} key {keys[lane]}"); + } + + var later = Pass(rig, heap, keys); + for (var lane = 0; lane < Lanes; lane++) + { + AssertTexel(later[lane], Expected(keys[lane] % textures), $"later pass lane {lane} key {keys[lane]}"); + } + } + + [Fact] + public void AHeapSamplerRecordFiltersWithTheSamplerItNames() + { + using var rig = CreateRig(); + if (rig is null) return; + // One 2x1 texture (texel 0 colour 0, texel 1 colour 1, every row of both layers) and a table of S#s: even records + // point-sample, odd ones filter. At u = 0.5 a point sample reads texel 1 and a bilinear one their average. + var heap = Build(rig, textures: 1, records: 1, tableRecords: 1); + var texture = rig.Memory.Allocate(TextureBytes, TextureBytes); + var rows = new uint[TextureBytes / 4]; + for (var row = 0; row < rows.Length; row += 64) + { + rows[row] = Colour(0); + rows[row + 1] = Colour(1); + } + + rig.Memory.Write(texture, rows); + rig.Memory.Write(heap.Block + 0x40, Descriptors.Texture(texture, Rgba8, 2, 1, type: Type2DArray, depthOrLastLayer: 1)); + const int samplers = 8; + var table = rig.Memory.Allocate(samplers * 16); + for (var record = 0; record < samplers; record++) + { + var filter = (uint)(record & 1); + rig.Memory.Write(table + (ulong)record * 16, Descriptors.Sampler(magFilter: filter, minFilter: filter)); + } + + rig.Memory.Write(heap.Block + 0x10, [Descriptors.Lo(table), Descriptors.Hi(table) & 0xFFFF, samplers * 16, 0x00038FAC]); + var keys = Enumerable.Range(0, Lanes).Select(lane => lane * 3 % samplers).ToArray(); + _ = Pass(rig, heap, keys, SamplerProgram); + var result = Pass(rig, heap, keys, SamplerProgram); + var point = Expected(1); + var linear = Expected(0).Zip(Expected(1), (a, b) => (a + b) / 2).ToArray(); + for (var lane = 0; lane < Lanes; lane++) + { + AssertTexel(result[lane], keys[lane] % 2 == 0 ? point : linear, $"lane {lane} sampler record {keys[lane]}"); + } + } +} From 93ba8888bb0e4f2447fce5af5695b159fdca8dbc Mon Sep 17 00:00:00 2001 From: kuba Date: Fri, 20 Nov 2026 01:24:04 +0000 Subject: [PATCH 095/134] [Tests] Dispose a compile gate after the rig whose compiler threads wait on it Five tests declared their ManualResetEventSlim gate after the rig, so it was disposed first. A compiler thread that reached Gate.Wait() after that threw ObjectDisposedException outside any handler and ended the test host (abort on "SharpEmu Metal v2 pipeline compile N", four times on 2026-11-19/20 under a load average of 40-110, when a thread could be a whole test late). The gate is now declared before the rig, so the host joins its compiler threads before the gate goes. The gate is a test hook; no shipped path sets one. --- .../MetalAsyncPipelineTests.cs | 16 ++++++++++++---- .../MetalGraphicsWaitOffCacheTests.cs | 4 +++- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalAsyncPipelineTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalAsyncPipelineTests.cs index ce3c55479..7198c7b71 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalAsyncPipelineTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalAsyncPipelineTests.cs @@ -190,11 +190,13 @@ public void ATargetIsRebuiltEveryFrameOnlyWhenEachOfTheLastFramesRebuiltIt() [Fact] public void ADrawIntoATargetNotRebuiltEveryFrameWaitsForItsPipeline() { + // Declared before the rig, so it is disposed after it: a compiler thread may still reach this gate until the + // rig's host has joined its threads, and waiting on a disposed gate throws on that thread and ends the process. + using var gate = new ManualResetEventSlim(false); using var rig = CreateRig(); if (rig is null) return; const uint size = 16; rig.Host.AsynchronousGraphics = true; - using var gate = new ManualResetEventSlim(false); rig.Host.PipelineCompiler.Gate = gate; var target = rig.ColorTarget(size, size); var state = new SceneState(size, size).ColorTarget(0, target, size, size); @@ -325,6 +327,9 @@ private static void StoreWhileADrawWaitsForItsLibraryCompile(SceneRig rig, bool [Fact] public void InWideModeADrawIntoATargetDrawnEveryFrameIsLeftOutWhileItsPipelineCompiles() { + // Declared before the rig, so it is disposed after it: a compiler thread may still reach this gate until the + // rig's host has joined its threads, and waiting on a disposed gate throws on that thread and ends the process. + using var gate = new ManualResetEventSlim(false); using var rig = CreateRig(); if (rig is null) return; const uint size = 16; @@ -349,7 +354,6 @@ uint Frame(bool green) Assert.Equal(red, Frame(green: false)); } - using var gate = new ManualResetEventSlim(false); rig.Host.PipelineCompiler.Gate = gate; Assert.Equal(red, Frame(green: true)); Assert.Equal(1, rig.Host.CompilingDrawCounters.Skipped); @@ -392,6 +396,9 @@ public void InWideModeADepthTargetIsCountedWhenEachFrameClearsItsDepth(bool wide [Fact] public void WithoutWideModeATargetOnlyDrawnEveryFrameWaitsForThePipeline() { + // Declared before the rig, so it is disposed after it: a compiler thread may still reach this gate until the + // rig's host has joined its threads, and waiting on a disposed gate throws on that thread and ends the process. + using var gate = new ManualResetEventSlim(false); using var rig = CreateRig(); if (rig is null) return; const uint size = 16; @@ -405,7 +412,6 @@ public void WithoutWideModeATargetOnlyDrawnEveryFrameWaitsForThePipeline() rig.Submit(rig.DrawMesh(new ScenePm4(), Target(), SceneDraws.Quad(0.5f, 1, 0, 0))); } - using var gate = new ManualResetEventSlim(false); rig.Host.PipelineCompiler.Gate = gate; var additive = Target(); additive.Context[Cx.CbBlend0Control] = 1u | (1u << 8) | (1u << 16) | (1u << 30); @@ -422,6 +428,9 @@ public void WithoutWideModeATargetOnlyDrawnEveryFrameWaitsForThePipeline() [Fact] public void ADispatchSuspendedOnItsPipelineKeepsItsModulesThroughATrimAndStoresOnceReady() { + // Declared before the rig, so it is disposed after it: a compiler thread may still reach this gate until the + // rig's host has joined its threads, and waiting on a disposed gate throws on that thread and ends the process. + using var gate = new ManualResetEventSlim(false); using var rig = CreateRig(); if (rig is null) return; if (!rig.Host.SupportsPipelineSuspend) @@ -432,7 +441,6 @@ public void ADispatchSuspendedOnItsPipelineKeepsItsModulesThroughATrimAndStoresO rig.Host.ShaderCacheLimits = MetalShaderCacheLimits.Unbounded; const uint groups = 4; - using var gate = new ManualResetEventSlim(false); rig.Host.PipelineCompiler.Gate = gate; var buffer = rig.Memory.Allocate(groups * 64 * 4, 256); rig.Enqueue(rig.Dispatch(new ScenePm4(), ScenePrograms.StoreGlobalId, Descriptors.Buffer(buffer, 4, groups * 64, format: 20), groups).ToArray()); diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalGraphicsWaitOffCacheTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalGraphicsWaitOffCacheTests.cs index db3eb25eb..72d7b8e90 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalGraphicsWaitOffCacheTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalGraphicsWaitOffCacheTests.cs @@ -26,11 +26,13 @@ public sealed class MetalGraphicsWaitOffCacheTests(ITestOutputHelper output) public void ADrawThatWaitsSharesTheCompileAndTheReaskTakesIt(bool compilerThreadRuns) { if (!RequireDevice()) return; + // Declared before the rig, so it is disposed after it: a compiler thread may still reach this gate until the + // rig's host has joined its threads, and waiting on a disposed gate throws on that thread and ends the process. + using var gate = new ManualResetEventSlim(false); using var rig = new MetalPassRig(Device.Value, 1024 * 1024); var host = rig.Host; host.AsynchronousGraphics = true; Assert.True(((IShaderPipelineHost)host).WaitsForGraphicsPipelines); - using var gate = new ManualResetEventSlim(false); host.PipelineCompiler.Gate = gate; _ = host.PipelineCompiler.TakeCounters(); From 7b7357562b569115d016e73802b34aa24473e0f7 Mon Sep 17 00:00:00 2001 From: kuba Date: Fri, 20 Nov 2026 01:31:08 +0000 Subject: [PATCH 096/134] [GPU] Share BindlessHeapViewTable with Metal as a public contract The Metal heap host keeps its views in the shared BindlessHeapViewTable. The previous commit gave SharpEmu.Gpu.Metal the internals of SharpEmu.Libs to reach it, but ExtractedPackageContractTests allows no new friend assemblies: extracted backends use explicit public contracts. The table and its Region are now public, and the friend entry is gone. --- src/SharpEmu.Libs/SharpEmu.Libs.csproj | 2 -- src/SharpEmu.Libs/VideoOut/BindlessHeapViewTable.cs | 5 +++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/SharpEmu.Libs/SharpEmu.Libs.csproj b/src/SharpEmu.Libs/SharpEmu.Libs.csproj index ce33b0fa5..95bdaad2e 100644 --- a/src/SharpEmu.Libs/SharpEmu.Libs.csproj +++ b/src/SharpEmu.Libs/SharpEmu.Libs.csproj @@ -29,8 +29,6 @@ SPDX-License-Identifier: GPL-2.0-or-later - - diff --git a/src/SharpEmu.Libs/VideoOut/BindlessHeapViewTable.cs b/src/SharpEmu.Libs/VideoOut/BindlessHeapViewTable.cs index b97a41ed6..97db849ce 100644 --- a/src/SharpEmu.Libs/VideoOut/BindlessHeapViewTable.cs +++ b/src/SharpEmu.Libs/VideoOut/BindlessHeapViewTable.cs @@ -12,9 +12,10 @@ namespace SharpEmu.Libs.VideoOut; // Otherwise it takes free elements, then the elements of the views no pending command reads, least recently used first, // and at last shares the run of a view of its shape that is still read, as one heap that moved (a title's whole texture // heap, kept in two copies, is larger than half of set 1). -internal sealed class BindlessHeapViewTable(uint capacity) +// Public: the Vulkan and Metal backends both keep their heap views in it. +public sealed class BindlessHeapViewTable(uint capacity) { - internal sealed class Region + public sealed class Region { // The heap whose records the run's elements hold now. public required BindlessHeapDescriptor Heap { get; set; } From ca4b60a6e50ade7f2a3f9d941487b8b0845011b8 Mon Sep 17 00:00:00 2001 From: kuba Date: Fri, 20 Nov 2026 01:32:45 +0000 Subject: [PATCH 097/134] [Metal] Keep translated shaders in the game's translation disk cache Upstream keeps each game's translated shaders (TranslationDiskCache) and scalar graphs (ShaderAnalysisCache) on disk beside its pipeline cache; only the Vulkan presenter named the folders and only Vulkan rebuilt a shader from a payload, so on macOS every session translated every shader again and the graphs went to the one folder all games share. The Metal payload is the whole translation, not the dump text: Gen5MslShaderPayload writes the source and every field of Gen5MslShader and the records it holds, behind the stage and hash of the request. IGuestCompiledShader.CachePayload (default: Payload, so Vulkan is unchanged) is what the cache stores, and a request-taking CreateCachedShader overload (default: the old one) lets the Metal backend refuse a payload made for another request and rebuild the shader exactly as a translation does, request included, so its source is still dropped after the library build and translated again on demand. MetalTranslationCache opens both folders under pipeline_cache//metal-v2 where the presenter starts (the GPU process with the split on), with a stamp of the prewarm stamp, the MSL translator and Metal backend builds and the payload format. A rejected entry is now counted and the first one logged. --- src/SharpEmu.Libs/Gpu/IGuestCompiledShader.cs | 6 + src/SharpEmu.Libs/Gpu/IGuestGpuBackend.cs | 5 + .../Gpu/Pipelines/TranslationDiskCache.cs | 46 ++- src/SharpEmu.Libs/SharpEmu.Libs.csproj | 2 + .../Gen5MslArgumentLayout.cs | 2 +- .../Gen5MslShaderPayload.cs | 315 ++++++++++++++++++ .../Resources/ScalarGraphDiskCache.cs | 4 +- .../MetalCompiledGuestShader.cs | 42 +++ .../V2/MetalShaderPrewarm.cs | 2 +- .../V2/MetalTranslationCache.cs | 50 +++ .../SharpEmu.Gpu.Metal/V2/MetalV2Backend.cs | 6 + .../SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs | 2 + 12 files changed, 465 insertions(+), 17 deletions(-) create mode 100644 src/SharpEmu.ShaderCompiler.Metal/Gen5MslShaderPayload.cs create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalTranslationCache.cs diff --git a/src/SharpEmu.Libs/Gpu/IGuestCompiledShader.cs b/src/SharpEmu.Libs/Gpu/IGuestCompiledShader.cs index 155e31474..3707e08ff 100644 --- a/src/SharpEmu.Libs/Gpu/IGuestCompiledShader.cs +++ b/src/SharpEmu.Libs/Gpu/IGuestCompiledShader.cs @@ -14,6 +14,12 @@ public interface IGuestCompiledShader byte[] Payload { get; } uint? InputLocationMask => null; + /// <summary>What the translation disk cache keeps of this shader (TranslationDiskCache), and what the backend's + /// <see cref="IGuestGpuBackend.CreateCachedShader(byte[], uint?, ShaderCompiler.ShaderCompileRequest)"/> builds it + /// again from: the payload, unless the payload alone does not make the shader (Metal's is the source text without + /// the reflection the host reads).</summary> + byte[] CachePayload => Payload; + /// <summary>The words the flattened resource table bound with this module must have: a /// host binds a shorter table zero-padded to it.</summary> uint FlattenedTableMinimumWords => 0; diff --git a/src/SharpEmu.Libs/Gpu/IGuestGpuBackend.cs b/src/SharpEmu.Libs/Gpu/IGuestGpuBackend.cs index 2c6ea04b4..938da1594 100644 --- a/src/SharpEmu.Libs/Gpu/IGuestGpuBackend.cs +++ b/src/SharpEmu.Libs/Gpu/IGuestGpuBackend.cs @@ -53,6 +53,11 @@ public interface IGuestGpuBackend // The shader of a translation the translation disk cache kept (TranslationDiskCache); null when the backend keeps none. IGuestCompiledShader? CreateCachedShader(byte[] payload, uint? inputLocationMask) => null; + // The same for the request the translation is taken for: a backend whose payload names the request it was made from + // refuses (null) one made for another. A cache hit gives the shader a translation of request would give. + IGuestCompiledShader? CreateCachedShader(byte[] payload, uint? inputLocationMask, ShaderCompileRequest request) => + CreateCachedShader(payload, inputLocationMask); + // The vertex stage a tessellated pipeline requires and the control stage that feeds the guest's hull factors to the tessellator. (IGuestCompiledShader Vertex, IGuestCompiledShader Control) CompileTessellationBridge( SharpEmu.ShaderCompiler.Resources.BindingLayout layout, Gen5TessellationDomain domain) => diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/TranslationDiskCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/TranslationDiskCache.cs index 30dbbae65..2509d5573 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/TranslationDiskCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/TranslationDiskCache.cs @@ -88,6 +88,7 @@ private static readonly (string Name, string Value)[] Variables = Environment.Ge private static volatile string? _stamp; private static long _countedBytes = -1; private static int _reportedFailure; + private static long _rejectedEntries; // The running game's folder, beside its pipeline cache, and the device's translation stamp (the prewarm stamp); null stops. // Entries go to this build's folder inside it. @@ -100,6 +101,10 @@ public static void UseGameFolder(string? folder, string? stamp) internal static string? Folder => _folder; + // Entries that were on disk under their key and were not taken (damaged, another format, or refused by the backend); + // each is translated again and its entry replaced. + internal static long RejectedEntries => Interlocked.Read(ref _rejectedEntries); + // This build's folder, marked as used now. Other builds' folders but the newest KeptBuilds - 1 are deleted, and so are the // flat entries of the first layout. private static string UseBuildFolder(string gameFolder, string stamp) @@ -248,7 +253,7 @@ public static bool TryTranslate(IGuestGpuBackend compiler, ShaderCompileRequest return compiler.TryCompileProgram(request, out compiled, out error); } - var cached = TryLoad(key, compiler); + var cached = TryLoad(key, compiler, request); if (cached is not null) { compiled = cached; @@ -265,8 +270,8 @@ public static bool TryTranslate(IGuestGpuBackend compiler, ShaderCompileRequest return true; } - // The stored program for key as the backend's shader; null on a miss or a damaged entry. - internal static IGuestCompiledShader? TryLoad(string key, IGuestGpuBackend backend) + // The stored program for key as the backend's shader (for request, when given); null on a miss or a damaged entry. + internal static IGuestCompiledShader? TryLoad(string key, IGuestGpuBackend backend, ShaderCompileRequest? request = null) { if (_folder is not { } folder) { @@ -285,13 +290,13 @@ public static bool TryTranslate(IGuestGpuBackend compiler, ShaderCompileRequest if (file.Length is <= 32 or > MaxEntryBytes || !CryptographicOperations.FixedTimeEquals(file.AsSpan(0, 32), SHA256.HashData(file.AsSpan(32)))) { - return null; + return Rejected(key, "size or checksum"); } using var reader = new BinaryReader(Inflate(file, 32)); if (reader.ReadInt32() != Version || reader.ReadString() != key) { - return null; + return Rejected(key, "version or key"); } uint? mask = reader.ReadBoolean() ? reader.ReadUInt32() : null; @@ -299,23 +304,37 @@ public static bool TryTranslate(IGuestGpuBackend compiler, ShaderCompileRequest var payload = reader.ReadBytes(payloadLength); if (payload.Length != payloadLength) { - return null; + return Rejected(key, "short payload"); } - var shader = backend.CreateCachedShader(payload, mask); - if (shader is not null) + var shader = request is null + ? backend.CreateCachedShader(payload, mask) + : backend.CreateCachedShader(payload, mask, request); + if (shader is null) { - MarkUsed(path); + return Rejected(key, $"the {backend.BackendName} backend refused the payload"); } + MarkUsed(path); return shader; } - catch (Exception) + catch (Exception error) { - return null; + return Rejected(key, $"{error.GetType().Name}: {error.Message}"); } } + // A rejected entry is a miss: counted, and the first one of the process logged with its reason. + private static IGuestCompiledShader? Rejected(string key, string reason) + { + if (Interlocked.Increment(ref _rejectedEntries) == 1) + { + Console.Error.WriteLine($"[PERF][TRANSLATION_CACHE] entry {key[..Math.Min(16, key.Length)]} not taken ({reason}); translating again."); + } + + return null; + } + internal static void Store(string key, IGuestCompiledShader shader) { if (_folder is not { } folder) @@ -332,8 +351,9 @@ internal static void Store(string key, IGuestCompiledShader shader) writer.Write(key); writer.Write(shader.InputLocationMask.HasValue); if (shader.InputLocationMask is { } mask) writer.Write(mask); - writer.Write(shader.Payload.Length); - writer.Write(shader.Payload); + var payload = shader.CachePayload; + writer.Write(payload.Length); + writer.Write(payload); } using var compressed = new MemoryStream(); diff --git a/src/SharpEmu.Libs/SharpEmu.Libs.csproj b/src/SharpEmu.Libs/SharpEmu.Libs.csproj index 95bdaad2e..e6a23e2ec 100644 --- a/src/SharpEmu.Libs/SharpEmu.Libs.csproj +++ b/src/SharpEmu.Libs/SharpEmu.Libs.csproj @@ -29,6 +29,8 @@ SPDX-License-Identifier: GPL-2.0-or-later <InternalsVisibleTo Include="SharpEmu.Libs.Tests" /> <InternalsVisibleTo Include="SharpEmu.GnmMode" /> <InternalsVisibleTo Include="SharpEmu.Gpu.Vulkan" /> + <!-- The Metal host opens the translation disk cache for its game (TranslationDiskCache). --> + <InternalsVisibleTo Include="SharpEmu.Gpu.Metal" /> <!-- The runtime reads internal load-progress diagnostics. --> <InternalsVisibleTo Include="SharpEmu.Core" /> </ItemGroup> diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslArgumentLayout.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslArgumentLayout.cs index 6a5768ac5..0413804f4 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslArgumentLayout.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslArgumentLayout.cs @@ -70,7 +70,7 @@ public sealed class Gen5MslArgumentLayout private const uint ResourceBytes = 8; private const uint WordBytes = 4; - private Gen5MslArgumentLayout(IReadOnlyList<MslArgumentField> fields, uint byteSize) + internal Gen5MslArgumentLayout(IReadOnlyList<MslArgumentField> fields, uint byteSize) { Fields = fields; ByteSize = byteSize; diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslShaderPayload.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslShaderPayload.cs new file mode 100644 index 000000000..d8805f266 --- /dev/null +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslShaderPayload.cs @@ -0,0 +1,315 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Text; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.ShaderCompiler.Metal; + +/// <summary> +/// A translated MSL shader as bytes, for the translation disk cache (TranslationDiskCache): the source and every +/// field of <see cref="Gen5MslShader"/> and the records it holds, written one by one, behind the stage and hash of +/// the request it was translated from. Reading it back gives a record equal field by field to the translation, so a +/// later session builds the same libraries and pipelines from it. +/// </summary> +/// <remarks> +/// A field added to any of these records must be written here and the format version raised (the test that pins +/// the records' properties fails until it is). The version is part of the cache's stamp, so entries of an older +/// format are never read; a payload of another version, a short or overlong one, or one with an unknown enum value +/// is refused with the reason, never read as far as it goes. +/// </remarks> +public static class Gen5MslShaderPayload +{ + /// <summary>The layout version; part of the translation cache's stamp.</summary> + public const int FormatVersion = 1; + + // "MSLC", little-endian. + private const uint Magic = 0x434C534D; + + // Bounds a damaged count must not get past before the read fails on the length. + private const int MaxListCount = 1 << 20; + + /// <summary>The bytes of <paramref name="shader"/>, translated from a request of + /// <paramref name="requestStage"/> and <paramref name="requestHash"/>.</summary> + public static byte[] Write(Gen5MslShader shader, ShaderStage requestStage, ulong requestHash) + { + ArgumentNullException.ThrowIfNull(shader); + using var stream = new MemoryStream(shader.Source.Length + 1024); + using (var writer = new BinaryWriter(stream, Encoding.UTF8, leaveOpen: true)) + { + writer.Write(Magic); + writer.Write(FormatVersion); + writer.Write((byte)requestStage); + writer.Write(requestHash); + + writer.Write(shader.Source); + writer.Write(shader.EntryPoint); + writer.Write((int)shader.Stage); + writer.Write(shader.AttributeCount); + writer.Write(shader.ThreadgroupSizeX); + writer.Write(shader.ThreadgroupSizeY); + writer.Write(shader.ThreadgroupSizeZ); + WriteArgumentLayout(writer, shader.ArgumentLayout); + WriteMeshInfo(writer, shader.MeshInfo); + writer.Write(shader.WritesLayer); + writer.Write(shader.WritesViewportIndex); + writer.Write(shader.UsesPerVertexInputs); + writer.Write(shader.UsesMipStatisticsConstant); + writer.Write(shader.BufferWordConstants.Count); + foreach (var constant in shader.BufferWordConstants) + { + writer.Write(constant.Index); + writer.Write(constant.Dword); + } + + writer.Write(shader.ConstantPositions is not null); + if (shader.ConstantPositions is { } positions) + { + writer.Write(positions.Length); + // The bits, so a NaN keeps its payload. + foreach (var position in positions) writer.Write(BitConverter.SingleToUInt32Bits(position)); + } + + writer.Write(shader.CannotDiscard); + writer.Write(shader.ColorOutputMask); + writer.Write(shader.PersistentThreads); + WriteTessellation(writer, shader.Tessellation); + writer.Write(shader.FlattenedTableMinimumWords); + } + + return stream.ToArray(); + } + + /// <summary>Reads a payload <see cref="Write"/> made; false with the reason when it is not one, or is + /// damaged.</summary> + public static bool TryRead(byte[] payload, out Gen5MslShader shader, out ShaderStage requestStage, + out ulong requestHash, out string error) + { + ArgumentNullException.ThrowIfNull(payload); + shader = null!; + requestStage = ShaderStage.Unknown; + requestHash = 0; + try + { + using var stream = new MemoryStream(payload, writable: false); + using var reader = new BinaryReader(stream, Encoding.UTF8); + if (payload.Length < 8 || reader.ReadUInt32() != Magic) + { + error = "not an MSL shader payload"; + return false; + } + + var version = reader.ReadInt32(); + if (version != FormatVersion) + { + error = $"payload format {version}, this build reads {FormatVersion}"; + return false; + } + + requestStage = Defined((ShaderStage)reader.ReadByte()); + requestHash = reader.ReadUInt64(); + + var source = reader.ReadString(); + var entryPoint = reader.ReadString(); + var stage = Defined((Gen5MslStage)reader.ReadInt32()); + var attributeCount = reader.ReadUInt32(); + var threadgroupX = reader.ReadUInt32(); + var threadgroupY = reader.ReadUInt32(); + var threadgroupZ = reader.ReadUInt32(); + var argumentLayout = ReadArgumentLayout(reader); + var meshInfo = ReadMeshInfo(reader); + var writesLayer = reader.ReadBoolean(); + var writesViewportIndex = reader.ReadBoolean(); + var usesPerVertexInputs = reader.ReadBoolean(); + var usesMipStatisticsConstant = reader.ReadBoolean(); + var bufferWordConstants = new Gen5MslShader.BufferWordConstant[Count(reader)]; + for (var index = 0; index < bufferWordConstants.Length; index++) + { + bufferWordConstants[index] = new Gen5MslShader.BufferWordConstant(reader.ReadUInt32(), reader.ReadUInt32()); + } + + float[]? constantPositions = null; + if (reader.ReadBoolean()) + { + constantPositions = new float[Count(reader)]; + for (var index = 0; index < constantPositions.Length; index++) + { + constantPositions[index] = BitConverter.UInt32BitsToSingle(reader.ReadUInt32()); + } + } + + var cannotDiscard = reader.ReadBoolean(); + var colorOutputMask = reader.ReadUInt32(); + var persistentThreads = reader.ReadBoolean(); + var tessellation = ReadTessellation(reader); + var flattenedTableMinimumWords = reader.ReadUInt32(); + if (stream.Position != stream.Length) + { + error = $"{stream.Length - stream.Position} bytes past the end of the shader"; + return false; + } + + shader = new Gen5MslShader(source, entryPoint, stage, attributeCount, threadgroupX, threadgroupY, threadgroupZ, + argumentLayout, meshInfo, writesLayer, writesViewportIndex) + { + UsesPerVertexInputs = usesPerVertexInputs, + UsesMipStatisticsConstant = usesMipStatisticsConstant, + BufferWordConstants = bufferWordConstants, + ConstantPositions = constantPositions, + CannotDiscard = cannotDiscard, + ColorOutputMask = colorOutputMask, + PersistentThreads = persistentThreads, + Tessellation = tessellation, + FlattenedTableMinimumWords = flattenedTableMinimumWords, + }; + error = string.Empty; + return true; + } + catch (Exception exception) when (exception is EndOfStreamException or InvalidDataException or IOException or + DecoderFallbackException or ArgumentException or OverflowException) + { + shader = null!; + error = $"damaged payload: {exception.GetType().Name}: {exception.Message}"; + return false; + } + } + + private static void WriteArgumentLayout(BinaryWriter writer, Gen5MslArgumentLayout? layout) + { + writer.Write(layout is not null); + if (layout is null) + { + return; + } + + writer.Write(layout.ByteSize); + writer.Write(layout.Fields.Count); + foreach (var field in layout.Fields) + { + writer.Write((uint)field.Kind); + writer.Write((int)field.FieldKind); + writer.Write(field.Name); + writer.Write(field.Count); + writer.Write(field.FirstId); + writer.Write(field.ByteOffset); + writer.Write(field.ByteSize); + } + } + + private static Gen5MslArgumentLayout? ReadArgumentLayout(BinaryReader reader) + { + if (!reader.ReadBoolean()) + { + return null; + } + + var byteSize = reader.ReadUInt32(); + var fields = new MslArgumentField[Count(reader)]; + for (var index = 0; index < fields.Length; index++) + { + fields[index] = new MslArgumentField( + (DescriptorBindingKind)reader.ReadUInt32(), + Defined((MslArgumentFieldKind)reader.ReadInt32()), + reader.ReadString(), + reader.ReadUInt32(), + reader.ReadUInt32(), + reader.ReadUInt32(), + reader.ReadUInt32()); + } + + return new Gen5MslArgumentLayout(fields, byteSize); + } + + private static void WriteMeshInfo(BinaryWriter writer, Gen5MslMeshInfo? mesh) + { + writer.Write(mesh is not null); + if (mesh is null) + { + return; + } + + writer.Write(mesh.ThreadsPerThreadgroup); + writer.Write(mesh.WavesPerThreadgroup); + writer.Write(mesh.MaxVertices); + writer.Write(mesh.MaxPrimitives); + writer.Write(mesh.VerticesPerPrimitive); + writer.Write((int)mesh.Topology); + writer.Write(mesh.ThreadgroupMemoryBytes); + writer.Write(mesh.DrawInfoBufferIndex); + writer.Write(mesh.IndexBufferIndex); + writer.Write(mesh.ReadsIndexBuffer); + writer.Write(mesh.GeometryVerticesOut); + writer.Write(mesh.NarrowWave64); + writer.Write(mesh.DeviceLds); + writer.Write(mesh.Wave64); + writer.Write(mesh.LdsBytes); + writer.Write(mesh.Amplified); + writer.Write(mesh.GeometryInputVertices); + writer.Write(mesh.GeometryInputPrimitives); + } + + private static Gen5MslMeshInfo? ReadMeshInfo(BinaryReader reader) => + !reader.ReadBoolean() + ? null + : new Gen5MslMeshInfo( + ThreadsPerThreadgroup: reader.ReadUInt32(), + WavesPerThreadgroup: reader.ReadUInt32(), + MaxVertices: reader.ReadUInt32(), + MaxPrimitives: reader.ReadUInt32(), + VerticesPerPrimitive: reader.ReadUInt32(), + Topology: Defined((Gen5MslMeshTopology)reader.ReadInt32()), + ThreadgroupMemoryBytes: reader.ReadUInt32(), + DrawInfoBufferIndex: reader.ReadUInt32(), + IndexBufferIndex: reader.ReadUInt32(), + ReadsIndexBuffer: reader.ReadBoolean(), + GeometryVerticesOut: reader.ReadUInt32(), + NarrowWave64: reader.ReadBoolean(), + DeviceLds: reader.ReadBoolean(), + Wave64: reader.ReadBoolean(), + LdsBytes: reader.ReadUInt32(), + Amplified: reader.ReadBoolean(), + GeometryInputVertices: reader.ReadUInt32(), + GeometryInputPrimitives: reader.ReadUInt32()); + + private static void WriteTessellation(BinaryWriter writer, Gen5TessellationLaunch? launch) + { + writer.Write(launch is not null); + if (launch is null) + { + return; + } + + writer.Write((byte)launch.Role); + writer.Write(launch.PatchesPerGroup); + writer.Write(launch.ControlPoints); + writer.Write(launch.OffchipBlockBytes); + writer.Write(launch.FactorBytesPerPatch); + writer.Write((byte)launch.Partition); + writer.Write(launch.OutputClockwise); + writer.Write(launch.MaxFactor); + writer.Write(launch.Quad); + } + + private static Gen5TessellationLaunch? ReadTessellation(BinaryReader reader) => + !reader.ReadBoolean() + ? null + : new Gen5TessellationLaunch( + Role: Defined((Gen5TessellationRole)reader.ReadByte()), + PatchesPerGroup: reader.ReadUInt32(), + ControlPoints: reader.ReadUInt32(), + OffchipBlockBytes: reader.ReadUInt32(), + FactorBytesPerPatch: reader.ReadUInt32(), + Partition: Defined((Gen5TessellationPartition)reader.ReadByte()), + OutputClockwise: reader.ReadBoolean(), + MaxFactor: reader.ReadUInt32(), + Quad: reader.ReadBoolean()); + + private static int Count(BinaryReader reader) + { + var count = reader.ReadInt32(); + return count is >= 0 and <= MaxListCount ? count : throw new InvalidDataException($"count {count} out of range"); + } + + private static T Defined<T>(T value) where T : struct, Enum => + Enum.IsDefined(value) ? value : throw new InvalidDataException($"{typeof(T).Name} {value} is not defined"); +} diff --git a/src/SharpEmu.ShaderCompiler/Resources/ScalarGraphDiskCache.cs b/src/SharpEmu.ShaderCompiler/Resources/ScalarGraphDiskCache.cs index 5fd63078d..c006c25b9 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ScalarGraphDiskCache.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ScalarGraphDiskCache.cs @@ -35,8 +35,8 @@ internal static class ScalarGraphDiskCache internal static void UseGameFolder(string folder) => _gameFolder = folder; - // A host that names no game folder (the Metal host does not yet) keeps the one folder every game shared before the - // per-game folders, at the cap it had then. + // A host that names no game folder (both hosts name one once their device is up) keeps the one folder every game + // shared before the per-game folders, at the cap it had then. private static readonly string SharedCachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SharpEmu", "shader-analysis"); private const long SharedMaxCacheBytes = 256L * 1024 * 1024; diff --git a/src/graphics/SharpEmu.Gpu.Metal/MetalCompiledGuestShader.cs b/src/graphics/SharpEmu.Gpu.Metal/MetalCompiledGuestShader.cs index 4654ddb24..d8186382c 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/MetalCompiledGuestShader.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/MetalCompiledGuestShader.cs @@ -48,6 +48,48 @@ internal sealed class MetalCompiledGuestShader(Gen5MslShader shader, ShaderCompi public string PayloadFileExtension => "msl"; + /// <summary>The source and every reflection field, behind its request's stage and hash + /// (<see cref="Gen5MslShaderPayload"/>): what the translation disk cache keeps, and + /// <see cref="FromCachePayload"/> reads back. A fixed shader has no translation to keep.</summary> + public byte[] CachePayload => _request is { } request + ? Gen5MslShaderPayload.Write(AcquireShader(), request.Stage, request.Hash) + : throw new InvalidOperationException("A shader without its request is not a translation the cache keeps."); + + private static long _cachePayloadsRefused; + + /// <summary>Cache payloads <see cref="FromCachePayload"/> refused in this process.</summary> + internal static long CachePayloadsRefused => Interlocked.Read(ref _cachePayloadsRefused); + + /// <summary> + /// The shader a cache payload holds, for the request it is taken for: the same shader a translation of + /// <paramref name="request"/> constructs, request included, so its source can be dropped and translated again + /// like a fresh one's. Null, counted and logged, when the payload is damaged, of another format, or was made + /// for another stage or program. + /// </summary> + internal static MetalCompiledGuestShader? FromCachePayload(byte[] payload, ShaderCompileRequest request) + { + string reason; + if (!Gen5MslShaderPayload.TryRead(payload, out var shader, out var stage, out var hash, out var error)) + { + reason = error; + } + else if (stage != request.Stage || hash != request.Hash) + { + reason = $"made for {stage} 0x{hash:X16}, taken for {request.Stage} 0x{request.Hash:X16}"; + } + else + { + return new MetalCompiledGuestShader(shader, request); + } + + if (Interlocked.Increment(ref _cachePayloadsRefused) <= 8) + { + Console.Error.WriteLine($"[METAL-V2][TRANSLATION_CACHE] cached shader for 0x{request.Hash:X16} refused: {reason}."); + } + + return null; + } + public uint FlattenedTableMinimumWords => Shader.FlattenedTableMinimumWords; /// <summary>XxHash3 of the UTF-8 <see cref="Payload"/>, computed once and kept.</summary> diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs index b04b58348..32e5865d0 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs @@ -820,7 +820,7 @@ private static void FlushProgress(ShaderPrewarmList list, string stamp) // The translators decide the MSL; the device and the OS decide what the driver's // compiler makes of it. - private static string Stamp(IGuestGpuBackend compiler, nint device) => + internal static string Stamp(IGuestGpuBackend compiler, nint device) => string.Join( '|', StampPart(typeof(Gen5ShaderTranslator)), diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalTranslationCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalTranslationCache.cs new file mode 100644 index 000000000..2f94cfa26 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalTranslationCache.cs @@ -0,0 +1,50 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Globalization; +using SharpEmu.Libs.Gpu; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.VideoOut; +using SharpEmu.Logging; +using SharpEmu.ShaderCompiler.Metal; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.Gpu.Metal.V2; + +/// <summary> +/// The game's two shader disk caches, beside the rest of its Metal shader data +/// (pipeline_cache/<title>/metal-v2, where the prewarm list and the binary archive live): the +/// translations (TranslationDiskCache, <c>translations/</c>), so a later session takes a program's MSL +/// and reflection from disk instead of translating it again, and the scalar graphs +/// (ShaderAnalysisCache, <c>analysis/</c>). Opened by the process that translates, where the +/// presenter starts: the GPU process with the split on, the one process with it off. +/// SHARPEMU_TRANSLATION_CACHE=0 turns the translations off; SHARPEMU_SHADER_ANALYSIS_CACHE_PATH +/// names another folder for the graphs ("0" turns them off). +/// </summary> +internal static class MetalTranslationCache +{ + /// <summary> + /// What the payload of a translation depends on beyond what TranslationDiskCache keys itself + /// (the builds of SharpEmu.ShaderCompiler and SharpEmu.Libs, the request, the SHARPEMU_ + /// switches): the prewarm stamp (the translators' code, the backend, the math mode, the + /// host's translation switches, the device and the OS), the build of the MSL translator (any + /// rebuild, as Vulkan keys on its SPIR-V translator's), the build of this assembly (the shader + /// type the payload is read into) and the payload's format. + /// </summary> + internal static string Stamp(IGuestGpuBackend compiler, nint device) => + string.Join( + '|', + MetalShaderPrewarm.Stamp(compiler, device), + typeof(Gen5MslTranslator).Module.ModuleVersionId.ToString("N"), + typeof(MetalTranslationCache).Module.ModuleVersionId.ToString("N"), + "payload=" + Gen5MslShaderPayload.FormatVersion.ToString(CultureInfo.InvariantCulture)); + + /// <summary>Points both caches at the running game's folders.</summary> + public static void Start(nint device) + { + var directory = SharpEmuPaths.UserPath( + "pipeline_cache", MetalShaderPrewarm.SanitizeTitleId(VideoOutBackendServices.GetApplicationTitleId()), "metal-v2"); + ShaderAnalysisCache.UseGameFolder(Path.Combine(directory, "analysis")); + TranslationDiskCache.UseGameFolder(Path.Combine(directory, "translations"), Stamp(GuestGpu.Current, device)); + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Backend.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Backend.cs index 3e5d54f36..44326ca25 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Backend.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Backend.cs @@ -55,6 +55,12 @@ public bool TryCompileProgram(ShaderCompileRequest request, out IGuestCompiledSh return true; } + // A translation the translation disk cache kept, for the request it is taken for; the payload names its request, + // so one made for another stage or program is a miss. Without the request (the two-argument form) nothing is + // taken: the shader could not be checked, nor drop its source and translate it again like a fresh one. + public IGuestCompiledShader? CreateCachedShader(byte[] payload, uint? inputLocationMask, ShaderCompileRequest request) => + MetalCompiledGuestShader.FromCachePayload(payload, request); + public IGuestCompiledShader GetDepthOnlyFragmentShader() => DepthOnlyFragmentShader; public void EnsureStarted(uint width, uint height) => MetalV2Presenter.EnsureStarted(width, height); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs index e53e53c6f..bc099f327 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Presenter.cs @@ -275,6 +275,8 @@ public static void EnsureStarted(uint width, uint height) _windowStarted = true; _requestedWidth = width; _requestedHeight = height; + // Before the prewarm and the game plan or translate a shader. + MetalTranslationCache.Start(_device); // Before the prewarm, whose libraries it may already hold. MetalBinaryArchive.Start(_device); MetalShaderPrewarm.Start(_device); From d3375c4c5666eb8c185a903f4c842907b25cc85b Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 01:39:06 +0000 Subject: [PATCH 098/134] [Tests] Cover the Metal translation cache payload, its sessions and its refusals Gen5MslShaderPayloadTests: translations of every stage (compute, wave64, persistent threads, vertex with constant positions, pixel with per-vertex inputs, primitive shaders, hull and domain, a storage image with a runtime swizzle) and a record with every field set read back field by field; the record types' properties are pinned so a new field must be written; every truncation, another format, trailing bytes and an undefined stage are refused with a reason. MetalTranslationCacheTests: a rebuilt shader is the translation with its request (payload, dump identity, the library key MetalBinaryArchive computes, source release and re-translation); a second session over the same folder takes every shader without calling the translator; another stamp misses; a truncated, corrupt, other-stage or other-program entry is a counted miss that translates again and is replaced. On the device: a rebuilt runtime-swizzle store writes the texel the translation writes, and a rebuilt shader builds its module and pipeline on the render host and drops its source. docs/macos/configuration.md: SHARPEMU_TRANSLATION_CACHE and SHARPEMU_SHADER_ANALYSIS_CACHE_PATH beside the binary-archive switches. --- docs/macos/configuration.md | 2 + src/SharpEmu.Libs/SharpEmu.Libs.csproj | 1 + .../MetalShaderSourceReleaseTests.cs | 21 ++ .../MetalTranslationCacheTests.cs | 272 ++++++++++++++++ .../Gen5MslLoadElisionTests.cs | 2 +- .../Gen5MslPixelInputTests.cs | 8 +- .../Gen5MslShaderPayloadTests.cs | 290 ++++++++++++++++++ .../Gen5MslTessellationLaunchTests.cs | 2 +- .../MetalRuntimeImageSwizzleExecutionTests.cs | 31 +- 9 files changed, 622 insertions(+), 7 deletions(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalTranslationCacheTests.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslShaderPayloadTests.cs diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index e03c29fa8..26b89eccf 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -75,6 +75,8 @@ them for measurements or to isolate a problem. | `SHARPEMU_METAL_MESHLETS` | on | `0` disables the meshlet cache. | | `SHARPEMU_METAL_V2_BINARY_ARCHIVE` | on | `0` disables the on-disk library and pipeline archives. | | `SHARPEMU_METAL_V2_BINARY_ARCHIVE_BUDGET_MB` | `8192` | Size bound of the archives on disk. | +| `SHARPEMU_TRANSLATION_CACHE` | on | `0` stops keeping translated shaders on disk. By default each translation (MSL and its reflection) is kept in `pipeline_cache/<title ID>/metal-v2/translations`, up to 8 GiB per game, and a later session of the same build takes it from there instead of translating the program again. A new build, translator switch, device or OS uses a new folder. | +| `SHARPEMU_SHADER_ANALYSIS_CACHE_PATH` | per game | Folder of the scalar-graph cache of shader planning. By default `pipeline_cache/<title ID>/metal-v2/analysis`; `0` turns the cache off. | | `SHARPEMU_METAL_V2_ASYNC_PIPELINES` | on | `0` builds pipeline states on the GPU worker thread. | | `SHARPEMU_METAL_V2_ASYNC_LIBRARIES` | on | `0` compiles each shader library on the thread that needs it, not on the compile pool. | | `SHARPEMU_METAL_V2_GRAPHICS_WAIT_OFF_CACHE` | on | A draw that cannot be left out while its pipeline compiles waits for the compile outside the shared pipeline cache's lock, so other draws' programs keep resolving. `0` builds the pipeline under the lock, as before. Only with `SHARPEMU_METAL_V2_ASYNC_GRAPHICS` on. | diff --git a/src/SharpEmu.Libs/SharpEmu.Libs.csproj b/src/SharpEmu.Libs/SharpEmu.Libs.csproj index e6a23e2ec..f495c4f7c 100644 --- a/src/SharpEmu.Libs/SharpEmu.Libs.csproj +++ b/src/SharpEmu.Libs/SharpEmu.Libs.csproj @@ -31,6 +31,7 @@ SPDX-License-Identifier: GPL-2.0-or-later <InternalsVisibleTo Include="SharpEmu.Gpu.Vulkan" /> <!-- The Metal host opens the translation disk cache for its game (TranslationDiskCache). --> <InternalsVisibleTo Include="SharpEmu.Gpu.Metal" /> + <InternalsVisibleTo Include="SharpEmu.Gpu.Metal.Tests" /> <!-- The runtime reads internal load-progress diagnostics. --> <InternalsVisibleTo Include="SharpEmu.Core" /> </ItemGroup> diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalShaderSourceReleaseTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalShaderSourceReleaseTests.cs index 0fd25afc1..ee858af1d 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalShaderSourceReleaseTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalShaderSourceReleaseTests.cs @@ -150,6 +150,27 @@ public void AModuleReleasedByTheShaderCacheBoundIsBuiltAgainFromItsRequest() Assert.Equal(expected, metal.PayloadHash); } + // A shader the translation disk cache rebuilt (MetalCompiledGuestShader.FromCachePayload) builds its library and + // pipeline as the translation does, drops its source like it, and translates its request again to the same text. + [Fact] + public void AShaderFromTheTranslationCacheBuildsItsModuleAndDropsItsSourceLikeATranslation() + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var request = Gen5ComputeFixtures.CreateComputeRequest(Gen5ComputeFixtures.ExecStore); + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var original, out var error), error); + var fresh = new MetalCompiledGuestShader(original, request); + var rebuilt = MetalCompiledGuestShader.FromCachePayload(fresh.CachePayload, request); + Assert.NotNull(rebuilt); + + var pipeline = Pipeline(rig.Host, rebuilt, 1); + + Assert.NotEqual(default, pipeline); + Assert.True(rebuilt.SourceReleased); + Assert.Equal(original.Source, rebuilt.AcquireShader().Source); + Assert.Equal(fresh.PayloadHash, rebuilt.PayloadHash); + } + [Theory] [InlineData(false)] [InlineData(true)] diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalTranslationCacheTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalTranslationCacheTests.cs new file mode 100644 index 000000000..bbd35985b --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalTranslationCacheTests.cs @@ -0,0 +1,272 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.HLE; +using SharpEmu.Libs.Gpu; +using SharpEmu.Libs.Gpu.GpuCommands; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Metal; +using SharpEmu.ShaderCompiler.Metal.Tests; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +/// <summary> +/// The translation disk cache on Metal: a session keeps each translation, and a later session over the same folder +/// takes every shader from it without the translator, as the shader a translation gives (reflection, request, the +/// library key the host computes). An entry that is damaged, of another build, or made for another request is a +/// counted miss that translates again. +/// </summary> +[Collection(MetalTranslationCacheCollection.Name)] +public sealed class MetalTranslationCacheTests : IDisposable +{ + private readonly string _directory = Path.Combine(Path.GetTempPath(), "SharpEmuTests", Guid.NewGuid().ToString("N")); + + public MetalTranslationCacheTests() => TranslationDiskCache.UseGameFolder(_directory, "metal-test-stamp"); + + public void Dispose() + { + TranslationDiskCache.UseGameFolder(null, null); + if (Directory.Exists(_directory)) + { + Directory.Delete(_directory, recursive: true); + } + } + + // Compute (plain, LDS, loop), vertex, pixel, and a storage image with a runtime swizzle. + private static IEnumerable<(string Name, ShaderCompileRequest Request)> Requests() + { + foreach (var fixture in new[] { Gen5ComputeFixtures.ExecStore, Gen5ComputeFixtures.Fmac, Gen5ComputeFixtures.Lds, Gen5ComputeFixtures.Loop }) + { + yield return ("compute-" + fixture.Name, Gen5ComputeFixtures.CreateComputeRequest(fixture)); + } + + yield return ("vertex", Gen5ComputeFixtures.RequestOrThrow( + Gen5ComputeFixtures.DecodeOrThrow(new Gen5ComputeFixture("vertex", Gen5ComputeFixtures.VertexWords, 0, 0)), ShaderStage.Vertex)); + yield return ("pixel", Gen5ComputeFixtures.RequestOrThrow( + Gen5ComputeFixtures.DecodeOrThrow(new Gen5ComputeFixture("pixel", Gen5ComputeFixtures.PixelWords, 0, 0)), ShaderStage.Pixel, + pixelOutputs: [new Gen5PixelOutputBinding(0, 0, Gen5PixelOutputKind.Float, default)])); + ShaderCompileRequest? image = null; + Assert.True(Gen5ImageFixtures.TryCompile("ImageStore", Gen5ImageFixtures.ImageType2D, out _, out var error, + unifiedFormat: 71, dstSelect: 0xF2E, addressValues: [1, 0], storeValues: [1, 2, 3, 4], runtimeImageSwizzles: true, + inspect: (request, _) => image = request), error); + Assert.Equal(1u, image!.Bindings.StorageImageSwizzleCount); + yield return ("image-runtime-swizzle", image); + } + + private static string Key(ShaderCompileRequest request) => + TranslationDiskCache.Key( + new ProgramKey(request.Stage, request.Hash, request.UserDataCount, (uint)request.Program.Instructions.Count, 0, []), + request.UserDataBase, new ResourceSpecialization(), 0, request) + ?? throw new InvalidOperationException($"No translation cache key for {request.Stage} 0x{request.Hash:X16}."); + + [Fact] + public void ARebuiltShaderIsTheTranslationWithItsRequest() + { + foreach (var (name, request) in Requests()) + { + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var translated, out var error), error); + var fresh = new MetalCompiledGuestShader(translated, request); + + var rebuilt = MetalCompiledGuestShader.FromCachePayload(fresh.CachePayload, request); + + Assert.NotNull(rebuilt); + AssertSameShader(fresh, rebuilt, name); + // The rebuilt shader keeps the request, so the host can drop its source and translate it again. + rebuilt.ReleaseSource(); + Assert.True(rebuilt.SourceReleased, name); + Assert.Equal(translated.Source, rebuilt.AcquireShader().Source); + } + } + + [Fact] + public void ASecondSessionTakesEveryShaderFromTheCacheWithoutTranslating() + { + var requests = Requests().ToArray(); + var first = new CountingBackend(); + var fresh = new Dictionary<string, MetalCompiledGuestShader>(); + foreach (var (name, request) in requests) + { + Assert.True(TranslationDiskCache.TryTranslate(first, request, Key(request), out var compiled, out var error), error); + fresh[name] = Assert.IsType<MetalCompiledGuestShader>(compiled); + } + + Assert.Equal(requests.Length, first.Translations); + Assert.Equal(requests.Length, Directory.GetFiles(TranslationDiskCache.Folder!, "*.spvc").Length); + + // The next session: the same folder and stamp, a new backend. + TranslationDiskCache.UseGameFolder(_directory, "metal-test-stamp"); + var second = new CountingBackend(); + var rejected = TranslationDiskCache.RejectedEntries; + foreach (var (name, request) in requests) + { + Assert.True(TranslationDiskCache.TryTranslate(second, request, Key(request), out var compiled, out var error), error); + AssertSameShader(fresh[name], Assert.IsType<MetalCompiledGuestShader>(compiled), name); + } + + Assert.Equal(0, second.Translations); + Assert.Equal(requests.Length, second.CachedShaders); + Assert.Equal(rejected, TranslationDiskCache.RejectedEntries); + } + + [Fact] + public void AnotherStampIsAMiss() + { + var (_, request) = Requests().First(); + Assert.True(TranslationDiskCache.TryTranslate(new CountingBackend(), request, Key(request), out _, out var error), error); + + TranslationDiskCache.UseGameFolder(_directory, "another-translator-build"); + var backend = new CountingBackend(); + Assert.True(TranslationDiskCache.TryTranslate(backend, request, Key(request), out _, out error), error); + + Assert.Equal(1, backend.Translations); + Assert.Equal(0, backend.CachedShaders); + } + + // A file cut short, a flipped byte, and an entry made for a request of another stage under this request's key: + // each is a counted miss, translated afresh, and its entry is replaced by the translation. + [Theory] + [InlineData("truncated")] + [InlineData("corrupt")] + [InlineData("other-stage")] + public void ADamagedOrForeignEntryIsACountedMissThatTranslatesAgain(string damage) + { + var requests = Requests().ToArray(); + var (_, request) = requests.First(entry => entry.Request.Stage == ShaderStage.Compute); + var key = Key(request); + var path = Path.Combine(TranslationDiskCache.Folder!, key + ".spvc"); + if (damage == "other-stage") + { + var (_, pixel) = requests.First(entry => entry.Request.Stage == ShaderStage.Pixel); + Assert.True(TranslationDiskCache.TryTranslate(new CountingBackend(), pixel, Key(pixel), out var other, out var otherError), otherError); + TranslationDiskCache.Store(key, other!); + } + else + { + Assert.True(TranslationDiskCache.TryTranslate(new CountingBackend(), request, key, out _, out var storeError), storeError); + var bytes = File.ReadAllBytes(path); + File.WriteAllBytes(path, damage == "truncated" ? bytes[..(bytes.Length / 2)] : Flip(bytes, bytes.Length - 3)); + } + + var rejected = TranslationDiskCache.RejectedEntries; + var refused = MetalCompiledGuestShader.CachePayloadsRefused; + var backend = new CountingBackend(); + + Assert.True(TranslationDiskCache.TryTranslate(backend, request, key, out var compiled, out var error), error); + + Assert.Equal(1, backend.Translations); + Assert.Equal(rejected + 1, TranslationDiskCache.RejectedEntries); + Assert.Equal(damage == "other-stage" ? refused + 1 : refused, MetalCompiledGuestShader.CachePayloadsRefused); + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var expected, out error), error); + Assert.Equal(expected.Source, Assert.IsType<MetalCompiledGuestShader>(compiled).AcquireShader().Source); + + // The translation replaced the entry: the next session takes it. + var next = new CountingBackend(); + Assert.True(TranslationDiskCache.TryTranslate(next, request, key, out _, out error), error); + Assert.Equal(0, next.Translations); + } + + // A payload for the right stage but another program (hash) is refused too. + [Fact] + public void APayloadOfAnotherProgramIsRefused() + { + // The fixtures share one hash: the other program is the same request under another hash. + var request = Gen5ComputeFixtures.CreateComputeRequest(Gen5ComputeFixtures.ExecStore); + var other = request.WithProgram(request.Program); + typeof(ShaderCompileRequest).GetField("<Hash>k__BackingField", + System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!.SetValue(other, request.Hash ^ 1); + Assert.NotEqual(request.Hash, other.Hash); + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var translated, out var error), error); + var payload = new MetalCompiledGuestShader(translated, request).CachePayload; + var refused = MetalCompiledGuestShader.CachePayloadsRefused; + + Assert.Null(MetalCompiledGuestShader.FromCachePayload(payload, other)); + Assert.Equal(refused + 1, MetalCompiledGuestShader.CachePayloadsRefused); + Assert.NotNull(MetalCompiledGuestShader.FromCachePayload(payload, request)); + } + + private static byte[] Flip(byte[] bytes, int index) + { + var copy = (byte[])bytes.Clone(); + copy[index] ^= 0x5A; + return copy; + } + + // The same shader the host reads: every reflection field (the payload writes all of them), the request, the dump + // payload and its identity, and the library key the host computes from the source and its options. + private static void AssertSameShader(MetalCompiledGuestShader fresh, MetalCompiledGuestShader rebuilt, string name) + { + var expected = fresh.AcquireShader(); + var actual = rebuilt.AcquireShader(); + Assert.NotSame(expected, actual); + Assert.Equal(fresh.CachePayload, rebuilt.CachePayload); + Assert.Equal(expected.Source, actual.Source); + Assert.Equal(expected.EntryPoint, actual.EntryPoint); + Assert.Equal(expected.Stage, actual.Stage); + Assert.Equal(expected.UsesPerVertexInputs, actual.UsesPerVertexInputs); + Assert.Equal(expected.FlattenedTableMinimumWords, rebuilt.FlattenedTableMinimumWords); + Assert.Equal(fresh.Payload, rebuilt.Payload); + Assert.Equal(MetalShaderPrewarm.Identity(fresh), MetalShaderPrewarm.Identity(rebuilt)); + Assert.Equal( + MetalBinaryArchive.LibraryKey(expected.Source, expected.UsesPerVertexInputs), + MetalBinaryArchive.LibraryKey(actual.Source, actual.UsesPerVertexInputs)); + Assert.True(rebuilt.CachePayload.Length > 0, name); + } + + // Translates as the Metal backend does and counts what it translated and what it took from the cache. + private sealed class CountingBackend : IGuestGpuBackend + { + private static Exception Unsupported() => new NotSupportedException("The counting backend only translates."); + + public int Translations { get; private set; } + + public int CachedShaders { get; private set; } + + public string BackendName => "Metal (counting)"; + + public bool TryCompileProgram(ShaderCompileRequest request, out IGuestCompiledShader? shader, out string error) + { + Translations++; + shader = Gen5MslTranslator.TryCompileProgram(request, out var compiled, out error) + ? new MetalCompiledGuestShader(compiled, request) + : null; + return shader is not null; + } + + public IGuestCompiledShader? CreateCachedShader(byte[] payload, uint? inputLocationMask, ShaderCompileRequest request) + { + var shader = MetalCompiledGuestShader.FromCachePayload(payload, request); + if (shader is not null) CachedShaders++; + return shader; + } + + public void CountShaderCompilation() + { + } + + public IGuestCompiledShader GetDepthOnlyFragmentShader() => throw Unsupported(); + public void EnsureStarted(uint width, uint height) => throw Unsupported(); + public void HideSplashScreen() => throw Unsupported(); + public void Submit(byte[] bgraFrame, uint width, uint height) => throw Unsupported(); + public void SubmitGuestDraw(GuestDrawKind drawKind, uint width, uint height) => throw Unsupported(); + public bool TrySubmitGuestImage(int videoOutHandle, int displayBufferIndex, ulong address, uint width, uint height, + uint pitchInPixel, ulong flipRequestId) => throw Unsupported(); + public void SubmitCommandStream(ICpuMemory memory, uint queue, ulong address, uint dwordCount, ulong submissionId, + object? geometrySnapshots) => throw Unsupported(); + public IdleOutcome SubmitDone(ICpuMemory memory) => throw Unsupported(); + public void RegisterKnownDisplayBuffer(ulong address, uint guestFormat) => throw Unsupported(); + public bool IsGpuGuestImageAvailable(ulong address, uint format, uint numberType) => false; + public (long Draws, double DrawMs, long Pipelines, long ShaderCompilations) ReadAndResetPerfCounters() => throw Unsupported(); + public void RequestClose() => throw Unsupported(); + } +} + +// The cache's folder is process-wide: these tests run one at a time. +[CollectionDefinition(Name, DisableParallelization = true)] +public sealed class MetalTranslationCacheCollection +{ + public const string Name = "MetalTranslationCache"; +} diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslLoadElisionTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslLoadElisionTests.cs index 14feb614b..068328736 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslLoadElisionTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslLoadElisionTests.cs @@ -154,7 +154,7 @@ public void ValidMaskWithoutRestoreKeepsTheDiscard() // ---- programs ---- - private static Gen5ShaderProgram PresentQuad() + internal static Gen5ShaderProgram PresentQuad() { var instructions = new List<Gen5ShaderInstruction>(); void Add(string opcode, Gen5ShaderEncoding encoding, Gen5Operand[] sources, Gen5Operand[] destinations, diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslPixelInputTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslPixelInputTests.cs index a45a70012..8e5db77cf 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslPixelInputTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslPixelInputTests.cs @@ -16,7 +16,7 @@ namespace SharpEmu.ShaderCompiler.Metal.Tests; /// </summary> public sealed class Gen5MslPixelInputTests(ITestOutputHelper output) { - private const uint PerspCenter = 1u << 1; + internal const uint PerspCenter = 1u << 1; private const uint PullModel = 1u << 3; private const uint PosW = 1u << 11; private const uint FrontFace = 1u << 12; @@ -25,11 +25,11 @@ public sealed class Gen5MslPixelInputTests(ITestOutputHelper output) private const uint PosFixedPoint = 1u << 15; // VINTRP op: 0 = V_INTERP_P1_F32, 1 = V_INTERP_P2_F32, 2 = V_INTERP_MOV_F32. - private static uint Interp(uint vdst, uint op, uint attribute, uint channel, uint vsrc) => + internal static uint Interp(uint vdst, uint op, uint attribute, uint channel, uint vsrc) => 0xC8000000u | (vdst << 18) | (op << 16) | (attribute << 10) | (channel << 8) | vsrc; // exp mrt0 v(a), v(b), v(c), v(d) done vm, then s_endpgm. - private static uint[] ExportAndEnd(uint a, uint b, uint c, uint d) => + internal static uint[] ExportAndEnd(uint a, uint b, uint c, uint d) => [0xF800180F, a | (b << 8) | (c << 16) | (d << 24), 0xBF810000]; [Theory] @@ -983,7 +983,7 @@ private void AssertCompiles(Gen5MslShader shader) Assert.True(compiled, $"Metal rejected the emitted pixel MSL: {error}\n{shader.Source}"); } - private static Gen5MslShader Compile( + internal static Gen5MslShader Compile( uint[] words, uint inputs, uint? enable = null, diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslShaderPayloadTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslShaderPayloadTests.cs new file mode 100644 index 000000000..1cba5b26e --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslShaderPayloadTests.cs @@ -0,0 +1,290 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections; +using System.Reflection; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.ShaderCompiler.Metal.Tests; + +/// <summary> +/// The translation disk cache keeps a Metal translation as Gen5MslShaderPayload bytes and a later session builds its +/// libraries and pipelines from what they read back: every field of every shader must come back as the translator +/// made it, or the second launch draws differently from the first. +/// </summary> +public sealed class Gen5MslShaderPayloadTests(ITestOutputHelper output) +{ + // Every public property of the records a payload holds. A property added to one of them fails here until the + // payload writes it (and its format version is raised). + private static readonly (Type Type, string[] Properties)[] PinnedProperties = + [ + (typeof(Gen5MslShader), + [ + "AttributeCount", "ArgumentLayout", "BufferWordConstants", "CannotDiscard", "ColorOutputMask", "ConstantPositions", + "EntryPoint", "FlattenedTableMinimumWords", "MeshInfo", "PersistentThreads", "Source", "Stage", "Tessellation", + "ThreadgroupSizeX", "ThreadgroupSizeY", "ThreadgroupSizeZ", "UsesMipStatisticsConstant", "UsesPerVertexInputs", + "WritesLayer", "WritesViewportIndex", + ]), + (typeof(Gen5MslArgumentLayout), ["ByteSize", "Fields"]), + (typeof(MslArgumentField), ["ByteOffset", "ByteSize", "Count", "FieldKind", "FirstId", "Kind", "Name"]), + (typeof(Gen5MslMeshInfo), + [ + "Amplified", "DeviceLds", "DrawInfoBufferIndex", "GeometryInputPrimitives", "GeometryInputVertices", + "GeometryVerticesOut", "GuestWaveLanes", "HasGeometryHalf", "IndexBufferIndex", "LdsBytes", "MaxPrimitives", + "MaxVertices", "NarrowWave64", "PrimitivesPerSubgroup", "ReadsIndexBuffer", "ThreadgroupMemoryBytes", + "ThreadsPerThreadgroup", "Topology", "VerticesPerPrimitive", "VerticesPerSubgroup", "Wave64", "WavesPerThreadgroup", + ]), + (typeof(Gen5TessellationLaunch), + [ + "ControlPoints", "FactorBytesPerPatch", "MaxFactor", "OffchipBlockBytes", "OutputClockwise", "Partition", + "PatchesPerGroup", "Quad", "Role", + ]), + (typeof(Gen5MslShader.BufferWordConstant), ["Dword", "Index"]), + ]; + + [Fact] + public void ThePayloadWritesEveryPropertyOfTheRecordsItHolds() + { + foreach (var (type, properties) in PinnedProperties) + { + var actual = type.GetProperties(BindingFlags.Public | BindingFlags.Instance) + .Where(static property => property.Name != "EqualityContract") + .Select(static property => property.Name).Order(StringComparer.Ordinal).ToArray(); + Assert.Equal(properties.Order(StringComparer.Ordinal).ToArray(), actual); + } + } + + // Translations of each stage and of the paths that set the reflection fields: compute (plain, LDS, wave64, + // persistent threads), vertex (plain, constant positions), pixel (plain, per-vertex inputs), primitive shaders + // (mesh info), tessellation (hull and domain), and storage images with runtime swizzles. + public static TheoryData<string> Translations() => new(Corpus().Select(static entry => entry.Name)); + + [Theory] + [MemberData(nameof(Translations))] + public void ATranslationReadsBackFieldByField(string name) + { + var shader = Corpus().Single(entry => entry.Name == name).Compile(); + + var payload = Gen5MslShaderPayload.Write(shader, ShaderStage.Pixel, 0x0123_4567_89AB_CDEF); + Assert.True(Gen5MslShaderPayload.TryRead(payload, out var read, out var stage, out var hash, out var error), error); + + Assert.Equal(ShaderStage.Pixel, stage); + Assert.Equal(0x0123_4567_89AB_CDEFul, hash); + AssertSameFields(shader, read, nameof(Gen5MslShader)); + Assert.Equal(payload, Gen5MslShaderPayload.Write(read, stage, hash)); + output.WriteLine($"{name}: {payload.Length} bytes, stage {shader.Stage}, entry {shader.EntryPoint}"); + } + + // The corpus covers what each field is for; this record sets every field to a value other than its default, + // so a field the payload drops or swaps fails even when no translation above sets it. + [Fact] + public void ARecordWithEveryFieldSetReadsBackFieldByField() + { + var shader = new Gen5MslShader( + "kernel void k() {}\n", "k", Gen5MslStage.Mesh, 3, 4, 5, 6, + new Gen5MslArgumentLayout( + [ + new MslArgumentField(DescriptorBindingKind.Buffers, MslArgumentFieldKind.BufferPointers, "buffers", 2, 0, 0, 16), + new MslArgumentField(DescriptorBindingKind.Samplers, MslArgumentFieldKind.Samplers, "samplers", 1, 2, 16, 8), + ], + 24), + new Gen5MslMeshInfo(64, 2, 128, 96, 3, Gen5MslMeshTopology.Line, 4096, 7, 8, true, 9, true, true, true, 1024, true, 10, 11), + WritesLayer: true, + WritesViewportIndex: true) + { + UsesPerVertexInputs = true, + UsesMipStatisticsConstant = true, + BufferWordConstants = [new(12, 13), new(14, 15)], + ConstantPositions = [1f, -1f, float.NaN, 0.5f], + CannotDiscard = true, + ColorOutputMask = 0x5, + PersistentThreads = true, + Tessellation = new Gen5TessellationLaunch(Gen5TessellationRole.Domain, 16, 4, 0x8000, 24, + Gen5TessellationPartition.FractionalOdd, OutputClockwise: true, MaxFactor: 15, Quad: true), + FlattenedTableMinimumWords = 17, + }; + AssertNoDefaults(shader, nameof(Gen5MslShader)); + + Assert.True(Gen5MslShaderPayload.TryRead(Gen5MslShaderPayload.Write(shader, ShaderStage.Vertex, 1), + out var read, out var stage, out _, out var error), error); + + Assert.Equal(ShaderStage.Vertex, stage); + AssertSameFields(shader, read, nameof(Gen5MslShader)); + Assert.Equal(BitConverter.SingleToUInt32Bits(float.NaN), BitConverter.SingleToUInt32Bits(read.ConstantPositions![2])); + } + + [Fact] + public void ADamagedOrForeignPayloadIsRefusedWithItsReason() + { + var payload = Gen5MslShaderPayload.Write(Gen5ComputeFixtures.CompileRequestOrThrow(Gen5ComputeFixtures.ExecStore), + ShaderStage.Compute, 1); + + // Every truncation, from nothing to one byte short. + for (var length = 0; length < payload.Length; length++) + { + Assert.False(Gen5MslShaderPayload.TryRead(payload[..length], out _, out _, out _, out var error), $"length {length}"); + Assert.NotEmpty(error); + } + + var version = (byte[])payload.Clone(); + version[4]++; + Assert.False(Gen5MslShaderPayload.TryRead(version, out _, out _, out _, out var versionError)); + Assert.Contains("format", versionError, StringComparison.Ordinal); + + var magic = (byte[])payload.Clone(); + magic[0] ^= 0xFF; + Assert.False(Gen5MslShaderPayload.TryRead(magic, out _, out _, out _, out _)); + + Assert.False(Gen5MslShaderPayload.TryRead([.. payload, 0], out _, out _, out _, out var trailingError)); + Assert.Contains("past the end", trailingError, StringComparison.Ordinal); + + // A SPIR-V module (another backend's payload) or the bare MSL text is not a payload. + Assert.False(Gen5MslShaderPayload.TryRead([0x03, 0x02, 0x23, 0x07, 0, 0, 1, 0], out _, out _, out _, out _)); + Assert.False(Gen5MslShaderPayload.TryRead("kernel void k() {}"u8.ToArray(), out _, out _, out _, out _)); + + // An undefined stage: the payload of a request this build has no stage for. + var stage = (byte[])payload.Clone(); + stage[8] = 0xEE; + Assert.False(Gen5MslShaderPayload.TryRead(stage, out _, out _, out _, out var stageError)); + Assert.Contains("ShaderStage", stageError, StringComparison.Ordinal); + } + + private sealed record Entry(string Name, Func<Gen5MslShader> Compile); + + private static IEnumerable<Entry> Corpus() + { + foreach (var fixture in Gen5ComputeFixtures.All) + { + yield return new("compute-" + fixture.Name, () => Gen5ComputeFixtures.CompileRequestOrThrow(fixture)); + } + + yield return new("compute-wave64", () => Gen5ComputeFixtures.CompileRequestOrThrow( + Gen5ComputeFixtures.Wave64Broadcast, waveLaneCount: 64, localSizeX: 64)); + yield return new("compute-persistent", () => + { + var shader = Gen5ComputeFixtures.CompileRequestOrThrow(Gen5ComputeFixtures.PersistentQueueLoop); + Assert.True(shader.PersistentThreads); + return shader; + }); + yield return new("vertex", () => Gen5ComputeFixtures.CompileVertexOrThrow()); + yield return new("vertex-constant-positions", () => + { + var request = Gen5ComputeFixtures.RequestOrThrow(Gen5MslLoadElisionTests.PresentQuad(), ShaderStage.Vertex); + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error), error); + Assert.NotNull(shader.ConstantPositions); + return shader; + }); + yield return new("pixel", () => Gen5ComputeFixtures.CompilePixelOrThrow()); + yield return new("pixel-per-vertex-inputs", () => + { + var shader = Gen5MslPixelInputTests.Compile( + [Gen5MslPixelInputTests.Interp(4, 2, 1, 2, 0), .. Gen5MslPixelInputTests.ExportAndEnd(4, 4, 4, 4)], + Gen5MslPixelInputTests.PerspCenter, cntl: [0, 0x401]); + Assert.True(shader.UsesPerVertexInputs); + return shader; + }); + yield return new("mesh-passthrough", () => Gen5NggFixtures.CompileOrThrow(Gen5NggFixtures.Passthrough())); + yield return new("mesh-culling", () => + { + var shader = Gen5NggFixtures.CompileOrThrow(Gen5NggFixtures.CullingTriangle()); + Assert.NotNull(shader.MeshInfo); + return shader; + }); + yield return new("tessellation-hull", () => Gen5MslTessellationLaunchTests.CompileShader(ShaderStage.Compute, + new Gen5TessellationLaunch(Gen5TessellationRole.Hull, 21, 3, 0x8000, 16))); + yield return new("tessellation-domain", () => Gen5MslTessellationLaunchTests.CompileShader(ShaderStage.Vertex, + new Gen5TessellationLaunch(Gen5TessellationRole.Domain, 16, 4, 0x8000, 24, Gen5TessellationPartition.FractionalOdd, + MaxFactor: 15, Quad: true))); + yield return new("image-runtime-swizzle", () => + { + BindingLayout? layout = null; + Assert.True(Gen5ImageFixtures.TryCompile("ImageStore", Gen5ImageFixtures.ImageType2D, out var shader, out var error, + unifiedFormat: 71, dstSelect: 0xF2E, addressValues: [1, 0], storeValues: [1, 2, 3, 4], + runtimeImageSwizzles: true, inspect: (request, _) => layout = request.Bindings), error); + Assert.Equal(1u, layout!.StorageImageSwizzleCount); + return shader!; + }); + } + + private static void AssertSameFields(object? expected, object? actual, string path) + { + if (expected is null || actual is null) + { + Assert.True(expected is null && actual is null, $"{path}: {expected ?? "null"} != {actual ?? "null"}"); + return; + } + + // A list reads back as an array: the elements are what the host reads. + var type = expected.GetType(); + Assert.True(type == actual.GetType() || (expected is IEnumerable && actual is IEnumerable && type != typeof(string)), + $"{path}: {type} != {actual.GetType()}"); + if (type.IsPrimitive || type.IsEnum || type == typeof(string)) + { + if (expected is float single) + { + Assert.True(BitConverter.SingleToUInt32Bits(single) == BitConverter.SingleToUInt32Bits((float)actual), path); + return; + } + + Assert.True(expected.Equals(actual), $"{path}: {expected} != {actual}"); + return; + } + + if (expected is IEnumerable sequence) + { + var left = sequence.Cast<object?>().ToArray(); + var right = ((IEnumerable)actual).Cast<object?>().ToArray(); + Assert.True(left.Length == right.Length, $"{path}: {left.Length} items != {right.Length}"); + for (var index = 0; index < left.Length; index++) + { + AssertSameFields(left[index], right[index], $"{path}[{index}]"); + } + + return; + } + + foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) + { + if (property.Name == "EqualityContract" || property.GetIndexParameters().Length != 0) + { + continue; + } + + AssertSameFields(property.GetValue(expected), property.GetValue(actual), $"{path}.{property.Name}"); + } + } + + private static void AssertNoDefaults(object value, string path) + { + foreach (var property in value.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) + { + if (property.Name == "EqualityContract") + { + continue; + } + + var field = property.GetValue(value); + var name = $"{path}.{property.Name}"; + Assert.True(field is not null, $"{name} is null"); + var type = field.GetType(); + if (type.IsValueType) + { + Assert.True(!field.Equals(Activator.CreateInstance(type)), $"{name} has its default value"); + } + else if (field is string text) + { + Assert.True(text.Length != 0, $"{name} is empty"); + } + else if (field is IEnumerable sequence) + { + Assert.True(sequence.Cast<object>().Any(), $"{name} is empty"); + } + else + { + AssertNoDefaults(field, name); + } + } + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslTessellationLaunchTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslTessellationLaunchTests.cs index bf8453337..69d97479a 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslTessellationLaunchTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslTessellationLaunchTests.cs @@ -126,7 +126,7 @@ private static string Compile(ShaderStage stage, Gen5TessellationLaunch tessella return Regex.Replace(CompileShader(stage, tessellation, supportsDrawParameters).Source, @"\b([sv])\[(\d+)\]", "$1$2"); } - private static Gen5MslShader CompileShader(ShaderStage stage, Gen5TessellationLaunch tessellation, bool supportsDrawParameters = false) + internal static Gen5MslShader CompileShader(ShaderStage stage, Gen5TessellationLaunch tessellation, bool supportsDrawParameters = false) { var program = Gen5ComputeFixtures.DecodeOrThrow(new Gen5ComputeFixture("tessellation", EndProgram, 0, 0)); var request = Gen5ComputeFixtures.RequestOrThrow(program, stage, diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalRuntimeImageSwizzleExecutionTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalRuntimeImageSwizzleExecutionTests.cs index ae4d8a2e5..c22ff1585 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalRuntimeImageSwizzleExecutionTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalRuntimeImageSwizzleExecutionTests.cs @@ -67,6 +67,34 @@ public void RuntimeSelectStoresWriteTheBakedTexelBitForBit(uint guestFormat, uin output.WriteLine($"Compared {stores} baked and runtime-select stores of format {guestFormat} (d16={d16})."); } + // A shader the translation disk cache rebuilt from its payload (Gen5MslShaderPayload) compiles to a library and + // stores, through the runtime select, the texel the fresh translation stores. + [Theory] + [MemberData(nameof(Formats))] + public void AShaderRebuiltFromItsCachePayloadStoresTheTexelTheTranslationStores(uint guestFormat, uint pixelFormat, + uint texelBytes, bool d16) + { + var device = DeviceGate(); + var rebuilt = 0; + foreach (var select in new[] { 0xF2Eu, 0x204u, 0x12Eu }) + { + var fresh = Store(guestFormat, pixelFormat, texelBytes, d16, 0xF, select, runtime: true, device); + var cached = Store(guestFormat, pixelFormat, texelBytes, d16, 0xF, select, runtime: true, device, shader => + { + Assert.True(Gen5MslShaderPayload.TryRead(Gen5MslShaderPayload.Write(shader, ShaderStage.Compute, 0x5EED), + out var read, out _, out _, out var error), error); + Assert.NotSame(shader, read); + rebuilt++; + return read; + }); + Assert.Equal(fresh.Source, cached.Source); + Assert.Equal(Convert.ToHexString(fresh.Texel), Convert.ToHexString(cached.Texel)); + } + + Assert.Equal(3, rebuilt); + output.WriteLine($"Compared 3 fresh and rebuilt stores of format {guestFormat} (d16={d16}, device={device})."); + } + // The 24 orderings of X, Y, Z and W. private static IEnumerable<uint> Permutations() { @@ -131,7 +159,7 @@ private static byte[] Texel(uint guestFormat, uint dmask, uint select) } private static (byte[] Texel, string Source) Store(uint guestFormat, uint pixelFormat, uint texelBytes, bool d16, - uint dmask, uint select, bool runtime, bool device) + uint dmask, uint select, bool runtime, bool device, Func<Gen5MslShader, Gen5MslShader>? rebuild = null) { BindingLayout? layout = null; ResourceSnapshot? snapshot = null; @@ -141,6 +169,7 @@ private static (byte[] Texel, string Source) Store(uint guestFormat, uint pixelF storeValues: Data(guestFormat, d16), runtimeImageSwizzles: runtime, inspect: (compiled, resources) => (request, layout, snapshot) = (compiled, compiled.Bindings, resources)), error); Assert.Equal(runtime ? 1u : 0u, layout!.StorageImageSwizzleCount); + shader = rebuild is null ? shader : rebuild(shader!); if (!device) { return ([], shader!.Source); From 989d2dd61348a0f35d9977c4fcd18f8c472b2682 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 01:45:08 +0000 Subject: [PATCH 099/134] [Metal] Name the translation folder through a public entry, not a new Libs friend The architecture rule keeps Libs' friend assemblies to Core, its tests, GnmMode and Vulkan, so the Metal presenter names the game's translation folder through TranslationCache.UseGameFolder, the way ShaderAnalysisCache names the scalar graphs' folder. The cache-level Metal tests move to Libs.Tests beside the upstream TranslationDiskCache tests (same collection: the folder is process-wide), with the MSL fixtures linked in. --- .../Gpu/Pipelines/TranslationDiskCache.cs | 7 +++++++ src/SharpEmu.Libs/SharpEmu.Libs.csproj | 3 --- .../V2/MetalTranslationCache.cs | 4 ++-- .../MetalTranslationDiskCacheTests.cs} | 19 +++++++------------ .../SharpEmu.Libs.Tests.csproj | 4 ++++ 5 files changed, 20 insertions(+), 17 deletions(-) rename tests/{SharpEmu.Gpu.Metal.Tests/MetalTranslationCacheTests.cs => SharpEmu.Libs.Tests/Gpu/Pipelines/MetalTranslationDiskCacheTests.cs} (95%) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/TranslationDiskCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/TranslationDiskCache.cs index 2509d5573..f28fbdaf2 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/TranslationDiskCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/TranslationDiskCache.cs @@ -13,6 +13,13 @@ namespace SharpEmu.Libs.Gpu.Pipelines; +// The running game's translation folder and stamp, for a host outside this assembly (the Metal presenter), as +// ShaderAnalysisCache names the scalar graphs' folder: see TranslationDiskCache.UseGameFolder. +public static class TranslationCache +{ + public static void UseGameFolder(string? folder, string? stamp) => TranslationDiskCache.UseGameFolder(folder, stamp); +} + // SHARPEMU_TRANSLATION_CACHE=0 turns it off. Each game keeps the programs it translated on disk, so a later session // takes a program's SPIR-V from disk instead of translating it again. The key is everything the translation reads: the // translated program's instructions, every field of the request (pipeline state, specialization, binding layout, memory diff --git a/src/SharpEmu.Libs/SharpEmu.Libs.csproj b/src/SharpEmu.Libs/SharpEmu.Libs.csproj index f495c4f7c..95bdaad2e 100644 --- a/src/SharpEmu.Libs/SharpEmu.Libs.csproj +++ b/src/SharpEmu.Libs/SharpEmu.Libs.csproj @@ -29,9 +29,6 @@ SPDX-License-Identifier: GPL-2.0-or-later <InternalsVisibleTo Include="SharpEmu.Libs.Tests" /> <InternalsVisibleTo Include="SharpEmu.GnmMode" /> <InternalsVisibleTo Include="SharpEmu.Gpu.Vulkan" /> - <!-- The Metal host opens the translation disk cache for its game (TranslationDiskCache). --> - <InternalsVisibleTo Include="SharpEmu.Gpu.Metal" /> - <InternalsVisibleTo Include="SharpEmu.Gpu.Metal.Tests" /> <!-- The runtime reads internal load-progress diagnostics. --> <InternalsVisibleTo Include="SharpEmu.Core" /> </ItemGroup> diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalTranslationCache.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalTranslationCache.cs index 2f94cfa26..378f4309d 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalTranslationCache.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalTranslationCache.cs @@ -14,7 +14,7 @@ namespace SharpEmu.Gpu.Metal.V2; /// <summary> /// The game's two shader disk caches, beside the rest of its Metal shader data /// (pipeline_cache/<title>/metal-v2, where the prewarm list and the binary archive live): the -/// translations (TranslationDiskCache, <c>translations/</c>), so a later session takes a program's MSL +/// translations (TranslationCache / TranslationDiskCache, <c>translations/</c>), so a later session takes a program's MSL /// and reflection from disk instead of translating it again, and the scalar graphs /// (ShaderAnalysisCache, <c>analysis/</c>). Opened by the process that translates, where the /// presenter starts: the GPU process with the split on, the one process with it off. @@ -45,6 +45,6 @@ public static void Start(nint device) var directory = SharpEmuPaths.UserPath( "pipeline_cache", MetalShaderPrewarm.SanitizeTitleId(VideoOutBackendServices.GetApplicationTitleId()), "metal-v2"); ShaderAnalysisCache.UseGameFolder(Path.Combine(directory, "analysis")); - TranslationDiskCache.UseGameFolder(Path.Combine(directory, "translations"), Stamp(GuestGpu.Current, device)); + TranslationCache.UseGameFolder(Path.Combine(directory, "translations"), Stamp(GuestGpu.Current, device)); } } diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalTranslationCacheTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/MetalTranslationDiskCacheTests.cs similarity index 95% rename from tests/SharpEmu.Gpu.Metal.Tests/MetalTranslationCacheTests.cs rename to tests/SharpEmu.Libs.Tests/Gpu/Pipelines/MetalTranslationDiskCacheTests.cs index bbd35985b..047a075a3 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalTranslationCacheTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/MetalTranslationDiskCacheTests.cs @@ -1,6 +1,7 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using SharpEmu.Gpu.Metal; using SharpEmu.Gpu.Metal.V2; using SharpEmu.HLE; using SharpEmu.Libs.Gpu; @@ -12,7 +13,7 @@ using SharpEmu.ShaderCompiler.Resources; using Xunit; -namespace SharpEmu.Gpu.Metal.Tests; +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; /// <summary> /// The translation disk cache on Metal: a session keeps each translation, and a later session over the same folder @@ -20,12 +21,13 @@ namespace SharpEmu.Gpu.Metal.Tests; /// library key the host computes). An entry that is damaged, of another build, or made for another request is a /// counted miss that translates again. /// </summary> -[Collection(MetalTranslationCacheCollection.Name)] -public sealed class MetalTranslationCacheTests : IDisposable +// The folder is process-wide: these share the upstream tests' collection. +[Collection(TranslationDiskCacheCollection.Name)] +public sealed class MetalTranslationDiskCacheTests : IDisposable { private readonly string _directory = Path.Combine(Path.GetTempPath(), "SharpEmuTests", Guid.NewGuid().ToString("N")); - public MetalTranslationCacheTests() => TranslationDiskCache.UseGameFolder(_directory, "metal-test-stamp"); + public MetalTranslationDiskCacheTests() => TranslationDiskCache.UseGameFolder(_directory, "metal-test-stamp"); public void Dispose() { @@ -209,7 +211,7 @@ private static void AssertSameShader(MetalCompiledGuestShader fresh, MetalCompil Assert.Equal(expected.UsesPerVertexInputs, actual.UsesPerVertexInputs); Assert.Equal(expected.FlattenedTableMinimumWords, rebuilt.FlattenedTableMinimumWords); Assert.Equal(fresh.Payload, rebuilt.Payload); - Assert.Equal(MetalShaderPrewarm.Identity(fresh), MetalShaderPrewarm.Identity(rebuilt)); + Assert.Equal(fresh.PayloadHash, rebuilt.PayloadHash); Assert.Equal( MetalBinaryArchive.LibraryKey(expected.Source, expected.UsesPerVertexInputs), MetalBinaryArchive.LibraryKey(actual.Source, actual.UsesPerVertexInputs)); @@ -263,10 +265,3 @@ public void SubmitCommandStream(ICpuMemory memory, uint queue, ulong address, ui public void RequestClose() => throw Unsupported(); } } - -// The cache's folder is process-wide: these tests run one at a time. -[CollectionDefinition(Name, DisableParallelization = true)] -public sealed class MetalTranslationCacheCollection -{ - public const string Name = "MetalTranslationCache"; -} diff --git a/tests/SharpEmu.Libs.Tests/SharpEmu.Libs.Tests.csproj b/tests/SharpEmu.Libs.Tests/SharpEmu.Libs.Tests.csproj index 41346788f..46891b656 100644 --- a/tests/SharpEmu.Libs.Tests/SharpEmu.Libs.Tests.csproj +++ b/tests/SharpEmu.Libs.Tests/SharpEmu.Libs.Tests.csproj @@ -96,6 +96,10 @@ SPDX-License-Identifier: GPL-2.0-or-later </ItemGroup> <ItemGroup> <Compile Include="../Fixtures/Tile5Volume/Tile5VolumeOracle.cs" Link="Fixtures/Tile5VolumeOracle.cs" /> + <!-- Translated programs for the Metal translation cache tests (Gpu/Pipelines/MetalTranslationDiskCacheTests.cs). --> + <Compile Include="../SharpEmu.ShaderCompiler.Metal.Tests/Gen5ComputeFixtures.cs" Link="Fixtures/Gen5ComputeFixtures.cs" /> + <Compile Include="../SharpEmu.ShaderCompiler.Metal.Tests/Gen5ImageFixtures.cs" Link="Fixtures/Gen5ImageFixtures.cs" /> + <Compile Include="../SharpEmu.ShaderCompiler.Metal.Tests/FakeGuestMemory.cs" Link="Fixtures/FakeGuestMemory.cs" /> <EmbeddedResource Include="../Fixtures/Tile5Volume/offsets.csv" LogicalName="Tile5Volume.offsets.csv" /> </ItemGroup> <ItemGroup> From f0ec1458248294afa99266ddd1cae37f22b2c804 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 02:04:39 +0000 Subject: [PATCH 100/134] [Metal] Refuse replay capture for a program that reads the bindless heap Upstream's host replays no draw or dispatch whose program uses the heap, and the engine seals none (RenderRecorder.IsReplayable). The Metal capture let the heap's argument fields stand, so only the engine's check kept such a stage out. The capture now refuses it by name (bindless), and a scene test runs two identical heap dispatches in one submission: neither is sealed or replayed and both read their records' textures. --- .../V2/MetalRenderHost.Replay.cs | 9 ++++++ .../Scenes/BindlessHeapSceneTests.cs | 29 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Replay.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Replay.cs index 196ecdd57..a53b4b41c 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Replay.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Replay.cs @@ -450,6 +450,15 @@ private bool CaptureStages(ReplayCapture capture, bool compute) return ReplayRefusal.Bindless; } + // A program that reads the bindless heap is never replayed: each item prepares its heap views and takes the + // marks that completed before it (PrepareHeapViews), which a replay would skip. The engine already seals no + // such program (RenderRecorder.IsReplayable); the host refuses too, as upstream's does + // (VulkanVideoPresenter.DrawReplay.cs: entry.UsesBindlessHeap). + if (layout.UsesBindlessHeap) + { + return ReplayRefusal.Bindless; + } + if (program.UsesDeviceAddresses || info.WritesDeviceAddresses || snapshot.DeviceAddressRanges.Length != 0) { return ReplayRefusal.DeviceAddresses; diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/BindlessHeapSceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/BindlessHeapSceneTests.cs index 3d351de6f..fedc19611 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/BindlessHeapSceneTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/BindlessHeapSceneTests.cs @@ -162,6 +162,35 @@ public void TheFirstDispatchMarksAndALaterOneReadsTheTextureOfEachRecord() } } + // Two identical dispatches in one submission are what dispatch replay serves. A program that reads the heap is + // never replayed: the engine does not seal it (RenderRecorder.IsReplayable) and the host would refuse its capture + // (MetalRenderHost.Replay.cs), because each dispatch prepares its own heap views. Both read what one alone reads. + [Fact] + public void ADispatchThatReadsTheHeapIsNeverReplayed() + { + using var rig = CreateRig(); + if (rig is null) return; + if (!rig.Host.DispatchReplayEnabled) return; + const int textures = 8; + var heap = Build(rig, textures, records: 16, tableRecords: 16); + var keys = Enumerable.Range(0, Lanes).Select(lane => lane * 5 % 16).ToArray(); + _ = Pass(rig, heap, keys); + + rig.Memory.Write<uint>(heap.Output, new uint[Lanes * 4]); + rig.Memory.Write<uint>(heap.Output + KeyOffset, keys.Select(key => (uint)key << 4).ToArray()); + uint[] userData = [Descriptors.Lo(heap.Block), Descriptors.Hi(heap.Block)]; + var pm4 = rig.Dispatch(new ScenePm4(), Program, userData, 1, threadsX: Lanes); + rig.Submit(rig.Dispatch(pm4, Program, userData, 1, threadsX: Lanes)); + + Assert.False(rig.Host.ReplaySealed(true), "a dispatch that reads the heap was sealed for replay"); + Assert.Equal(0, rig.Host.ReplayCounts.Dispatches); + var words = rig.Read<float>(heap.Output, Lanes * 4); + for (var lane = 0; lane < Lanes; lane++) + { + AssertTexel(words.AsSpan(lane * 4, 4).ToArray(), Expected(keys[lane] % textures), $"lane {lane} key {keys[lane]}"); + } + } + [Fact] public void ResolvedElementsStayAcrossDispatchesAndARewrittenRecordTakesItsNewTexture() { From ac5ff881fb9028b6edea51cb0b733af21929e1c0 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 02:26:35 +0000 Subject: [PATCH 101/134] [Tests] Pin that a backend with its own mesh pipelines never takes upstream's task launch Upstream's mesh task launch (7cf0ac568, MeshTaskLaunch) is a mode of the mesh execution path, which only a provider answering MeshShadersSupported enters. Metal runs the same primitive-shader draws as mesh pipelines of its own (SupportsPrimitiveShaderMeshPipelines) and launches an automatic indirect one from the guest record on the GPU. The test pins that such a provider resolves the draw as a graphics draw and hands the record to the host's indirect draw, with or without a task-launch device: no mesh-execution program, no indirect mesh conversion, no CPU read. --- .../Gpu/Rendering/RenderExecutorDrawTests.cs | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorDrawTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorDrawTests.cs index 28bcd25ff..9a58306da 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorDrawTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorDrawTests.cs @@ -307,6 +307,44 @@ public void AutoIndirectMeshDrawReadsItsArgumentsOnTheGpu(bool gpuIndirect) AssertOrder("preparation_begin", "prepare_bindings", "draw_mesh 6 2 1", "preparation_end"); } + // A backend that runs primitive shaders as mesh pipelines of its own (Metal: SupportsPrimitiveShaderMeshPipelines + // without MeshShadersSupported) resolves an automatic indirect primitive-shader draw as an ordinary graphics draw and + // hands the guest record to its own indirect draw, which launches the mesh pipeline from it on the GPU. That holds + // while a task-launch device is present too (MeshTaskLaunch): the draw never asks for a mesh-execution or + // task-launched program and never prepares an indirect mesh conversion, and its record is not read here. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AutoIndirectPrimitiveShaderDraw_OnOwnMeshPipelines_IsNeverTaskLaunched(bool taskLaunchDevice) + { + var deviceSupported = MeshTaskLaunch.DeviceSupported; + MeshTaskLaunch.DeviceSupported = taskLaunchDevice; + try + { + _pipelines.SupportsPrimitiveShaderMeshPipelines = true; + _host.SupportsIndirectMeshDraw = true; + var banks = Banks(); + ApplyGeometryStageDraw(banks, maxVerticesOut: 3); + // A stage mask upstream's mesh execution path takes (RequiresMeshExecution): not a plain vertex program. + Assert.False(RenderExecutor.RunsPlainVertexProgram(banks.Context.ShaderStages)); + WriteIndirectArguments(6, 2, 4, 5); + + _executor.DrawAuto(1, banks, Auto(0, source: DrawOffsetSource.IndirectArguments) with { IndirectArgumentsAddress = IndirectArguments }); + + Assert.Contains(_pipelines.Calls, c => c.StartsWith("get_graphics_programs", StringComparison.Ordinal)); + Assert.DoesNotContain(_pipelines.Calls, c => c.StartsWith("get_mesh_programs", StringComparison.Ordinal)); + Assert.Null(_host.IndirectMeshRequest); + Assert.Equal(0, _host.GuestReads); + Assert.Contains(_host.Calls, c => c.StartsWith("draw_indirect", StringComparison.Ordinal)); + Assert.DoesNotContain(_host.Calls, c => c.StartsWith("draw_mesh", StringComparison.Ordinal)); + Assert.Empty(_pipelines.UnsupportedGraphics); + } + finally + { + MeshTaskLaunch.DeviceSupported = deviceSupported; + } + } + private void WriteIndirectArguments(params uint[] words) { var bytes = new byte[words.Length * 4]; From 65bfec9b2a9cd326590d151908f9cda3346e993c Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 02:27:42 +0000 Subject: [PATCH 102/134] [Tests] Pin the GPU launch of an automatic amplified mesh draw against upstream's task launch Upstream launches an automatic indirect draw of a mesh-style primitive shader (one input point per subgroup) from a task stage that reads the record and passes the first vertex in its payload (MeshTaskLaunch, 7cf0ac568). On Metal the launch kernel plays that part. The kernel equivalence test now covers the amplified program (its own kernel branch, one subgroup per point), and a new device theory renders an automatic amplified draw from a GPU-written record: the first vertex numbers the point, so only the record from vertex 1 lights the center, a second instance draws again, zero instances draw nothing, and one instance matches the CPU draw pixel for pixel. A kernel that dropped the first vertex fails three of its four cases. --- .../NggMeshIndirectLaunchTests.cs | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/NggMeshIndirectLaunchTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/NggMeshIndirectLaunchTests.cs index 47e269a1f..e41a802e4 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/NggMeshIndirectLaunchTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/NggMeshIndirectLaunchTests.cs @@ -205,6 +205,87 @@ public void AnIndirectDrawWithGpuWrittenArgumentsRendersLikeTheCpuDraw( Assert.Equal(words, block); } + // The draw upstream launches from a task stage (MeshTaskLaunch, 7cf0ac568): an automatic indirect draw of a + // mesh-style primitive shader, one input point per subgroup, whose (vertexCount, instanceCount, firstVertex, + // firstInstance) a GPU pass wrote. Upstream's task stage reads the record and emits one mesh group per point with + // the first vertex in its payload. Here the launch kernel reads it and launches one amplified subgroup per point, + // with the first vertex in the draw-info block's base vertex, which numbers the point (its ES vertex index). Only + // point 1 puts the fixture's triangle through the center, so a record of one point from vertex 1 lights it and one + // from vertex 0 does not, on the GPU launch exactly as on the CPU draw of the same counts. A second instance draws + // the same triangle again; zero instances draw nothing. + [Theory] + [InlineData(1u, 1u, true)] + [InlineData(0u, 1u, false)] + [InlineData(1u, 2u, true)] + [InlineData(1u, 0u, false)] + public void AnAmplifiedAutomaticDrawLaunchesItsPointsFromTheGpuRecord(uint firstVertex, uint instances, bool lit) + { + if (SkipWithoutMetalDevice("the amplified indirect mesh draw")) return; + + var shader = Gen5NggFixtures.CompileOrThrow( + Gen5NggFixtures.AmplifiedWave64Triangle(), Gen5NggFixtures.AmplifiedStageInfo); + var mesh = shader.MeshInfo!; + Assert.True(mesh.Amplified); + Assert.True(MetalNative.TryCompileLibrary(shader.Source + FragmentSource, out var library, out var compileError), compileError); + const Gen5MslMeshInputTopology input = Gen5MslMeshInputTopology.PointList; + const uint points = 1; + + var words = new uint[Gen5MslMeshInfo.DrawInfoDwordCount]; + Gen5MslMeshLaunch.FillDrawInfo(mesh, input, words, points, instances, false, 0, firstVertex, 0, 0); + var subgroups = Gen5MslMeshLaunch.SubgroupCount(mesh, input, points); + Assert.Equal(points, subgroups); + // The direct draw of the test rig launches one grid row, so the CPU draw is compared for one instance. + var cpu = instances == 1 ? RenderAmplified(library, shader, mesh, Bytes(words), subgroups, null) : null; + + var slot = new byte[Gen5MslMeshLaunch.SlotBytes]; + Gen5MslMeshLaunch.WriteMeshParameters(Parameters(slot, 0), mesh, input, 0, false, 0, 0, MaxThreadgroups); + var launch = new MeshIndirectLaunch(Bytes([points, instances, firstVertex, 0]), slot, mesh.DrawInfoBufferIndex); + var gpu = RenderAmplified(library, shader, mesh, new byte[Gen5MslMeshInfo.DrawInfoByteSize], 0, launch); + + var written = System.Runtime.InteropServices.MemoryMarshal.Cast<byte, uint>(launch.Written); + var grid = written.Slice((int)Gen5MslMeshLaunch.GridByteOffset / 4, 3).ToArray(); + Assert.Equal(instances == 0 ? [0u, 0u, 1u] : [subgroups, instances, 1u], grid); + Assert.Equal(firstVertex, written[5]); + var center = Green(gpu, TargetSize / 2, TargetSize / 2); + output.WriteLine($"first vertex {firstVertex}, {instances} instance(s): center green {center}"); + Assert.Equal(lit ? 1.0f : 0.0f, center, 3); + Assert.Equal(0.0f, Green(gpu, 1, 1), 3); + if (cpu is not null) + { + Assert.Equal(cpu, gpu); + } + } + + // The amplified program also binds the meshlet slot (DrawMesh binds the null buffer there for any program without a + // GS half) and reads its draw from the block, or from the launch the kernel wrote. + private float[] RenderAmplified( + nint library, Gen5MslShader shader, Gen5MslMeshInfo mesh, byte[] drawInfo, uint threadgroups, MeshIndirectLaunch? indirect) + { + Assert.True( + MetalNative.TryRenderMesh( + library, + shader.EntryPoint, + "gen5_mesh_test_fs", + [ + (new byte[Math.Max(shader.ArgumentLayout?.ByteSize ?? 0, 8)], 0u), + (new byte[64], 1u), + (drawInfo, mesh.DrawInfoBufferIndex), + (new byte[16], mesh.IndexBufferIndex), + (new byte[16], Gen5MslMeshInfo.MeshletBufferIndex), + ], + threadgroups, + mesh.ThreadsPerThreadgroup, + TargetSize, + TargetSize, + out var pixels, + out var error, + indirect: indirect), + $"the amplified mesh draw failed: {error}"); + return pixels; + } + + private static float Green(float[] pixels, uint x, uint y) => pixels[(int)(((y * TargetSize) + x) * 4) + 1]; + private float[] Render( nint library, Gen5MslShader shader, @@ -306,6 +387,9 @@ private static (uint[] Grid, uint[]? Words) CpuLaunch(Gen5MslMeshInfo mesh, Laun VerticesPerPrimitive: 3, Topology: Gen5MslMeshTopology.Triangle, ThreadgroupMemoryBytes: 4096, DrawInfoBufferIndex: 2, IndexBufferIndex: 3, ReadsIndexBuffer: true, GeometryVerticesOut: 24, Wave64: true, GeometryInputVertices: 24, GeometryInputPrimitives: 4)); + // A mesh-style subgroup (one input point, PRIM_AMP_FACTOR primitives out): one subgroup per point. + yield return ("amplified wave64", Gen5NggFixtures.CompileOrThrow( + Gen5NggFixtures.AmplifiedWave64Triangle(), Gen5NggFixtures.AmplifiedStageInfo).MeshInfo!); yield return ("points", new Gen5MslMeshInfo( ThreadsPerThreadgroup: 32, WavesPerThreadgroup: 1, MaxVertices: 32, MaxPrimitives: 32, VerticesPerPrimitive: 1, Topology: Gen5MslMeshTopology.Point, ThreadgroupMemoryBytes: 4096, From fb1cdf355f399bfe5af32653ad4d602c38c51b7a Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 02:28:25 +0000 Subject: [PATCH 103/134] [Tests] Pin Metal's amplified mesh sizing against upstream's primitive amplification plan Upstream's MeshDrawPlanner (7cf0ac568) gives a mesh-style subgroup min(256, PRIM_AMP_FACTOR) primitives, more than VGT_GS_MAX_VERT_OUT vertices when the factor is larger, and a lane per primitive. Metal's BuildAmplifiedMeshInfo already does the same; until now only the case of equal vertex and primitive counts was tested. The theory covers primitives past the vertices (wave64 and wave32), the 256 clamp and vertices past the primitives, and on device builds and runs each pipeline. --- .../NggMeshRuntimeTests.cs | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/NggMeshRuntimeTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/NggMeshRuntimeTests.cs index d9a236a06..c7de92fed 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/NggMeshRuntimeTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/NggMeshRuntimeTests.cs @@ -846,6 +846,67 @@ public void IndexedWave64PrimitiveShaderDrawsTrianglesFromEverySubgroup() Assert.Equal(0.0f, Green(pixels, TargetSize - 2, 1), 3); } + // Upstream's mesh planner (MeshDrawPlanner, 7cf0ac568) gives a mesh-style subgroup (one input point) + // min(256, PRIM_AMP_FACTOR) primitives, which can be more than VGT_GS_MAX_VERT_OUT vertices, and a lane per + // primitive as well as per vertex, since each lane exports one primitive. Metal's amplified mesh info follows the same + // rule: primitives from PRIM_AMP_FACTOR clamped to 256, threads in whole guest waves over the larger output. + [Theory] + [InlineData(true, 64u, 200u, 200u, 256u)] + [InlineData(true, 128u, 128u, 128u, 128u)] + [InlineData(true, 32u, 0x1FFu, 256u, 256u)] + [InlineData(true, 200u, 16u, 16u, 256u)] + [InlineData(false, 64u, 200u, 200u, 224u)] + [InlineData(false, 256u, 0x1FFu, 256u, 256u)] + public void PrimitiveAmplificationSizesTheOutputAndTheLanes( + bool wave64, uint verticesOut, uint amplification, uint primitives, uint threads) + { + var stage = Gen5NggFixtures.AmplifiedStageInfo with + { + IsWave64 = wave64, + AmplifiedVerticesOut = verticesOut, + MaxOutputPerSubgroup = verticesOut, + PrimitiveAmplificationFactor = amplification, + }; + var shader = Gen5NggFixtures.CompileOrThrow(Gen5NggFixtures.AmplifiedWave64Triangle(), stage); + var mesh = shader.MeshInfo!; + Assert.True(mesh.Amplified); + Assert.Equal(verticesOut, mesh.MaxVertices); + Assert.Equal(primitives, mesh.MaxPrimitives); + Assert.Equal(threads, mesh.ThreadsPerThreadgroup); + Assert.Equal(threads / mesh.GuestWaveLanes, mesh.WavesPerThreadgroup); + Assert.True(mesh.ThreadsPerThreadgroup >= Math.Max(mesh.MaxVertices, mesh.MaxPrimitives)); + if (SkipWithoutMetalDevice("the amplified mesh pipeline compile")) return; + + // The device takes the pipeline's declared output (Metal refuses one past its mesh size limit) and runs a point. + var source = shader.Source + FragmentSource; + Assert.True(MetalNative.TryCompileLibrary(source, out var library, out var compileError), compileError); + var words = new uint[Gen5MslMeshInfo.DrawInfoDwordCount]; + Gen5MslMeshLaunch.FillDrawInfo( + mesh, Gen5MslMeshInputTopology.PointList, words, count: 1, instanceCount: 1, indexed: false, + indexType: 0, firstIndex: 0, baseVertex: 0, firstInstance: 0); + var drawInfo = new byte[words.Length * sizeof(uint)]; + Buffer.BlockCopy(words, 0, drawInfo, 0, drawInfo.Length); + Assert.True( + MetalNative.TryRenderMesh( + library, + shader.EntryPoint, + "gen5_mesh_test_fs", + [ + (BuildArgumentBuffer(shader), 0u), + (new byte[64], 1u), + (drawInfo, mesh.DrawInfoBufferIndex), + (new byte[16], mesh.IndexBufferIndex), + (new byte[16], Gen5MslMeshInfo.MeshletBufferIndex), + ], + threadgroups: 1, + mesh.ThreadsPerThreadgroup, + TargetSize, + TargetSize, + out _, + out var renderError), + $"the amplified mesh pipeline failed: {renderError}"); + } + [Theory] [InlineData(100u, null)] [InlineData(68u, 40u)] From 13c8cb35657545b783feaf91ad839fbd4e540340 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 02:34:56 +0000 Subject: [PATCH 104/134] [Shader] Step the stand-in shader clock 2^32 + 1 per read, and say when a program reads it Metal has no shader clock: MSL 4.1 declares no clock, timer or cycle-count function and AGX rejects llvm.readcyclecounter, so IShaderPipelineHost.ShaderDeviceClockEnabled stays false on Metal (upstream reads OpReadClockKHR at device scope where Vulkan has shaderDeviceClock). S_MEMTIME / S_MEMREALTIME already read a per-invocation counter of their own reads here, but it moved by 1 per read, so a guest wait for N ticks ran N loop trips. Upstream's SPIR-V fallback (7cf0ac568) moves its counter 2^32 per read, which ends any wait on the 64-bit difference for a 32-bit number of ticks. The counter now moves 2^32 + 1 per read: the high dword as upstream's, the low dword still by one, so a wait on the low dword alone keeps progressing. The stand-in counts reads, not time; each program translated with it is counted (Gen5MslTranslator.StandInClockPrograms) and logged once per shader hash. SHARPEMU_METAL_SHADER_CLOCK_STEP=0 steps by 1 again. The clock test now checks both steps on the device: the second read's high dword is 2 (was 0) because each read moves the high dword. --- docs/macos/configuration.md | 1 + .../Gen5MslCodegenOptions.cs | 8 +++++ .../Gen5MslTranslator.Resources.cs | 26 ++++++++++++++++ .../Gen5MslTranslator.cs | 31 +++++++++++++------ .../Gen5MslMemoryImageSemanticsTests.cs | 31 ++++++++++++++----- 5 files changed, 81 insertions(+), 16 deletions(-) diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 10f0c3726..da0f26c22 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -72,6 +72,7 @@ them for measurements or to isolate a problem. | `SHARPEMU_METAL_BINDLESS_HEAP` | on | `0` turns off the bindless heap. By default an image or sampler a program reads from a descriptor table at a record only the shader knows is read through the heap: the shader marks the records it reads, the host resolves each marked record's texture or sampler from guest memory, and the program reads it from a later draw on (the first read of a record returns zeros). `0` plans those tables as before (bindless image tables, at most 256 candidates, off-class candidates read null). | | `SHARPEMU_RUNTIME_IMAGE_SWIZZLE` | on | `0` bakes each storage image's destination select into the translated program, one program per select. By default a store reads the image's channel map from shader data, which the host writes from the bound descriptor. | | `SHARPEMU_METAL_FORMAT_LOAD_COMPONENT_BOUNDS` | on | `0` restores the old bound of a formatted buffer load whose format is fixed at translation: the whole element had to fit below the buffer's size. By default each selected component is checked at its own address, wrapping past 2^32 as on the hardware, so a component that wraps to the buffer's start is read, and the load reads its constants only when a selected component is out of range. An element that fits whole still takes one compare. Loads whose format is read at run time always check per component. | +| `SHARPEMU_METAL_SHADER_CLOCK_STEP` | on | Metal has no shader clock, so `S_MEMTIME`/`S_MEMREALTIME` read a per-invocation counter of their own reads (logged once per shader as `[MSL][WARN][SHADER_CLOCK]`). By default each read moves it 2^32 + 1, as upstream's SPIR-V fallback moves its high dword: a guest wait on the 64-bit difference for fewer than 2^32 ticks ends at its next read, and a wait on the low dword still sees one tick per read. `0` steps by 1, so such a wait runs one loop trip per tick. | | `SHARPEMU_GRAPHICS_PARTIAL_LANES` | off | `1` makes pixel-shader lane reads (DPP, DPP8, PERMLANE16, V_READLANE) of a lane the fragment simdgroup never launched read the reading lane's own value, and treats such a lane as active when the guest EXEC mask has its bit. Off by default, as upstream: it changes every pixel shader with cross-lane operations. | | `SHARPEMU_METAL_MESHLETS` | on | `0` disables the meshlet cache. | | `SHARPEMU_METAL_V2_BINARY_ARCHIVE` | on | `0` disables the on-disk library and pipeline archives. | diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs index b80fa9a5d..e6659a6b3 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs @@ -337,6 +337,13 @@ public sealed record Gen5MslCodegenOptions( /// keeps the cases.</summary> public bool IndexedImageCandidates { get; init; } = true; + /// <summary>The stand-in for S_MEMTIME / S_MEMREALTIME (MSL has no shader clock) moves 2^32 + 1 ahead per read + /// instead of 1, as upstream's SPIR-V fallback moves 2^32 (Gen5SpirvTranslator.ReadShaderClock): a guest wait on + /// the 64-bit difference of two reads for fewer than 2^32 ticks then ends at its next read, where a step of 1 + /// spun the loop once per tick; a wait on the low dword alone still sees it move by 1 per read. + /// SHARPEMU_METAL_SHADER_CLOCK_STEP=0 steps by 1 again.</summary> + public bool ShaderClockWideStep { get; init; } = true; + public static Gen5MslCodegenOptions FromEnvironment { get; } = new( StructuredControlFlow: Environment.GetEnvironmentVariable("SHARPEMU_MSL_STRUCTURED") != "0", RegisterAllocation: Environment.GetEnvironmentVariable("SHARPEMU_MSL_REGALLOC") != "0", @@ -397,6 +404,7 @@ public sealed record Gen5MslCodegenOptions( GroupUniformBarriers = Environment.GetEnvironmentVariable("SHARPEMU_MSL_GROUP_BARRIERS") != "0", HalfLocalWaveLoops = Environment.GetEnvironmentVariable("SHARPEMU_MSL_HALF_LOOPS") != "0", IndexedImageCandidates = Environment.GetEnvironmentVariable("SHARPEMU_MSL_INDEXED_CANDIDATES") != "0", + ShaderClockWideStep = Environment.GetEnvironmentVariable("SHARPEMU_METAL_SHADER_CLOCK_STEP") != "0", MeshDeviceLdsThresholdBytes = uint.TryParse( Environment.GetEnvironmentVariable("SHARPEMU_MSL_MESH_LDS_THRESHOLD"), out var threshold) ? Math.Min(threshold, 16384u) : 12288u, diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs index d6ad1ae8d..f8ff4de6b 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs @@ -130,10 +130,36 @@ public static bool TryCompileProgram( } } + NoteStandInClock(request); Gen5MslDump.Write(request, shader); return true; } + private static long _standInClockPrograms; + private static readonly System.Collections.Concurrent.ConcurrentDictionary<ulong, byte> StandInClockHashes = new(); + + /// <summary>Programs translated with the stand-in shader clock (TryEmitShaderClock): MSL has no clock, so their + /// S_MEMTIME / S_MEMREALTIME count reads, not time.</summary> + public static long StandInClockPrograms => Interlocked.Read(ref _standInClockPrograms); + + // A program that reads the guest's clock gets a counter of its own reads instead: counted, and logged once per hash, + // so a title whose timing depends on it says so. + private static void NoteStandInClock(ShaderCompileRequest request) + { + if (!request.Program.Instructions.Any(static instruction => instruction.Opcode is "SMemtime" or "SMemrealtime")) + { + return; + } + + Interlocked.Increment(ref _standInClockPrograms); + if (StandInClockHashes.TryAdd(request.Hash, 0)) + { + Console.Error.WriteLine( + $"[MSL][WARN][SHADER_CLOCK] 0x{request.Hash:X16} reads S_MEMTIME/S_MEMREALTIME: Metal has no shader clock, " + + "so each read advances a per-invocation counter (reads, not time)."); + } + } + private sealed partial class CompilationContext { private const string ResourcesName = "sharpemu_resources"; diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs index 03e6e752b..c23136e50 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs @@ -2441,14 +2441,23 @@ private bool TryEmitScalarMemory( private const string ShaderClockName = "sharpemu_shader_clock"; // S_MEMTIME / S_MEMREALTIME write a 64-bit counter to the SDATA pair. A Metal shader - // has no clock to read: MSL declares none, and the AGX compiler fails the pipeline - // on llvm.readcyclecounter (__builtin_readcyclecounter; checked on an M4, macOS 27). - // The stand-in is the invocation's own tick counter, advanced by one on every read of - // either instruction: a read returns more than every earlier read in the invocation, - // so a delta between two reads is positive and a wait for the counter to pass a mark - // ends. It counts reads, not time, and is not comparable between invocations or with - // the 100 MHz reference clock the command processor's timestamps report. Every lane - // of a wave runs the same scalar instructions, so the value is wave-uniform. + // has no clock to read: MSL declares none (MSL 4.1 has no clock, timer or cycle-count + // function), and the AGX compiler fails the pipeline on llvm.readcyclecounter + // (__builtin_readcyclecounter; checked on an M4, macOS 27). Upstream reads + // OpReadClockKHR at device scope where Vulkan has shaderDeviceClock + // (IShaderPipelineHost.ShaderDeviceClockEnabled stays false on Metal). + // The stand-in is the invocation's own tick counter, advanced on every read of either + // instruction before it is stored: a read returns more than every earlier read in the + // invocation, so a delta between two reads is positive and a wait for the counter to + // pass a mark ends. With ShaderClockWideStep (default) each read moves it 2^32 + 1: + // the high dword by one, as upstream's fallback (2^32 per read) does, so a wait on the + // 64-bit difference for fewer than 2^32 ticks ends at its next read; the low dword by + // one, so a wait on the low dword alone still progresses one tick per read. It counts + // reads, not time: it is not comparable between invocations or with the 100 MHz + // reference clock the command processor's timestamps report, and a guest that + // measures elapsed time with it measures read counts. Every lane of a wave runs the + // same scalar instructions, so the value is wave-uniform. Each program translated + // with it is counted (StandInClockPrograms) and logged once per shader hash. private bool TryEmitShaderClock(Gen5ShaderInstruction instruction, out string error) { error = string.Empty; @@ -2458,11 +2467,15 @@ private bool TryEmitShaderClock(Gen5ShaderInstruction instruction, out string er return false; } - Line($"{ShaderClockName} += 1ul;"); + Line(_options.ShaderClockWideStep + ? $"{ShaderClockName} += {ShaderClockWideStepLiteral};" + : $"{ShaderClockName} += 1ul;"); StoreScalar64(low.Value, ShaderClockName); return true; } + private const string ShaderClockWideStepLiteral = "0x100000001ul"; + private bool TryEmitGlobalMemory( Gen5ShaderInstruction instruction, Gen5GlobalMemoryControl control, diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslMemoryImageSemanticsTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslMemoryImageSemanticsTests.cs index c36d37ff0..570078511 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslMemoryImageSemanticsTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslMemoryImageSemanticsTests.cs @@ -316,13 +316,18 @@ public void Wave64BpermuteShufflesWithinTheSimdgroupAndStaysInItsOwnHalf() // ---- S_MEMTIME / S_MEMREALTIME and SMEM cache maintenance ---- [Theory] - [InlineData(0x24u)] // s_memtime - [InlineData(0x25u)] // s_memrealtime - public void ShaderClockReadsAreNonZeroAndAdvanceAcrossACacheInvalidate(uint opcode) + [InlineData(0x24u, true)] // s_memtime + [InlineData(0x25u, true)] // s_memrealtime + [InlineData(0x24u, false)] + [InlineData(0x25u, false)] + public void ShaderClockReadsAreNonZeroAndAdvanceAcrossACacheInvalidate(uint opcode, bool wideStep) { // MSL has no shader clock, so the 64-bit counter advances on every read: a later - // read is larger, never the hardcoded zero a missing clock would leave. - var fixture = new Gen5ComputeFixture($"smem-clock-{opcode:X2}", + // read is larger, never the hardcoded zero a missing clock would leave. The wide step + // (default) moves it 2^32 + 1 per read, as upstream's SPIR-V fallback moves its high + // dword: a wait on the 64-bit difference ends at the next read, one on the low dword + // still sees it move by one. SHARPEMU_METAL_SHADER_CLOCK_STEP=0 steps by one. + var fixture = new Gen5ComputeFixture($"smem-clock-{opcode:X2}-{wideStep}", [ 0xF4000000u | opcode << 18 | 4u << 6, 0u, // s_memtime s[4:5] 0xF4800000u, 0u, // s_dcache_inv @@ -332,13 +337,19 @@ public void ShaderClockReadsAreNonZeroAndAdvanceAcrossACacheInvalidate(uint opco 0x7E060204, // v_mov_b32 v3, s4 0x7E080206, // v_mov_b32 v4, s6 0x7E0A0207, // v_mov_b32 v5, s7 + 0x7E0C0205, // v_mov_b32 v6, s5 0xE0700000, 0x80020300, // buffer_store_dword v3, off, s[8:11], 0 0xE0700004, 0x80020400, // buffer_store_dword v4, off, s[8:11], 0 offset:4 0xE0700008, 0x80020500, // buffer_store_dword v5, off, s[8:11], 0 offset:8 + 0xE070000C, 0x80020600, // buffer_store_dword v6, off, s[8:11], 0 offset:12 SEndpgm, ], 8, 16); - var shader = Gen5ComputeFixtures.CompileRequestOrThrow(fixture); + var before = Gen5MslTranslator.StandInClockPrograms; + var shader = Gen5ComputeFixtures.CompileRequestOrThrow(fixture, + options: Gen5MslCodegenOptions.FromEnvironment with { ShaderClockWideStep = wideStep }); Assert.Contains("sharpemu_shader_clock", shader.Source); + Assert.Equal(wideStep, shader.Source.Contains("sharpemu_shader_clock += 0x100000001ul;", StringComparison.Ordinal)); + Assert.True(Gen5MslTranslator.StandInClockPrograms > before); if (!RequireDevice()) return; Assert.True(MetalNative.TryCompileLibrary(shader.Source, out var library, out var compileError), @@ -347,9 +358,15 @@ public void ShaderClockReadsAreNonZeroAndAdvanceAcrossACacheInvalidate(uint opco new byte[PushData.ByteSize], shader.ArgumentLayout!, 1, out var result, out var runError), runError); var first = BinaryPrimitives.ReadUInt32LittleEndian(result.AsSpan(0)); var second = BinaryPrimitives.ReadUInt32LittleEndian(result.AsSpan(4)); + var secondHigh = BinaryPrimitives.ReadUInt32LittleEndian(result.AsSpan(8)); + var firstHigh = BinaryPrimitives.ReadUInt32LittleEndian(result.AsSpan(12)); Assert.NotEqual(0u, first); Assert.True(second > first, $"{second} <= {first}"); - Assert.Equal(0u, BinaryPrimitives.ReadUInt32LittleEndian(result.AsSpan(8))); + Assert.Equal(1u, second - first); + // The 64-bit difference of the two reads: 2^32 + 1 with the wide step, which ends any wait for fewer + // than 2^32 ticks; 1 without it. + var difference = (((ulong)secondHigh << 32) | second) - (((ulong)firstHigh << 32) | first); + Assert.Equal(wideStep ? 0x1_0000_0001ul : 1ul, difference); } // ---- image sampling: LOD clamp, A16, UNRM ---- From e521592c144806ca2bc3b7d4ee3b3103608e9a6c Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 02:42:02 +0000 Subject: [PATCH 105/134] [Metal] Hand out the compute compile in flight (GetComputePipelineCompletion) Upstream's host returns the Task of a compute pipeline compile still running (VulkanVideoPresenter.GetComputePipelineCompletion); Metal answered the interface default, null, so a dispatch that may not be left out (RenderRecorder.Compute) and a linked module's bounded wait (RenderExecutor.WaitForLinkedModule) slept a millisecond per poll until the compile finished. MetalPipelineCompiler.Completion hands out a continuation of the pending compile that never faults: a waiter of an abandoned speculative compile re-asks TryCreateComputePipeline, which starts its own compile and reports a real failure where it always did, instead of throwing in the recorder. MetalRenderHost.GetComputePipelineCompletion keys it by program id, as TryCreateComputePipeline keys the compile. SHARPEMU_METAL_COMPUTE_COMPILE_WAIT=0 hands out nothing again. Latency only; nothing compiled changes. --- docs/macos/configuration.md | 1 + .../V2/MetalPipelineCompiler.cs | 11 ++ .../V2/MetalRenderHost.Pipelines.cs | 13 +++ .../MetalComputeCompileWaitTests.cs | 105 ++++++++++++++++++ 4 files changed, 130 insertions(+) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalComputeCompileWaitTests.cs diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index da0f26c22..2425e51b2 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -80,6 +80,7 @@ them for measurements or to isolate a problem. | `SHARPEMU_TRANSLATION_CACHE` | on | `0` stops keeping translated shaders on disk. By default each translation (MSL and its reflection) is kept in `pipeline_cache/<title ID>/metal-v2/translations`, up to 8 GiB per game, and a later session of the same build takes it from there instead of translating the program again. A new build, translator switch, device or OS uses a new folder. | | `SHARPEMU_SHADER_ANALYSIS_CACHE_PATH` | per game | Folder of the scalar-graph cache of shader planning. By default `pipeline_cache/<title ID>/metal-v2/analysis`; `0` turns the cache off. | | `SHARPEMU_METAL_V2_ASYNC_PIPELINES` | on | `0` builds pipeline states on the GPU worker thread. | +| `SHARPEMU_METAL_COMPUTE_COMPILE_WAIT` | on | A dispatch that must have its compute pipeline, and a linked module's bounded wait, wait on the compile still running for it (as upstream's host hands it out) instead of polling every millisecond. `0` polls as before. | | `SHARPEMU_METAL_V2_ASYNC_LIBRARIES` | on | `0` compiles each shader library on the thread that needs it, not on the compile pool. | | `SHARPEMU_METAL_V2_GRAPHICS_WAIT_OFF_CACHE` | on | A draw that cannot be left out while its pipeline compiles waits for the compile outside the shared pipeline cache's lock, so other draws' programs keep resolving. `0` builds the pipeline under the lock, as before. Only with `SHARPEMU_METAL_V2_ASYNC_GRAPHICS` on. | | `SHARPEMU_RESOLVE_SHARDS` | `1` | Threads that resolve draw and dispatch programs ahead of the GPU worker, 1 to 8. With more than one, each has its own queue and its own part of the resolve memo, and a draw always goes to the same one. `1` is the single resolver; `2` measured no frame-time gain in Demon's Souls for more resolver CPU. Logged once at start; per-thread counts and the shared-lock wait are in the `shards=(...)` field of the `[METAL-V2][PERF]` prefetch counters. | diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalPipelineCompiler.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalPipelineCompiler.cs index eb3a98a56..04cda10da 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalPipelineCompiler.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalPipelineCompiler.cs @@ -216,6 +216,17 @@ public bool TryWait(object key, out Result? result) return TryTakeFinished(key, pending, out result); } + /// <summary> + /// Completes when the compile started for this key has finished, or null when none is in flight. It never + /// faults: the caller asks TryTake again, which reports a failed compile the way it always does (a dispatch + /// that waits on an abandoned speculative compile then starts its own instead of throwing here). + /// </summary> + public Task? Completion(object key) => + _pending.TryGetValue(key, out var pending) + ? pending.Work.ContinueWith(static _ => { }, CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default) + : null; + /// <summary> /// Blocks until the compile started for this key is done, leaving its result for TryTake: built here and now /// when no compiler thread has started it, waited for when one has. Nothing to wait for when there is none. diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs index 69134b88a..f18189718 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs @@ -1641,6 +1641,19 @@ public bool TryCreateComputePipeline(ComputePipelineDescription description, out return true; } + /// <summary> + /// The compile TryCreateComputePipeline left running for this program, as upstream's host hands out its in-flight + /// compile (IShaderPipelineHost.GetComputePipelineCompletion): a dispatch that may not be left out + /// (RenderRecorder.Compute) and a linked module's bounded wait (RenderExecutor.WaitForLinkedModule) then wake when + /// it finishes instead of polling every millisecond. Null when nothing compiles for it. + /// SHARPEMU_METAL_COMPUTE_COMPILE_WAIT=0 answers null always, so those waits poll as before. + /// </summary> + public Task? GetComputePipelineCompletion(ShaderProgram program) => + ComputeCompileWait && !SynchronousPipelines ? Compiler.Completion(program.Id) : null; + + internal static bool ComputeCompileWait { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_COMPUTE_COMPILE_WAIT") != "0"; + // Set on the worker while it asks for the pipeline of a dispatch it has read ahead to. [ThreadStatic] private static bool _prefetchingPipeline; diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalComputeCompileWaitTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalComputeCompileWaitTests.cs new file mode 100644 index 000000000..707cea13b --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalComputeCompileWaitTests.cs @@ -0,0 +1,105 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Metal; +using SharpEmu.ShaderCompiler.Metal.Tests; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests; + +/// <summary> +/// The compile TryCreateComputePipeline leaves running is handed out (IShaderPipelineHost.GetComputePipelineCompletion), +/// as upstream's host hands out its in-flight compute compile: a dispatch that may not be left out and a linked module's +/// bounded wait then wake when it finishes instead of polling every millisecond. The task never faults; the re-ask takes +/// the pipeline. SHARPEMU_METAL_COMPUTE_COMPILE_WAIT=0 hands out nothing. Device work is behind the exclusive device gate. +/// </summary> +public sealed class MetalComputeCompileWaitTests(ITestOutputHelper output) +{ + private static readonly Lazy<nint> Device = new(MetalNative.MTLCreateSystemDefaultDevice); + + [Fact] + public void AComputeCompileInFlightHandsOutItsCompletionAndTheReaskTakesThePipeline() + { + if (!RequireDevice()) return; + // Declared before the rig, so it is disposed after it: a compiler thread may still reach this gate until the + // rig's host has joined its threads, and waiting on a disposed gate throws on that thread and ends the process. + using var gate = new ManualResetEventSlim(false); + using var rig = new MetalPassRig(Device.Value, 1024 * 1024); + var host = rig.Host; + IShaderPipelineHost pipelines = host; + var description = Description(host, 0x5EED); + Assert.Null(pipelines.GetComputePipelineCompletion(description.Program)); + + host.PipelineCompiler.Gate = gate; + Assert.False(host.TryCreateComputePipeline(description, out _)); + var completion = pipelines.GetComputePipelineCompletion(description.Program); + Assert.NotNull(completion); + Assert.False(completion!.IsCompleted); + // Another program's compile is not this one's. + Assert.Null(pipelines.GetComputePipelineCompletion(new ShaderProgram(description.Program.Id + 1, 0))); + + gate.Set(); + Assert.True(completion.Wait(TimeSpan.FromSeconds(60)), "The compute compile never finished."); + Assert.False(completion.IsFaulted); + Assert.True(host.TryCreateComputePipeline(description, out var handle)); + Assert.NotEqual(0L, (long)handle.Pipeline); + Assert.Null(pipelines.GetComputePipelineCompletion(description.Program)); + } + + [Fact] + public void WithTheSwitchOffNoCompletionIsHandedOut() + { + if (!RequireDevice()) return; + using var gate = new ManualResetEventSlim(false); + using var rig = new MetalPassRig(Device.Value, 1024 * 1024); + var host = rig.Host; + IShaderPipelineHost pipelines = host; + var description = Description(host, 0x5EEE); + host.PipelineCompiler.Gate = gate; + Assert.False(host.TryCreateComputePipeline(description, out _)); + var previous = MetalRenderHost.ComputeCompileWait; + try + { + MetalRenderHost.ComputeCompileWait = false; + Assert.Null(pipelines.GetComputePipelineCompletion(description.Program)); + } + finally + { + MetalRenderHost.ComputeCompileWait = previous; + gate.Set(); + } + } + + private static ComputePipelineDescription Description(MetalRenderHost host, ulong hash) + { + var request = Gen5ComputeFixtures.CreateComputeRequest(Gen5ComputeFixtures.ExecStore); + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var compiled, out var error), error); + var shader = new MetalCompiledGuestShader(compiled, request); + var program = new ShaderProgram(hash, host.CreateShaderModule(shader, ShaderStage.Compute, hash, hash)); + return new ComputePipelineDescription + { + Input = new ComputeInputInfo { ThreadsX = 32, ThreadsY = 1, ThreadsZ = 1 }, + Program = program, + Stage = new ShaderProgramInfo { Stage = ShaderStageKind.Compute, Hash = hash }, + }; + } + + private bool RequireDevice() + { + if (Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") != "1") + { + output.WriteLine("Pipeline compiles run on the device only behind the exclusive device gate."); + return false; + } + + Assert.True(OperatingSystem.IsMacOS()); + Assert.NotEqual(0, Device.Value); + return true; + } +} From 9dc27bad9cdbaf1654158a5a5af057f08ce8708c Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 03:04:16 +0000 Subject: [PATCH 106/134] [Shader] Lower linked shader calls and call records to MSL The Metal translator refused any program the shader call linker had produced, so a caller was compiled alone and its S_SWAPPC_B64 calls were skipped. It now lowers the linker's controls the way the SPIR-V translator does: - SCbranchCallMismatch (ShaderCallMatchControl) compares the caller's address and argument registers with the dispatch's call targets and arguments (shader data), or the link-time constants when the layout pushes none. - ShaderCallEntry writes the return address relocated with the shader base and, for a run-time argument, finds the record's row with a branchless binary search over the dispatch's call record table. - The SEndpgm fault claims an 8-word call fault report (new argument field call_faults: the FaultBuffer binding already carries the device-address reach feedback on Metal) and ends the wave; the SBranch fault of a run-time-record program sets the callee's call mark and returns at once. - S_GETPC_B64 of a linked function reads its pushed call target plus its offset. - An image or sampler a callee reads through its record is the heap element of the row's field, read with no mark; integer images are not declared for records. Programs without calls translate exactly as before (full device suite and goldens pass); new argument fields exist only for linked layouts. The translation payload format moves to 2 because argument layouts can now hold the new field kinds. Tests: MslLinkedCallTests mirrors upstream's LinkedCalls_* device tests (selection by target and argument, SCC across the call, the fault report, 65 records, callee and caller program addresses, moved arguments), a call mark, a callee reading its record's image and sampler through the heap, and the payload round trip. The test harness binds a call fault buffer. ShaderCallsReportTheBackendLimitation asserted the old refusal; it is now ShaderCallsCompileLinkedOrAlone and asserts that the linked program compiles. --- .../Gen5MslArgumentLayout.cs | 28 + .../Gen5MslShaderPayload.cs | 3 +- .../Gen5MslTranslator.Alu.cs | 13 +- .../Gen5MslTranslator.BindlessHeap.cs | 19 +- .../Gen5MslTranslator.Pixel.cs | 5 + .../Gen5MslTranslator.Resources.cs | 67 ++- .../Gen5MslTranslator.ShaderCalls.cs | 303 +++++++++++ .../Gen5MslTranslator.cs | 37 +- .../MetalNative.cs | 9 +- .../MslLinkedCallTests.cs | 478 ++++++++++++++++++ .../MslTranslationTests.cs | 15 +- 11 files changed, 944 insertions(+), 33 deletions(-) create mode 100644 src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.ShaderCalls.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Metal.Tests/MslLinkedCallTests.cs diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslArgumentLayout.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslArgumentLayout.cs index a6b7df656..07c80bcf2 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslArgumentLayout.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslArgumentLayout.cs @@ -37,6 +37,10 @@ public enum MslArgumentFieldKind // The bindless heap's feedback words (BindlessHeap.FeedbackWords): the mark bitsets the shader sets for every // element it reads, then the numeric class of every image element, which the host writes. BindlessHeapFeedback, + // The call fault report of a program linked with its shader calls (Gen5MslArgumentLayout.CallFaultWords): a call + // that finds no record of its target claims it and ends the wave, and the host reports it. Metal-only: the fault + // buffer binding carries the device-address reach feedback, so the report has a pointer of its own. + CallFaults, } // One field of the stage argument buffer: its binding kind, id range and byte range. @@ -64,6 +68,14 @@ public sealed class Gen5MslArgumentLayout /// <summary>The bytes of one bindless heap element: a texture's or sampler's gpuResourceID.</summary> public const int HeapElementBytes = 8; public const string MipStatisticsName = "mip_stats"; + public const string CallRecordsName = "call_records"; + public const string CallRecordWordsName = "call_record_words"; + public const string CallMarksName = "call_marks"; + public const string CallFaultsName = "call_faults"; + /// <summary>The words of the call fault report: a claim word (2 once a wave has reported), then the caller's hash + /// (low, high), the call's pc, the target (low, high), the stage and 1 — the record SPIR-V keeps at the end of its fault + /// buffer.</summary> + public const int CallFaultWords = 8; /// <summary>The bytes of one bindless table entry: gpuResourceID, variant, reserved.</summary> public const int BindlessEntryBytes = 16; @@ -141,6 +153,15 @@ public static Gen5MslArgumentLayout Build(BindingLayout layout) // finest level, clamped and unclamped sample counts of each counter id. Add(binding.Kind, MslArgumentFieldKind.Pointer, MipStatisticsName, 1, ResourceBytes); break; + case DescriptorBindingKind.CallRecords: + // The dispatch's call record rows and their fields' heap elements (BindlessHeap.CallRecordKeyWords). + Add(binding.Kind, MslArgumentFieldKind.Pointer, CallRecordsName, 1, ResourceBytes); + Add(binding.Kind, MslArgumentFieldKind.Word, CallRecordWordsName, 1, WordBytes); + break; + case DescriptorBindingKind.CallMarks: + // The call marks bitset (CallMarks.Bytes) a call to a callee the program lacks sets. + Add(binding.Kind, MslArgumentFieldKind.Pointer, CallMarksName, 1, ResourceBytes); + break; default: Add(binding.Kind, MslArgumentFieldKind.Textures, ImageClassName(binding.Kind), count, ResourceBytes); break; @@ -161,6 +182,13 @@ public static Gen5MslArgumentLayout Build(BindingLayout layout) Add(DescriptorBindingKind.Buffers, MslArgumentFieldKind.BindlessHeapFeedback, HeapFeedbackName, 1, ResourceBytes); } + // A program linked with its shader calls reports a call that found no record (Gen5MslTranslator.ShaderCalls.cs). + // Only a layout that pushes call targets declares it, so no other program's fields move. + if (layout.CallTargetCount != 0 && layout.Find(DescriptorBindingKind.FaultBuffer) is not null) + { + Add(DescriptorBindingKind.FaultBuffer, MslArgumentFieldKind.CallFaults, CallFaultsName, 1, ResourceBytes); + } + // Always last, so adding them never moves a descriptor field. Add(DescriptorBindingKind.Buffers, MslArgumentFieldKind.StepReport, StepReportName, 1, ResourceBytes); Add(DescriptorBindingKind.Buffers, MslArgumentFieldKind.PairLocks, PairLocksName, 1, ResourceBytes); diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslShaderPayload.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslShaderPayload.cs index d8805f266..e3c443025 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslShaderPayload.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslShaderPayload.cs @@ -21,7 +21,8 @@ namespace SharpEmu.ShaderCompiler.Metal; public static class Gen5MslShaderPayload { /// <summary>The layout version; part of the translation cache's stamp.</summary> - public const int FormatVersion = 1; + /// <remarks>Version 2: argument layouts may hold the linked-call field kinds (call records, call marks, call faults).</remarks> + public const int FormatVersion = 2; // "MSLC", little-endian. private const uint Magic = 0x434C534D; diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Alu.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Alu.cs index 393381708..6982858e3 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Alu.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Alu.cs @@ -2175,10 +2175,15 @@ private bool TryEmitScalarAlu( if (instruction.Opcode == "SGetpcB64") { { - // The shader base is pushed per draw; the program offset is added to it. - var (baseLow, baseHigh) = ShaderBaseWords(); - var offset = unchecked(instruction.ProgramOffset + (ulong)(instruction.Words.Count * sizeof(uint))); - var address = Temp("ulong", $"((ulong){baseLow} | ((ulong){baseHigh} << 32)) + {offset}ul"); + // The shader base is pushed per draw; the program offset is added to it. A linked function reads + // its own address from the call targets (Gen5MslTranslator.ShaderCalls.cs). + if (!TryGetFunctionProgramCounter(instruction, out var address)) + { + var (baseLow, baseHigh) = ShaderBaseWords(); + var offset = unchecked(instruction.ProgramOffset + (ulong)(instruction.Words.Count * sizeof(uint))); + address = Temp("ulong", $"((ulong){baseLow} | ((ulong){baseHigh} << 32)) + {offset}ul"); + } + StoreScalar(destination, $"(uint){address}"); StoreScalar(destination + 1, $"(uint)({address} >> 32)"); return true; diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.BindlessHeap.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.BindlessHeap.cs index 5c125e44c..59f9967ef 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.BindlessHeap.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.BindlessHeap.cs @@ -123,9 +123,13 @@ private void MarkHeapElement(int slot, string index) } // The element of one array at index, marked; its handle's validity goes to _heapImageValid. - private string HeapTexture(int slot, string textureType, string index) + private string HeapTexture(int slot, string textureType, string index, bool mark = true) { - MarkHeapElement(slot, index); + if (mark) + { + MarkHeapElement(slot, index); + } + var element = Temp("uint", $"{HeapLiteral((uint)slot * BindlessHeap.Capacity)} + {index}"); var elements = $"{ResourcesName}.{Gen5MslArgumentLayout.HeapElementsName}"; _heapImageValid = Temp("bool", $"{elements}[{element}] != 0ul"); @@ -144,6 +148,17 @@ private string HeapSampler(int slot, HeapRecordUse use) $"((device const {HeapSamplerStruct}*){elements})[{HeapLiteral((uint)slot * BindlessHeap.Capacity)} + {index}].state"); } + // The sampler of a call record's field (Gen5MslTranslator.ShaderCalls.cs): the element the host resolved for the + // record the last entry found, unmarked. + private string CallRecordSampler(CallRecordFieldUse use) + { + var index = CallRecordElement(use.Field); + _usesHeapSamplers = true; + var elements = $"{ResourcesName}.{Gen5MslArgumentLayout.HeapElementsName}"; + return Temp("sampler", + $"((device const {HeapSamplerStruct}*){elements})[{HeapLiteral((uint)use.Slot * BindlessHeap.Capacity)} + {index}].state"); + } + // The float 2D-array class a 3D heap read takes for a record that holds a 2D texture. private static MslImageClass HeapVolumeLayerClass() => new( string.Empty, diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Pixel.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Pixel.cs index fc1321b65..c360a2490 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Pixel.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Pixel.cs @@ -113,6 +113,11 @@ private bool TryEmitImage( return TryEmitHeapImage(instruction, image, heapImage, heapSlot, out error); } + if (IsCallRecordImageAccess(instruction, out var recordImage)) + { + return TryEmitCallRecordImage(instruction, image, recordImage, out error); + } + if (!TryResolveLayoutImage(instruction, image, out texture, out samplerName, out imageClass, out dstSelect, out mipLevel, out compareFunction, out packedFormat, out samplerInfo, out error, out resourceIndex)) { return false; diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs index d6ad1ae8d..3b28f599d 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs @@ -36,14 +36,6 @@ public static bool TryCompileProgram( Gen5MslCodegenOptions? options = null) { shader = default!; - // Call records are the elements a linked callee's records hold (CallRecordSelector), which only linked shader - // calls produce; those are refused below. Guest heap records read the heap (Gen5MslTranslator.BindlessHeap.cs). - if (request.CallRecordImageByMemoryIndex.Count != 0 || request.CallRecordSamplerByMemoryIndex.Count != 0) - { - error = "Metal does not support call record descriptors."; - return false; - } - // The guest mesh stage (Vulkan's task/mesh path) has no MSL emission; the Metal mesh path // compiles NGG primitive shaders as Vertex requests with PrimitiveShader set instead. if (request.Stage == ShaderStage.Mesh) @@ -51,13 +43,27 @@ public static bool TryCompileProgram( error = "Metal does not support mesh shaders."; return false; } - // A program the shader-call linker rewrote carries call dispatch the MSL emitter cannot - // express. An unlinked S_SWAPPC_B64 keeps today's behaviour (TryEmitScalar64 skips it), - // and an explicit branch target alone (ShaderLinkedBranchControl) compiles. - if (request.Program.Instructions.Any(instruction => - instruction.Control is ShaderCallMatchControl or ShaderCallEntryControl or ShaderCallFaultControl)) + // A program the shader-call linker rewrote reads its callees' addresses and its records' arguments from the + // dispatch (Gen5MslTranslator.ShaderCalls.cs): the layout holds one pair per callee and per argument. An unlinked + // S_SWAPPC_B64 (a backend that does not link) is the caller compiled alone: TryEmitScalar64 skips it. + var callArguments = Gen5ShaderCallLinker.CallEntryArguments(request.Program); + if (request.Bindings.CallArgumentCount != 0 && callArguments.Length != request.Bindings.CallArgumentCount) { - error = "Metal does not support linked shader calls."; + error = $"the layout holds {request.Bindings.CallArgumentCount} call arguments for {callArguments.Length}"; + return false; + } + + var callTargets = Gen5ShaderCallLinker.CallTargets(request.Program); + if (request.Bindings.CallTargetCount != 0 && callTargets.Length != request.Bindings.CallTargetCount) + { + error = $"the layout holds {request.Bindings.CallTargetCount} call targets for {callTargets.Length} callees"; + return false; + } + + if ((request.CallRecordImageByMemoryIndex.Count != 0 || request.CallRecordSamplerByMemoryIndex.Count != 0) && + (request.Bindings.Find(DescriptorBindingKind.CallRecords) is null || !request.Bindings.UsesBindlessHeap)) + { + error = "the layout of a program that reads call records holds no call records or bindless heap"; return false; } try @@ -323,6 +329,12 @@ private void DeclareLayoutBindings() case DescriptorBindingKind.MipStatistics: _hasMipStatistics = true; break; + case DescriptorBindingKind.CallRecords: + _hasCallRecords = true; + break; + case DescriptorBindingKind.CallMarks: + _hasCallMarks = true; + break; default: DeclareImageClass(binding, info); break; @@ -475,7 +487,7 @@ private void EmitResourceStruct(StringBuilder source) MslArgumentFieldKind.StepReport or MslArgumentFieldKind.PairLocks => $"device atomic_uint* {field.Name}", MslArgumentFieldKind.BindlessImageTables => $"array<device const {BindlessEntryStruct}*, {field.Count}> {field.Name}", MslArgumentFieldKind.BindlessHeapElements => $"device const ulong* {field.Name}", - MslArgumentFieldKind.BindlessHeapFeedback => $"device atomic_uint* {field.Name}", + MslArgumentFieldKind.BindlessHeapFeedback or MslArgumentFieldKind.CallFaults => $"device atomic_uint* {field.Name}", _ => $"uint {field.Name}", }; source.AppendLine($" {declaration} [[id({field.FirstId})]];"); @@ -536,7 +548,8 @@ private static string BindlessTypedStruct(string textureType) DescriptorBindingKind.DeviceAddressPageTable => "device const Gen5AddressRange*", DescriptorBindingKind.FlattenedResourceTable or DescriptorBindingKind.ShaderData => _options.UniformTablesInConstantSpace ? "constant uint*" : "device const uint*", - DescriptorBindingKind.MipStatistics => "device atomic_uint*", + DescriptorBindingKind.MipStatistics or DescriptorBindingKind.CallMarks => "device atomic_uint*", + DescriptorBindingKind.CallRecords => "device const uint*", _ => "device uint*", }; @@ -608,6 +621,12 @@ private void EmitLayoutInitialState(StringBuilder source) { source.AppendLine($" uint {scratch} = 0u;"); } + + if (_hasCallRecords && UsesCallRecordRow) + { + // No row until a run-time entry finds one: a record read before it takes the null element. + source.AppendLine($" uint {CallRecordRowName} = 0xFFFFFFFFu;"); + } } // One dword of this stage's block: from push data, or the shader-data buffer when spilled. @@ -2415,6 +2434,10 @@ private bool TryResolveLayoutImage( HeapRecordUse heapImage = default; var fromHeap = fixedElement is null && heapSlot >= 0 && _heapRecordIndex is not null && request.HeapImageByMemoryIndex.TryGetValue(memoryIndex, out heapImage); + // A call record's image is the element the host resolved for the record its callee's entry found + // (Gen5MslTranslator.ShaderCalls.cs), read without a mark. + var fromCallRecord = !fromHeap && fixedElement is null && heapSlot >= 0 && _callRecordElement is not null && + request.CallRecordImageByMemoryIndex.ContainsKey(memoryIndex); if (heapVolumeLayers) { if (!fromHeap || heapSlot != BindlessHeap.VolumeSlot) @@ -2444,6 +2467,10 @@ private bool TryResolveLayoutImage( { texture = HeapTexture(heapSlot, imageClass.TextureType, HeapImageIndex(_heapRecordIndex!, heapSlot, heapNumericClass)); } + else if (fromCallRecord) + { + texture = HeapTexture(heapSlot, imageClass.TextureType, _callRecordElement!, mark: false); + } else if (imageInfo.BindlessSlot != DescriptorConstants.NoIndex) { if (fixedElement is null || _bindlessAccess is not { } bindless) @@ -2470,6 +2497,14 @@ private bool TryResolveLayoutImage( var heapSamplerIndex = request.Resources.SamplerByMemoryIndex.TryGetValue(memoryIndex, out var mapped) ? mapped : entry.Sampler; samplerInfo = heapSamplerIndex < (uint)info.Samplers.Count ? info.Samplers[(int)heapSamplerIndex] : null; } + else if (UsesSampler(instruction.Opcode) && fixedElement is null && + request.CallRecordSamplerByMemoryIndex.TryGetValue(memoryIndex, out var recordSampler)) + { + // A call record's sampler is the element of its record's field in the sampler array of its kind. + samplerName = CallRecordSampler(recordSampler); + var recordSamplerIndex = request.Resources.SamplerByMemoryIndex.TryGetValue(memoryIndex, out var mapped) ? mapped : entry.Sampler; + samplerInfo = recordSamplerIndex < (uint)info.Samplers.Count ? info.Samplers[(int)recordSamplerIndex] : null; + } else if (UsesSampler(instruction.Opcode)) { if (!_hasSamplers) diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.ShaderCalls.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.ShaderCalls.cs new file mode 100644 index 000000000..f47714602 --- /dev/null +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.ShaderCalls.cs @@ -0,0 +1,303 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Globalization; +using System.Text; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.ShaderCompiler.Metal; + +// Linked shader calls (Gen5ShaderCallLinker). The linker inlines every callee of a call site into the caller: a test per +// target (SCbranchCallMismatch, ShaderCallMatchControl) that branches past the target's copy unless the caller's address +// and argument registers name it, the copy's entry (ShaderCallEntryControl) that writes the return address, the copy with +// its return turned into a branch, and after the last copy the site's fault (ShaderCallFaultControl). The program is +// ordinary control flow over scalar registers, so MSL needs no function pointers: the tests are block terminators, the +// entry an instruction. The callees' addresses and the records' arguments come from the dispatch's shader data +// (BindingLayout.CallTargetsDword, CallArgumentsDword), so one library serves every placement of the code and tables. +// +// With run-time call records (ShaderCallEntryControl.RuntimeArgument) a site holds one copy per callee for every record of +// it: the entry finds the record's row among the dispatch's call records (DescriptorBindingKind.CallRecords), and the +// images and samplers the copy reads through the record's argument are the heap elements the host resolved for that row. +// A call whose callee the program lacks marks it (DescriptorBindingKind.CallMarks) and returns at once. +// +// The SPIR-V translator also merges the copies of a callee into one body and outlines compute bodies into functions +// (Gen5SpirvTranslator.SharedCalls.cs) to bound its driver's compile time; those rewrites keep the linker's run-time +// behaviour, and this translator emits the linker's form as it is. +public static partial class Gen5MslTranslator +{ + private sealed partial class CompilationContext + { + private const string CallRecordRowName = "sharpemu_call_record_row"; + private const string CallRecordSearchName = "sharpemu_search_call_records"; + private const string CallRecordElementName = "sharpemu_call_record_element"; + + private bool _hasCallRecords; + private bool _hasCallMarks; + private bool _usesCallRecordSearch; + private Dictionary<ulong, int>? _callTargetSlots; + private Dictionary<ulong, int>? _callArgumentSlots; + + // The element index of the call record image access being emitted (its row's field), for TryResolveLayoutImage. + private string? _callRecordElement; + + // A program whose images or samplers a call record holds keeps the row its last entry found. + private bool UsesCallRecordRow => + _request.CallRecordImageByMemoryIndex.Count != 0 || _request.CallRecordSamplerByMemoryIndex.Count != 0; + + private static string HexLiteral(uint value) => "0x" + value.ToString("X", CultureInfo.InvariantCulture) + "u"; + + // The slot of each callee among the call targets and of each nonzero argument among the call arguments, when the + // layout pushes them (as the SPIR-V translator takes them from the linked program before its bodies are shared). + private void PlanShaderCalls() + { + var layout = _request.Bindings; + if (layout.CallTargetCount != 0) + { + _callTargetSlots = []; + foreach (var target in Gen5ShaderCallLinker.CallTargets(_request.Program)) + { + _callTargetSlots.TryAdd(target, _callTargetSlots.Count); + } + } + + if (layout.CallArgumentCount != 0) + { + _callArgumentSlots = []; + foreach (var argument in Gen5ShaderCallLinker.CallEntryArguments(_request.Program)) + { + _callArgumentSlots.TryAdd(argument, _callArgumentSlots.Count); + } + } + } + + // A 64-bit value the dispatch pushes as two shader data dwords. + private string ShaderDataPair(uint dword) => + $"((ulong){ShaderDataDword(dword)} | ((ulong){ShaderDataDword(dword + 1)} << 32))"; + + // A callee's address: the dispatch's call target for it, or its link-time address without pushed targets. + private string CallTargetExpression(ulong address) => + _callTargetSlots is not null && _callTargetSlots.TryGetValue(address, out var slot) + ? ShaderDataPair(_request.Bindings.CallTargetsDword + (uint)slot * 2) + : $"{address.ToString(CultureInfo.InvariantCulture)}ul"; + + private string ScalarPair(uint register) => + $"((ulong){ScalarExpression(register)} | ((ulong){ScalarExpression(register + 1)} << 32))"; + + // Whether a test's record argument matches the caller's argument registers: the dispatch's argument for its slot, + // a null argument as the constant, and every argument for a callee whose records are all run-time. + private string CallArgumentCondition(uint register, ulong argument, bool runtime) + { + if (runtime) + { + return "true"; + } + + if (argument != 0 && _callArgumentSlots is not null && _callArgumentSlots.TryGetValue(argument, out var slot)) + { + var dword = _request.Bindings.CallArgumentsDword + (uint)slot * 2; + return $"({ScalarExpression(register)} == {ShaderDataDword(dword)} && " + + $"{ScalarExpression(register + 1)} == {ShaderDataDword(dword + 1)})"; + } + + return $"({ScalarExpression(register)} == {HexLiteral((uint)argument)} && " + + $"{ScalarExpression(register + 1)} == {HexLiteral((uint)(argument >> 32))})"; + } + + // The branch of a site's test: taken (past the target's copy) unless the caller names the target and argument. + private string CallMismatchCondition(ShaderCallMatchControl call) => + $"!({ScalarPair(call.AddressRegister)} == {CallTargetExpression(call.Address)} && " + + $"{CallArgumentCondition(call.ArgumentRegister, call.Argument, call.RuntimeArgument)})"; + + // S_GETPC_B64 of a linked function: its address from the call targets, plus its offset and the instruction size. + private bool TryGetFunctionProgramCounter(Gen5ShaderInstruction instruction, out string address) + { + address = string.Empty; + if (instruction.Control is not ShaderFunctionPcControl function || _callTargetSlots is null) + { + return false; + } + + var offset = unchecked(function.FunctionOffset + (ulong)(instruction.Words.Count * sizeof(uint))); + address = Temp("ulong", $"{CallTargetExpression(function.FunctionAddress)} + {offset.ToString(CultureInfo.InvariantCulture)}ul"); + return true; + } + + // A copy's entry: the return address, relocated with the dispatch's shader base as the caller's code is, into the + // return register pair; with a run-time argument, the row of the record the caller's argument names. + private void EmitShaderCallEntry(ShaderCallEntryControl call) + { + string address; + if (_request.Bindings.UsesShaderBase) + { + var (low, high) = ShaderBaseWords(); + var offset = unchecked(call.ReturnAddress - _request.Program.Address); + address = Temp("ulong", $"((ulong){low} | ((ulong){high} << 32)) + {offset.ToString(CultureInfo.InvariantCulture)}ul"); + } + else + { + address = Temp("ulong", $"{call.ReturnAddress.ToString(CultureInfo.InvariantCulture)}ul"); + } + + StoreScalar(call.ReturnRegister, $"(uint){address}"); + StoreScalar(call.ReturnRegister + 1, $"(uint)({address} >> 32)"); + if (!call.RuntimeArgument || !_hasCallRecords || !UsesCallRecordRow) + { + return; + } + + var callee = _callTargetSlots is { } slots && slots.TryGetValue(call.Callee, out var slot) ? (uint)slot : uint.MaxValue; + _usesCallRecordSearch = true; + Line($"{CallRecordRowName} = {CallRecordSearchName}({ResourcesName}.{Gen5MslArgumentLayout.CallRecordsName}, " + + $"{ResourcesName}.{Gen5MslArgumentLayout.CallRecordWordsName}, {ScalarExpression(call.ArgumentRegister)}, " + + $"{ScalarExpression(call.ArgumentRegister + 1)}, {HexLiteral(callee)});"); + } + + // The SEndpgm fault of a program linked per record: the first wave to get here records the call (the caller, the + // call's pc and target, the stage) for the host, then the wave ends. + private void EmitShaderCallFault(ShaderCallFaultControl call) + { + if (_argumentLayout?.Fields.Any(static field => field.FieldKind == MslArgumentFieldKind.CallFaults) != true) + { + return; + } + + var faults = $"{ResourcesName}.{Gen5MslArgumentLayout.CallFaultsName}"; + uint[] values = [(uint)_request.Hash, (uint)(_request.Hash >> 32), call.CallPc]; + Line($"if ({faults} != nullptr)"); + Line("{"); + _indent++; + var expected = Temp("uint", "0u"); + Line($"if (atomic_compare_exchange_weak_explicit(&{faults}[0], &{expected}, 2u, memory_order_relaxed, memory_order_relaxed))"); + Line("{"); + _indent++; + string[] words = + [ + HexLiteral(values[0]), HexLiteral(values[1]), HexLiteral(values[2]), + ScalarExpression(call.AddressRegister), ScalarExpression(call.AddressRegister + 1), + HexLiteral((uint)_request.Stage), "1u", + ]; + for (var index = 0; index < words.Length; index++) + { + Line($"atomic_store_explicit(&{faults}[{index + 1}], {words[index]}, memory_order_relaxed);"); + } + + _indent--; + Line("}"); + _indent--; + Line("}"); + } + + // A run-time-record call whose callee the program lacks sets the callee's bit (CallMarks.Bit of its target and this + // program's hash) before it returns at once; a plain read first keeps a marked callee from repeating the atomic. + private void EmitCallMark(ShaderCallFaultControl call) + { + if (!_hasCallMarks) + { + return; + } + + var marks = $"{ResourcesName}.{Gen5MslArgumentLayout.CallMarksName}"; + var value = Temp("uint", + $"{ScalarExpression(call.AddressRegister)} ^ ({ScalarExpression(call.AddressRegister + 1)} * 0x9E3779B1u) ^ " + + HexLiteral(CallMarks.Seed(_request.Hash))); + value = Temp("uint", $"({value} ^ ({value} >> 16u)) * 0x7FEB352Du"); + value = Temp("uint", $"({value} ^ ({value} >> 15u)) * 0x846CA68Bu"); + var bit = Temp("uint", $"({value} ^ ({value} >> 16u)) & {HexLiteral(CallMarks.Bits - 1)}"); + var mask = Temp("uint", $"1u << ({bit} & 31u)"); + Line($"if ((atomic_load_explicit(&{marks}[{bit} >> 5u], memory_order_relaxed) & {mask}) == 0u)"); + Line("{"); + _indent++; + Line($"atomic_fetch_or_explicit(&{marks}[{bit} >> 5u], {mask}, memory_order_relaxed);"); + _indent--; + Line("}"); + } + + // The heap element of one field of the record the last entry found, or the null element. + private string CallRecordElement(int field) + { + if (!_hasCallRecords || !UsesCallRecordRow) + { + return HeapLiteral(BindlessHeap.CallRecordNullIndex); + } + + return Temp("uint", $"{CallRecordElementName}({ResourcesName}.{Gen5MslArgumentLayout.CallRecordsName}, " + + $"{ResourcesName}.{Gen5MslArgumentLayout.CallRecordWordsName}, {CallRecordRowName}, {(uint)field}u)"); + } + + // The image access whose image a call record holds: its field's element and the heap array of its class. + private bool IsCallRecordImageAccess(Gen5ShaderInstruction instruction, out CallRecordFieldUse use) + { + use = default; + return _request.Memory.TryGetIndex(instruction.Pc, 0, out var memoryIndex) && + _request.CallRecordImageByMemoryIndex.TryGetValue(memoryIndex, out use) && use.Slot >= 0; + } + + // A call record image read: the element of the record's field, read through the float declaration of its class + // with no mark (the host resolved it with the record); a null element reads zero. + private bool TryEmitCallRecordImage(Gen5ShaderInstruction instruction, Gen5ImageControl image, CallRecordFieldUse use, out string error) + { + _callRecordElement = CallRecordElement(use.Field); + try + { + return TryEmitHeapRead(instruction, image, ImageNumericClass.Float, layers: false, out error); + } + finally + { + _callRecordElement = null; + _heapImageValid = null; + } + } + + // The row search every run-time entry calls and the field lookup of a record read: the port of the SPIR-V + // translator's searchCallRecords (a branchless binary search for the first row not below the key, which it + // returns when the row holds the key) and CallRecordElement. Every word they read lies inside the buffer. + private void EmitShaderCallPrelude(StringBuilder source) + { + if (!_hasCallRecords || !UsesCallRecordRow) + { + return; + } + + var keyWords = HeapLiteral(BindlessHeap.CallRecordKeyWords); + var nullIndex = HeapLiteral(BindlessHeap.CallRecordNullIndex); + source.AppendLine($"static inline uint {CallRecordElementName}(device const uint* records, uint words, uint row, uint field)"); + source.AppendLine("{"); + source.AppendLine(" uint count = words != 0u ? records[0] : 0u;"); + source.AppendLine(" bool found = row < count;"); + source.AppendLine(" uint safe = found ? row : 0u;"); + source.AppendLine($" uint first_index = 1u + count * {keyWords} + safe;"); + source.AppendLine(" uint first = words != 0u ? records[first_index < words ? first_index : 0u] : 0u;"); + source.AppendLine(" uint index = first + field;"); + source.AppendLine(" uint element = words != 0u ? records[index < words ? index : 0u] : 0u;"); + source.AppendLine($" return found ? min(element, {nullIndex}) : {nullIndex};"); + source.AppendLine("}"); + source.AppendLine(); + if (!_usesCallRecordSearch) + { + return; + } + + source.AppendLine($"static uint {CallRecordSearchName}(device const uint* records, uint words, uint low, uint high, uint callee)"); + source.AppendLine("{"); + source.AppendLine($" uint count = words != 0u ? min(records[0], (words - 1u) / {keyWords}) : 0u;"); + source.AppendLine(" uint position = 0u;"); + source.AppendLine($" for (uint step = {HeapLiteral((BindlessHeap.CallRecordMaximumRows + 1) >> 1)}; step != 0u; step >>= 1u)"); + source.AppendLine(" {"); + source.AppendLine(" uint probe = position + step;"); + source.AppendLine(" bool in_range = probe <= count;"); + source.AppendLine($" uint key = 1u + (in_range ? probe - 1u : 0u) * {keyWords};"); + source.AppendLine(" uint row_low = in_range ? records[key] : 0u;"); + source.AppendLine(" uint row_high = in_range ? records[key + 1u] : 0u;"); + source.AppendLine(" uint row_callee = in_range ? records[key + 2u] : 0u;"); + source.AppendLine(" bool below = row_high < high || (row_high == high && (row_low < low || (row_low == low && row_callee < callee)));"); + source.AppendLine(" position = in_range && below ? probe : position;"); + source.AppendLine(" }"); + source.AppendLine(" bool found = position < count;"); + source.AppendLine($" uint key = 1u + (found ? position : 0u) * {keyWords};"); + source.AppendLine(" bool equal = found && records[key] == low && records[key + 1u] == high && records[key + 2u] == callee;"); + source.AppendLine(" return equal ? position : 0xFFFFFFFFu;"); + source.AppendLine("}"); + source.AppendLine(); + } + } +} diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs index 03e6e752b..4692de4c6 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs @@ -645,6 +645,7 @@ public bool TryCompile(out Gen5MslShader shader, out string error) { DeclareLayoutBindings(); + PlanShaderCalls(); } foreach (var instruction in _request.Program.Instructions) @@ -926,6 +927,7 @@ private void EmitModule(StringBuilder source, IReadOnlyList<ShaderBlock> blocks) // A request binds one argument buffer per stage; its lengths replace the uniforms. EmitResourceStruct(source); + EmitShaderCallPrelude(source); AppendTrailingPreludes(source, preludes, _options.BranchlessDwordLoads, _options.CheapFloatWrappers); if (UsesMipStatisticsConstant) @@ -2011,12 +2013,23 @@ private bool TryEmitBlockBodyCore( if (instruction.Opcode == "SEndpgm") { + if (instruction.Control is ShaderCallFaultControl callFault) + { + EmitShaderCallFault(callFault); + } + terminator = BlockTerminator.Exit("active = false;"); return true; } if (instruction.Opcode == "SBranch") { + // A run-time-record call whose callee the program lacks returns at once, marked for the host. + if (instruction.Control is ShaderCallFaultControl { ReturnPc: not null } returnAtOnce) + { + EmitCallMark(returnAtOnce); + } + // A branch to (or past) the program's end is an exit — the // pattern sprite alpha-kill shaders use to skip their tail. if (IsExitBranchTarget(instructions, instruction)) @@ -2042,7 +2055,12 @@ private bool TryEmitBlockBodyCore( if (instruction.Opcode.StartsWith("SCbranch", StringComparison.Ordinal)) { - if (!TryGetBranchCondition(instruction.Opcode, out var condition)) + string condition; + if (instruction.Control is ShaderCallMatchControl callMatch) + { + condition = CallMismatchCondition(callMatch); + } + else if (!TryGetBranchCondition(instruction.Opcode, out condition)) { error = $"unsupported conditional branch {instruction.Opcode}"; return false; @@ -2237,6 +2255,12 @@ private bool TryEmitInstruction( { error = string.Empty; BeginInstruction(instruction); + if (instruction.Control is ShaderCallEntryControl callEntry) + { + EmitShaderCallEntry(callEntry); + return true; + } + switch (instruction.Opcode) { // No shader trap handler is installed, so S_TRAP has no effect. @@ -5075,6 +5099,17 @@ private static bool TryGetBranchTargetPc( targetPc = linked.TargetPc; return true; } + // A site's test of one target branches past the target's copy; a run-time-record fault returns from the call. + if (instruction.Control is ShaderCallMatchControl call) + { + targetPc = call.TargetPc; + return true; + } + if (instruction.Control is ShaderCallFaultControl { ReturnPc: { } returnPc }) + { + targetPc = returnPc; + return true; + } if (instruction.Encoding != Gen5ShaderEncoding.Sopp || instruction.Words.Count == 0) { diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.cs index 186803985..0252f8d17 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalNative.cs @@ -237,7 +237,8 @@ public static bool TryExecuteWithArgumentBuffer( IReadOnlyList<DeviceTable>? bindlessTables = null, Func<DescriptorBindingKind, nint>? textureOfClass = null, IReadOnlyList<(uint Index, uint Value)>? constants = null, - (DeviceTable Elements, DeviceTable Feedback)? heap = null) + (DeviceTable Elements, DeviceTable Feedback)? heap = null, + DeviceTable? callFaults = null) { result = []; stepCapHits = 0; @@ -304,6 +305,11 @@ public static bool TryExecuteWithArgumentBuffer( case MslArgumentFieldKind.PairLocks: BitConverter.TryWriteBytes(arguments.AsSpan((int)field.ByteOffset), pairLocksAddress); break; + case MslArgumentFieldKind.CallFaults: + // The call fault report of a linked program, or none (the shader skips the report). + BitConverter.TryWriteBytes(arguments.AsSpan((int)field.ByteOffset), + callFaults is { } faults ? SendULong(faults.Buffer, Selector("gpuAddress")) : 0ul); + break; case MslArgumentFieldKind.Pointer: // A read-only table the host fills before the encode: the user // data words, the flattened resource table, the address ranges. @@ -342,6 +348,7 @@ public static bool TryExecuteWithArgumentBuffer( .. heap is { } heapTables ? (nint[])[heapTables.Elements.Buffer, .. heapTables.Elements.Residents, heapTables.Feedback.Buffer] : [], + .. callFaults is { } faultTable ? (nint[])[faultTable.Buffer] : [], .. textureOfClass is null ? Array.Empty<nint>() : layout.Fields .Where(static field => field.FieldKind == MslArgumentFieldKind.Textures) .Select(field => textureOfClass(field.Kind)).Distinct(), diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslLinkedCallTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslLinkedCallTests.cs new file mode 100644 index 000000000..eca17e853 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslLinkedCallTests.cs @@ -0,0 +1,478 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.ShaderCompiler.Metal.Tests; + +/// <summary> +/// Linked shader calls on Metal (Gen5MslTranslator.ShaderCalls.cs): the linker's tests select a callee by the caller's +/// address and argument registers against the dispatch's call targets and arguments, an entry writes the return address +/// relocated with the shader base, a call no record names reports a call fault and ends the wave, a run-time-record +/// program marks a callee it lacks, and a callee reads an image its record holds through the bindless heap. The MSL +/// twins of the SPIR-V LinkedCalls_* device tests (tests/SharpEmu.Libs.Tests/Gpu/Vulkan/DeviceAddressShaderTests.cs). +/// </summary> +public sealed class MslLinkedCallTests(ITestOutputHelper output) +{ + private const ulong Hash = 0x1234_5678_9ABC_DEF0; + private const uint UserDataCount = 16; + private const uint ResultRegister = 4; + private const int ResultBytes = 256; + private const uint NullOperand = 125; + + // Instruction builders: the shapes of ResourceTestProgram (tests/SharpEmu.ShaderCompiler.Tests), which this project + // does not reference. + private static Gen5Operand Operand(uint value) => + value <= 64 ? Gen5Operand.Source(128 + value) : new Gen5Operand(Gen5OperandKind.LiteralConstant, value); + + private static Gen5ShaderProgram Program(params Gen5ShaderInstruction[] instructions) => new(0, instructions); + + private static Gen5ShaderInstruction EndProgram(uint pc) => + new(pc, Gen5ShaderEncoding.Sopp, "SEndpgm", [0xBF810000], [], [], null); + + private static Gen5ShaderInstruction Nop(uint pc) => + new(pc, Gen5ShaderEncoding.Sopp, "SNop", [0xBF800000], [], [], null); + + private static Gen5ShaderInstruction MoveScalar(uint pc, uint destination, uint value) => + new(pc, Gen5ShaderEncoding.Sop1, "SMovB32", [0u], [Operand(value)], [Gen5Operand.Scalar(destination)], null); + + private static Gen5ShaderInstruction Sop1(uint pc, string opcode, uint destination, Gen5Operand source) => + new(pc, Gen5ShaderEncoding.Sop1, opcode, [0u], [source], [Gen5Operand.Scalar(destination)], null); + + private static Gen5ShaderInstruction Sop2(uint pc, string opcode, uint destination, Gen5Operand source0, Gen5Operand source1) => + new(pc, Gen5ShaderEncoding.Sop2, opcode, [0u], [source0, source1], [Gen5Operand.Scalar(destination)], null); + + private static Gen5ShaderInstruction Sopc(uint pc, string opcode, Gen5Operand source0, Gen5Operand source1) => + new(pc, Gen5ShaderEncoding.Sopc, opcode, [0u], [source0, source1], [], null); + + private static Gen5ShaderInstruction Vop1(uint pc, string opcode, uint destination, Gen5Operand source) => + new(pc, Gen5ShaderEncoding.Vop1, opcode, [0u], [source], [Gen5Operand.Vector(destination)], null); + + private static Gen5ShaderInstruction Vop2(uint pc, string opcode, uint destination, Gen5Operand source0, Gen5Operand source1) => + new(pc, Gen5ShaderEncoding.Vop2, opcode, [0u], [source0, source1], [Gen5Operand.Vector(destination)], null); + + private static Gen5ShaderInstruction ScalarLoad(uint pc, uint baseRegister, uint destination, uint count, int immediateOffset = 0) => + new(pc, Gen5ShaderEncoding.Smem, count == 1 ? "SLoadDword" : $"SLoadDwordx{count}", [0u, 0u], + [Gen5Operand.Scalar(baseRegister), Gen5Operand.Source(NullOperand)], + Enumerable.Range((int)destination, (int)count).Select(index => Gen5Operand.Scalar((uint)index)).ToArray(), + new Gen5ScalarMemoryControl(count, immediateOffset, null)); + + // image_sample_lz v[4:7], v[0:1], T# s[resource], S# s[sampler] dmask:0xf dim:2D. + private static Gen5ShaderInstruction ImageSample(uint pc, uint resourceRegister, uint samplerRegister) + { + var control = new Gen5ImageControl(0xF, 0, [0u, 1u, 2u], 4, resourceRegister, samplerRegister, 1, false, Glc: false, Slc: false, A16: false, D16: false); + return new Gen5ShaderInstruction(pc, Gen5ShaderEncoding.Mimg, "ImageSampleLz", [0u, 0u], + [Gen5Operand.Vector(0), Gen5Operand.Scalar(resourceRegister), Gen5Operand.Scalar(samplerRegister)], [Gen5Operand.Vector(4)], control); + } + + private static Gen5ShaderInstruction BufferAccess(uint pc, string opcode, uint resourceRegister, uint dwords = 1, uint vectorData = 4, + bool offsetEnabled = false, uint vectorAddress = 0) + { + var data = Enumerable.Range((int)vectorData, (int)dwords).Select(index => Gen5Operand.Vector((uint)index)).ToArray(); + return new Gen5ShaderInstruction(pc, Gen5ShaderEncoding.Mubuf, opcode, [0u, 0u], + [Gen5Operand.Vector(vectorAddress), Gen5Operand.Scalar(resourceRegister), Gen5Operand.Source(NullOperand), .. data], [], + new Gen5BufferMemoryControl(dwords, vectorAddress, vectorData, resourceRegister, 0, false, offsetEnabled, Glc: false, Slc: false)); + } + + // The request the pipeline cache builds for a linked program: the call arguments and targets pushed as shader data. + private static ShaderCompileRequest Request(Gen5ShaderProgram program, bool bindlessHeap = false, bool callRecords = false, bool callMarks = false) + { + var plan = ShaderResourcePlan.Extract(program, ShaderStage.Compute, Hash, 0, UserDataCount, + bindlessHeap: bindlessHeap, callRecords: callRecords, callMarks: callMarks, scalarDataOnDevice: false); + // The default specialization, as upstream's ResourceTestProgram.Prepare: the result V# is a user data buffer. + var specialization = ResourceSpecialization.Default(plan.Info); + var resources = ResourceMaterializer.ApplyTo(plan, specialization); + var layout = BindingLayout.Allocate( + resources.Info, + BindingLayout.CollectUserDataRegisters(program, 0, UserDataCount, plan.Graph.ExcludedUserDataRegisters), + BindingLayout.UsesGlobalDataShare(program), + ShaderCompileRequest.RequiresFlattenedTable(plan, resources), + BindingLayout.ReadsShaderBase(program), + pushDataStartDword: 0, + callArgumentCount: BindingLayout.CountCallArguments(program), + callTargetCount: BindingLayout.CountCallTargets(program)); + return new ShaderCompileRequest(plan, resources, layout) { WaveSize = 32, LocalSizeX = 32 }; + } + + private static Gen5MslShader Compile(ShaderCompileRequest request) + { + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error), error); + return shader; + } + + // One dispatch of a linked program: the shader data the host pushes (the shader base and the call data), the result + // buffer, and the call fault report read back. + private sealed class Run + { + private readonly Gen5MslShader _shader; + private readonly nint _library; + private byte[] _result = []; + + public Run(Gen5ShaderProgram program, bool bindlessHeap = false, bool callRecords = false, bool callMarks = false) + { + Request = MslLinkedCallTests.Request(program, bindlessHeap, callRecords, callMarks); + _shader = Compile(Request); + Assert.True(MetalNative.TryCompileLibrary(_shader.Source, out _library, out var error), $"{error}\n{_shader.Source}"); + } + + public ShaderCompileRequest Request { get; } + + public uint[] Faults { get; private set; } = []; + + public void Dispatch(uint threads = 1, ulong shaderBase = 0, ulong[]? callTargets = null, ulong[]? callArguments = null, + IReadOnlyList<DeviceTable>? tables = null, (DeviceTable Elements, DeviceTable Feedback)? heap = null) + { + var layout = Request.Bindings; + var shaderData = new uint[layout.ShaderDataDwordCount]; + if (layout.UsesShaderBase) + { + shaderData[layout.ShaderBaseDword] = (uint)shaderBase; + shaderData[layout.ShaderBaseDword + 1] = (uint)(shaderBase >> 32); + } + + var offset = (int)layout.CallArgumentsDword; + foreach (var address in (callArguments ?? Gen5ShaderCallLinker.CallEntryArguments(Request.Program)) + .Concat(callTargets ?? Gen5ShaderCallLinker.CallTargets(Request.Program))) + { + shaderData[offset++] = (uint)address; + shaderData[offset++] = (uint)(address >> 32); + } + + var push = new byte[PushData.ByteSize]; + var allTables = (tables ?? []).ToList(); + if (layout.UsesPushData) + { + for (var index = 0; index < shaderData.Length; index++) + { + BinaryPrimitives.WriteUInt32LittleEndian(push.AsSpan((int)(layout.PushDataStartDword + index) * 4), shaderData[index]); + } + } + else + { + allTables.Add(MetalNative.CreateWordTable(DescriptorBindingKind.ShaderData, shaderData)); + } + + var faults = MetalNative.CreateWordTable(DescriptorBindingKind.FaultBuffer, new uint[Gen5MslArgumentLayout.CallFaultWords]); + Assert.True(MetalNative.TryExecuteWithArgumentBuffer(_library, _shader.EntryPoint, new byte[ResultBytes], push, + _shader.ArgumentLayout!, threads, out _result, out _, out var error, tables: allTables, heap: heap, callFaults: faults), error); + Faults = MetalNative.ReadWords(faults); + } + + public uint Word(int offset) => BinaryPrimitives.ReadUInt32LittleEndian(_result.AsSpan(offset)); + } + + private bool SkipWithoutMetalDevice() + { + if (MetalNative.IsAvailable) return false; + Assert.False(OperatingSystem.IsMacOS() && Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") == "1", + "The required gate cannot run linked calls without a Metal device."); + output.WriteLine("No Metal device on this host; linked calls skipped."); + return true; + } + + private static uint[] FaultRecord(ulong hash, uint callPc, uint addressLow, uint addressHigh) => + [2, (uint)hash, (uint)(hash >> 32), callPc, addressLow, addressHigh, (uint)ShaderStage.Compute, 1]; + + // A program linked per record selects a target by its address and argument, keeps SCC across the call, and reports a + // call that no record names (the target, the argument or the high address word differ) before it ends the wave. + [Theory] + [InlineData(0x2000u, 0u, 10u, 77u)] + [InlineData(0x2000u, 0u, 11u, 99u)] + [InlineData(0x2000u, 0u, 12u, 0u)] + [InlineData(0x3000u, 0u, 10u, 55u)] + [InlineData(0x2000u, 1u, 10u, 0u)] + public void SelectArgumentsPreserveSccAndReportUnknownTargets(uint addressLow, uint addressHigh, uint argument, uint expected) + { + var caller = Program(MoveScalar(0, 14, addressLow), MoveScalar(4, 15, addressHigh), + MoveScalar(8, 16, argument), MoveScalar(12, 17, 0), + Sopc(16, "SCmpEqU32", Operand(1), Operand(1)), + Sop1(20, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + Sop2(24, "SCselectB32", 8, Operand(123), Operand(9)), + Vop1(28, "VMovB32", 2, Gen5Operand.Scalar(8)), + Vop1(32, "VMovB32", 3, Gen5Operand.Scalar(14)), + Vop1(36, "VMovB32", 4, Gen5Operand.Scalar(15)), + BufferAccess(40, "BufferStoreDwordx4", ResultRegister, dwords: 4, vectorData: 1), EndProgram(48)); + Gen5ShaderProgram Function(uint value) => Program( + Vop1(0, "VMovB32", 1, Operand(value)), + Sop1(4, "SSetpcB64", 0, Gen5Operand.Scalar(14))); + var linked = Gen5ShaderCallLinker.Link(caller, + [new(20, 14, 16, 14, caller.Address + 24, + [new(0x2000, 10, Function(77)), new(0x2000, 11, Function(99)), new(0x3000, 10, Function(55))])]); + var source = Compile(Request(linked)).Source; + Assert.Contains($"{Gen5MslArgumentLayout.CallFaultsName}[0]", source, StringComparison.Ordinal); + if (SkipWithoutMetalDevice()) return; + + var run = new Run(linked); + run.Dispatch(); + Assert.Equal(expected, run.Word(0)); + if (expected != 0) + { + Assert.Equal(123u, run.Word(4)); + Assert.Equal(24u, run.Word(8)); + Assert.Equal(0u, run.Word(12)); + Assert.All(run.Faults, word => Assert.Equal(0u, word)); + } + else + { + Assert.Equal(FaultRecord(run.Request.Hash, 20, addressLow, addressHigh), run.Faults); + } + } + + // The test of the 65th record of one target runs after 64 that do not match. + [Fact] + public void SelectTheLastRecordBeyondSixtyFourEntries() + { + if (SkipWithoutMetalDevice()) return; + var caller = Program(MoveScalar(0, 14, 0x2000), MoveScalar(4, 15, 0), + MoveScalar(8, 16, 64), MoveScalar(12, 17, 0), + Sop1(16, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + BufferAccess(20, "BufferStoreDword", ResultRegister, vectorData: 1), EndProgram(28)); + var function = Program(Vop1(0, "VMovB32", 1, Gen5Operand.Scalar(16)), + Sop1(4, "SSetpcB64", 0, Gen5Operand.Scalar(14))); + var targets = Enumerable.Range(0, 65).Select(index => new ShaderCallTarget(0x2000, (ulong)index, function)).ToArray(); + var linked = Gen5ShaderCallLinker.Link(caller, [new(16, 14, 16, 14, 20, targets)]); + var run = new Run(linked); + run.Dispatch(); + Assert.Equal(64u, run.Word(0)); + Assert.All(run.Faults, word => Assert.Equal(0u, word)); + } + + // A site finds the record of each callee, whichever callee and argument the caller names; an unknown pair faults. + [Theory] + [InlineData(0x2000u, 10u, 110u)] + [InlineData(0x2000u, 11u, 111u)] + [InlineData(0x3000u, 10u, 210u)] + [InlineData(0x3000u, 11u, 211u)] + [InlineData(0x3000u, 12u, 0u)] + public void SiteLookupFindsTheRecordOfEachCallee(uint address, uint argument, uint expected) + { + if (SkipWithoutMetalDevice()) return; + var caller = Program(MoveScalar(0, 14, address), MoveScalar(4, 15, 0), MoveScalar(8, 16, argument), MoveScalar(12, 17, 0), + Sop1(16, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + BufferAccess(20, "BufferStoreDword", ResultRegister, vectorData: 1), EndProgram(28)); + Gen5ShaderProgram Function(uint add) => Program( + Vop1(0, "VMovB32", 1, Gen5Operand.Scalar(16)), + Vop2(4, "VAddU32", 1, Operand(add), Gen5Operand.Vector(1)), + Sop1(8, "SSetpcB64", 0, Gen5Operand.Scalar(14))); + var first = Function(100); + var second = Function(200); + var linked = Gen5ShaderCallLinker.Link(caller, [new(16, 14, 16, 14, 20, + [new(0x2000, 10, first), new(0x3000, 10, second), new(0x2000, 11, first), new(0x3000, 11, second)])]); + var run = new Run(linked); + run.Dispatch(); + Assert.Equal(expected, run.Word(0)); + if (expected != 0) Assert.All(run.Faults, word => Assert.Equal(0u, word)); + else Assert.Equal(FaultRecord(run.Request.Hash, 16, address, 0), run.Faults); + } + + // A function reads its program address with S_GETPC_B64: the address the dispatch pushes for it (a function the game + // placed elsewhere than at link time is still found and reads where it now is), and the return address follows the + // shader base. + [Theory] + [InlineData(0x8000ul, 0x8000ul)] + [InlineData(0x20000ul, 0x20000ul)] + [InlineData(0x8000ul, 0x5_0000_0400ul)] + public void FunctionReadsItsOwnProgramAddress(ulong function, ulong placed) + { + if (SkipWithoutMetalDevice()) return; + const ulong callerAddress = 0x10000; + const ulong shaderBase = 0x3_0040_0000; + var caller = Program(MoveScalar(0, 14, (uint)placed), MoveScalar(4, 15, (uint)(placed >> 32)), MoveScalar(8, 16, 10), + MoveScalar(12, 17, 0), + Sop1(16, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + Vop1(20, "VMovB32", 3, Gen5Operand.Scalar(14)), Vop1(24, "VMovB32", 4, Gen5Operand.Scalar(15)), + BufferAccess(28, "BufferStoreDwordx4", ResultRegister, dwords: 4, vectorData: 1), EndProgram(36)) with { Address = callerAddress }; + var body = Program(Nop(0), Sop1(4, "SGetpcB64", 2, Gen5Operand.Scalar(0)), + Vop1(8, "VMovB32", 1, Gen5Operand.Scalar(2)), Vop1(12, "VMovB32", 2, Gen5Operand.Scalar(3)), + Sop1(16, "SSetpcB64", 0, Gen5Operand.Scalar(14))); + var linked = Gen5ShaderCallLinker.Link(caller, [new(16, 14, 16, 14, callerAddress + 20, [new(function, 10, body)])]); + var run = new Run(linked); + run.Dispatch(shaderBase: shaderBase, callTargets: [placed]); + Assert.Equal((uint)(placed + 8), run.Word(0)); + Assert.Equal((uint)((placed + 8) >> 32), run.Word(4)); + Assert.Equal(unchecked((uint)(shaderBase + 20)), run.Word(8)); + Assert.Equal((uint)(shaderBase >> 32), run.Word(12)); + Assert.All(run.Faults, word => Assert.Equal(0u, word)); + } + + // The caller's own S_GETPC_B64 after a call reads the shader base plus its offset in the caller's code. + [Fact] + public void CallerReadsItsOwnProgramAddressAfterACall() + { + if (SkipWithoutMetalDevice()) return; + const ulong shaderBase = 0x3_0040_0000; + var caller = Program(MoveScalar(0, 14, 0x2000), MoveScalar(4, 15, 0), MoveScalar(8, 16, 10), MoveScalar(12, 17, 0), + Sop1(16, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + Sop1(20, "SGetpcB64", 2, Gen5Operand.Scalar(0)), + Vop1(24, "VMovB32", 3, Gen5Operand.Scalar(2)), Vop1(28, "VMovB32", 4, Gen5Operand.Scalar(3)), + BufferAccess(32, "BufferStoreDwordx4", ResultRegister, dwords: 4, vectorData: 1), EndProgram(40)); + var function = Program(Vop1(0, "VMovB32", 1, Gen5Operand.Scalar(16)), Vop1(4, "VMovB32", 2, Operand(7)), + Sop1(8, "SSetpcB64", 0, Gen5Operand.Scalar(14))); + var linked = Gen5ShaderCallLinker.Link(caller, [new(16, 14, 16, 14, caller.Address + 20, [new(0x2000, 10, function)])]); + var run = new Run(linked); + run.Dispatch(shaderBase: shaderBase); + Assert.Equal(10u, run.Word(0)); + Assert.Equal(7u, run.Word(4)); + Assert.Equal(unchecked((uint)(shaderBase + 24)), run.Word(8)); + Assert.Equal((uint)(shaderBase >> 32), run.Word(12)); + Assert.All(run.Faults, word => Assert.Equal(0u, word)); + } + + // Moved records keep the module: the test compares the caller's argument with the argument the dispatch pushes for the + // record's slot, so a table moved to other addresses selects by its new arguments, and the old ones fault. + [Theory] + [InlineData(0x2000u, 0x500010u, 0x500010u + 100)] + [InlineData(0x2000u, 0x100010u, 0u)] + public void MovedArgumentsKeepTheModule(uint address, uint argument, uint expected) + { + if (SkipWithoutMetalDevice()) return; + var caller = Program(MoveScalar(0, 14, address), MoveScalar(4, 15, 0), MoveScalar(8, 16, argument), MoveScalar(12, 17, 0), + Sop1(16, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + BufferAccess(20, "BufferStoreDword", ResultRegister, vectorData: 1), EndProgram(28)); + var function = Program( + Vop1(0, "VMovB32", 1, Gen5Operand.Scalar(16)), + Vop2(4, "VAddU32", 1, Operand(100), Gen5Operand.Vector(1)), + Sop1(8, "SSetpcB64", 0, Gen5Operand.Scalar(14))); + var linked = Gen5ShaderCallLinker.Link(caller, [new(16, 14, 16, 14, 20, [new(0x2000, 0x100010, function)])]); + Assert.Equal([0x100010ul], Gen5ShaderCallLinker.CallEntryArguments(linked)); + var run = new Run(linked); + run.Dispatch(callArguments: [0x500010ul]); + Assert.Equal(expected, run.Word(0)); + if (expected != 0) Assert.All(run.Faults, word => Assert.Equal(0u, word)); + else Assert.Equal(FaultRecord(run.Request.Hash, 16, address, 0), run.Faults); + } + + // A program linked with run-time records marks a call to a callee it lacks (CallMarks.Bit of the target and the + // caller's hash) and returns from the call at once; a callee it holds runs and marks nothing. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void RuntimeRecordCallsMarkCalleesTheProgramLacks(bool withCallee) + { + var caller = Program(MoveScalar(0, 14, 0x2000), MoveScalar(4, 15, 0), MoveScalar(8, 16, 10), MoveScalar(12, 17, 0), + Vop1(16, "VMovB32", 1, Operand(5)), + Sop1(20, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + BufferAccess(24, "BufferStoreDword", ResultRegister, vectorData: 1), EndProgram(32)); + var callee = Program(Vop1(0, "VMovB32", 1, Gen5Operand.Scalar(16)), Sop1(4, "SSetpcB64", 0, Gen5Operand.Scalar(14))); + ShaderCallTarget[] targets = withCallee ? [new ShaderCallTarget(0x2000, 0, callee)] : []; + var linked = Gen5ShaderCallLinker.Link(caller, [new(20, 14, 16, 14, 24, targets)], runtimeArguments: true); + var request = Request(linked, callRecords: true, callMarks: true); + Assert.NotNull(request.Bindings.Find(DescriptorBindingKind.CallMarks)); + var source = Compile(request).Source; + Assert.Contains($"atomic_fetch_or_explicit(&sharpemu_resources.{Gen5MslArgumentLayout.CallMarksName}[", source, + StringComparison.Ordinal); + // Without call marks the program still returns from the call at once, and binds no marks. + var unmarked = Compile(Request(linked, callRecords: true)).Source; + Assert.DoesNotContain(Gen5MslArgumentLayout.CallMarksName, unmarked, StringComparison.Ordinal); + if (SkipWithoutMetalDevice()) return; + + var run = new Run(linked, callRecords: true, callMarks: true); + var marks = MetalNative.CreateWordTable(DescriptorBindingKind.CallMarks, new uint[CallMarks.Words]); + run.Dispatch(tables: [marks]); + Assert.Equal(withCallee ? 10u : 5u, run.Word(0)); + var expected = new uint[CallMarks.Words]; + if (!withCallee) + { + var bit = CallMarks.Bit(0x2000, run.Request.Hash); + expected[bit >> 5] = 1u << (int)(bit & 31); + } + + Assert.Equal(expected, MetalNative.ReadWords(marks)); + Assert.All(run.Faults, word => Assert.Equal(0u, word)); + } + + // A callee reads an image its record holds (the T# loaded through the record's argument): the row of the caller's + // argument is found once at the entry, and the image is the heap element the host gave that row's field. An argument no + // row holds reads the null element, which reads zero. + [Theory] + [InlineData(0x40u, true)] + [InlineData(0x80u, false)] + public void ACalleeReadsTheImageOfItsRecordThroughTheHeap(uint argument, bool found) + { + // The argument is a value only the wave knows (lane 0's thread id plus the argument), as a record address read from + // memory is: the host cannot evaluate it, so the callee's reads through it are record fields. + var caller = Program(MoveScalar(0, 14, 0x2000), MoveScalar(4, 15, 0), + Vop2(8, "VAddU32", 8, Operand(argument), Gen5Operand.Vector(0)), + new Gen5ShaderInstruction(16, Gen5ShaderEncoding.Vop1, "VReadfirstlaneB32", [0u], [Gen5Operand.Vector(8)], [Gen5Operand.Scalar(16)], null), + MoveScalar(20, 17, 0), + Sop1(24, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + BufferAccess(28, "BufferStoreDwordx4", ResultRegister, dwords: 4, vectorData: 4), EndProgram(36)); + var callee = Program(ScalarLoad(0, 16, 20, 8), ScalarLoad(8, 16, 28, 4, immediateOffset: 32), + Vop1(16, "VMovB32", 0, Operand(0x3F000000)), Vop1(24, "VMovB32", 1, Operand(0x3F000000)), + ImageSample(32, 20, 28), + Sop1(40, "SSetpcB64", 0, Gen5Operand.Scalar(14))); + var linked = Gen5ShaderCallLinker.Link(caller, [new(24, 14, 16, 14, 28, [new ShaderCallTarget(0x2000, 0, callee)])], + runtimeArguments: true); + var request = Request(linked, bindlessHeap: true, callRecords: true); + var use = Assert.Single(request.CallRecordImageByMemoryIndex).Value; + var samplerUse = Assert.Single(request.CallRecordSamplerByMemoryIndex).Value; + Assert.NotEqual(use.Field, samplerUse.Field); + var source = Compile(request).Source; + Assert.Contains("sharpemu_search_call_records(", source, StringComparison.Ordinal); + Assert.Contains("sharpemu_call_record_element(", source, StringComparison.Ordinal); + if (SkipWithoutMetalDevice()) return; + + const uint element = BindlessHeap.CallRecordFirstIndex; + const uint samplerElement = BindlessHeap.CallRecordFirstIndex + 1; + uint[] texel = [0x3F800000, 0x40000000, 0x40400000, 0x40800000]; + var texture = MetalNative.CreateTexelTexture(MetalNative.PixelFormatRgba32Float, + BindlessHeap.ImageClasses[use.Slot].Dimension == ImageDimension.Dim2D ? MetalNative.TextureType2D : MetalNative.TextureType2DArray, 1, texel); + var elements = new byte[BindlessHeap.ArrayCount * BindlessHeap.Capacity * Gen5MslArgumentLayout.HeapElementBytes]; + BinaryPrimitives.WriteUInt64LittleEndian(elements.AsSpan((int)(((uint)use.Slot * BindlessHeap.Capacity + element) * 8)), + MetalNative.ResourceId(texture)); + BinaryPrimitives.WriteUInt64LittleEndian(elements.AsSpan((int)(((uint)samplerUse.Slot * BindlessHeap.Capacity + samplerElement) * 8)), + MetalNative.ResourceId(MetalNative.CreatePointSampler())); + var feedbackWords = new uint[BindlessHeap.FeedbackWords]; + feedbackWords[BindlessHeap.MarkWords + (element >> (int)BindlessHeap.ClassWordShift)] |= + BindlessHeap.ClassCode(ImageNumericClass.Float) << (int)((element & (BindlessHeap.ClassesPerWord - 1)) * BindlessHeap.ClassBits); + // One row: the key (argument 0x40, callee slot 0), its first field at word 5, the fields' elements. + var recordWords = new uint[] { 1, 0x40, 0, 0, 5, 0, 0, 0 }; + recordWords[5 + use.Field] = element; + recordWords[5 + samplerUse.Field] = samplerElement; + var records = MetalNative.CreateWordTable(DescriptorBindingKind.CallRecords, recordWords); + var run = new Run(linked, bindlessHeap: true, callRecords: true); + run.Dispatch(tables: [records], + heap: (MetalNative.CreateHeapElements(elements, [texture]), MetalNative.CreateHeapFeedback(feedbackWords))); + for (var component = 0; component < 4; component++) + { + Assert.Equal(found ? texel[component] : 0u, run.Word(component * 4)); + } + + Assert.All(run.Faults, word => Assert.Equal(0u, word)); + } + + // The translation cache keeps a linked program's argument layout: its call record, call mark and call fault fields + // read back as written (Gen5MslShaderPayload format 2). + [Fact] + public void ALinkedTranslationReadsBackItsCallFields() + { + var caller = Program(MoveScalar(0, 14, 0x2000), MoveScalar(4, 15, 0), + Vop2(8, "VAddU32", 8, Operand(0x40), Gen5Operand.Vector(0)), + new Gen5ShaderInstruction(16, Gen5ShaderEncoding.Vop1, "VReadfirstlaneB32", [0u], [Gen5Operand.Vector(8)], [Gen5Operand.Scalar(16)], null), + MoveScalar(20, 17, 0), + Sop1(24, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + BufferAccess(28, "BufferStoreDwordx4", ResultRegister, dwords: 4, vectorData: 4), EndProgram(36)); + var callee = Program(ScalarLoad(0, 16, 20, 8), ScalarLoad(8, 16, 28, 4, immediateOffset: 32), + Vop1(16, "VMovB32", 0, Operand(0x3F000000)), Vop1(24, "VMovB32", 1, Operand(0x3F000000)), + ImageSample(32, 20, 28), + Sop1(40, "SSetpcB64", 0, Gen5Operand.Scalar(14))); + var perRecord = Compile(Request(Gen5ShaderCallLinker.Link(caller, [new(24, 14, 16, 14, 28, [new ShaderCallTarget(0x2000, 0, callee)])]))); + var runtime = Compile(Request(Gen5ShaderCallLinker.Link(caller, [new(24, 14, 16, 14, 28, [])], runtimeArguments: true), + bindlessHeap: true, callRecords: true, callMarks: true)); + var recorded = Compile(Request(Gen5ShaderCallLinker.Link(caller, [new(24, 14, 16, 14, 28, [new ShaderCallTarget(0x2000, 0, callee)])], + runtimeArguments: true), bindlessHeap: true, callRecords: true)); + Assert.Contains(perRecord.ArgumentLayout!.Fields, field => field.FieldKind == MslArgumentFieldKind.CallFaults); + Assert.Contains(runtime.ArgumentLayout!.Fields, field => field.Name == Gen5MslArgumentLayout.CallMarksName); + Assert.Contains(recorded.ArgumentLayout!.Fields, field => field.Name == Gen5MslArgumentLayout.CallRecordsName); + foreach (var shader in new[] { perRecord, runtime, recorded }) + { + var payload = Gen5MslShaderPayload.Write(shader, ShaderStage.Compute, Hash); + Assert.True(Gen5MslShaderPayload.TryRead(payload, out var read, out _, out _, out var error), error); + Assert.Equal(shader.ArgumentLayout!.Fields, read.ArgumentLayout!.Fields); + Assert.Equal(shader.Source, read.Source); + } + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslTranslationTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslTranslationTests.cs index b1c44e1e3..ebd711d29 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslTranslationTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslTranslationTests.cs @@ -16,7 +16,7 @@ public sealed class MslTranslationTests [Theory] [InlineData(false)] [InlineData(true)] - public void ShaderCallsReportTheBackendLimitation(bool linked) + public void ShaderCallsCompileLinkedOrAlone(bool linked) { var program = new Gen5ShaderProgram(0x1000, [ new(0, Gen5ShaderEncoding.Sop1, "SSwappcB64", [0xBE8E2100], @@ -31,15 +31,14 @@ public void ShaderCallsReportTheBackendLimitation(bool linked) [new ShaderCallTarget(0x2000, 0, function)])]); } var request = Gen5ComputeFixtures.RequestOrThrow(program, ShaderStage.Compute); - // An unlinked S_SWAPPC_B64 is the caller compiled alone (the call is skipped): the - // pipeline cache only links calls for a backend that supports them, which Metal does not. - if (!linked) + // An unlinked S_SWAPPC_B64 is the caller compiled alone (the call is skipped, as before the port). A linked program + // compiles since Metal lowers the linker's call controls (Gen5MslTranslator.ShaderCalls.cs); this request pushes no + // call targets, so the test compares the link-time address (MslLinkedCallTests runs the pushed form). + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error), error); + if (linked) { - Assert.True(Gen5MslTranslator.TryCompileProgram(request, out _, out var unlinkedError), unlinkedError); - return; + Assert.Contains("8192ul", shader.Source, StringComparison.Ordinal); } - Assert.False(Gen5MslTranslator.TryCompileProgram(request, out _, out var error)); - Assert.Equal("Metal does not support linked shader calls.", error); } [Fact] From 652fb015fd6a3830f4c9815cdf472cd50c65a743 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 03:10:24 +0000 Subject: [PATCH 107/134] [Metal] Answer stable image descriptor limits from the device's argument buffer limits Upstream 7cf0ac568 lets a host give the shader planner a per-stage budget within which a program's images bind one per slot (ShaderResourcePlan.StableImageBindings), so its specialization stops depending on which image slots a draw fills with equal descriptors. Metal kept the interface default (no budget), compiling one specialization per alias partition. MetalStableImageLimits derives the budget from the device: argument buffers tier 2 and Apple7+ (textures 1M per stage, samplers 996 on Apple7/8 and 500K on Apple9+ per stage, at most maxArgumentBufferSamplerCount; buffers unlimited), per Apple's Metal Feature Set Tables. Every stage has its own argument buffer, so compute and graphics share it. SHARPEMU_METAL_STABLE_IMAGE_BINDINGS=0 answers no budget. The prewarm plans as the live host: compute prewarm and the static precompile pass the budget, corpus host flags carry the budget the session answered (CorpusReplayHost answers it), the static precompile predicts the plan's binding policy under the current budget, graphics records made under another budget are skipped and counted (graphics_stale), and the budget is part of the prewarm stamp (and so of the translation cache stamp). --- docs/macos/configuration.md | 1 + .../Gpu/Pipelines/ShaderCorpus.cs | 5 + .../Gpu/Pipelines/ShaderPrewarmCompiler.cs | 30 ++++- .../Gpu/Pipelines/ShaderProgramCache.cs | 25 ++++- .../Gpu/ShaderCache/StaticShaderPlanner.cs | 16 ++- .../Resources/ResourceSpecialization.cs | 4 +- .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 8 ++ .../V2/MetalShaderPrewarm.cs | 54 +++++++-- .../V2/MetalStableImageLimits.cs | 106 ++++++++++++++++++ .../V2/MetalStaticPrecompile.cs | 19 ++-- 10 files changed, 237 insertions(+), 31 deletions(-) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalStableImageLimits.cs diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 2425e51b2..eaf79711b 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -70,6 +70,7 @@ them for measurements or to isolate a problem. | `SHARPEMU_METAL_MESH_SHADERS` | on | `0` disables mesh pipelines for primitive-shader draws. | | `SHARPEMU_METAL_DRAW_PARAMETERS` | on | `0` turns off draw parameters in translated vertex programs. By default a vertex program's instance index counts from the draw's base instance, and when an indirect draw names a user-data register for its base vertex or start instance, the program counts its vertex index from the base vertex and stores both bases there (the command processor no longer writes those registers). `0` gives the program Metal's ids, which include both bases, and stores nothing. | | `SHARPEMU_METAL_BINDLESS_HEAP` | on | `0` turns off the bindless heap. By default an image or sampler a program reads from a descriptor table at a record only the shader knows is read through the heap: the shader marks the records it reads, the host resolves each marked record's texture or sampler from guest memory, and the program reads it from a later draw on (the first read of a record returns zeros). `0` plans those tables as before (bindless image tables, at most 256 candidates, off-class candidates read null). | +| `SHARPEMU_METAL_STABLE_IMAGE_BINDINGS` | on | `0` gives every program compact image bindings again. By default a program whose images fit Metal's per-stage argument-buffer limits (textures 1M; samplers 996 on Apple7/8, 500K on Apple9+, at most `maxArgumentBufferSamplerCount`) binds one texture per image slot, so one specialization serves every draw however its slots repeat descriptors (fewer shader compiles). Programs over the limits, and bindless, indirect, linked and dynamic-mip ones, keep compact bindings (one texture per distinct descriptor). The setting is part of the shader prewarm stamp: changing it re-prewarms once. | | `SHARPEMU_RUNTIME_IMAGE_SWIZZLE` | on | `0` bakes each storage image's destination select into the translated program, one program per select. By default a store reads the image's channel map from shader data, which the host writes from the bound descriptor. | | `SHARPEMU_METAL_FORMAT_LOAD_COMPONENT_BOUNDS` | on | `0` restores the old bound of a formatted buffer load whose format is fixed at translation: the whole element had to fit below the buffer's size. By default each selected component is checked at its own address, wrapping past 2^32 as on the hardware, so a component that wraps to the buffer's start is read, and the load reads its constants only when a selected component is out of range. An element that fits whole still takes one compare. Loads whose format is read at run time always check per component. | | `SHARPEMU_METAL_SHADER_CLOCK_STEP` | on | Metal has no shader clock, so `S_MEMTIME`/`S_MEMREALTIME` read a per-invocation counter of their own reads (logged once per shader as `[MSL][WARN][SHADER_CLOCK]`). By default each read moves it 2^32 + 1, as upstream's SPIR-V fallback moves its high dword: a guest wait on the 64-bit difference for fewer than 2^32 ticks ends at its next read, and a wait on the low dword still sees one tick per read. `0` steps by 1, so such a wait runs one loop trip per tick. | diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCorpus.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCorpus.cs index bd211a117..0c18ac4ed 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCorpus.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCorpus.cs @@ -27,6 +27,11 @@ public sealed record ShaderCorpusHostFlags public bool ComputeRunsOn32LaneSubgroups { get; init; } public bool DrawParameters { get; init; } public bool RuntimeImageSwizzles { get; init; } + // The stable image budgets the planning host answered (IShaderPipelineHost.ComputeImageDescriptorLimits, + // GraphicsImageDescriptorLimits): a replay plans as the session did, so its specialization applies. A record + // without them was taken with none (compact bindings). + public StableImageDescriptorLimits ComputeImageLimits { get; init; } + public StableImageDescriptorLimits GraphicsImageLimits { get; init; } } // One program as the translator was about to see it. Options is null when the guest code did not diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmCompiler.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmCompiler.cs index e649c8862..a58fd1ffb 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmCompiler.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmCompiler.cs @@ -12,22 +12,42 @@ public static class ShaderPrewarmCompiler public static bool TryCompilePrewarm(ComputePrewarmRecord record, ShaderCodeCapture code, IGuestGpuBackend compiler, bool sharedInt64Atomics, bool execGuardElision, bool signedZeroInfNanPreserve, out IGuestCompiledShader? compiled, out BindingLayout? layout, out string error, bool hostWave64Supported = false, bool hostComputeSubgroup32 = false, bool imageInt64Atomics = false, bool tableBlocks = false, - Func<ulong, IShaderFrontend?>? frontendOf = null, bool runtimeImageSwizzles = false) => + Func<ulong, IShaderFrontend?>? frontendOf = null, bool runtimeImageSwizzles = false, + StableImageDescriptorLimits stableImageLimits = default) => ShaderProgramCache.TryCompilePrewarm(record, code, compiler, sharedInt64Atomics, execGuardElision, signedZeroInfNanPreserve, out compiled, out layout, out error, - hostWave64Supported, hostComputeSubgroup32, imageInt64Atomics, tableBlocks: tableBlocks, frontendOf: frontendOf, - runtimeImageSwizzles: runtimeImageSwizzles); + hostWave64Supported, hostComputeSubgroup32, imageInt64Atomics, stableImageLimits: stableImageLimits, tableBlocks: tableBlocks, + frontendOf: frontendOf, runtimeImageSwizzles: runtimeImageSwizzles); /// <summary> /// Translates a recorded graphics program through the shared plan, layout and request builders /// of live draws, over the recorded guest code; the backend turns the request into a module. /// </summary> public static bool TryCompileGraphicsPrewarm(in GraphicsPrewarmList.Item item, IGuestGpuBackend compiler, - out IGuestCompiledShader? compiled, out string error) + out IGuestCompiledShader? compiled, out string error) => + TryCompileGraphicsPrewarm(item, compiler, null, out compiled, out error, out _); + + /// <summary> + /// As above; with <paramref name="imageLimits"/> (the stable image budget the host answers now), a record whose + /// session answered another budget is not translated (<paramref name="stale"/>): its specialization follows the + /// other image binding policy, which this host's sessions no longer ask for. + /// </summary> + public static bool TryCompileGraphicsPrewarm(in GraphicsPrewarmList.Item item, IGuestGpuBackend compiler, + StableImageDescriptorLimits? imageLimits, out IGuestCompiledShader? compiled, out string error, out bool stale) { compiled = null; + stale = false; try { - if (!ShaderCorpus.TryBuildRequest(GraphicsPrewarmList.Decode(item), out var request, out error)) + var record = GraphicsPrewarmList.Decode(item); + if (imageLimits is { } limits && + (record.Host.GraphicsImageLimits != limits || record.Host.ComputeImageLimits != limits)) + { + stale = true; + error = $"recorded under another stable image budget ({record.Host.GraphicsImageLimits}, now {limits})"; + return false; + } + + if (!ShaderCorpus.TryBuildRequest(record, out var request, out error)) { return false; } diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index eb09aac8a..12f85051d 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -779,6 +779,8 @@ private ShaderCodeCapture CaptureCode(ShaderSource source, RecordingCpuMemory re ComputeRunsOn32LaneSubgroups = options?.ComputeInfo is { } compute && _host.ComputeRunsOn32LaneSubgroups(compute), DrawParameters = _host.ShaderDrawParametersSupported, RuntimeImageSwizzles = _host.RuntimeImageSwizzlesSupported, + ComputeImageLimits = _host.ComputeImageDescriptorLimits, + GraphicsImageLimits = _host.GraphicsImageDescriptorLimits, }; // What the code bytes held when they failed, and any command-processor write into @@ -3026,14 +3028,27 @@ internal static bool TryBuildCorpusRequest(ShaderCorpusRecord record, out Shader /// </summary> internal static bool TryPredictSpecialization(ShaderCorpusRecord record, out ResourceSpecialization? specialization, out string error) { - specialization = TryPlanResources(record, out var info, out error) ? ResourceSpecialization.Default(info!) : null; - return specialization is not null; + specialization = null; + if (!TryPlan(record, out var plan, out error)) + { + return false; + } + + // The plan's image binding policy (StableImageBindings): ApplyTo refuses a specialization of the other one. + specialization = ResourceSpecialization.Default(plan!.Info, plan.StableImageBindings); + return true; } /// <summary>The resource tables of the record's plan.</summary> internal static bool TryPlanResources(ShaderCorpusRecord record, out ShaderResourceInfo? info, out string error) { - info = null; + info = TryPlan(record, out var plan, out error) ? plan!.Info : null; + return info is not null; + } + + private static bool TryPlan(ShaderCorpusRecord record, out ShaderResourcePlan? plan, out string error) + { + plan = null; error = string.Empty; var previousThrowOnFatal = GpuFatal.ThrowOnFatal; GpuFatal.ThrowOnFatal = true; @@ -3046,7 +3061,7 @@ internal static bool TryPlanResources(ShaderCorpusRecord record, out ShaderResou } var cache = new ShaderProgramCache(record.Code.CreateContext(), null!, new CorpusReplayHost(record.Host)); - info = cache.CreateEntry(record.CreateSource(), options).Plan.Info; + plan = cache.CreateEntry(record.CreateSource(), options).Plan; return true; } catch (Exception exception) when (exception is ShaderProgramRejectedException or GpuFatal.AbandonedWorkException or @@ -3077,6 +3092,8 @@ private sealed class CorpusReplayHost(ShaderCorpusHostFlags flags) : IShaderPipe public bool ClipDistanceEnabled => flags.ClipDistance; public bool ShaderDrawParametersSupported => flags.DrawParameters; public bool RuntimeImageSwizzlesSupported => flags.RuntimeImageSwizzles; + public StableImageDescriptorLimits ComputeImageDescriptorLimits => flags.ComputeImageLimits; + public StableImageDescriptorLimits GraphicsImageDescriptorLimits => flags.GraphicsImageLimits; public RenderHostLimits Limits => default; public GpuSampleCount NoAttachmentSampleCounts => default; diff --git a/src/SharpEmu.Libs/Gpu/ShaderCache/StaticShaderPlanner.cs b/src/SharpEmu.Libs/Gpu/ShaderCache/StaticShaderPlanner.cs index b42b1bffe..f954b5f37 100644 --- a/src/SharpEmu.Libs/Gpu/ShaderCache/StaticShaderPlanner.cs +++ b/src/SharpEmu.Libs/Gpu/ShaderCache/StaticShaderPlanner.cs @@ -100,7 +100,10 @@ private StaticShaderPlanner(ShaderInventoryFile inventory, ShaderCorpusHostFlags /// learns the palettes from <paramref name="recorded"/> and the seed at /// <paramref name="seedPath"/>. Null when the inventory cannot be opened. /// </summary> - public static StaticShaderPlanner? Open(string directory, IEnumerable<ShaderCorpusRecord> recorded, string? seedPath) + /// With <paramref name="imageLimits"/>, every state predicts under that stable image budget (the current host's) + /// instead of the one its recording session answered. + public static StaticShaderPlanner? Open(string directory, IEnumerable<ShaderCorpusRecord> recorded, string? seedPath, + StableImageDescriptorLimits? imageLimits = null) { if (ShaderInventoryFile.Open(directory) is not { } inventory) { @@ -108,7 +111,16 @@ private StaticShaderPlanner(ShaderInventoryFile inventory, ShaderCorpusHostFlags } var records = recorded.Where(static record => record.Options is not null).ToList(); - var host = records.FirstOrDefault()?.Host ?? new ShaderCorpusHostFlags(); + if (imageLimits is { } limits) + { + records = records + .Select(record => record with { Host = record.Host with { ComputeImageLimits = limits, GraphicsImageLimits = limits } }) + .ToList(); + } + + var host = records.FirstOrDefault()?.Host ?? + (imageLimits is { } budget ? new ShaderCorpusHostFlags { ComputeImageLimits = budget, GraphicsImageLimits = budget } + : new ShaderCorpusHostFlags()); var planner = new StaticShaderPlanner(inventory, host); var seed = seedPath is null ? null : ShaderSeedFile.Load(seedPath); planner.Learn(records, seed); diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceSpecialization.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceSpecialization.cs index 5defb99ca..bd2e192b9 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceSpecialization.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceSpecialization.cs @@ -158,9 +158,11 @@ public override int GetHashCode() }; // The specialization of a plan before any draw: raw buffers and the tracked image classes. - public static ResourceSpecialization Default(ShaderResourceInfo info) => new() + // stableImageBindings: the plan's image binding policy (ShaderResourcePlan.StableImageBindings), which ApplyTo checks. + public static ResourceSpecialization Default(ShaderResourceInfo info, bool stableImageBindings = false) => new() { BaseBufferCount = info.Buffers.Count, + StableImageBindings = stableImageBindings, Buffers = info.Buffers.Select(_ => new BufferSpecialization(0, DescriptorConstants.InvalidFormat, DescriptorConstants.IdentityDestinationSelect)).ToList(), Images = info.Images.Select(image => new ImageSpecialization( image.NumericClass == ImageNumericClass.Unsupported diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index 18dbe6bd7..b5246cb22 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -273,6 +273,14 @@ internal ulong ReadCompletedSerial(bool useCompletedSnapshot) public uint MaxPushDescriptors => 0; + // Each stage has its own argument buffer, so compute and graphics stages share one per-stage budget + // (MetalStableImageLimits). The prewarm answers the same (MetalShaderPrewarm.ComputeImageLimits). + public SharpEmu.ShaderCompiler.Resources.StableImageDescriptorLimits ComputeImageDescriptorLimits => + MetalStableImageLimits.Of(_device); + + public SharpEmu.ShaderCompiler.Resources.StableImageDescriptorLimits GraphicsImageDescriptorLimits => + MetalStableImageLimits.Of(_device); + // Metal threadgroups are always 32-wide on Apple silicon; a wave64 compute // program is emitted as two wave32 halves by the translator. public bool ComputeWave64Supported => false; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs index 32e5865d0..647c2a7f6 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs @@ -336,6 +336,7 @@ private static bool StartCore(nint device) "pipeline_cache", SanitizeTitleId(VideoOutBackendServices.GetApplicationTitleId()), "metal-v2"); var compiler = GuestGpu.Current; var stamp = Stamp(compiler, device); + _stableImageLimits = MetalStableImageLimits.Of(device); // Seeded before the compute prewarm or the game plans a shader. MetalDeviceDataLoadsStore.Open(directory, stamp); // Loaded before the gate lets the game go, so every module the game creates @@ -559,8 +560,16 @@ private readonly record struct PrewarmWork( // slots, where the module the game creates for it takes it from. private static void PrewarmGraphicsLibrary(in GraphicsPrewarmList.Item item, IGuestGpuBackend compiler) { - if (!ShaderPrewarmCompiler.TryCompileGraphicsPrewarm(item, compiler, out var compiled, out var error)) + if (!ShaderPrewarmCompiler.TryCompileGraphicsPrewarm( + item, compiler, _stableImageLimits, out var compiled, out var error, out var stale)) { + if (stale) + { + // Recorded by a session under the other image binding policy; the session records this one's anew. + Interlocked.Increment(ref _graphicsStale); + return; + } + NoteGraphicsFailure(error); return; } @@ -579,6 +588,12 @@ private static void PrewarmGraphicsLibrary(in GraphicsPrewarmList.Item item, IGu } } + // The stable image budget this start's live host answers (MetalStableImageLimits.Of of the prewarm's device). + private static SharpEmu.ShaderCompiler.Resources.StableImageDescriptorLimits _stableImageLimits; + + // Graphics records made under another stable image budget, not translated. + private static int _graphicsStale; + private static void NoteGraphicsFailure(string error) { if (Interlocked.Increment(ref _graphicsFailed) <= MaxLoggedPrewarmFailures) @@ -663,6 +678,7 @@ private static bool CompletePrecompile() return Precompile.Complete( $"computes={Volatile.Read(ref _compiled)} compute_failed={Volatile.Read(ref _failed)} " + $"graphics_libraries={Volatile.Read(ref _graphicsCompiled)} graphics_failed={Volatile.Read(ref _graphicsFailed)} " + + $"graphics_stale={Volatile.Read(ref _graphicsStale)} " + $"libraries_held={MetalLibraryPrewarm.HeldLibraries} {MetalStaticPrecompile.Describe()}"); } @@ -830,6 +846,8 @@ internal static string Stamp(IGuestGpuBackend compiler, nint device) => // The switches decide the MSL as the translators do; what is stored under this stamp // and not keyed by source text (the static precompile's finished units) follows them. MetalRenderHost.TranslationSwitchStamp, + // The stable image budget decides which specializations a session asks for (MetalStableImageLimits). + MetalStableImageLimits.StampPart(MetalStableImageLimits.Of(device)), MetalNative.ReadNsString(MetalNative.Send(device, SelName)), RuntimeInformation.OSDescription); @@ -838,23 +856,34 @@ internal static string Stamp(IGuestGpuBackend compiler, nint device) => public static string Identity(MetalCompiledGuestShader shader) => shader.PayloadHash.ToString("X16", System.Globalization.CultureInfo.InvariantCulture); + /// <summary> + /// A recorded compute program translated as the live host translates it: the compile flags the host answers + /// (MetalRenderHost.Prewarm*) and its stable image budget (MetalStableImageLimits.Of of the same device), so the + /// plan admits stable image bindings exactly when the session's did and the recorded specialization applies. + /// </summary> + internal static bool TryCompileCompute(ComputePrewarmRecord record, ShaderCodeCapture code, IGuestGpuBackend compiler, + SharpEmu.ShaderCompiler.Resources.StableImageDescriptorLimits stableImageLimits, + out IGuestCompiledShader? compiled, out string error) => + ShaderPrewarmCompiler.TryCompilePrewarm( + record, + code, + compiler, + MetalRenderHost.PrewarmSharedInt64Atomics, + MetalRenderHost.PrewarmExecGuardElision, + MetalRenderHost.PrewarmSignedZeroInfNanPreserve, + out compiled, + out _, + out error, + stableImageLimits: stableImageLimits, + runtimeImageSwizzles: MetalRenderHost.PrewarmRuntimeImageSwizzles); + private static void PrewarmComputePipeline( ComputePrewarmRecord record, ShaderCodeCapture code, IGuestGpuBackend compiler, nint device) { - if (!ShaderPrewarmCompiler.TryCompilePrewarm( - record, - code, - compiler, - MetalRenderHost.PrewarmSharedInt64Atomics, - MetalRenderHost.PrewarmExecGuardElision, - MetalRenderHost.PrewarmSignedZeroInfNanPreserve, - out var compiled, - out _, - out var error, - runtimeImageSwizzles: MetalRenderHost.PrewarmRuntimeImageSwizzles)) + if (!TryCompileCompute(record, code, compiler, MetalStableImageLimits.Of(device), out var compiled, out var error)) { NoteFailure(record, error); return; @@ -1031,6 +1060,7 @@ private static void Finish(ShaderPrewarmList list, string stamp, long started) $"archived={Volatile.Read(ref _archived)} " + $"runtime_first={Volatile.Read(ref _runtimeFirst)} " + $"graphics_libraries={Volatile.Read(ref _graphicsCompiled)} graphics_failed={Volatile.Read(ref _graphicsFailed)} " + + $"graphics_stale={Volatile.Read(ref _graphicsStale)} " + $"ms={Stopwatch.GetElapsedTime(started).TotalMilliseconds:F0} " + $"yielded_ms={Interlocked.Read(ref _yieldedTicks) * 1000 / Stopwatch.Frequency} " + $"runtime_compute_modules={runtime.Count} matched={matched}"; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStableImageLimits.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStableImageLimits.cs new file mode 100644 index 000000000..736fe88b6 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStableImageLimits.cs @@ -0,0 +1,106 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Globalization; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.Gpu.Metal.V2; + +/// <summary> +/// The budget within which a program's images bind one per slot (ShaderResourcePlan.StableImageBindings), whatever +/// descriptors a draw repeats, so one specialization serves every alias partition of its image slots +/// (IShaderPipelineHost.ComputeImageDescriptorLimits, GraphicsImageDescriptorLimits; upstream answers them from the +/// Vulkan device limits). A plan over the budget keeps compact bindings, one element per distinct descriptor. +/// +/// Every stage reads its images, samplers and buffers through its own argument buffer (Gen5MslArgumentLayout), written +/// with gpuResourceIDs and gpuAddresses: the argument buffers tier 2 layout. Nothing is shared between the stages of a +/// pipeline, so compute and graphics stages have one budget, the per-stage argument buffer limits of Apple's Metal +/// Feature Set Tables ("GPU implementation limits by family", Argument buffers; the limits count what a stage reaches +/// through every argument buffer it reads): +/// <list type="bullet"> +/// <item>textures per stage: 1M on Apple6 to Apple11. Sampled and storage images are both textures, so their sum is +/// held to it through Resources, which also counts the buffers.</item> +/// <item>buffers per stage: no limit on Apple6 to Apple11.</item> +/// <item>samplers per stage: 996 on Apple7 and Apple8, 500K on Apple9 to Apple11; also no more than the unique +/// argument-buffer samplers the app may create, MTLDevice.maxArgumentBufferSamplerCount (1024 or more on macOS: +/// "Improving CPU performance by using argument buffers").</item> +/// </list> +/// A device without tier 2 argument buffers or below Apple7 (not a device this app runs on) answers no budget. +/// SHARPEMU_METAL_STABLE_IMAGE_BINDINGS=0 answers no budget: every program keeps compact bindings, as before. +/// </summary> +internal static class MetalStableImageLimits +{ + internal static readonly bool Enabled = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_STABLE_IMAGE_BINDINGS") != "0"; + + internal const uint TexturesPerStage = 1_000_000; + internal const uint SamplersPerStageApple7 = 996; + internal const uint SamplersPerStageApple9 = 500_000; + + // MTLArgumentBuffersTier2. + private const nint ArgumentBuffersTier2 = 1; + private const nint GpuFamilyApple7 = 1007; + private const nint GpuFamilyApple9 = 1009; + + private static readonly nint SelArgumentBuffersSupport = MetalNative.Selector("argumentBuffersSupport"); + private static readonly nint SelMaxArgumentBufferSamplerCount = MetalNative.Selector("maxArgumentBufferSamplerCount"); + private static readonly nint SelSupportsFamily = MetalNative.Selector("supportsFamily:"); + private static readonly nint SelRespondsToSelector = MetalNative.Selector("respondsToSelector:"); + + private static readonly object Gate = new(); + private static nint _device; + private static StableImageDescriptorLimits _deviceLimits; + + /// <summary>The budget this process answers for the device: the live host and the prewarm alike.</summary> + internal static StableImageDescriptorLimits Of(nint device) => Of(device, Enabled); + + internal static StableImageDescriptorLimits Of(nint device, bool enabled) + { + if (!enabled || device == 0) + { + return default; + } + + lock (Gate) + { + if (_device != device) + { + _deviceLimits = Query(device); + _device = device; + } + + return _deviceLimits; + } + } + + /// <summary>The budget of a device with these capabilities.</summary> + internal static StableImageDescriptorLimits FromCapabilities(bool tier2, bool apple7, bool apple9, ulong maxUniqueSamplers) + { + if (!tier2 || !apple7 || maxUniqueSamplers == 0) + { + return default; + } + + var samplers = (uint)Math.Min(apple9 ? SamplersPerStageApple9 : SamplersPerStageApple7, maxUniqueSamplers); + return new StableImageDescriptorLimits(TexturesPerStage, TexturesPerStage, samplers, uint.MaxValue, TexturesPerStage); + } + + /// <summary>The budget as the prewarm stamp keeps it: entries made under another budget are not taken as current.</summary> + internal static string StampPart(StableImageDescriptorLimits limits) => + string.Create(CultureInfo.InvariantCulture, + $"stable_images={limits.SampledImages},{limits.StorageImages},{limits.Samplers},{limits.StorageBuffers},{limits.Resources}"); + + private static StableImageDescriptorLimits Query(nint device) + { + var tier2 = MetalNative.Send(device, SelArgumentBuffersSupport) == ArgumentBuffersTier2; + var families = MetalNative.SendBool(device, SelRespondsToSelector, SelSupportsFamily); + var apple7 = families && MetalNative.SendBool(device, SelSupportsFamily, GpuFamilyApple7); + var apple9 = families && MetalNative.SendBool(device, SelSupportsFamily, GpuFamilyApple9); + var samplers = (ulong)MetalNative.Send(device, SelMaxArgumentBufferSamplerCount); + var limits = FromCapabilities(tier2, apple7, apple9, samplers); + Console.Error.WriteLine( + $"[METAL-V2][INFO] Stable image bindings: tier2={tier2} apple7={apple7} apple9={apple9} " + + $"max_argument_buffer_samplers={samplers} -> {StampPart(limits)}"); + return limits; + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStaticPrecompile.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStaticPrecompile.cs index 5b6c699ca..14ef07a2a 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStaticPrecompile.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStaticPrecompile.cs @@ -14,9 +14,12 @@ using SharpEmu.Logging; using SharpEmu.ShaderCompiler; using SharpEmu.ShaderCompiler.Metal; +using SharpEmu.ShaderCompiler.Resources; namespace SharpEmu.Gpu.Metal.V2; + + /// <summary> /// The static shader precompile: programs the game has not drawn or dispatched yet - those /// it creates this session (sceAgcCreateShader, ShaderInventory) and those the scanner finds @@ -273,7 +276,10 @@ private static void Run(nint device, string metalDirectory, string stamp, IGuest var titleDirectory = Path.GetDirectoryName(metalDirectory)!; _seedPath = StaticShaderPlanner.SeedPath(SharpEmuPaths.UserPath(), _titleId); var records = Recorded(); - var planner = StaticShaderPlanner.Open(titleDirectory, records, _seedPath); + // Predicted under this host's stable image budget, whatever budget the recorded sessions answered, so a predicted + // specialization is the one Translate's plan (and the session) takes. + var imageLimits = MetalStableImageLimits.Of(device); + var planner = StaticShaderPlanner.Open(titleDirectory, records, _seedPath, imageLimits); if (planner is null) { StaticShaderPlanner.DisableCapture(); @@ -487,7 +493,7 @@ private static void Process(StaticShaderPlanner planner, MetalBinaryArchive arch return; } - foreach (var shader in Translate(build, compiler)) + foreach (var shader in Translate(build, compiler, MetalStableImageLimits.Of(device))) { Interlocked.Increment(ref _translated); var key = MetalBinaryArchive.LibraryKey(shader.Source, shader.UsesPerVertexInputs); @@ -525,17 +531,16 @@ private static void Process(StaticShaderPlanner planner, MetalBinaryArchive arch } /// <summary>The MSL a build translates to, through the request builders of recorded programs.</summary> - internal static List<Gen5MslShader> Translate(StaticShaderBuild build, IGuestGpuBackend compiler) + internal static List<Gen5MslShader> Translate(StaticShaderBuild build, IGuestGpuBackend compiler, + StableImageDescriptorLimits stableImageLimits) { var shaders = new List<Gen5MslShader>(2); try { if (build.Compute is { } compute) { - if (ShaderPrewarmCompiler.TryCompilePrewarm(compute, build.ComputeCode!, compiler, - MetalRenderHost.PrewarmSharedInt64Atomics, MetalRenderHost.PrewarmExecGuardElision, - MetalRenderHost.PrewarmSignedZeroInfNanPreserve, out var compiled, out _, out _, - runtimeImageSwizzles: MetalRenderHost.PrewarmRuntimeImageSwizzles) && + if (MetalShaderPrewarm.TryCompileCompute(compute, build.ComputeCode!, compiler, stableImageLimits, + out var compiled, out _) && compiled is MetalCompiledGuestShader metal) { shaders.Add(metal.Shader); From 9acbbf57549218ea4efebe7ddc691f38654172c5 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 03:14:25 +0000 Subject: [PATCH 108/134] [Metal] Prepare call records, marks and faults for linked shader calls With the translator lowering linked programs, the Metal host now takes the shader calls the program cache links: - MetalV2Backend.LinkedShaderCallsSupported, and MetalRenderHost's RuntimeCallRecordsSupported / CallMarksSupported (the bindless heap must be on, as the records live in it), all behind SHARPEMU_METAL_SHADER_CALLS (default on; 0 compiles callers alone and skips their calls, as before). - Call records (MetalCallRecordPreparation, a port of the Vulkan presenter's preparation with upstream's SHARPEMU_CALL_RECORD_SPANS): each dispatch's sorted rows, the heap element of every field a callee reads through its record (one per slot and descriptor words from BindlessHeap.CallRecordFirstIndex), the memory the callees reach, merged. The words go up as the call_records field; the ranges are ordered, flushed and invalidated with the stage's device-address ranges; record textures stay current each submission and resident with the heap's. - Refusals are loud: exhausted record elements, rows past the shader's search depth, records whose written buffer describes no buffer, and integer record images (the shader reads record images through the float declaration) warn and count. - Call marks: two shared bitsets, swapped once the other's submissions completed and read into CallMarkedAt / CallMarkSnapshots for the program cache's callee tiers. - Call faults: the 8-word report a per-record call with no record claims is read at each flush and logged as [UNLINKED_CALL] with a counter. - LinkedProgramCacheDirectory: pipeline_cache/<title>/metal-v2/linked. CallRecordBufferPolicy exposes ShaderProgramCache.ClassifyRecordBuffer publicly, since Libs gives extracted backends public contracts only. Tests: MetalCallRecordPreparationTests ports upstream's CallRecordPreparationTests (per field and with spans) and CallRecordSpanTests without a device. --- docs/macos/configuration.md | 1 + .../Gpu/Pipelines/CallRecordBufferPolicy.cs | 17 + .../V2/MetalCallRecordPreparation.cs | 416 ++++++++++++++++++ .../V2/MetalRenderHost.BindlessHeap.cs | 5 +- .../V2/MetalRenderHost.Descriptors.cs | 32 +- .../V2/MetalRenderHost.ShaderCalls.cs | 294 +++++++++++++ .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 3 + .../SharpEmu.Gpu.Metal/V2/MetalV2Backend.cs | 3 + .../MetalCallRecordPreparationTests.cs | 272 ++++++++++++ 9 files changed, 1034 insertions(+), 9 deletions(-) create mode 100644 src/SharpEmu.Libs/Gpu/Pipelines/CallRecordBufferPolicy.cs create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalCallRecordPreparation.cs create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ShaderCalls.cs create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalCallRecordPreparationTests.cs diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 10f0c3726..8f801db78 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -70,6 +70,7 @@ them for measurements or to isolate a problem. | `SHARPEMU_METAL_MESH_SHADERS` | on | `0` disables mesh pipelines for primitive-shader draws. | | `SHARPEMU_METAL_DRAW_PARAMETERS` | on | `0` turns off draw parameters in translated vertex programs. By default a vertex program's instance index counts from the draw's base instance, and when an indirect draw names a user-data register for its base vertex or start instance, the program counts its vertex index from the base vertex and stores both bases there (the command processor no longer writes those registers). `0` gives the program Metal's ids, which include both bases, and stores nothing. | | `SHARPEMU_METAL_BINDLESS_HEAP` | on | `0` turns off the bindless heap. By default an image or sampler a program reads from a descriptor table at a record only the shader knows is read through the heap: the shader marks the records it reads, the host resolves each marked record's texture or sampler from guest memory, and the program reads it from a later draw on (the first read of a record returns zeros). `0` plans those tables as before (bindless image tables, at most 256 candidates, off-class candidates read null). | +| `SHARPEMU_METAL_SHADER_CALLS` | on | `0` turns off linked shader calls, as before they were ported to Metal. By default a program that calls functions with `S_SWAPPC_B64` is compiled with its callees linked in: the call compares the caller's address and argument with the dispatch's call targets and runs the matching callee. With the bindless heap on, a program can also be linked with run-time call records: the host writes the table of each dispatch's records and resolves the images and samplers they hold into the heap, and a call to a callee the program lacks is marked so the program cache links it later. A call that no record names ends its wave and logs `[UNLINKED_CALL]`. `0` compiles the caller alone, which skips the call. The callee lists are kept in `pipeline_cache/<title>/metal-v2/linked`. `SHARPEMU_CALL_RECORD_SPANS=0` reads each record field by field instead of once per record (same result); `SHARPEMU_RUNTIME_CALL_RECORDS=0` links one copy of a callee per record instead of using run-time records. | | `SHARPEMU_RUNTIME_IMAGE_SWIZZLE` | on | `0` bakes each storage image's destination select into the translated program, one program per select. By default a store reads the image's channel map from shader data, which the host writes from the bound descriptor. | | `SHARPEMU_METAL_FORMAT_LOAD_COMPONENT_BOUNDS` | on | `0` restores the old bound of a formatted buffer load whose format is fixed at translation: the whole element had to fit below the buffer's size. By default each selected component is checked at its own address, wrapping past 2^32 as on the hardware, so a component that wraps to the buffer's start is read, and the load reads its constants only when a selected component is out of range. An element that fits whole still takes one compare. Loads whose format is read at run time always check per component. | | `SHARPEMU_GRAPHICS_PARTIAL_LANES` | off | `1` makes pixel-shader lane reads (DPP, DPP8, PERMLANE16, V_READLANE) of a lane the fragment simdgroup never launched read the reading lane's own value, and treats such a lane as active when the guest EXEC mask has its bit. Off by default, as upstream: it changes every pixel shader with cross-lane operations. | diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/CallRecordBufferPolicy.cs b/src/SharpEmu.Libs/Gpu/Pipelines/CallRecordBufferPolicy.cs new file mode 100644 index 000000000..4dc9d7f5e --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/Pipelines/CallRecordBufferPolicy.cs @@ -0,0 +1,17 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +namespace SharpEmu.Libs.Gpu.Pipelines; + +// What a buffer a linked callee reads through its call record needs at a dispatch (ShaderProgramCache.ClassifyRecordBuffer), +// as a public contract for a backend that prepares call records outside this assembly (the Metal backend). +public static class CallRecordBufferPolicy +{ + // The buffer is made resident as a device-address range. + public static bool Resident(ulong address, ulong size, bool written) => + ShaderProgramCache.ClassifyRecordBuffer(address, size, written) == ShaderProgramCache.RecordBuffer.Resident; + + // The words describe no buffer and the callee writes through them: the record is left out (its call returns at once). + public static bool LeavesRecordOut(ulong address, ulong size, bool written) => + ShaderProgramCache.ClassifyRecordBuffer(address, size, written) == ShaderProgramCache.RecordBuffer.LeaveRecordOut; +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCallRecordPreparation.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCallRecordPreparation.cs new file mode 100644 index 000000000..4eea42fc1 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalCallRecordPreparation.cs @@ -0,0 +1,416 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.Gpu.Metal.V2; + +// The call records of a program linked with run-time record arguments: the port of the Vulkan presenter's preparation +// (VulkanVideoPresenter.CallRecords.cs and .CallRecordSpans.cs). For every record of a dispatch's tables, the image and +// sampler fields its callee reads through the record's argument get a heap element (the host's Element callback, from +// BindlessHeap.CallRecordFirstIndex on), and the words table the shader's call entries search is written +// (BindlessHeap.CallRecordKeyWords). The memory a callee reads through its record, its own reads and its buffers, comes back +// as device-address ranges the host orders and flushes as a planned range. Guest memory is read through the callbacks, so +// the preparation runs without a device in tests. +// +// Call record spans (upstream's SHARPEMU_CALL_RECORD_SPANS, on by default; "0" or any value but "1" turns them off): each +// record is read once over the span of its callee's fields and V#s, with the per-field preparation's rows, elements, words +// and merged ranges. +internal sealed class MetalCallRecordPreparation( + MetalCallRecordPreparation.GuestRead tryRead, + Func<ulong, ulong, bool> canRead, + MetalCallRecordPreparation.ElementOf element) +{ + internal delegate bool GuestRead(ulong address, Span<byte> destination); + + // The heap element of a field whose descriptor words were read: eight words, a sampler's last four zero. + internal delegate uint ElementOf(CallRecordField field, ReadOnlySpan<uint> words); + + internal static readonly bool ConfiguredSpans = + Environment.GetEnvironmentVariable("SHARPEMU_CALL_RECORD_SPANS") is null or "" or "1"; + + // Tests: the mode of this instance, whatever the configuration. + internal bool Spans { get; init; } = ConfiguredSpans; + + // Rows past the shader's search depth and records left out because a buffer they write describes no buffer. + internal long DroppedRows, LeftOutRecords; + private int _reports; + + private void Warn(string message) + { + if (_reports++ < 8) + { + Console.Error.WriteLine(message); + } + } + + internal (uint[] Words, DeviceAddressRange[] Ranges) Prepare(ShaderProgramInfo program, ShaderStageResources stage) => + Spans ? PrepareSpanned(program, stage) : PrepareOriginal(program, stage); + + // The preparation without call record spans, which is also their reference. + internal (uint[] Words, DeviceAddressRange[] Ranges) PrepareOriginal(ShaderProgramInfo program, ShaderStageResources stage) + { + var callees = program.CallRecordCallees; + var targets = stage.CallTargets ?? []; + var slotOf = new Dictionary<ulong, int>(targets.Length); + for (var slot = 0; slot < targets.Length; slot++) + { + slotOf.TryAdd(targets[slot], slot); + } + + var rows = new List<(uint Low, uint High, uint Callee, ulong Argument)>(stage.CallRecords?.Length ?? 0); + foreach (var (target, argument) in stage.CallRecords ?? []) + { + if (slotOf.TryGetValue(target, out var slot) && slot < callees.Count && + !LeavesRecordOut(callees[slot], target, argument, program.Hash)) + { + rows.Add(((uint)argument, (uint)(argument >> 32), (uint)slot, argument)); + } + } + + rows.Sort(static (left, right) => + left.High != right.High ? left.High.CompareTo(right.High) : + left.Low != right.Low ? left.Low.CompareTo(right.Low) : left.Callee.CompareTo(right.Callee)); + if (rows.Count > BindlessHeap.CallRecordMaximumRows) + { + DroppedRows += rows.Count - BindlessHeap.CallRecordMaximumRows; + Warn($"[METAL-V2][WARN] A dispatch has more call records than the shader searches: records={rows.Count} " + + $"searched={BindlessHeap.CallRecordMaximumRows} hash=0x{program.Hash:X16}."); + rows.RemoveRange((int)BindlessHeap.CallRecordMaximumRows, rows.Count - (int)BindlessHeap.CallRecordMaximumRows); + } + + var fieldWords = 0; + foreach (var row in rows) + { + fieldWords += callees[(int)row.Callee].Fields.Length; + } + + var keyWords = (int)BindlessHeap.CallRecordKeyWords; + var rowStarts = 1 + rows.Count * keyWords; + var words = new uint[Math.Max(rowStarts + rows.Count + fieldWords, (int)BindlessHeap.CallRecordMinimumWords)]; + words[0] = (uint)rows.Count; + var cursor = rowStarts + rows.Count; + var ranges = new List<DeviceAddressRange>(); + Span<uint> buffer = stackalloc uint[4]; + Span<uint> descriptor = stackalloc uint[8]; + for (var index = 0; index < rows.Count; index++) + { + var row = rows[index]; + words[1 + index * keyWords] = row.Low; + words[2 + index * keyWords] = row.High; + words[3 + index * keyWords] = row.Callee; + words[rowStarts + index] = (uint)cursor; + var callee = callees[(int)row.Callee]; + foreach (var field in callee.Fields) + { + descriptor.Clear(); + words[cursor++] = tryRead(row.Argument + field.Immediate, MemoryMarshal.AsBytes(descriptor[..(field.Sampler ? 4 : 8)])) + ? element(field, descriptor) + : BindlessHeap.CallRecordNullIndex; + } + + if (callee.ArgumentBytes != 0) + { + ranges.Add(new DeviceAddressRange(uint.MaxValue, row.Argument, callee.ArgumentBytes, true, false)); + } + + foreach (var field in callee.Buffers) + { + if (!tryRead(row.Argument + field.Immediate, MemoryMarshal.AsBytes(buffer))) + { + continue; + } + + var address = buffer[0] | ((ulong)(buffer[1] & 0xFFFF) << 32); + var stride = (buffer[1] >> 16) & 0x3FFF; + var size = (ulong)buffer[2] * Math.Max(stride, 1u); + if (CallRecordBufferPolicy.Resident(address, size, field.Written)) + { + ranges.Add(new DeviceAddressRange(uint.MaxValue, address, size, true, field.Written)); + } + } + } + + ranges.AddRange(stage.CallRecordRanges ?? []); + return (words, MergeRanges(ranges)); + } + + // Whether a record is left out because a buffer its callee writes holds no buffer descriptor + // (CallRecordBufferPolicy): its call returns at once instead of storing through it. + private bool LeavesRecordOut(CallRecordCallee callee, ulong target, ulong argument, ulong hash) + { + Span<uint> buffer = stackalloc uint[4]; + foreach (var field in callee.Buffers) + { + if (!tryRead(argument + field.Immediate, MemoryMarshal.AsBytes(buffer))) + { + continue; + } + + if (LeavesOut(buffer, field, target, argument, hash)) + { + return true; + } + } + + return false; + } + + private bool LeavesOut(ReadOnlySpan<uint> buffer, CallRecordBuffer field, ulong target, ulong argument, ulong hash) + { + var address = buffer[0] | ((ulong)(buffer[1] & 0xFFFF) << 32); + var size = (ulong)buffer[2] * Math.Max((buffer[1] >> 16) & 0x3FFF, 1u); + if (!CallRecordBufferPolicy.LeavesRecordOut(address, size, field.Written)) + { + return false; + } + + LeftOutRecords++; + Warn($"[METAL-V2][WARN][LINKED_PROGRAM] A call record's buffer describes no buffer; its call returns at once: " + + $"hash=0x{hash:X16} target=0x{target:X} argument=0x{argument:X} base=0x{address:X} size=0x{size:X}."); + return true; + } + + // Ranges that overlap or meet, or lie apart only by readable memory within a page, become one, so a dispatch makes few + // ranges resident for many records. + private DeviceAddressRange[] MergeRanges(List<DeviceAddressRange> ranges) + { + if (ranges.Count == 0) + { + return []; + } + + ranges.Sort(static (left, right) => left.Written != right.Written ? left.Written.CompareTo(right.Written) : left.Base.CompareTo(right.Base)); + var merged = new List<DeviceAddressRange>(ranges.Count); + var current = ranges[0]; + for (var index = 1; index < ranges.Count; index++) + { + var range = ranges[index]; + var end = current.Base + current.Size; + if (range.Written == current.Written && + (range.Base <= end || (range.Base - end <= 4096 && canRead(end, range.Base - end)))) + { + current = current with { Size = Math.Max(end, range.Base + range.Size) - current.Base }; + continue; + } + + merged.Add(current); + current = range; + } + + merged.Add(current); + return [.. merged]; + } + + // The bytes past a record's argument that its callee's fields (32 bytes for an image, 16 for a sampler) and buffer V#s + // (16 bytes) occupy: from the lowest immediate, Length bytes. Zero length when it reads none, or when they lie more than + // MaxSpan bytes apart; such records are read field by field. + private readonly record struct Span(uint First, int Length); + + private const int MaxSpan = 512; + + private static readonly ConditionalWeakTable<CallRecordCallee, StrongBox<Span>> SpanTable = new(); + + private static Span SpanOf(CallRecordCallee callee) => SpanTable.GetValue(callee, static callee => + { + var first = ulong.MaxValue; + var end = 0ul; + foreach (var field in callee.Fields) + { + first = Math.Min(first, field.Immediate); + end = Math.Max(end, (ulong)field.Immediate + (field.Sampler ? 16u : 32u)); + } + + foreach (var buffer in callee.Buffers) + { + first = Math.Min(first, buffer.Immediate); + end = Math.Max(end, (ulong)buffer.Immediate + 16u); + } + + return new StrongBox<Span>(first == ulong.MaxValue || end - first > MaxSpan + ? default : new Span((uint)first, (int)(end - first))); + }).Value; + + // A record the preparation keeps, with the offset of its span's bytes in the scratch (-1: read field by field). + private readonly record struct Row(uint Low, uint High, uint Callee, ulong Argument, int Bytes, uint First); + + private readonly Dictionary<ulong, int> _slotOf = new(); + private readonly List<Row> _rows = new(); + private byte[] _bytes = new byte[4096]; + private int _byteCount; + + // PrepareOriginal with each record read once over its span. + internal (uint[] Words, DeviceAddressRange[] Ranges) PrepareSpanned(ShaderProgramInfo program, ShaderStageResources stage) + { + var callees = program.CallRecordCallees; + var targets = stage.CallTargets ?? []; + _slotOf.Clear(); + for (var slot = 0; slot < targets.Length; slot++) + { + _slotOf.TryAdd(targets[slot], slot); + } + + var rows = _rows; + rows.Clear(); + _byteCount = 0; + foreach (var (target, argument) in stage.CallRecords ?? []) + { + if (!_slotOf.TryGetValue(target, out var slot) || slot >= callees.Count) + { + continue; + } + + var callee = callees[slot]; + var span = SpanOf(callee); + var bytes = -1; + if (span.Length != 0) + { + if (_bytes.Length - _byteCount < span.Length) + { + Array.Resize(ref _bytes, Math.Max(_bytes.Length * 2, _byteCount + span.Length)); + } + + if (tryRead(argument + span.First, _bytes.AsSpan(_byteCount, span.Length))) + { + bytes = _byteCount; + _byteCount += span.Length; + } + } + + var row = new Row((uint)argument, (uint)(argument >> 32), (uint)slot, argument, bytes, span.First); + if (!LeavesRecordOut(callee, target, program.Hash, row)) + { + rows.Add(row); + } + } + + rows.Sort(static (left, right) => + left.High != right.High ? left.High.CompareTo(right.High) : + left.Low != right.Low ? left.Low.CompareTo(right.Low) : left.Callee.CompareTo(right.Callee)); + if (rows.Count > BindlessHeap.CallRecordMaximumRows) + { + DroppedRows += rows.Count - BindlessHeap.CallRecordMaximumRows; + Warn($"[METAL-V2][WARN] A dispatch has more call records than the shader searches: records={rows.Count} " + + $"searched={BindlessHeap.CallRecordMaximumRows} hash=0x{program.Hash:X16}."); + rows.RemoveRange((int)BindlessHeap.CallRecordMaximumRows, rows.Count - (int)BindlessHeap.CallRecordMaximumRows); + } + + var fieldWords = 0; + foreach (var row in rows) + { + fieldWords += callees[(int)row.Callee].Fields.Length; + } + + var keyWords = (int)BindlessHeap.CallRecordKeyWords; + var rowStarts = 1 + rows.Count * keyWords; + var words = new uint[Math.Max(rowStarts + rows.Count + fieldWords, (int)BindlessHeap.CallRecordMinimumWords)]; + words[0] = (uint)rows.Count; + var cursor = rowStarts + rows.Count; + var ranges = new List<DeviceAddressRange>(); + Span<uint> descriptor = stackalloc uint[8]; + var argumentBase = 0ul; + var argumentEnd = 0ul; + var argumentOpen = false; + for (var index = 0; index < rows.Count; index++) + { + var row = rows[index]; + words[1 + index * keyWords] = row.Low; + words[2 + index * keyWords] = row.High; + words[3 + index * keyWords] = row.Callee; + words[rowStarts + index] = (uint)cursor; + var callee = callees[(int)row.Callee]; + foreach (var field in callee.Fields) + { + // As the per-field preparation: the words past a sampler's four stay zero in the key. + descriptor.Clear(); + words[cursor++] = ReadRecordWords(row, field.Immediate, descriptor[..(field.Sampler ? 4 : 8)]) + ? element(field, descriptor) + : BindlessHeap.CallRecordNullIndex; + } + + if (callee.ArgumentBytes != 0) + { + // An argument range that overlaps or meets the open one (rows ascend by argument) joins it, as the merge + // joins them; one whose end wraps is added on its own. + var end = row.Argument + callee.ArgumentBytes; + if (argumentOpen && row.Argument <= argumentEnd && end > row.Argument) + { + argumentEnd = Math.Max(argumentEnd, end); + } + else + { + if (argumentOpen) + { + ranges.Add(new DeviceAddressRange(uint.MaxValue, argumentBase, argumentEnd - argumentBase, true, false)); + argumentOpen = false; + } + + if (end > row.Argument) + { + (argumentBase, argumentEnd, argumentOpen) = (row.Argument, end, true); + } + else + { + ranges.Add(new DeviceAddressRange(uint.MaxValue, row.Argument, callee.ArgumentBytes, true, false)); + } + } + } + + foreach (var field in callee.Buffers) + { + var buffer = descriptor[..4]; + if (!ReadRecordWords(row, field.Immediate, buffer)) + { + continue; + } + + var address = buffer[0] | ((ulong)(buffer[1] & 0xFFFF) << 32); + var stride = (buffer[1] >> 16) & 0x3FFF; + var size = (ulong)buffer[2] * Math.Max(stride, 1u); + if (CallRecordBufferPolicy.Resident(address, size, field.Written)) + { + ranges.Add(new DeviceAddressRange(uint.MaxValue, address, size, true, field.Written)); + } + } + } + + if (argumentOpen) + { + ranges.Add(new DeviceAddressRange(uint.MaxValue, argumentBase, argumentEnd - argumentBase, true, false)); + } + + ranges.AddRange(stage.CallRecordRanges ?? []); + return (words, MergeRanges(ranges)); + } + + private bool LeavesRecordOut(CallRecordCallee callee, ulong target, ulong hash, in Row row) + { + Span<uint> buffer = stackalloc uint[4]; + foreach (var field in callee.Buffers) + { + if (ReadRecordWords(row, field.Immediate, buffer) && LeavesOut(buffer, field, target, row.Argument, hash)) + { + return true; + } + } + + return false; + } + + // The words at an immediate past a record's argument: from its span when it was read whole, else read now. + private bool ReadRecordWords(in Row row, uint immediate, Span<uint> destination) + { + var target = MemoryMarshal.AsBytes(destination); + if (row.Bytes < 0) + { + return tryRead(row.Argument + immediate, target); + } + + _bytes.AsSpan(row.Bytes + (int)(immediate - row.First), target.Length).CopyTo(target); + return true; + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessHeap.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessHeap.cs index 7e2a9afb9..b4ce18165 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessHeap.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessHeap.cs @@ -163,6 +163,8 @@ private unsafe Span<ulong> ElementSpan(int slot) => private void DisposeBindlessHeap() { _heapEntries.Clear(); + _callRecordEntries.Clear(); + _callRecordTextures.Order.Clear(); _heapRegionEntries.Clear(); _heapImageViews.ReleaseIdle(ulong.MaxValue, ulong.MaxValue, static _ => { }); _heapSamplerViews.ReleaseIdle(ulong.MaxValue, ulong.MaxValue, static _ => { }); @@ -740,7 +742,8 @@ private void BindBindlessHeap() var textures = new List<nint>(); _heapTextures.Declared.Clear(); var signature = 0UL; - foreach (var entry in _heapEntries.Values) + // The heap's records, and the call records' (MetalRenderHost.ShaderCalls.cs). + foreach (var entry in _heapEntries.Values.Concat(_callRecordEntries.Values)) { if (entry.Texture == 0) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs index 66afbf74f..ef41a2a49 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs @@ -61,6 +61,9 @@ internal sealed class MetalStageBindings : IPreparedBindings public MetalGuestRange[] Buffers = []; public uint[] BufferLengths = []; public uint[] ShaderData = []; + // A linked program's call record table and the memory its callees read through the records (MetalRenderHost.ShaderCalls.cs). + public uint[] CallRecordWords = []; + public DeviceAddressRange[] CallRecordRanges = []; public ulong[] BindlessTableAddresses = []; // The stage's heap views as shader data (MetalRenderHost.BindlessHeap.cs), found before its images. public uint[] HeapViews = []; @@ -599,6 +602,7 @@ public IPreparedBindings PrepareBindings(ShaderStageResources stage) stage.WriteDispatchThreadLimits(shaderData.AsSpan(0, shaderDwords)); stage.WriteCallData(shaderData.AsSpan(0, shaderDwords)); + PrepareCallRecords(prepared, program, stage); if (packet is not null) { RecyclePacket(packet); @@ -1258,13 +1262,17 @@ private static (ulong, ulong) ParseRangeOverlap(string? text) private void BindDeviceAddressRanges( MetalStageBindings stage, ShaderResourceInfo info, ResourceSnapshot snapshot) { + // A linked program's call records add the memory their callees read through the records (PrepareCallRecords). + var deviceRanges = stage.CallRecordRanges.Length == 0 + ? snapshot.DeviceAddressRanges + : [.. snapshot.DeviceAddressRanges, .. stage.CallRecordRanges]; var unplanned = false; var declaredWrite = false; - if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled && (stage.Program.UsesDeviceAddresses || snapshot.DeviceAddressRanges.Length != 0)) + if (SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.Enabled && (stage.Program.UsesDeviceAddresses || deviceRanges.Length != 0)) { // An encoder running a device-address program: its reach is evaluated only when every handle is planned. var planned = true; - foreach (var range in snapshot.DeviceAddressRanges) + foreach (var range in deviceRanges) { planned &= range.Planned; } @@ -1273,17 +1281,17 @@ private void BindDeviceAddressRanges( } BeginDeviceRangeOrdering(stage); - if (snapshot.DeviceAddressRanges.Length != 0 && _singleCopy is { } singleCopy) + if (deviceRanges.Length != 0 && _singleCopy is { } singleCopy) { // Counted, and given back, only if the program got past BeforeDeviceAddressPreparation: // ranges it pinned are known and cost a lookup each. _mappedDeviceAddressBytes ??= MappedDeviceAddressBytes; singleCopy.BeforeDeviceAddressProgram( - info.WritesDeviceAddresses, snapshot.DeviceAddressRanges, DeviceAddressMappingVersion(), + info.WritesDeviceAddresses, deviceRanges, DeviceAddressMappingVersion(), _mappedDeviceAddressBytes, late: true); } - foreach (var range in snapshot.DeviceAddressRanges) + foreach (var range in deviceRanges) { if (!range.Planned) { @@ -1344,7 +1352,7 @@ private void BindDeviceAddressRanges( { Console.Error.WriteLine( $"[METAL-V2][BIG-WRITEBACK-RANGE] stage={stage.Program.Stage} hash=0x{stage.Program.Hash:X16} h{range.Handle} " + - $"base=0x{range.Base:X} size=0x{size:X}{(range.Written ? " written" : string.Empty)} ranges={snapshot.DeviceAddressRanges.Length}"); + $"base=0x{range.Base:X} size=0x{size:X}{(range.Written ? " written" : string.Empty)} ranges={deviceRanges.Length}"); } if (!range.Written) { @@ -1380,8 +1388,8 @@ private void BindDeviceAddressRanges( $"device-address-unbounded-{stage.Program.Hash:X16}", $"A shader stores through the device-address page table with no evaluated range, so every " + $"later guest read waits for its submission: hash=0x{stage.Program.Hash:X16} " + - $"unplanned={unplanned} ranges={snapshot.DeviceAddressRanges.Length} [" + - string.Join(", ", snapshot.DeviceAddressRanges.Select(static range => + $"unplanned={unplanned} ranges={deviceRanges.Length} [" + + string.Join(", ", deviceRanges.Select(static range => $"h{range.Handle} {(range.Planned ? "planned" : "unplanned")} {(range.Written ? "written" : "read")} " + $"0x{range.Base:X}+0x{range.Size:X}")) + "]."); } @@ -1862,6 +1870,9 @@ private void WriteArgumentBuffer(MetalStageBindings stage, int stageIndex) case MslArgumentFieldKind.BindlessHeapFeedback: BinaryPrimitives.WriteUInt64LittleEndian(span, RequireHeapAddress(_heapFeedbackAddress, stage)); break; + case MslArgumentFieldKind.CallFaults: + BinaryPrimitives.WriteUInt64LittleEndian(span, CallFaultsAddress()); + break; case MslArgumentFieldKind.BindlessImageTables: for (var index = 0; index < field.Count; index++) { @@ -2062,6 +2073,10 @@ private ulong PointerFieldValue(MetalStageBindings stage, DescriptorBindingKind return UploadDwords(stage.ShaderData.AsSpan(0, (int)stage.Program.Bindings!.ShaderDataDwordCount)); case DescriptorBindingKind.MipStatistics: return LodStatisticsAddress(); + case DescriptorBindingKind.CallRecords: + return UploadDwords(stage.CallRecordWords); + case DescriptorBindingKind.CallMarks: + return CallMarksAddress(); default: throw Fatal($"The argument layout has a pointer field of an unknown kind: kind={kind}."); } @@ -2075,6 +2090,7 @@ private ulong PointerFieldValue(MetalStageBindings stage, DescriptorBindingKind DescriptorBindingKind.FlattenedResourceTable => (uint)stage.StageResources.Resources.FlattenedResourceTable.Length, DescriptorBindingKind.ShaderData => stage.Program.Bindings!.ShaderDataDwordCount, + DescriptorBindingKind.CallRecords => (uint)stage.CallRecordWords.Length, _ => throw Fatal($"The argument layout has a word field of an unknown kind: kind={kind}."), }; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ShaderCalls.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ShaderCalls.cs new file mode 100644 index 000000000..a8d8f6d79 --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ShaderCalls.cs @@ -0,0 +1,294 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Numerics; +using System.Runtime.InteropServices; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.VideoOut; +using SharpEmu.Logging; +using SharpEmu.ShaderCompiler.Metal; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.Gpu.Metal.V2; + +// Linked shader calls (Gen5ShaderCallLinker, lowered by Gen5MslTranslator.ShaderCalls.cs). SHARPEMU_METAL_SHADER_CALLS=0 +// turns all of it off, as before the port: the program cache compiles a caller alone and skips its calls. +// - Call records of programs linked with run-time arguments (MetalCallRecordPreparation): the words table a dispatch's +// call entries search, the heap elements of the descriptors its callees read through their records (from +// BindlessHeap.CallRecordFirstIndex on; they need the bindless heap), and the memory they reach, ordered and flushed with +// the stage's device-address ranges. +// - Call marks (CallMarks): two shared bitsets; dispatches mark the active one, and once the other's submissions have +// completed it is read, its bits stamped with the snapshot number (CallMarkedAt) and cleared, and the two swap. The +// program cache compares the stamps with the snapshot in which it named a callee (ShaderCalleeTiers). +// - Call faults: a call of a program linked per record that no record names claims an 8-word report +// (Gen5MslArgumentLayout.CallFaultWords), read once per flush and logged as [UNLINKED_CALL] with a counter. +internal sealed partial class MetalRenderHost +{ + internal static readonly bool ShaderCallsEnabled = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_SHADER_CALLS") != "0"; + + // Records live in the bindless heap, so they need it; marks exist only for programs linked with run-time records. + public bool RuntimeCallRecordsSupported => ShaderCallsEnabled && BindlessHeapEnabled; + + public bool CallMarksSupported => RuntimeCallRecordsSupported; + + public long CallMarkSnapshots => Volatile.Read(ref _callMarkSnapshots); + + public long CallMarkedAt(uint bit) => Volatile.Read(ref _callMarkedAt[bit & (CallMarks.Bits - 1)]); + + // pipeline_cache/<title>/metal-v2/linked, beside the translations and analysis caches (MetalTranslationCache). + public string? LinkedProgramCacheDirectory => ShaderCallsEnabled + ? _linkedProgramCacheDirectory ??= SharpEmuPaths.UserPath("pipeline_cache", + MetalShaderPrewarm.SanitizeTitleId(VideoOutBackendServices.GetApplicationTitleId()), "metal-v2", "linked") + : null; + + private string? _linkedProgramCacheDirectory; + + // Call records. + private readonly record struct CallRecordKey(int Slot, ulong First, ulong Second, ulong Third, ulong Fourth); + + private readonly Dictionary<CallRecordKey, HeapEntry> _callRecordEntries = new(); + private readonly uint[] _callRecordNext = new uint[BindlessHeap.ArrayCount]; + private readonly HeapRegionEntries _callRecordTextures = new(); + private MetalCallRecordPreparation? _callRecordPreparation; + private int _callRecordReports; + + internal long CallRecordElementsExhausted, CallRecordIntegerImages, UnlinkedCalls; + + internal MetalCallRecordPreparation CallRecordPreparation => _callRecordPreparation ??= new MetalCallRecordPreparation( + ReadCallRecordBytes, (address, size) => _memory.CanRead(address, size), CallRecordElement); + + // The stage's call record words and ranges, for a program whose callees read descriptors through their records. + private void PrepareCallRecords(MetalStageBindings prepared, ShaderProgramInfo program, ShaderStageResources stage) + { + prepared.CallRecordWords = []; + prepared.CallRecordRanges = []; + if (program.CallRecordCallees.Count == 0) + { + return; + } + + if (!RuntimeCallRecordsSupported) + { + throw Fatal($"A program reads call records with linked shader calls or the bindless heap off: hash=0x{program.Hash:X16}."); + } + + PrepareBindlessHeap(); + (prepared.CallRecordWords, prepared.CallRecordRanges) = CallRecordPreparation.Prepare(program, stage); + // Each record texture as an acquire now would give it, noted as used by this submission. + MakeHeapRegionCurrent(_callRecordTextures, SubmissionSerial); + } + + private bool ReadCallRecordBytes(ulong address, Span<byte> destination) + { + if (TryReadResidentGuestBytes(address, destination, clean: true)) + { + return true; + } + + // Bytes a recorded GPU write may still own: read word by word, which waits for the write. + if ((destination.Length & 3) != 0) + { + return false; + } + + var words = MemoryMarshal.Cast<byte, uint>(destination); + for (var word = 0; word < words.Length; word++) + { + if (!TryReadGuestWord(address + (ulong)word * sizeof(uint), out words[word])) + { + return false; + } + } + + return true; + } + + // The heap element that holds the descriptor of one record field: one per distinct descriptor and array, resolved when + // it is first seen. A record's image is read through the float declaration of its class, so an integer texture is + // refused to the null element (warn + counter), never read through the wrong declaration. + private uint CallRecordElement(CallRecordField field, ReadOnlySpan<uint> words) + { + static ulong Pair(uint low, uint high) => low | ((ulong)high << 32); + var key = new CallRecordKey(field.Slot, Pair(words[0], words[1]), Pair(words[2], words[3]), Pair(words[4], words[5]), + Pair(words[6], words[7])); + if (_callRecordEntries.TryGetValue(key, out var entry)) + { + return entry.Index; + } + + var next = _callRecordNext[field.Slot]; + if (BindlessHeap.CallRecordFirstIndex + next >= BindlessHeap.CallRecordNullIndex) + { + CallRecordElementsExhausted++; + if (_callRecordReports++ < 8) + { + Console.Error.WriteLine($"[METAL-V2][WARN] The call record elements of a bindless heap array are used up: slot={field.Slot}; " + + "further records read as null."); + } + + return BindlessHeap.CallRecordNullIndex; + } + + _callRecordNext[field.Slot] = next + 1; + entry = new HeapEntry + { + Slot = field.Slot, + Index = BindlessHeap.CallRecordFirstIndex + next, + Words = words[..(field.Sampler ? 4 : 8)].ToArray(), + }; + _callRecordEntries.Add(key, entry); + _callRecordTextures.Order.Add(entry); + if (entry.Slot < BindlessHeap.ImageKinds.Length && + HeapRecordClass(entry, entry.Words) is not (ImageNumericClass.Float or ImageNumericClass.Unsupported)) + { + CallRecordIntegerImages++; + if (_callRecordReports++ < 8) + { + Console.Error.WriteLine($"[METAL-V2][WARN] A call record holds an integer image, which the shader reads through its " + + $"float declaration: slot={field.Slot} element={entry.Index}; it reads as null."); + } + + WriteHeapImage(entry.Slot, entry.Index, 0); + return entry.Index; + } + + ResolveHeapEntry(entry); + return entry.Index; + } + + // Call marks. + private readonly long[] _callMarkedAt = new long[CallMarks.Bits]; + private long _callMarkSnapshots; + private readonly nint[] _callMarkBuffers = new nint[2]; + private readonly nint[] _callMarkContents = new nint[2]; + private readonly ulong[] _callMarkAddresses = new ulong[2]; + // The last submission that bound each bitset, and whether it holds marks not read yet. + private readonly ulong[] _callMarkSerial = new ulong[2]; + private readonly bool[] _callMarkPending = new bool[2]; + private int _callMarkActive; + + private unsafe Span<uint> CallMarkWords(int index) => new((void*)_callMarkContents[index], (int)CallMarks.Words); + + private ulong CallMarksAddress() + { + if (_callMarkBuffers[0] == 0) + { + for (var index = 0; index < 2; index++) + { + _callMarkBuffers[index] = _guestMemory.CreateReportBuffer(CallMarks.Bytes, $"SharpEmu call marks {index}", + out _callMarkContents[index], out _callMarkAddresses[index]); + CallMarkWords(index).Clear(); + } + } + + var active = _callMarkActive; + _callMarkSerial[active] = SubmissionSerial; + _callMarkPending[active] = true; + NoteUsedResource(_callMarkBuffers[active], Mtl.ResourceUsageRead | Mtl.ResourceUsageWrite); + return _callMarkAddresses[active]; + } + + // Once per flush: the inactive bitset, once every submission that bound it has completed, is read and cleared; then a + // bitset bound since the last swap gives way to the cleared one. + private void PollCallMarks() + { + if (_callMarkBuffers[0] == 0) + { + return; + } + + var other = 1 - _callMarkActive; + if (_callMarkPending[other] && _callMarkSerial[other] <= CompletedSerial) + { + var words = CallMarkWords(other); + var snapshot = Volatile.Read(ref _callMarkSnapshots) + 1; + for (var word = 0; word < words.Length; word++) + { + for (var bits = Volatile.Read(ref words[word]); bits != 0; bits &= bits - 1) + { + Volatile.Write(ref _callMarkedAt[word * 32 + BitOperations.TrailingZeroCount(bits)], snapshot); + } + } + + words.Clear(); + _callMarkPending[other] = false; + Volatile.Write(ref _callMarkSnapshots, snapshot); + } + + if (!_callMarkPending[other] && _callMarkPending[_callMarkActive]) + { + _callMarkActive = other; + } + } + + // Call faults. + private nint _callFaultBuffer; + private nint _callFaultContents; + private ulong _callFaultAddress; + + private unsafe Span<uint> CallFaultWords => new((void*)_callFaultContents, Gen5MslArgumentLayout.CallFaultWords); + + private ulong CallFaultsAddress() + { + if (_callFaultBuffer == 0) + { + _callFaultBuffer = _guestMemory.CreateReportBuffer(Gen5MslArgumentLayout.CallFaultWords * sizeof(uint), "SharpEmu call faults", + out _callFaultContents, out _callFaultAddress); + CallFaultWords.Clear(); + } + + NoteUsedResource(_callFaultBuffer, Mtl.ResourceUsageRead | Mtl.ResourceUsageWrite); + return _callFaultAddress; + } + + // Once per flush: a claimed report names the caller, the call and its target; the waves that made the call ended at it. + private void ReportCallFaults() + { + PollCallMarks(); + if (_callFaultBuffer == 0) + { + return; + } + + var words = CallFaultWords; + if (Volatile.Read(ref words[0]) != 2) + { + return; + } + + var hash = (ulong)words[2] << 32 | words[1]; + var target = (ulong)words[5] << 32 | words[4]; + var pc = words[3]; + var stage = words[6]; + words[1..].Clear(); + Volatile.Write(ref words[0], 0u); + var unlinked = ++UnlinkedCalls; + if (unlinked <= 16 || (unlinked & (unlinked - 1)) == 0) + { + Console.Error.WriteLine($"[METAL-V2][WARN][UNLINKED_CALL] The shader called an unlinked function: hash=0x{hash:X16} " + + $"pc=0x{pc:X} target=0x{target:X16} stage={stage} count={unlinked}. The waves that made the call were ended; " + + "images can be incorrect."); + } + } + + private void DisposeShaderCalls() + { + _callRecordEntries.Clear(); + _callRecordTextures.Order.Clear(); + foreach (ref var buffer in _callMarkBuffers.AsSpan()) + { + if (buffer != 0) + { + MetalNative.SendVoid(buffer, MetalNative.Selector("release")); + buffer = 0; + } + } + + if (_callFaultBuffer != 0) + { + MetalNative.SendVoid(_callFaultBuffer, MetalNative.Selector("release")); + _callFaultBuffer = 0; + } + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index 18dbe6bd7..fd7b500cc 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -768,6 +768,7 @@ private ulong FlushCommandBuffer(PassEndCause cause, MetalFlushCause why) // every submission's status is read once it has finished. DrainFinishedSubmissions(); ReportStepCaps(); + ReportCallFaults(); RetainInFlight(_commandBuffer, serial); // The host's own reference on the buffer it just committed, for the wait that reads // its timing after this flush (or after a later call that flushed nothing). The @@ -3280,7 +3281,9 @@ public void Dispose() RetireUploadPreludes(CompletedSerial, all: true); ReleaseInFlightSubmissions(); ReportStepCaps(); + ReportCallFaults(); DisposeStepReport(); + DisposeShaderCalls(); } catch (Exception exception) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Backend.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Backend.cs index 44326ca25..92eff4517 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Backend.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalV2Backend.cs @@ -29,6 +29,9 @@ internal sealed class MetalV2Backend : IGuestGpuBackend public string BackendName => "Metal v2"; + // Linked shader calls lower to MSL (Gen5MslTranslator.ShaderCalls.cs); SHARPEMU_METAL_SHADER_CALLS=0 compiles callers alone. + public bool LinkedShaderCallsSupported => MetalRenderHost.ShaderCallsEnabled; + /// <summary> /// v2 builds MTLMeshRenderPipelineDescriptor pipelines and launches /// drawMeshThreadgroups, so the merged ES/GS stage runs as what it is. diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalCallRecordPreparationTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalCallRecordPreparationTests.cs new file mode 100644 index 000000000..d1e7c4a68 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalCallRecordPreparationTests.cs @@ -0,0 +1,272 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Buffers.Binary; +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +// The call record preparation of the Metal host (MetalCallRecordPreparation), without a device: the rows and words table a +// linked program's call entries search, the buffer policy (a record whose written buffer describes no buffer is left out; +// a buffer it describes is a resident range), and call record spans preparing what the per-field preparation prepares. The +// Metal twins of tests/SharpEmu.Libs.Tests/VideoOut/CallRecordPreparationTests.cs and CallRecordSpanTests.cs. +public class MetalCallRecordPreparationTests +{ + // Off: the per-field preparation. The derived class runs every case with call record spans. + protected virtual bool Spans => false; + + private const ulong Target = 0x2000; + private const ulong Argument = 0x1000; + + // Guest memory of one mapped region. + internal sealed class Memory(ulong start, int size) + { + private readonly byte[] _bytes = new byte[size]; + + public bool CanRead(ulong address, ulong length) => + address >= start && length <= (ulong)_bytes.Length && address - start <= (ulong)_bytes.Length - length; + + public bool TryRead(ulong address, Span<byte> destination) + { + if (!CanRead(address, (ulong)destination.Length)) return false; + _bytes.AsSpan((int)(address - start), destination.Length).CopyTo(destination); + return true; + } + + public void Write(ulong address, ReadOnlySpan<byte> source) + { + Assert.True(CanRead(address, (ulong)source.Length)); + source.CopyTo(_bytes.AsSpan((int)(address - start))); + } + } + + internal sealed record Prepared(uint[] Words, DeviceAddressRange[] Ranges, List<string> Elements); + + // The elements stand in for the bindless heap (which needs a device): each call is listed with its slot and words and + // gets the next number. + internal static Prepared Prepare(bool spans, Memory memory, CallRecordCallee[] callees, ulong[] targets, + (ulong Target, ulong Argument)[] records, DeviceAddressRange[]? stageRanges = null) + { + var elements = new List<string>(); + var preparation = new MetalCallRecordPreparation(memory.TryRead, memory.CanRead, (field, words) => + { + elements.Add($"{field.Slot}:{string.Join(",", words.ToArray())}"); + return (uint)elements.Count; + }) + { Spans = spans }; + var program = new ShaderProgramInfo { CallRecordCallees = callees }; + var stage = new ShaderStageResources(program, new ResourceSnapshot()) + { + CallTargets = targets, + CallRecords = records, + CallRecordRanges = stageRanges, + }; + var (words, ranges) = preparation.Prepare(program, stage); + return new(words, ranges, elements); + } + + private (uint[] Words, DeviceAddressRange[] Ranges) Prepare(Memory memory, CallRecordBuffer[] buffers, + params (ulong Target, ulong Argument)[] records) + { + var prepared = Prepare(Spans, memory, [new CallRecordCallee([], buffers, 64)], [Target], records); + return (prepared.Words, prepared.Ranges); + } + + internal static void Descriptor(Memory memory, ulong at, ulong address, uint records, uint stride = 0) + { + Span<byte> bytes = stackalloc byte[16]; + BinaryPrimitives.WriteUInt32LittleEndian(bytes, (uint)address); + BinaryPrimitives.WriteUInt32LittleEndian(bytes[4..], (uint)(address >> 32) | stride << 16); + BinaryPrimitives.WriteUInt32LittleEndian(bytes[8..], records); + BinaryPrimitives.WriteUInt32LittleEndian(bytes[12..], 0); + memory.Write(at, bytes); + } + + [Fact] + public void ARecordWithoutBufferFieldsKeepsItsKeyAndArgumentRange() + { + var memory = new Memory(Argument, 0x2000); + var result = Prepare(memory, [], (Target, Argument)); + Assert.Equal(1u, result.Words[0]); + Assert.Equal((uint)Argument, result.Words[1]); + Assert.Equal(0u, result.Words[2]); + Assert.Equal(0u, result.Words[3]); + Assert.Contains(result.Ranges, range => range.Base == Argument && range.Size == 64 && !range.Written); + } + + [Theory] + [InlineData(0x8000ul, 64u, false, true, true)] + [InlineData(0x8000ul, 64u, true, true, true)] + [InlineData(1ul << 40, 64u, false, true, false)] + [InlineData(1ul << 40, 64u, true, false, false)] + [InlineData(0ul, 64u, false, true, false)] + [InlineData(0ul, 64u, true, true, false)] + [InlineData(0x8000ul, 0u, false, true, false)] + [InlineData(0x8000ul, 0u, true, true, false)] + public void BufferPolicyControlsTheUploadedRowAndResidentRange(ulong address, uint size, bool written, bool keep, bool resident) + { + var memory = new Memory(Argument, 0x2000); + Descriptor(memory, Argument, address, size); + var result = Prepare(memory, [new CallRecordBuffer(0, written)], (Target, Argument)); + Assert.Equal(keep ? 1u : 0u, result.Words[0]); + if (!keep) + { + Assert.Empty(result.Ranges); + return; + } + + Assert.Equal((uint)Argument, result.Words[1]); + Assert.Contains(result.Ranges, range => range.Base == Argument && range.Size == 64 && !range.Written); + Assert.Equal(resident, result.Ranges.Any(range => range.Base == address && range.Size == size && range.Written == written)); + } + + [Fact] + public void AnInvalidWritableRecordDoesNotRemoveTheValidRecordBesideIt() + { + var memory = new Memory(Argument, 0x2000); + Descriptor(memory, Argument, 0x8000, 64); + Descriptor(memory, Argument + 0x100, 1ul << 40, 64); + var result = Prepare(memory, [new CallRecordBuffer(0, true)], (Target, Argument + 0x100), (Target, Argument)); + Assert.Equal(1u, result.Words[0]); + Assert.Equal((uint)Argument, result.Words[1]); + Assert.Contains(result.Ranges, range => range.Base == 0x8000 && range.Written); + Assert.DoesNotContain(result.Ranges, range => range.Base == Argument + 0x100); + } + + [Fact] + public void AnUnreadableFieldPreservesTheExistingKeepRecordPolicy() + { + var memory = new Memory(Argument, 0x2000); + var result = Prepare(memory, [new CallRecordBuffer(0, true)], (Target, 0x5000)); + Assert.Equal(1u, result.Words[0]); + Assert.Equal(0x5000u, result.Words[1]); + Assert.Equal(0x5000ul, Assert.Single(result.Ranges).Base); + } + + // Rows sort by argument (high, low) and callee; each row's first field index points at its fields' elements, which the + // shader reads as call_records[call_records[1 + rows * 3 + row] + field]. + [Fact] + public void RowsSortByArgumentAndCalleeAndNameTheirFieldElements() + { + var memory = new Memory(Argument, 0x2000); + CallRecordCallee[] callees = [new([new CallRecordField(0, false, 0), new CallRecordField(32, true, 8)], [], 0), new([], [], 0)]; + var prepared = Prepare(Spans, memory, callees, [0x2000, 0x3000], + [(0x2000, Argument + 0x40), (0x3000, Argument), (0x2000, Argument), (0x9000, Argument)]); + Assert.Equal(3u, prepared.Words[0]); + Assert.Equal(new uint[] { (uint)Argument, 0, 0, (uint)Argument, 0, 1, (uint)Argument + 0x40, 0, 0 }, prepared.Words[1..10]); + var starts = prepared.Words[10..13]; + Assert.Equal(new uint[] { 1, 2 }, prepared.Words[(int)starts[0]..((int)starts[0] + 2)]); + Assert.Equal(starts[0] + 2, starts[1]); + Assert.Equal(new uint[] { 3, 4 }, prepared.Words[(int)starts[2]..((int)starts[2] + 2)]); + } +} + +public sealed class SpannedMetalCallRecordPreparationTests : MetalCallRecordPreparationTests +{ + protected override bool Spans => true; +} + +// Call record spans: on the same memory the preparation hands the heap the same descriptor words in the same order, and +// writes the same words table and merged ranges, as the per-field preparation. +public sealed class MetalCallRecordSpanTests +{ + private const ulong Base = 0x10000; + private const int Size = 0x10000; + + // Callees whose fields and V#s lie within one span, one whose span is too wide to read whole, one that reads nothing. + private static readonly CallRecordCallee[] Callees = + [ + new([new CallRecordField(0, false, 1), new CallRecordField(32, true, 7)], [new CallRecordBuffer(48, false)], 64), + new([], [new CallRecordBuffer(0, true), new CallRecordBuffer(16, false)], 32), + new([new CallRecordField(0x100, false, 2)], [new CallRecordBuffer(0, false)], 0), + new([new CallRecordField(0, false, 3)], [new CallRecordBuffer(0x300, false)], 16), + new([], [], 16), + ]; + + private static readonly ulong[] Targets = [0x2000, 0x3000, 0x4000, 0x5000, 0x6000]; + + private static void Same(MetalCallRecordPreparationTests.Prepared expected, MetalCallRecordPreparationTests.Prepared actual) + { + Assert.Equal(expected.Words, actual.Words); + Assert.Equal(expected.Ranges, actual.Ranges); + Assert.Equal(expected.Elements, actual.Elements); + } + + // Random memory with valid, null and invalid V#s, and records whose spans lie inside the region, cross its end or lie past + // it, with unknown targets and repeated arguments. + private static (MetalCallRecordPreparationTests.Memory Memory, (ulong, ulong)[] Records) RandomRecords(int seed, int count) + { + var random = new Random(seed); + var memory = new MetalCallRecordPreparationTests.Memory(Base, Size); + var noise = new byte[Size]; + random.NextBytes(noise); + memory.Write(Base, noise); + var records = new List<(ulong, ulong)>(); + for (var index = 0; index < count; index++) + { + var argument = Base + (ulong)random.Next(0, Size + 0x400) / 16 * 16; + if (random.Next(4) == 0 && records.Count != 0) argument = records[random.Next(records.Count)].Item2; + var target = random.Next(12) == 0 ? 0x9000ul : Targets[random.Next(Targets.Length)]; + if (random.Next(3) == 0) + { + foreach (var immediate in new uint[] { 0, 16, 48, 0x300 }) + { + if (argument + immediate + 16 <= Base + Size) + MetalCallRecordPreparationTests.Descriptor(memory, argument + immediate, 0x8000 + (ulong)random.Next(0x1000) * 16, + (uint)random.Next(1, 64), 16); + } + } + else if (random.Next(3) == 0 && argument + 32 <= Base + Size) + { + MetalCallRecordPreparationTests.Descriptor(memory, argument, 0, 0); + MetalCallRecordPreparationTests.Descriptor(memory, argument + 16, 1ul << 40, 64); + } + + if (!records.Contains((target, argument))) records.Add((target, argument)); + } + + return (memory, [.. records]); + } + + [Theory] + [InlineData(1, 8)] + [InlineData(2, 64)] + [InlineData(3, 300)] + [InlineData(4, 2000)] + public void SpansPrepareWhatTheOriginalPrepares(int seed, int count) + { + var (memory, records) = RandomRecords(seed, count); + DeviceAddressRange[] stageRanges = [new(3, 0x8000, 0x40, true, false), new(4, 0x9000, 0x20, true, true)]; + var original = MetalCallRecordPreparationTests.Prepare(false, memory, Callees, Targets, records, stageRanges); + Same(original, MetalCallRecordPreparationTests.Prepare(true, memory, Callees, Targets, records, stageRanges)); + Assert.NotEmpty(original.Elements); + Assert.True(original.Words[0] > 0); + } + + // A record whose span crosses the end of mapped memory is read field by field: the fields inside still read, and the + // ones past the end take the null element, as in the original. + [Fact] + public void ASpanPastMappedMemoryReadsFieldByField() + { + var memory = new MetalCallRecordPreparationTests.Memory(Base, Size); + var argument = Base + Size - 40; + MetalCallRecordPreparationTests.Descriptor(memory, argument + 16, 0x8000, 4, 16); + var records = new[] { (Targets[1], argument), (Targets[0], argument) }; + var original = MetalCallRecordPreparationTests.Prepare(false, memory, Callees, Targets, records); + var spanned = MetalCallRecordPreparationTests.Prepare(true, memory, Callees, Targets, records); + Same(original, spanned); + Assert.Contains(spanned.Ranges, range => range.Base == 0x8000 && range.Size == 64); + Assert.Single(spanned.Elements); + Assert.Equal(BindlessHeap.CallRecordNullIndex, spanned.Words[^1]); + } + + [Fact] + public void SpansAreOnUnlessConfigured() + { + if (Environment.GetEnvironmentVariable("SHARPEMU_CALL_RECORD_SPANS") is not null) return; + Assert.True(MetalCallRecordPreparation.ConfiguredSpans); + } +} From 3d977d288d1362a86848530a474adf688d4b6697 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 03:15:10 +0000 Subject: [PATCH 109/134] [Shader] Reduce wave32 DPP row scans read at lanes 15/31 over the simdgroup in MSL Port of Gen5SpirvTranslator.WaveReductions (upstream 7cf0ac568) to the MSL translator. With ShaderCompileRequest.SubgroupArithmetic on, a pixel or wave32 compute program whose block holds the exact row scan (S_AND mask from an entry-EXEC copy, S_ORN2_SAVEEXEC of EXEC, V_CNDMASK identity/value/mask, DPP row_shr 1/2/4/8, optional EXEC restore, V_READLANE 15 and/or 31) has each read replaced by simd_<op> over the V_CNDMASK result of its row, the identity elsewhere. Same matcher and proofs as the SPIR-V one, on the MSL translator's own (more conservative) scalar-write helpers. A fragment simdgroup holding one quad has a row with no running lane: the nearest running lane read of lane 31 returned row 0's scan where the PS5 returns the identity, and a partial compute group shuffled from a lane that does not exist. The device tests (compute 32/20/12 threads, a one-quad fragment simdgroup; all eight operations; reads of 15, 31, both, both reversed) fail without the change and pass with it. The decoded DPP form of V_ADD_NC_U32 is VAddI32 (VOP2 0x25); the matcher accepts it beside VAddU32, which the SPIR-V matcher alone names. --- .../Gen5MslTranslator.WaveReductions.cs | 354 ++++++++++ .../Gen5MslTranslator.cs | 9 +- .../Gen5ComputeFixtures.cs | 4 +- .../Gen5MslWaveReductionTests.cs | 638 ++++++++++++++++++ 4 files changed, 1003 insertions(+), 2 deletions(-) create mode 100644 src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.WaveReductions.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslWaveReductionTests.cs diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.WaveReductions.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.WaveReductions.cs new file mode 100644 index 000000000..ef553f079 --- /dev/null +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.WaveReductions.cs @@ -0,0 +1,354 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler; + +namespace SharpEmu.ShaderCompiler.Metal; + +// Wave32 row reductions (ShaderCompileRequest.SubgroupArithmetic), ported from +// Gen5SpirvTranslator.WaveReductions with the same pattern and the same proofs: +// S_AND_B32 mask, x, entry entry holds a subset of the entry EXEC (IsEntryExecSubset) +// S_ORN2_SAVEEXEC_B32 saved, x EXEC = x | ~EXEC, every lane (x holds EXEC) +// V_CNDMASK_B32 v, identity, value, mask (VOP3) +// V_<op> v, v, v DPP row_shr:1, 2, 4 and 8, full masks, FI and BOUND_CTRL clear +// [S_MOV_B32 exec_lo, saved] +// V_READLANE_B32 s, v, 15 and/or V_READLANE_B32 s, v, 31 +// On the PS5 every lane of the wave exists and V_CNDMASK gives each lane outside mask the identity, so lane 15 (31) +// holds the operation over row 0 (1). A fragment simdgroup holds only the fragments (and helpers) the rasterizer +// packed into it: a lane that never ran has no register to read, and a row can have none at all. Neither the +// nearest-running-lane read of a pixel V_READLANE (sharpemu_present_lane) nor the scan over the running lanes gives +// the PS5's value then. Each read is replaced by a SIMD-group reduction (MSL 6.10.2: simd_sum, simd_min, simd_max, +// simd_and, simd_or, simd_xor over the active threads, kernel and fragment functions, Apple7 and later) of the +// V_CNDMASK result over its row, the other rows taking the identity. mask selects only lanes of the entry EXEC, +// which are running threads, so a lane missing from the simdgroup takes the identity on the PS5 too and leaving it +// out changes nothing. The scan itself is emitted unchanged. +public static partial class Gen5MslTranslator +{ + private sealed partial class CompilationContext + { + private readonly record struct WaveReduction(int CndmaskIndex, uint Vector, string Operation, bool Signed, uint Identity, int Row); + + // VCC_LO: SGPRs from here on (VCC, trap registers, M0, NULL, EXEC) are written by instructions that do not name them. + private const uint FirstSpecialScalarRegister = VccLoRegister; + + // The V_CNDMASK results kept for the reads after them, by instruction index. + private readonly Dictionary<int, string> _waveReductionValues = new(); + + // Guest lane = simdgroup lane, one guest wave32 per simdgroup: a pixel stage with real lanes, or a wave32 + // compute program. Vertex runs one lane per thread; a wave64 or a mesh wave is not one simdgroup. + private bool WaveReductionsApply => + _request.SubgroupArithmetic && _waveLaneCount == 32 && HasRealWaveLanes && !IsWave64 && !IsNarrowWave64 && + _stage is Gen5MslStage.Pixel or Gen5MslStage.Compute; + + // The reductions of a block by instruction index: the V_CNDMASK (Row -1) and each replaced V_READLANE. Null when the + // block has none or the stage cannot compute them. + private Dictionary<int, WaveReduction>? FindWaveReductions(ShaderBlock block) + { + if (!WaveReductionsApply) + { + return null; + } + + Dictionary<int, WaveReduction>? found = null; + for (var index = block.StartIndex; index < block.EndIndex; index++) + { + TryMatchWaveReduction(block, index, ref found); + } + + return found; + } + + // After the instruction at index was emitted: keeps a V_CNDMASK result, or replaces a row read. + private void ApplyWaveReduction(Dictionary<int, WaveReduction> reductions, int index) + { + if (!reductions.TryGetValue(index, out var reduction)) + { + return; + } + + if (reduction.Row < 0) + { + _waveReductionValues[reduction.CndmaskIndex] = Temp("uint", VectorExpression(reduction.Vector)); + return; + } + + if (!_waveReductionValues.TryGetValue(reduction.CndmaskIndex, out var value)) + { + return; + } + + var contribution = Temp( + "uint", + $"select({FormatUInt(reduction.Identity)}, {value}, (sharpemu_lane >> 4u) == {reduction.Row}u)"); + var reduced = reduction.Signed + ? $"as_type<uint>({reduction.Operation}(as_type<int>({contribution})))" + : $"{reduction.Operation}({contribution})"; + StoreScalar(_request.Program.Instructions[index].Destinations[0].Value, Temp("uint", reduced)); + } + + // index names the S_ORN2_SAVEEXEC_B32 of a reduction. + private void TryMatchWaveReduction(ShaderBlock block, int index, ref Dictionary<int, WaveReduction>? found) + { + var instructions = _request.Program.Instructions; + var saveexec = instructions[index]; + if (saveexec.Opcode != "SOrn2SaveexecB32" || + saveexec.Destinations is not [{ Kind: Gen5OperandKind.ScalarRegister } saved] || + saveexec.Sources is not [{ Kind: Gen5OperandKind.ScalarRegister } execSource] || + !HoldsExec(block, index, execSource.Value)) + { + return; + } + + var at = index + 1; + while (at < block.EndIndex && instructions[at].Opcode is "SWaitcnt" or "SNop") at++; + // The VOP3 form, whose mask is a named SGPR: the VOP2 form reads VCC, which compares and carries write unnamed. + if (at >= block.EndIndex || + instructions[at] is not { Opcode: "VCndmaskB32" } cndmask || + cndmask.Destinations is not [{ Kind: Gen5OperandKind.VectorRegister } scanned] || + cndmask.Sources is not [var identitySource, _, { Kind: Gen5OperandKind.ScalarRegister } mask] || + cndmask.Control is not Gen5Vop3Control { AbsoluteMask: 0, NegateMask: 0, OutputModifier: 0, Clamp: false } || + !TryGetReductionConstant(identitySource, out var identity) || + !SelectsEntryLanes(block, at, mask.Value)) + { + return; + } + + var cndmaskIndex = at; + var vector = scanned.Value; + string? scan = null; + foreach (var shift in new uint[] { 1, 2, 4, 8 }) + { + if (++at >= block.EndIndex || + instructions[at] is not { Control: Gen5DppControl dpp } step || + dpp is not { FetchInactive: false, BoundControl: false, AbsoluteMask: 0, NegateMask: 0, BankMask: 15, RowMask: 15 } || + dpp.Control != 0x110 + shift || + step.Destinations is not [{ Kind: Gen5OperandKind.VectorRegister } written] || written.Value != vector || + step.Sources is not [{ Kind: Gen5OperandKind.VectorRegister } left, { Kind: Gen5OperandKind.VectorRegister } right] || + left.Value != vector || right.Value != vector || + (scan ??= step.Opcode) != step.Opcode) + { + return; + } + } + + var (operation, signed, expectedIdentity) = scan switch + { + "VMaxU32" => ("simd_max", false, 0u), + "VMinU32" => ("simd_min", false, uint.MaxValue), + "VMaxI32" => ("simd_max", true, 0x8000_0000u), + "VMinI32" => ("simd_min", true, 0x7FFF_FFFFu), + "VOrB32" => ("simd_or", false, 0u), + "VAndB32" => ("simd_and", false, uint.MaxValue), + "VXorB32" => ("simd_xor", false, 0u), + // V_ADD_NC_U32 decodes as VAddI32 in its VOP2 form, the only one DPP has (VOP3 0x125 is VAddU32): both + // are the same wrapping add. The SPIR-V matcher names VAddU32 only, so it never sees a decoded DPP add. + "VAddU32" or "VAddI32" => ("simd_sum", false, 0u), + _ => ((string?)null, false, 1u), + }; + if (operation is null || identity != expectedIdentity) + { + return; + } + + at++; + if (at < block.EndIndex && instructions[at] is { Opcode: "SMovB32" } restore && + restore.Destinations is [{ Kind: Gen5OperandKind.ScalarRegister, Value: ExecLoRegister }] && + restore.Sources is [{ Kind: Gen5OperandKind.ScalarRegister } restored] && restored.Value == saved.Value) + { + at++; + } + + var reads = new List<(int Index, int Row)>(); + for (; at < block.EndIndex && reads.Count < 2; at++) + { + if (instructions[at] is not { Opcode: "VReadlaneB32" } readlane || + readlane.Destinations is not [{ Kind: Gen5OperandKind.ScalarRegister }] || + readlane.Sources.Count < 2 || + readlane.Sources[0] is not { Kind: Gen5OperandKind.VectorRegister } source || source.Value != vector || + !TryGetFixedReductionLane(readlane.Sources[1], out var lane) || lane is not (15 or 31) || + reads.Exists(read => read.Row == (int)(lane >> 4))) + { + break; + } + + reads.Add((at, (int)(lane >> 4))); + } + + if (reads.Count == 0) + { + return; + } + + found ??= new Dictionary<int, WaveReduction>(); + found[cndmaskIndex] = new WaveReduction(cndmaskIndex, vector, operation, signed, identity, -1); + foreach (var (readIndex, row) in reads) + { + found[readIndex] = new WaveReduction(cndmaskIndex, vector, operation, signed, identity, row); + } + } + + // Whether the scalar register holds EXEC when the instruction at index runs: it is EXEC itself, or the last + // instruction of the block that may write EXEC before it is S_MOV_B32 exec_lo, register and nothing between them + // writes the register. + private bool HoldsExec(ShaderBlock block, int index, uint register) + { + if (register == ExecLoRegister) + { + return true; + } + + if (register >= FirstSpecialScalarRegister) + { + return false; + } + + var instructions = _request.Program.Instructions; + for (var at = index - 1; at >= block.StartIndex; at--) + { + var instruction = instructions[at]; + if (instruction is { Opcode: "SMovB32", Sources: [{ Kind: Gen5OperandKind.ScalarRegister } source] } && + instruction.Destinations is [{ Kind: Gen5OperandKind.ScalarRegister, Value: ExecLoRegister }] && + source.Value == register) + { + return true; + } + + if (MayWriteExec(instruction) || MayWriteReductionScalar(instruction, register)) + { + return false; + } + } + + return false; + } + + // Whether the SGPR mask that V_CNDMASK reads at cndmaskIndex selects only lanes of the wave's entry EXEC: its last + // write in the block is S_AND_B32 mask, x, entry (in either order), entry holding a subset of the entry EXEC. + private bool SelectsEntryLanes(ShaderBlock block, int cndmaskIndex, uint mask) + { + if (mask >= FirstSpecialScalarRegister) + { + return false; + } + + var instructions = _request.Program.Instructions; + for (var at = cndmaskIndex - 1; at >= block.StartIndex; at--) + { + var instruction = instructions[at]; + if (MayWriteReductionScalar(instruction, mask)) + { + return instruction is { Opcode: "SAndB32", Sources: [var left, var right] } && + (IsEntryExecSubset(left, at) || IsEntryExecSubset(right, at)); + } + } + + return false; + } + + // Whether the operand is an SGPR that holds a subset of the wave's entry EXEC when the instruction at useIndex runs. + // Its one copy S_MOV_B32 register, exec_lo comes before useIndex, in the entry block (which no branch reaches) and + // before any EXEC write; every other write of it is S_AND_B32 or S_ANDN2_B32 of itself, which keeps a subset. + private bool IsEntryExecSubset(Gen5Operand operand, int useIndex) + { + if (operand.Kind != Gen5OperandKind.ScalarRegister || operand.Value >= FirstSpecialScalarRegister) + { + return false; + } + + var register = operand.Value; + var instructions = _request.Program.Instructions; + var copy = -1; + var inEntryBlock = true; + var execWritten = false; + for (var at = 0; at < instructions.Count; at++) + { + var instruction = instructions[at]; + if (instruction is { Opcode: "SMovB32", Sources: [{ Kind: Gen5OperandKind.ScalarRegister, Value: ExecLoRegister }] } && + instruction.Destinations is [{ Kind: Gen5OperandKind.ScalarRegister } destination] && + destination.Value == register) + { + if (copy >= 0 || !inEntryBlock || execWritten) + { + return false; + } + + copy = at; + } + else if (MayWriteReductionScalar(instruction, register) && !KeepsSubset(instruction, register)) + { + return false; + } + + execWritten |= MayWriteExec(instruction); + inEntryBlock &= !IsBranch(instruction.Opcode) && instruction.Opcode is not ("SEndpgm" or "SBarrier") && + instruction.Control is not ShaderCallEntryControl; + } + + if (copy < 0 || copy >= useIndex) + { + return false; + } + + // A branch into the entry block would run the copy again, after EXEC may have changed. + for (var at = 0; at < instructions.Count; at++) + { + if (!IsBranch(instructions[at].Opcode) || !TryGetBranchTargetPc(instructions[at], out var target)) + { + continue; + } + + for (var entry = 0; entry <= copy; entry++) + { + if (instructions[entry].Pc == target) + { + return false; + } + } + } + + return true; + } + + // S_AND_B32 register, register, x (either order) and S_ANDN2_B32 register, register, x keep a subset of register. + private static bool KeepsSubset(Gen5ShaderInstruction instruction, uint register) => + instruction.Destinations is [{ Kind: Gen5OperandKind.ScalarRegister } destination] && + destination.Value == register && + instruction switch + { + { Opcode: "SAndB32", Sources: [var left, var right] } => IsScalarOperand(left, register) || IsScalarOperand(right, register), + { Opcode: "SAndn2B32", Sources: [var left, _] } => IsScalarOperand(left, register), + _ => false, + }; + + private static bool IsScalarOperand(Gen5Operand operand, uint register) => + operand.Kind == Gen5OperandKind.ScalarRegister && operand.Value == register; + + // MayWriteScalar (an over-approximation: full-width destinations, a vector instruction's lane-mask pair and VCC, + // anything relative-addressed), and, as the SPIR-V matcher has it, a linked call's instructions, which set + // registers they do not name. + private static bool MayWriteReductionScalar(Gen5ShaderInstruction instruction, uint register) => + instruction.Control is ShaderCallEntryControl or ShaderCallMatchControl or ShaderCallGroupControl or ShaderCallFaultControl || + MayWriteScalar(instruction, register); + + private static bool TryGetReductionConstant(Gen5Operand operand, out uint value) + { + value = operand.Value; + return operand.Kind == Gen5OperandKind.LiteralConstant || + operand.Kind == Gen5OperandKind.EncodedConstant && Gen5InlineConstants.TryDecode(operand.Value, out value); + } + + // A V_READLANE lane select that is a constant (Gen5SpirvTranslator.TryGetFixedLane), in a wave32. + private static bool TryGetFixedReductionLane(Gen5Operand operand, out uint lane) + { + lane = operand.Value; + if (operand.Kind == Gen5OperandKind.EncodedConstant && operand.Value is >= 128 and <= 192) + lane -= 128; + else if (operand.Kind == Gen5OperandKind.EncodedConstant && operand.Value is >= 193 and <= 208) + lane = unchecked(192u - operand.Value); + else if (operand.Kind != Gen5OperandKind.LiteralConstant) + return false; + lane &= 31u; + return true; + } + } +} diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs index c23136e50..7579c31db 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs @@ -1943,13 +1943,16 @@ private bool TryEmitBlockBodyCore( terminator = BlockTerminator.Exit("active = false;"); var block = blocks[blockIndex]; var instructions = _request.Program.Instructions; + var waveReductions = FindWaveReductions(block); for (var index = block.StartIndex; index < block.EndIndex; index++) { var instruction = instructions[index]; var isTerminator = index == block.EndIndex - 1; + // A reduction's V_CNDMASK stays out of an EXEC run: its kept result is read after the run would close. var inExecRun = IsExecRunInstruction(instruction) && !IsUnobservedAluInstruction(instruction) && - !(!isTerminator && CanFuseWave64ReadLanes(instruction, instructions[index + 1])); + !(!isTerminator && CanFuseWave64ReadLanes(instruction, instructions[index + 1])) && + waveReductions?.ContainsKey(index) != true; if (!inExecRun) { CloseExecRun(); @@ -2140,6 +2143,10 @@ private bool TryEmitBlockBodyCore( else { EmitInterpolationRewrites(instruction.Pc); + if (waveReductions is not null) + { + ApplyWaveReduction(waveReductions, index); + } } if (isTerminator) diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ComputeFixtures.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ComputeFixtures.cs index b563a170d..f74f69190 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ComputeFixtures.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5ComputeFixtures.cs @@ -887,7 +887,8 @@ public static ShaderCompileRequest RequestOrThrow(Gen5ShaderProgram program, Sha uint floatMode = ShaderCompileRequest.DefaultFloatMode, bool dx10Clamp = true, bool pixelGuestWave32 = false, uint meshPerVertexParameterMask = 0, IReadOnlyList<uint>? vertexInterpolants = null, Gen5TessellationLaunch? tessellation = null, bool pixelEarlyDepth = false, bool supportsDrawParameters = false, - int baseVertexUserData = -1, int startInstanceUserData = -1, bool? graphicsPartialSubgroupLanes = null) + int baseVertexUserData = -1, int startInstanceUserData = -1, bool? graphicsPartialSubgroupLanes = null, + bool subgroupArithmetic = false) { var plan = ShaderResourcePlan.Extract(program, stage, RequestHash, userDataBase, UserDataCount, excludedUserDataRegisters: excludedUserDataRegisters); @@ -937,6 +938,7 @@ public static ShaderCompileRequest RequestOrThrow(Gen5ShaderProgram program, Sha // Unset keeps the request's own default (SHARPEMU_GRAPHICS_PARTIAL_LANES). GraphicsPartialSubgroupLanes = graphicsPartialSubgroupLanes ?? new ShaderCompileRequest(plan, resources, layout).GraphicsPartialSubgroupLanes, + SubgroupArithmetic = subgroupArithmetic, }; } diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslWaveReductionTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslWaveReductionTests.cs new file mode 100644 index 000000000..f9f68fe60 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/Gen5MslWaveReductionTests.cs @@ -0,0 +1,638 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.ShaderCompiler.Metal.Tests; + +/// <summary> +/// The wave32 row reductions of Gen5MslTranslator.WaveReductions (ShaderCompileRequest.SubgroupArithmetic), as the +/// SPIR-V translator has them (WaveReductionDeviceTests in Libs.Tests): s80 copies the entry EXEC and drops lanes 19 +/// and up, lanes outside s0 = EXEC & s80 take the identity, a DPP row_shr 1/2/4/8 scan runs, and lanes 15 and/or 31 +/// are read. On the PS5 every lane of the wave exists, so each read is the operation over its row's lanes in s0. +/// A simdgroup with fewer threads than the wave (a partial threadgroup, a fragment simdgroup holding one quad) has +/// rows with some or no running lane; the reads must still give the PS5's value. +/// </summary> +public sealed class Gen5MslWaveReductionTests(ITestOutputHelper output) +{ + public static readonly string[] Operations = + ["VMaxU32", "VMinU32", "VMaxI32", "VMinI32", "VOrB32", "VAndB32", "VXorB32", "VAddU32"]; + + public enum Reads { Both, Fifteen, ThirtyOne, BothReversed } + + private const uint Unread = 0xEEEE; + private const uint TargetSize = 8; + + public static IEnumerable<object[]> OperationsAndThreads() => + from operation in Operations from threads in new uint[] { 32, 20, 12 } select new object[] { operation, threads }; + + public static IEnumerable<object[]> OperationData() => Operations.Select(operation => new object[] { operation }); + + // A threadgroup of fewer than 32 threads leaves lanes missing from the simdgroup: 20 threads leave row 1 with lanes + // 16-19 (16-18 in the mask), 12 threads leave row 1 with none. + [Theory] + [MemberData(nameof(OperationsAndThreads))] + public void Wave32RowScan_ReadsEachRowOverTheLanesThatExist(string operation, uint threads) + { + if (SkipWithoutMetalDevice("the wave reduction compute test")) return; + + var present = threads == 32 ? uint.MaxValue : (1u << (int)threads) - 1u; + foreach (var reads in Enum.GetValues<Reads>()) + { + var actual = RunCompute(operation, reads, threads, subgroupArithmetic: true); + var (expected15, expected31) = Expected(operation, reads, present); + for (var lane = 0; lane < threads; lane++) + { + Assert.True(expected15 == actual[lane].S1, + $"{operation} {reads} threads={threads} lane {lane}: lane 15 read 0x{actual[lane].S1:X8}, expected 0x{expected15:X8}"); + Assert.True(expected31 == actual[lane].S2, + $"{operation} {reads} threads={threads} lane {lane}: lane 31 read 0x{actual[lane].S2:X8}, expected 0x{expected31:X8}"); + } + + // A full simdgroup gives the same values without the reduction: the old lowering was right there. + if (threads == 32) + { + Assert.Equal(actual, RunCompute(operation, reads, threads, subgroupArithmetic: false)); + } + } + } + + // A triangle covering only the center of pixel (1,1): its quad runs, the rest of the fragment simdgroup does not, + // so row 1 has no running lane (the case a nearest-running-lane read of lane 31 got wrong: it read row 0's scan). + [Theory] + [MemberData(nameof(OperationData))] + public void Wave32RowScan_InAPixelSimdgroupWithAnEmptyRow(string operation) + { + if (SkipWithoutMetalDevice("the wave reduction pixel test")) return; + + foreach (var reads in Enum.GetValues<Reads>()) + { + var on = Texel(Render(operation, reads, subgroupArithmetic: true), 1, 1); + var off = Texel(Render(operation, reads, subgroupArithmetic: false), 1, 1); + var lane = on.B & 31u; + var present = on.A; + output.WriteLine($"{operation} {reads}: pixel (1,1) ran on lane {lane}, running lanes 0x{present:X8}"); + Assert.Equal(present, off.A); + Assert.NotEqual(0u, present); + // One quad: its lanes sit in one row, so the other row has no running lane. + var emptyRow = (present & 0xFFFFu) == 0 ? 0 : 1; + Assert.Equal(0u, present & (0xFFFFu << (16 * emptyRow))); + + var (expected15, expected31) = Expected(operation, reads, present); + Assert.Equal(expected15, on.R); + Assert.Equal(expected31, on.G); + Identity(operation, out var identity); + if (reads != (emptyRow == 0 ? Reads.ThirtyOne : Reads.Fifteen)) + { + Assert.Equal(identity, emptyRow == 0 ? on.R : on.G); + } + + if (emptyRow == 1) + { + // Row 0 has its running lanes at the bottom of the row: the old nearest-running-lane read of lane 15 + // held the row's scan and agrees; lane 31 read row 0's scan where the PS5 reads the identity. + if (reads != Reads.ThirtyOne) + { + Assert.Equal(on.R, off.R); + } + + if (reads != Reads.Fifteen) + { + Assert.Equal(Fold(operation, 0, present), off.G); + } + } + } + } + + // Every operation becomes its SIMD-group reduction; the signed ones compare as int. + [Theory] + [InlineData("VMaxU32", "simd_max(t", false, "0u")] + [InlineData("VMinU32", "simd_min(t", false, "0xFFFFFFFFu")] + [InlineData("VMaxI32", "simd_max(as_type<int>", true, "0x80000000u")] + [InlineData("VMinI32", "simd_min(as_type<int>", true, "0x7FFFFFFFu")] + [InlineData("VOrB32", "simd_or(t", false, "0u")] + [InlineData("VAndB32", "simd_and(t", false, "0xFFFFFFFFu")] + [InlineData("VXorB32", "simd_xor(t", false, "0u")] + [InlineData("VAddU32", "simd_sum(t", false, "0u")] + public void EachOperationIsItsSimdgroupReduction(string operation, string call, bool signed, string identity) + { + foreach (var stage in new[] { ShaderStage.Compute, ShaderStage.Pixel }) + { + var source = Translate(Decode(Program(operation, Reads.Both, stage == ShaderStage.Pixel)), stage, true); + Assert.Equal(2, Occurrences(source, call)); + Assert.Equal(signed ? 2 : 0, Occurrences(source, "as_type<uint>(simd_")); + Assert.Contains($"select({identity}, ", source, StringComparison.Ordinal); + Assert.Contains("(sharpemu_lane >> 4u) == 0u)", source, StringComparison.Ordinal); + Assert.Contains("(sharpemu_lane >> 4u) == 1u)", source, StringComparison.Ordinal); + } + } + + // Only the exact scan becomes a reduction (the SPIR-V matcher's cases, Wave32RowScan_OnlyTheExactScanIsReduced). + [Theory] + [InlineData("Exact", 2)] + [InlineData("NoSubgroupArithmetic", 0)] + [InlineData("IdentityChanged", 0)] + [InlineData("ShiftOrder", 0)] + [InlineData("BoundControl", 0)] + [InlineData("OtherLane", 0)] + [InlineData("ExecNotSaved", 0)] + [InlineData("ScanSourceChanged", 0)] + [InlineData("MaskAllLanes", 0)] + [InlineData("MaskNotFromEntryCopy", 0)] + [InlineData("MaskInVcc", 0)] + [InlineData("EntryCopyOverwritten", 0)] + [InlineData("EntryCopyAfterExecWrite", 0)] + [InlineData("EntryCopyInOddRegister", 2)] + [InlineData("EntryCopyPairWrite", 0)] + [InlineData("MaskInOddRegister", 2)] + [InlineData("MaskPairWrite", 0)] + [InlineData("SavedSourceKept", 2)] + [InlineData("SavedSourcePairWrite", 0)] + [InlineData("OneRead", 1)] + [InlineData("SameRowTwice", 1)] + [InlineData("ReadAfterOtherInstruction", 0)] + [InlineData("WaitBeforeCndmask", 2)] + public void Wave32RowScan_OnlyTheExactScanIsReduced(string variant, int reductions) + { + var instructions = Decode(Program("VMaxU32", Reads.Both, pixel: false)).Instructions.ToList(); + int Find(string opcode, int skip = 0) => instructions.FindIndex(skip, instruction => instruction.Opcode == opcode); + if (variant is "EntryCopyInOddRegister" or "EntryCopyPairWrite") + { + Rename(instructions, 80, 81, _ => true); + } + + if (variant is "MaskInOddRegister" or "MaskPairWrite") + { + Rename(instructions, 0, 1, instruction => instruction.Opcode is "SAndB32" or "VCndmaskB32"); + } + + var cndmask = Find("VCndmaskB32"); + var maskWrite = Find("SAndB32"); + var read = Find("VReadlaneB32"); + switch (variant) + { + case "IdentityChanged": + instructions[cndmask] = instructions[cndmask] with { Sources = [Operand(5), .. instructions[cndmask].Sources.Skip(1)] }; + break; + case "ShiftOrder": + (instructions[cndmask + 1], instructions[cndmask + 2]) = (instructions[cndmask + 2], instructions[cndmask + 1]); + break; + case "BoundControl": + instructions[cndmask + 3] = instructions[cndmask + 3] with { Control = new Gen5DppControl(0x114, false, true, 0, 0, 15, 15) }; + break; + case "OtherLane": + instructions[read] = ReadLane(1, 2, 14); + break; + case "ExecNotSaved": + var saveexec = Find("SOrn2SaveexecB32"); + instructions[saveexec] = Sop1("SOrn2SaveexecB32", 20, Gen5Operand.Scalar(80)); + break; + case "ScanSourceChanged": + instructions[cndmask + 2] = instructions[cndmask + 2] with { Sources = [Gen5Operand.Vector(1), Gen5Operand.Vector(2)] }; + break; + case "MaskAllLanes": + // A lane missing from the simdgroup would take value, not the identity, on the PS5. + instructions[maskWrite] = MoveScalar(0, uint.MaxValue); + break; + case "MaskNotFromEntryCopy": + instructions[maskWrite] = Sop2("SAndB32", 0, Gen5Operand.Scalar(126), Gen5Operand.Scalar(81)); + instructions.Insert(0, MoveScalar(81, 0x7FFFF)); + break; + case "MaskInVcc": + instructions[cndmask] = Vop2("VCndmaskB32", 2, Operand(0), Gen5Operand.Vector(1)); + break; + case "EntryCopyOverwritten": + instructions.Insert(maskWrite, Sop2("SOrB32", 80, Gen5Operand.Scalar(80), Operand(1u << 25))); + break; + case "EntryCopyAfterExecWrite": + instructions.Insert(0, Sop2("SAndB32", 126, Gen5Operand.Scalar(126), Operand(uint.MaxValue))); + break; + case "EntryCopyPairWrite": + // S_MOV_B64 s[80:81] names s80 only. + instructions.Insert(maskWrite, Sop1("SMovB64", 80, Gen5Operand.Scalar(8))); + break; + case "MaskPairWrite": + // S_MOV_B64 s[0:1] names s0 only. + instructions.Insert(maskWrite + 1, Sop1("SMovB64", 0, Gen5Operand.Scalar(8))); + break; + case "SavedSourceKept": + case "SavedSourcePairWrite": + // S_MOV_B32 exec_lo, s3 makes s3 hold EXEC; S_MOV_B64 s[2:3] names s2 only. + var savedAt = Find("SOrn2SaveexecB32"); + instructions[savedAt] = Sop1("SOrn2SaveexecB32", 20, Gen5Operand.Scalar(3)); + instructions.InsertRange(savedAt, variant == "SavedSourceKept" + ? [MoveScalarRegister(3, 126), MoveScalarRegister(126, 3)] + : [MoveScalarRegister(3, 126), MoveScalarRegister(126, 3), Sop1("SMovB64", 2, Gen5Operand.Scalar(8))]); + break; + case "OneRead": + instructions[read + 1] = MoveScalar(2, Unread); + break; + case "SameRowTwice": + // The second read of row 0 is left to the scan. + instructions[read + 1] = ReadLane(2, 2, 15); + break; + case "ReadAfterOtherInstruction": + instructions.Insert(read, MoveScalar(3, 0)); + break; + case "WaitBeforeCndmask": + instructions.Insert(cndmask, Sopp("SWaitcnt")); + break; + } + + var source = Translate(Placed(instructions), ShaderStage.Compute, variant != "NoSubgroupArithmetic"); + Assert.Equal(reductions, Occurrences(source, "simd_max(")); + } + + // V_ADD_NC_U32 decodes as VAddI32 in its VOP2 (DPP) form and as VAddU32 in VOP3; the scan is the same add. + [Theory] + [InlineData("VAddI32", 2)] + [InlineData("VAddU32", 2)] + [InlineData("VSubU32", 0)] + public void TheScanAddMatchesUnderEitherDecodedName(string opcode, int reductions) + { + var instructions = Decode(Program("VAddU32", Reads.Both, pixel: false)).Instructions.ToList(); + Assert.Equal(4, instructions.Count(instruction => instruction is { Opcode: "VAddI32", Control: Gen5DppControl })); + for (var index = 0; index < instructions.Count; index++) + { + if (instructions[index].Control is Gen5DppControl) + { + instructions[index] = instructions[index] with { Opcode = opcode }; + } + } + + Assert.Equal(reductions, Occurrences(Translate(Placed(instructions), ShaderStage.Compute, true), "simd_sum(")); + } + + // Without the request flag, in a stage whose simdgroup is not one guest wave32, or for a shader without the scan, + // the translation is the one it always was. + [Fact] + public void ShadersWithoutTheScanOrTheFlagTranslateAsBefore() + { + var compute = Decode(Program("VAddU32", Reads.Both, pixel: false)); + var pixel = Decode(Program("VAddU32", Reads.Both, pixel: true)); + Assert.DoesNotContain("simd_sum(", Translate(compute, ShaderStage.Compute, false), StringComparison.Ordinal); + Assert.DoesNotContain("simd_sum(", Translate(pixel, ShaderStage.Pixel, false), StringComparison.Ordinal); + + // Single-lane pixel stage (graphics subgroups off) and a wave64 compute program. + Assert.Equal( + Translate(pixel, ShaderStage.Pixel, false, enableGraphicsSubgroupOperations: false), + Translate(pixel, ShaderStage.Pixel, true, enableGraphicsSubgroupOperations: false)); + Assert.Equal( + Translate(compute, ShaderStage.Compute, false, waveLaneCount: 64, localSizeX: 64), + Translate(compute, ShaderStage.Compute, true, waveLaneCount: 64, localSizeX: 64)); + + // Programs without the pattern: byte for byte the same with the flag. + foreach (var fixture in Gen5ComputeFixtures.All) + { + var program = Gen5ComputeFixtures.DecodeOrThrow(fixture); + Assert.Equal(Translate(program, ShaderStage.Compute, false), Translate(program, ShaderStage.Compute, true)); + } + + var pixelFixture = Gen5ComputeFixtures.DecodeOrThrow(new Gen5ComputeFixture("pixel", Gen5ComputeFixtures.PixelWords, 0, 0)); + Assert.Equal(Translate(pixelFixture, ShaderStage.Pixel, false), Translate(pixelFixture, ShaderStage.Pixel, true)); + } + + // The two-row pattern compiles in a fragment function with the partial-lane lowering on as well: the reduction + // reads no other lane, so it does not depend on how absent lanes are read. + [Fact] + public void TheReductionDoesNotDependOnThePartialLaneLowering() + { + var program = Decode(Program("VXorB32", Reads.Both, pixel: true)); + var partial = Translate(program, ShaderStage.Pixel, true, graphicsPartialSubgroupLanes: true); + Assert.Equal(2, Occurrences(partial, "simd_xor(")); + if (SkipWithoutMetalDevice("the partial-lane reduction compile")) return; + + Assert.True(MetalNative.TryCompileLibrary(partial + VertexSource, out _, out var error), $"{error}\n{partial}"); + } + + // ---- the guest program ---- + + // Each lane's value: 8 * lane + 100 (MAX_U, ADD), 3 * lane + 7 (XOR: the XOR of one quad's is not zero), + // 1023 - 8 * lane (MIN_U), 8 * lane - 100 (MAX_I, MIN_I), 1 << lane (OR), ~(1 << lane) (AND). + private static uint Value(string operation, uint lane) => operation switch + { + "VXorB32" => 3 * lane + 7, + "VMinU32" => 1023 - 8 * lane, + "VMaxI32" or "VMinI32" => unchecked(8 * lane - 100), + "VOrB32" => 1u << (int)lane, + "VAndB32" => ~(1u << (int)lane), + _ => 8 * lane + 100, + }; + + private static uint[] Identity(string operation, out uint identity) + { + identity = operation switch + { + "VMinU32" or "VAndB32" => uint.MaxValue, + "VMaxI32" => 0x8000_0000u, + "VMinI32" => 0x7FFF_FFFFu, + _ => 0u, + }; + // v_cndmask_b32_e64 v2, identity, v1, s0 + return identity switch + { + 0u => [0xD5010002, 0x00020280], + uint.MaxValue => [0xD5010002, 0x000202C1], + _ => [0xD5010002, 0x000202FF, identity], + }; + } + + private static uint Combine(string operation, uint left, uint right) => operation switch + { + "VMaxU32" => Math.Max(left, right), + "VMinU32" => Math.Min(left, right), + "VMaxI32" => (uint)Math.Max((int)left, (int)right), + "VMinI32" => (uint)Math.Min((int)left, (int)right), + "VOrB32" => left | right, + "VAndB32" => left & right, + "VXorB32" => left ^ right, + _ => left + right, + }; + + // The operation over the lanes of a row that run (present) and are in the scan mask (lanes 0 to 18). + private static uint Fold(string operation, uint row, uint present) + { + Identity(operation, out var result); + for (var lane = row * 16; lane < row * 16 + 16; lane++) + { + if (((present >> (int)lane) & 1u) != 0 && lane <= 18) result = Combine(operation, result, Value(operation, lane)); + } + + return result; + } + + private static (uint Fifteen, uint ThirtyOne) Expected(string operation, Reads reads, uint present) => + ( + reads == Reads.ThirtyOne ? Unread : Fold(operation, 0, present), + reads == Reads.Fifteen ? Unread : Fold(operation, 1, present) + ); + + // DPP V_<op> v2, v2, v2 row_shr:shift, full masks, FI and BOUND_CTRL clear. + private static uint[] Step(string operation, uint shift) + { + uint opcode = operation switch + { + "VMaxU32" => 0x14, + "VMinU32" => 0x13, + "VMaxI32" => 0x12, + "VMinI32" => 0x11, + "VOrB32" => 0x1C, + "VAndB32" => 0x1B, + "VXorB32" => 0x1D, + "VAddU32" => 0x25, + _ => throw new ArgumentOutOfRangeException(nameof(operation)), + }; + return [0x000404FA | (opcode << 25), 0xFF000002 | ((0x110 + shift) << 8)]; + } + + private static uint[] Program(string operation, Reads reads, bool pixel) + { + var words = new List<uint> + { + 0xD7650000, 0x020100C1, // v_mbcnt_lo_u32_b32 v0, -1, 0 + 0xBE89037E, // s_mov_b32 s9, exec_lo + 0xBED0037E, // s_mov_b32 s80, exec_lo + 0x8A50FF50, 0xFFF80000, // s_andn2_b32 s80, s80, 0xfff80000 + }; + words.AddRange(operation switch + { + // v_lshlrev_b32 v1, 3, v0; v_xor_b32 v1, 0x3ff, v1 + "VMinU32" => [0x34020083, 0x3A0202FF, 0x000003FF], + // v_lshlrev_b32 v1, 3, v0; v_add_nc_u32 v1, -100, v1 + "VMaxI32" or "VMinI32" => [0x34020083, 0x4A0202FF, 0xFFFFFF9C], + // v_mad_u32_u24 v1, v0, 3, 7 + "VXorB32" => [0xD5430001, 0x021D0700], + // v_lshlrev_b32_e64 v1, v0, 1 + "VOrB32" => [0xD51A0001, 0x02010300], + // v_lshlrev_b32_e64 v1, v0, 1; v_not_b32 v1, v1 + "VAndB32" => [0xD51A0001, 0x02010300, 0x7E026F01], + // v_lshlrev_b32 v1, 3, v0; v_add_nc_u32 v1, 100, v1 + _ => [0x34020083, 0x4A0202FF, 0x00000064], + }); + words.Add(0x8700507E); // s_and_b32 s0, exec_lo, s80 + words.Add(0xBE94407E); // s_orn2_saveexec_b32 s20, exec_lo + words.AddRange(Identity(operation, out _)); + foreach (var shift in new uint[] { 1, 2, 4, 8 }) + { + words.AddRange(Step(operation, shift)); + } + + words.Add(0xBEFE0314); // s_mov_b32 exec_lo, s20 + uint[] read15 = [0xD7600001, 0x02011F02]; // v_readlane_b32 s1, v2, 15 + uint[] read31 = [0xD7600002, 0x02013F02]; // v_readlane_b32 s2, v2, 31 + uint[] unread1 = [0xBE8103FF, Unread]; // s_mov_b32 s1, 0xeeee + uint[] unread2 = [0xBE8203FF, Unread]; // s_mov_b32 s2, 0xeeee + words.AddRange(reads switch + { + Reads.Both => [.. read15, .. read31], + Reads.BothReversed => [.. read31, .. read15], + Reads.Fifteen => [.. read15, .. unread2], + _ => [.. read31, .. unread1], + }); + words.AddRange([0x7E080201, 0x7E0A0202]); // v_mov_b32 v4, s1; v_mov_b32 v5, s2 + words.AddRange(pixel + ? + [ + 0x7E180209, // v_mov_b32 v12, s9 + 0xF800180F, 0x0C000504, // exp mrt0 v4, v5, v0, v12 done vm + ] + : + [ + 0xE0702000, 0x80010400, // buffer_store_dword v4, v0, s[4:7], 0 idxen + 0xE0702004, 0x80010500, // buffer_store_dword v5, v0, s[4:7], 0 idxen offset:4 + ]); + words.Add(0xBF810000); // s_endpgm + return [.. words]; + } + + private static Gen5ShaderProgram Decode(uint[] words) => + Gen5ComputeFixtures.DecodeOrThrow(new Gen5ComputeFixture("wave-reduction", words, 0, 0)); + + private static ResourceRuntimeInputs StoreInputs(uint threads) + { + var userData = new uint[16]; + userData[4] = 0x200000; + userData[5] = 8u << 16; + userData[6] = threads; + userData[7] = DescriptorConstants.IdentityDestinationSelect; + return new ResourceRuntimeInputs { UserData = userData }; + } + + private static ShaderCompileRequest Request(Gen5ShaderProgram program, ShaderStage stage, bool subgroupArithmetic, + uint waveLaneCount = 32, uint localSizeX = 32, bool enableGraphicsSubgroupOperations = true, bool? graphicsPartialSubgroupLanes = null) => + Gen5ComputeFixtures.RequestOrThrow(program, stage, waveLaneCount: waveLaneCount, localSizeX: localSizeX, + pixelOutputs: stage == ShaderStage.Pixel ? [new Gen5PixelOutputBinding(0, 0, Gen5PixelOutputKind.Uint)] : null, + runtimeInputs: stage == ShaderStage.Compute && program.Instructions.Any(instruction => instruction.Control is Gen5BufferMemoryControl) + ? StoreInputs(localSizeX) : null, + enableGraphicsSubgroupOperations: enableGraphicsSubgroupOperations, + pixelGuestWave32: true, + graphicsPartialSubgroupLanes: graphicsPartialSubgroupLanes, + subgroupArithmetic: subgroupArithmetic); + + private static string Translate(Gen5ShaderProgram program, ShaderStage stage, bool subgroupArithmetic, + uint waveLaneCount = 32, uint localSizeX = 32, bool enableGraphicsSubgroupOperations = true, bool? graphicsPartialSubgroupLanes = false) + { + var request = Request(program, stage, subgroupArithmetic, waveLaneCount, localSizeX, enableGraphicsSubgroupOperations, + graphicsPartialSubgroupLanes); + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error), error); + return shader.Source; + } + + private (uint S1, uint S2)[] RunCompute(string operation, Reads reads, uint threads, bool subgroupArithmetic) + { + var request = Request(Decode(Program(operation, reads, pixel: false)), ShaderStage.Compute, subgroupArithmetic, + localSizeX: threads, graphicsPartialSubgroupLanes: false); + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error), error); + Assert.True(MetalNative.TryCompileLibrary(shader.Source, out var library, out var compileError), $"{compileError}\n{shader.Source}"); + Assert.True( + MetalNative.TryExecuteWithArgumentBuffer( + library, + shader.EntryPoint, + new byte[threads * 8], + new byte[Resources.PushData.ByteSize], + shader.ArgumentLayout!, + threads, + out var bytes, + out var runError), + runError); + var lanes = new (uint, uint)[threads]; + for (var lane = 0; lane < threads; lane++) + { + lanes[lane] = (BitConverter.ToUInt32(bytes, lane * 8), BitConverter.ToUInt32(bytes, lane * 8 + 4)); + } + + return lanes; + } + + private const string VertexSource = """ + + struct SharpEmuWaveReductionVertex + { + float4 position [[position]]; + }; + + vertex SharpEmuWaveReductionVertex sharpemu_wave_reduction_vs( + uint id [[vertex_id]], + constant float2* positions [[buffer(0)]]) + { + SharpEmuWaveReductionVertex vertex_out; + vertex_out.position = float4(positions[id], 0.0f, 1.0f); + return vertex_out; + } + """; + + private static byte[] Render(string operation, Reads reads, bool subgroupArithmetic) + { + var request = Request(Decode(Program(operation, reads, pixel: true)), ShaderStage.Pixel, subgroupArithmetic, + graphicsPartialSubgroupLanes: false); + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error), error); + Assert.True( + MetalNative.TryCompileLibrary(shader.Source + VertexSource, out var library, out error), + $"Metal rejected the wave reduction MSL: {error}\n{shader.Source}"); + + // Covers only the center of pixel (1,1) of the 8x8 target. + var triangle = new[] { -0.8f, 0.8f, -0.4f, 0.8f, -0.8f, 0.4f }; + var positions = new byte[triangle.Length * sizeof(float)]; + Buffer.BlockCopy(triangle, 0, positions, 0, positions.Length); + var resources = new byte[Math.Max(shader.ArgumentLayout?.ByteSize ?? 0, 256)]; + Assert.True( + MetalNative.TryRenderTriangles( + library, + "sharpemu_wave_reduction_vs", + shader.EntryPoint, + [(positions, 0)], + [(resources, (uint)Gen5MslArgumentLayout.ResourcesBufferIndex)], + 3, + TargetSize, + TargetSize, + MetalNative.Rgba32UintPixelFormat, + out var texels, + out error), + error); + return texels; + } + + private static (uint R, uint G, uint B, uint A) Texel(byte[] texels, uint x, uint y) + { + var offset = (int)(((y * TargetSize) + x) * 16); + return ( + BitConverter.ToUInt32(texels, offset), + BitConverter.ToUInt32(texels, offset + 4), + BitConverter.ToUInt32(texels, offset + 8), + BitConverter.ToUInt32(texels, offset + 12)); + } + + // ---- hand-built instructions for the matcher cases (shapes of Libs.Tests' ResourceTestProgram) ---- + + private static Gen5Operand Operand(uint value) => + value <= 64 ? Gen5Operand.Source(128 + value) : new Gen5Operand(Gen5OperandKind.LiteralConstant, value); + + private static Gen5ShaderInstruction MoveScalar(uint destination, uint value) => + new(0, Gen5ShaderEncoding.Sop1, "SMovB32", [0u], [Operand(value)], [Gen5Operand.Scalar(destination)], null); + + private static Gen5ShaderInstruction MoveScalarRegister(uint destination, uint source) => + new(0, Gen5ShaderEncoding.Sop1, "SMovB32", [0u], [Gen5Operand.Scalar(source)], [Gen5Operand.Scalar(destination)], null); + + private static Gen5ShaderInstruction Sop1(string opcode, uint destination, Gen5Operand source) => + new(0, Gen5ShaderEncoding.Sop1, opcode, [0u], [source], [Gen5Operand.Scalar(destination)], null); + + private static Gen5ShaderInstruction Sop2(string opcode, uint destination, Gen5Operand source0, Gen5Operand source1) => + new(0, Gen5ShaderEncoding.Sop2, opcode, [0u], [source0, source1], [Gen5Operand.Scalar(destination)], null); + + private static Gen5ShaderInstruction Sopp(string opcode) => + new(0, Gen5ShaderEncoding.Sopp, opcode, [0xBF8C0000u], [], [], null); + + private static Gen5ShaderInstruction Vop2(string opcode, uint destination, Gen5Operand source0, Gen5Operand source1) => + new(0, Gen5ShaderEncoding.Vop2, opcode, [0u], [source0, source1], [Gen5Operand.Vector(destination)], null); + + private static Gen5ShaderInstruction ReadLane(uint scalarRegister, uint vectorRegister, uint lane) => + new(0, Gen5ShaderEncoding.Vop3, "VReadlaneB32", [0u, 0u], + [Gen5Operand.Vector(vectorRegister), Gen5Operand.Source(128 + lane), Gen5Operand.Scalar(0)], [Gen5Operand.Scalar(scalarRegister)], null); + + // Renames an SGPR in the operands of the instructions the filter picks. + private static void Rename(List<Gen5ShaderInstruction> instructions, uint from, uint to, Func<Gen5ShaderInstruction, bool> filter) + { + Gen5Operand Map(Gen5Operand operand) => + operand.Kind == Gen5OperandKind.ScalarRegister && operand.Value == from ? Gen5Operand.Scalar(to) : operand; + for (var index = 0; index < instructions.Count; index++) + { + if (filter(instructions[index])) + { + instructions[index] = instructions[index] with + { + Sources = instructions[index].Sources.Select(Map).ToArray(), + Destinations = instructions[index].Destinations.Select(Map).ToArray(), + }; + } + } + } + + // Straight-line code: each instruction at its own pc. + private static Gen5ShaderProgram Placed(List<Gen5ShaderInstruction> instructions) + { + var placed = new List<Gen5ShaderInstruction>(); + uint pc = 0; + foreach (var instruction in instructions) + { + placed.Add(instruction with { Pc = pc }); + pc += 8; + } + + return new Gen5ShaderProgram(0, placed); + } + + private static int Occurrences(string source, string text) => + (source.Length - source.Replace(text, string.Empty, StringComparison.Ordinal).Length) / text.Length; + + private bool SkipWithoutMetalDevice(string activity) + { + if (MetalNative.IsAvailable) return false; + Assert.False( + OperatingSystem.IsMacOS() && Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") == "1", + $"The required gate cannot run {activity} without a Metal device."); + output.WriteLine($"No Metal device on this host; {activity} skipped."); + return true; + } +} From 4075926b1d1edcac6267d12c3ad3f3b0d3661e17 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 03:16:19 +0000 Subject: [PATCH 110/134] [Tests] Stable image bindings on Metal: budget, one-pipeline scene, prewarm round trip MetalStableImageLimitsTests pins the budget derived from the feature set tables. StableImageBindingSceneTests draws one two-slot pixel program with the slots holding one texture and two textures in both orders: every pixel reads its slot's texture, with one pixel module under the budget and one per alias partition with the switch off; the host answers the prewarm's budget and the prewarm stamp changes with the switch. MetalStableImagePrewarmTests (shared paths the Metal prewarm takes, MSL translator): a Metal-shaped host compiles one specialization where compact bindings give two; graphics and compute records made by a live session replay to the session's MSL under the same budget (switch on and off); a record made under the other budget is skipped as stale; the static precompile's prediction follows the plan's policy. MetalStableImageLimits.Enabled becomes settable so the tests compare both policies. --- .../V2/MetalStableImageLimits.cs | 3 +- .../MetalStableImageLimitsTests.cs | 46 ++++ .../Scenes/StableImageBindingSceneTests.cs | 164 +++++++++++++ .../Pipelines/MetalStableImagePrewarmTests.cs | 220 ++++++++++++++++++ 4 files changed, 432 insertions(+), 1 deletion(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalStableImageLimitsTests.cs create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/Scenes/StableImageBindingSceneTests.cs create mode 100644 tests/SharpEmu.Libs.Tests/Gpu/Pipelines/MetalStableImagePrewarmTests.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStableImageLimits.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStableImageLimits.cs index 736fe88b6..2ece2ba09 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStableImageLimits.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalStableImageLimits.cs @@ -30,7 +30,8 @@ namespace SharpEmu.Gpu.Metal.V2; /// </summary> internal static class MetalStableImageLimits { - internal static readonly bool Enabled = + /// <summary>The switch, read once; tests set it to compare both policies in one process.</summary> + internal static bool Enabled { get; set; } = Environment.GetEnvironmentVariable("SHARPEMU_METAL_STABLE_IMAGE_BINDINGS") != "0"; internal const uint TexturesPerStage = 1_000_000; diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalStableImageLimitsTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalStableImageLimitsTests.cs new file mode 100644 index 000000000..19350841a --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalStableImageLimitsTests.cs @@ -0,0 +1,46 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +/// <summary> +/// The stable image budget a device answers (MetalStableImageLimits), from Apple's Metal Feature Set Tables: argument +/// buffers tier 2 and Apple7 or later, textures 1M per stage, samplers 996 per stage on Apple7/Apple8 and 500K on +/// Apple9 and later, never more than the unique argument-buffer samplers the device allows, buffers unlimited. +/// </summary> +public sealed class MetalStableImageLimitsTests +{ + [Theory] + [InlineData(true, true, false, 1024ul, 996u)] + [InlineData(true, true, false, 512ul, 512u)] + [InlineData(true, true, true, 2048ul, 2048u)] + [InlineData(true, true, true, 1_000_000ul, 500_000u)] + public void ATier2Apple7DeviceAnswersItsArgumentBufferLimits(bool tier2, bool apple7, bool apple9, ulong uniqueSamplers, + uint samplers) + { + var limits = MetalStableImageLimits.FromCapabilities(tier2, apple7, apple9, uniqueSamplers); + Assert.Equal(new StableImageDescriptorLimits(1_000_000, 1_000_000, samplers, uint.MaxValue, 1_000_000), limits); + } + + [Theory] + [InlineData(false, true, true, 1024ul)] + [InlineData(true, false, false, 1024ul)] + [InlineData(true, true, true, 0ul)] + public void ADeviceWithoutTheTablesLimitsAnswersNoBudget(bool tier2, bool apple7, bool apple9, ulong uniqueSamplers) => + Assert.Equal(default, MetalStableImageLimits.FromCapabilities(tier2, apple7, apple9, uniqueSamplers)); + + [Fact] + public void TheSwitchOffAnswersNoBudget() => Assert.Equal(default, MetalStableImageLimits.Of(1, enabled: false)); + + [Fact] + public void TheStampNamesTheBudget() + { + Assert.NotEqual(MetalStableImageLimits.StampPart(default), + MetalStableImageLimits.StampPart(MetalStableImageLimits.FromCapabilities(true, true, false, 1024))); + Assert.Equal("stable_images=0,0,0,0,0", MetalStableImageLimits.StampPart(default)); + } +} diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/StableImageBindingSceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/StableImageBindingSceneTests.cs new file mode 100644 index 000000000..de4378923 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/StableImageBindingSceneTests.cs @@ -0,0 +1,164 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections; +using System.Reflection; +using System.Runtime.InteropServices; +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests.Scenes; + +/// <summary> +/// Stable image bindings on the Metal host (MetalStableImageLimits, upstream 7cf0ac568): a pixel program that samples +/// two image slots is drawn with both slots holding one texture, then two different textures in both orders. Within the +/// device's budget the program binds one texture per slot, so all three draws use one specialization (one pixel module) +/// and every pixel reads its own slot's texture; with SHARPEMU_METAL_STABLE_IMAGE_BINDINGS=0 the equal slots alias one +/// argument-buffer element and the program is specialized once per alias partition, with the same pixels. +/// </summary> +public sealed class StableImageBindingSceneTests(ITestOutputHelper output) : SceneTestBase(output) +{ + private const uint Rgba8 = 56; + private const uint Size = 8; + + /// <summary> + /// MRT0 = (T#0.r, T#0.g, T#1.r, T#1.g): T#0 in s[0:7] and T#1 in s[8:15] sampled through the S# in s[16:19] at the + /// interpolated PARAM0.xy (twenty user SGPRs, so the primitive mask is s20). + /// </summary> + private static readonly uint[] TwoSlotProgram = + [ + 0xBEFC0314, // s_mov_b32 m0, s20 + 0xC8080000, // v_interp_p1_f32_e32 v2, v0, attr0.x + 0xC8090001, // v_interp_p2_f32_e32 v2, v1, attr0.x + 0xC80C0100, // v_interp_p1_f32_e32 v3, v0, attr0.y + 0xC80D0101, // v_interp_p2_f32_e32 v3, v1, attr0.y + 0xF0800F08, 0x00800402, // image_sample v[4:7], v[2:3], s[0:7], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xF0800F08, 0x00820802, // image_sample v[8:11], v[2:3], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C3F70, // s_waitcnt vmcnt(0) + 0xF800180F, 0x09080504, // exp mrt0 v4, v5, v8, v9 done vm + 0xBF810000, // s_endpgm + ]; + + [Theory] + [InlineData(true, 1)] + [InlineData(false, 2)] + public void OneProgramSamplesEachSlotsOwnTextureWhetherTheSlotsHoldOneTextureOrTwo(bool stable, int pixelModules) + { + var saved = MetalStableImageLimits.Enabled; + MetalStableImageLimits.Enabled = stable; + try + { + using var rig = CreateRig(); + if (rig is null) return; + Assert.Equal(stable, ((SharpEmu.Libs.Gpu.Pipelines.IShaderPipelineHost)rig.Host).GraphicsImageDescriptorLimits.Resources != 0); + var red = SolidTexture(rig, 0xFF0000FF); + var green = SolidTexture(rig, 0xFF00FF00); + var sampler = Descriptors.Sampler(); + var pm4 = new ScenePm4(); + (uint[] Slot0, uint[] Slot1, float[] Expected)[] draws = + [ + (red, red, [1, 0, 1, 0]), + (red, green, [1, 0, 0, 1]), + (green, red, [0, 1, 1, 0]), + (green, green, [0, 1, 0, 1]), + ]; + var targets = new List<ulong>(); + foreach (var (slot0, slot1, _) in draws) + { + var target = rig.ColorTarget(Size, Size, 16, 0xFF); + targets.Add(target); + var state = new SceneState(Size, Size).ColorTarget(0, target, Size, Size, format: 14, numberType: 7); + rig.DrawMesh(pm4, state, Quad(), TwoSlotProgram, [.. slot0, .. slot1, .. sampler]); + } + + rig.Submit(pm4); + Assert.Empty(rig.Fatals); + for (var index = 0; index < draws.Length; index++) + { + var image = MemoryMarshal.Cast<byte, float>(rig.ReadImage(targets[index], Size, Size, 16)).ToArray(); + for (var pixel = 0; pixel < Size * Size; pixel++) + { + for (var channel = 0; channel < 4; channel++) + { + Assert.True(MathF.Abs(image[(pixel * 4) + channel] - draws[index].Expected[channel]) < 0.002f, + $"draw {index} pixel {pixel} channel {channel}: {image[(pixel * 4) + channel]}, " + + $"expected {draws[index].Expected[channel]}"); + } + } + } + + Assert.Equal(pixelModules, PixelModules(rig.Host)); + } + finally + { + MetalStableImageLimits.Enabled = saved; + } + } + + // The live host answers one budget for compute and graphics, the one the prewarm passes (MetalStableImageLimits.Of + // of the same device), and the prewarm stamp (so the translation cache stamp) holds it: entries made with the switch + // on are not taken with it off. + [Fact] + public void TheHostAndThePrewarmAnswerOneBudgetAndTheStampHoldsIt() + { + var saved = MetalStableImageLimits.Enabled; + try + { + using var rig = CreateRig(); + if (rig is null) return; + var device = (nint)typeof(MetalRenderHost).GetField("_device", BindingFlags.Instance | BindingFlags.NonPublic)! + .GetValue(rig.Host)!; + var host = (SharpEmu.Libs.Gpu.Pipelines.IShaderPipelineHost)rig.Host; + var compiler = new MetalV2Backend(); + MetalStableImageLimits.Enabled = true; + var on = MetalShaderPrewarm.Stamp(compiler, device); + var budget = MetalStableImageLimits.Of(device); + Output.WriteLine(MetalStableImageLimits.StampPart(budget)); + Assert.Equal(MetalStableImageLimits.TexturesPerStage, budget.SampledImages); + Assert.InRange(budget.Samplers, MetalStableImageLimits.SamplersPerStageApple7, MetalStableImageLimits.SamplersPerStageApple9); + Assert.Equal(budget, host.ComputeImageDescriptorLimits); + Assert.Equal(budget, host.GraphicsImageDescriptorLimits); + MetalStableImageLimits.Enabled = false; + Assert.Equal(default, host.ComputeImageDescriptorLimits); + Assert.Equal(default, host.GraphicsImageDescriptorLimits); + Assert.NotEqual(on, MetalShaderPrewarm.Stamp(compiler, device)); + } + finally + { + MetalStableImageLimits.Enabled = saved; + } + } + + // A linear RGBA8 texture of one colour. + private static uint[] SolidTexture(SceneRig rig, uint abgr) + { + var rows = new byte[Size * Size * 4]; + for (var texel = 0; texel < Size * Size; texel++) + { + BitConverter.TryWriteBytes(rows.AsSpan(texel * 4), abgr); + } + + return Descriptors.Texture(rig.LinearImage(Size, Size, 4, rows), Rgba8, Size, Size); + } + + // The whole target, PARAM0 = (0.5, 0.5, 0, 1) everywhere. + private static SceneVertex[] Quad() + { + static SceneVertex V(float x, float y) => SceneVertex.At(x, y, 0.5f, 0.5f, 0.5f, 0f, 1f); + return [V(-1, -1), V(1, -1), V(-1, 1), V(-1, 1), V(1, -1), V(1, 1)]; + } + + // The pixel modules the host created: one per specialization the program cache compiled. + private static int PixelModules(MetalRenderHost host) + { + var modules = (IList)typeof(MetalRenderHost).GetField("_modules", BindingFlags.Instance | BindingFlags.NonPublic)! + .GetValue(host)!; + lock (modules) + { + return modules.Cast<object>().Count(module => + (ShaderStage)module.GetType().GetField("Stage")!.GetValue(module)! == ShaderStage.Pixel); + } + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/MetalStableImagePrewarmTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/MetalStableImagePrewarmTests.cs new file mode 100644 index 000000000..d388113a2 --- /dev/null +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/MetalStableImagePrewarmTests.cs @@ -0,0 +1,220 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Text; +using SharpEmu.Libs.Gpu.Pipelines; +using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Tests.Gpu.Scheduling; +using SharpEmu.ShaderCompiler; +using SharpEmu.ShaderCompiler.Metal; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; + +namespace SharpEmu.Libs.Tests.Gpu.Pipelines; + +// Stable image bindings as the Metal host answers them (MetalStableImageLimits: one per-stage budget for compute and +// graphics, textures 1M, samplers 996 on Apple7/8, buffers unlimited), through the shared paths the Metal prewarm +// takes: a Metal-shaped host compiles one MSL specialization where compact bindings give one per alias partition, and +// what a live session records is found again by the prewarm under the same budget, with the switch on (the budget) and +// off (no budget). A record made under the other budget is not translated as if current. +[Collection(SchedulingStateCollection.Name)] +public sealed class MetalStableImagePrewarmTests : IDisposable +{ + private const ulong CodeAddress = PipelineTestGuest.MemoryBase + 0x1_0000; + private const ulong HeaderAddress = PipelineTestGuest.MemoryBase + 0x8000; + private const ulong BufferAddress = PipelineTestGuest.MemoryBase + 0x4_0000; + private const uint ImageType2D = 9; + + // The Metal host's answer on an Apple7/Apple8 device, SHARPEMU_METAL_STABLE_IMAGE_BINDINGS on. + internal static readonly StableImageDescriptorLimits MetalLimits = new(1_000_000, 1_000_000, 996, uint.MaxValue, 1_000_000); + + // MRT0 = (T#0.r, T#0.g, T#1.r, T#1.g): T#0 s[0:7], T#1 s[8:15], S# s[16:19] at PARAM0.xy (s20 is the primitive mask). + private static readonly uint[] TwoSlotProgram = + [ + 0xBEFC0314, // s_mov_b32 m0, s20 + 0xC8080000, // v_interp_p1_f32_e32 v2, v0, attr0.x + 0xC8090001, // v_interp_p2_f32_e32 v2, v1, attr0.x + 0xC80C0100, // v_interp_p1_f32_e32 v3, v0, attr0.y + 0xC80D0101, // v_interp_p2_f32_e32 v3, v1, attr0.y + 0xF0800F08, 0x00800402, // image_sample v[4:7], v[2:3], s[0:7], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xF0800F08, 0x00820802, // image_sample v[8:11], v[2:3], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D + 0xBF8C3F70, // s_waitcnt vmcnt(0) + 0xF800180F, 0x09080504, // exp mrt0 v4, v5, v8, v9 done vm + 0xBF810000, // s_endpgm + ]; + + private readonly string _directory = Path.Combine(Path.GetTempPath(), "SharpEmuTests", Guid.NewGuid().ToString("N")); + private readonly FatalScope _fatal = new(); + + public void Dispose() + { + _fatal.Dispose(); + if (Directory.Exists(_directory)) + { + Directory.Delete(_directory, recursive: true); + } + } + + private static byte[] Msl(ShaderCompileRequest request) + { + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error), error); + return Encoding.UTF8.GetBytes(shader.Source); + } + + // T# slot 0 at A, slot 1 at A (one descriptor in both slots) or at B, then an S# of zeros and the primitive mask. + private static uint[] UserData(bool sameTexture) + { + var userData = new uint[21]; + WriteTexture(userData, 0, 0x20); + WriteTexture(userData, 8, sameTexture ? 0x20u : 0x40u); + return userData; + } + + private static void WriteTexture(uint[] userData, int at, uint baseAddress) + { + userData[at] = baseAddress; + userData[at + 1] = 71u << 20; // 8_8_8_8 unorm + userData[at + 2] = (63u << 14) | 63u; // 64 x 64 + userData[at + 3] = (ImageType2D << 28) | Gen5ShaderTranslator.IdentityImageDstSelect; + } + + // A live session's pixel draws, each partition in turn; the MSL of every specialization it compiled. + private List<string> DrawPixel(StableImageDescriptorLimits limits, params bool[] sameTexture) + { + var drawn = new List<string>(); + var guest = new PipelineTestGuest(request => + { + var msl = Msl(request); + drawn.Add(Encoding.UTF8.GetString(msl)); + return msl; + }); + guest.Host.GraphicsImageDescriptorLimits = limits; + guest.Host.ComputeImageDescriptorLimits = limits; + using (var list = GraphicsPrewarmList.Open(_directory)) + { + Assert.NotNull(list); + guest.Host.GraphicsPrewarm = list; + guest.RegisterProgram(CodeAddress, HeaderAddress, TwoSlotProgram); + foreach (var same in sameTexture) + { + var cursor = 0u; + guest.Programs.GetOrCompile(guest.Source(CodeAddress, ShaderStage.Pixel, UserData(same)), + new StageCompileOptions { PixelInfo = new PixelInputInfo() }, ref cursor, out _); + } + } + + return drawn; + } + + // Two slots holding one texture, then two textures: one specialization within the Metal budget, two without. + [Theory] + [InlineData(true, 1)] + [InlineData(false, 2)] + public void AMetalShapedHostCompilesOneSpecializationForEveryAliasPartition(bool stable, int compiles) + { + var drawn = DrawPixel(stable ? MetalLimits : default, true, false); + Assert.Equal(compiles, drawn.Count); + } + + // The graphics prewarm replays each recorded specialization to the MSL the draw compiled, under the budget the + // session answered (the switch on: the Metal budget; off: none). + [Theory] + [InlineData(true)] + [InlineData(false)] + public void TheGraphicsPrewarmFindsWhatTheSessionRecorded(bool stable) + { + var limits = stable ? MetalLimits : default; + var drawn = DrawPixel(limits, true, false); + using var list = GraphicsPrewarmList.Open(_directory); + Assert.NotNull(list); + var items = list.Loaded(); + Assert.Equal(drawn.Count, items.Count); + var replayed = new List<string>(); + foreach (var item in items) + { + var record = GraphicsPrewarmList.Decode(item); + Assert.Equal(limits, record.Host.GraphicsImageLimits); + Assert.Equal(stable, record.Specialization!.StableImageBindings); + var compiler = new FakeShaderCompiler(Msl); + Assert.True(ShaderPrewarmCompiler.TryCompileGraphicsPrewarm(item, compiler, limits, out var compiled, out var error, + out var stale), error); + Assert.False(stale); + replayed.Add(Encoding.UTF8.GetString(((FakeCompiledShader)compiled!).Spirv)); + } + + Assert.Equal(drawn.Order(StringComparer.Ordinal), replayed.Order(StringComparer.Ordinal)); + } + + // A record the session made under the other setting is skipped as stale, never translated. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void TheGraphicsPrewarmSkipsARecordMadeUnderTheOtherBudget(bool stable) + { + _ = DrawPixel(stable ? MetalLimits : default, true); + using var list = GraphicsPrewarmList.Open(_directory); + Assert.NotNull(list); + var item = Assert.Single(list.Loaded()); + var compiler = new FakeShaderCompiler(Msl); + Assert.False(ShaderPrewarmCompiler.TryCompileGraphicsPrewarm(item, compiler, stable ? default : MetalLimits, + out _, out var error, out var stale)); + Assert.True(stale, error); + Assert.Empty(compiler.Requests); + } + + // The static precompile predicts the plan's binding policy, so its specialization applies to the plan. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void APredictedSpecializationFollowsThePlansBindingPolicy(bool stable) + { + _ = DrawPixel(stable ? MetalLimits : default, true); + using var list = GraphicsPrewarmList.Open(_directory); + Assert.NotNull(list); + var record = GraphicsPrewarmList.Decode(Assert.Single(list.Loaded())) with { Specialization = null }; + Assert.True(ShaderProgramCache.TryPredictSpecialization(record, out var predicted, out var error), error); + Assert.Equal(stable, predicted!.StableImageBindings); + Assert.True(ShaderCorpus.TryBuildRequest(record with { Specialization = predicted }, out var request, out error), error); + Assert.NotNull(request); + } + + // The compute prewarm call the Metal prewarm makes (ShaderPrewarmCompiler.TryCompilePrewarm with the host's budget) + // finds the specialization a live dispatch recorded, and refuses one of the other policy. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void TheComputePrewarmFindsWhatTheSessionRecorded(bool stable) + { + var limits = stable ? MetalLimits : default; + byte[] runtime; + using (var list = ShaderPrewarmList.Open(_directory)) + { + Assert.NotNull(list); + var guest = new PipelineTestGuest(Msl); + guest.Host.ShaderPrewarm = list; + guest.Host.ComputeImageDescriptorLimits = limits; + guest.Host.GraphicsImageDescriptorLimits = limits; + guest.RegisterProgram(CodeAddress, HeaderAddress, ImageBindingTestProgram.Code()); + ImageBindingTestProgram.WriteDescriptors(guest, BufferAddress, ImageBindingTestProgram.Partitions[0]); + var cursor = 0u; + guest.Programs.GetOrCompile(guest.Source(CodeAddress, ShaderStage.Compute, + [unchecked((uint)BufferAddress), (uint)(BufferAddress >> 32)]), + PipelineTestGuest.ComputeOptions(), ref cursor, out _); + runtime = Assert.Single(guest.Compiler.Shaders).Spirv; + } + + using var reloaded = ShaderPrewarmList.Open(_directory); + Assert.NotNull(reloaded); + var (record, code) = Assert.Single(reloaded.LoadedComputes()); + Assert.Equal(stable, record.Specialization.StableImageBindings); + var compiler = new FakeShaderCompiler(Msl); + Assert.True(ShaderPrewarmCompiler.TryCompilePrewarm(record, code, compiler, false, true, false, + out var compiled, out _, out var error, stableImageLimits: limits), error); + Assert.Equal(runtime, Assert.IsType<FakeCompiledShader>(compiled).Spirv); + var other = new FakeShaderCompiler(Msl); + Assert.False(ShaderPrewarmCompiler.TryCompilePrewarm(record, code, other, false, true, false, + out _, out _, out error, stableImageLimits: stable ? default : MetalLimits)); + Assert.Contains("image binding policy", error); + Assert.Empty(other.Requests); + } +} From 1ad2b43d15f21562192759c717707bbb82cff34a Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 03:20:08 +0000 Subject: [PATCH 111/134] [Metal] Answer PixelSubgroupArithmetic from the device, behind SHARPEMU_METAL_PIXEL_SUBGROUP_ARITHMETIC MetalRenderHost.PixelSubgroupArithmetic is true when the device supports MTLGPUFamilyApple7 (the feature set tables' SIMD-scoped reduction operations, which the MSL simd_sum/min/max/and/or/xor the translator emits need), graphics subgroups are on, and SHARPEMU_METAL_PIXEL_SUBGROUP_ARITHMETIC is not 0 (default on). The switch joins TranslationSwitchStamp, under which the prewarm and the translation cache store their work; the cache key already writes every request field, SubgroupArithmetic included (now pinned by a test). The graphics prewarm replays recorded host answers, so ShaderCorpusHostFlags records PixelSubgroupArithmetic and CorpusReplayHost answers it: a replayed row scan translates to the MSL the draw compiled (GraphicsPrewarmReplayTests). --- docs/macos/configuration.md | 1 + .../Gpu/Pipelines/ShaderCorpus.cs | 1 + .../Gpu/Pipelines/ShaderProgramCache.cs | 2 + .../V2/MetalRenderHost.BufferWordVariants.cs | 3 +- .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 22 +++++++++ .../MetalPixelSubgroupArithmeticTests.cs | 48 +++++++++++++++++++ .../Pipelines/GraphicsPrewarmReplayTests.cs | 44 ++++++++++++++++- .../Gpu/Pipelines/PipelineTestSupport.cs | 2 + .../Pipelines/TranslationDiskCacheTests.cs | 11 +++++ 9 files changed, 131 insertions(+), 3 deletions(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalPixelSubgroupArithmeticTests.cs diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 2425e51b2..e26d07df5 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -73,6 +73,7 @@ them for measurements or to isolate a problem. | `SHARPEMU_RUNTIME_IMAGE_SWIZZLE` | on | `0` bakes each storage image's destination select into the translated program, one program per select. By default a store reads the image's channel map from shader data, which the host writes from the bound descriptor. | | `SHARPEMU_METAL_FORMAT_LOAD_COMPONENT_BOUNDS` | on | `0` restores the old bound of a formatted buffer load whose format is fixed at translation: the whole element had to fit below the buffer's size. By default each selected component is checked at its own address, wrapping past 2^32 as on the hardware, so a component that wraps to the buffer's start is read, and the load reads its constants only when a selected component is out of range. An element that fits whole still takes one compare. Loads whose format is read at run time always check per component. | | `SHARPEMU_METAL_SHADER_CLOCK_STEP` | on | Metal has no shader clock, so `S_MEMTIME`/`S_MEMREALTIME` read a per-invocation counter of their own reads (logged once per shader as `[MSL][WARN][SHADER_CLOCK]`). By default each read moves it 2^32 + 1, as upstream's SPIR-V fallback moves its high dword: a guest wait on the 64-bit difference for fewer than 2^32 ticks ends at its next read, and a wait on the low dword still sees one tick per read. `0` steps by 1, so such a wait runs one loop trip per tick. | +| `SHARPEMU_METAL_PIXEL_SUBGROUP_ARITHMETIC` | on | `0` turns off the wave32 row reductions in translated pixel shaders. By default, on a GPU with SIMD-group reductions (Apple7 and later, every Apple silicon Mac), a pixel shader's DPP row scan read at lane 15 or 31 is computed as a SIMD-group reduction over its row, so a row of the guest wave the fragment simdgroup holds no fragment of reads the identity as on the PS5. `0` keeps the scan's own lane reads. | | `SHARPEMU_GRAPHICS_PARTIAL_LANES` | off | `1` makes pixel-shader lane reads (DPP, DPP8, PERMLANE16, V_READLANE) of a lane the fragment simdgroup never launched read the reading lane's own value, and treats such a lane as active when the guest EXEC mask has its bit. Off by default, as upstream: it changes every pixel shader with cross-lane operations. | | `SHARPEMU_METAL_MESHLETS` | on | `0` disables the meshlet cache. | | `SHARPEMU_METAL_V2_BINARY_ARCHIVE` | on | `0` disables the on-disk library and pipeline archives. | diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCorpus.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCorpus.cs index bd211a117..3ec0d2c2a 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCorpus.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderCorpus.cs @@ -27,6 +27,7 @@ public sealed record ShaderCorpusHostFlags public bool ComputeRunsOn32LaneSubgroups { get; init; } public bool DrawParameters { get; init; } public bool RuntimeImageSwizzles { get; init; } + public bool PixelSubgroupArithmetic { get; init; } } // One program as the translator was about to see it. Options is null when the guest code did not diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index eb09aac8a..fb180076d 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -779,6 +779,7 @@ private ShaderCodeCapture CaptureCode(ShaderSource source, RecordingCpuMemory re ComputeRunsOn32LaneSubgroups = options?.ComputeInfo is { } compute && _host.ComputeRunsOn32LaneSubgroups(compute), DrawParameters = _host.ShaderDrawParametersSupported, RuntimeImageSwizzles = _host.RuntimeImageSwizzlesSupported, + PixelSubgroupArithmetic = _host.PixelSubgroupArithmetic, }; // What the code bytes held when they failed, and any command-processor write into @@ -3077,6 +3078,7 @@ private sealed class CorpusReplayHost(ShaderCorpusHostFlags flags) : IShaderPipe public bool ClipDistanceEnabled => flags.ClipDistance; public bool ShaderDrawParametersSupported => flags.DrawParameters; public bool RuntimeImageSwizzlesSupported => flags.RuntimeImageSwizzles; + public bool PixelSubgroupArithmetic => flags.PixelSubgroupArithmetic; public RenderHostLimits Limits => default; public GpuSampleCount NoAttachmentSampleCounts => default; diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs index b5334fd60..990bca95f 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BufferWordVariants.cs @@ -78,7 +78,8 @@ internal sealed partial class MetalRenderHost internal static string TranslationSwitchStamp => $"portable={(PortableBuffers ? 1 : 0)},buffer_word_constants={(BufferWordConstants ? 1 : 0)}," + $"draw_parameters={(DrawParameters ? 1 : 0)}," + - $"runtime_image_swizzle={(RuntimeImageSwizzle.Enabled ? 1 : 0)}" + + $"runtime_image_swizzle={(RuntimeImageSwizzle.Enabled ? 1 : 0)}," + + $"pixel_subgroup_arithmetic={(PixelSubgroupArithmeticRequested ? 1 : 0)}" + // ShaderCompileRequest.GraphicsPartialSubgroupLanes takes its default from this variable. (Environment.GetEnvironmentVariable("SHARPEMU_GRAPHICS_PARTIAL_LANES") == "1" ? ",graphics_partial_lanes=1" : ""); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index 18dbe6bd7..068cfa6af 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -172,6 +172,8 @@ public MetalRenderHost( _relay = relay; PerVertexPixelInputsSupported = SupportsApple10Features(device); DepthBoundsTestSupported = SupportsApple10Features(device); + PixelSubgroupArithmetic = PixelSubgroupArithmeticRequested && GraphicsSubgroupOperationsEnabled && + SupportsSimdgroupReductions(device); GuestPixelFormats.NarrowSrgbFormats = SupportsNarrowSrgb(device); _sharedEvent = MetalNative.Send(device, SelNewSharedEvent); if (_sharedEvent == 0) @@ -336,6 +338,26 @@ internal ulong ReadCompletedSerial(bool useCompletedSnapshot) public GpuSampleCount NoAttachmentSampleCounts => GpuSampleCount.Count1Bit; + // A pixel shader's wave32 row scan read at lane 15 or 31 becomes a SIMD-group reduction over the row + // (Gen5MslTranslator.WaveReductions): a fragment simdgroup can hold only some of the guest wave's lanes, and a + // row with none of them read another row's scan. The translator emits simd_sum/min/max/and/or/xor, which MSL + // offers fragment functions from Metal 2.1 (MSL spec 6.10.2) and the feature set tables list as "SIMD-scoped + // reduction operations" for Apple7 and later; pixel shaders have real lanes only with graphics subgroups on. + // SHARPEMU_METAL_PIXEL_SUBGROUP_ARITHMETIC=0 keeps the scan's own lane reads. + public bool PixelSubgroupArithmetic { get; } + + internal static readonly bool PixelSubgroupArithmeticRequested = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_PIXEL_SUBGROUP_ARITHMETIC") != "0"; + + private const nint GpuFamilyApple7 = 1007; + + private static bool SupportsSimdgroupReductions(nint device) + { + var supportsFamily = MetalNative.Selector("supportsFamily:"); + return MetalNative.SendBool(device, MetalNative.Selector("respondsToSelector:"), supportsFamily) && + MetalNative.SendBool(device, supportsFamily, GpuFamilyApple7); + } + // Per-vertex pixel inputs are MSL 4.0's metal::vertex_value (macOS 26). The feature set // tables list "pre-raster per-vertex values" for Apple10 (M5) only; an M4 compiles the // source but get() returns garbage, so nothing older may claim it. diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalPixelSubgroupArithmeticTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalPixelSubgroupArithmeticTests.cs new file mode 100644 index 000000000..782e54051 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalPixelSubgroupArithmeticTests.cs @@ -0,0 +1,48 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.Tests.Scenes; +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.Pipelines; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests; + +/// <summary> +/// IShaderPipelineHost.PixelSubgroupArithmetic on Metal: pixel wave32 row scans become SIMD-group reductions +/// (Gen5MslTranslator.WaveReductions) where the device has SIMD-scoped reductions (Apple7 and later) and +/// SHARPEMU_METAL_PIXEL_SUBGROUP_ARITHMETIC is not 0. The switch decides the MSL, so it is part of the stamp that +/// the prewarm and the translation cache store their work under. +/// </summary> +public sealed class MetalPixelSubgroupArithmeticTests(ITestOutputHelper output) : SceneTestBase(output) +{ + private const nint GpuFamilyApple7 = 1007; + + [Fact] + public void TheSwitchIsPartOfTheTranslationStamp() + { + var expected = MetalRenderHost.PixelSubgroupArithmeticRequested ? 1 : 0; + Assert.Contains($"pixel_subgroup_arithmetic={expected}", MetalRenderHost.TranslationSwitchStamp, StringComparison.Ordinal); + Assert.Equal( + Environment.GetEnvironmentVariable("SHARPEMU_METAL_PIXEL_SUBGROUP_ARITHMETIC") != "0", + MetalRenderHost.PixelSubgroupArithmeticRequested); + } + + [Fact] + public void TheHostAnswersFromTheDevicesSimdgroupReductions() + { + using var rig = CreateRig(); + if (rig is null) return; + + var device = MetalNative.MTLCreateSystemDefaultDevice(); + var reductions = MetalNative.SendBool(device, MetalNative.Selector("supportsFamily:"), GpuFamilyApple7); + IShaderPipelineHost host = rig.Host; + Output.WriteLine($"Apple7 reductions: {reductions}, graphics subgroups: {host.GraphicsSubgroupOperationsEnabled}"); + Assert.Equal( + reductions && host.GraphicsSubgroupOperationsEnabled && MetalRenderHost.PixelSubgroupArithmeticRequested, + host.PixelSubgroupArithmetic); + // Every supported Mac (Apple silicon) is Apple7 or later. + Assert.True(reductions); + } +} diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/GraphicsPrewarmReplayTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/GraphicsPrewarmReplayTests.cs index 67d98d21d..e3b76223a 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/GraphicsPrewarmReplayTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/GraphicsPrewarmReplayTests.cs @@ -37,6 +37,33 @@ public sealed class GraphicsPrewarmReplayTests : IDisposable 0xBF810000, // s_endpgm ]; + // A wave32 row scan read at lanes 15 and 31 (Gen5MslTranslator.WaveReductions): s80 copies the entry EXEC, + // s0 = EXEC & s80, V_CNDMASK gives lanes outside s0 the identity, a DPP row_shr 1/2/4/8 add scans each row. + private static readonly uint[] RowScan = + [ + 0xD7650000, 0x020100C1, // v_mbcnt_lo_u32_b32 v0, -1, 0 + 0xBE89037E, // s_mov_b32 s9, exec_lo + 0xBED0037E, // s_mov_b32 s80, exec_lo + 0x8A50FF50, 0xFFF80000, // s_andn2_b32 s80, s80, 0xfff80000 + 0x34020083, // v_lshlrev_b32 v1, 3, v0 + 0x4A0202FF, 0x00000064, // v_add_nc_u32 v1, 0x64, v1 + 0x8700507E, // s_and_b32 s0, exec_lo, s80 + 0xBE94407E, // s_orn2_saveexec_b32 s20, exec_lo + 0xD5010002, 0x00020280, // v_cndmask_b32_e64 v2, 0, v1, s0 + 0x4A0404FA, 0xFF011102, // v_add_nc_u32_dpp v2, v2, v2 row_shr:1 row_mask:0xf bank_mask:0xf + 0x4A0404FA, 0xFF011202, // v_add_nc_u32_dpp v2, v2, v2 row_shr:2 row_mask:0xf bank_mask:0xf + 0x4A0404FA, 0xFF011402, // v_add_nc_u32_dpp v2, v2, v2 row_shr:4 row_mask:0xf bank_mask:0xf + 0x4A0404FA, 0xFF011802, // v_add_nc_u32_dpp v2, v2, v2 row_shr:8 row_mask:0xf bank_mask:0xf + 0xBEFE0314, // s_mov_b32 exec_lo, s20 + 0xD7600001, 0x02011F02, // v_readlane_b32 s1, v2, 15 + 0xD7600002, 0x02013F02, // v_readlane_b32 s2, v2, 31 + 0x7E080201, // v_mov_b32 v4, s1 + 0x7E0A0202, // v_mov_b32 v5, s2 + 0x7E180209, // v_mov_b32 v12, s9 + 0xF800180F, 0x0C000504, // exp mrt0 v4, v5, v0, v12 done vm + 0xBF810000, // s_endpgm + ]; + private readonly string _directory = Path.Combine(Path.GetTempPath(), "SharpEmuTests", Guid.NewGuid().ToString("N")); private readonly FatalScope _fatal = new(); private readonly bool _previousMipStatistics = ResourceMaterializer.RecordMipStatistics; @@ -63,7 +90,7 @@ private static uint[] UserData() } // The draw: translates with the switch as the Metal host sets it, and records the program. - private string RecordDraw(bool mipStatistics) + private string RecordDraw(bool mipStatistics, uint[]? program = null, bool pixelSubgroupArithmetic = false) { ResourceMaterializer.RecordMipStatistics = mipStatistics; var drawn = new List<string>(); @@ -77,7 +104,8 @@ private string RecordDraw(bool mipStatistics) { Assert.NotNull(list); guest.Host.GraphicsPrewarm = list; - guest.RegisterProgram(CodeAddress, HeaderAddress, SampledTexture); + guest.Host.PixelSubgroupArithmetic = pixelSubgroupArithmetic; + guest.RegisterProgram(CodeAddress, HeaderAddress, program ?? SampledTexture); var source = guest.Source(CodeAddress, ShaderStage.Pixel, UserData()); var options = new StageCompileOptions { PixelInfo = new PixelInputInfo() }; var cursor = 0u; @@ -120,4 +148,16 @@ public void AReplayWithoutTheDrawsMipStatisticsSwitchMakesALibraryTheGameNeverAs var drawn = RecordDraw(mipStatistics: true); Assert.NotEqual(drawn, Replay(mipStatistics: false)); } + + // The host's PixelSubgroupArithmetic answer is kept with the record, so the prewarm compiles the reduction (or + // the plain scan) the draw asked for. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void ARecordedRowScanReplaysWithTheHostsSubgroupArithmetic(bool pixelSubgroupArithmetic) + { + var drawn = RecordDraw(mipStatistics: false, RowScan, pixelSubgroupArithmetic); + Assert.Equal(pixelSubgroupArithmetic ? 2 : 0, drawn.Split("simd_sum(").Length - 1); + Assert.Equal(drawn, Replay(mipStatistics: false)); + } } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PipelineTestSupport.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PipelineTestSupport.cs index b700e5548..3682fba15 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PipelineTestSupport.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/PipelineTestSupport.cs @@ -98,6 +98,8 @@ public uint[] NormalizeImageDescriptor(IShaderFrontend frontend, ReadOnlySpan<ui // Off as on Metal (IShaderPipelineHost.RuntimeImageSwizzlesSupported); a test of the Vulkan plan turns it on. public bool RuntimeImageSwizzlesSupported { get; set; } + public bool PixelSubgroupArithmetic { get; set; } + public RenderHostLimits Limits => new(16384, 16384, 16384, 16384); public bool TryResolveColorOutput(uint dataFormat, uint numberType, uint componentSwap, out Gen5PixelOutputKind outputKind, out Gen5ColorComponentMapping componentMapping) diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/TranslationDiskCacheTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/TranslationDiskCacheTests.cs index 8982aa970..555ff56e5 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/TranslationDiskCacheTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/TranslationDiskCacheTests.cs @@ -53,6 +53,17 @@ public void PathsDumpsLogsAndProfilesStayOutOfTheKey(string name, bool ignored) public void OnlyTheTranslatorsAddressSwitchesPutTheAddressInTheKey(string name, bool selects) => Assert.Equal(selects, TranslationDiskCache.AddressSelectsTranslation(name)); + // A translation made with the row-scan reductions (PixelSubgroupArithmetic) is never served to a request without + // them, or the other way: the key writes every request field, SubgroupArithmetic among them. + [Fact] + public void TheKeyHoldsTheRequestsSubgroupArithmetic() + { + var properties = (System.Reflection.PropertyInfo[])typeof(TranslationDiskCache) + .GetField("RequestProperties", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)! + .GetValue(null)!; + Assert.Contains(properties, property => property.Name == nameof(SharpEmu.ShaderCompiler.ShaderCompileRequest.SubgroupArithmetic)); + } + [Fact] public void AStoredTranslationLoadsAsTheSameShader() { From f4f51f79abb29cf92125ffff222d7abd3f7279a1 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 04:10:56 +0000 Subject: [PATCH 112/134] [GPU] Hold a dispatch while its linked program links or translates, and report one left out The program cache links and translates a program with shader calls on a worker (DeferLinking) and reported it pending with an empty rejection, which ReportShaderSkip ignored: the dispatch was left out silently (ShaderPipelineCache.TryPrepareProgram -> RenderExecutor.Compute no-program). A dispatch now waits for that work, bounded by SHARPEMU_LINKED_COMPILE_WAIT_MS like its module wait; one still pending after the bound is counted (LinkedPreparationSkips) and logged once per program as [GPU][WARN][LINKED_PENDING]. Read-ahead resolves do not wait. --- .../Gpu/Pipelines/ShaderPipelineCache.cs | 88 ++++++++++++++++--- .../Gpu/Pipelines/ShaderProgramCache.cs | 14 +++ 2 files changed, 92 insertions(+), 10 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index 9bcdc5de5..58061af06 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -2399,7 +2399,7 @@ public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitia { _computeRebound.Increment(); t_resolvePath = ResolvePath.ComputeRebound; - var rebound = RebindComputeProgram(kept, entry, compute, dispatchInitiator, dimensionX, dimensionY, dimensionZ); + var rebound = RebindComputeProgram(kept, entry, compute, dispatchInitiator, dimensionX, dimensionY, dimensionZ, ahead); KeepComputeProgram(kept, rebound, compute, dimensionX, dimensionY, dimensionZ); return ahead ? Ahead(rebound, kept.Kernel, kept.Source, out refusal) @@ -2588,7 +2588,7 @@ private void KeepComputeProgram(KeptComputeProgram kept, ComputeProgram program, // The kept program's entry with this dispatch's user data: its code is not read or hashed again. private ComputeProgram RebindComputeProgram(KeptComputeProgram kept, ProgramSourceEntry entry, ComputeStageRegisters compute, uint dispatchInitiator, - uint dimensionX, uint dimensionY, uint dimensionZ) + uint dimensionX, uint dimensionY, uint dimensionZ, bool ahead) { using var profileScope = RenderPhaseProfile.MeasureDetail(RenderPhaseProfile.Phase.ProgramPreparation); var userData = UserData(compute.UserScalars, compute.UserScalarCount, probeWrittenRegisters: false, compute.Address, "compute", ref _computeUserData); @@ -2606,10 +2606,18 @@ private ComputeProgram RebindComputeProgram(KeptComputeProgram kept, ProgramSour options.ComputeSystemRegisters = kept.SystemRegisters; options.ComputeDispatch = CountedDispatch(input, kept.SystemRegisters, dimensionX, dimensionY, dimensionZ, kept.GpuThreadCounts); options.Tessellation = null; - if (!_programs.TryGetProgramForEntry(entry, source, options, _strictShaders, ref pushDataCursor, out handle, out stage, out var rejection)) + var started = System.Diagnostics.Stopwatch.GetTimestamp(); + var cursor = pushDataCursor; + var idleRetries = 0; + while (!_programs.TryGetProgramForEntry(entry, source, options, _strictShaders, ref pushDataCursor, out handle, out stage, out var rejection)) { - ReportShaderSkip(source, rejection); - return new ComputeProgram { Available = false }; + if (rejection.Length != 0 || ahead || !HoldPendingPreparation(source, started, ref idleRetries)) + { + ReportShaderSkip(source, rejection); + return new ComputeProgram { Available = false }; + } + + pushDataCursor = cursor; } } @@ -2828,7 +2836,8 @@ private ComputeProgram GetComputeProgramCore( computeOptions, ref pushDataCursor, out handle, - out stage)) + out stage, + holdPending: !ahead)) { return new ComputeProgram { Available = false }; } @@ -2858,12 +2867,71 @@ private ComputeProgram GetComputeProgramCore( : null; private bool TryPrepareProgram(ShaderSource source, StageCompileOptions options, ref uint pushDataCursor, - out ShaderProgram program, out ShaderStageResources stage) + out ShaderProgram program, out ShaderStageResources stage, bool holdPending = false) { - if (_programs.TryGetProgram(source, options, _strictShaders, ref pushDataCursor, out program, out stage, out var rejection)) - return true; + var started = System.Diagnostics.Stopwatch.GetTimestamp(); + var cursor = pushDataCursor; + var idleRetries = 0; + while (true) + { + pushDataCursor = cursor; + if (_programs.TryGetProgram(source, options, _strictShaders, ref pushDataCursor, out program, out stage, out var rejection)) + return true; + if (rejection.Length != 0 || !holdPending) + { + ReportShaderSkip(source, rejection); + return false; + } + + if (!HoldPendingPreparation(source, started, ref idleRetries)) + return false; + } + } + + // A program with shader calls is linked and translated on a worker (DeferLinking) and reports pending meanwhile. + // The dispatch that asked for it waits for that work, as a linked dispatch waits for its module + // (RenderExecutor.SkipWhileLinkedModuleCompiles), for at most LinkedPreparationWait: a skipped dispatch that set up + // later work is lost for good. A program whose preparation outlasts the bound is not waited for again, and every + // dispatch skipped for it is counted (LinkedPreparationSkips) and reported once per program. + internal long LinkedPreparationWait = RenderExecutor.LinkedCompileWaitTicks; + private readonly HashSet<ulong> _slowPreparations = new(); + private long _linkedPreparationSkips; + public long LinkedPreparationSkips => Interlocked.Read(ref _linkedPreparationSkips); + + private bool HoldPendingPreparation(ShaderSource source, long started, ref int idleRetries) + { + var left = LinkedPreparationWait - (System.Diagnostics.Stopwatch.GetTimestamp() - started); + if (left > 0 && !_slowPreparations.Contains(source.Hash)) + { + if (_programs.PendingPreparation(source.Hash) is { } task) + { + idleRetries = 0; + try + { + task.Wait(TimeSpan.FromSeconds((double)left / System.Diagnostics.Stopwatch.Frequency)); + } + catch (AggregateException) + { + // A failed link or translation surfaces at the next request, which refuses the program. + } + + return true; + } + + // Pending with no worker: the next request starts one (a per-record link); a program that stays so is refused. + if (++idleRetries <= 2) + return true; + } + + Interlocked.Increment(ref _linkedPreparationSkips); + if (_slowPreparations.Add(source.Hash)) + { + Console.Error.WriteLine( + $"[GPU][WARN][LINKED_PENDING] stage={source.Label} hash=0x{source.Hash:X16}: the linked program was not prepared within " + + $"{LinkedPreparationWait * 1000 / System.Diagnostics.Stopwatch.Frequency} ms (SHARPEMU_LINKED_COMPILE_WAIT_MS); its dispatches " + + "are skipped until it is ready and counted in LinkedPreparationSkips. Images can be incorrect."); + } - ReportShaderSkip(source, rejection); return false; } diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index eb09aac8a..27d1f889a 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -818,6 +818,20 @@ public ShaderProgram GetOrCompile(ShaderSource source, StageCompileOptions optio } } + // The worker a pending program waits on: its deferred link, else its deferred translation; null when neither runs + // (the program is ready, refused, or a per-record link starts at its next request). Callers hold the pipeline gate + // that serializes TryGetProgram, so the translations are not changed meanwhile. + public Task? PendingPreparation(ulong hash) + { + lock (_callGate) + { + if (_pendingLinks.TryGetValue(hash, out var link)) + return link.Link; + } + + return _pendingTranslations.TryGetValue(hash, out var translation) ? translation.Translation : null; + } + // False with no rejection while the program's link runs on a worker (DeferLinking). public bool TryGetProgram(ShaderSource source, StageCompileOptions options, bool strictShaders, ref uint pushDataCursor, out ShaderProgram program, out ShaderStageResources stage, out string rejection) From 1e649614847628fa2839e6a21f09850935443ee6 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 04:11:02 +0000 Subject: [PATCH 113/134] [Metal] Read a call record's integer image through its element's numeric class A call record image was read through the float declaration and the host refused integer textures to the null element. The host now resolves a record image to its integer view and writes its element's class word, with the image arrays numbering their record elements in one sequence so a class word names one record image; a load or size query of a class with integer forms branches on that class (uint, sint, float), as a heap record load does. --- .../Gen5MslTranslator.Resources.cs | 4 +- .../Gen5MslTranslator.ShaderCalls.cs | 29 ++++++++- .../V2/MetalRenderHost.BindlessHeap.cs | 8 ++- .../V2/MetalRenderHost.ShaderCalls.cs | 35 +++++------ .../MslLinkedCallTests.cs | 60 +++++++++++++++++++ 5 files changed, 111 insertions(+), 25 deletions(-) diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs index 3b28f599d..83b8fcf7b 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs @@ -2450,7 +2450,7 @@ private bool TryResolveLayoutImage( imageClass = HeapVolumeLayerClass(); } - if (fromHeap && heapNumericClass != ImageNumericClass.Float) + if ((fromHeap || fromCallRecord) && heapNumericClass != ImageNumericClass.Float) { imageClass = HeapIntegerClass(imageClass, heapNumericClass); } @@ -2469,7 +2469,7 @@ private bool TryResolveLayoutImage( } else if (fromCallRecord) { - texture = HeapTexture(heapSlot, imageClass.TextureType, _callRecordElement!, mark: false); + texture = HeapTexture(heapSlot, imageClass.TextureType, HeapImageIndex(_callRecordElement!, heapSlot, heapNumericClass), mark: false); } else if (imageInfo.BindlessSlot != DescriptorConstants.NoIndex) { diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.ShaderCalls.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.ShaderCalls.cs index f47714602..a47a23f40 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.ShaderCalls.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.ShaderCalls.cs @@ -232,14 +232,37 @@ private bool IsCallRecordImageAccess(Gen5ShaderInstruction instruction, out Call _request.CallRecordImageByMemoryIndex.TryGetValue(memoryIndex, out use) && use.Slot >= 0; } - // A call record image read: the element of the record's field, read through the float declaration of its class - // with no mark (the host resolved it with the record); a null element reads zero. + // A call record image read: the element of the record's field, with no mark (the host resolved it with the + // record); a null element reads zero. A load or size query of a class with integer forms branches on the element's + // numeric class, which the host wrote with the element, and reads it through that class's declaration, as a heap + // record load does; any other read takes the float declaration, whose class check reads an integer element null. private bool TryEmitCallRecordImage(Gen5ShaderInstruction instruction, Gen5ImageControl image, CallRecordFieldUse use, out string error) { _callRecordElement = CallRecordElement(use.Field); try { - return TryEmitHeapRead(instruction, image, ImageNumericClass.Float, layers: false, out error); + if (!IsHeapLoad(instruction, use.Slot)) + { + return TryEmitHeapRead(instruction, image, ImageNumericClass.Float, layers: false, out error); + } + + var elementClass = HeapElementClass(_callRecordElement); + foreach (var numericClass in new[] { ImageNumericClass.Float, ImageNumericClass.Uint, ImageNumericClass.Sint }) + { + Line($"if ({elementClass} == {HeapLiteral(BindlessHeap.ClassCode(numericClass))})"); + Line("{"); + _indent++; + var emitted = TryEmitHeapRead(instruction, image, numericClass, layers: false, out error); + _indent--; + Line("}"); + if (!emitted) + { + return false; + } + } + + error = string.Empty; + return true; } finally { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessHeap.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessHeap.cs index b4ce18165..c9990af1a 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessHeap.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessHeap.cs @@ -164,6 +164,7 @@ private void DisposeBindlessHeap() { _heapEntries.Clear(); _callRecordEntries.Clear(); + _callRecordImages.Clear(); _callRecordTextures.Order.Clear(); _heapRegionEntries.Clear(); _heapImageViews.ReleaseIdle(ulong.MaxValue, ulong.MaxValue, static _ => { }); @@ -660,10 +661,15 @@ private void WriteHeapImage(int slot, uint index, ulong resourceId) } // The numeric class of the element at index: that of the integer view an array holds there (the arrays hold views of - // one record at an index), or float. + // one record at an index, and one call record image at a call record index), or float. private void WriteHeapElementClass(uint index) { var code = 0u; + if (index >= BindlessHeap.CallRecordFirstIndex && _callRecordImages.TryGetValue(index, out var record) && record.Resolved) + { + code = BindlessHeap.ClassCode(record.NumericClass); + } + for (var slot = 0; slot < BindlessHeap.ImageKinds.Length && code == 0; slot++) { if (_heapEntries.TryGetValue((slot, index), out var entry) && entry.Resolved) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ShaderCalls.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ShaderCalls.cs index a8d8f6d79..c1bda9551 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ShaderCalls.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ShaderCalls.cs @@ -49,11 +49,15 @@ internal sealed partial class MetalRenderHost private readonly Dictionary<CallRecordKey, HeapEntry> _callRecordEntries = new(); private readonly uint[] _callRecordNext = new uint[BindlessHeap.ArrayCount]; + // The image arrays number their record elements in one sequence, so the class word of an element index + // (WriteHeapElementClass) holds the numeric class of the one record image there. + private uint _callRecordNextImage; + private readonly Dictionary<uint, HeapEntry> _callRecordImages = new(); private readonly HeapRegionEntries _callRecordTextures = new(); private MetalCallRecordPreparation? _callRecordPreparation; private int _callRecordReports; - internal long CallRecordElementsExhausted, CallRecordIntegerImages, UnlinkedCalls; + internal long CallRecordElementsExhausted, UnlinkedCalls; internal MetalCallRecordPreparation CallRecordPreparation => _callRecordPreparation ??= new MetalCallRecordPreparation( ReadCallRecordBytes, (address, size) => _memory.CanRead(address, size), CallRecordElement); @@ -105,8 +109,8 @@ private bool ReadCallRecordBytes(ulong address, Span<byte> destination) } // The heap element that holds the descriptor of one record field: one per distinct descriptor and array, resolved when - // it is first seen. A record's image is read through the float declaration of its class, so an integer texture is - // refused to the null element (warn + counter), never read through the wrong declaration. + // it is first seen. An integer image is resolved to its integer view and its element's class word names its class, so + // a load reads it through that class's declaration (Gen5MslTranslator.TryEmitCallRecordImage). private uint CallRecordElement(CallRecordField field, ReadOnlySpan<uint> words) { static ulong Pair(uint low, uint high) => low | ((ulong)high << 32); @@ -117,7 +121,8 @@ private uint CallRecordElement(CallRecordField field, ReadOnlySpan<uint> words) return entry.Index; } - var next = _callRecordNext[field.Slot]; + var image = field.Slot < BindlessHeap.ImageKinds.Length; + var next = image ? _callRecordNextImage : _callRecordNext[field.Slot]; if (BindlessHeap.CallRecordFirstIndex + next >= BindlessHeap.CallRecordNullIndex) { CallRecordElementsExhausted++; @@ -130,7 +135,10 @@ private uint CallRecordElement(CallRecordField field, ReadOnlySpan<uint> words) return BindlessHeap.CallRecordNullIndex; } - _callRecordNext[field.Slot] = next + 1; + if (image) + _callRecordNextImage = next + 1; + else + _callRecordNext[field.Slot] = next + 1; entry = new HeapEntry { Slot = field.Slot, @@ -139,20 +147,8 @@ private uint CallRecordElement(CallRecordField field, ReadOnlySpan<uint> words) }; _callRecordEntries.Add(key, entry); _callRecordTextures.Order.Add(entry); - if (entry.Slot < BindlessHeap.ImageKinds.Length && - HeapRecordClass(entry, entry.Words) is not (ImageNumericClass.Float or ImageNumericClass.Unsupported)) - { - CallRecordIntegerImages++; - if (_callRecordReports++ < 8) - { - Console.Error.WriteLine($"[METAL-V2][WARN] A call record holds an integer image, which the shader reads through its " + - $"float declaration: slot={field.Slot} element={entry.Index}; it reads as null."); - } - - WriteHeapImage(entry.Slot, entry.Index, 0); - return entry.Index; - } - + if (image) + _callRecordImages.Add(entry.Index, entry); ResolveHeapEntry(entry); return entry.Index; } @@ -275,6 +271,7 @@ private void ReportCallFaults() private void DisposeShaderCalls() { _callRecordEntries.Clear(); + _callRecordImages.Clear(); _callRecordTextures.Order.Clear(); foreach (ref var buffer in _callMarkBuffers.AsSpan()) { diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslLinkedCallTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslLinkedCallTests.cs index eca17e853..3ee46fefd 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslLinkedCallTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslLinkedCallTests.cs @@ -68,6 +68,13 @@ private static Gen5ShaderInstruction ImageSample(uint pc, uint resourceRegister, [Gen5Operand.Vector(0), Gen5Operand.Scalar(resourceRegister), Gen5Operand.Scalar(samplerRegister)], [Gen5Operand.Vector(4)], control); } + private static Gen5ShaderInstruction ImageLoad(uint pc, uint resourceRegister) + { + var control = new Gen5ImageControl(0xF, 0, [0u, 1u], 4, resourceRegister, 0, 1, false, Glc: false, Slc: false, A16: false, D16: false); + return new Gen5ShaderInstruction(pc, Gen5ShaderEncoding.Mimg, "ImageLoad", [0u, 0u], + [Gen5Operand.Vector(0), Gen5Operand.Scalar(resourceRegister)], [Gen5Operand.Vector(4)], control); + } + private static Gen5ShaderInstruction BufferAccess(uint pc, string opcode, uint resourceRegister, uint dwords = 1, uint vectorData = 4, bool offsetEnabled = false, uint vectorAddress = 0) { @@ -444,6 +451,59 @@ public void ACalleeReadsTheImageOfItsRecordThroughTheHeap(uint argument, bool fo Assert.All(run.Faults, word => Assert.Equal(0u, word)); } + // A callee loads an integer image its record holds: the load branches on the class the host wrote for the record's + // element and reads it through the uint or sint declaration, bit for bit. The float branch would read the element + // null, as the class check refuses an element of another class. + [Theory] + [InlineData(ImageNumericClass.Uint)] + [InlineData(ImageNumericClass.Sint)] + public void ACalleeLoadsTheIntegerImageOfItsRecordThroughItsClass(ImageNumericClass numericClass) + { + var caller = Program(MoveScalar(0, 14, 0x2000), MoveScalar(4, 15, 0), + Vop2(8, "VAddU32", 8, Operand(0x40), Gen5Operand.Vector(0)), + new Gen5ShaderInstruction(16, Gen5ShaderEncoding.Vop1, "VReadfirstlaneB32", [0u], [Gen5Operand.Vector(8)], [Gen5Operand.Scalar(16)], null), + MoveScalar(20, 17, 0), + Sop1(24, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + BufferAccess(28, "BufferStoreDwordx4", ResultRegister, dwords: 4, vectorData: 4), EndProgram(36)); + var callee = Program(ScalarLoad(0, 16, 20, 8), + Vop1(8, "VMovB32", 0, Operand(0)), Vop1(16, "VMovB32", 1, Operand(0)), + ImageLoad(24, 20), + Sop1(32, "SSetpcB64", 0, Gen5Operand.Scalar(14))); + var linked = Gen5ShaderCallLinker.Link(caller, [new(24, 14, 16, 14, 28, [new ShaderCallTarget(0x2000, 0, callee)])], + runtimeArguments: true); + var request = Request(linked, bindlessHeap: true, callRecords: true); + var use = Assert.Single(request.CallRecordImageByMemoryIndex).Value; + Assert.True(BindlessHeap.HoldsIntegers(use.Slot), $"slot={use.Slot}"); + var source = Compile(request).Source; + Assert.Contains("texture2d<uint", source, StringComparison.Ordinal); + Assert.Contains("texture2d<int", source, StringComparison.Ordinal); + if (SkipWithoutMetalDevice()) return; + + const uint element = BindlessHeap.CallRecordFirstIndex; + uint[] texel = numericClass == ImageNumericClass.Uint ? [0x7, 0x80000001, 0x12345678, 0xFFFFFFFF] : [0xFFFFFFF9, 0x80000000, 0x42, 0x7FFFFFFF]; + var format = numericClass == ImageNumericClass.Uint ? MetalNative.PixelFormatRgba32Uint : MetalNative.Rgba32SintPixelFormat; + var texture = MetalNative.CreateTexelTexture(format, + BindlessHeap.ImageClasses[use.Slot].Dimension == ImageDimension.Dim2D ? MetalNative.TextureType2D : MetalNative.TextureType2DArray, 1, texel); + var elements = new byte[BindlessHeap.ArrayCount * BindlessHeap.Capacity * Gen5MslArgumentLayout.HeapElementBytes]; + BinaryPrimitives.WriteUInt64LittleEndian(elements.AsSpan((int)(((uint)use.Slot * BindlessHeap.Capacity + element) * 8)), + MetalNative.ResourceId(texture)); + var feedbackWords = new uint[BindlessHeap.FeedbackWords]; + feedbackWords[BindlessHeap.MarkWords + (element >> (int)BindlessHeap.ClassWordShift)] |= + BindlessHeap.ClassCode(numericClass) << (int)((element & (BindlessHeap.ClassesPerWord - 1)) * BindlessHeap.ClassBits); + var recordWords = new uint[] { 1, 0x40, 0, 0, 5, 0, 0, 0 }; + recordWords[5 + use.Field] = element; + var records = MetalNative.CreateWordTable(DescriptorBindingKind.CallRecords, recordWords); + var run = new Run(linked, bindlessHeap: true, callRecords: true); + run.Dispatch(tables: [records], + heap: (MetalNative.CreateHeapElements(elements, [texture]), MetalNative.CreateHeapFeedback(feedbackWords))); + for (var component = 0; component < 4; component++) + { + Assert.Equal(texel[component], run.Word(component * 4)); + } + + Assert.All(run.Faults, word => Assert.Equal(0u, word)); + } + // The translation cache keeps a linked program's argument layout: its call record, call mark and call fault fields // read back as written (Gen5MslShaderPayload format 2). [Fact] From bcb7f608c092fb3ab1ef116fd1df072c7273b67d Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 04:11:06 +0000 Subject: [PATCH 114/134] [Metal] Make an unlinked shader call fatal under SHARPEMU_STRICT_COMPUTE, as on Vulkan Mirrors BdaFaultProcessor: the fault record read at a flush stops the emulator unless SHARPEMU_STRICT_COMPUTE=0, which keeps the counted [UNLINKED_CALL] warning. At shutdown the fault is only reported. --- .../V2/MetalRenderHost.ShaderCalls.cs | 23 ++++++--- .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 2 +- .../Scenes/UnlinkedCallFaultSceneTests.cs | 48 +++++++++++++++++++ 3 files changed, 65 insertions(+), 8 deletions(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/Scenes/UnlinkedCallFaultSceneTests.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ShaderCalls.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ShaderCalls.cs index c1bda9551..75984c797 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ShaderCalls.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ShaderCalls.cs @@ -21,7 +21,8 @@ namespace SharpEmu.Gpu.Metal.V2; // completed it is read, its bits stamped with the snapshot number (CallMarkedAt) and cleared, and the two swap. The // program cache compares the stamps with the snapshot in which it named a callee (ShaderCalleeTiers). // - Call faults: a call of a program linked per record that no record names claims an 8-word report -// (Gen5MslArgumentLayout.CallFaultWords), read once per flush and logged as [UNLINKED_CALL] with a counter. +// (Gen5MslArgumentLayout.CallFaultWords), read once per flush and logged as [UNLINKED_CALL] with a counter; under +// SHARPEMU_STRICT_COMPUTE (on unless 0) it is fatal, as on Vulkan (BdaFaultProcessor). internal sealed partial class MetalRenderHost { internal static readonly bool ShaderCallsEnabled = @@ -223,9 +224,11 @@ private void PollCallMarks() private nint _callFaultContents; private ulong _callFaultAddress; - private unsafe Span<uint> CallFaultWords => new((void*)_callFaultContents, Gen5MslArgumentLayout.CallFaultWords); + internal unsafe Span<uint> CallFaultWords => new((void*)_callFaultContents, Gen5MslArgumentLayout.CallFaultWords); + // An unlinked call stops the emulator, as any compute failure does, unless SHARPEMU_STRICT_COMPUTE=0 (tests change it). + internal bool StrictCompute = Environment.GetEnvironmentVariable("SHARPEMU_STRICT_COMPUTE") != "0"; - private ulong CallFaultsAddress() + internal ulong CallFaultsAddress() { if (_callFaultBuffer == 0) { @@ -239,7 +242,7 @@ private ulong CallFaultsAddress() } // Once per flush: a claimed report names the caller, the call and its target; the waves that made the call ended at it. - private void ReportCallFaults() + internal void ReportCallFaults(bool shutdown = false) { PollCallMarks(); if (_callFaultBuffer == 0) @@ -259,12 +262,18 @@ private void ReportCallFaults() var stage = words[6]; words[1..].Clear(); Volatile.Write(ref words[0], 0u); + var message = $"The shader called an unlinked function: hash=0x{hash:X16} pc=0x{pc:X} target=0x{target:X16} stage={stage}."; + // At shutdown the host is draining and the fault is only reported; the emulator is stopping anyway. + if (StrictCompute && !shutdown) + { + throw Fatal(message); + } + var unlinked = ++UnlinkedCalls; if (unlinked <= 16 || (unlinked & (unlinked - 1)) == 0) { - Console.Error.WriteLine($"[METAL-V2][WARN][UNLINKED_CALL] The shader called an unlinked function: hash=0x{hash:X16} " + - $"pc=0x{pc:X} target=0x{target:X16} stage={stage} count={unlinked}. The waves that made the call were ended; " + - "images can be incorrect."); + Console.Error.WriteLine($"[METAL-V2][WARN][UNLINKED_CALL] {message} count={unlinked}. The waves that made the call were " + + "ended; images can be incorrect. SHARPEMU_STRICT_COMPUTE=0 is set."); } } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index fd7b500cc..e944653d1 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -3281,7 +3281,7 @@ public void Dispose() RetireUploadPreludes(CompletedSerial, all: true); ReleaseInFlightSubmissions(); ReportStepCaps(); - ReportCallFaults(); + ReportCallFaults(shutdown: true); DisposeStepReport(); DisposeShaderCalls(); } diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/UnlinkedCallFaultSceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/UnlinkedCallFaultSceneTests.cs new file mode 100644 index 000000000..28dde26c3 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/UnlinkedCallFaultSceneTests.cs @@ -0,0 +1,48 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests.Scenes; + +/// <summary> +/// A wave that called a function no link resolved writes a fault record (Gen5MslArgumentLayout.CallFaultWords). The host +/// reads it once per flush: under SHARPEMU_STRICT_COMPUTE (on unless 0) it is fatal, as on Vulkan +/// (BdaFaultProcessor), and otherwise it is counted and logged as [UNLINKED_CALL]. +/// </summary> +public sealed class UnlinkedCallFaultSceneTests(ITestOutputHelper output) : SceneTestBase(output) +{ + [Theory] + [InlineData(true)] + [InlineData(false)] + public void AnUnlinkedCallIsFatalUnderStrictCompute(bool strict) + { + using var rig = CreateRig(); + if (rig is null) return; + rig.Host.StrictCompute = strict; + rig.Host.CallFaultsAddress(); + var words = rig.Host.CallFaultWords; + words[1] = 0x9ABCDEF0; + words[2] = 0x12345678; + words[3] = 0x40; + words[4] = 0x2000; + words[6] = 5; + words[0] = 2; + + if (strict) + { + Assert.Throws<SceneFatalException>(() => rig.Host.ReportCallFaults()); + Assert.Contains(rig.Fatals, message => message.Contains("unlinked function: hash=0x123456789ABCDEF0 pc=0x40", StringComparison.Ordinal)); + Assert.Equal(0, rig.Host.UnlinkedCalls); + } + else + { + rig.Host.ReportCallFaults(); + Assert.Equal(1, rig.Host.UnlinkedCalls); + Assert.Empty(rig.Fatals); + } + + Assert.Equal(0u, rig.Host.CallFaultWords[0]); + } +} From 1778c85b2f2b276c589f76cfe875a92f74147eef Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 04:11:16 +0000 Subject: [PATCH 115/134] [Metal] Prewarm linked programs under the host's bindless heap policy A linked prewarm record keeps the heap policy it was linked with and is refused under another. Metal's prewarm went through ShaderPrewarmCompiler, which had no heap parameter, so every heap-linked record failed its replay; the wrapper now takes the policy and Metal passes MetalRenderHost.BindlessHeapEnabled, as the live plan uses. --- .../Gpu/Pipelines/ShaderPrewarmCompiler.cs | 4 +- .../V2/MetalShaderPrewarm.cs | 5 ++- .../ShaderPrewarmLinkedReplayTests.cs | 37 +++++++++++++++++++ 3 files changed, 43 insertions(+), 3 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmCompiler.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmCompiler.cs index e649c8862..bffdf0d87 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmCompiler.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmCompiler.cs @@ -12,9 +12,9 @@ public static class ShaderPrewarmCompiler public static bool TryCompilePrewarm(ComputePrewarmRecord record, ShaderCodeCapture code, IGuestGpuBackend compiler, bool sharedInt64Atomics, bool execGuardElision, bool signedZeroInfNanPreserve, out IGuestCompiledShader? compiled, out BindingLayout? layout, out string error, bool hostWave64Supported = false, bool hostComputeSubgroup32 = false, bool imageInt64Atomics = false, bool tableBlocks = false, - Func<ulong, IShaderFrontend?>? frontendOf = null, bool runtimeImageSwizzles = false) => + Func<ulong, IShaderFrontend?>? frontendOf = null, bool runtimeImageSwizzles = false, bool bindlessHeap = false) => ShaderProgramCache.TryCompilePrewarm(record, code, compiler, sharedInt64Atomics, execGuardElision, signedZeroInfNanPreserve, out compiled, out layout, out error, - hostWave64Supported, hostComputeSubgroup32, imageInt64Atomics, tableBlocks: tableBlocks, frontendOf: frontendOf, + hostWave64Supported, hostComputeSubgroup32, imageInt64Atomics, bindlessHeap: bindlessHeap, tableBlocks: tableBlocks, frontendOf: frontendOf, runtimeImageSwizzles: runtimeImageSwizzles); /// <summary> diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs index 32e5865d0..372399c10 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs @@ -854,7 +854,10 @@ private static void PrewarmComputePipeline( out var compiled, out _, out var error, - runtimeImageSwizzles: MetalRenderHost.PrewarmRuntimeImageSwizzles)) + runtimeImageSwizzles: MetalRenderHost.PrewarmRuntimeImageSwizzles, + // As the live dispatch plans it (IShaderPipelineHost.SupportsBindlessHeap): a linked record holds the + // heap policy it was linked with and is refused under another. + bindlessHeap: MetalRenderHost.BindlessHeapEnabled)) { NoteFailure(record, error); return; diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPrewarmLinkedReplayTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPrewarmLinkedReplayTests.cs index 12f32365f..3ccca0800 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPrewarmLinkedReplayTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderPrewarmLinkedReplayTests.cs @@ -118,6 +118,43 @@ public void RuntimeRecordModesRoundTripThroughRecordingAndTheTranslator(bool cal replay.Program.Instructions.Select(instruction => instruction.Control)); } + // A host with the bindless heap (Metal's MetalShaderPrewarm, through ShaderPrewarmCompiler) links its run-time record + // callers under the heap policy, which the record keeps: the replay through the shared prewarm entry point translates + // the same request when it passes the host's policy, and refuses the record loudly under another. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AHeapLinkedRecordReplaysThroughThePrewarmEntryPointUnderTheHostsPolicy(bool callMarks) + { + using var fatal = new FatalScope(); + ShaderCompileRequest runtime; + using (var list = Open()) + { + var guest = CreateGuest(list, linked: true); + guest.Host.SupportsBindlessHeap = true; + guest.Host.RuntimeCallRecordsSupported = true; + guest.Host.CallMarksSupported = callMarks; + UseIsolatedCallUnion(guest, withCallee: true); + Compile(guest, linked: true); + runtime = Assert.Single(guest.Compiler.Requests); + } + + using var restored = Open(); + var (record, code) = Assert.Single(restored.LoadedComputes()); + Assert.True(record.Linked?.BindlessHeap); + var compiler = new FakeShaderCompiler(CompileSpirv); + Assert.True(ShaderPrewarmCompiler.TryCompilePrewarm(record, code, compiler, false, true, false, + out _, out var layout, out var error, bindlessHeap: true), error); + Assert.Equal(runtime.Bindings, layout); + var replay = Assert.Single(compiler.Requests); + Assert.Equal(runtime.Program.Instructions.Select(instruction => instruction.Control), + replay.Program.Instructions.Select(instruction => instruction.Control)); + + Assert.False(ShaderPrewarmCompiler.TryCompilePrewarm(record, code, new FakeShaderCompiler(CompileSpirv), false, true, false, + out _, out _, out error)); + Assert.Contains("binding policy", error, StringComparison.Ordinal); + } + private void UseIsolatedCallUnion(PipelineTestGuest guest, bool withCallee) { // Runtime linking loads kept callees before its first compile. Inject a store under this test's directory, From dce819be193b10de221e6afa744402914843de20 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 04:20:42 +0000 Subject: [PATCH 116/134] [Metal] Follow upstream's call-mark relink for run-time call records, count the skipped calls, and test it end to end A caller linked with run-time call records first links the callees an earlier session kept for it (none in a new one), so its first dispatches run at once and each call to a callee its program lacks marks the callee and returns (ShaderCalleeTiers, as on Vulkan). The Metal host already delivered the marks: an instrumented run showed one snapshot per completed submission, the callee counted at snapshot 3, the choice settled at 11, and the relinked program served from the dispatch after its pipeline was ready (dispatch 72 under load). The earlier round's scene test stopped after one dispatch, so it only ever saw the interim program. The interim skip is no longer silent: the host counts each marked (caller, callee) per read snapshot (MarkedCalls, call_marks= on the perf line beside unlinked_calls=), and the program cache logs each caller once when its calls first reach callees its program lacks ([GPU][INFO][CALLEE_TIERS], diagnostic only; nothing changes for Vulkan beyond that line). LinkedCallSceneTests: run-time records (dispatch until the callee lands, then a second host over the same linked cache directory runs the kept callee at its first dispatch), per-record links (host knob RuntimeCallRecordsEnabled, as SHARPEMU_RUNTIME_CALL_RECORDS=0), and the held-compiler case. Tests set LinkedProgramCacheDirectory to a temporary directory so a kept callee from an earlier run cannot hide the sequence. --- .../Gpu/Pipelines/ShaderProgramCache.cs | 12 +- .../V2/MetalRenderHost.ShaderCalls.cs | 37 +++- .../SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs | 3 + .../Scenes/LinkedCallSceneTests.cs | 209 ++++++++++++++++++ 4 files changed, 254 insertions(+), 7 deletions(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/Scenes/LinkedCallSceneTests.cs diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index 27d1f889a..0009558ff 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -364,6 +364,8 @@ internal static bool PendingPermutationServes(IReadOnlyList<ProgramPermutation> // The callees each runtime-record caller's calls reach (ShaderCalleeTiers), when the host marks calls; without marks a // caller links every callee its tables name. private readonly Dictionary<ProgramKey, ShaderCalleeTiers> _calleeTiers = new(ProgramKeyComparer.Instance); + // The callers whose first calls to callees their program lacked have been logged ([CALLEE_TIERS]). + private readonly HashSet<ulong> _calleeTierReports = []; // The linked programs and the call-linking state above belong to the thread holding this lock. It is taken before _gate // and never inside it: a link, a pipeline poll and a fallback's recursion happen under it, a permutation compile does not. @@ -1373,7 +1375,15 @@ private ShaderProgram CompleteProgram(ProgramSourceEntry entry, bool sourceWasCa { if (runtimeFallback is null) { - tiers.Observe(library, programKey.Hash, _host); + if (tiers.Observe(library, programKey.Hash, _host) != 0 && _calleeTierReports.Add(programKey.Hash)) + { + // Diagnostic only: until the program that holds them is ready, these calls keep returning + // at once (call marks) and the caller's dispatches run without the callees' effects. + Console.Error.WriteLine($"[GPU][INFO][CALLEE_TIERS] stage={source.Label} hash=0x{programKey.Hash:X16}: " + + $"calls reached {tiers.Called} callee(s) the caller's linked program lacks; they returned at once " + + "and the caller is linked again with them once its calls settle. Logged once per caller."); + } + var chosen = tiers.Choose(union, FallbackGeneration(programKey), _host.CallMarkSnapshots); library = _libraryMemo is { } chosenMemo ? chosenMemo.WithSiteCallees(library, caller.Address, chosen) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ShaderCalls.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ShaderCalls.cs index 75984c797..b007dc5fc 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ShaderCalls.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ShaderCalls.cs @@ -29,7 +29,10 @@ internal sealed partial class MetalRenderHost Environment.GetEnvironmentVariable("SHARPEMU_METAL_SHADER_CALLS") != "0"; // Records live in the bindless heap, so they need it; marks exist only for programs linked with run-time records. - public bool RuntimeCallRecordsSupported => ShaderCallsEnabled && BindlessHeapEnabled; + public bool RuntimeCallRecordsSupported => ShaderCallsEnabled && BindlessHeapEnabled && RuntimeCallRecordsEnabled; + + // Tests link a copy per record on one host, as SHARPEMU_RUNTIME_CALL_RECORDS=0 does for the process. + internal bool RuntimeCallRecordsEnabled { get; set; } = true; public bool CallMarksSupported => RuntimeCallRecordsSupported; @@ -38,10 +41,13 @@ internal sealed partial class MetalRenderHost public long CallMarkedAt(uint bit) => Volatile.Read(ref _callMarkedAt[bit & (CallMarks.Bits - 1)]); // pipeline_cache/<title>/metal-v2/linked, beside the translations and analysis caches (MetalTranslationCache). - public string? LinkedProgramCacheDirectory => ShaderCallsEnabled - ? _linkedProgramCacheDirectory ??= SharpEmuPaths.UserPath("pipeline_cache", - MetalShaderPrewarm.SanitizeTitleId(VideoOutBackendServices.GetApplicationTitleId()), "metal-v2", "linked") - : null; + // Tests set it before the first dispatch (the program cache opens the store at its first runtime-record caller). + public string? LinkedProgramCacheDirectory + { + get => ShaderCallsEnabled ? _linkedProgramCacheDirectory ??= SharpEmuPaths.UserPath("pipeline_cache", + MetalShaderPrewarm.SanitizeTitleId(VideoOutBackendServices.GetApplicationTitleId()), "metal-v2", "linked") : null; + internal set => _linkedProgramCacheDirectory = value; + } private string? _linkedProgramCacheDirectory; @@ -60,6 +66,17 @@ internal sealed partial class MetalRenderHost internal long CallRecordElementsExhausted, UnlinkedCalls; + // Calls that returned at once because the caller's program did not hold their callee yet: each bit a read mark snapshot + // holds is one (caller, callee address) whose calls were skipped since the snapshot before. The program cache links the + // callee in once its calls have settled (ShaderCalleeTiers), and the program that holds it serves from the next dispatch + // after its pipeline is ready; until then the caller runs without the callee's effects, as on Vulkan. Counted in total + // (MarkedCalls) and on the perf line (call_marks=); the program cache logs each caller once ([CALLEE_TIERS]). + internal long MarkedCalls => Volatile.Read(ref _markedCalls); + private long _markedCalls; + private long _markedCallsWindow; + + internal long TakeMarkedCalls() => Interlocked.Exchange(ref _markedCallsWindow, 0); + internal MetalCallRecordPreparation CallRecordPreparation => _callRecordPreparation ??= new MetalCallRecordPreparation( ReadCallRecordBytes, (address, size) => _memory.CanRead(address, size), CallRecordElement); @@ -202,7 +219,15 @@ private void PollCallMarks() var snapshot = Volatile.Read(ref _callMarkSnapshots) + 1; for (var word = 0; word < words.Length; word++) { - for (var bits = Volatile.Read(ref words[word]); bits != 0; bits &= bits - 1) + var held = Volatile.Read(ref words[word]); + if (held != 0) + { + var count = BitOperations.PopCount(held); + Interlocked.Add(ref _markedCalls, count); + Interlocked.Add(ref _markedCallsWindow, count); + } + + for (var bits = held; bits != 0; bits &= bits - 1) { Volatile.Write(ref _callMarkedAt[word * 32 + BitOperations.TrailingZeroCount(bits)], snapshot); } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs index e944653d1..3d3adb6b7 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.cs @@ -2934,6 +2934,9 @@ public void ReportCounters() // (a miss it compiled itself, or a draw that could not be left out), and compiles // queued or running on the compiler threads now. $"draws_skipped_compiling={Interlocked.Exchange(ref _drawsSkippedCompiling, 0)} " + + // Calls that returned at once because their caller's linked program lacked the callee (MarkedCalls), and + // calls no link resolved at all. + $"call_marks={TakeMarkedCalls()} unlinked_calls={UnlinkedCalls} " + $"leave_out=[{FormatLeaveOutCounters()}] " + // Pipelines specialized for a draw's buffer words, and the draws on them (FormatBufferWordCounters). $"buffer_words=[{FormatBufferWordCounters()}] " + diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/LinkedCallSceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/LinkedCallSceneTests.cs new file mode 100644 index 000000000..9968c1962 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/LinkedCallSceneTests.cs @@ -0,0 +1,209 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests.Scenes; + +/// <summary> +/// Linked shader calls end to end on the Metal host: a compute program loads a function's address and argument from a +/// table its user data names and calls it with S_SWAPPC_B64, and the callee's result lands after the call returns. +/// <para> +/// With run-time call records (the default) the program cache follows upstream's sequence (ShaderCalleeTiers): a caller +/// first links the callees an earlier session kept for it, none in a new one, so its first dispatches run at once and each +/// call to a callee the program lacks marks the callee and returns (the store sees the caller's own value). The host reads +/// the marks once their submission completes (CallMarkSnapshots); a mark newer than the naming makes the callee called, the +/// caller is linked again with it once its calls settle, and the new program serves from the dispatch after its pipeline is +/// ready. Nothing is held or re-run meanwhile; the skipped calls are counted (MarkedCalls). With a copy linked per record +/// (SHARPEMU_RUNTIME_CALL_RECORDS=0) the first dispatch already runs the callee. +/// </para> +/// </summary> +public sealed class LinkedCallSceneTests(ITestOutputHelper output) : SceneTestBase(output) +{ + private const uint BufferFormat = 20; + + // Generous: the relink waits a few completed submissions, then links, translates and compiles in the background, and + // the device is shared with other test runs. + private static readonly TimeSpan RelinkBound = TimeSpan.FromSeconds(60); + + // s_buffer_load_dwordx4 s[16:19], s[0:3], 0 (the record: function low/high, argument low/high); s_waitcnt; + // s_mov_b32 s14..s17 from s16..s19; s_swappc_b64 s[14:15], s[14:15]; buffer_store_dword v1, off, s[4:7], 0; s_endpgm. + private static readonly uint[] Caller = + [ + 0xF4280400, 0xFA000000, 0xBF8C0000, 0xBE8E0310, 0xBE8F0311, 0xBE900312, 0xBE910313, 0xBE8E210E, + 0xE0700000, 0x80010100, 0xBF810000, + ]; + + // v_mov_b32 v1, s16 (the argument's low word); s_setpc_b64 s[14:15]. + private static readonly uint[] Callee = [0x7E020210, 0xBE80200E]; + + // A second function: v_mov_b32 v1, 0x100; v_add_nc_u32 v1, s16, v1; s_setpc_b64 s[14:15]. + private static readonly uint[] OtherCallee = [0x7E0202FF, 0x00000100, 0x4A020210, 0xBE80200E]; + + // Run-time records: the first dispatch runs the caller without the callee (its call marks it and returns), the marks + // reach the program cache, the caller is linked again with the callee, and a later dispatch stores the callee's value. + // A second host over the same linked cache directory (a later session) links the kept callee into the caller's first + // program, so its first dispatch already runs it. + [Theory] + [InlineData(false, 0x77u, 0x77u)] + [InlineData(true, 0x55u, 0x155u)] + public void ARuntimeRecordCallReachesItsCalleeOnceItsMarksRelinkTheCaller(bool other, uint argument, uint expected) + { + var directory = TemporaryDirectory(); + try + { + using (var rig = CreateRig()) + { + if (rig is null) return; + rig.Host.LinkedProgramCacheDirectory = directory; + var scene = new CallScene(rig, other ? OtherCallee : Callee, argument); + + var first = scene.Dispatch(); + Assert.Equal(0u, first[0]); + Assert.Equal(0xDEADBEEFu, first[1]); + + var dispatches = scene.DispatchUntil(expected, RelinkBound, Output); + Assert.True(dispatches > 0, $"the callee's value never landed within {RelinkBound.TotalSeconds} s"); + Assert.True(rig.Host.MarkedCalls > 0, "the skipped calls were not counted"); + Assert.True(rig.Host.CallMarkSnapshots > 3, "the callee became called before a mark newer than its naming"); + Assert.Equal(expected, scene.Dispatch()[0]); + Assert.Equal(0, rig.Host.UnlinkedCalls); + Assert.Empty(rig.Fatals); + } + + Assert.True(File.Exists(Path.Combine(directory, "callees.bin")), "the relinked caller's callees were not kept"); + using (var later = CreateRig()!) + { + later.Host.LinkedProgramCacheDirectory = directory; + var scene = new CallScene(later, other ? OtherCallee : Callee, argument); + var words = scene.Dispatch(); + Assert.Equal(expected, words[0]); + Assert.Equal(0xDEADBEEFu, words[1]); + Assert.Equal(0, later.Host.MarkedCalls); + Assert.Equal(0, later.Host.UnlinkedCalls); + Assert.Empty(later.Fatals); + } + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + // A copy linked per record (the host refuses run-time records, as SHARPEMU_RUNTIME_CALL_RECORDS=0 does): the first + // dispatch waits for its linked program and runs the callee, and nothing is marked. + [Theory] + [InlineData(false, 0x77u, 0x77u)] + [InlineData(true, 0x55u, 0x155u)] + public void APerRecordLinkRunsTheCalleeAtTheFirstDispatch(bool other, uint argument, uint expected) + { + using var rig = CreateRig(); + if (rig is null) return; + rig.Host.RuntimeCallRecordsEnabled = false; + var scene = new CallScene(rig, other ? OtherCallee : Callee, argument); + + var words = scene.Dispatch(); + + Assert.Equal(expected, words[0]); + Assert.Equal(0xDEADBEEFu, words[1]); + Assert.Equal(0, rig.Host.MarkedCalls); + Assert.Equal(0, rig.Host.UnlinkedCalls); + Assert.Empty(rig.Fatals); + } + + // The caller's first program is still compiling at its first dispatch (the compiler is held): the dispatch waits for it + // within SHARPEMU_LINKED_COMPILE_WAIT_MS and runs once it is ready, instead of being left out; the relink that follows + // compiles behind the same gate and brings the callee in. + [Fact] + public void ADispatchWhoseLinkedModuleIsStillCompilingRunsOnceItIsReady() + { + // Declared before the rig, so it is disposed after it: a compiler thread may still reach this gate until the + // rig's host has joined its threads, and waiting on a disposed gate throws on that thread and ends the process. + using var gate = new ManualResetEventSlim(false); + var directory = TemporaryDirectory(); + try + { + using var rig = CreateRig(); + if (rig is null) return; + rig.Host.LinkedProgramCacheDirectory = directory; + rig.Host.PipelineCompiler.Gate = gate; + var scene = new CallScene(rig, Callee, 0x99); + using var release = Task.Delay(TimeSpan.FromMilliseconds(500)).ContinueWith(_ => gate.Set()); + + var first = scene.Dispatch(); + + Assert.True(gate.IsSet, "the dispatch ran before its module was released"); + Assert.Equal(0u, first[0]); + Assert.Equal(0xDEADBEEFu, first[1]); + Assert.True(scene.DispatchUntil(0x99, RelinkBound, Output) > 0, "the callee's value never landed"); + Assert.Equal(0, rig.Host.UnlinkedCalls); + Assert.Empty(rig.Fatals); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + private static string TemporaryDirectory() + { + var directory = Path.Combine(Path.GetTempPath(), "sharpemu-linked-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + return directory; + } + + // One caller dispatch over a table naming the function and its argument; each dispatch refills the result first. + private sealed class CallScene + { + private readonly SceneRig _rig; + private readonly ulong _caller; + private readonly ulong _table; + private readonly ulong _result; + + public CallScene(SceneRig rig, uint[] function, uint argument) + { + _rig = rig; + var address = rig.Program(function); + _table = rig.Memory.Allocate(16, 256); + rig.Memory.Write<uint>(_table, [(uint)address, (uint)(address >> 32), argument, 0]); + _result = rig.Memory.Allocate(64, 256); + _caller = rig.Program(Caller); + } + + public uint[] Dispatch() + { + _rig.Memory.Write<uint>(_result, Enumerable.Repeat(0xDEADBEEFu, 16).ToArray()); + var state = new SceneState(1, 1); + state.Context.Clear(); + state.Uconfig.Clear(); + state.ComputeShader(_caller, 1, 1, 1, + [.. Descriptors.Buffer(_table, 4, 4, BufferFormat), .. Descriptors.Buffer(_result, 4, 16, BufferFormat)], true, false, false, 0, 0); + _rig.Submit(state.Emit(new ScenePm4()).DispatchDirect(1, 1, 1)); + return _rig.Read<uint>(_result, 2); + } + + // Dispatches (each submission completes before the next, as frames do) until the first word is the expected value; + // returns how many dispatches that took, or 0 past the bound. Every interim dispatch runs the caller (no 0xDEADBEEF). + public int DispatchUntil(uint expected, TimeSpan bound, ITestOutputHelper output) + { + var clock = System.Diagnostics.Stopwatch.StartNew(); + for (var dispatches = 1; clock.Elapsed < bound; dispatches++) + { + var words = Dispatch(); + if (words[0] == expected) + { + Assert.Equal(0xDEADBEEFu, words[1]); + output.WriteLine($"landed after {dispatches} dispatches, {clock.ElapsedMilliseconds} ms, " + + $"{_rig.Host.CallMarkSnapshots} mark snapshots, {_rig.Host.MarkedCalls} marked calls"); + return dispatches; + } + + Assert.Equal(0u, words[0]); + Thread.Sleep(5); + } + + return 0; + } + } +} From 3b1c55499dc8a7896f88df683caa2353d0ae16d9 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 04:30:59 +0000 Subject: [PATCH 117/134] [Shader] Share the bodies of a callee's per-record copies at a call site in MSL A program linked per record holds one copy of a callee for each record of a site's table; inlined, the MSL source and the Metal library compile grew with records x callee size. Port upstream's ShareLinkedCallBodies to MSL (Gen5MslTranslator.SharedCalls.cs): the last copy of each callee at each site is kept, every record's test and entry stay, the entry stores the record's slot (sharpemu_call_slot), and every other copy's body becomes a forward branch into the kept one. An instruction of the kept body whose memory records differ between the records is emitted once per distinct set, under a test of the slot, reading the memory records of that record's copy (MemoryPc); the plan still holds every copy, so bindings do not change. Not ported: the site lookup and the outlined DontInline functions that serve several sites. MSL has no goto or lambdas and a translated body reads and writes the kernel's own locals, so a device function would take the whole register state by reference; the growth with records is what sharing within a site removes. Default on; SHARPEMU_METAL_SHARED_CALL_BODIES=0 (Gen5MslCodegenOptions. SharedCallBodies) inlines as before. Run-time-record programs hold one copy per callee and are unchanged. Tests: MslLinkedCallTests pass with the switch on and off (30/30 each); RecordsOfOneCalleeShareOneBody (1/8/64/256 records, both forms give the same words and faults); ASharedBodyEmitsAMemoryInstructionPerRecordWhoseResourcesDiffer. --- docs/macos/configuration.md | 1 + .../Gen5MslCodegenOptions.cs | 6 + .../Gen5MslTranslator.BindlessHeap.cs | 2 +- .../Gen5MslTranslator.Resources.cs | 38 +- .../Gen5MslTranslator.ShaderCalls.cs | 7 +- .../Gen5MslTranslator.SharedCalls.cs | 326 ++++++++++++++++++ .../Gen5MslTranslator.cs | 8 +- .../MslLinkedCallTests.cs | 107 +++++- 8 files changed, 473 insertions(+), 22 deletions(-) create mode 100644 src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.SharedCalls.cs diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 8f801db78..7cb5cc0eb 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -71,6 +71,7 @@ them for measurements or to isolate a problem. | `SHARPEMU_METAL_DRAW_PARAMETERS` | on | `0` turns off draw parameters in translated vertex programs. By default a vertex program's instance index counts from the draw's base instance, and when an indirect draw names a user-data register for its base vertex or start instance, the program counts its vertex index from the base vertex and stores both bases there (the command processor no longer writes those registers). `0` gives the program Metal's ids, which include both bases, and stores nothing. | | `SHARPEMU_METAL_BINDLESS_HEAP` | on | `0` turns off the bindless heap. By default an image or sampler a program reads from a descriptor table at a record only the shader knows is read through the heap: the shader marks the records it reads, the host resolves each marked record's texture or sampler from guest memory, and the program reads it from a later draw on (the first read of a record returns zeros). `0` plans those tables as before (bindless image tables, at most 256 candidates, off-class candidates read null). | | `SHARPEMU_METAL_SHADER_CALLS` | on | `0` turns off linked shader calls, as before they were ported to Metal. By default a program that calls functions with `S_SWAPPC_B64` is compiled with its callees linked in: the call compares the caller's address and argument with the dispatch's call targets and runs the matching callee. With the bindless heap on, a program can also be linked with run-time call records: the host writes the table of each dispatch's records and resolves the images and samplers they hold into the heap, and a call to a callee the program lacks is marked so the program cache links it later. A call that no record names ends its wave and logs `[UNLINKED_CALL]`. `0` compiles the caller alone, which skips the call. The callee lists are kept in `pipeline_cache/<title>/metal-v2/linked`. `SHARPEMU_CALL_RECORD_SPANS=0` reads each record field by field instead of once per record (same result); `SHARPEMU_RUNTIME_CALL_RECORDS=0` links one copy of a callee per record instead of using run-time records. | +| `SHARPEMU_METAL_SHARED_CALL_BODIES` | on | `0` inlines one copy of a callee per record, as the call linker emits it. By default the copies of one callee at one call site of a program linked per record (`SHARPEMU_RUNTIME_CALL_RECORDS=0`, or a caller the program cache links per record) share one body: each record's entry stores its slot and branches into the last copy, and an instruction whose records bind different resources is emitted once per record under a test of the slot. The MSL source and the Metal compile then grow with the records' tests instead of records x callee size (64 records of a 34-instruction callee: 207 KB / 65 ms instead of 1282 KB / 206 ms). Same results either way. | | `SHARPEMU_RUNTIME_IMAGE_SWIZZLE` | on | `0` bakes each storage image's destination select into the translated program, one program per select. By default a store reads the image's channel map from shader data, which the host writes from the bound descriptor. | | `SHARPEMU_METAL_FORMAT_LOAD_COMPONENT_BOUNDS` | on | `0` restores the old bound of a formatted buffer load whose format is fixed at translation: the whole element had to fit below the buffer's size. By default each selected component is checked at its own address, wrapping past 2^32 as on the hardware, so a component that wraps to the buffer's start is read, and the load reads its constants only when a selected component is out of range. An element that fits whole still takes one compare. Loads whose format is read at run time always check per component. | | `SHARPEMU_GRAPHICS_PARTIAL_LANES` | off | `1` makes pixel-shader lane reads (DPP, DPP8, PERMLANE16, V_READLANE) of a lane the fragment simdgroup never launched read the reading lane's own value, and treats such a lane as active when the guest EXEC mask has its bit. Off by default, as upstream: it changes every pixel shader with cross-lane operations. | diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs index b80fa9a5d..a69a56fa5 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs @@ -337,6 +337,11 @@ public sealed record Gen5MslCodegenOptions( /// keeps the cases.</summary> public bool IndexedImageCandidates { get; init; } = true; + /// <summary>The copies of one callee that a program linked per record holds at a call site share one body, entered + /// from each record's entry with the record's slot (Gen5MslTranslator.SharedCalls.cs), instead of one inlined copy + /// per record. SHARPEMU_METAL_SHARED_CALL_BODIES=0 inlines every copy.</summary> + public bool SharedCallBodies { get; init; } = true; + public static Gen5MslCodegenOptions FromEnvironment { get; } = new( StructuredControlFlow: Environment.GetEnvironmentVariable("SHARPEMU_MSL_STRUCTURED") != "0", RegisterAllocation: Environment.GetEnvironmentVariable("SHARPEMU_MSL_REGALLOC") != "0", @@ -397,6 +402,7 @@ public sealed record Gen5MslCodegenOptions( GroupUniformBarriers = Environment.GetEnvironmentVariable("SHARPEMU_MSL_GROUP_BARRIERS") != "0", HalfLocalWaveLoops = Environment.GetEnvironmentVariable("SHARPEMU_MSL_HALF_LOOPS") != "0", IndexedImageCandidates = Environment.GetEnvironmentVariable("SHARPEMU_MSL_INDEXED_CANDIDATES") != "0", + SharedCallBodies = Environment.GetEnvironmentVariable("SHARPEMU_METAL_SHARED_CALL_BODIES") != "0", MeshDeviceLdsThresholdBytes = uint.TryParse( Environment.GetEnvironmentVariable("SHARPEMU_MSL_MESH_LDS_THRESHOLD"), out var threshold) ? Math.Min(threshold, 16384u) : 12288u, diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.BindlessHeap.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.BindlessHeap.cs index 59f9967ef..17eecc4a3 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.BindlessHeap.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.BindlessHeap.cs @@ -189,7 +189,7 @@ private bool IsHeapImageAccess(Gen5ShaderInstruction instruction, out HeapRecord { use = default; slot = -1; - if (!_request.Memory.TryGetIndex(instruction.Pc, 0, out var memoryIndex) || + if (!_request.Memory.TryGetIndex(MemoryPc(instruction.Pc), 0, out var memoryIndex) || !_request.HeapImageByMemoryIndex.TryGetValue(memoryIndex, out use)) { return false; diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs index 83b8fcf7b..f6ca98926 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Resources.cs @@ -99,12 +99,18 @@ public static bool TryCompileProgram( } options ??= Gen5MslCodegenOptions.FromEnvironment; - var context = new CompilationContext(request, options); + SharedCallBodies? sharedCalls = null; + if (options.SharedCallBodies) + { + request = ShareLinkedCallBodies(request, out sharedCalls); + } + + var context = new CompilationContext(request, options, sharedCalls); var compiled = context.TryCompile(out shader, out error); if (!compiled && context.HalfLocalLoopExchanged) { options = options with { HalfLocalWaveLoops = false }; - context = new CompilationContext(request, options); + context = new CompilationContext(request, options, sharedCalls); compiled = context.TryCompile(out shader, out error); } @@ -116,7 +122,7 @@ public static bool TryCompileProgram( } options = options with { HalfLocalExecBranches = false }; - context = new CompilationContext(request, options); + context = new CompilationContext(request, options, sharedCalls); compiled = context.TryCompile(out shader, out error); } @@ -130,7 +136,7 @@ public static bool TryCompileProgram( } Interlocked.Increment(ref _execRunsRefused); - if (!new CompilationContext(request, options with { ExecRuns = false }).TryCompile(out shader, out error)) + if (!new CompilationContext(request, options with { ExecRuns = false }, sharedCalls).TryCompile(out shader, out error)) { return false; } @@ -227,11 +233,13 @@ private readonly record struct MslImageClass( } private readonly Gen5MslCodegenOptions _options; + private readonly SharedCallBodies? _sharedCalls; - public CompilationContext(ShaderCompileRequest request, Gen5MslCodegenOptions options) + public CompilationContext(ShaderCompileRequest request, Gen5MslCodegenOptions options, SharedCallBodies? sharedCalls = null) { _request = request; _options = options; + _sharedCalls = sharedCalls; _argumentLayout = Gen5MslArgumentLayout.Build(request.Bindings); // An NGG primitive shader that exchanges data through LDS, synchronizes or asks // for export space is the merged ES/GS workgroup stage, which only a mesh @@ -627,6 +635,12 @@ private void EmitLayoutInitialState(StringBuilder source) // No row until a run-time entry finds one: a record read before it takes the null element. source.AppendLine($" uint {CallRecordRowName} = 0xFFFFFFFFu;"); } + + if (_sharedCalls is not null) + { + // The slot of the record whose entry ran last, which a shared body's record variants select by. + source.AppendLine($" uint {CallSlotName} = 0u;"); + } } // One dword of this stage's block: from push data, or the shader-data buffer when spilled. @@ -1433,7 +1447,7 @@ bool TryScalarBufferRun(int component, out (int First, int Count) run) uint? binding = null; for (var index = first; index < first + count; index++) { - if (!request.Memory.TryGetIndex(instruction.Pc, (uint)index, out var memory)) + if (!request.Memory.TryGetIndex(MemoryPc(instruction.Pc), (uint)index, out var memory)) { return false; } @@ -1461,7 +1475,7 @@ bool TryScalarBufferRun(int component, out (int First, int Count) run) return false; } - if (!request.Memory.TryGetIndex(instruction.Pc, (uint)component, out var memoryIndex)) + if (!request.Memory.TryGetIndex(MemoryPc(instruction.Pc), (uint)component, out var memoryIndex)) { error = $"scalar load component {component} has no memory record"; return false; @@ -1616,7 +1630,7 @@ private bool TryEmitLayoutGlobalMemory(Gen5ShaderInstruction instruction, Gen5Gl } var request = _request; - if (!request.Memory.TryGetIndex(instruction.Pc, 0, out var memoryIndex)) + if (!request.Memory.TryGetIndex(MemoryPc(instruction.Pc), 0, out var memoryIndex)) { error = "global access has no memory record"; return false; @@ -2161,7 +2175,7 @@ private bool TryResolveLayoutBuffer(uint pc, out int bindingIndex, out BufferRes bindingIndex = -1; resource = null!; var request = _request; - if (!request.Memory.TryGetIndex(pc, 0, out var memoryIndex)) + if (!request.Memory.TryGetIndex(MemoryPc(pc), 0, out var memoryIndex)) { return false; } @@ -2187,7 +2201,7 @@ private bool TryGetImageElementCases(Gen5ShaderInstruction instruction, Gen5Imag elements = []; error = string.Empty; var request = _request; - if (!request.Memory.TryGetIndex(instruction.Pc, 0, out var memoryIndex)) + if (!request.Memory.TryGetIndex(MemoryPc(instruction.Pc), 0, out var memoryIndex)) { return false; } @@ -2277,7 +2291,7 @@ private bool TryIndexImageCandidates(Gen5ShaderInstruction instruction, string s { var request = _request; if (!_options.IndexedImageCandidates || elements.Count < IndexedCandidateMinimum || - !request.Memory.TryGetIndex(instruction.Pc, 0, out var memoryIndex) || + !request.Memory.TryGetIndex(MemoryPc(instruction.Pc), 0, out var memoryIndex) || !request.IndirectRootByMemoryIndex.ContainsKey(memoryIndex)) { return false; @@ -2379,7 +2393,7 @@ private bool TryResolveLayoutImage( mipLevel = "0u"; var request = _request; var info = request.Resources.Info; - if (!request.Memory.TryGetIndex(instruction.Pc, 0, out var memoryIndex)) + if (!request.Memory.TryGetIndex(MemoryPc(instruction.Pc), 0, out var memoryIndex)) { error = "image access has no memory record"; return false; diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.ShaderCalls.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.ShaderCalls.cs index a47a23f40..aa845522a 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.ShaderCalls.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.ShaderCalls.cs @@ -20,9 +20,8 @@ namespace SharpEmu.ShaderCompiler.Metal; // images and samplers the copy reads through the record's argument are the heap elements the host resolved for that row. // A call whose callee the program lacks marks it (DescriptorBindingKind.CallMarks) and returns at once. // -// The SPIR-V translator also merges the copies of a callee into one body and outlines compute bodies into functions -// (Gen5SpirvTranslator.SharedCalls.cs) to bound its driver's compile time; those rewrites keep the linker's run-time -// behaviour, and this translator emits the linker's form as it is. +// As the SPIR-V translator does (Gen5SpirvTranslator.SharedCalls.cs), the records of one callee at one site share one +// body (Gen5MslTranslator.SharedCalls.cs); its outlined functions that serve several sites are not ported. public static partial class Gen5MslTranslator { private sealed partial class CompilationContext @@ -228,7 +227,7 @@ private string CallRecordElement(int field) private bool IsCallRecordImageAccess(Gen5ShaderInstruction instruction, out CallRecordFieldUse use) { use = default; - return _request.Memory.TryGetIndex(instruction.Pc, 0, out var memoryIndex) && + return _request.Memory.TryGetIndex(MemoryPc(instruction.Pc), 0, out var memoryIndex) && _request.CallRecordImageByMemoryIndex.TryGetValue(memoryIndex, out use) && use.Slot >= 0; } diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.SharedCalls.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.SharedCalls.cs new file mode 100644 index 000000000..b17360c55 --- /dev/null +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.SharedCalls.cs @@ -0,0 +1,326 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Globalization; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.ShaderCompiler.Metal; + +// Shared call bodies, the MSL form of upstream's ShareLinkedCallBodies (Gen5SpirvTranslator.SharedCalls.cs). A program +// linked per record (Gen5ShaderCallLinker without run-time records) holds one copy of a callee for each record of a call +// site's table: the copies are the same instructions and differ only in the record's argument, and so in the descriptors +// the body loads through it (the plan's memory records at each copy's pcs). Inlined, the MSL source and the Metal compile +// grow with records x callee size. Here the module keeps the last copy of each callee at each site: every record's test +// and entry stay, the entry stores the record's slot (sharpemu_call_slot), and the body of every other copy becomes a +// branch into the kept one, forward, so the program gains no back edge. An instruction of the kept body whose memory +// records differ between the records is emitted once for each distinct set, selected by the slot, with the memory +// records of that record's copy; every other instruction is emitted once. The resource plan still holds every copy, so +// bindings do not change. +// +// What is not ported: upstream's site lookup (one test per callee instead of per record) and its DontInline functions +// that let one body serve several sites (compute, wave32). MSL has no goto and no lambdas, and a translated body reads +// and writes the kernel's own locals (the registers this program touches, EXEC, VCC, SCC, the lane and LDS state), so a +// body outlined into a device function would take that whole state by reference; Metal inlines device functions anyway. +// A site's records share one body, which is what grows with the table. +// +// SHARPEMU_METAL_SHARED_CALL_BODIES=0 (Gen5MslCodegenOptions.SharedCallBodies) emits every copy inline, as before. +public static partial class Gen5MslTranslator +{ + internal sealed class SharedCallBodies + { + // Each sharing record's entry pc and its slot in its body's records. + public required Dictionary<uint, uint> SlotByEntryPc { get; init; } + + // The kept copy of each shared body: its pc range and every record's body start, in slot order. + public required List<(uint Start, uint End, uint[] Bases)> Bodies { get; init; } + + // The pc of an instruction of a kept body in each record's copy, by slot. + public bool TryGetRecordPcs(uint pc, out uint[] pcs) + { + var low = 0; + var high = Bodies.Count - 1; + while (low <= high) + { + var middle = low + ((high - low) >> 1); + var body = Bodies[middle]; + if (pc < body.Start) + { + high = middle - 1; + } + else if (pc >= body.End) + { + low = middle + 1; + } + else + { + pcs = new uint[body.Bases.Length]; + for (var slot = 0; slot < pcs.Length; slot++) + { + pcs[slot] = body.Bases[slot] + (pc - body.Start); + } + + return true; + } + } + + pcs = []; + return false; + } + } + + // The request with each site's copies of one callee sharing the last copy's body, or the request itself when no two + // copies can share. + internal static ShaderCompileRequest ShareLinkedCallBodies(ShaderCompileRequest request, out SharedCallBodies? shared) + { + shared = null; + var instructions = request.Program.Instructions; + if (!instructions.Any(static instruction => instruction.Control is ShaderCallEntryControl)) + { + return request; + } + + // A body runs from its entry to the next record's test or to the site's fault. + var bodies = new List<(int Entry, int Start, int End, int Site, ulong Target)>(); + var site = 0; + ulong target = 0; + for (var index = 0; index < instructions.Count; index++) + { + var control = instructions[index].Control; + if (control is ShaderCallMatchControl match) + { + target = match.Address; + } + else if (control is ShaderCallFaultControl) + { + site++; + } + else if (control is ShaderCallEntryControl) + { + var end = index + 1; + while (end < instructions.Count && instructions[end].Control is not (ShaderCallMatchControl or ShaderCallFaultControl)) + { + end++; + } + + if (end < instructions.Count && end > index + 1) + { + bodies.Add((index, index + 1, end, site, target)); + } + + index = end - 1; + } + } + + var slotByEntryPc = new Dictionary<uint, uint>(); + var shares = new List<(uint Start, uint End, uint[] Bases)>(); + var replaced = new Dictionary<int, (int End, uint Target)>(); + foreach (var group in bodies.GroupBy(static body => (body.Site, body.Target))) + { + var kept = group.Last(); + var members = group.Where(member => member == kept || SameBody(instructions, kept.Start, kept.End, member.Start, member.End)).ToList(); + if (members.Count < 2) + { + continue; + } + + var start = instructions[kept.Start].Pc; + for (var slot = 0; slot < members.Count; slot++) + { + var member = members[slot]; + slotByEntryPc.Add(instructions[member.Entry].Pc, (uint)slot); + if (member != kept) + { + replaced.Add(member.Start, (member.End, start)); + } + } + + shares.Add((start, instructions[kept.End].Pc, members.Select(member => instructions[member.Start].Pc).ToArray())); + } + + if (shares.Count == 0) + { + return request; + } + + var program = new List<Gen5ShaderInstruction>(instructions.Count); + for (var index = 0; index < instructions.Count; index++) + { + if (replaced.TryGetValue(index, out var copy)) + { + program.Add(new Gen5ShaderInstruction(instructions[index].Pc, Gen5ShaderEncoding.Sopp, "SBranch", [0xBF820000], [], [], + new ShaderLinkedBranchControl(copy.Target))); + index = copy.End - 1; + continue; + } + + program.Add(instructions[index]); + } + + shares.Sort(static (left, right) => left.Start.CompareTo(right.Start)); + shared = new SharedCallBodies { SlotByEntryPc = slotByEntryPc, Bodies = shares }; + return request.WithProgram(request.Program with { Instructions = program }); + } + + // The same instructions at the same offsets; a branch inside the body keeps its offset, one leaving it its target. + private static bool SameBody(IReadOnlyList<Gen5ShaderInstruction> instructions, int firstStart, int firstEnd, int copyStart, int copyEnd) + { + if (firstEnd - firstStart != copyEnd - copyStart) + { + return false; + } + + var firstPc = instructions[firstStart].Pc; + var firstEndPc = instructions[firstEnd].Pc; + var copyPc = instructions[copyStart].Pc; + for (var offset = 0; offset < firstEnd - firstStart; offset++) + { + var left = instructions[firstStart + offset]; + var right = instructions[copyStart + offset]; + if (left.Pc - firstPc != right.Pc - copyPc || left.Opcode != right.Opcode || left.Encoding != right.Encoding || + left.AddressOffset != right.AddressOffset || !left.Words.SequenceEqual(right.Words) || + !left.Sources.SequenceEqual(right.Sources) || !left.Destinations.SequenceEqual(right.Destinations)) + { + return false; + } + + if (left.Control is ShaderLinkedBranchControl leftBranch && right.Control is ShaderLinkedBranchControl rightBranch) + { + var inside = leftBranch.TargetPc >= firstPc && leftBranch.TargetPc < firstEndPc; + if (inside + ? rightBranch.TargetPc - copyPc != leftBranch.TargetPc - firstPc + : rightBranch.TargetPc != leftBranch.TargetPc) + { + return false; + } + } + else if (!Equals(left.Control, right.Control)) + { + return false; + } + } + + return true; + } + + private sealed partial class CompilationContext + { + private const string CallSlotName = "sharpemu_call_slot"; + + // While a record's variant of a shared body's instruction is emitted: the pc of that instruction in the record's + // copy, whose memory records it reads (MemoryPc). + private uint? _recordMemoryPc; + + // While a shared body's instruction is emitted for its records: the emission does not divide it again. + private bool _emittingCallRecord; + + // A shared body's instruction that reads memory records, emitted for its records (TryEmitSharedCallInstruction). + private bool IsSharedCallMemoryInstruction(Gen5ShaderInstruction instruction, out uint[] pcs) + { + pcs = []; + return _sharedCalls is { } shared && !_emittingCallRecord && _request.Memory.TryGetIndex(instruction.Pc, 0, out _) && + shared.TryGetRecordPcs(instruction.Pc, out pcs); + } + + // The pc whose memory records the instruction at pc reads: its record's copy while a record variant is emitted. + private uint MemoryPc(uint pc) => _recordMemoryPc ?? pc; + + private void EmitCallSlot(Gen5ShaderInstruction entry) + { + if (_sharedCalls is { } shared && shared.SlotByEntryPc.TryGetValue(entry.Pc, out var slot)) + { + Line($"{CallSlotName} = {slot.ToString(CultureInfo.InvariantCulture)}u;"); + } + } + + // An instruction of a shared body that reads memory records: once when every record reads the same ones, else once + // per distinct set, under a test of the slot, with the memory records of the set's first record. + private bool TryEmitSharedCallInstruction(Gen5ShaderInstruction instruction, uint[] pcs, out string error) + { + error = string.Empty; + var signatures = pcs.Select(CallRecordSignature).ToArray(); + _emittingCallRecord = true; + try + { + return signatures.All(signature => signature == signatures[0]) + ? TryEmitInstruction(instruction, out error) + : TryEmitRecordVariants(instruction, pcs, signatures, out error); + } + finally + { + _emittingCallRecord = false; + } + } + + private bool TryEmitRecordVariants(Gen5ShaderInstruction instruction, uint[] pcs, string[] signatures, out string error) + { + error = string.Empty; + + var first = true; + foreach (var group in Enumerable.Range(0, pcs.Length).GroupBy(slot => signatures[slot])) + { + var condition = string.Join(" || ", group.Select(slot => $"{CallSlotName} == {slot.ToString(CultureInfo.InvariantCulture)}u")); + Line($"{(first ? "" : "else ")}if ({condition})"); + Line("{"); + _indent++; + _recordMemoryPc = pcs[group.First()]; + try + { + if (!TryEmitInstruction(instruction, out error)) + { + return false; + } + } + finally + { + _recordMemoryPc = null; + _indent--; + } + + Line("}"); + first = false; + } + + return true; + } + + // What decides the code of a memory instruction at pc: its memory records and the resources they bind (as + // upstream's CallRecordSignature). Two records with the same signature emit the same code. + private string CallRecordSignature(uint pc) + { + var request = _request; + var text = new System.Text.StringBuilder(); + for (uint component = 0; request.Memory.TryGetIndex(pc, component, out var index); component++) + { + var entry = request.Memory[index]; + text.Append(entry.Kind).Append(',').Append(entry.Access).Append(',').Append(entry.Offset).Append(',').Append(entry.Dmask) + .Append(',').Append(entry.DataDwords).Append(',').Append(entry.DataBits).Append(',').Append(entry.ComponentCount) + .Append(',').Append(entry.DataFormat).Append(',').Append(entry.NumberFormat).Append(',').Append(entry.ImageSampleFlags) + .Append(',').Append(entry.ImageDimension).Append(',').Append(entry.ImageClass).Append(',').Append(entry.NeedsSampler) + .Append(',').Append(entry.AddressIsFull).Append(',').Append(entry.DataSigned).Append(',').Append(entry.Typed) + .Append(',').Append(entry.Formatted).Append(',').Append(entry.ImageHasMip).Append(',').Append(entry.ImageR128) + .Append(',').Append(entry.Glc).Append(',').Append(entry.Slc).Append(',').Append(entry.IndexEnabled) + .Append(',').Append(entry.OffsetEnabled).Append(',').Append(entry.PlanningOnly).Append(',').Append(entry.DeviceDescriptor) + .Append(',').Append(entry.AddressSpace).Append(',').Append(entry.BufferDescriptor?.Provenance) + .Append(',').Append(entry.BufferDescriptor?.StaticResource) + // The resource itself: this translator binds each buffer and image by its own index. + .Append(",res=").Append(entry.Resource); + var sampler = request.Resources.SamplerByMemoryIndex.TryGetValue(index, out var mappedSampler) ? mappedSampler : entry.Sampler; + text.Append(",smp=").Append(sampler); + if (request.CallRecordImageByMemoryIndex.TryGetValue(index, out var recordImage)) + text.Append(",record=").Append(recordImage.Field).Append(',').Append(recordImage.Slot); + if (request.CallRecordSamplerByMemoryIndex.TryGetValue(index, out var recordSampler)) + text.Append(",recordsmp=").Append(recordSampler.Field).Append(',').Append(recordSampler.Slot); + if (request.FlattenedSlotByMemoryIndex.TryGetValue(index, out var flattened)) text.Append(",flat=").Append(flattened); + // A key read stores its value for a later image access of the same record, so each record keeps its own. + if (request.IndirectKeyMemoryIndices.Contains(index)) text.Append(",key=").Append(index); + if (request.IndirectOffsetKeyMemoryIndices.Contains(index)) text.Append(",offsetkey=").Append(index); + if (request.IndirectRootByMemoryIndex.TryGetValue(index, out var root)) text.Append(",root=").Append(root); + if (request.BufferCandidateTableByMemoryIndex.TryGetValue(index, out var table)) text.Append(",table=").Append(table); + if (request.WrittenRangeSlotByMemoryIndex.TryGetValue(index, out var written)) text.Append(",written=").Append(written); + text.Append(';'); + } + + return text.ToString(); + } + } +} diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs index 4692de4c6..6802d5297 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs @@ -2254,10 +2254,16 @@ private bool TryEmitInstruction( out string error) { error = string.Empty; + if (IsSharedCallMemoryInstruction(instruction, out var recordPcs)) + { + return TryEmitSharedCallInstruction(instruction, recordPcs, out error); + } + BeginInstruction(instruction); if (instruction.Control is ShaderCallEntryControl callEntry) { EmitShaderCallEntry(callEntry); + EmitCallSlot(instruction); return true; } @@ -2615,7 +2621,7 @@ private bool TryEmitBufferMemoryAccess( return TryEmitVertexInputFetch(control, vertexInput, out error); } - if (_request.Memory.TryGetIndex(instruction.Pc, 0, out var accessMemoryIndex)) + if (_request.Memory.TryGetIndex(MemoryPc(instruction.Pc), 0, out var accessMemoryIndex)) { var accessMemory = _request.Memory[accessMemoryIndex]; if (accessMemory.PlanningOnly) diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslLinkedCallTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslLinkedCallTests.cs index 3ee46fefd..049a4adb3 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslLinkedCallTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslLinkedCallTests.cs @@ -104,9 +104,9 @@ private static ShaderCompileRequest Request(Gen5ShaderProgram program, bool bind return new ShaderCompileRequest(plan, resources, layout) { WaveSize = 32, LocalSizeX = 32 }; } - private static Gen5MslShader Compile(ShaderCompileRequest request) + private static Gen5MslShader Compile(ShaderCompileRequest request, Gen5MslCodegenOptions? options = null) { - Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error), error); + Assert.True(Gen5MslTranslator.TryCompileProgram(request, out var shader, out var error, options), error); return shader; } @@ -118,13 +118,20 @@ private sealed class Run private readonly nint _library; private byte[] _result = []; - public Run(Gen5ShaderProgram program, bool bindlessHeap = false, bool callRecords = false, bool callMarks = false) + public Run(Gen5ShaderProgram program, bool bindlessHeap = false, bool callRecords = false, bool callMarks = false, + Gen5MslCodegenOptions? options = null) { Request = MslLinkedCallTests.Request(program, bindlessHeap, callRecords, callMarks); - _shader = Compile(Request); + _shader = Compile(Request, options); + var started = System.Diagnostics.Stopwatch.GetTimestamp(); Assert.True(MetalNative.TryCompileLibrary(_shader.Source, out _library, out var error), $"{error}\n{_shader.Source}"); + LibraryMilliseconds = System.Diagnostics.Stopwatch.GetElapsedTime(started).TotalMilliseconds; } + public string Source => _shader.Source; + + public double LibraryMilliseconds { get; } + public ShaderCompileRequest Request { get; } public uint[] Faults { get; private set; } = []; @@ -275,6 +282,98 @@ Gen5ShaderProgram Function(uint add) => Program( else Assert.Equal(FaultRecord(run.Request.Hash, 16, address, 0), run.Faults); } + // The copies of one callee that a per-record link holds at a site share one body (Gen5MslTranslator.SharedCalls.cs): + // each record's entry stores its slot and branches into the last copy, so the module holds one body however many + // records the table has. Every record still runs with its own argument, a store inside the body (a memory instruction + // whose records bind the same buffer) is emitted once, the caller continues with the body's registers, an unknown + // argument still faults, and the inlined form + // (SharedCallBodies off, SHARPEMU_METAL_SHARED_CALL_BODIES=0) computes the same words. The output lists the MSL size and + // the Metal library compile time of both forms. + [Theory] + [InlineData(1)] + [InlineData(8)] + [InlineData(64)] + [InlineData(256)] + public void RecordsOfOneCalleeShareOneBody(int records) + { + // The caller adds 5 to v2 after the call and stores v[1:2]; the body stores v1 = argument + 3 * 31 and v2 = 7 itself + // first, so both stores read the body's result. + Gen5ShaderProgram Caller(uint argument) => Program(MoveScalar(0, 14, 0x2000), MoveScalar(4, 15, 0), + MoveScalar(8, 16, argument), MoveScalar(12, 17, 0), Vop1(16, "VMovB32", 2, Operand(0)), + Sop1(20, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + Vop2(24, "VAddU32", 2, Operand(5), Gen5Operand.Vector(2)), + BufferAccess(28, "BufferStoreDwordx2", ResultRegister, dwords: 2, vectorData: 1), EndProgram(36)); + var function = Program([ + Vop1(0, "VMovB32", 1, Gen5Operand.Scalar(16)), + .. Enumerable.Range(0, 31).Select(index => Vop2(4 + (uint)index * 4, "VAddU32", 1, Operand(3), Gen5Operand.Vector(1))), + Vop1(128, "VMovB32", 2, Operand(7)), + BufferAccess(132, "BufferStoreDwordx2", ResultRegister, dwords: 2, vectorData: 1), + Sop1(140, "SSetpcB64", 0, Gen5Operand.Scalar(14))]); + ShaderCallTarget[] Targets() => + Enumerable.Range(0, records).Select(index => new ShaderCallTarget(0x2000, 10 + (ulong)index, function)).ToArray(); + + var shared = Compile(Request(Gen5ShaderCallLinker.Link(Caller(10), [new(20, 14, 16, 14, 24, Targets())])), + Gen5MslCodegenOptions.FromEnvironment with { SharedCallBodies = true }).Source; + var inline = Compile(Request(Gen5ShaderCallLinker.Link(Caller(10), [new(20, 14, 16, 14, 24, Targets())])), + Gen5MslCodegenOptions.FromEnvironment with { SharedCallBodies = false }).Source; + if (records > 1) + { + Assert.Contains("sharpemu_call_slot", shared, StringComparison.Ordinal); + Assert.True(shared.Length < inline.Length, $"shared {shared.Length} bytes, inline {inline.Length}"); + } + + if (SkipWithoutMetalDevice()) return; + var arguments = new[] { 10u, 10u + (uint)records / 2, 10u + (uint)records - 1, 10u + (uint)records }.Distinct(); + double sharedMs = 0, inlineMs = 0; + foreach (var argument in arguments) + { + var linked = Gen5ShaderCallLinker.Link(Caller(argument), [new(20, 14, 16, 14, 24, Targets())]); + var words = new List<(uint, uint, uint[])>(); + foreach (var sharing in new[] { true, false }) + { + var run = new Run(linked, options: Gen5MslCodegenOptions.FromEnvironment with { SharedCallBodies = sharing }); + if (sharing) sharedMs = run.LibraryMilliseconds; + else inlineMs = run.LibraryMilliseconds; + run.Dispatch(); + words.Add((run.Word(0), run.Word(4), run.Faults)); + } + + var known = argument < 10 + (uint)records; + Assert.Equal(known ? argument + 93 : 0u, words[0].Item1); + Assert.Equal(known ? 12u : 0u, words[0].Item2); + if (known) Assert.All(words[0].Item3, word => Assert.Equal(0u, word)); + else Assert.Equal(FaultRecord(Hash, 20, 0x2000, 0), words[0].Item3); + Assert.Equal(words[1].Item1, words[0].Item1); + Assert.Equal(words[1].Item2, words[0].Item2); + Assert.Equal(words[1].Item3, words[0].Item3); + } + + output.WriteLine($"SHARED_BODIES records={records} shared_msl_bytes={shared.Length} shared_library_ms={sharedMs:F0} " + + $"inline_msl_bytes={inline.Length} inline_library_ms={inlineMs:F0}"); + } + + // Records whose copies load a different buffer through their own argument: the shared body emits the load once per + // record under a test of the slot, each with its own copy's memory records, and the library compiles. + [Fact] + public void ASharedBodyEmitsAMemoryInstructionPerRecordWhoseResourcesDiffer() + { + var caller = Program(MoveScalar(0, 14, 0x2000), MoveScalar(4, 15, 0), MoveScalar(8, 16, 0x100000), MoveScalar(12, 17, 0), + Sop1(16, "SSwappcB64", 14, Gen5Operand.Scalar(14)), + BufferAccess(20, "BufferStoreDword", ResultRegister, vectorData: 1), EndProgram(28)); + // s[20:23] = the V# at the record's argument; v1 = the buffer's first dword. + var function = Program(ScalarLoad(0, 16, 20, 4), BufferAccess(8, "BufferLoadDword", 20, vectorData: 1), + Sop1(16, "SSetpcB64", 0, Gen5Operand.Scalar(14))); + var linked = Gen5ShaderCallLinker.Link(caller, [new(16, 14, 16, 14, 20, + [new(0x2000, 0x100000, function), new(0x2000, 0x200000, function), new(0x2000, 0x300000, function)])]); + var request = Request(linked); + var shared = Compile(request, Gen5MslCodegenOptions.FromEnvironment with { SharedCallBodies = true }).Source; + var inline = Compile(request, Gen5MslCodegenOptions.FromEnvironment with { SharedCallBodies = false }).Source; + Assert.Contains("sharpemu_call_slot == 2u", shared, StringComparison.Ordinal); + Assert.DoesNotContain("sharpemu_call_slot", inline, StringComparison.Ordinal); + if (SkipWithoutMetalDevice()) return; + Assert.True(MetalNative.TryCompileLibrary(shared, out _, out var error), error); + } + // A function reads its program address with S_GETPC_B64: the address the dispatch pushes for it (a function the game // placed elsewhere than at link time is still found and reads where it now is), and the return address follows the // shader base. From 2b329c842617e78fd53d17a2fe8ef16772f588ba Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 04:34:51 +0000 Subject: [PATCH 118/134] [Metal] Prewarm linked records after every other compute, never held, in upstream's linked lane order Upstream compiles the linked permutations earlier sessions recorded on a background lane the game does not wait for (VulkanVideoPresenter. StartLinkedPrewarm, SHARPEMU_PREWARM_LINKED=background by default), in ShaderPrewarmQueue.LinkedLaneOrder: every caller's first record before any second, a caller's first being the library that links its kept callees (ShaderCallUnionStore, what a session links first), slow callers first within a round. Metal queued linked records with the ordinary computes in recorded order, so a whole-module linked compile could hold the guest at boot (first frame) and delay the computes behind it. MetalShaderPrewarm.HoldFirstLinkedLast: HoldFirst over the plain records, then the linked ones, not held, in that order (new public LinkedPrewarmOrder in Libs, a contract over the internal lane order and union store, since Libs gives the Metal backend public contracts only). Workers stay shared; Metal has no per-caller linked cache file, so the per-caller one-at-a-time gate of upstream's queue is not needed. Tests: MetalShaderPrewarmPendingTests.LinkedRecordsAreNeverHeldForAndCompile LastInTheirLanesOrder (with and without a first-frame list) and ShaderCallUnionStoreTests.TheLinkedPrewarmOrderPutsEachCallersKeptLibraryFirst. --- .../Gpu/Pipelines/LinkedPrewarmOrder.cs | 33 +++++++++++++++++++ .../V2/MetalShaderPrewarm.cs | 32 +++++++++++++++++- .../MetalShaderPrewarmPendingTests.cs | 29 ++++++++++++++++ .../Pipelines/ShaderCallUnionStoreTests.cs | 31 +++++++++++++++++ 4 files changed, 124 insertions(+), 1 deletion(-) create mode 100644 src/SharpEmu.Libs/Gpu/Pipelines/LinkedPrewarmOrder.cs diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/LinkedPrewarmOrder.cs b/src/SharpEmu.Libs/Gpu/Pipelines/LinkedPrewarmOrder.cs new file mode 100644 index 000000000..9a6deb575 --- /dev/null +++ b/src/SharpEmu.Libs/Gpu/Pipelines/LinkedPrewarmOrder.cs @@ -0,0 +1,33 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Libs.VideoOut; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.Libs.Gpu.Pipelines; + +// The order in which the boot prewarm compiles the linked records of earlier sessions (ComputePrewarmRecord with linked +// callees), as a public contract for a backend outside this assembly (the Metal backend; Libs gives extracted backends +// public contracts only). It is upstream's background lane order (ShaderPrewarmQueue.LinkedLaneOrder, used by +// VulkanVideoPresenter.StartLinkedPrewarm): every caller's first record before any caller's second; a caller's first is +// the record whose library links the callees an earlier session kept for it (ShaderCallUnionStore, the library a session +// links first), else its oldest, and its others follow newest first; within a round, callers a session saw compile for +// minutes (ShaderPrewarmList.IsSlowLinkedCompile) go first, then the order in which callers were first recorded. +public static class LinkedPrewarmOrder +{ + // Whether the record is a linked permutation (its program holds callees). + public static bool IsLinked(ComputePrewarmRecord record) => record.Linked is not null; + + // The linked records in the lane's order. linkedDirectory: the host's LinkedProgramCacheDirectory (null keeps none). + public static T[] Order<T>(IReadOnlyList<T> records, Func<T, ComputePrewarmRecord> record, ShaderPrewarmList list, + string? linkedDirectory) => + Order(records, item => record(item).Hash, item => record(item).Linked, list.IsSlowLinkedCompile, linkedDirectory); + + internal static T[] Order<T>(IReadOnlyList<T> records, Func<T, ulong> caller, Func<T, LinkedShaderPrewarm?> linked, + Func<ulong, bool> slow, string? linkedDirectory) + { + var kept = ShaderCallUnionStore.Open(linkedDirectory); + return ShaderPrewarmQueue<T>.LinkedLaneOrder(records, caller, slow, + item => linked(item) is { } library && kept.KeepsCalleesOf(ShaderStage.Compute, caller(item), library)); + } +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs index 372399c10..e949d6c9d 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs @@ -370,7 +370,12 @@ private static bool StartCore(nint device) return false; } - var ordered = HoldFirst(pending, HoldsForEveryCompute ? null : list.ReadFirstFrameComputes(), out var heldComputes); + var linkedDirectory = Path.Combine(directory, "linked"); + // The hold-until-done and precompile modes hold the guest for every record, linked ones too (upstream's + // SHARPEMU_PREWARM_LINKED=all): their phase counts every record as held. + var ordered = HoldFirstLinkedLast(pending, HoldsForEveryCompute ? null : list.ReadFirstFrameComputes(), + HoldsForEveryCompute ? static _ => false : LinkedPrewarmOrder.IsLinked, + linked => LinkedPrewarmOrder.Order(linked, static item => item.Record, list, linkedDirectory), out var heldComputes); var orderedGraphics = HoldFirstGraphics( graphics, HoldsForEveryCompute ? null : _graphics?.ReadFirstFrame(), out var heldGraphics); var held = heldComputes + heldGraphics; @@ -677,6 +682,31 @@ private static bool CompletePrecompile() /// held it for all of them, 126 s at the splash screen (run 20261017-075343-ds-base-boot), /// while the rest can compile behind the logos and the intro. /// </summary> + /// <summary> + /// HoldFirst over the records without linked callees, then the linked records (ComputePrewarmRecord with callees), which + /// the guest is never held for, in upstream's linked lane order (LinkedPrewarmOrder, as + /// VulkanVideoPresenter.StartLinkedPrewarm compiles them on its background lane): a linked permutation is a whole-module + /// compile that can take far longer than an ordinary compute (records x callee size), the session serves the caller's + /// dispatches from a ready permutation or links its kept callees itself meanwhile, and the permutation a session asks + /// for first goes first. + /// </summary> + internal static List<(ComputePrewarmRecord Record, ShaderCodeCapture Code, bool Held)> HoldFirstLinkedLast( + IReadOnlyList<(ComputePrewarmRecord Record, ShaderCodeCapture Code)> pending, + IReadOnlyList<ulong>? firstFrame, + Func<ComputePrewarmRecord, bool> isLinked, + Func<IReadOnlyList<(ComputePrewarmRecord Record, ShaderCodeCapture Code)>, IEnumerable<(ComputePrewarmRecord Record, ShaderCodeCapture Code)>> orderLinked, + out int held) + { + var ordered = HoldFirst(pending.Where(item => !isLinked(item.Record)).ToList(), firstFrame, out held); + var linked = pending.Where(item => isLinked(item.Record)).ToList(); + if (linked.Count != 0) + { + ordered.AddRange(orderLinked(linked).Select(static item => (item.Record, item.Code, false))); + } + + return ordered; + } + internal static List<(ComputePrewarmRecord Record, ShaderCodeCapture Code, bool Held)> HoldFirst( IReadOnlyList<(ComputePrewarmRecord Record, ShaderCodeCapture Code)> pending, IReadOnlyList<ulong>? firstFrame, diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalShaderPrewarmPendingTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalShaderPrewarmPendingTests.cs index 84e3f8f99..b9eecf7dc 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalShaderPrewarmPendingTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalShaderPrewarmPendingTests.cs @@ -125,6 +125,35 @@ public void TheComputesBeforeTheFirstFrameAreHeldForAndCompiledFirst() Assert.Equal(new ulong[] { 0x1000, 0x3000, 0x2000 }, held3.Select(item => item.Record.Address)); } + // Linked records never hold the guest and compile after every other compute, in the linked lane's order (the order + // function stands in for LinkedPrewarmOrder, whose order ShaderCallUnionStoreTests checks), even when the first frame + // or a list without one would hold them. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void LinkedRecordsAreNeverHeldForAndCompileLastInTheirLanesOrder(bool firstFrameList) + { + using (var list = Open()) + { + Record(list, 0x1000); + Record(list, 0x2000); + Record(list, 0x3000); + Record(list, 0x4000); + list.WriteFirstFrameComputes(); + Record(list, 0x5000); + } + + using var reopened = Open(); + var linked = new HashSet<ulong> { 0x1000, 0x3000, 0x5000 }; + var ordered = MetalShaderPrewarm.HoldFirstLinkedLast(reopened.LoadedComputes(), + firstFrameList ? reopened.ReadFirstFrameComputes() : null, record => linked.Contains(record.Address), + records => records.OrderByDescending(item => item.Record.Address), out var held); + + Assert.Equal(2, held); + Assert.Equal(new ulong[] { 0x2000, 0x4000, 0x5000, 0x3000, 0x1000 }, ordered.Select(item => item.Record.Address)); + Assert.Equal(new[] { true, true, false, false, false }, ordered.Select(item => item.Held)); + } + [Fact] public void AFirstFrameBeforeAnyComputeHoldsForNone() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCallUnionStoreTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCallUnionStoreTests.cs index 25dd2b0d3..a302d1bcb 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCallUnionStoreTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/ShaderCallUnionStoreTests.cs @@ -38,6 +38,37 @@ public void ARecordedLibraryIsTheKeptOneOnlyWhenItsSiteCalleesMatch() } } + // The linked prewarm lane's order as the Metal backend takes it (LinkedPrewarmOrder): each caller's kept library first, + // every caller's first record before any second, slow callers first within a round, the rest newest first. + [Fact] + public void TheLinkedPrewarmOrderPutsEachCallersKeptLibraryFirst() + { + var directory = Path.Combine(Path.GetTempPath(), $"sharpemu-callees-{Guid.NewGuid():N}"); + try + { + new ShaderCallUnionStore(Path.Combine(directory, "callees.bin")).Save(ShaderStage.Compute, Caller, + new Dictionary<uint, UnitedCallee[]> { [0] = [Callee(FunctionAddress)] }); + const ulong Slow = 0x5104; + (ulong Caller, LinkedShaderPrewarm Library, string Name)[] records = + [ + (Caller, Library((0, OtherAddress)), "a-old"), + (Slow, Library((0, OtherAddress)), "slow-old"), + (Caller, Library((0, FunctionAddress)), "a-kept"), + (Caller, Library((0, OtherAddress), (8, OtherAddress)), "a-new"), + (Slow, Library((0, FunctionAddress)), "slow-new"), + ]; + + var ordered = LinkedPrewarmOrder.Order(records, static record => record.Caller, static record => record.Library, + static caller => caller == Slow, directory); + + Assert.Equal(["slow-old", "a-kept", "slow-new", "a-new", "a-old"], ordered.Select(static record => record.Name)); + } + finally + { + if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true); + } + } + private static UnitedCallee Callee(ulong address) { uint[] words = [0xBF800000, 0xBE80200E]; From 193db5810219033b50e317838d65022e1fddde0d Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 10:59:16 +0000 Subject: [PATCH 119/134] [Shader] Keep the low bits of every integer image store, not only those with a store map A Metal integer texture write saturates a value its view format cannot hold (0xFFFF8000 to R16Uint stores 0xFFFF); the hardware and upstream's store through the unsigned view (99f9fe930) keep the register's low bits. The previous round narrowed only stores whose image has a run-time store channel map. Every other written integer storage image now takes a 2-bit width slot in shader data (ImageStoreWidth, BindingLayout StorageImageWidthsDword): images with the select baked into the module (SHARPEMU_RUNTIME_IMAGE_SWIZZLE=0) and indirect-table candidates. The host writes each slot from the image's own bound T# (Gen5MslTranslator WriteStoreWidths, which also writes the map-carried codes), and the MSL store narrows each channel by it (8, 16, 10_10_10_2), sign-extending for int textures. A translator that finds no slot for an integer store refuses the program instead of emitting a saturating write. Heap and bindless-table images are sampled only (PlanHeapRecords, OnlySampledReadsThrough), packed stores already extract each field at its width, and conversion formats store 32-bit or float channels, so no other store needs a width. --- .../Gen5MslTranslator.Pixel.cs | 31 +++--- .../Gen5MslTranslator.StoreWidths.cs | 105 ++++++++++++++++++ .../Resources/BindingLayout.cs | 13 ++- .../Resources/ImageStoreWidth.cs | 55 +++++++++ .../V2/MetalRenderHost.Descriptors.cs | 33 ++---- .../MetalStoreChannelMapTests.cs | 67 +++++++++++ .../MetalIntegerStoreWidthTests.cs | 91 +++++++++++++++ .../MslTranslationTests.cs | 11 +- 8 files changed, 357 insertions(+), 49 deletions(-) create mode 100644 src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.StoreWidths.cs create mode 100644 src/SharpEmu.ShaderCompiler/Resources/ImageStoreWidth.cs create mode 100644 tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalIntegerStoreWidthTests.cs diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Pixel.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Pixel.cs index fc1321b65..d693578aa 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Pixel.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.Pixel.cs @@ -14,7 +14,7 @@ public static partial class Gen5MslTranslator /// <summary> /// The width code of an image store's components for a T# format, which the host puts in the image's store channel map - /// (MetalRenderHost.WriteStoreComponentWidths): 1 for 8-bit, 2 for 16-bit, 3 for 10_10_10_2 (X, Y, Z 10, W 2) + /// (WriteStoreWidths): 1 for 8-bit, 2 for 16-bit, 3 for 10_10_10_2 (X, Y, Z 10, W 2) /// components; 0 for any other format, whose components the store passes whole. /// </summary> public static uint StoreComponentWidthCode(uint imageFormat) @@ -206,17 +206,23 @@ private bool EmitImageOperation( } else { + // An integer store with the select in the module narrows each channel to the width its image's + // slot gives (Gen5MslTranslator.StoreWidths.cs), as the run-time select's store does. + string? width = null; + if (kind is "uint" or "int" && (width = StoreWidthCode(resourceIndex, out error)) is null) + { + return false; + } + for (var component = 0; component < 4; component++) { var sourceIndex = Gen5ShaderTranslator.GetImageStoreSourceIndex( dstSelect, image.Dmask, component); - components[component] = sourceIndex >= 0 - ? ImageTexelComponent( - kind, - ImageStoreComponent(image, kind, (uint)sourceIndex)) - : kind == "float" ? "0.0f" : "0"; + components[component] = sourceIndex < 0 ? kind == "float" ? "0.0f" : "0" + : width is null ? ImageTexelComponent(kind, ImageStoreComponent(image, kind, (uint)sourceIndex)) + : NarrowStoreComponent(kind, ImageStoreComponent(image, kind, (uint)sourceIndex), width, (uint)component); } } @@ -813,18 +819,7 @@ private void EmitRuntimeSwizzleStoreTexel(Gen5ImageControl image, string kind, i { var code = Temp("uint", $"((({map}) >> {channel * 3}u) & 7u) ^ {channel}u"); var raw = $"({code} < 4u ? {words}[{code} & 3u] : 0u)"; - if (width is null) - { - components[channel] = ImageTexelComponent(kind, raw); - continue; - } - - var bits = Temp("uint", - $"{width} == 1u ? 8u : {width} == 2u ? 16u : {width} == 3u ? {(channel == 3 ? 2 : 10)}u : 32u"); - var value = Temp("uint", raw); - components[channel] = kind == "int" - ? $"({bits} == 32u ? as_type<int>({value}) : extract_bits(as_type<int>({value}), 0u, {bits}))" - : $"({bits} == 32u ? {value} : extract_bits({value}, 0u, {bits}))"; + components[channel] = width is null ? ImageTexelComponent(kind, raw) : NarrowStoreComponent(kind, raw, width, channel); } } diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.StoreWidths.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.StoreWidths.cs new file mode 100644 index 000000000..f94db9b2e --- /dev/null +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.StoreWidths.cs @@ -0,0 +1,105 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.ShaderCompiler.Metal; + +// An integer image store keeps the low bits of each register, where a Metal write saturates a value its view format +// cannot hold (0xFFFF8000 written to an R16Uint view stores 0xFFFF; the hardware, and upstream's store through the +// unsigned view, 0x8000). Each store narrows its components to the width of the format the host binds: the width code +// (StoreComponentWidthCode) of an image with a store channel map sits above its map, and every other written integer +// storage image has a width slot of its own (ImageStoreWidth, BindingLayout.StorageImageWidthsDword). +public static partial class Gen5MslTranslator +{ + /// <summary> + /// Writes the store width code of every written integer storage image from its bound T#: above the store channel + /// map of an image that has one (its bits 12-13), in the image's width slot otherwise. A null or absent descriptor + /// gives code 0 (stored whole; the write lands on a null texture). + /// </summary> + public static void WriteStoreWidths(uint[] shaderData, BindingLayout layout, IReadOnlyList<ImageResource> images, + bool runtimeImageSwizzles, IReadOnlyList<uint[]> descriptors) + { + if (layout.StorageImageWidthCount != 0) + { + Array.Clear(shaderData, (int)layout.StorageImageWidthsDword, (int)ImageStoreWidth.DwordCount(layout.StorageImageWidthCount)); + } + + var mapSlot = 0; + var widthSlot = 0; + for (var index = 0; index < images.Count; index++) + { + var image = images[index]; + var hasMap = layout.StorageImageSwizzleCount != 0 && image.Written && RuntimeImageSwizzle.Serves(image); + var hasWidth = ImageStoreWidth.TakesSlot(image, runtimeImageSwizzles); + if (!hasMap && !hasWidth) + { + continue; + } + + var code = index < descriptors.Count && descriptors[index] is { Length: >= 8 } words + ? StoreComponentWidthCode(GuestImageFormat.FormatOf(words)) + : 0u; + if (hasMap) + { + if (mapSlot < layout.StorageImageSwizzleCount) + { + shaderData[(int)layout.StorageImageSwizzlesDword + (mapSlot / 2)] |= code << (StoreWidthCodeShift + (mapSlot % 2 * 16)); + } + + mapSlot++; + continue; + } + + if (widthSlot >= layout.StorageImageWidthCount) + { + throw new InvalidOperationException( + $"The store width slots do not match the layout: image={index} slot={widthSlot} layout={layout.StorageImageWidthCount}."); + } + + shaderData[(int)layout.StorageImageWidthsDword + (widthSlot / ImageStoreWidth.SlotsPerDword)] |= + code << (widthSlot % ImageStoreWidth.SlotsPerDword * ImageStoreWidth.BitsPerSlot); + widthSlot++; + } + + if (widthSlot != layout.StorageImageWidthCount) + { + throw new InvalidOperationException( + $"The store width slots do not match the layout: images={widthSlot} layout={layout.StorageImageWidthCount}."); + } + } + + private sealed partial class CompilationContext + { + // The width code of an integer store with no store channel map, read from the image's width slot; null, with the + // error, when the layout gives the image no slot: its store would saturate, so the program is refused. + private string? StoreWidthCode(int resourceIndex, out string error) + { + error = string.Empty; + var slot = resourceIndex < 0 ? -1 + : ImageStoreWidth.Slot(_request.Resources.Info.Images, resourceIndex, _request.Resources.Info.UsesRuntimeImageSwizzles); + if (slot < 0 || slot >= _request.Bindings.StorageImageWidthCount) + { + error = $"integer image store to image {resourceIndex} has no store width slot (slots={_request.Bindings.StorageImageWidthCount})"; + return null; + } + + var dword = _request.Bindings.StorageImageWidthsDword + (uint)(slot / ImageStoreWidth.SlotsPerDword); + var shift = slot % ImageStoreWidth.SlotsPerDword * ImageStoreWidth.BitsPerSlot; + return Temp("uint", $"({ShaderDataDword(dword)} >> {shift}u) & 3u"); + } + + // One integer component of a store, as uint bits, narrowed to the bits of the physical channel the width code + // gives (1: 8, 2: 16, 3: 10_10_10_2, 0: whole) and, for an int texture, sign-extended from them, so the write + // keeps the register's low bits instead of saturating; the result is the texel component of kind. + private string NarrowStoreComponent(string kind, string raw, string width, uint channel) + { + var bits = Temp("uint", + $"{width} == 1u ? 8u : {width} == 2u ? 16u : {width} == 3u ? {(channel == 3 ? 2 : 10)}u : 32u"); + var value = Temp("uint", raw); + return kind == "int" + ? $"({bits} == 32u ? as_type<int>({value}) : extract_bits(as_type<int>({value}), 0u, {bits}))" + : $"({bits} == 32u ? {value} : extract_bits({value}, 0u, {bits}))"; + } + } +} diff --git a/src/SharpEmu.ShaderCompiler/Resources/BindingLayout.cs b/src/SharpEmu.ShaderCompiler/Resources/BindingLayout.cs index 54313344f..5a85bc73d 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/BindingLayout.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/BindingLayout.cs @@ -414,6 +414,9 @@ public sealed class BindingLayout : IEquatable<BindingLayout> // The store channel map (RuntimeImageSwizzle.StoreChannelMap) of every written image that takes its destination select // from shader data (ShaderResourceInfo.UsesRuntimeImageSwizzles), in image order, two to a dword (16 bits each). public uint StorageImageSwizzleCount { get; init; } + + // The component width code of every other written integer storage image (ImageStoreWidth), 16 to a dword. + public uint StorageImageWidthCount { get; init; } // The program reads bindless heap records through descriptor set 1 (see BindlessHeap). public bool UsesBindlessHeap { get; init; } @@ -458,7 +461,9 @@ public sealed class BindingLayout : IEquatable<BindingLayout> public uint HeapViewsDword => StorageImageSwizzlesDword + (StorageImageSwizzleCount + 1) / 2; - public uint ShaderDataDwordCount => HeapViewsDword + HeapViewCount * HeapView.DwordCount; + public uint StorageImageWidthsDword => HeapViewsDword + HeapViewCount * HeapView.DwordCount; + + public uint ShaderDataDwordCount => StorageImageWidthsDword + ImageStoreWidth.DwordCount(StorageImageWidthCount); public bool UsesPushData => PushDataStartDword != PushData.NoStart; @@ -739,11 +744,13 @@ public static BindingLayout Allocate( usesBufferLengths &= memoryOffsetCount != 0 && !usesTableBlock; var bufferStrideCount = info.UsesIndexedBuffers ? (uint)info.Buffers.Count : 0u; var storageImageSwizzleCount = info.UsesRuntimeImageSwizzles ? RuntimeImageSwizzle.SlotCount(info.Images) : 0u; + var storageImageWidthCount = ImageStoreWidth.SlotCount(info.Images, info.UsesRuntimeImageSwizzles); var shaderDataDwords = memoryOffsetDword + (usesTableBlock ? 2u : (memoryOffsetCount + 3) / 4) + bufferWordCount + (usesBufferLengths ? memoryOffsetCount : 0) + (usesDispatchThreadLimits ? 3u : 0u) + mipStatisticsCount + (usesMeshDrawParameters ? 6u : 0u) + (usesTessellationData ? Gen5TessellationData.DwordCount : 0u) + callArgumentCount * 2 + callTargetCount * 2 + - (bufferStrideCount + 1) / 2 + (storageImageSwizzleCount + 1) / 2 + info.HeapViewCount * HeapView.DwordCount; + (bufferStrideCount + 1) / 2 + (storageImageSwizzleCount + 1) / 2 + info.HeapViewCount * HeapView.DwordCount + + ImageStoreWidth.DwordCount(storageImageWidthCount); var pushStart = usesTessellationData ? PushData.NoStart : pushDataAtTop ? PushData.TopFor(pushDataStartDword, shaderDataDwords) : PushData.StartFor(pushDataStartDword, shaderDataDwords); @@ -858,6 +865,7 @@ public static BindingLayout Allocate( CallTargetCount = callTargetCount, BufferStrideCount = bufferStrideCount, StorageImageSwizzleCount = storageImageSwizzleCount, + StorageImageWidthCount = storageImageWidthCount, UsesBindlessHeap = info.UsesBindlessHeap, HeapViewCount = info.HeapViewCount, UserDataRegisters = userDataRegisters, @@ -893,6 +901,7 @@ public bool Equals(BindingLayout? other) CallTargetCount != other.CallTargetCount || BufferStrideCount != other.BufferStrideCount || StorageImageSwizzleCount != other.StorageImageSwizzleCount || + StorageImageWidthCount != other.StorageImageWidthCount || UsesBindlessHeap != other.UsesBindlessHeap || HeapViewCount != other.HeapViewCount || !SameValues(UserDataRegisters, other.UserDataRegisters)) diff --git a/src/SharpEmu.ShaderCompiler/Resources/ImageStoreWidth.cs b/src/SharpEmu.ShaderCompiler/Resources/ImageStoreWidth.cs new file mode 100644 index 000000000..258c3aa49 --- /dev/null +++ b/src/SharpEmu.ShaderCompiler/Resources/ImageStoreWidth.cs @@ -0,0 +1,55 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Collections.Generic; + +namespace SharpEmu.ShaderCompiler.Resources; + +// An integer image store keeps the low bits of each register (upstream stores a write-only SINT image through its UINT +// view, 99f9fe930), where a Metal write saturates a value its view format cannot hold, so the MSL store narrows each +// component to the width of the format the host binds. A written image with a store channel map (RuntimeImageSwizzle) +// carries that width above its map; every other written integer storage image (the select baked into the module with +// SHARPEMU_RUNTIME_IMAGE_SWIZZLE=0, an indirect table's candidate) takes a width slot here: 2 bits per image, 16 to a +// dword (BindingLayout.StorageImageWidthsDword), written by the host from the image's bound T#. A host whose stores keep +// the low bits by themselves leaves the slots zero, which narrows nothing. +public static class ImageStoreWidth +{ + public const int BitsPerSlot = 2; + public const int SlotsPerDword = 32 / BitsPerSlot; + + // A written integer storage image whose stores have no store channel map to carry the width. + public static bool TakesSlot(ImageResource image, bool runtimeImageSwizzles) => + image.Written && image.ResourceClass == ImageResourceClass.Storage && + image.NumericClass is ImageNumericClass.Uint or ImageNumericClass.Sint && + !(runtimeImageSwizzles && RuntimeImageSwizzle.Serves(image)); + + // The image's width slot: its rank among the images that take one, or -1 for any other image. + public static int Slot(IReadOnlyList<ImageResource> images, int index, bool runtimeImageSwizzles) + { + if ((uint)index >= (uint)images.Count || !TakesSlot(images[index], runtimeImageSwizzles)) + { + return -1; + } + + var slot = 0; + for (var other = 0; other < index; other++) + { + slot += TakesSlot(images[other], runtimeImageSwizzles) ? 1 : 0; + } + + return slot; + } + + public static uint SlotCount(IReadOnlyList<ImageResource> images, bool runtimeImageSwizzles) + { + var count = 0u; + foreach (var image in images) + { + count += TakesSlot(image, runtimeImageSwizzles) ? 1u : 0u; + } + + return count; + } + + public static uint DwordCount(uint slots) => (slots + SlotsPerDword - 1) / SlotsPerDword; +} diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs index 66afbf74f..113205feb 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Descriptors.cs @@ -653,36 +653,19 @@ internal static bool WriteStageShaderData(uint[] shaderData, ShaderProgramInfo p // Each written image's store channel map, from its bound T# (RuntimeImageSwizzle). RuntimeImageSwizzle.WriteStoreMaps(shaderData, layout, info.Images, snapshot.Images); - WriteStoreComponentWidths(shaderData, layout, info.Images, snapshot.Images); + WriteStoreComponentWidths(shaderData, layout, info, snapshot.Images); return true; } // An integer image store keeps the low bits of each register (a write-only 16_SINT image is stored as unsigned bits // through its R16Uint view, upstream 99f9fe930), where a Metal write saturates a value its format cannot hold. The - // MSL store narrows each component itself from the width code its T# gives (Gen5MslTranslator - // StoreComponentWidthCode), carried in bits 12-13 of the image's store channel map, above the map's 12 bits. - internal static void WriteStoreComponentWidths(uint[] shaderData, BindingLayout layout, IReadOnlyList<ImageResource> images, - IReadOnlyList<uint[]> descriptors) - { - if (layout.StorageImageSwizzleCount == 0) - { - return; - } - - for (var index = 0; index < images.Count; index++) - { - var slot = RuntimeImageSwizzle.Slot(images, index); - if (slot < 0 || slot >= layout.StorageImageSwizzleCount || index >= descriptors.Count || - descriptors[index] is not { Length: >= 8 } words) - { - continue; - } - - var code = SharpEmu.ShaderCompiler.Metal.Gen5MslTranslator.StoreComponentWidthCode(GuestImageFormat.FormatOf(words)); - shaderData[(int)layout.StorageImageSwizzlesDword + (slot / 2)] |= - code << (SharpEmu.ShaderCompiler.Metal.Gen5MslTranslator.StoreWidthCodeShift + (slot % 2 * 16)); - } - } + // MSL store narrows each component itself from the width code its bound T# gives (Gen5MslTranslator + // StoreComponentWidthCode): in bits 12-13 of the image's store channel map when it has one, in its width slot + // (ImageStoreWidth) otherwise. + internal static void WriteStoreComponentWidths(uint[] shaderData, BindingLayout layout, ShaderResourceInfo info, + IReadOnlyList<uint[]> descriptors) => + SharpEmu.ShaderCompiler.Metal.Gen5MslTranslator.WriteStoreWidths(shaderData, layout, info.Images, + info.UsesRuntimeImageSwizzles, descriptors); private Exception UserRegisterOutsideUserData(ShaderProgramInfo program, BindingLayout layout, ResourceSnapshot snapshot) { diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalStoreChannelMapTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalStoreChannelMapTests.cs index 19b5592d2..aefc80dff 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalStoreChannelMapTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalStoreChannelMapTests.cs @@ -68,6 +68,73 @@ public void TheShaderDataCarriesEachWrittenImagesStoreChannelMap() Assert.Equal(shaderData, packet.ShaderData[..packet.ShaderDataCount]); } + // A written integer storage image with no store channel map (the select baked into the module, or an indirect + // table's candidate) takes a width slot, which the host fills from that image's own bound T#: the MSL store narrows + // its integer channels by it instead of saturating (Gen5MslTranslator.StoreWidths.cs). + [Theory] + [InlineData(false)] + [InlineData(true)] + public void TheShaderDataCarriesTheStoreWidthOfEachIntegerImageWithoutAMap(bool runtimeSwizzles) + { + // Image 0: a plain integer storage image (a map with run-time selects, a width slot without). Image 1: a float + // one (a map with run-time selects, no width slot). Images 2 and 3: an indirect table's root and candidate (width slots either way). + ImageResource[] images = [Storage(ImageNumericClass.Uint), Storage(), Storage(ImageNumericClass.Uint, root: 2), + Storage(ImageNumericClass.Sint, root: 2)]; + var info = new ShaderResourceInfo { Images = [.. images], UsesRuntimeImageSwizzles = runtimeSwizzles }; + var resources = new SpecializedResourceInfo { Info = info }; + var layout = new BindingLayout + { + UserDataRegisters = [0], + MemoryOffsetDword = 8, + StorageImageSwizzleCount = runtimeSwizzles ? 2u : 0u, + StorageImageWidthCount = ImageStoreWidth.SlotCount(info.Images, runtimeSwizzles), + }; + Assert.Equal(runtimeSwizzles ? 2u : 3u, layout.StorageImageWidthCount); + var program = new ShaderProgramInfo + { + Stage = ShaderStageKind.Compute, Resources = resources, Bindings = layout, UserDataBase = 0, + }; + var snapshot = new ResourceSnapshot + { + Images = [Texture(0x10_0000, 0xFAC, Format16Uint), Texture(0x20_0000, 0xFAC), Texture(0x30_0000, 0xFAC, Format8Uint), + Texture(0x40_0000, 0xFAC, Format10x3x2Uint)], + Samplers = [], + UserData = [7], + }; + + var shaderData = new uint[layout.ShaderDataDwordCount]; + Assert.True(MetalRenderHost.WriteStageShaderData(shaderData, program, layout, info, snapshot, 0)); + // Width codes: 2 (16-bit), 1 (8-bit), 3 (10_10_10_2), 2 bits per slot. + var expected = runtimeSwizzles ? 1u | (3u << 2) : 2u | (1u << 2) | (3u << 4); + Assert.Equal(expected, shaderData[layout.StorageImageWidthsDword]); + if (runtimeSwizzles) + { + // Images 0 (16-bit) and 1 (RGBA8) carry their codes above their identity maps instead. + Assert.Equal((2u << SharpEmu.ShaderCompiler.Metal.Gen5MslTranslator.StoreWidthCodeShift) | + (1u << (SharpEmu.ShaderCompiler.Metal.Gen5MslTranslator.StoreWidthCodeShift + 16)), shaderData[layout.StorageImageSwizzlesDword]); + } + + var packet = MetalRenderHost.BuildBindingPacket(program, resources, layout, snapshot, 0)!; + Assert.Equal(shaderData, packet.ShaderData[..packet.ShaderDataCount]); + } + + private const uint Format8Uint = 5; + private const uint Format16Uint = 11; + private const uint Format10x3x2Uint = 54; + + private static uint[] Texture(ulong address, uint select, uint format) + { + var words = Descriptors.Texture(address, format, 16, 16); + words[3] = (words[3] & ~0xFFFu) | select; + return words; + } + + private static ImageResource Storage(ImageNumericClass numericClass, uint root = DescriptorConstants.NoIndex) => new() + { + ResourceClass = ImageResourceClass.Storage, NumericClass = numericClass, Dimension = ImageDimension.Dim2D, + Written = true, IndirectRoot = root, + }; + private static uint[] Texture(ulong address, uint select) { var words = Descriptors.Texture(address, Rgba8, 16, 16); diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalIntegerStoreWidthTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalIntegerStoreWidthTests.cs new file mode 100644 index 000000000..8bb198dfb --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalIntegerStoreWidthTests.cs @@ -0,0 +1,91 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.ShaderCompiler.Metal.Tests; + +/// <summary> +/// An integer image store whose select is baked into the module (SHARPEMU_RUNTIME_IMAGE_SWIZZLE=0, or an indirect +/// table's candidate) keeps the low bits of each register, as the hardware and upstream's store through the unsigned +/// view do, where a Metal integer texture write saturates: the store narrows each component to the width its image's +/// width slot (ImageStoreWidth) gives, which the host writes from the bound T# (Gen5MslTranslator.WriteStoreWidths). +/// </summary> +public sealed class MetalIntegerStoreWidthTests(ITestOutputHelper output) +{ + private const uint Size = 2; + + // Guest unified format, MTLPixelFormat of the view the host binds, bytes per texel, component widths (X first). + // A write-only 16_SINT image is viewed and stored as R16Uint (upstream 99f9fe930). + public static TheoryData<uint, uint, uint, uint[]> Formats() => new() + { + { 5, 13, 1, [8] }, // 8_UINT -> R8Uint + { 11, 23, 2, [16] }, // 16_UINT -> R16Uint + { 12, 23, 2, [16] }, // 16_SINT, write-only -> R16Uint + { 54, 91, 4, [10, 10, 10, 2] }, // 2_10_10_10_UINT (X, Y, Z 10 bits, W 2) -> RGB10A2Uint + }; + + // Wider than any of the formats, with distinct low bits per component. + private static readonly uint[] Values = [0xFFFF_82AB, 0x0001_2345, 0xFFFF_FC01, 0xFFFF_FFFE]; + + [Theory] + [MemberData(nameof(Formats))] + public void AnIntegerStoreWithTheSelectInTheModuleKeepsTheLowBits(uint guestFormat, uint pixelFormat, uint texelBytes, uint[] widths) + { + BindingLayout? layout = null; + ResourceSnapshot? snapshot = null; + ShaderCompileRequest? request = null; + Assert.True(Gen5ImageFixtures.TryCompile("ImageStore", Gen5ImageFixtures.ImageType2D, out var shader, out var error, + unifiedFormat: guestFormat, dmask: 0xF, addressValues: [1, 0], storeValues: Values, runtimeImageSwizzles: false, + inspect: (compiled, resources) => (request, layout, snapshot) = (compiled, compiled.Bindings, resources)), error); + Assert.Equal(0u, layout!.StorageImageSwizzleCount); + Assert.Equal(1u, layout.StorageImageWidthCount); + Assert.Contains("extract_bits", shader!.Source, StringComparison.Ordinal); + + // The shader data the descriptor path writes (MetalRenderHost.WriteStageShaderData): here only the width slot. + var shaderData = new uint[layout.ShaderDataDwordCount]; + Gen5MslTranslator.WriteStoreWidths(shaderData, layout, request!.Resources.Info.Images, request.Resources.Info.UsesRuntimeImageSwizzles, + snapshot!.Images); + var expectedCode = widths.Length == 4 ? 3u : widths[0] == 8 ? 1u : 2u; + Assert.Equal(expectedCode, shaderData[layout.StorageImageWidthsDword] & 3u); + if (Environment.GetEnvironmentVariable("SHARPEMU_TEST_REQUIRE_DEVICE") != "1") + { + output.WriteLine("Texture execution requires the exclusive Metal device gate; only the layout and source are checked."); + return; + } + + Assert.True(MetalNative.IsAvailable, "The required gate needs a Metal device."); + Assert.True(layout.UsesPushData); + Assert.True(MetalNative.TryCompileLibrary(shader.Source, out var library, out error), error + shader.Source); + byte[] Store(uint[] data) + { + var push = new byte[PushData.ByteSize]; + Buffer.BlockCopy(data, 0, push, (int)layout.PushDataStartDword * 4, data.Length * 4); + var texture = MetalNative.CreateRawTexture(pixelFormat, Size, Size, texelBytes, + Enumerable.Repeat((byte)0xA5, (int)(Size * Size * texelBytes)).ToArray()); + Assert.True(MetalNative.TryExecuteWithArgumentBuffer(library, shader.EntryPoint, new byte[16], push, + shader.ArgumentLayout!, 1, out _, out error, texture), error); + return MetalNative.ReadRawTexture(texture, Size, Size, texelBytes).AsSpan((int)texelBytes, (int)texelBytes).ToArray(); + } + + var texel = Store(shaderData); + // Width code 0 stores each register whole, as every store without a slot did: Metal saturates it. + var whole = Store(new uint[shaderData.Length]); + + // Each component's low bits, packed from bit 0 (X first): a saturating write stores all ones instead. + var packed = 0ul; + var shift = 0; + for (var component = 0; component < widths.Length; component++) + { + packed |= (Values[component] & ((1ul << (int)widths[component]) - 1)) << shift; + shift += (int)widths[component]; + } + + var expected = BitConverter.GetBytes(packed).AsSpan(0, (int)texelBytes).ToArray(); + output.WriteLine($"format {guestFormat}: narrowed {Convert.ToHexString(texel)}, whole {Convert.ToHexString(whole)}"); + Assert.Equal(Convert.ToHexString(expected), Convert.ToHexString(texel)); + Assert.NotEqual(Convert.ToHexString(expected), Convert.ToHexString(whole)); + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslTranslationTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslTranslationTests.cs index b1c44e1e3..e33edbd98 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslTranslationTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MslTranslationTests.cs @@ -1065,10 +1065,13 @@ public void UintImageStoreUsesUintTextureAndInverseDescriptorSwizzle() "texture2d<uint, access::write>", shader.Source, StringComparison.Ordinal); - Assert.Contains( - ".write(vec<uint, 4>(v6, v5, v4, v7),", - shader.Source, - StringComparison.Ordinal); + // Each channel's register, in the inverse select's order, is narrowed to the width its image's width slot gives + // before the write (an integer store keeps the low bits, Gen5MslTranslator.StoreWidths.cs). + var channels = new[] { "v6", "v5", "v4", "v7" } + .Select(register => shader.Source.IndexOf($" = {register};", StringComparison.Ordinal)).ToArray(); + Assert.All(channels, at => Assert.True(at >= 0, shader.Source)); + Assert.Equal(channels.Order(), channels); + Assert.Contains(".write(vec<uint, 4>((", shader.Source, StringComparison.Ordinal); } [Fact] From 3e2f72349953b4ae70f80f6fab00dc1efcccf8c0 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 10:59:58 +0000 Subject: [PATCH 120/134] [Metal] Count compute prewarm records of the other image binding policy as stale Graphics prewarm records made under another stable image budget are skipped and counted as graphics_stale; compute records of the other policy were refused by ResourceMaterializer.ApplyTo and counted as failures (failed=, logged as "Shader prewarm failed") once per start until the list was re-recorded. The prewarm now tells that refusal apart (ResourceMaterializer.ImageBindingPolicyMismatch) and counts it as compute_stale, logged beside graphics_stale in the "Shader prewarm done" and precompile summaries; every other refusal is still a failure. --- .../Resources/ResourceMaterializer.cs | 9 +++- .../V2/MetalShaderPrewarm.cs | 28 +++++++++++-- .../Pipelines/MetalStableImagePrewarmTests.cs | 42 +++++++++++++++++++ 3 files changed, 75 insertions(+), 4 deletions(-) diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs index bb297683f..cde8f2912 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceMaterializer.cs @@ -4245,12 +4245,19 @@ private static bool BuildSamplerPlan(ShaderResourceInfo info, IReadOnlyList<Imag /// </summary> public static bool SpecializationGuards { get; set; } = true; + /// <summary> + /// What ApplyTo refuses a specialization of the other stable image binding policy with: a recorded one (a prewarm + /// record) made by a session whose host answered another stable image budget. The Metal prewarm counts such a + /// compute record as stale, not failed. + /// </summary> + public const string ImageBindingPolicyMismatch = "shader image binding policy does not match the plan"; + public static SpecializedResourceInfo ApplyTo(ShaderResourcePlan plan, ResourceSpecialization specialization) { var source = plan.Info; if (plan.StableImageBindings != specialization.StableImageBindings || (plan.StableImageBindings && specialization.ImageDescriptorGroups.Count != 0)) - throw new ResourcePlanException("shader image binding policy does not match the plan"); + throw new ResourcePlanException(ImageBindingPolicyMismatch); if (source.Buffers.Count != specialization.BaseBufferCount || source.Images.Count > specialization.Images.Count) { throw new ResourcePlanException( diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs index 647c2a7f6..73e039bae 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs @@ -594,6 +594,28 @@ private static void PrewarmGraphicsLibrary(in GraphicsPrewarmList.Item item, IGu // Graphics records made under another stable image budget, not translated. private static int _graphicsStale; + // Compute records made under the other stable image binding policy (their specialization's StableImageBindings is + // not the plan's under this host's budget): refused before translation, like stale graphics records, and not counted + // as failures; the session records them anew under this policy. + private static int _computeStale; + + internal static int ComputeStale => Volatile.Read(ref _computeStale); + + internal static int ComputeFailed => Volatile.Read(ref _failed); + + // A compute record the prewarm could not compile: stale when its specialization follows the other image binding + // policy (ResourceMaterializer.ImageBindingPolicyMismatch), a failure otherwise. + internal static void NoteComputeRefusal(ComputePrewarmRecord record, string error) + { + if (error == SharpEmu.ShaderCompiler.Resources.ResourceMaterializer.ImageBindingPolicyMismatch) + { + Interlocked.Increment(ref _computeStale); + return; + } + + NoteFailure(record, error); + } + private static void NoteGraphicsFailure(string error) { if (Interlocked.Increment(ref _graphicsFailed) <= MaxLoggedPrewarmFailures) @@ -678,7 +700,7 @@ private static bool CompletePrecompile() return Precompile.Complete( $"computes={Volatile.Read(ref _compiled)} compute_failed={Volatile.Read(ref _failed)} " + $"graphics_libraries={Volatile.Read(ref _graphicsCompiled)} graphics_failed={Volatile.Read(ref _graphicsFailed)} " + - $"graphics_stale={Volatile.Read(ref _graphicsStale)} " + + $"graphics_stale={Volatile.Read(ref _graphicsStale)} compute_stale={Volatile.Read(ref _computeStale)} " + $"libraries_held={MetalLibraryPrewarm.HeldLibraries} {MetalStaticPrecompile.Describe()}"); } @@ -885,7 +907,7 @@ private static void PrewarmComputePipeline( { if (!TryCompileCompute(record, code, compiler, MetalStableImageLimits.Of(device), out var compiled, out var error)) { - NoteFailure(record, error); + NoteComputeRefusal(record, error); return; } @@ -1060,7 +1082,7 @@ private static void Finish(ShaderPrewarmList list, string stamp, long started) $"archived={Volatile.Read(ref _archived)} " + $"runtime_first={Volatile.Read(ref _runtimeFirst)} " + $"graphics_libraries={Volatile.Read(ref _graphicsCompiled)} graphics_failed={Volatile.Read(ref _graphicsFailed)} " + - $"graphics_stale={Volatile.Read(ref _graphicsStale)} " + + $"graphics_stale={Volatile.Read(ref _graphicsStale)} compute_stale={Volatile.Read(ref _computeStale)} " + $"ms={Stopwatch.GetElapsedTime(started).TotalMilliseconds:F0} " + $"yielded_ms={Interlocked.Read(ref _yieldedTicks) * 1000 / Stopwatch.Frequency} " + $"runtime_compute_modules={runtime.Count} matched={matched}"; diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/MetalStableImagePrewarmTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/MetalStableImagePrewarmTests.cs index d388113a2..e0e5fb6a5 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/MetalStableImagePrewarmTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Pipelines/MetalStableImagePrewarmTests.cs @@ -217,4 +217,46 @@ public void TheComputePrewarmFindsWhatTheSessionRecorded(bool stable) Assert.Contains("image binding policy", error); Assert.Empty(other.Requests); } + + // The Metal compute prewarm (MetalShaderPrewarm.TryCompileCompute, then NoteComputeRefusal) counts a record made under + // the other image binding policy as stale beside graphics_stale, never as a failure, and translates nothing for it. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void TheMetalComputePrewarmCountsARecordOfTheOtherPolicyAsStale(bool stable) + { + var limits = stable ? MetalLimits : default; + using (var list = ShaderPrewarmList.Open(_directory)) + { + Assert.NotNull(list); + var guest = new PipelineTestGuest(Msl); + guest.Host.ShaderPrewarm = list; + guest.Host.ComputeImageDescriptorLimits = limits; + guest.Host.GraphicsImageDescriptorLimits = limits; + guest.RegisterProgram(CodeAddress, HeaderAddress, ImageBindingTestProgram.Code()); + ImageBindingTestProgram.WriteDescriptors(guest, BufferAddress, ImageBindingTestProgram.Partitions[0]); + var cursor = 0u; + guest.Programs.GetOrCompile(guest.Source(CodeAddress, ShaderStage.Compute, + [unchecked((uint)BufferAddress), (uint)(BufferAddress >> 32)]), + PipelineTestGuest.ComputeOptions(), ref cursor, out _); + } + + using var reloaded = ShaderPrewarmList.Open(_directory); + Assert.NotNull(reloaded); + var (record, code) = Assert.Single(reloaded.LoadedComputes()); + var other = new FakeShaderCompiler(Msl); + Assert.False(SharpEmu.Gpu.Metal.V2.MetalShaderPrewarm.TryCompileCompute(record, code, other, stable ? default : MetalLimits, + out _, out var error)); + Assert.Empty(other.Requests); + var stale = SharpEmu.Gpu.Metal.V2.MetalShaderPrewarm.ComputeStale; + var failed = SharpEmu.Gpu.Metal.V2.MetalShaderPrewarm.ComputeFailed; + SharpEmu.Gpu.Metal.V2.MetalShaderPrewarm.NoteComputeRefusal(record, error); + Assert.Equal(stale + 1, SharpEmu.Gpu.Metal.V2.MetalShaderPrewarm.ComputeStale); + Assert.Equal(failed, SharpEmu.Gpu.Metal.V2.MetalShaderPrewarm.ComputeFailed); + + // Any other refusal is still a failure. + SharpEmu.Gpu.Metal.V2.MetalShaderPrewarm.NoteComputeRefusal(record, "the record has no specialization"); + Assert.Equal(stale + 1, SharpEmu.Gpu.Metal.V2.MetalShaderPrewarm.ComputeStale); + Assert.Equal(failed + 1, SharpEmu.Gpu.Metal.V2.MetalShaderPrewarm.ComputeFailed); + } } From 4550b286cc685357833ccb38ec5a938adcc8b7a7 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 11:08:18 +0000 Subject: [PATCH 121/134] [Metal] Keep a colour target rendered past its 1x1 level to its chain ImageRequestBuilders.ColorTarget keeps MipLevel + 1 levels when CB_COLOR_VIEW names a level past the extent's 1x1 level, and MetalImageTransfer.ShapeFor passed them to setMipmapLevelCount: unclamped. A device test shows what Metal does with a 4x4 texture-tiled target drawn at level 3: the test host aborts in -[MTLTextureDescriptorInternal validateWithDevice:] ("requests 4 mipmap levels, but the dimensions (4, 4, 1) can only support a maximum of 3"). As upstream's host does for the same request: the texture keeps the extent's chain (CachedImage MipChainLevels; MetalImageTransfer.HostLevels), transfers leave the guest levels past it out (DropLevelsWithoutHostLevel; PlanColor drops their copies and tiles), and the attachment renders into the texture's last level, also 1x1 (ClampToHostLevels; AcquireColorAttachment clamps the view, so the pass and the written range name that level). ColorTargetLevelSceneTests draws at level 3 of a 64KB_S and a 4KB_S 4x4 target and finds the one texel in guest memory. A render-target-swizzled (64KB_R_X) target past its chain is still refused by the shared request builder on every host (no render-target mip layout for it). --- .../V2/MetalImageTransfer.cs | 18 ++++++- .../V2/MetalRenderHost.Images.cs | 9 ++++ .../Scenes/ColorTargetLevelSceneTests.cs | 52 +++++++++++++++++++ 3 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/Scenes/ColorTargetLevelSceneTests.cs diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageTransfer.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageTransfer.cs index 3664011bd..ea599c9b9 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageTransfer.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalImageTransfer.cs @@ -605,18 +605,29 @@ public MetalTextureShape ShapeFor(in ImageDescription description, uint firstLev // Metal sizes level i of a texture as max(1, width >> i), as the guest does, so a // texture from firstLevel has exactly the extents of the chain's levels from there. + // A description with levels past its extent's 1x1 level (a colour target rendered past + // it, ImageRequestBuilders.ColorTarget) keeps the chain's levels only, as upstream's + // CachedImage does (MipChainLevels): Metal aborts on a texture descriptor with more. return new MetalTextureShape( (ulong)format, (ulong)TextureTypeOf(description), Math.Max(description.Extent.Width >> (int)firstLevel, 1), Math.Max(description.Extent.Height >> (int)firstLevel, 1), description.IsVolume ? description.Extent.Depth : 1, - description.Resources.Levels - firstLevel, + Math.Max(HostLevels(description), firstLevel + 1) - firstLevel, description.IsVolume ? 1 : description.Resources.Layers, description.Samples, (ulong)UsageOf(description, format, SrgbWritable.Value)); } + /// <summary> + /// The guest levels a texture of the description holds: its levels, but none past its extent's 1x1 level. The + /// guest levels after those have no texture level; transfers leave them out (PlanColor). + /// </summary> + internal static uint HostLevels(in ImageDescription description) => + Math.Min(description.Resources.Levels, ImageDescription.FullChainLevels( + description.Extent.Width, description.Extent.Height, description.IsVolume ? description.Extent.Depth : 1)); + public (ulong Start, ulong End) LevelBytes(in ImageDescription description, uint firstLevel) { if (firstLevel == 0 || ImageDescription.IsEmptyRange(description.Data)) @@ -1821,6 +1832,11 @@ private static TransferPlan PlanColor(in ImageDescription description) plan.TexelHeight = element.TexelHeight; } + // Guest levels past the texture's chain (HostLevels) have no texture level to move, as upstream's + // DropLevelsWithoutHostLevel: an upload leaves them out, a download leaves their guest bytes as they are. + var hostLevels = HostLevels(description); + plan.Copies.RemoveAll(copy => copy.Level >= hostLevels); + plan.Tiles.RemoveAll(transfer => transfer.Level >= hostLevels); return plan; } diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Images.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Images.cs index 98b297c83..11f0c052d 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Images.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Images.cs @@ -42,6 +42,15 @@ ColorAttachmentAcquisition IRenderHost.AcquireColorAttachment(in ColorTargetStat imageIdentifier = _imageCache.FindImage(ref request, exactFormat: false); } + // A level past the texture's chain (a colour target rendered past its 1x1 level) renders into the texture's + // last level, which is 1x1 too, as upstream's ClampToHostLevels does: the view, the pass and what it marks + // written name that level. + var hostLevels = MetalImageTransfer.HostLevels(in request.Description); + if (request.View.BaseLevel >= hostLevels && hostLevels != 0) + { + request = request with { View = request.View with { BaseLevel = hostLevels - 1, LevelCount = 1 } }; + } + var metadataClear = _imageCache.TryConsumeDccAttachmentClear( in request, in target.Resolution, out var clearValue); // BeginRendering, or a clear's drain, decides the upload of a CPU-written target. diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ColorTargetLevelSceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ColorTargetLevelSceneTests.cs new file mode 100644 index 000000000..1b52a3860 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/ColorTargetLevelSceneTests.cs @@ -0,0 +1,52 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using Xunit; +using Xunit.Abstractions; + +namespace SharpEmu.Gpu.Metal.Tests.Scenes; + +/// <summary> +/// A colour target rendered at a mip level past its extent's 1x1 level: a 4x4 surface has three levels (4, 2, 1), and +/// CB_COLOR_VIEW names level 3. The request keeps MipLevel + 1 levels (ImageRequestBuilders.ColorTarget), which a Metal +/// texture of that extent cannot have. Upstream's host keeps the texture to its chain (CachedImage: MipLevels clamped to +/// MipChainLevels) and renders such a level into the last level the texture has (ClampToHostLevels), which is 1x1 too. +/// </summary> +public sealed class ColorTargetLevelSceneTests(ITestOutputHelper output) : SceneTestBase(output) +{ + private const uint Size = 4; + private const uint Fmt8888 = 10; + private const uint NtUnorm = 0; + private const uint SurfaceBytes = 0x20000; + + // Texture-tiled colour targets (64KB_S, 4KB_S): their layout covers the level past the chain, so the request reaches + // the host. A render-target-swizzled one (64KB_R_X) is refused by the shared request builder on every host + // (TryGetRenderTargetMipLayout has no layout for it: "The render-target layout is not supported"). + [Theory] + [InlineData(9u)] + [InlineData(5u)] + public void ADrawToALevelPastTheChainRendersIntoTheLastLevel(uint tileMode) + { + using var rig = CreateRig(); + if (rig is null) return; + var target = rig.Memory.Allocate(SurfaceBytes, 0x10000); + rig.Memory.Write(target, new byte[SurfaceBytes]); + var state = new SceneState(1, 1).ColorTarget(0, target, Size, Size, Fmt8888, NtUnorm, tileMode: tileMode, + mipLevel: 3, maxMip: 3, blendBypass: true); + rig.Submit(rig.DrawMesh(new ScenePm4(), state, SceneDraws.Quad(0.5f, 1, 0, 0, 1))); + + // The 1x1 texel the draw wrote lands in the surface's guest bytes once; nothing else does. + var bytes = rig.Read(target, (int)SurfaceBytes); + var red = 0; + var other = 0; + for (var offset = 0; offset < bytes.Length; offset += 4) + { + var word = BitConverter.ToUInt32(bytes, offset); + red += word == 0xFF0000FFu ? 1 : 0; + other += word != 0 && word != 0xFF0000FFu ? 1 : 0; + } + + Assert.Equal(0, other); + Assert.Equal(1, red); + } +} From b30ab2b1e3973ea34840bbd45cc3915f3f8844d6 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 11:21:41 +0000 Subject: [PATCH 122/134] [Metal] Read a bindless heap view's records in runs when comparing them again Port of upstream's bulk heap record reads (VulkanVideoPresenter.BindlessHeap.cs, 7cf0ac568 / 99f9fe930) to MetalRenderHost.HeapRuns.cs: HeapRecordRunEnd, IHeapRunVisitor, VisitHeapRuns and HeapBulkReadsConfigured, same switch (SHARPEMU_HEAP_BULK_READS, default on) and same limits (runs of at most 64 KiB, gaps of at most 1 KiB). RevalidateHeapRegion reads the records of a view's entries one guest read per run instead of one per record; a run that cannot be read clean (a page a recorded GPU write may own, an unmapped one) falls back to ReadHeapRecord for each of its entries, a visit that resolved ends its run so no entry compares bytes read before an earlier resolve, and an R128 view's four words compare as the eight-word T# its entry keeps. Upstream resolves newly marked records one read each, and so does this port. The override is per host (HeapBulkReadsOverride) so a test of one setting never changes another test's host. MetalBindlessHeapRunTests are upstream's BindlessHeapRunTests over the Metal port. Nothing crosses the GPU process split: the reads are the host's own guest-memory reads. --- docs/macos/configuration.md | 1 + .../V2/MetalRenderHost.BindlessHeap.cs | 7 + .../V2/MetalRenderHost.HeapRuns.cs | 204 ++++++++++++ .../MetalBindlessHeapRunTests.cs | 310 ++++++++++++++++++ 4 files changed, 522 insertions(+) create mode 100644 src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.HeapRuns.cs create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/MetalBindlessHeapRunTests.cs diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 74de3fdb6..1a61f7840 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -70,6 +70,7 @@ them for measurements or to isolate a problem. | `SHARPEMU_METAL_MESH_SHADERS` | on | `0` disables mesh pipelines for primitive-shader draws. | | `SHARPEMU_METAL_DRAW_PARAMETERS` | on | `0` turns off draw parameters in translated vertex programs. By default a vertex program's instance index counts from the draw's base instance, and when an indirect draw names a user-data register for its base vertex or start instance, the program counts its vertex index from the base vertex and stores both bases there (the command processor no longer writes those registers). `0` gives the program Metal's ids, which include both bases, and stores nothing. | | `SHARPEMU_METAL_BINDLESS_HEAP` | on | `0` turns off the bindless heap. By default an image or sampler a program reads from a descriptor table at a record only the shader knows is read through the heap: the shader marks the records it reads, the host resolves each marked record's texture or sampler from guest memory, and the program reads it from a later draw on (the first read of a record returns zeros). `0` plans those tables as before (bindless image tables, at most 256 candidates, off-class candidates read null). | +| `SHARPEMU_HEAP_BULK_READS` | on | `0` reads each bindless heap record on its own when the host compares a heap view's records with guest memory again. By default the records of a view are read in runs of nearby records (at most 64 KiB, gaps of at most 1 KiB), one guest read per run; a run that cannot be read (a page a GPU write may still own, an unmapped one) falls back to the per-record read for its records, and a record that resolved ends its run. Same name and default as upstream's switch. | | `SHARPEMU_METAL_STABLE_IMAGE_BINDINGS` | on | `0` gives every program compact image bindings again. By default a program whose images fit Metal's per-stage argument-buffer limits (textures 1M; samplers 996 on Apple7/8, 500K on Apple9+, at most `maxArgumentBufferSamplerCount`) binds one texture per image slot, so one specialization serves every draw however its slots repeat descriptors (fewer shader compiles). Programs over the limits, and bindless, indirect, linked and dynamic-mip ones, keep compact bindings (one texture per distinct descriptor). The setting is part of the shader prewarm stamp: changing it re-prewarms once. | | `SHARPEMU_RUNTIME_IMAGE_SWIZZLE` | on | `0` bakes each storage image's destination select into the translated program, one program per select. By default a store reads the image's channel map from shader data, which the host writes from the bound descriptor. | | `SHARPEMU_METAL_FORMAT_LOAD_COMPONENT_BOUNDS` | on | `0` restores the old bound of a formatted buffer load whose format is fixed at translation: the whole element had to fit below the buffer's size. By default each selected component is checked at its own address, wrapping past 2^32 as on the hardware, so a component that wraps to the buffer's start is read, and the load reads its constants only when a selected component is out of range. An element that fits whole still takes one compare. Loads whose format is read at run time always check per component. | diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessHeap.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessHeap.cs index 7e2a9afb9..950c26c3d 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessHeap.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.BindlessHeap.cs @@ -391,6 +391,13 @@ private void ReleaseIdleHeapViews(ulong serial) // The entries of one view, in record order, compared with their records now: a changed record is resolved again. private void RevalidateHeapRegion(HeapRegionEntries entries, ulong serial) { + if (HeapBulkReadsActive) + { + // Records read in runs (MetalRenderHost.HeapRuns.cs, SHARPEMU_HEAP_BULK_READS). + RevalidateHeapRegionInRuns(entries, serial); + return; + } + entries.ValidatedSerial = serial; Span<uint> words = stackalloc uint[8]; foreach (var entry in entries.Order.ToArray()) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.HeapRuns.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.HeapRuns.cs new file mode 100644 index 000000000..0f9cacf0b --- /dev/null +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.HeapRuns.cs @@ -0,0 +1,204 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Runtime.InteropServices; +using SharpEmu.Libs.VideoOut; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.Gpu.Metal.V2; + +// Bulk heap record reads, upstream's VulkanVideoPresenter.BindlessHeap.cs (VisitHeapRuns, 7cf0ac568 / 99f9fe930): +// revalidation reads the records of a view's entries in runs, one guest read per run of nearby records, instead of one +// read per record. SHARPEMU_HEAP_BULK_READS=0 reads each record on its own, as before. A run that cannot be read (a page +// a recorded GPU write may still own, an unmapped one) falls back to the per-record read of each of its entries, which +// waits for such a write, so every entry compares the words its own read would return. +internal sealed partial class MetalRenderHost +{ + internal static readonly bool HeapBulkReadsConfigured = Environment.GetEnvironmentVariable("SHARPEMU_HEAP_BULK_READS") != "0"; + + // Tests set it on their own host, so a test of one setting never changes another test's host. + internal bool? HeapBulkReadsOverride; + + internal bool HeapBulkReadsActive => HeapBulkReadsOverride ?? HeapBulkReadsConfigured; + + // A run spans at most this many bytes and skips at most HeapRunGapBytes between two records it reads. + internal const uint HeapRunMaxBytes = 64 << 10; + internal const uint HeapRunGapBytes = 1 << 10; + + private byte[]? _heapRunBytes; + + // Run reads that succeeded and runs that fell back to per-record reads, for tests. + internal long HeapRunReads, HeapRunFallbacks; + + // The end (exclusive) of the run of sorted record indexes that starts at start: every index in it is below records, + // the run spans at most HeapRunMaxBytes, and no two neighbors are more than HeapRunGapBytes of records apart. + internal static int HeapRecordRunEnd(ReadOnlySpan<uint> indexes, int start, uint recordBytes, uint records) + { + var first = indexes[start]; + var last = first; + var end = start + 1; + while (end < indexes.Length) + { + var next = indexes[end]; + if (next >= records || (ulong)(next - last) * recordBytes > HeapRunGapBytes + recordBytes || + ((ulong)next - first + 1) * recordBytes > HeapRunMaxBytes) + { + break; + } + + last = next; + end++; + } + + return end; + } + + // What revalidation in runs reads and visits: the host implements it over its views, guest memory and entries + // (HeapRunVisitor); tests implement it over fakes. + internal interface IHeapRunVisitor + { + // The view's heap as it is now: a resolve may move it. + BindlessHeapDescriptor Heap(bool sampler); + + bool TryRead(ulong address, Span<byte> destination); + + // The record of the entry at position, read on its own as ReadHeapRecord reads it; the word count. + int ReadRecord(int position, Span<uint> words); + + // Compares the entry at position with words and resolves it again when they changed; true when it did. + bool Visit(int position, ReadOnlySpan<uint> words); + } + + // Visits the entries at positions [from, to) of one heap view, whose sorted record indexes are indexes, each with the + // words of its record. Records are read in runs (HeapRecordRunEnd) into buffer. A visit that resolved ends its run: the + // next entry starts a new one, read after that resolve, with the heap as the resolve left it, so no entry compares + // bytes read before an earlier entry's resolve, and buffer is never read across one. A run that cannot be read falls + // back to one read per entry, each right before its visit. Entries past the heap's records get no words, as + // ReadHeapRecord gives them. + internal static void VisitHeapRuns<T>(ref T visitor, ReadOnlySpan<uint> indexes, int from, int to, bool sampler, + Span<byte> buffer, Span<uint> scratch) where T : IHeapRunVisitor + { + indexes = indexes[..to]; + var start = from; + while (start < to) + { + var heap = visitor.Heap(sampler); + var bytes = heap.DescriptorBytes; + if (heap.Base == 0 || indexes[start] >= heap.Records) + { + _ = visitor.Visit(start, ReadOnlySpan<uint>.Empty); + start++; + continue; + } + + // The records of a heap are its stride apart; each holds the descriptor in its first bytes. + var stride = Math.Max(heap.Stride, bytes); + var end = HeapRecordRunEnd(indexes, start, stride, heap.Records); + var first = indexes[start]; + var run = buffer[..checked((int)(((ulong)indexes[end - 1] - first) * stride + bytes))]; + if (!visitor.TryRead(heap.Base + (ulong)first * stride, run)) + { + for (; start < end; start++) + { + _ = visitor.Visit(start, scratch[..visitor.ReadRecord(start, scratch)]); + } + + continue; + } + + while (start < end) + { + var offset = checked((int)((indexes[start] - first) * stride)); + var resolved = visitor.Visit(start, MemoryMarshal.Cast<byte, uint>(run.Slice(offset, (int)bytes))); + start++; + if (resolved) + { + break; + } + } + } + } + + // The host's side of VisitHeapRuns, over the entries of one view in record order: the view's descriptors are its + // heap's records, a stride apart (BindlessHeapViewTable.Region.Descriptors). + private readonly struct HeapRunVisitor(MetalRenderHost owner, HeapEntry[] order, BindlessHeapViewTable.Region region) : IHeapRunVisitor + { + public BindlessHeapDescriptor Heap(bool sampler) => region.Descriptors with { Sampler = sampler }; + + public bool TryRead(ulong address, Span<byte> destination) + { + // The bytes as the per-record read's first attempt sees them; a run any GPU write may still own falls back. + var read = owner.TryReadResidentGuestBytes(address, destination, clean: true); + if (read) + { + owner.HeapRunReads++; + } + else + { + owner.HeapRunFallbacks++; + } + + return read; + } + + public int ReadRecord(int position, Span<uint> words) => owner.ReadHeapRecord(order[position], words); + + public bool Visit(int position, ReadOnlySpan<uint> words) => owner.RevalidateHeapEntry(order[position], words); + } + + // The entries of one view, in record order, compared with their records read in runs (HeapRecordRunEnd). + private void RevalidateHeapRegionInRuns(HeapRegionEntries entries, ulong serial) + { + entries.ValidatedSerial = serial; + // Every entry of a view's list holds that view's region while the view keeps it. + if (entries.Order.Find(static entry => entry.Region is not null)?.Region is not { } region) + { + return; + } + + var order = entries.Order.ToArray(); + var records = new uint[order.Length]; + for (var position = 0; position < order.Length; position++) + { + records[position] = order[position].Index - region.View.First; + } + + Span<uint> scratch = stackalloc uint[8]; + var visitor = new HeapRunVisitor(this, order, region); + VisitHeapRuns(ref visitor, records, 0, order.Length, region.Heap.Sampler, + (_heapRunBytes ??= new byte[HeapRunMaxBytes]).AsSpan(), scratch); + } + + // One entry compared with the words of its record (RevalidateHeapRegion's step): resolved again when they changed, or + // when it had no texture the last time; true when it was resolved. + private bool RevalidateHeapEntry(HeapEntry entry, ReadOnlySpan<uint> words) + { + if (entry.Region is null || !_heapEntries.TryGetValue((entry.Slot, entry.Index), out var current) || + !ReferenceEquals(current, entry)) + { + // Released by a resolve of an earlier entry (the view lost its run). + return false; + } + + // An R128 T# is its four words; the rest of the T# is zero. + Span<uint> extended = stackalloc uint[8]; + if (words.Length == 4 && entry.Region is { Heap: { Sampler: false, R128: true } }) + { + extended.Clear(); + words.CopyTo(extended); + words = extended; + } + + // A T# that had no texture when it was last looked at (its memory was not mapped) is looked at again. + if (words.SequenceEqual(entry.Words) && + (entry.Resolved || entry.Slot >= BindlessHeap.ImageKinds.Length || + HeapRecordClass(entry, words) == ImageNumericClass.Unsupported)) + { + return false; + } + + entry.Words = words.ToArray(); + ResolveHeapEntry(entry); + return true; + } +} diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalBindlessHeapRunTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalBindlessHeapRunTests.cs new file mode 100644 index 000000000..b64fcea87 --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalBindlessHeapRunTests.cs @@ -0,0 +1,310 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +// Bindless heap revalidation reads sorted records in runs (MetalRenderHost.HeapRecordRunEnd, MetalRenderHost.HeapRuns.cs), +// as upstream's host does (tests/SharpEmu.Libs.Tests/VideoOut/BindlessHeapRunTests.cs, same cases over the Metal port). +public sealed class MetalBindlessHeapRunTests +{ + private const uint ImageBytes = BindlessHeap.ImageRecordBytes; + + [Fact] + public void ARunKeepsRepeatedAndNearbyRecordsAndEndsAtAGap() + { + var gapRecords = MetalRenderHost.HeapRunGapBytes / ImageBytes; + uint[] indexes = [3, 3, 4, 4 + gapRecords + 1, 4 + gapRecords + 1 + gapRecords + 2]; + Assert.Equal(4, MetalRenderHost.HeapRecordRunEnd(indexes, 0, ImageBytes, 49152)); + // 37 skips 32 records after 4 (the gap limit) and stays; 71 skips 33 after 37 and starts its own run. + Assert.Equal(4, MetalRenderHost.HeapRecordRunEnd(indexes, 3, ImageBytes, 49152)); + Assert.Equal(5, MetalRenderHost.HeapRecordRunEnd(indexes, 4, ImageBytes, 49152)); + } + + [Fact] + public void ARunEndsBeforeTheRecordsTheHeapHasNot() + { + uint[] indexes = [10, 11, 12, 13]; + Assert.Equal(2, MetalRenderHost.HeapRecordRunEnd(indexes, 0, ImageBytes, 12)); + } + + [Fact] + public void ARunSpansAtMostTheRunLimit() + { + var limitRecords = MetalRenderHost.HeapRunMaxBytes / ImageBytes; + var indexes = Enumerable.Range(0, (int)limitRecords + 5).Select(static index => (uint)index).ToArray(); + Assert.Equal((int)limitRecords, MetalRenderHost.HeapRecordRunEnd(indexes, 0, ImageBytes, uint.MaxValue)); + } + + // Any sorted set of indexes splits into runs that cover it once each, and every run obeys the limits. + [Theory] + [InlineData(1, 16u)] + [InlineData(2, 32u)] + [InlineData(3, 16u)] + [InlineData(4, 32u)] + public void RunsPartitionSortedIndexesWithinTheLimits(int seed, uint recordBytes) + { + var random = new System.Random(seed); + var indexes = Enumerable.Range(0, 3000).Select(_ => (uint)random.Next(0, 49152)).Order().ToArray(); + var start = 0; + while (start < indexes.Length) + { + var end = MetalRenderHost.HeapRecordRunEnd(indexes, start, recordBytes, 49152); + Assert.True(end > start); + Assert.True(((ulong)indexes[end - 1] - indexes[start] + 1) * recordBytes <= MetalRenderHost.HeapRunMaxBytes); + for (var at = start + 1; at < end; at++) + { + Assert.True((ulong)(indexes[at] - indexes[at - 1]) * recordBytes <= MetalRenderHost.HeapRunGapBytes + recordBytes); + } + + if (end < indexes.Length) + { + var next = indexes[end]; + Assert.True((ulong)(next - indexes[end - 1]) * recordBytes > MetalRenderHost.HeapRunGapBytes + recordBytes || + ((ulong)next - indexes[start] + 1) * recordBytes > MetalRenderHost.HeapRunMaxBytes); + } + + start = end; + } + } + + private const ulong MemoryBase = 0x10000; + + // Guest memory as a byte array from MemoryBase, and one heap in it; every visit is kept with its words. + private sealed class FakeHeap(byte[] memory, ulong heapBase, uint records, uint[] indexes, bool sampler, bool r128 = false) + : MetalRenderHost.IHeapRunVisitor + { + public ulong Base = heapBase; + public uint Records = records; + public bool FailRunReads; + public int RunReads; + public int RecordReads; + public readonly List<(int Position, uint[] Words)> Visits = new(); + // Runs on each visit; true means the visit resolved. + public Func<int, bool> OnVisit = _ => false; + public readonly uint RecordBytes = new BindlessHeapDescriptor(sampler, 0, 0, 0, 0, r128).DescriptorBytes; + // The records of a table are larger than the descriptor each one starts with. + private uint? _stride; + public uint Stride { get => _stride ?? RecordBytes; set => _stride = value; } + + public BindlessHeapDescriptor Heap(bool samplerHeap) => new(samplerHeap, Base, Records, Stride, 0, r128); + + public bool TryRead(ulong address, Span<byte> destination) + { + RunReads++; + return !FailRunReads && Read(address, destination); + } + + public int ReadRecord(int position, Span<uint> words) + { + RecordReads++; + var index = indexes[position]; + var count = (int)(RecordBytes / sizeof(uint)); + return Base != 0 && index < Records && + Read(Base + (ulong)index * Stride, System.Runtime.InteropServices.MemoryMarshal.AsBytes(words[..count])) ? count : 0; + } + + public bool Visit(int position, ReadOnlySpan<uint> words) + { + Visits.Add((position, words.ToArray())); + return OnVisit(position); + } + + // What one read of the record at index returns now. + public uint[] RecordWords(uint index) + { + var words = new uint[RecordBytes / sizeof(uint)]; + return Base != 0 && index < Records && + Read(Base + (ulong)index * Stride, System.Runtime.InteropServices.MemoryMarshal.AsBytes(words.AsSpan())) ? words : []; + } + + private bool Read(ulong address, Span<byte> destination) + { + if (address < MemoryBase || address - MemoryBase + (ulong)destination.Length > (ulong)memory.Length) return false; + memory.AsSpan((int)(address - MemoryBase), destination.Length).CopyTo(destination); + return true; + } + } + + private static byte[] Pattern(int bytes, int seed) + { + var memory = new byte[bytes]; + new System.Random(seed).NextBytes(memory); + return memory; + } + + private static void Visit(FakeHeap heap, uint[] indexes, bool sampler, byte[] buffer) + { + Span<uint> scratch = stackalloc uint[8]; + MetalRenderHost.VisitHeapRuns(ref heap, indexes, 0, indexes.Length, sampler, buffer, scratch); + } + + // Every entry is visited once, in order, with the words its own read returns, from far fewer reads. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void RunsVisitEveryEntryOnceInOrderWithItsRecordWords(bool sampler) + { + var memory = Pattern(0x40000, 7); + var random = new System.Random(3); + var indexes = Enumerable.Range(0, 600).Select(_ => (uint)random.Next(0, 4000)).Order().ToArray(); + var heap = new FakeHeap(memory, MemoryBase + 0x100, 4000, indexes, sampler); + Visit(heap, indexes, sampler, new byte[MetalRenderHost.HeapRunMaxBytes]); + Assert.Equal(Enumerable.Range(0, indexes.Length), heap.Visits.Select(visit => visit.Position)); + for (var at = 0; at < indexes.Length; at++) + { + Assert.Equal(heap.RecordWords(indexes[at]), heap.Visits[at].Words); + } + + Assert.True(heap.RunReads < indexes.Length / 4); + Assert.Equal(0, heap.RecordReads); + } + + // The descriptors of a heap view are a record stride apart (a table of 440-byte records, each starting with its T#): + // a run reads from the first record's descriptor to the last one's, and each entry takes its own record's words. + [Theory] + [InlineData(false)] + [InlineData(true)] + public void RunsOverATablesRecordsReadEachRecordsDescriptor(bool sampler) + { + var memory = Pattern(0x40000, 17); + uint[] indexes = [0, 1, 2, 3, 5, 5, 8, 40, 47, 48]; + var heap = new FakeHeap(memory, MemoryBase + 0x40, 49, indexes, sampler) { Stride = 440 }; + Visit(heap, indexes, sampler, new byte[MetalRenderHost.HeapRunMaxBytes]); + Assert.Equal(Enumerable.Range(0, indexes.Length), heap.Visits.Select(visit => visit.Position)); + for (var at = 0; at < indexes.Length; at++) + { + Assert.Equal(heap.RecordWords(indexes[at]), heap.Visits[at].Words); + } + + // Records 0..8 are one run; 40 and 47 are each more than the gap from the record before. + Assert.Equal(3, heap.RunReads); + Assert.Equal(0, heap.RecordReads); + } + + // A view of 16-byte T#s (R128) takes the four words of each record's descriptor, in a table and in a heap of packed + // descriptors, where the records are 16 bytes apart. + [Theory] + [InlineData(440u)] + [InlineData(16u)] + public void RunsOverR128DescriptorsReadSixteenBytesOfEachRecord(uint stride) + { + var memory = Pattern(0x40000, 23); + uint[] indexes = [0, 1, 2, 3, 5, 8, 47, 48]; + var heap = new FakeHeap(memory, MemoryBase + 0x40, 49, indexes, sampler: false, r128: true) { Stride = stride }; + Visit(heap, indexes, false, new byte[MetalRenderHost.HeapRunMaxBytes]); + Assert.Equal(Enumerable.Range(0, indexes.Length), heap.Visits.Select(visit => visit.Position)); + for (var at = 0; at < indexes.Length; at++) + { + Assert.Equal(4, heap.Visits[at].Words.Length); + Assert.Equal(heap.RecordWords(indexes[at]), heap.Visits[at].Words); + } + + Assert.Equal(0, heap.RecordReads); + } + + // A resolve may land bytes over later records of its run: the entries after it read them after it. + [Fact] + public void AResolveRereadsTheRestOfItsRun() + { + var memory = Pattern(0x10000, 11); + uint[] indexes = [0, 1, 2, 3]; + var heap = new FakeHeap(memory, MemoryBase, 64, indexes, sampler: false); + heap.OnVisit = position => + { + if (position != 1) return false; + memory.AsSpan((int)(2 * heap.RecordBytes), (int)heap.RecordBytes).Fill(0xAB); + return true; + }; + Visit(heap, indexes, sampler: false, new byte[MetalRenderHost.HeapRunMaxBytes]); + Assert.Equal(4, heap.Visits.Count); + Assert.All(heap.Visits[2].Words, word => Assert.Equal(0xABABABABu, word)); + Assert.Equal(heap.RecordWords(3), heap.Visits[3].Words); + Assert.Equal(2, heap.RunReads); + } + + // A nested revalidation inside a resolve may reuse the run buffer: no entry after the resolve reads it as it was. + [Fact] + public void ARunBufferOverwrittenDuringAResolveIsReadAgain() + { + var memory = Pattern(0x10000, 13); + uint[] indexes = [4, 5, 6, 7]; + var buffer = new byte[MetalRenderHost.HeapRunMaxBytes]; + var heap = new FakeHeap(memory, MemoryBase, 64, indexes, sampler: false); + heap.OnVisit = position => + { + if (position != 0) return false; + buffer.AsSpan().Fill(0x5A); + return true; + }; + Visit(heap, indexes, sampler: false, buffer); + for (var at = 0; at < indexes.Length; at++) + { + Assert.Equal(heap.RecordWords(indexes[at]), heap.Visits[at].Words); + } + } + + // A run that cannot be read is visited one record read at a time, each right before its visit. + [Fact] + public void AnUnreadableRunFallsBackToOneReadPerEntry() + { + var memory = Pattern(0x10000, 17); + uint[] indexes = [1, 2, 2, 9]; + var heap = new FakeHeap(memory, MemoryBase, 64, indexes, sampler: true) { FailRunReads = true }; + heap.OnVisit = position => + { + if (position != 1) return false; + memory.AsSpan((int)(9 * heap.RecordBytes), (int)heap.RecordBytes).Fill(0x11); + return true; + }; + Visit(heap, indexes, sampler: true, new byte[MetalRenderHost.HeapRunMaxBytes]); + Assert.Equal(4, heap.RecordReads); + for (var at = 0; at < indexes.Length; at++) + { + Assert.Equal(heap.RecordWords(indexes[at]), heap.Visits[at].Words); + } + + Assert.All(heap.Visits[3].Words, word => Assert.Equal(0x11111111u, word)); + } + + // Records the heap does not hold, and every record of a heap at address zero, get no words. + [Fact] + public void RecordsPastTheHeapGetNoWords() + { + var memory = Pattern(0x10000, 19); + uint[] indexes = [1, 3, 5, 9]; + var heap = new FakeHeap(memory, MemoryBase, 4, indexes, sampler: false); + Visit(heap, indexes, sampler: false, new byte[MetalRenderHost.HeapRunMaxBytes]); + Assert.Equal(heap.RecordWords(1), heap.Visits[0].Words); + Assert.Equal(heap.RecordWords(3), heap.Visits[1].Words); + Assert.Empty(heap.Visits[2].Words); + Assert.Empty(heap.Visits[3].Words); + + var unplaced = new FakeHeap(memory, 0, 64, indexes, sampler: false); + Visit(unplaced, indexes, sampler: false, new byte[MetalRenderHost.HeapRunMaxBytes]); + Assert.All(unplaced.Visits, visit => Assert.Empty(visit.Words)); + Assert.Equal(0, unplaced.RunReads); + } + + // A resolve that moves the heap: the entries after it read their records at the new base. + [Fact] + public void AMovedHeapIsReadAtItsNewBaseAfterAResolve() + { + var memory = Pattern(0x20000, 23); + uint[] indexes = [0, 1, 2]; + var heap = new FakeHeap(memory, MemoryBase, 64, indexes, sampler: false); + heap.OnVisit = position => + { + if (position != 0) return false; + heap.Base = MemoryBase + 0x10000; + return true; + }; + Visit(heap, indexes, sampler: false, new byte[MetalRenderHost.HeapRunMaxBytes]); + Assert.Equal(heap.RecordWords(1), heap.Visits[1].Words); + Assert.Equal(heap.RecordWords(2), heap.Visits[2].Words); + Assert.NotEqual(heap.Visits[1].Words, new FakeHeap(memory, MemoryBase, 64, indexes, sampler: false).RecordWords(1)); + } +} From 8962deaf5a91491df2364b255ad22c98f735d857 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 11:21:41 +0000 Subject: [PATCH 123/134] [Shader] Mark a heap record once per block in MSL, as the SPIR-V translator does Gen5SpirvTranslator.MarkHeapRecord leaves out a mark of a record already marked in the same block under the same EXEC (_markedHeapRecords), relying on SPIR-V value numbering to see the same index id. The MSL heap emission re-derived the record index and emitted the guarded atomic for every read. Gen5MslTranslator.HeapMarks.cs keeps, per guest block, the record index of a use (key, view, immediate), the element index of a numeric class and the marks emitted, while their scope stays open (Line follows the braces), no line wrote the indirect key's scratch, and the earlier mark covered these lanes (EXEC known full, or no line since wrote EXEC). A block start, a jump target and CaptureLines (lines placed elsewhere) drop everything kept. A repeated read of the same record in a block reuses the index and leaves the mark out. MetalBindlessHeapTests: ARecordReadTwiceInABlockIsMarkedOnce (one mark in the source of a block that samples the record twice) and the device test EveryLaneReadsTheElementOfItsRecordAndMarksIt over that program (every texel and mark as with one read). --- .../Gen5MslTranslator.BindlessHeap.cs | 29 +++- .../Gen5MslTranslator.ControlFlow.cs | 1 + .../Gen5MslTranslator.HeapMarks.cs | 145 ++++++++++++++++++ .../Gen5MslTranslator.LaneMasks.cs | 3 + .../Gen5MslTranslator.cs | 1 + .../MetalBindlessHeapTests.cs | 30 +++- 6 files changed, 203 insertions(+), 6 deletions(-) create mode 100644 src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.HeapMarks.cs diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.BindlessHeap.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.BindlessHeap.cs index 5c125e44c..db3ea078d 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.BindlessHeap.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.BindlessHeap.cs @@ -67,6 +67,19 @@ private string HeapFeedbackWord(string index) => // (past its records, or not at its descriptor's offset in a record) takes the null element, and no index is past // the table whatever the view's words say. private string HeapRecordIndex(HeapRecordUse use) + { + // The same use's index, still in scope and unchanged, is the same value (HeapMarks). + if (TryKeptHeapRecordIndex(use, out var keptIndex)) + { + return keptIndex; + } + + var index = NewHeapRecordIndex(use); + KeepHeapRecordIndex(use, index); + return index; + } + + private string NewHeapRecordIndex(HeapRecordUse use) { var key = _indirectKeyScratch.TryGetValue(use.KeyMemoryIndex, out var scratch) ? scratch : "0u"; var viewDword = _request.Bindings.HeapViewsDword + (uint)use.View * HeapView.DwordCount; @@ -102,15 +115,27 @@ private string HeapImageIndex(string index, int slot, ImageNumericClass numericC return index; } + if (TryKeptHeapClassIndex(index, slot, numericClass, out var keptIndex)) + { + return keptIndex; + } + var elementClass = HeapElementClass(index); - return Temp("uint", + var classIndex = Temp("uint", $"{elementClass} == {HeapLiteral(BindlessHeap.ClassCode(numericClass))} ? {index} : {HeapLiteral(BindlessHeap.CallRecordNullIndex)}"); + KeepHeapClassIndex(index, slot, numericClass, classIndex); + return classIndex; } // Sets the element's bit in its array's mark words, for the lanes the guest runs; a plain read first keeps marked - // elements from repeating the atomic. + // elements from repeating the atomic. A mark an earlier one in the same block already covers is left out (HeapMarks). private void MarkHeapElement(int slot, string index) { + if (HeapMarkCovered(slot, index)) + { + return; + } + var word = Temp("uint", $"{HeapLiteral((uint)slot * BindlessHeap.FeedbackWordsPerArray)} + ({index} >> 5u)"); var bit = Temp("uint", $"1u << ({index} & 31u)"); var feedback = HeapFeedbackWord(word); diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.ControlFlow.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.ControlFlow.cs index a8bf77fe2..9e59f6d61 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.ControlFlow.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.ControlFlow.cs @@ -79,6 +79,7 @@ private bool TryEmitBlocks(IReadOnlyList<ShaderBlock> blocks, out string error) { _body.Clear(); _indent = 0; + ForgetHeapMarks(); if (!TryEmitBlockBody(blocks, index, out var terminator, out error)) { error = $"block=0x{blocks[index].StartPc:X}: {error}"; diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.HeapMarks.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.HeapMarks.cs new file mode 100644 index 000000000..a3ead16c9 --- /dev/null +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.HeapMarks.cs @@ -0,0 +1,145 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Text.RegularExpressions; +using SharpEmu.ShaderCompiler.Resources; + +namespace SharpEmu.ShaderCompiler.Metal; + +// Heap marks within a block, the MSL form of the SPIR-V translator's MarkHeapRecord dedup (Gen5SpirvTranslator.Resources.cs, +// _markedHeapRecords): a record a read marked is not marked again by a later read of the same record in the same +// straight-line code, under the same EXEC. SPIR-V finds "the same record" through its value numbering (the same index id +// within a block); MSL has none, so the record index of a use (its key, view and immediate) and the element index of a +// numeric class are kept while they are in scope and their inputs are unchanged, and a mark is left out when: +// - the earlier mark's scope is still open (it ran before this point on every path here), +// - the index is the same temp (the same value), +// - and the earlier mark covered these lanes: it ran with EXEC known full, or no line since wrote EXEC. +// Every guest block starts with nothing kept (TryEmitBlocks), as does every jump target, and lines captured to be placed +// elsewhere (CaptureLines) drop everything kept, so no kept mark or index crosses code it does not dominate. +public static partial class Gen5MslTranslator +{ + private sealed partial class CompilationContext + { + // The scopes open where the body is being emitted, innermost last; 0 is the block's own scope. + private readonly List<int> _heapScopes = [0]; + private int _heapScopeSerial; + // Bumped by every line that may write EXEC. + private int _heapExecSerial; + + private readonly Dictionary<(int Slot, string Index), (int Scope, bool Full, int Exec)> _heapMarks = []; + private readonly Dictionary<(int Key, int View, uint Immediate), (string Index, int Scope)> _heapRecordIndexes = []; + private readonly Dictionary<(string Index, int Slot, ImageNumericClass Class), (string Index, int Scope)> _heapClassIndexes = []; + + // A write to EXEC (=, &=, |=, ^=, not ==) and a write to an indirect key's scratch. + private static readonly Regex HeapExecWrite = new(@"(^|[^A-Za-z0-9_.])exec\s*[&|^]?=(?!=)", RegexOptions.CultureInvariant); + private static readonly Regex HeapJumpTarget = new(@"^\s*(case\b|default\s*:|[A-Za-z_][A-Za-z0-9_]*\s*:(?!:))", RegexOptions.CultureInvariant); + + private int HeapScope => _heapScopes[^1]; + + private bool HeapScopeOpen(int scope) => _heapScopes.Contains(scope); + + // Nothing kept: a new block, a jump target, or lines moved elsewhere. + private void ForgetHeapMarks() + { + _heapMarks.Clear(); + _heapRecordIndexes.Clear(); + _heapClassIndexes.Clear(); + _heapScopes.Clear(); + _heapScopes.Add(0); + _heapExecSerial++; + } + + // Follows the scopes, EXEC writes, key writes and jump targets of each line the body takes (Line). + private void NoteHeapLine(string text) + { + if (_heapMarks.Count == 0 && _heapRecordIndexes.Count == 0 && _heapClassIndexes.Count == 0) + { + // Nothing kept: only the scopes matter, and they restart with the next kept entry's scope. + _heapScopes.Clear(); + _heapScopes.Add(0); + return; + } + + if (text.Contains('\n') || HeapJumpTarget.IsMatch(text)) + { + ForgetHeapMarks(); + return; + } + + var trimmed = text.Trim(); + if (trimmed.StartsWith('}')) + { + if (_heapScopes.Count > 1) + { + _heapScopes.RemoveAt(_heapScopes.Count - 1); + } + else + { + // A scope closed that opened before anything was kept. + ForgetHeapMarks(); + return; + } + } + + if (trimmed.EndsWith('{')) + { + _heapScopes.Add(++_heapScopeSerial); + } + + if (trimmed.Contains("exec", StringComparison.Ordinal) && HeapExecWrite.IsMatch(trimmed)) + { + _heapExecSerial++; + } + + if (trimmed.StartsWith("indirect_image_key", StringComparison.Ordinal)) + { + _heapRecordIndexes.Clear(); + _heapClassIndexes.Clear(); + } + } + + // The record index a use took earlier in this scope, unchanged since. + private bool TryKeptHeapRecordIndex(HeapRecordUse use, out string index) + { + if (_heapRecordIndexes.TryGetValue((use.KeyMemoryIndex, use.View, use.Immediate), out var kept) && HeapScopeOpen(kept.Scope)) + { + index = kept.Index; + return true; + } + + index = string.Empty; + return false; + } + + private void KeepHeapRecordIndex(HeapRecordUse use, string index) => + _heapRecordIndexes[(use.KeyMemoryIndex, use.View, use.Immediate)] = (index, HeapScope); + + private bool TryKeptHeapClassIndex(string index, int slot, ImageNumericClass numericClass, out string classIndex) + { + if (_heapClassIndexes.TryGetValue((index, slot, numericClass), out var kept) && HeapScopeOpen(kept.Scope)) + { + classIndex = kept.Index; + return true; + } + + classIndex = string.Empty; + return false; + } + + private void KeepHeapClassIndex(string index, int slot, ImageNumericClass numericClass, string classIndex) => + _heapClassIndexes[(index, slot, numericClass)] = (classIndex, HeapScope); + + // True when an earlier mark of the element at index already covers this one; otherwise this mark is kept. + private bool HeapMarkCovered(int slot, string index) + { + if (_heapMarks.TryGetValue((slot, index), out var kept) && HeapScopeOpen(kept.Scope) && + (kept.Full || kept.Exec == _heapExecSerial)) + { + return true; + } + + _heapMarks[(slot, index)] = (HeapScope, _execKnownFull, _heapExecSerial); + return false; + } + } +} diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.LaneMasks.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.LaneMasks.cs index 89ffe3d47..ff614764c 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.LaneMasks.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.LaneMasks.cs @@ -124,6 +124,8 @@ private string[] CaptureLines(Func<bool> emit, out bool ok) var start = _body.Length; var indent = _indent; _indent = 0; + // The captured lines are placed elsewhere: nothing kept for heap marks crosses them (HeapMarks). + ForgetHeapMarks(); try { ok = emit(); @@ -131,6 +133,7 @@ private string[] CaptureLines(Func<bool> emit, out bool ok) finally { _indent = indent; + ForgetHeapMarks(); } var captured = _body.ToString(start, _body.Length - start); diff --git a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs index 7579c31db..f54e603e3 100644 --- a/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs +++ b/src/SharpEmu.ShaderCompiler.Metal/Gen5MslTranslator.cs @@ -4748,6 +4748,7 @@ private string ApplyByteBias(int bindingIndex, string byteAddress) => private void Line(string text) { + NoteHeapLine(text); for (var index = 0; index < _indent; index++) { _body.Append(" "); diff --git a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalBindlessHeapTests.cs b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalBindlessHeapTests.cs index 17532d9f4..4aeed5fa4 100644 --- a/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalBindlessHeapTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Metal.Tests/MetalBindlessHeapTests.cs @@ -43,6 +43,11 @@ public sealed class MetalBindlessHeapTests(ITestOutputHelper output) // (s_lshl_b32 s100, s100, 4; s_buffer_load_dwordx4 s[28:31], s[8:11], s100). private static uint[] HeapSampler() => Patch(Sample, (4, 0xF40C0300), (5, 0xFA000040), (24, 0x8F648464), (26, 0xF4280704), (27, 0xC8000000)); + // The sample twice in the waterfall's block (the image_sample_l at 29-30 repeated after it, the loop's + // s_cbranch_execnz moved back two words: -15), reading the same record under the same EXEC. + private static uint[] DoubleSample() => + [.. Sample[..31], Sample[29], Sample[30], .. Patch(Sample, (33, 0xBF89FFF1))[31..]]; + private static uint[] Patch(uint[] words, params (int Index, uint Word)[] patches) { var patched = words.ToArray(); @@ -245,14 +250,31 @@ private static void AssertLane(uint[] result, int pass, int lane, int key, uint[ } } - // Record e holds texture (e * 37) % 64, except every seventh, whose element is null; keys past the view read the null - // element. Every read element is marked, and nothing else. + // A record read twice in one block under the same EXEC is marked once, as the SPIR-V translator's MarkHeapRecord + // leaves out a repeated mark within a block (HeapMarks): the second read reuses the first one's record index. [Fact] - public void EveryLaneReadsTheElementOfItsRecordAndMarksIt() + public void ARecordReadTwiceInABlockIsMarkedOnce() + { + static int Count(string source, string text) => (source.Length - source.Replace(text, string.Empty, StringComparison.Ordinal).Length) / text.Length; + const string Mark = "atomic_fetch_or_explicit(&sharpemu_resources.heap_feedback["; + Assert.True(Gen5MslTranslator.TryCompileProgram(Request(Sample, bindlessHeap: true, out _), out var single, out var error), error); + Assert.True(Gen5MslTranslator.TryCompileProgram(Request(DoubleSample(), bindlessHeap: true, out _), out var twice, out error), error); + Assert.Equal(1, Count(single!.Source, Mark)); + Assert.Equal(1, Count(twice!.Source, Mark)); + Assert.Equal(2 * Count(single.Source, ".sample("), Count(twice.Source, ".sample(")); + } + + // Record e holds texture (e * 37) % 64, except every seventh, whose element is null; keys past the view read the null + // element. Every read element is marked, and nothing else; also when the block reads each record twice and marks it + // once (ARecordReadTwiceInABlockIsMarkedOnce). + [Theory] + [InlineData(false)] + [InlineData(true)] + public void EveryLaneReadsTheElementOfItsRecordAndMarksIt(bool twice) { if (!DeviceGate()) return; - var request = Request(Sample, bindlessHeap: true, out var snapshot); + var request = Request(twice ? DoubleSample() : Sample, bindlessHeap: true, out var snapshot); var slot = BindlessHeap.ImageSlot(ImageDescriptorBinding.ForImage(request.Resources.Info.Images[0])!.Value); Assert.Equal(BindlessHeap.VolumeLayerSlot, slot); var textures = Enumerable.Range(0, 64) From f2f9d8daa309514bec50fae619d41d14a33f5911 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 11:34:18 +0000 Subject: [PATCH 124/134] [Tests] Heap scene tests: bulk reads on and off, pixel stage, depth compare, R128 BindlessHeapSceneTests through the whole Metal host: - the rewritten-record test runs with SHARPEMU_HEAP_BULK_READS on and off (per host override) and checks that only the bulk setting reads runs; - a pixel shader's waterfall reads a heap record into every pixel of a target from its second draw on; - a depth-compare read (image_sample_c_l) of records naming linear R32F textures gets a depth view and compares its reference with each depth; - an R128 read (MIMG bit 15) of 32-byte records takes the 2D texture the first four words name, whatever the other four hold; and a one-layer 2D-array record reads its texture. An R128 T# has no array fields: ResourceMaterializer.ValidImageDescriptor takes only 1D/2D/2D-MSAA for it, so an R128 2D-array record reads null by design. A table of 16-byte T#s loaded with s_buffer_load_dwordx4 is not planned as a heap (TryPlanHeapRecord takes an eight-word image handle, as upstream's does). --- .../Scenes/BindlessHeapSceneTests.cs | 158 +++++++++++++++++- 1 file changed, 156 insertions(+), 2 deletions(-) diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/BindlessHeapSceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/BindlessHeapSceneTests.cs index fedc19611..9572f1356 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/BindlessHeapSceneTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/BindlessHeapSceneTests.cs @@ -32,6 +32,34 @@ public sealed class BindlessHeapSceneTests(ITestOutputHelper output) : SceneTest // (s_lshl_b32 s100, s100, 4; s_buffer_load_dwordx4 s[28:31], s[8:11], s100): a heap sampler record. private static readonly uint[] SamplerProgram = Patch(Program, (4, 0xF40C0300), (5, 0xFA000040), (24, 0x8F648464), (26, 0xF4280704), (27, 0xC8000000)); + // image_sample_l v[20:23], v[4:6], s[12:19], s[28:31] dmask:0xf dim:2D r128 (MIMG bit 15; lod v6 = 1.0, which a + // 1x1 texture clamps to level 0): the sample reads only the first four words of the eight the record load reads. An + // R128 T# has no array fields, so it names a 1D or 2D image only (ResourceMaterializer.ValidImageDescriptor); a + // table of 16-byte T#s loaded with s_buffer_load_dwordx4 is not planned as a heap (TryPlanHeapRecord takes an image + // handle of eight loaded words, as upstream's does). + private static readonly uint[] R128Program = Patch(Program, (29, 0xF0908F08)); + + // A depth-compare read: v4 = 0.35 (the reference), v5/v6 = 0.5, v7 = layer 1, v8 = lod 0 (the four v_movs replaced + // by five, two words longer before the loop, so the loop's branch keeps its offset), then + // image_sample_c_l v20, v[4:8], s[12:19], s[28:31] dmask:0x1 dim:2D_ARRAY. + private const float CompareReference = 0.35f; + private static readonly uint[] CompareProgram = + [ + .. Program[..15], 0x7E0802FF, BitConverter.SingleToUInt32Bits(CompareReference), 0x7E0A02F0, 0x7E0C02F0, 0x7E0E02F2, 0x7E100280, + .. Patch(Program, (29, 0xF0B00128))[19..], + ]; + + // The waterfall in a pixel shader (wave64, assembled with llvm-mc for gfx1030): user data s[0:1] the block, every + // pixel's key the dword at +0x14000 of the V# at block + 0x20, the texel exported to mrt0. + private static readonly uint[] PixelProgram = + [ + 0xF4080200, 0xFA000010, 0xF4080600, 0xFA000020, 0xF4080700, 0xFA000030, 0xBF8CC07F, 0x7E0202FF, + 0x00014000, 0xE0301000, 0x80060201, 0xBF8C3F70, 0x2C160484, 0x7E0802F0, 0x7E0A02F0, 0x7E0C02F2, + 0x7E0E0280, 0xBE86047E, 0x7E260281, 0x7EC8050B, 0xBE94047E, 0x7DA41664, 0x8F648564, 0x7E260280, + 0xF42C0304, 0xC8000000, 0xBF8CC07F, 0xF0900F28, 0x00E31404, 0xBEFE0414, 0x7DAA2680, 0xBF89FFF3, + 0xBEFE0406, 0xBF8C3F70, 0xF800180F, 0x17161514, 0xBF810000, + ]; + private static uint[] Patch(uint[] words, params (int Index, uint Word)[] patches) { var patched = words.ToArray(); @@ -191,11 +219,16 @@ public void ADispatchThatReadsTheHeapIsNeverReplayed() } } - [Fact] - public void ResolvedElementsStayAcrossDispatchesAndARewrittenRecordTakesItsNewTexture() + // The same under both ways of reading the view's records when it is compared again: in runs + // (SHARPEMU_HEAP_BULK_READS, MetalRenderHost.HeapRuns.cs) and one record at a time. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void ResolvedElementsStayAcrossDispatchesAndARewrittenRecordTakesItsNewTexture(bool bulkReads) { using var rig = CreateRig(); if (rig is null) return; + rig.Host.HeapBulkReadsOverride = bulkReads; const int textures = 4; var heap = Build(rig, textures, records: 8, tableRecords: 8); var lowKeys = Enumerable.Range(0, Lanes).Select(lane => lane % 4).ToArray(); @@ -232,6 +265,9 @@ public void ResolvedElementsStayAcrossDispatchesAndARewrittenRecordTakesItsNewTe { AssertTexel(last[lane], Expected(lowKeys[lane] == 1 ? 3 : lowKeys[lane] % textures), $"rewritten lane {lane} key {lowKeys[lane]}"); } + + // The comparison read the records in runs only when bulk reads are on. + Assert.Equal(bulkReads, rig.Host.HeapRunReads + rig.Host.HeapRunFallbacks > 0); } [Fact] @@ -303,4 +339,122 @@ public void AHeapSamplerRecordFiltersWithTheSamplerItNames() AssertTexel(result[lane], keys[lane] % 2 == 0 ? point : linear, $"lane {lane} sampler record {keys[lane]}"); } } + // Records of eight-word T#s of a one-layer 2D array. + [Fact] + public void AOneLayerRecordReadsItsTexture() + { + using var rig = CreateRig(); + if (rig is null) return; + const int textures = 4; + const int records = 8; + var heap = Build(rig, textures, records, tableRecords: records); + for (var record = 0; record < records; record++) + { + rig.Memory.Write<uint>(heap.Table + (ulong)record * RecordBytes, + Descriptors.Texture(heap.Textures[record % textures], Rgba8, 1, 1, type: Type2DArray)); + } + + var keys = Enumerable.Range(0, Lanes).Select(lane => lane * 3 % records).ToArray(); + _ = Pass(rig, heap, keys); + var result = Pass(rig, heap, keys); + for (var lane = 0; lane < Lanes; lane++) + { + AssertTexel(result[lane], Expected(keys[lane] % textures), $"lane {lane} one-layer record {keys[lane]}"); + } + } + + // An R128 read of a heap record: the record's first four words name a 2D texture and the host takes the rest of the + // T# as zero, whatever the record's other four words hold (all ones: reserved bits set, a base array past the last + // one, so a host that read them would find no texture). + [Theory] + [InlineData(true)] + [InlineData(false)] + public void AnR128RecordReadsTheTextureItsFourWordsName(bool onesAfter) + { + using var rig = CreateRig(); + if (rig is null) return; + const int textures = 4; + const int records = 8; + var heap = Build(rig, textures, records, tableRecords: records); + for (var record = 0; record < records; record++) + { + rig.Memory.Write<uint>(heap.Table + (ulong)record * RecordBytes, + [.. Descriptors.Texture(heap.Textures[record % textures], Rgba8, 1, 1)[..4], .. Enumerable.Repeat(onesAfter ? 0xFFFFFFFFu : 0u, 4)]); + } + + var keys = Enumerable.Range(0, Lanes).Select(lane => lane * 3 % records).ToArray(); + _ = Pass(rig, heap, keys, R128Program); + var result = Pass(rig, heap, keys, R128Program); + for (var lane = 0; lane < Lanes; lane++) + { + AssertTexel(result[lane], Expected(keys[lane] % textures), $"lane {lane} R128 record {keys[lane]}"); + } + } + + // T# DST_SEL (R, 0, 0, 1), the swizzle a depth texture carries (ShadowSceneTests.DepthSwizzle). + private const uint DepthSwizzle = 4 | (0 << 3) | (0 << 6) | (1 << 9); + + // A depth-compare read of a heap record: each record names a linear R32F texture of one depth (0.1, 0.3, 0.5, 0.7), + // which the host gives a depth view, and the sampler's Less compares the reference 0.35 with it: 1 where the + // reference is below the texel, 0 elsewhere. + [Fact] + public void ADepthCompareRecordComparesTheReferenceWithItsDepth() + { + using var rig = CreateRig(); + if (rig is null) return; + const int textures = 4; + const int records = 8; + var heap = Build(rig, textures, records, tableRecords: records); + static float Depth(int texture) => 0.1f + 0.2f * texture; + var depths = new ulong[textures]; + for (var texture = 0; texture < textures; texture++) + { + depths[texture] = rig.Memory.Allocate(TextureBytes, TextureBytes); + rig.Memory.Write<float>(depths[texture], Enumerable.Repeat(Depth(texture), TextureBytes / 4).ToArray()); + } + + for (var record = 0; record < records; record++) + { + rig.Memory.Write<uint>(heap.Table + (ulong)record * RecordBytes, + Descriptors.Texture(depths[record % textures], 22, 1, 1, type: Type2DArray, depthOrLastLayer: 1, dstSelect: DepthSwizzle)); + } + + rig.Memory.Write<uint>(heap.Block + 0x30, Descriptors.Sampler(depthCompare: CompareFunc.Less)); + var keys = Enumerable.Range(0, Lanes).Select(lane => lane * 5 % records).ToArray(); + _ = Pass(rig, heap, keys, CompareProgram); + var result = Pass(rig, heap, keys, CompareProgram); + for (var lane = 0; lane < Lanes; lane++) + { + var expected = CompareReference < Depth(keys[lane] % textures) ? 1f : 0f; + Assert.True(result[lane][0] == expected, $"lane {lane} record {keys[lane]}: compared {result[lane][0]}, expected {expected}"); + } + } + // A pixel shader reads a heap record: its first draw marks the record, and a later draw reads the record's texture + // into every pixel. + [Fact] + public void APixelShaderReadsTheTextureOfAHeapRecord() + { + using var rig = CreateRig(); + if (rig is null) return; + const uint size = 8; + const int textures = 4; + const int key = 5; + var heap = Build(rig, textures, records: 8, tableRecords: 8); + rig.Memory.Write<uint>(heap.Output + KeyOffset, [key << 4]); + float[] Draw() + { + var target = rig.ColorTarget(size, size, 16); + var state = new SceneState(size, size).ColorTarget(0, target, size, size, format: 14, numberType: 7); + rig.Submit(rig.DrawMesh(new ScenePm4(), state, SceneDraws.Quad(0.5f, 0, 0, 0), PixelProgram, + [Descriptors.Lo(heap.Block), Descriptors.Hi(heap.Block)])); + return System.Runtime.InteropServices.MemoryMarshal.Cast<byte, float>(rig.ReadImage(target, size, size, 16)).ToArray(); + } + + _ = Draw(); + var pixels = Draw(); + for (var pixel = 0; pixel < size * size; pixel++) + { + AssertTexel(pixels.AsSpan(pixel * 4, 4).ToArray(), Expected(key % textures), $"pixel {pixel}"); + } + } } From 536cd8bc5a722c7bf9a86305b2f7bf3f20e66ae5 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 13:05:56 +0000 Subject: [PATCH 125/134] [GPU] Give the provider's ahead and retry resolutions their interface signatures again The upstream merge added an optional gpuThreadCounts parameter to ShaderPipelineCache.ResolveComputeProgramAhead and to GetComputeProgram(banks, ..., retry). IShaderPipelineProvider gives both members default bodies, so the class methods compiled, kept passing the tests that call the class, and stopped implementing the members: through the interface every dispatch resolved ahead was refused as unsupported (Demon's Souls: 0 of 9803 dispatch jobs taken, against 23013 of 23662 on main), and a dispatch with a retry took the legacy path past the kept programs. Both public forms now have exactly the members' signatures; the form with the thread-count flag is private. InterfaceDefaultShadowTests fails for any class method that shares a name with an interface member the class leaves to its default. --- .../Gpu/Pipelines/ShaderPipelineCache.cs | 16 +++- .../InterfaceDefaultShadowTests.cs | 79 +++++++++++++++++++ 2 files changed, 91 insertions(+), 4 deletions(-) create mode 100644 tests/SharpEmu.Gpu.Metal.Tests/InterfaceDefaultShadowTests.cs diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs index 58061af06..113fbb87f 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderPipelineCache.cs @@ -2310,8 +2310,15 @@ public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitia bool gpuThreadCounts) => GetComputeProgram(banks, dispatchInitiator, dimensionX, dimensionY, dimensionZ, indirect, retry: null, gpuThreadCounts); + // Each public form below has exactly the interface member's signature: IShaderPipelineProvider gives these members + // default bodies, so a form with one more (even optional) parameter would not implement its member and the default + // would answer for it (InterfaceDefaultShadowTests). public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitiator, uint dimensionX, uint dimensionY, uint dimensionZ, bool indirect, - ComputeProgramRetry? retry, bool gpuThreadCounts = false) => + ComputeProgramRetry? retry) => + GetComputeProgram(banks, dispatchInitiator, dimensionX, dimensionY, dimensionZ, indirect, retry, gpuThreadCounts: false); + + private ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitiator, uint dimensionX, uint dimensionY, uint dimensionZ, bool indirect, + ComputeProgramRetry? retry, bool gpuThreadCounts) => GetComputeProgramKept(banks, dispatchInitiator, dimensionX, dimensionY, dimensionZ, indirect | gpuThreadCounts, retry, ahead: false, out _, gpuThreadCounts)!; @@ -2320,9 +2327,10 @@ public ComputeProgram GetComputeProgram(RegisterBanks banks, uint dispatchInitia // frontend may turn into an image copy, or that is unavailable, is refused, so the dispatch resolves it as before. // The kept programs it reads and updates are this thread's own. public ComputeProgram? ResolveComputeProgramAhead(RegisterBanks banks, uint dispatchInitiator, uint dimensionX, uint dimensionY, - uint dimensionZ, bool indirect, out ComputePrefetchRefusal refusal, bool gpuThreadCounts = false) => - GetComputeProgramKept(banks, dispatchInitiator, dimensionX, dimensionY, dimensionZ, indirect | gpuThreadCounts, retry: null, ahead: true, - out refusal, gpuThreadCounts); + uint dimensionZ, bool indirect, out ComputePrefetchRefusal refusal) => + // A dispatch whose thread counts the GPU writes is never resolved ahead (RenderExecutor.Compute). + GetComputeProgramKept(banks, dispatchInitiator, dimensionX, dimensionY, dimensionZ, indirect, retry: null, ahead: true, + out refusal, gpuThreadCounts: false); private ComputeProgram? GetComputeProgramKept(RegisterBanks banks, uint dispatchInitiator, uint dimensionX, uint dimensionY, uint dimensionZ, bool indirect, ComputeProgramRetry? retry, bool ahead, out ComputePrefetchRefusal refusal, bool gpuThreadCounts) diff --git a/tests/SharpEmu.Gpu.Metal.Tests/InterfaceDefaultShadowTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/InterfaceDefaultShadowTests.cs new file mode 100644 index 000000000..c4304c47f --- /dev/null +++ b/tests/SharpEmu.Gpu.Metal.Tests/InterfaceDefaultShadowTests.cs @@ -0,0 +1,79 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Reflection; +using SharpEmu.Gpu.Metal.V2; +using SharpEmu.Libs.Gpu.Rendering; +using Xunit; + +namespace SharpEmu.Gpu.Metal.Tests; + +/// <summary> +/// The engine's host and provider interfaces give most members a default body, so a host only implements what it +/// supports. That makes one mistake silent: a class method that is meant to implement such a member but whose +/// signature differs (an added optional parameter, a changed type) compiles, is called by code that holds the class, +/// and is never called through the interface, which answers with the default instead. Upstream sync f1af467a6 did +/// that to ShaderPipelineCache.ResolveComputeProgramAhead: every dispatch resolved ahead was refused as unsupported. +/// </summary> +public sealed class InterfaceDefaultShadowTests +{ + [Fact] + public void NoClassMethodSharesANameWithAnInterfaceDefaultItDoesNotImplement() + { + var assemblies = new[] { typeof(MetalRenderHost).Assembly, typeof(IShaderPipelineProvider).Assembly } + .Concat(typeof(MetalRenderHost).Assembly.GetReferencedAssemblies() + .Where(name => name.Name!.StartsWith("SharpEmu.", StringComparison.Ordinal)) + .Select(Assembly.Load)) + .Distinct() + .ToArray(); + const BindingFlags Declared = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; + var shadows = new List<string>(); + foreach (var type in assemblies.SelectMany(TypesOf).Where(type => type is { IsClass: true, IsAbstract: false })) + { + foreach (var contract in type.GetInterfaces().Where(contract => assemblies.Contains(contract.Assembly))) + { + var map = type.GetInterfaceMap(contract); + // By base definition: an override implements the member its base method does. + var targets = new HashSet<MethodInfo>(map.TargetMethods.Select(target => target.GetBaseDefinition())); + for (var index = 0; index < map.InterfaceMethods.Length; index++) + { + // The default body answers for this member: the class implements nothing for it. + if (map.TargetMethods[index].DeclaringType != contract) + { + continue; + } + + var member = map.InterfaceMethods[index]; + for (var declaring = type; declaring is not null && declaring != typeof(object); declaring = declaring.BaseType) + { + foreach (var method in declaring.GetMethods(Declared)) + { + if (method.Name == member.Name && !targets.Contains(method.GetBaseDefinition())) + { + shadows.Add($"{type.FullName}.{method.Name}({Parameters(method)}) does not implement " + + $"{contract.Name}.{member.Name}({Parameters(member)}), which answers with its default"); + } + } + } + } + } + } + + Assert.True(shadows.Count == 0, string.Join(Environment.NewLine, shadows.Distinct().Order(StringComparer.Ordinal))); + } + + private static IEnumerable<Type> TypesOf(Assembly assembly) + { + try + { + return assembly.GetTypes(); + } + catch (ReflectionTypeLoadException error) + { + return error.Types.Where(type => type is not null)!; + } + } + + private static string Parameters(MethodInfo method) => + string.Join(", ", method.GetParameters().Select(parameter => parameter.ParameterType.Name)); +} From c2abc04b28bf74ac94c67df83bd226c4a0673824 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 14:43:30 +0000 Subject: [PATCH 126/134] [Metal] Read a posted word copy's pending bytes ahead of the worker and without a GPU wait A posted word copy (TryPostWordCopy, new in the upstream sync) is a command-processor write: a pending GPU write whose bytes the command-processor overlay holds until it lands. The resolve threads' readers knew only pending copies, so every draw resolved ahead that read the copied table abandoned (~500 a frame in Demon's Souls) and was resolved again on the worker, whose clean reads of the table waited for the GPU (~11 waits a frame). Off the worker, a word, a clean word and a proof's compared range a GPU write owns are now read from the overlay when it covers them whole (no image, no pending label), the rest of the word's line kept like a copied line, with the owned answer dropped and the range kept for the take's write-log test, as a copy read. The worker's clean read takes the overlay before waiting. SHARPEMU_METAL_V2_CONCURRENT_OVERLAY_READS=0 restores the old behaviour. --- .../V2/MetalPendingWriteOverlay.cs | 108 ++++++++++++++++ .../V2/MetalRenderHost.ConcurrentResolve.cs | 25 +++- .../V2/MetalRenderHost.CopyReads.cs | 115 +++++++++++++++++- .../V2/MetalRenderHost.Pipelines.cs | 5 +- ...ldingTests.PendingCommandProcessorReads.cs | 83 +++++++++++++ 5 files changed, 331 insertions(+), 5 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalPendingWriteOverlay.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalPendingWriteOverlay.cs index 604c36933..bf52a0337 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalPendingWriteOverlay.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalPendingWriteOverlay.cs @@ -344,6 +344,114 @@ public MetalOverlayCoverage Coverage(ulong address, ulong size, Func<ulong> comp } } } + /// <summary> + /// <see cref="Coverage"/> and <see cref="Apply"/> at one moment, for a range of up to 64 bytes: true when the + /// pending writes cover every byte of it, with <paramref name="destination"/> holding their bytes, oldest first. + /// A forget or a retire from another thread cannot fall between the test and the read. False leaves + /// <paramref name="destination"/> partly written, for the caller to discard. + /// </summary> + public bool TryReadCovered(ulong address, Span<byte> destination, Func<ulong> completedSerial) + { + var size = (ulong)destination.Length; + if (size == 0 || size > 64 || Count == 0 || !MayOverlap(address, size)) + { + return false; + } + + lock (_gate) + { + if (!AnyOverlapLocked(address, size)) + { + return false; + } + + RetireOverlappingLocked(address, size, completedSerial()); + var collect = new CollectVisitor(); + ForEachOverlapping(address, size, ref collect); + if (collect.Entries is not { } entries) + { + return false; + } + + entries.Sort(static (left, right) => left.Sequence.CompareTo(right.Sequence)); + ulong covered = 0; + foreach (var entry in entries) + { + var start = Math.Max(address, entry.Address); + var end = Math.Min(address + size, entry.End); + for (var at = start; at < end; at++) + { + if (!entry.IsDead(at - entry.Address)) + { + destination[(int)(at - address)] = entry.Bytes[at - entry.Address]; + covered |= 1UL << (int)(at - address); + } + } + } + + return covered == (size == 64 ? ulong.MaxValue : (1UL << (int)size) - 1); + } + } + + /// <summary> + /// <see cref="TryReadCovered"/> for each aligned dword of a range of up to 256 bytes, at one moment: bit i of the + /// result is set when the pending writes cover all four bytes of dword i, whose bytes <paramref name="destination"/> + /// then holds. The bytes of a dword whose bit is clear are left partly written, for the caller to discard. + /// </summary> + public ulong ReadCoveredWords(ulong address, Span<byte> destination, Func<ulong> completedSerial) + { + var size = (ulong)destination.Length; + if (size == 0 || size > 256 || ((address | size) & 3) != 0 || Count == 0 || !MayOverlap(address, size)) + { + return 0; + } + + Span<ulong> covered = stackalloc ulong[4]; + lock (_gate) + { + if (!AnyOverlapLocked(address, size)) + { + return 0; + } + + RetireOverlappingLocked(address, size, completedSerial()); + var collect = new CollectVisitor(); + ForEachOverlapping(address, size, ref collect); + if (collect.Entries is not { } entries) + { + return 0; + } + + entries.Sort(static (left, right) => left.Sequence.CompareTo(right.Sequence)); + foreach (var entry in entries) + { + var start = Math.Max(address, entry.Address); + var end = Math.Min(address + size, entry.End); + for (var at = start; at < end; at++) + { + if (!entry.IsDead(at - entry.Address)) + { + var offset = (int)(at - address); + destination[offset] = entry.Bytes[at - entry.Address]; + covered[offset >> 6] |= 1UL << (offset & 63); + } + } + } + } + + ulong words = 0; + for (var word = 0; word < (int)(size >> 2); word++) + { + var offset = word * sizeof(uint); + if (((covered[offset >> 6] >> (offset & 63)) & 0xF) == 0xF) + { + words |= 1UL << word; + } + } + + return words; + } + /// <summary>Writes the pending bytes over <paramref name="destination"/>, oldest first.</summary> public void Apply(ulong address, Span<byte> destination) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs index b782e1582..b4001d543 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs @@ -1341,6 +1341,18 @@ private bool TryReadGuestWordConcurrentTested(ulong address, out uint word, Conc return true; } + if (TryReadPendingCommandProcessorBytesConcurrent(address, bytes, assumptions)) + { + assumptions.Forget(ConcurrentQuery.Word, address, sizeof(uint), answers); + word = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(bytes); + if ((address & 3) == 0 && ConcurrentWordLines) + { + FillOverlayLine(assumptions, address & ~lineMask); + } + + return true; + } + // The source tests overwrote the owner; the abandon is the word's. _lastConcurrentOwner = owner; } @@ -1433,6 +1445,13 @@ private bool TryReadCleanGuestWordConcurrent(ulong address, out uint word, Concu return true; } + if (TryReadPendingCommandProcessorBytesConcurrent(address, bytes, assumptions)) + { + assumptions.Forget(ConcurrentQuery.Resident, address, sizeof(uint), answers); + word = System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(bytes); + return true; + } + _lastConcurrentOwner = owner; Interlocked.Increment(ref _cleanReadsAbandoned); NoteAbandonCause(address, sizeof(uint)); @@ -1521,7 +1540,8 @@ private unsafe bool TryCompareResidentGuestBytesConcurrent( // (IsConcurrentResolveStillCurrent) tests every word compared here as it would the words read. A range a GPU write // owns is read through the pending copy that writes all of it, as TryReadGuestWordConcurrentTested reads each of its // words (TryReadThroughPendingCopyConcurrent: that copy the latest write over the range, its source owned by - // nothing, the source's answers recorded, the range's owned answer dropped), and compared there: any word of the + // nothing, the source's answers recorded, the range's owned answer dropped), or as the pending command-processor + // write that covers all of it (TryReadPendingCommandProcessorBytesConcurrent, likewise), and compared there: any word of the // range read alone finds that same copy, since a later write over it would be the range's latest. Any other owned // range refuses the compare, its owned answer dropped: the caller then reads the words itself, recording their own // answers. Then the other ranges' bytes, where they lie. @@ -1556,7 +1576,8 @@ private bool TryCompareGuestWordsConcurrent(ReadOnlySpan<ulong> addresses, ReadO { var before = assumptions.Answers.Count; var bytes = through[..length]; - if (TryReadThroughPendingCopyConcurrent(address, bytes, assumptions)) + if (TryReadThroughPendingCopyConcurrent(address, bytes, assumptions) || + TryReadPendingCommandProcessorBytesConcurrent(address, bytes, assumptions)) { if (owned) { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CopyReads.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CopyReads.cs index 78321e284..57abe0afd 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CopyReads.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.CopyReads.cs @@ -616,7 +616,120 @@ private string TakeCopyReadCounters() => $" copy_read_pending={Interlocked.Exchange(ref _copyReadPending, 0)}" + $" copy_read_order={Interlocked.Exchange(ref _copyReadOrder, 0)}" + $" copy_read_none={Interlocked.Exchange(ref _copyReadNone, 0)}" + - $" concurrent_copy_reads={Interlocked.Exchange(ref _concurrentCopyReads, 0)}"; + $" concurrent_copy_reads={Interlocked.Exchange(ref _concurrentCopyReads, 0)}" + + $" concurrent_overlay_reads={Interlocked.Exchange(ref _concurrentOverlayReads, 0)}" + + $" clean_overlay_reads={Interlocked.Exchange(ref _cleanOverlayReads, 0)}"; + + /// <summary> + /// SHARPEMU_METAL_V2_CONCURRENT_OVERLAY_READS=0 abandons a resolution off the worker that reads a word a pending + /// command-processor write owes, as before, and lets the worker's clean read of such a word wait for the GPU. + /// A posted word copy (TryPostWordCopy) is such a write: Demon's Souls posts ~120 a frame, among them the 3 KB table + /// its draws read (see ConcurrentCopyReads), and every draw resolved ahead that read it was abandoned and resolved + /// again on the worker (~500 a frame), whose own clean reads of it waited for the GPU (~11 waits, ~12 ms a frame). + /// </summary> + internal bool ConcurrentOverlayReads { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_CONCURRENT_OVERLAY_READS") != "0"; + + private long _concurrentOverlayReads; + private long _cleanOverlayReads; + + /// <summary> + /// Off the worker: a word a recorded GPU write owns, read as the bytes a command-processor write recorded ahead of + /// the draw still owes there, the way the worker reads it (TryReadGuest answers from the overlay before any wait). + /// The overlay speaks only for bytes no write recorded after it covers (each such write forgets them before it is + /// logged), so bytes it covers whole are the ones the draw sees, landed by the take or not. No image the GPU drew + /// into may own them, and no pending label (the worker reads labels first). Like a copy read, the word's owned + /// answer is dropped by the caller and the range kept for the take's write-log test: a write logged after the + /// resolution began over these bytes refuses it. + /// </summary> + private bool TryReadPendingCommandProcessorBytesConcurrent(ulong address, Span<byte> destination, ConcurrentAssumptions assumptions) + { + if (!ConcurrentOverlayReads || _cpOverlay.Count == 0) + { + return false; + } + + var size = (ulong)destination.Length; + var serial = assumptions.Serial; + if (size == 0 || size > ConcurrentWordLineBytes || address > ulong.MaxValue - size || + (_imageCache.MayOwn(address, size) && _imageCache.HasGpuModifiedImageBytes(address, size)) || + (_labelOverlay.Count != 0 && _labelOverlay.Coverage(address, size, serial) != MetalOverlayCoverage.None)) + { + return false; + } + + // Up to 64 bytes byte by byte; a longer range (a compared range of a proof, up to a line) in whole words. + var covered = size <= 64 + ? _cpOverlay.TryReadCovered(address, destination, serial) + : ((address | size) & 3) == 0 && + _cpOverlay.ReadCoveredWords(address, destination, serial) == (size == 256 ? ulong.MaxValue : (1UL << (int)(size / 4)) - 1); + if (!covered) + { + return false; + } + + Interlocked.Increment(ref _concurrentOverlayReads); + assumptions.NoteCopiedThrough(address, size); + return true; + } + + /// <summary> + /// Right after a word was read from a pending command-processor write (TryPendingCommandProcessorBytesConcurrent), the + /// other words of its line that the same reading would answer are read into the resolution's copy line, and later + /// reads of them take the bytes from there (TryReadGuestWordConcurrent), as FillCopyLine does for a pending copy. + /// A resolution reads a posted table word by word (Demon's Souls: ~100 words a draw, ~500 draws a frame), and each + /// word's own tests and overlay read took the overlay's lock. Each word kept is what that reading returns now: + /// - owned by a recorded GPU write (the line's pending word mask), and by nothing tested before it: no write the + /// command thread queued for this job, no image the GPU drew into over the line; + /// - covered whole by the overlay, with no pending label over the line; + /// all read while the record stamp and the ownership versions stand (checked before and after). The line is kept + /// for the take's write-log test like a copied line: a write logged after the resolution began refuses it. + /// </summary> + private void FillOverlayLine(ConcurrentAssumptions assumptions, ulong line) + { + assumptions.CopyLine = ulong.MaxValue; + const ulong size = ConcurrentWordLineBytes; + var versions = OwnershipVersions(); + var stamp = _gpuWrites.MutationStamp; + if ((stamp & 1) != 0 || PendingCommandWriteHolds(line, size) || + (_imageCache.MayOwn(line, size) && _imageCache.HasGpuModifiedImageBytes(line, size)) || + (_labelOverlay.Count != 0 && _labelOverlay.Coverage(line, size, assumptions.Serial) != MetalOverlayCoverage.None) || + !_gpuWrites.TryPendingWordMask(line, assumptions.Serial(), out var pending, out var maskStamp) || maskStamp != stamp) + { + return; + } + + var words = _cpOverlay.ReadCoveredWords(line, assumptions.CopyLineBytes, assumptions.Serial) & pending; + if (words == 0 || _gpuWrites.MutationStamp != stamp || OwnershipVersions() != versions) + { + return; + } + + assumptions.NoteCopiedThrough(line, size); + assumptions.CopyLine = line; + assumptions.CopyLineWords = words; + assumptions.CopyLineStamp = stamp; + assumptions.CopyLineVersions = versions; + } + + /// <summary> + /// On the worker: a clean read of a word a recorded GPU write owns, answered from a pending command-processor write + /// that covers it whole instead of waiting for the GPU (TryReadGuest's order). False: the caller waits as before. + /// </summary> + private bool TryReadPendingCommandProcessorBytes(ulong address, Span<byte> destination) + { + if (!ConcurrentOverlayReads || _cpOverlay.Count == 0 || + (_imageCache.MayOwn(address, (ulong)destination.Length) && _imageCache.HasGpuModifiedImageBytes(address, (ulong)destination.Length)) || + !_cpOverlay.TryReadCovered(address, destination, _completedSerialReader ??= () => CompletedSerial)) + { + return false; + } + + Interlocked.Increment(ref _cleanOverlayReads); + Interlocked.Increment(ref _overlayReads); + NotePendingAnswer(address, destination.Length); + return true; + } private void WriteCopyReadTraces() { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs index f18189718..745bd1e01 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs @@ -2047,7 +2047,8 @@ public bool TryReadCleanGuestWord(ulong address, out uint word) } // A recorded GPU write still landing in the word is ahead of the draw being resolved, which on the GPU reads the - // word after it: read through the write's copy, or after waiting for it (TryReadGuestCore), the value the draw + // word after it: read as the command-processor write that owes it, through the write's copy, or after waiting + // for it (TryReadPendingCommandProcessorBytes, then TryReadGuestCore), the value the draw // sees. Neither the stale backing (one resource branch kept on the worker, both on the resolver: bd5c2009a) nor a // refusal (both paths kept: the path the shader does not take had its descriptor read from whatever that memory // held, floats in Demon's Souls, which fataled as an invalid image) is that value. The resolving thread reads it @@ -2061,7 +2062,7 @@ public bool TryReadCleanGuestWord(ulong address, out uint word) } Interlocked.Increment(ref _cleanReadsLanded); - if (!TryReadGuestCore(address, bytes)) + if (!TryReadPendingCommandProcessorBytes(address, bytes) && !TryReadGuestCore(address, bytes)) { return false; } diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.PendingCommandProcessorReads.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.PendingCommandProcessorReads.cs index dc44b83e3..345161c5c 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.PendingCommandProcessorReads.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.PendingCommandProcessorReads.cs @@ -74,6 +74,89 @@ public void AWriteDataInsideAnOpenPassIsReadAsWrittenWithoutEndingThePassOrWaiti Assert.Equal(0x5EC0DD00u, BitConverter.ToUInt32(after)); } + // A command-processor write recorded outside a pass (a posted word copy, in Demon's Souls the 3 KB table its draws + // read) is a pending GPU write over its bytes. A draw resolved ahead of the worker reads them as written, as the worker + // does, instead of abandoning; the worker's clean read takes them without waiting for the GPU. A GPU write recorded + // after the resolution began over those bytes refuses it at the take. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void OwedBytesUnderAPendingWriteAreReadAsWrittenAheadOfTheWorkerAndOnIt(bool overlayReads) + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + host.ConcurrentOverlayReads = overlayReads; + rig.WriteBacking32(TableAddress, 0x0BAD0BAD); + rig.WriteBacking32(TableAddress + 4, 0x0BAD0BAD); + rig.WriteBacking32(TableAddress + 8, 0x22222222); + host.RecordCommandProcessorWrite(TableAddress, BitConverter.GetBytes(0xC0FFEE22_C0FFEE11UL), "word copy"); + var serial = host.SubmissionSerial; + Assert.Equal(0x0BAD0BADu, rig.ReadBacking32(TableAddress)); + + var concurrent = (IConcurrentResolveHost)host; + concurrent.BeginConcurrentResolve(); + object assumptions; + try + { + if (!overlayReads) + { + // As before: the word's owner is the recorded write, which no pending copy explains. + Assert.Throws<SharpEmu.Libs.Gpu.Scheduling.GpuFatal.AbandonedWorkException>(() => host.TryReadGuestWord(TableAddress, out _)); + Assert.Throws<SharpEmu.Libs.Gpu.Scheduling.GpuFatal.AbandonedWorkException>(() => host.TryReadCleanGuestWord(TableAddress, out _)); + return; + } + + Assert.True(host.TryReadGuestWord(TableAddress, out var word)); + Assert.Equal(0xC0FFEE11u, word); + // The rest of the line: the write's other word as written (from the line read with the first), and a word + // no write owns as memory holds it. + Assert.True(host.TryReadGuestWord(TableAddress + 4, out var second)); + Assert.Equal(0xC0FFEE22u, second); + Assert.True(host.TryReadGuestWord(TableAddress + 8, out var unowned)); + Assert.Equal(0x22222222u, unowned); + // A proof's compare of the range sees the bytes as written too, not as memory holds them. + ulong[] addresses = [TableAddress]; + int[] lengths = [8]; + Assert.True(host.TryCompareGuestWords(addresses, lengths, BitConverter.GetBytes(0xC0FFEE22_C0FFEE11UL))); + Assert.False(host.TryCompareGuestWords(addresses, lengths, BitConverter.GetBytes(0x0BAD0BAD_0BAD0BADUL))); + Assert.True(host.TryReadCleanGuestWord(TableAddress, out var clean)); + Assert.Equal(0xC0FFEE11u, clean); + } + finally + { + assumptions = concurrent.EndConcurrentResolve(); + if (!overlayReads) + { + concurrent.ReleaseAssumptions(assumptions); + } + } + + try + { + // The owned answers are dropped, as for a copy read; the take stands while nothing is written over the word. + Assert.DoesNotContain(((MetalRenderHost.ConcurrentAssumptions)assumptions).Answers, answer => answer.Owned); + Assert.True(concurrent.IsStillCurrent(assumptions)); + + // The worker reads the same bytes, without waiting for the write to land. + Assert.True(host.TryReadCleanGuestWord(TableAddress, out var worker)); + Assert.Equal(0xC0FFEE11u, worker); + Assert.True(host.CompletedSerial < serial, "the worker's clean read waited for the GPU"); + + // A store recorded after the resolution began over the word is the draw's value instead: refused. + host.NoteGuestMemoryWrite(TableAddress, sizeof(uint), MetalGpuWriteOrigin.StorageBuffer); + Assert.False(concurrent.IsStillCurrent(assumptions)); + } + finally + { + concurrent.ReleaseAssumptions(assumptions); + } + + host.FlushAndWaitForGpu(); + Assert.Equal(0xC0FFEE11u, rig.ReadBacking32(TableAddress)); + Assert.Equal(0xC0FFEE22u, rig.ReadBacking32(TableAddress + 4)); + } + [Fact] public void AGpuWriteRecordedAfterTheOwedBytesIsWhatAReadWaitsFor() { From 5db98d55fd4bf288a2b1324139fe468c80faa25a Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 15:49:34 +0000 Subject: [PATCH 127/134] [Metal] Take a posted word copy as a host store only when the GPU is idle, else leave it to its dispatch Upstream posts the copy as a host store at its stream position, which is sound on Vulkan because GPU reads go through buffer-cache copies taken at record time. Metal reads guest memory in place and does not track the ranges recorded work still reads, so a store is taken only when no command buffer is open and every submission is complete; otherwise the copy is refused as busy (counted) and runs as the dispatch it is, registered as a pending copy, as on main. Holding it as a causal command-processor write cost Demon's Souls ~20 ms a frame (label scatter, overlay scans, held landings). SHARPEMU_METAL_V2_POSTED_WORD_COPY_HOST_STORE=0 posts every copy as the held write again. --- .../V2/MetalRenderHost.PostedWordCopy.cs | 76 +++++++- .../Scenes/PostedWordCopySceneTests.cs | 183 +++++++++++++----- 2 files changed, 210 insertions(+), 49 deletions(-) diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.PostedWordCopy.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.PostedWordCopy.cs index 0af0473c8..726b26642 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.PostedWordCopy.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.PostedWordCopy.cs @@ -30,7 +30,22 @@ namespace SharpEmu.Gpu.Metal.V2; // - encode: the store cannot be recorded on the GPU at this point; // - host_kernel_copy: the Metal host's own kernel copy check takes it (an identical copy is consumed with // nothing written; under verify the copy runs as its dispatch). +// - busy (the store class, below): recorded or submitted GPU work could still touch the destination. // SHARPEMU_POSTED_WORD_COPY=0 (RenderExecutor) turns it off for every host. +// +// The store class (SHARPEMU_METAL_V2_POSTED_WORD_COPY_HOST_STORE, on; =0 posts every copy as a held command-processor +// write, as the port first did). Upstream's Vulkan host applies the copy as a host store at its stream position +// (VulkanVideoPresenter.KernelWrites.cs PostWordCopy -> CommandThread.PostOwnedWrite -> ApplyWrite, a plain +// _memory.TryWrite), which is sound there because every GPU read of guest bytes goes through a buffer-cache copy taken +// when the reading work was recorded (KernelWritePolicy.cs: "earlier readers have already taken their bytes"). Here the +// GPU reads guest memory in place through its windows and nothing tracks which ranges recorded work still reads, so a +// host store is only sound once no recorded or submitted work remains: then it is taken, written now and logged for the +// look-ahead resolutions (a write noted with no pending serial). Otherwise the copy is refused as busy and runs as the +// dispatch it is, which the host registers as a pending copy that readers read through (TryCopyWordsOnHost). Holding it +// as an ordered command-processor write instead costs more than that dispatch on this host: each one is a causal, +// CPU-visible write that holds every later command-processor write behind it, lands per word through the label scatter +// and stays in the pending-write overlay every recorded write scans until it lands (Demon's Souls: ~125 copies of ~3 KB +// a frame, 110 ms frames against 90 ms with them run as dispatches). internal sealed partial class MetalRenderHost { private const ulong MaxPostedCopyWords = 4 * 1024 * 1024; @@ -45,9 +60,10 @@ internal enum PostedWordCopyRefusal : byte Input, Encode, HostKernelCopy, + Busy, } - private static readonly string[] PostedWordCopyRefusalNames = ["posted", "unsupported", "thread", "image", "metadata", "input", "encode", "host_kernel_copy"]; + private static readonly string[] PostedWordCopyRefusalNames = ["posted", "unsupported", "thread", "image", "metadata", "input", "encode", "host_kernel_copy", "busy"]; private readonly long[] _postedWordCopies = new long[PostedWordCopyRefusalNames.Length]; @@ -58,6 +74,18 @@ internal enum PostedWordCopyRefusal : byte internal static bool PostedWordCopyExactImageBytes { get; set; } = Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_POSTED_WORD_COPY_EXACT_IMAGE") != "0"; + /// <summary> + /// The store class (see the file header): a copy is stored on the host when no GPU work can touch its destination and + /// refused as busy otherwise. False posts every copy as a held command-processor write. + /// </summary> + internal static bool PostedWordCopyHostStore { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_METAL_V2_POSTED_WORD_COPY_HOST_STORE") != "0"; + + private long _postedWordCopyHostStores; + + /// <summary>Posted copies taken as host stores, since the host started.</summary> + internal long PostedWordCopyHostStores => Interlocked.Read(ref _postedWordCopyHostStores); + /// <summary>Posted word copies (index 0) and refusals by reason, since the host started.</summary> internal long PostedWordCopies(PostedWordCopyRefusal outcome) => Interlocked.Read(ref _postedWordCopies[(int)outcome]); @@ -105,6 +133,14 @@ private PostedWordCopyRefusal PostWordCopy(ulong destination, ulong source, ulon // Draws deferred before the dispatch record their writes first, so the source check sees them. DrainDraws(); + // Checked before the identical-copy evaluation and the source read: a busy copy runs as its dispatch, whose own + // host check (TryCopyWordsOnHost) makes that evaluation. + var hostStore = PostedWordCopyHostStore; + if (hostStore && !NoGpuWorkCanTouch(destination, size)) + { + return PostedWordCopyRefusal.Busy; + } + // The host's own handling of a refused copy kernel comes first (SHARPEMU_METAL_V2_HOST_KERNEL_COPY): a // copy whose destination already holds its result is consumed there with nothing written, which a // posted store cannot beat, and under verify the copy runs so both checks see it. @@ -145,6 +181,13 @@ private PostedWordCopyRefusal PostWordCopy(ulong destination, ulong source, ulon SharpEmu.HLE.GpuMemory.FrameOverlapDiagnostic.NoteGpuWrite(destination, size, SharpEmu.HLE.GpuMemory.OverlapWrite.CpWrite); } + if (hostStore) + { + StorePostedWordCopy(destination, data); + Interlocked.Increment(ref _postedWordCopyHostStores); + return PostedWordCopyRefusal.None; + } + if (!TryEncodeCommandProcessorWrite(destination, data, "word copy", causal: true)) { return PostedWordCopyRefusal.Encode; @@ -154,6 +197,35 @@ private PostedWordCopyRefusal PostWordCopy(ulong destination, ulong source, ulon return PostedWordCopyRefusal.None; } + // Whether no GPU work recorded or submitted can still read or write these bytes: no command buffer open (everything + // recorded goes into one, including work encoded on it directly, which the encoder counts do not see), nothing held + // to land, every submission complete, and no recorded write or GPU-modified image over them. Reads by recorded work + // are not tracked on this host, so only an idle GPU proves it. + private bool NoGpuWorkCanTouch(ulong address, ulong size) => + _commandBuffer == 0 && _deferredLabelCopies.Count == 0 && _computeEncoder == 0 && _renderEncoder == 0 && + CompletedSerial >= Volatile.Read(ref _submittedSerial) && + CanWriteGuestOnHost(address, size); + + // The copy's bytes stored now, as a host fill stores (TryFillGuestMemoryOnHost), and logged with no pending serial: a + // look-ahead resolution that read these bytes before the store is refused at its take (LoggedWriteCoversRead). The + // store comes first, so a resolution that begins after the log entry reads the stored bytes. + private void StorePostedWordCopy(ulong destination, byte[] data) + { + var size = (ulong)data.Length; + if (!_memory.TryWrite(destination, data)) + { + throw Fatal($"A posted word copy could not be stored into readable guest memory: destination=0x{destination:X16} bytes={size}."); + } + + SupersedeKernelCopyChecks(destination, size); + _cpOverlay.Forget(destination, size); + _labelOverlay.Forget(destination, size); + _imageCache.InvalidateMemory(destination, size); + _stagedStorageCopies?.Forget(destination, size); + _stagedRanges?.OnHostWrite(destination, size); + _gpuWrites.Note(destination, size, serial: 0, MetalGpuWriteOrigin.Copy); + } + /// <summary>The posted word copy fields of the CHURN line; resets them.</summary> private string TakePostedWordCopyCounters() { @@ -164,6 +236,6 @@ private string TakePostedWordCopyCounters() .Append(Interlocked.Exchange(ref _postedWordCopies[index], 0)); } - return text.Append(']').ToString(); + return text.Append(",host_store=").Append(Interlocked.Exchange(ref _postedWordCopyHostStores, 0)).Append(']').ToString(); } } diff --git a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/PostedWordCopySceneTests.cs b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/PostedWordCopySceneTests.cs index ecf33be37..65c2626d4 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/Scenes/PostedWordCopySceneTests.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/Scenes/PostedWordCopySceneTests.cs @@ -10,8 +10,9 @@ namespace SharpEmu.Gpu.Metal.Tests.Scenes; /// <summary> /// IRenderHost.TryPostWordCopy on Metal (upstream 61e9ec8f3/5d4937c46): the executor, resolving a bounded word copy -/// on the worker at its stream position, hands the copy to the host as a command-processor store and drops the -/// dispatch. The store lands in stream order with the writes around it, and reads before it lands see it. +/// on the worker at its stream position, hands the copy to the host and drops the dispatch. By default the host stores +/// it at once when no GPU work can touch the destination and refuses it as busy otherwise; with the store class off it +/// is an ordered command-processor store that lands in stream order with the writes around it, read as written before. /// </summary> public sealed class PostedWordCopySceneTests(ITestOutputHelper output) : SceneTestBase(output) { @@ -24,59 +25,143 @@ private static uint[] Replicated(uint[] source, int words) => private static uint[] Words32(byte[] bytes) => Enumerable.Range(0, bytes.Length / 4).Select(word => BitConverter.ToUInt32(bytes, word * 4)).ToArray(); + // The held class (SHARPEMU_METAL_V2_POSTED_WORD_COPY_HOST_STORE=0): every copy is an ordered command-processor write. [Fact] public void APostedCopyLandsInStreamOrderBetweenTheStoresAroundIt() { - using var rig = CreateRig(); - if (rig is null) return; - var host = rig.Host; - var source = rig.Memory.Allocate(SourceWords * 4); - var destination = rig.Memory.Allocate(Words * 4); - uint[] pattern = [0x11111111, 0x22222222, 0x33333333, 0x44444444]; - rig.Memory.Write<uint>(source, pattern); - rig.Memory.Write(destination, new byte[Words * 4]); - - // A store before the copy is overwritten by it; a store after it overwrites it. - host.RecordCommandProcessorWrite(destination, BitConverter.GetBytes(0xDEADBEEFu), "test"); - Assert.True(((IRenderHost)host).TryPostWordCopy(destination, source, SourceWords, Words)); - host.RecordCommandProcessorWrite(destination + 8, BitConverter.GetBytes(0xFEEDFACEu), "test"); - Assert.Equal(1, host.PostedWordCopies(MetalRenderHost.PostedWordCopyRefusal.None)); - - var expected = Replicated(pattern, Words); - expected[2] = 0xFEEDFACE; - // Before the GPU ran it, a stream read sees the store as written. - Assert.Equal(expected, Words32(rig.Read(destination, Words * 4))); - - rig.Drain(); - Assert.Equal(expected, Words32(rig.Memory.ReadRaw(destination, Words * 4))); - Assert.Empty(rig.Fatals); + var saved = MetalRenderHost.PostedWordCopyHostStore; + MetalRenderHost.PostedWordCopyHostStore = false; + try + { + using var rig = CreateRig(); + if (rig is null) return; + var host = rig.Host; + var source = rig.Memory.Allocate(SourceWords * 4); + var destination = rig.Memory.Allocate(Words * 4); + uint[] pattern = [0x11111111, 0x22222222, 0x33333333, 0x44444444]; + rig.Memory.Write<uint>(source, pattern); + rig.Memory.Write(destination, new byte[Words * 4]); + + // A store before the copy is overwritten by it; a store after it overwrites it. + host.RecordCommandProcessorWrite(destination, BitConverter.GetBytes(0xDEADBEEFu), "test"); + Assert.True(((IRenderHost)host).TryPostWordCopy(destination, source, SourceWords, Words)); + host.RecordCommandProcessorWrite(destination + 8, BitConverter.GetBytes(0xFEEDFACEu), "test"); + Assert.Equal(1, host.PostedWordCopies(MetalRenderHost.PostedWordCopyRefusal.None)); + + var expected = Replicated(pattern, Words); + expected[2] = 0xFEEDFACE; + // Before the GPU ran it, a stream read sees the store as written. + Assert.Equal(expected, Words32(rig.Read(destination, Words * 4))); + + rig.Drain(); + Assert.Equal(expected, Words32(rig.Memory.ReadRaw(destination, Words * 4))); + Assert.Empty(rig.Fatals); + } + finally + { + MetalRenderHost.PostedWordCopyHostStore = saved; + } + } + + // The store class (default): with no GPU work recorded or in flight the copy is stored at once and logged, so a + // look-ahead resolution that read the bytes before it does not stand; with work recorded it is refused as busy and + // left to its dispatch, which stores nothing here. + [Fact] + public void AnIdleGpuTakesTheCopyAsAHostStoreAndABusyOneLeavesItToItsDispatch() + { + var saved = MetalRenderHost.PostedWordCopyHostStore; + MetalRenderHost.PostedWordCopyHostStore = true; + try + { + using var rig = CreateRig(); + if (rig is null) return; + var host = rig.Host; + var source = rig.Memory.Allocate(SourceWords * 4); + var destination = rig.Memory.Allocate(Words * 4); + var busyDestination = rig.Memory.Allocate(Words * 4); + uint[] pattern = [0x11111111, 0x22222222, 0x33333333, 0x44444444]; + rig.Memory.Write<uint>(source, pattern); + rig.Memory.Write(destination, new byte[Words * 4]); + rig.Memory.Write(busyDestination, new byte[Words * 4]); + rig.Drain(); + + var concurrent = (SharpEmu.Libs.Gpu.Rendering.IConcurrentResolveHost)host; + concurrent.BeginConcurrentResolve(); + object assumptions; + try + { + Assert.True(host.TryReadGuestWord(destination + 8, out var before)); + Assert.Equal(0u, before); + } + finally + { + assumptions = concurrent.EndConcurrentResolve(); + } + + try + { + Assert.True(concurrent.IsStillCurrent(assumptions)); + Assert.True(((IRenderHost)host).TryPostWordCopy(destination, source, SourceWords, Words)); + Assert.Equal(1, host.PostedWordCopyHostStores); + // Stored now, with nothing submitted, and the resolution that read the old bytes no longer stands. + Assert.Equal(Replicated(pattern, Words), Words32(rig.Memory.ReadRaw(destination, Words * 4))); + Assert.False(concurrent.IsStillCurrent(assumptions)); + } + finally + { + concurrent.ReleaseAssumptions(assumptions); + } + + // Recorded work that could still read the destination: refused, nothing stored. + host.RecordCommandProcessorWrite(rig.Memory.Allocate(sizeof(uint)), BitConverter.GetBytes(0xDEADBEEFu), "test"); + Assert.False(((IRenderHost)host).TryPostWordCopy(busyDestination, source, SourceWords, Words)); + Assert.Equal(1, host.PostedWordCopies(MetalRenderHost.PostedWordCopyRefusal.Busy)); + Assert.Equal(1, host.PostedWordCopies(MetalRenderHost.PostedWordCopyRefusal.None)); + rig.Drain(); + Assert.Equal(new uint[Words], Words32(rig.Memory.ReadRaw(busyDestination, Words * 4))); + Assert.Empty(rig.Fatals); + } + finally + { + MetalRenderHost.PostedWordCopyHostStore = saved; + } } [Fact] public void ACopyIsRefusedAndLeftToItsDispatchWhenItsSourceIsNotFinalOrItsRangeIsUnsupported() { - using var rig = CreateRig(); - if (rig is null) return; - var host = rig.Host; - var source = rig.Memory.Allocate(SourceWords * 4); - var destination = rig.Memory.Allocate(Words * 4); - rig.Memory.Write(destination, new byte[Words * 4]); - - // Source bytes a recorded store still owes: the kernel would read them on the GPU, the host cannot yet. - host.RecordCommandProcessorWrite(source, BitConverter.GetBytes(0x12345678u), "test"); - Assert.False(((IRenderHost)host).TryPostWordCopy(destination, source, SourceWords, Words)); - Assert.Equal(1, host.PostedWordCopies(MetalRenderHost.PostedWordCopyRefusal.Input)); - - // Overlapping, unaligned and oversized copies are not taken either. - Assert.False(((IRenderHost)host).TryPostWordCopy(destination, destination + 4, SourceWords, Words)); - Assert.False(((IRenderHost)host).TryPostWordCopy(destination + 2, source, SourceWords, Words)); - Assert.False(((IRenderHost)host).TryPostWordCopy(destination, source, SourceWords, 4 * 1024 * 1024 + 1)); - Assert.Equal(3, host.PostedWordCopies(MetalRenderHost.PostedWordCopyRefusal.Unsupported)); - - rig.Drain(); - // Nothing was stored for the refused copies. - Assert.Equal(new uint[Words], Words32(rig.Memory.ReadRaw(destination, Words * 4))); - Assert.Empty(rig.Fatals); + // The held class: under the store class a recorded write ahead of the copy refuses it as busy first. + var saved = MetalRenderHost.PostedWordCopyHostStore; + MetalRenderHost.PostedWordCopyHostStore = false; + try + { + using var rig = CreateRig(); + if (rig is null) return; + var host = rig.Host; + var source = rig.Memory.Allocate(SourceWords * 4); + var destination = rig.Memory.Allocate(Words * 4); + rig.Memory.Write(destination, new byte[Words * 4]); + + // Source bytes a recorded store still owes: the kernel would read them on the GPU, the host cannot yet. + host.RecordCommandProcessorWrite(source, BitConverter.GetBytes(0x12345678u), "test"); + Assert.False(((IRenderHost)host).TryPostWordCopy(destination, source, SourceWords, Words)); + Assert.Equal(1, host.PostedWordCopies(MetalRenderHost.PostedWordCopyRefusal.Input)); + + // Overlapping, unaligned and oversized copies are not taken either. + Assert.False(((IRenderHost)host).TryPostWordCopy(destination, destination + 4, SourceWords, Words)); + Assert.False(((IRenderHost)host).TryPostWordCopy(destination + 2, source, SourceWords, Words)); + Assert.False(((IRenderHost)host).TryPostWordCopy(destination, source, SourceWords, 4 * 1024 * 1024 + 1)); + Assert.Equal(3, host.PostedWordCopies(MetalRenderHost.PostedWordCopyRefusal.Unsupported)); + + rig.Drain(); + // Nothing was stored for the refused copies. + Assert.Equal(new uint[Words], Words32(rig.Memory.ReadRaw(destination, Words * 4))); + Assert.Empty(rig.Fatals); + } + finally + { + MetalRenderHost.PostedWordCopyHostStore = saved; + } } // Upstream 90d306cb1: the image refusal asks whether an image's bytes lie in the destination, not whether an image @@ -87,8 +172,11 @@ public void ACopyIsRefusedAndLeftToItsDispatchWhenItsSourceIsNotFinalOrItsRangeI [InlineData(false)] public void OnlyACopyThatMeetsAnImagesBytesIsRefusedForTheImage(bool exact) { + // The image refusal comes before the class choice; the held class posts the copy whatever the GPU is doing. var saved = MetalRenderHost.PostedWordCopyExactImageBytes; + var savedStore = MetalRenderHost.PostedWordCopyHostStore; MetalRenderHost.PostedWordCopyExactImageBytes = exact; + MetalRenderHost.PostedWordCopyHostStore = false; try { using var rig = CreateRig(); @@ -145,6 +233,7 @@ public void OnlyACopyThatMeetsAnImagesBytesIsRefusedForTheImage(bool exact) finally { MetalRenderHost.PostedWordCopyExactImageBytes = saved; + MetalRenderHost.PostedWordCopyHostStore = savedStore; } } } From 565323eee61a926cce271ad1e7f4de61fca4fd20 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 16:15:55 +0000 Subject: [PATCH 128/134] [GPU] Order an overlap-marked dispatch after the ones beside it when it shares their bytes A dispatch the stream reaches from the one before it with no barrier between them runs beside it (DispatchOverlap). Since the upstream merge a scalar load through a user-data pointer is a GPU device-address read, so a reader marked that way ran beside the copy dispatch that wrote what it reads and stored the bytes from before the copy (HostKernelCopySceneTests, 1/8 passing on the sync tip with posted copies off; main read the pointer on the CPU through the pending copy). DispatchChain now keeps the dispatches since the last ordered one and orders a marked dispatch after them when it touches what they wrote, writes what they touched, or either side's accesses are not all known; each such ordering is counted (overlap_ordered=[hazard,unknown]). SHARPEMU_DISPATCH_OVERLAP_HAZARDS=0 runs every marked dispatch beside the ones before it again. --- .../Gpu/Rendering/DispatchChain.cs | 83 +++++++++++++++++++ .../Gpu/Rendering/RenderRecorder.Compute.cs | 8 +- .../V2/MetalRenderHost.MeshIndirect.cs | 3 +- .../Gpu/Rendering/DispatchChainTests.cs | 63 ++++++++++++++ .../Rendering/RenderExecutorTestSupport.cs | 12 ++- 5 files changed, 165 insertions(+), 4 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs b/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs index 8962ecd6b..104dd9fef 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs @@ -29,6 +29,74 @@ internal sealed class DispatchChain private bool _recordWritesImages; private long _promotions; + // The dispatches recorded since the last one the stream ordered (DispatchOverlap): those an overlap-marked dispatch + // runs beside on a host that honours the mark. Kept apart from the deferred-barrier chain above, which a host that + // records its barriers at once resets after every dispatch. + private readonly List<GuestSpan> _groupTouched = new(); + private readonly List<GuestSpan> _groupWritten = new(); + private bool _groupConservative; + private bool _groupReadImages; + private bool _groupWroteImages; + + /// <summary> + /// Called after <see cref="NeedsHazardBarrier"/> for the same dispatch: whether it may still run beside the dispatches + /// recorded since the last ordered one, as the stream marked it (<paramref name="marked"/>). The console runs such + /// dispatches together too, so a guest only leaves the barrier out where it believes they share nothing; but the + /// host's dispatches do not take the console's time, and a dependency the console's timing hides (a small producer + /// finishing before its consumer reads) becomes a race here. A marked dispatch that touches what one of them wrote, + /// writes what one of them touched, or whose accesses (or theirs) are not all known is ordered after them instead, + /// and counted (<see cref="DispatchChainTally.OverlapsOrdered"/>). SHARPEMU_DISPATCH_OVERLAP_HAZARDS=0 runs every + /// marked dispatch beside the ones before it again. + /// </summary> + public bool KeepsOverlap(bool marked) + { + if (!marked || !OverlapHazardsChecked) + { + ResetGroup(); + AddToGroup(); + return marked; + } + + var unknown = _groupConservative || _recordConservative || _groupTouched.Count > MaxSpans; + var hazard = !unknown && + ((_recordReadsImages && _groupWroteImages) || (_recordWritesImages && (_groupWroteImages || _groupReadImages)) || + Overlaps(_recordTouched, _groupWritten) || Overlaps(_recordWritten, _groupTouched)); + if (unknown || hazard) + { + DispatchChainTally.NoteOverlapOrdered(unknown); + ResetGroup(); + AddToGroup(); + return false; + } + + AddToGroup(); + return true; + } + + /// <summary>A dispatch recorded without the mark whose own ordering the host decides: kept in the group, never ending it.</summary> + public void JoinOverlapGroup() => AddToGroup(); + + internal static bool OverlapHazardsChecked { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_DISPATCH_OVERLAP_HAZARDS") != "0"; + + private void ResetGroup() + { + _groupTouched.Clear(); + _groupWritten.Clear(); + _groupConservative = false; + _groupReadImages = false; + _groupWroteImages = false; + } + + private void AddToGroup() + { + _groupTouched.AddRange(_recordTouched); + _groupWritten.AddRange(_recordWritten); + _groupConservative |= _recordConservative; + _groupReadImages |= _recordReadsImages; + _groupWroteImages |= _recordWritesImages; + } + public bool NeedsHazardBarrier(ResolvedDispatch record, in ShaderStageResources stage, long promotions) { if (_open && promotions != _promotions) @@ -230,6 +298,21 @@ public static void Count(ChainDecision decision) } } + private static long _overlapsOrderedHazard; + private static long _overlapsOrderedUnknown; + + /// <summary>Overlap-marked dispatches ordered after the ones before them (DispatchChain.KeepsOverlap), always counted.</summary> + public static void NoteOverlapOrdered(bool unknown) => + Interlocked.Increment(ref unknown ? ref _overlapsOrderedUnknown : ref _overlapsOrderedHazard); + + /// <summary>Overlap-marked dispatches ordered for a shared range (Hazard) or for accesses not all known (Unknown).</summary> + public static (long Hazard, long Unknown) OverlapsOrdered => + (Interlocked.Read(ref _overlapsOrderedHazard), Interlocked.Read(ref _overlapsOrderedUnknown)); + + /// <summary>The overlap orderings since the last call, for a backend's report line.</summary> + public static string TakeOverlapReport() => + FormattableString.Invariant($"overlap_ordered=[hazard:{Interlocked.Exchange(ref _overlapsOrderedHazard, 0)},unknown:{Interlocked.Exchange(ref _overlapsOrderedUnknown, 0)}]"); + public static string TakeReport() => FormattableString.Invariant($"chain_open={Interlocked.Exchange(ref _decisions[(int)ChainDecision.Open], 0)} chain_start={Interlocked.Exchange(ref _decisions[(int)ChainDecision.Start], 0)} ") + FormattableString.Invariant($"chain_skipped={Interlocked.Exchange(ref _decisions[(int)ChainDecision.Skipped], 0)} chain_overlap={Interlocked.Exchange(ref _decisions[(int)ChainDecision.Overlap], 0)} chain_conservative={Interlocked.Exchange(ref _decisions[(int)ChainDecision.Conservative], 0)}"); diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Compute.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Compute.cs index b8837b61a..472b97035 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Compute.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderRecorder.Compute.cs @@ -334,11 +334,15 @@ private void RecordPreparedDispatch(ResolvedDispatch record, ComputeProgram comp } else if (threadDispatch is not null) { + // Its pass is ordered by the host, not by the mark: it joins the group, so a later marked dispatch + // is checked against it as well. + chain.JoinOverlapGroup(); threadDispatch.Dispatch(); dispatched = true; } else if (record.ThreadsOnGpu) { + chain.JoinOverlapGroup(); if (!TryDispatchThreadsIndirect(input, record.IndirectArgumentsAddress)) { throw _host.Fatal( @@ -349,7 +353,7 @@ private void RecordPreparedDispatch(ResolvedDispatch record, ComputeProgram comp } else { - _host.NextDispatchMayOverlap = record.MayOverlap; + _host.NextDispatchMayOverlap = chain.KeepsOverlap(record.MayOverlap); if (record.IndirectArgumentsAddress == 0 || !TryDispatchIndirect(record, arguments, input)) { _host.Dispatch(groupsX, groupsY, groupsZ); @@ -463,7 +467,7 @@ private bool TryReplayDispatch(ResolvedDispatch record, ComputeProgram computePr record.GroupsX, record.GroupsY, record.GroupsZ, record.IndirectArgumentsAddress); _host.BeginCheckedDispatch(); _host.BindPipeline(GpuBindPoint.Compute, in pipeline); - _host.NextDispatchMayOverlap = record.MayOverlap; + _host.NextDispatchMayOverlap = chain.KeepsOverlap(record.MayOverlap); _host.Dispatch(groupsX, groupsY, groupsZ); _host.EndCheckedDispatch(); chain.Commit(_host.TryDeferShaderAccessBarrier(), _host.DeferredBarrierPromotions); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.MeshIndirect.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.MeshIndirect.cs index dd98ec866..085a81f4c 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.MeshIndirect.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.MeshIndirect.cs @@ -120,7 +120,8 @@ internal string TakeIndirectCounters() => $"indirect_written={Interlocked.Exchange(ref _indirectLaunchesWritten, 0)} " + $"indirect_reused={Interlocked.Exchange(ref _indirectLaunchesReused, 0)} " + $"dispatch_threads_gpu={TakeThreadIndirectDispatches()} " + - $"dispatches_overlapped={Interlocked.Exchange(ref _guestDispatchesOverlapped, 0)}"; + $"dispatches_overlapped={Interlocked.Exchange(ref _guestDispatchesOverlapped, 0)} " + + SharpEmu.Libs.Gpu.Rendering.DispatchChainTally.TakeOverlapReport(); /// <summary>Passes an indirect launch ended that would otherwise have continued; reported and reset.</summary> internal long TakeIndirectPassEnds() => Interlocked.Exchange(ref _passEndIndirect, 0); diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs index 21e82b5c0..89045fb40 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs @@ -33,6 +33,13 @@ private void Dispatch(ulong submitId, BufferResourceInfo[] buffers, uint[][] des _executor.Dispatch(submitId, Banks(), 1, 1, 1, 0x41); } + // A dispatch the stream reached from the one before it through register writes alone (DispatchOverlap). + private void DispatchMarked(ulong submitId, BufferResourceInfo[] buffers, uint[][] descriptors) + { + _pipelines.Compute = ComputeProgram(Stage(Program(ShaderStageKind.Compute, buffers: buffers), buffers: descriptors)); + _executor.Dispatch(submitId, Banks(), 1, 1, 1, 0x41 | RenderExecutor.DispatchMayOverlapBit); + } + private int HazardBarriers => _host.Calls.Count(call => call == "write_hazard_barrier"); [Theory] @@ -127,6 +134,62 @@ public void APromotionOutsideTheChainStartsANewOne() Assert.Equal(2, HazardBarriers); } + // HostKernelCopySceneTests' reader: a marked dispatch reading what the marked dispatch before it wrote ran beside it + // and read the bytes from before the write. It is ordered after it now, and counted; disjoint ones still overlap. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void AMarkedDispatchThatReadsWhatTheOneBeforeItWroteIsOrderedAfterIt(bool checkHazards) + { + var saved = DispatchChain.OverlapHazardsChecked; + DispatchChain.OverlapHazardsChecked = checkHazards; + try + { + var before = DispatchChainTally.OverlapsOrdered; + DispatchMarked(1, [Written], [BufferDescriptor(BufferA, 4, 16)]); + DispatchMarked(2, [Read], [BufferDescriptor(BufferA + 0x20, 4, 4)]); + // A third, disjoint from both, still runs beside the second (the group restarts at the ordered one). + DispatchMarked(3, [Written], [BufferDescriptor(BufferB, 4, 16)]); + + Assert.Equal(checkHazards ? [true, false, true] : new[] { true, true, true }, _host.DispatchOverlaps); + Assert.Equal(before.Hazard + (checkHazards ? 1 : 0), DispatchChainTally.OverlapsOrdered.Hazard); + Assert.Equal(before.Unknown, DispatchChainTally.OverlapsOrdered.Unknown); + } + finally + { + DispatchChain.OverlapHazardsChecked = saved; + } + } + + [Fact] + public void AMarkedDispatchIsCheckedAgainstEveryDispatchSinceTheLastOrderedOne() + { + DispatchMarked(1, [Written], [BufferDescriptor(BufferA, 4, 16)]); + DispatchMarked(2, [Written], [BufferDescriptor(BufferB, 4, 16)]); + // Overlaps the first, two dispatches back, with no barrier between them either. + DispatchMarked(3, [Written], [BufferDescriptor(BufferA + 0x10, 4, 4)]); + + Assert.Equal([true, true, false], _host.DispatchOverlaps); + } + + [Fact] + public void AMarkedDispatchWhoseAccessesAreNotAllKnownIsOrdered() + { + var before = DispatchChainTally.OverlapsOrdered; + DispatchMarked(1, [Written], [BufferDescriptor(BufferA, 4, 16)]); + var heap = new ShaderProgramInfo + { + Stage = ShaderStageKind.Compute, + Buffers = [Written], + Bindings = new BindingLayout { UsesBindlessHeap = true }, + }; + _pipelines.Compute = ComputeProgram(Stage(heap, [BufferDescriptor(BufferB, 4, 16)])); + _executor.Dispatch(2, Banks(), 1, 1, 1, 0x41 | RenderExecutor.DispatchMayOverlapBit); + + Assert.Equal([true, false], _host.DispatchOverlaps); + Assert.Equal(before.Unknown + 1, DispatchChainTally.OverlapsOrdered.Unknown); + } + [Fact] public void AnUndeferredHostKeepsTheAccessBarrierAfterEveryDispatch() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs index 9a8e41bec..66615899d 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/RenderExecutorTestSupport.cs @@ -446,7 +446,17 @@ public bool TakesIndirectDrawArguments(ShaderProgram vertexProgram, ulong argume public void DrawMeshTasks(uint groupCountX, uint groupCountY, uint groupCountZ) => Calls.Add($"draw_mesh {groupCountX} {groupCountY} {groupCountZ}"); - public void Dispatch(uint groupsX, uint groupsY, uint groupsZ) => Calls.Add($"dispatch {groupsX} {groupsY} {groupsZ}"); + public void Dispatch(uint groupsX, uint groupsY, uint groupsZ) + { + Calls.Add($"dispatch {groupsX} {groupsY} {groupsZ}"); + DispatchOverlaps.Add(NextDispatchMayOverlap); + NextDispatchMayOverlap = false; + } + + /// <summary>The overlap mark each dispatch was recorded with (IRenderHost.NextDispatchMayOverlap).</summary> + public List<bool> DispatchOverlaps { get; } = new(); + + public bool NextDispatchMayOverlap { get; set; } public bool TryDispatchIndirect(ulong argumentsAddress, ReadOnlySpan<int> physicalAxisOfLogical) => false; From 434bf2579dd375dea4a417e31c95ca39a6436df9 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 16:22:32 +0000 Subject: [PATCH 129/134] [Docs] Describe the posted word copy store class, overlay reads and dispatch overlap hazards switches --- docs/macos/configuration.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index a22ae8710..8745a1868 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -140,7 +140,10 @@ undoes an optimization to isolate a miscompile: | `SHARPEMU_METAL_V2_DYNAMIC_STENCIL_OPS` | on | A draw's stencil operations and compare functions come from its own dynamic state, not from the draw its pipeline was first built for. `0` takes them from the pipeline again. | | `SHARPEMU_DRAW_REPLAY` | on | A draw that repeats the command-thread item before it in all but its user data (same programs, descriptor words, vertex input and targets) binds what that draw bound, with its own user data patched into the push data, instead of preparing and binding again (`MetalRenderHost.Replay.cs`). The host refuses, and the draw takes the full path, when anything that binding stood on has moved: the command buffer, the render pass, the image cache's binding epoch or image set, a read-only buffer's or vertex stream's read-binding memo answer, or the stage object. Draws with written buffers, storage images, movie planes, bindless tables, device addresses or per-draw argument fields are never captured. The `[METAL-V2][TBDR]` line reports the engine's `draw_replays` / `replay_miss` and the host's `replay_host=(draws,captured,capture_refused=[...],miss=[...])`. Needs the command thread (`SHARPEMU_METAL_V2_COMMAND_THREAD`, on). `0` binds every draw in full. | | `SHARPEMU_DISPATCH_REPLAY` | on | The same for a compute dispatch that repeats the one before it in all but its user data and thread limits: its shader data is built again from its own snapshot, and a dispatch that writes takes its buffers' whole binding chain again (a range other than the captured one rewrites the argument buffer, counted as `rebound`). Reported as `dispatch_replay_host=(...)` on the same line. `0` binds every dispatch in full. | -| `SHARPEMU_POSTED_WORD_COPY` | on | A bounded word-copy kernel whose source is final and whose destination holds no image or surface metadata is recorded as a command-processor store of the copied words at its place in the stream, not as a dispatch. The counter line reports `word_copy=[posted=...,unsupported=...,image=...,...]`. `0` runs every such kernel as a dispatch. | +| `SHARPEMU_POSTED_WORD_COPY` | on | A bounded word-copy kernel whose source is final and whose destination holds no image or surface metadata is taken out of the dispatch path at its place in the stream. The counter line reports `word_copy=[posted=...,unsupported=...,image=...,busy=...,host_store=...]`. `0` runs every such kernel as a dispatch. | +| `SHARPEMU_METAL_V2_POSTED_WORD_COPY_HOST_STORE` | on | How a posted word copy is applied. Upstream's Vulkan host stores the words on the host, which is sound there because GPU readers take a copy of their bytes when recorded. Metal reads guest memory in place, so the store is taken only when no recorded or submitted GPU work remains (`host_store`); otherwise the copy is refused as `busy` and runs as its dispatch, which readers read through as a pending copy. `0` posts every copy as a held command-processor write instead, which costs Demon's Souls about 20 ms a frame. | +| `SHARPEMU_METAL_V2_CONCURRENT_OVERLAY_READS` | on | A look-ahead resolution, and the render thread's clean read, take words a pending command-processor write still owes from that write's overlay when it covers them whole, instead of abandoning the resolution or waiting for the GPU. Counted as `concurrent_overlay_reads` and `clean_overlay_reads`. `0` abandons and waits as before. | +| `SHARPEMU_DISPATCH_OVERLAP_HAZARDS` | on | A dispatch the stream marks as free to overlap the ones before it (no barrier between them) is ordered after them when it reads what one of them wrote, writes what one of them touched, or either side's accesses are not all known. The console overlaps such dispatches too, but a dependency its timing hides is a race on the host. Counted as `overlap_ordered=[hazard:...,unknown:...]`. `0` honours every mark. | | `SHARPEMU_METAL_V2_POSTED_WORD_COPY_EXACT_IMAGE` | on | A posted word copy is refused for an image only when an image's guest bytes lie in its destination. Sharing a page with an image is not enough (upstream 90d306cb1). `0` refuses any destination an image shares a page with. | ## Diagnostics From 2f400300fae952c4c5432593b7f181866e8c34b9 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 19:27:09 +0000 Subject: [PATCH 130/134] [GPU] Refuse a write guard's GPU-owned predicate word and order marked dispatches only on real hazards Demon's Souls spawn-idle on the sync was ~12 % behind main with the render thread saturated: - ResourceBranchWriteGuard (upstream, SHARPEMU_BRANCHES_WITH_WRITES) gives plans that write memory branch blocks, so their predicates are now read through the clean reader. On Metal that reader waits for a GPU write still landing in the word; compute 0x6A8FECE6F91BDEB9 reads a count its producer dispatch writes just before, so the stream waited on the GPU ~90 times / ~800 ms per 2 s. A guard's read (ResourceBranchWriteGuard.ReadingWords) of such a word is now answered through the command processor or the pending copy, else refused on both threads (counted as clean_under_write guard_refused): the plan keeps both paths of that predicate, as it kept every source before it had blocks. SHARPEMU_GUARD_READS_REFUSE_PENDING=0 waits and abandons again. - DispatchChain.KeepsOverlap (565323eee) ordered ~7,000 marked dispatches per 5 s. Images now meet only where their data spans meet (SHARPEMU_DISPATCH_OVERLAP_IMAGE_SPANS=0: any written image meets every other), and two writes of the same buffer bytes that neither reads stay beside each other (SHARPEMU_DISPATCH_OVERLAP_WRITES_APART=0 orders them). Read-after-write and write-after-read still order, so the HostKernelCopy reader stays after its copy. The report gains overlap_by=[indirect,raw,war,waw,image,image_unresolved,images_apart,writes_apart]. --- .../Gpu/Rendering/DispatchChain.cs | 177 +++++++++++++++++- .../Rendering/RenderExecutor.PendingWrites.cs | 2 +- .../Resources/ResourceBranchWriteGuard.cs | 25 ++- .../V2/MetalRenderHost.ConcurrentResolve.cs | 19 +- .../V2/MetalRenderHost.Pipelines.cs | 28 ++- .../MetalClearFoldingTests.OwnedCleanReads.cs | 67 +++++++ .../Gpu/Rendering/DispatchChainTests.cs | 75 +++++++- 7 files changed, 374 insertions(+), 19 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs b/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs index 104dd9fef..0b54088ab 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs @@ -37,6 +37,17 @@ internal sealed class DispatchChain private bool _groupConservative; private bool _groupReadImages; private bool _groupWroteImages; + // The data each image the group's and this dispatch's shaders use covers (OverlapImageSpans), and whether one of them + // has none the request builders resolve. + private readonly List<GuestSpan> _groupImageTouched = new(); + private readonly List<GuestSpan> _groupImageWritten = new(); + private bool _groupImagesUnresolved; + private readonly List<GuestSpan> _groupRead = new(); + private readonly List<GuestSpan> _recordRead = new(); + private readonly List<GuestSpan> _recordImageTouched = new(); + private readonly List<GuestSpan> _recordImageWritten = new(); + private bool _recordImagesUnresolved; + private GuestSpan _recordIndirect; /// <summary> /// Called after <see cref="NeedsHazardBarrier"/> for the same dispatch: whether it may still run beside the dispatches @@ -45,7 +56,9 @@ internal sealed class DispatchChain /// host's dispatches do not take the console's time, and a dependency the console's timing hides (a small producer /// finishing before its consumer reads) becomes a race here. A marked dispatch that touches what one of them wrote, /// writes what one of them touched, or whose accesses (or theirs) are not all known is ordered after them instead, - /// and counted (<see cref="DispatchChainTally.OverlapsOrdered"/>). SHARPEMU_DISPATCH_OVERLAP_HAZARDS=0 runs every + /// and counted (<see cref="DispatchChainTally.OverlapsOrdered"/>, by cause in the report). An image meets another + /// only where their data does (<see cref="OverlapImageSpans"/>), and two writes of the same buffer bytes that neither + /// reads are not ordered (<see cref="OverlapWritesApart"/>). SHARPEMU_DISPATCH_OVERLAP_HAZARDS=0 runs every /// marked dispatch beside the ones before it again. /// </summary> public bool KeepsOverlap(bool marked) @@ -58,12 +71,53 @@ public bool KeepsOverlap(bool marked) } var unknown = _groupConservative || _recordConservative || _groupTouched.Count > MaxSpans; - var hazard = !unknown && - ((_recordReadsImages && _groupWroteImages) || (_recordWritesImages && (_groupWroteImages || _groupReadImages)) || - Overlaps(_recordTouched, _groupWritten) || Overlaps(_recordWritten, _groupTouched)); - if (unknown || hazard) + var imagesMeet = (_recordReadsImages && _groupWroteImages) || (_recordWritesImages && (_groupWroteImages || _groupReadImages)); + var cause = OverlapCause.None; + if (unknown) { - DispatchChainTally.NoteOverlapOrdered(unknown); + cause = OverlapCause.Unknown; + } + else if (_recordIndirect.Size != 0 && Overlaps(_recordIndirect, _groupWritten)) + { + cause = OverlapCause.Indirect; + } + else if (Overlaps(_recordRead, _groupWritten)) + { + cause = OverlapCause.BufferReadAfterWrite; + } + else if (Overlaps(_recordWritten, _groupRead)) + { + cause = OverlapCause.BufferWriteAfterRead; + } + else if (Overlaps(_recordWritten, _groupWritten)) + { + // Writes of the same bytes with no read of them between leave whichever lands last on the console as well: + // nothing reads a value the order decides, so they stay beside each other (OverlapWritesApart). + if (OverlapWritesApart) + { + DispatchChainTally.NoteOverlapWritesApart(); + } + else + { + cause = OverlapCause.BufferWriteAfterWrite; + } + } + + if (cause == OverlapCause.None && imagesMeet) + { + // Two images meet only where their data does; one whose data is not resolved meets every other. + cause = !OverlapImageSpans || _recordImagesUnresolved || _groupImagesUnresolved ? OverlapCause.ImageUnresolved + : Overlaps(_recordImageTouched, _groupImageWritten) || Overlaps(_recordImageWritten, _groupImageTouched) + ? OverlapCause.Image : OverlapCause.None; + if (cause == OverlapCause.None) + { + DispatchChainTally.NoteOverlapImagesApart(); + } + } + + if (cause != OverlapCause.None) + { + DispatchChainTally.NoteOverlapOrdered(cause); ResetGroup(); AddToGroup(); return false; @@ -79,22 +133,42 @@ public bool KeepsOverlap(bool marked) internal static bool OverlapHazardsChecked { get; set; } = Environment.GetEnvironmentVariable("SHARPEMU_DISPATCH_OVERLAP_HAZARDS") != "0"; + // SHARPEMU_DISPATCH_OVERLAP_IMAGE_SPANS (on by default, =0 off): an image read or written beside one written meets it + // only where their data meets (the span the request builders resolve, as RenderExecutor.MarkStageWrites marks for a + // storage image); off, any image a dispatch writes meets every image another one beside it uses, which orders most + // marked dispatches of a frame that writes images (Demon's Souls: ~290 of ~640 per frame). + // SHARPEMU_DISPATCH_OVERLAP_WRITES_APART (on by default, =0 off): a marked dispatch whose buffers meet the group's only + // where both write (no read on either side of the shared bytes) stays beside it; off, it is ordered after it. + internal static bool OverlapWritesApart { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_DISPATCH_OVERLAP_WRITES_APART") != "0"; + + internal static bool OverlapImageSpans { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_DISPATCH_OVERLAP_IMAGE_SPANS") != "0"; + private void ResetGroup() { _groupTouched.Clear(); _groupWritten.Clear(); + _groupRead.Clear(); _groupConservative = false; _groupReadImages = false; _groupWroteImages = false; + _groupImageTouched.Clear(); + _groupImageWritten.Clear(); + _groupImagesUnresolved = false; } private void AddToGroup() { _groupTouched.AddRange(_recordTouched); _groupWritten.AddRange(_recordWritten); + _groupRead.AddRange(_recordRead); _groupConservative |= _recordConservative; _groupReadImages |= _recordReadsImages; _groupWroteImages |= _recordWritesImages; + _groupImageTouched.AddRange(_recordImageTouched); + _groupImageWritten.AddRange(_recordImageWritten); + _groupImagesUnresolved |= _recordImagesUnresolved; } public bool NeedsHazardBarrier(ResolvedDispatch record, in ShaderStageResources stage, long promotions) @@ -161,9 +235,14 @@ private void Collect(ResolvedDispatch record, in ShaderStageResources stage) { _recordTouched.Clear(); _recordWritten.Clear(); + _recordRead.Clear(); _recordConservative = false; _recordReadsImages = false; _recordWritesImages = false; + _recordImageTouched.Clear(); + _recordImageWritten.Clear(); + _recordImagesUnresolved = false; + _recordIndirect = default; if (stage.Program is not { } program) { _recordConservative = true; @@ -207,14 +286,23 @@ private void Collect(ResolvedDispatch record, in ShaderStageResources stage) } var span = new GuestSpan(descriptor.Address, footprint); + var info = program.Buffers[index]; _recordTouched.Add(span); - if (program.Buffers[index].Written) + if (info.Written) { _recordWritten.Add(span); } + + // A buffer the shader neither reads nor writes per its info counts as read. + if (info.Read || info.Atomic || !info.Written) + { + _recordRead.Add(span); + } } var images = resources.Images; + var shapes = program.Resources?.Info.Images; + var resolveImages = OverlapHazardsChecked && OverlapImageSpans; for (var index = 0; index < program.Images.Length && index < images.Length; index++) { var words = images[index]; @@ -223,11 +311,31 @@ private void Collect(ResolvedDispatch record, in ShaderStageResources stage) continue; } + var written = program.Images[index].Written; _recordReadsImages = true; - if (program.Images[index].Written) + if (written) { _recordWritesImages = true; } + + if (!resolveImages) + { + continue; + } + + if (shapes is not null && index < shapes.Count && + RenderExecutor.TryGetImageData(program, shapes[index], words, index, out var data)) + { + _recordImageTouched.Add(data); + if (written) + { + _recordImageWritten.Add(data); + } + } + else + { + _recordImagesUnresolved = true; + } } foreach (var range in resources.DeviceAddressRanges) @@ -240,6 +348,8 @@ private void Collect(ResolvedDispatch record, in ShaderStageResources stage) var span = new GuestSpan(range.Base, range.Size); _recordTouched.Add(span); + // A device-address range does not say whether it is also read: it counts as read. + _recordRead.Add(span); if (range.Written) { _recordWritten.Add(span); @@ -253,10 +363,25 @@ private void Collect(ResolvedDispatch record, in ShaderStageResources stage) if (record.IndirectArgumentsAddress != 0) { - _recordTouched.Add(new GuestSpan(record.IndirectArgumentsAddress, IndirectArgumentBytes)); + _recordIndirect = new GuestSpan(record.IndirectArgumentsAddress, IndirectArgumentBytes); + _recordTouched.Add(_recordIndirect); + _recordRead.Add(_recordIndirect); } } + private static bool Overlaps(GuestSpan span, List<GuestSpan> right) + { + foreach (var other in right) + { + if (span.Address < other.End && other.Address < span.End) + { + return true; + } + } + + return false; + } + private static bool Overlaps(List<GuestSpan> left, List<GuestSpan> right) { foreach (var span in left) @@ -274,6 +399,19 @@ private static bool Overlaps(List<GuestSpan> left, List<GuestSpan> right) } } +internal enum OverlapCause +{ + None, + Unknown, + Indirect, + BufferReadAfterWrite, + BufferWriteAfterRead, + BufferWriteAfterWrite, + Image, + ImageUnresolved, + Count, +} + public enum ChainDecision { Open, @@ -300,18 +438,37 @@ public static void Count(ChainDecision decision) private static long _overlapsOrderedHazard; private static long _overlapsOrderedUnknown; + private static readonly long[] _overlapCauses = new long[(int)OverlapCause.Count]; + private static long _overlapImagesApart; + private static long _overlapWritesApart; + + /// <summary>A marked dispatch kept beside the group although both write the same buffer bytes, neither reading them.</summary> + internal static void NoteOverlapWritesApart() => Interlocked.Increment(ref _overlapWritesApart); /// <summary>Overlap-marked dispatches ordered after the ones before them (DispatchChain.KeepsOverlap), always counted.</summary> public static void NoteOverlapOrdered(bool unknown) => Interlocked.Increment(ref unknown ? ref _overlapsOrderedUnknown : ref _overlapsOrderedHazard); + internal static void NoteOverlapOrdered(OverlapCause cause) + { + NoteOverlapOrdered(cause == OverlapCause.Unknown); + Interlocked.Increment(ref _overlapCauses[(int)cause]); + } + + /// <summary>A marked dispatch kept beside the group although both use images, their data apart.</summary> + internal static void NoteOverlapImagesApart() => Interlocked.Increment(ref _overlapImagesApart); + /// <summary>Overlap-marked dispatches ordered for a shared range (Hazard) or for accesses not all known (Unknown).</summary> public static (long Hazard, long Unknown) OverlapsOrdered => (Interlocked.Read(ref _overlapsOrderedHazard), Interlocked.Read(ref _overlapsOrderedUnknown)); /// <summary>The overlap orderings since the last call, for a backend's report line.</summary> public static string TakeOverlapReport() => - FormattableString.Invariant($"overlap_ordered=[hazard:{Interlocked.Exchange(ref _overlapsOrderedHazard, 0)},unknown:{Interlocked.Exchange(ref _overlapsOrderedUnknown, 0)}]"); + FormattableString.Invariant($"overlap_ordered=[hazard:{Interlocked.Exchange(ref _overlapsOrderedHazard, 0)},unknown:{Interlocked.Exchange(ref _overlapsOrderedUnknown, 0)}] ") + + FormattableString.Invariant($"overlap_by=[indirect:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.Indirect], 0)},raw:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.BufferReadAfterWrite], 0)},") + + FormattableString.Invariant($"war:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.BufferWriteAfterRead], 0)},waw:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.BufferWriteAfterWrite], 0)},") + + FormattableString.Invariant($"image:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.Image], 0)},image_unresolved:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.ImageUnresolved], 0)},") + + FormattableString.Invariant($"images_apart:{Interlocked.Exchange(ref _overlapImagesApart, 0)},writes_apart:{Interlocked.Exchange(ref _overlapWritesApart, 0)}]"); public static string TakeReport() => FormattableString.Invariant($"chain_open={Interlocked.Exchange(ref _decisions[(int)ChainDecision.Open], 0)} chain_start={Interlocked.Exchange(ref _decisions[(int)ChainDecision.Start], 0)} ") + diff --git a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.PendingWrites.cs b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.PendingWrites.cs index ff162ad4c..01cbc63f8 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.PendingWrites.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/RenderExecutor.PendingWrites.cs @@ -174,7 +174,7 @@ private void MarkStageWrites(in ShaderStageResources stage, long sequence) } } - private static bool TryGetImageData(ShaderProgramInfo program, ImageResource image, uint[] words, int imageIndex, out GuestSpan data) + internal static bool TryGetImageData(ShaderProgramInfo program, ImageResource image, uint[] words, int imageIndex, out GuestSpan data) { data = default; if (new TextureDescriptorWords(words).BaseAddress == 0) diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceBranchWriteGuard.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceBranchWriteGuard.cs index 289c4e5b8..34d01b45d 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceBranchWriteGuard.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceBranchWriteGuard.cs @@ -33,11 +33,34 @@ internal ResourceBranchWriteGuard(ShaderResourcePlan plan, ResourceRuntimeInputs private bool Record(ulong address, out uint word) { - if (!_clean(address, out word)) return false; + using (EnterReads()) + { + if (!_clean(address, out word)) return false; + } + _reads.Add(address); return true; } + // Set on this thread while the guard reads a predicate or a written descriptor. A host whose clean reader waits for a + // GPU write still landing in the word (Metal: MetalRenderHost.TryReadCleanGuestWord) refuses such a word here instead: + // the selection of a plan that writes memory is an optimisation over keeping every source, which is what this plan + // did before it had blocks (SHARPEMU_BRANCHES_WITH_WRITES=0), so an unread predicate only keeps both of its paths. + [ThreadStatic] private static int _reading; + + public static bool ReadingWords => _reading != 0; + + public static ReadScope EnterReads() + { + _reading++; + return default; + } + + public readonly struct ReadScope : IDisposable + { + public void Dispose() => _reading--; + } + // Whether the selection made through Evaluator stands for this dispatch. internal bool Holds() { diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs index b4001d543..ce6752b9a 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.ConcurrentResolve.cs @@ -78,6 +78,16 @@ internal sealed partial class MetalRenderHost : IConcurrentResolveHost internal static bool CleanReadsLanded { get; set; } = Environment.GetEnvironmentVariable("SHARPEMU_CLEAN_READ_LANDED") != "0"; private long _cleanReadsCopied; private long _cleanReadsAbandoned; + // A branch write guard's read (ResourceBranchWriteGuard.ReadingWords) of a word a pending recorded GPU write owns and + // neither its copy nor the command processor answers: refused on both threads, never waited for nor abandoned, so the + // guarded plan keeps both paths of that predicate, as it kept every source before it had blocks. A predicate of the + // plan that dispatches right after its producer otherwise stalled the stream on the GPU every time (Demon's Souls: + // ~90 waits, ~800 ms per 2 s). SHARPEMU_GUARD_READS_REFUSE_PENDING=0 waits (worker) and abandons (resolver) again. + internal static bool GuardReadsRefusePending { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_GUARD_READS_REFUSE_PENDING") != "0"; + private long _guardReadsRefused; + + private static bool RefusesPendingGuardRead => GuardReadsRefusePending && SharpEmu.ShaderCompiler.Resources.ResourceBranchWriteGuard.ReadingWords; // Verify differences excused because a GPU write logged since the resolution began covers what it read. private long _supersededVerifies; // Takes refused because an owned answer (a refused clean or resident read) is clean now. @@ -186,7 +196,7 @@ private string FormatPrefetchCounters() var dispatches = $" dispatch_jobs={computeSubmitted} dispatch_taken={computeTaken} dispatch_refused=(abandoned={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Abandoned]}," + $"provider={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Provider]}{FormatProviderRefusals(prefetch.TakeProviderRefusals())},inputs={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Inputs]}," + $"ownership={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Ownership]},effects={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Effects]},replanned={computeRefused[(int)ParallelProgramPrefetch.ComputeRefusal.Replanned]}) {prefetch.TakeComputeReport()} " + - $"write_log_refusals={Interlocked.Exchange(ref _writeLogRefusals, 0)} superseded_verifies={Interlocked.Exchange(ref _supersededVerifies, 0)} owned_now_clean_refusals={Interlocked.Exchange(ref _ownedNowCleanRefusals, 0)} clean_under_write=(landed={Interlocked.Exchange(ref _cleanReadsLanded, 0)},copied={Interlocked.Exchange(ref _cleanReadsCopied, 0)},abandoned={Interlocked.Exchange(ref _cleanReadsAbandoned, 0)}) dispatch_wait_ms={computeWaitMs.ToString("F1", culture)} " + + $"write_log_refusals={Interlocked.Exchange(ref _writeLogRefusals, 0)} superseded_verifies={Interlocked.Exchange(ref _supersededVerifies, 0)} owned_now_clean_refusals={Interlocked.Exchange(ref _ownedNowCleanRefusals, 0)} clean_under_write=(landed={Interlocked.Exchange(ref _cleanReadsLanded, 0)},copied={Interlocked.Exchange(ref _cleanReadsCopied, 0)},abandoned={Interlocked.Exchange(ref _cleanReadsAbandoned, 0)},guard_refused={Interlocked.Exchange(ref _guardReadsRefused, 0)}) dispatch_wait_ms={computeWaitMs.ToString("F1", culture)} " + $"dispatch_saved_ms={computeSavedMs.ToString("F1", culture)}"; return $"resolved={resolved} abandoned={abandoned} abandoned_by=({TakeAbandonCauses()}) abandoned_verify={GpuFatal.TakeSpeculativeVerifyFailures()} taken={taken} refused={refused} drains={drains} drained={drained} deferred_barriers={deferredBarriers} operand_reads_kept={operandReadsKept} " + $"wait_ms={waitMs.ToString("F1", culture)} resolve_ms={prefetch.TakeResolveMilliseconds().ToString("F1", culture)} " + @@ -1452,6 +1462,13 @@ private bool TryReadCleanGuestWordConcurrent(ulong address, out uint word, Concu return true; } + if (RefusesPendingGuardRead) + { + // The owned answer stays recorded: the worker refuses the word as well while the write is pending. + Interlocked.Increment(ref _guardReadsRefused); + return false; + } + _lastConcurrentOwner = owner; Interlocked.Increment(ref _cleanReadsAbandoned); NoteAbandonCause(address, sizeof(uint)); diff --git a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs index 745bd1e01..8cfa657bc 100644 --- a/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs +++ b/src/graphics/SharpEmu.Gpu.Metal/V2/MetalRenderHost.Pipelines.cs @@ -2052,7 +2052,9 @@ public bool TryReadCleanGuestWord(ulong address, out uint word) // sees. Neither the stale backing (one resource branch kept on the worker, both on the resolver: bd5c2009a) nor a // refusal (both paths kept: the path the shader does not take had its descriptor read from whatever that memory // held, floats in Demon's Souls, which fataled as an invalid image) is that value. The resolving thread reads it - // through the copy as well, or abandons (TryReadCleanGuestWordConcurrent). + // through the copy as well, or abandons (TryReadCleanGuestWordConcurrent). A branch write guard's read is refused + // instead of waited for (GuardReadsRefusePending): its plan writes memory and kept every source before it had + // blocks, so both paths of its predicate are what it materialized then. Span<byte> bytes = stackalloc byte[sizeof(uint)]; if (_gpuWrites.MayCover(address, sizeof(uint)) && _gpuWrites.PendingSerial(address, sizeof(uint), CompletedSerial) != 0) { @@ -2061,10 +2063,28 @@ public bool TryReadCleanGuestWord(ulong address, out uint word) return false; } - Interlocked.Increment(ref _cleanReadsLanded); - if (!TryReadPendingCommandProcessorBytes(address, bytes) && !TryReadGuestCore(address, bytes)) + if (RefusesPendingGuardRead) { - return false; + // A branch write guard's read: through the command processor or the copy, never after a wait + // (GuardReadsRefusePending; the resolving thread refuses the word the same way). + if (!TryReadPendingCommandProcessorBytes(address, bytes)) + { + if (!TryReadThroughPendingCopy(address, bytes)) + { + Interlocked.Increment(ref _guardReadsRefused); + return false; + } + + NotePendingAnswer(address, bytes.Length); + } + } + else + { + Interlocked.Increment(ref _cleanReadsLanded); + if (!TryReadPendingCommandProcessorBytes(address, bytes) && !TryReadGuestCore(address, bytes)) + { + return false; + } } } else if (!_backing.TryReadBacking(address, bytes)) diff --git a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.OwnedCleanReads.cs b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.OwnedCleanReads.cs index 9b9f24938..97b72bbbf 100644 --- a/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.OwnedCleanReads.cs +++ b/tests/SharpEmu.Gpu.Metal.Tests/MetalClearFoldingTests.OwnedCleanReads.cs @@ -46,6 +46,73 @@ public void ACleanReadUnderAPendingWriteAbandonsTheResolutionAndTheWorkerReadsTh Assert.True(host.CompletedSerial >= serial); } + // A branch write guard's read of that word (its plan writes memory and kept every source before it had blocks) is + // refused on both threads instead: the resolver neither abandons nor answers, its refusal stands while the write is + // pending, and the worker does not wait. SHARPEMU_GUARD_READS_REFUSE_PENDING=0 abandons and waits again. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void ABranchWriteGuardsReadUnderAPendingWriteIsRefusedWithoutAWait(bool refuse) + { + if (!RequireDevice()) return; + using var rig = new Rig(Device.Value); + var host = rig.Host; + rig.WriteBacking32(PredicateWord, 0x1234); + host.NoteGuestMemoryWrite(PredicateWord, sizeof(uint), MetalGpuWriteOrigin.StorageBuffer); + var serial = host.SubmissionSerial; + var configured = MetalRenderHost.GuardReadsRefusePending; + MetalRenderHost.GuardReadsRefusePending = refuse; + try + { + using var reads = SharpEmu.ShaderCompiler.Resources.ResourceBranchWriteGuard.EnterReads(); + var concurrent = (IConcurrentResolveHost)host; + concurrent.BeginConcurrentResolve(); + object? assumptions = null; + try + { + if (refuse) + { + Assert.False(host.TryReadCleanGuestWord(PredicateWord, out _)); + } + else + { + Assert.Throws<GpuFatal.AbandonedWorkException>(() => host.TryReadCleanGuestWord(PredicateWord, out _)); + } + } + finally + { + assumptions = concurrent.EndConcurrentResolve(); + } + + if (refuse) + { + Assert.True(concurrent.IsStillCurrent(assumptions), "the refusal stands while the write is pending"); + } + + concurrent.ReleaseAssumptions(assumptions); + + if (refuse) + { + Assert.False(host.TryReadCleanGuestWord(PredicateWord, out _)); + Assert.True(host.CompletedSerial < serial, "the worker waited"); + } + else + { + Assert.True(host.TryReadCleanGuestWord(PredicateWord, out var word)); + Assert.Equal(0x1234u, word); + Assert.True(host.CompletedSerial >= serial); + } + } + finally + { + MetalRenderHost.GuardReadsRefusePending = configured; + } + + // Outside a guard's read the worker reads the landed value as before. + Assert.True(host.TryReadCleanGuestWord(PredicateWord, out var landed)); + Assert.Equal(0x1234u, landed); + } + [Fact] public void ACleanReadOfAPendingCopyDestinationIsAnsweredFromItsSourceOnBothThreads() { diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs index 89045fb40..3ec0060f7 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs @@ -1,7 +1,9 @@ // Copyright (C) 2026 SharpEmu Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later +using SharpEmu.Libs.Gpu.Images; using SharpEmu.Libs.Gpu.Rendering; +using SharpEmu.Libs.Tests.Gpu.Images; using SharpEmu.Libs.Tests.Gpu.Scheduling; using SharpEmu.ShaderCompiler.Resources; using Xunit; @@ -166,12 +168,37 @@ public void AMarkedDispatchIsCheckedAgainstEveryDispatchSinceTheLastOrderedOne() { DispatchMarked(1, [Written], [BufferDescriptor(BufferA, 4, 16)]); DispatchMarked(2, [Written], [BufferDescriptor(BufferB, 4, 16)]); - // Overlaps the first, two dispatches back, with no barrier between them either. - DispatchMarked(3, [Written], [BufferDescriptor(BufferA + 0x10, 4, 4)]); + // Reads what the first wrote, two dispatches back, with no barrier between them either. + DispatchMarked(3, [Read], [BufferDescriptor(BufferA + 0x10, 4, 4)]); Assert.Equal([true, true, false], _host.DispatchOverlaps); } + // Two marked dispatches writing the same buffer bytes, neither reading them, leave whichever lands last on the + // console too: they stay beside each other (SHARPEMU_DISPATCH_OVERLAP_WRITES_APART=0 orders them). A write over + // bytes the group read is ordered either way. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void MarkedWritesOfTheSameBytesThatNeitherReadsStayBesideEachOther(bool apart) + { + var saved = DispatchChain.OverlapWritesApart; + DispatchChain.OverlapWritesApart = apart; + try + { + DispatchMarked(1, [Written], [BufferDescriptor(BufferA, 4, 16)]); + DispatchMarked(2, [Written], [BufferDescriptor(BufferA + 0x10, 4, 4)]); + DispatchMarked(3, [Read], [BufferDescriptor(BufferB, 4, 16)]); + DispatchMarked(4, [Written], [BufferDescriptor(BufferB + 0x10, 4, 4)]); + + Assert.Equal([true, apart, true, false], _host.DispatchOverlaps); + } + finally + { + DispatchChain.OverlapWritesApart = saved; + } + } + [Fact] public void AMarkedDispatchWhoseAccessesAreNotAllKnownIsOrdered() { @@ -190,6 +217,50 @@ public void AMarkedDispatchWhoseAccessesAreNotAllKnownIsOrdered() Assert.Equal(before.Unknown + 1, DispatchChainTally.OverlapsOrdered.Unknown); } + // A marked dispatch sampling an image beside one that wrote an image meets it only where their data does (the span + // the request builders resolve); SHARPEMU_DISPATCH_OVERLAP_IMAGE_SPANS=0 makes any written image meet every other. + [Theory] + [InlineData(false, true, true)] + [InlineData(true, true, false)] + [InlineData(false, false, false)] + public void AMarkedDispatchMeetsAnImageWrittenBesideItOnlyWhereTheirDataMeets(bool sameImage, bool spans, bool overlaps) + { + var saved = DispatchChain.OverlapImageSpans; + DispatchChain.OverlapImageSpans = spans; + try + { + const ulong written = 0x1_7000_0000; + DispatchImage(1, written, store: true); + DispatchImage(2, sameImage ? written : written + 0x100_0000, store: false); + + Assert.Equal([true, overlaps], _host.DispatchOverlaps); + } + finally + { + DispatchChain.OverlapImageSpans = saved; + } + } + + private void DispatchImage(ulong submitId, ulong address, bool store) + { + var image = new ImageResource + { + ResourceClass = store ? SharpEmu.ShaderCompiler.Resources.ImageResourceClass.Storage : SharpEmu.ShaderCompiler.Resources.ImageResourceClass.Sampled, + NumericClass = ImageNumericClass.Float, + Dimension = ImageDimension.Dim2D, + Written = store, + }; + var program = new ShaderProgramInfo + { + Stage = ShaderStageKind.Compute, + Images = [new ImageResourceInfo(store ? SharpEmu.Libs.Gpu.Rendering.ImageResourceClass.Storage : SharpEmu.Libs.Gpu.Rendering.ImageResourceClass.Sampled, store)], + Resources = new SpecializedResourceInfo { Info = new ShaderResourceInfo { Images = [image] } }, + }; + var words = RegisterWords.Texture(address, GuestPixelFormat.Bits11_11_10Float, 256, 256, tile: GuestTileMode.RenderTarget); + _pipelines.Compute = ComputeProgram(new ShaderStageResources(program, new ResourceSnapshot { Images = [words] })); + _executor.Dispatch(submitId, Banks(), 1, 1, 1, 0x41 | RenderExecutor.DispatchMayOverlapBit); + } + [Fact] public void AnUndeferredHostKeepsTheAccessBarrierAfterEveryDispatch() { From ccd7c329b804c9822cef2b5222c4a78e355053d2 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 19:45:54 +0000 Subject: [PATCH 131/134] [Shader] Keep a plan with device-descriptor tables on the interpreted device-address ranges The compiled ranges (CompiledDeviceAddressRanges) evaluate a plan's ranges and its function V#s but have no device-descriptor table tail: the reference (DeviceAddressRangePlanner.EvaluateInterpreted) adds the buffers each table can select, or an unplanned written range. Once the SRT compiler finished, a store through V#s loaded from a table at a run-time offset therefore had no range: its writes were never recorded as pending and the dispatch chain saw no access to order on. Such a plan now stays on the interpreter, counted (descriptor_table_refusals on the PLAN_BUILDS line) and logged once per program ([SHADER][COMPILED-RANGES]). The test compares the written ranges of the binning program with the compiled ranges on and off. --- .../Resources/CompiledDeviceAddressRanges.cs | 24 ++++++++++ .../Resources/ResourcePlanBuildCounters.cs | 11 ++++- ...eviceAddressRangeTests.DescriptorTables.cs | 44 +++++++++++++++++++ .../Resources/DeviceDescriptorTableTests.cs | 6 +-- 4 files changed, 81 insertions(+), 4 deletions(-) create mode 100644 tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledDeviceAddressRangeTests.DescriptorTables.cs diff --git a/src/SharpEmu.ShaderCompiler/Resources/CompiledDeviceAddressRanges.cs b/src/SharpEmu.ShaderCompiler/Resources/CompiledDeviceAddressRanges.cs index f7987ced8..344f82454 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/CompiledDeviceAddressRanges.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/CompiledDeviceAddressRanges.cs @@ -21,6 +21,11 @@ namespace SharpEmu.ShaderCompiler.Resources; // The range assembly and the function-buffer tail are the reference's code with only the value evaluation replaced. // The function-buffer accesses are listed once per plan, and a call allocates nothing but its result array. // A plan with a cycle, a malformed node or more than MaxBlocks nodes stays on the interpreter. +// So does a plan with device-descriptor tables (stores through V#s it loads from a table at a run-time offset): the +// reference adds the buffers each table can select, or an unplanned written range, after the function V#s, and this +// code has no such tail. Compiled, those stores had no range once the SRT compiler finished, so their writes were never +// recorded as pending and a later host read of the bytes did not wait for them. Counted as descriptor_table_refusals on +// the PLAN_BUILDS line and logged once per program ([SHADER][COMPILED-RANGES]). // CallRecordPlanner.AddRecordRanges evaluates each callee's computed V#s (CallRecordBufferWords) the same way, compiled // once per callee, with the record helper's own rules: one memo per record, shared by its buffers; the user data a record // reads is what WithCallArguments builds (the draw's, zeros up to the argument registers, then the argument) without @@ -104,6 +109,12 @@ private CompiledDeviceAddressRanges(ShaderResourcePlan plan, FunctionBuffer[]? f return [.. functions]; } + // The refusal of a plan with device-descriptor tables (see the class comment). + internal const string DescriptorTablesRefusal = "descriptor_tables"; + + // The program hashes whose refusal was logged: one line per program for the session. + private static readonly System.Collections.Concurrent.ConcurrentDictionary<ulong, byte> DescriptorTableRefusalsLogged = new(); + // ShaderResourcePlan.CompileEvaluatorNow builds it under the plan's compile gate; null while the switch is off. internal static CompiledDeviceAddressRanges? TryBuild(ShaderResourcePlan plan) { @@ -132,6 +143,19 @@ internal static CompiledDeviceAddressRanges Build(ShaderResourcePlan plan, bool? if (plan.CallRecordCallees[callee].BufferWords is { Length: > 0 } buffers) records[callee] = RecordRanges.Build(plan, buffers); } + if (plan.DeviceDescriptorTables.Count != 0) + { + ResourcePlanBuildCounters.RecordDescriptorTableRefusal(); + if (DescriptorTableRefusalsLogged.TryAdd(plan.Hash, 0)) + { + Console.Error.WriteLine(FormattableString.Invariant( + $"[SHADER][COMPILED-RANGES] hash=0x{plan.Hash:X16} stage={plan.Stage} stays on the interpreted ranges: ") + + FormattableString.Invariant($"{plan.DeviceDescriptorTables.Count} device-descriptor table(s) the compiled ranges do not evaluate")); + } + + return new(plan, null, null, 0, DescriptorTablesRefusal, records); + } + var ranges = plan.DeviceAddressRanges; var functions = FunctionBuffers(plan); var roots = new List<(int Root, ScalarValue Value)>(); diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourcePlanBuildCounters.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourcePlanBuildCounters.cs index e77397f05..cd1f98cb5 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourcePlanBuildCounters.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourcePlanBuildCounters.cs @@ -26,12 +26,21 @@ internal static void RecordTransaction() Interlocked.Increment(ref _totalMethods); } + private static long _descriptorTableRefusals; + + // A plan whose device-address ranges stay on the interpreter for its device-descriptor tables + // (CompiledDeviceAddressRanges.DescriptorTablesRefusal); counted for the whole session. + internal static void RecordDescriptorTableRefusal() => Interlocked.Increment(ref _descriptorTableRefusals); + + internal static long DescriptorTableRefusals => Interlocked.Read(ref _descriptorTableRefusals); + /// <summary>The builds since the previous call, as one report line.</summary> public static string TakeReport() { var methods = Interlocked.Exchange(ref _evaluatorMethods, 0); var transactions = Interlocked.Exchange(ref _transactions, 0); return FormattableString.Invariant( - $"[PERF][PLAN_BUILDS] dynamic_methods={methods} transactions={transactions} total={Volatile.Read(ref _totalMethods)}"); + $"[PERF][PLAN_BUILDS] dynamic_methods={methods} transactions={transactions} total={Volatile.Read(ref _totalMethods)} ") + + FormattableString.Invariant($"descriptor_table_refusals={DescriptorTableRefusals}"); } } diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledDeviceAddressRangeTests.DescriptorTables.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledDeviceAddressRangeTests.DescriptorTables.cs new file mode 100644 index 000000000..2bb249444 --- /dev/null +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/CompiledDeviceAddressRangeTests.DescriptorTables.cs @@ -0,0 +1,44 @@ +// Copyright (C) 2026 SharpEmu Emulator Project +// SPDX-License-Identifier: GPL-2.0-or-later + +using System.Linq; +using SharpEmu.ShaderCompiler.Resources; +using Xunit; +using static SharpEmu.ShaderCompiler.Tests.Resources.ResourceTestProgram; + +namespace SharpEmu.ShaderCompiler.Tests.Resources; + +public sealed partial class CompiledDeviceAddressRangeTests +{ + // A store through V#s a loop loads from a table (DeviceDescriptorTableTests.BinningProgram) once the SRT compiler has + // built the plan's ranges: the written buffers the table selects, as the interpreter gives them. The compiled ranges + // had no device-descriptor table tail and gave none, so the store's writes were never pending. + [Theory] + [InlineData(3u)] + [InlineData((uint)DeviceAddressRangePlanner.MaxDescriptorTableEntries + 1)] + public void DescriptorTableStores_KeepTheirWrittenRangesOnceCompiled(uint count) + { + (DeviceAddressRange[] Ranges, string? Refusal) Written(Path path) + { + using var scope = new Scope(path); + var plan = Extract(DeviceDescriptorTableTests.BinningProgram()); + Assert.Single(plan.DeviceDescriptorTables); + plan.CompileEvaluatorNow(); + var memory = DeviceDescriptorTableTests.TableMemory(count); + var ranges = DeviceAddressRangePlanner.Evaluate(plan, Inputs([(uint)DeviceDescriptorTableTests.Table, 0], memory.Read)) + .Where(range => range.Written).ToArray(); + return (ranges, (plan.CompiledRanges as CompiledDeviceAddressRanges)?.Refusal); + } + + var refusals = ResourcePlanBuildCounters.DescriptorTableRefusals; + var interpreted = Written(Path.Off); + var compiled = Written(Path.On); + + Assert.NotEmpty(interpreted.Ranges); + Assert.Equal( + interpreted.Ranges.Select(range => (range.Base, range.Size, range.Planned)).ToArray(), + compiled.Ranges.Select(range => (range.Base, range.Size, range.Planned)).ToArray()); + Assert.Equal(CompiledDeviceAddressRanges.DescriptorTablesRefusal, compiled.Refusal); + Assert.True(ResourcePlanBuildCounters.DescriptorTableRefusals > refusals); + } +} diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/DeviceDescriptorTableTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/DeviceDescriptorTableTests.cs index a754e5c71..2f8626096 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/DeviceDescriptorTableTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/DeviceDescriptorTableTests.cs @@ -15,11 +15,11 @@ namespace SharpEmu.ShaderCompiler.Tests.Resources; // instead of all of guest memory; anything the draw cannot bound stays unplanned. public sealed class DeviceDescriptorTableTests { - private const ulong Table = 0x1000; + internal const ulong Table = 0x1000; private const int CountOffset = 136; // s3 = 0; header: s10 = count at [s0:s1 + 136]; while (s3 < s10) { s[4:7] = [s0:s1 + (s3 << 4) + 16]; store; s3++ } - private static Gen5ShaderProgram BinningProgram(uint guardRegister = 3) + internal static Gen5ShaderProgram BinningProgram(uint guardRegister = 3) { var instructions = new List<Gen5ShaderInstruction>(); uint pc = 0; @@ -47,7 +47,7 @@ void Add(Gen5ShaderInstruction instruction) return Program([.. instructions]); } - private static TestWordMemory TableMemory(uint count) + internal static TestWordMemory TableMemory(uint count) { var memory = new TestWordMemory { Base = Table, Words = new uint[64] }; memory.At(Table + CountOffset) = count; From 10d456b759a15590901883f0dbf9d3f1fd4c12c7 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 20:17:55 +0000 Subject: [PATCH 132/134] [GPU] Keep marked dispatches whose shared buffer bytes both sides only touch by atomics beside each other A sample of DispatchChain's read-after-write orderings in Demon's Souls (a temporary log, not kept: 600 at spawn idle) found 571 of 600 between dispatches that both bind the same buffer and use atomics on it: chains of indirect dispatches bumping a shared counter buffer (0xFF40D2EE7ACD4299, 0x53E6C4CECB347B31 -> 0x0EE5D04A33C19457, 0xF643EC7184F97AA5 -> 0xF2B77B2C701C4AAA: one atomic_fetch_add at an index from the resource table). Atomics against atomics have no order to keep: the GPU performs each whole, as the console does with the two running together. The resource tracker now records whether a buffer has any access that is not an atomic (BufferResource.PlainAccess), the program info carries BufferResourceInfo.AtomicOnly, and KeepsOverlap checks a buffer accessed only by atomics against the other side's plain reads and writes but not against its atomics (counted as atomics_apart; SHARPEMU_DISPATCH_OVERLAP_ATOMICS_APART=0 orders them again). Plain reads after writes, an atomic beside a plain access, and indirect arguments read where a dispatch wrote still order, so the HostKernelCopy reader stays after its copy. DS orderings per 5 s: ~7,000 -> ~2,300 (raw 870-1,230, image ~960, war ~240, indirect ~140). --- .../Gpu/Pipelines/ShaderProgramCache.cs | 3 +- .../Gpu/Rendering/DispatchChain.cs | 61 +++++++++++++++++-- .../Gpu/Rendering/ShaderStageResources.cs | 4 +- .../Resources/ResourceTracker.cs | 1 + .../Resources/ShaderResourceInfo.cs | 2 + .../Gpu/Rendering/DispatchChainTests.cs | 31 ++++++++++ .../Resources/ResourceTrackerTests.cs | 15 +++++ 7 files changed, 110 insertions(+), 7 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs index 0b07d1ef9..2f770613c 100644 --- a/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs +++ b/src/SharpEmu.Libs/Gpu/Pipelines/ShaderProgramCache.cs @@ -3436,7 +3436,8 @@ private static ShaderProgramInfo CreateProgramInfo( for (var index = 0; index < buffers.Length; index++) { var buffer = info.Buffers[index]; - buffers[index] = new BufferResourceInfo(buffer.Read, buffer.Written, buffer.Atomic, buffer.Formatted, buffer.Scalar, buffer.MaxByteExtent, buffer.PackedStride); + buffers[index] = new BufferResourceInfo(buffer.Read, buffer.Written, buffer.Atomic, buffer.Formatted, buffer.Scalar, buffer.MaxByteExtent, buffer.PackedStride, + AtomicOnly: buffer.Atomic && !buffer.PlainAccess); } var images = new ImageResourceInfo[info.Images.Count]; diff --git a/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs b/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs index 0b54088ab..87c37d335 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs @@ -42,8 +42,14 @@ internal sealed class DispatchChain private readonly List<GuestSpan> _groupImageTouched = new(); private readonly List<GuestSpan> _groupImageWritten = new(); private bool _groupImagesUnresolved; + // For the group's checks: the bytes read and written other than by atomics, and those of buffers every access of + // which is an atomic (BufferResourceInfo.AtomicOnly), which are both read and written. private readonly List<GuestSpan> _groupRead = new(); + private readonly List<GuestSpan> _groupPlainWritten = new(); + private readonly List<GuestSpan> _groupAtomic = new(); private readonly List<GuestSpan> _recordRead = new(); + private readonly List<GuestSpan> _recordPlainWritten = new(); + private readonly List<GuestSpan> _recordAtomic = new(); private readonly List<GuestSpan> _recordImageTouched = new(); private readonly List<GuestSpan> _recordImageWritten = new(); private bool _recordImagesUnresolved; @@ -58,7 +64,8 @@ internal sealed class DispatchChain /// writes what one of them touched, or whose accesses (or theirs) are not all known is ordered after them instead, /// and counted (<see cref="DispatchChainTally.OverlapsOrdered"/>, by cause in the report). An image meets another /// only where their data does (<see cref="OverlapImageSpans"/>), and two writes of the same buffer bytes that neither - /// reads are not ordered (<see cref="OverlapWritesApart"/>). SHARPEMU_DISPATCH_OVERLAP_HAZARDS=0 runs every + /// reads are not ordered (<see cref="OverlapWritesApart"/>), nor atomics against atomics on buffers both sides access + /// solely through atomics (<see cref="OverlapAtomicsApart"/>). SHARPEMU_DISPATCH_OVERLAP_HAZARDS=0 runs every /// marked dispatch beside the ones before it again. /// </summary> public bool KeepsOverlap(bool marked) @@ -81,15 +88,31 @@ public bool KeepsOverlap(bool marked) { cause = OverlapCause.Indirect; } - else if (Overlaps(_recordRead, _groupWritten)) + else if (Overlaps(_recordRead, _groupPlainWritten) || Overlaps(_recordRead, _groupAtomic) || + Overlaps(_recordAtomic, _groupPlainWritten)) { cause = OverlapCause.BufferReadAfterWrite; } - else if (Overlaps(_recordWritten, _groupRead)) + else if (Overlaps(_recordPlainWritten, _groupRead) || Overlaps(_recordPlainWritten, _groupAtomic) || + Overlaps(_recordAtomic, _groupRead)) { cause = OverlapCause.BufferWriteAfterRead; } - else if (Overlaps(_recordWritten, _groupWritten)) + else if (Overlaps(_recordAtomic, _groupAtomic)) + { + // Atomics against atomics: the GPU performs each one whole, in whatever order the two dispatches reach the + // bytes, as the console does with the two running together (an append counter both bump). Nothing else + // either of them does touches those bytes, so they stay beside each other (OverlapAtomicsApart). + if (OverlapAtomicsApart) + { + DispatchChainTally.NoteOverlapAtomicsApart(); + } + else + { + cause = OverlapCause.BufferAtomics; + } + } + else if (Overlaps(_recordPlainWritten, _groupPlainWritten)) { // Writes of the same bytes with no read of them between leave whichever lands last on the console as well: // nothing reads a value the order decides, so they stay beside each other (OverlapWritesApart). @@ -142,6 +165,11 @@ public bool KeepsOverlap(bool marked) internal static bool OverlapWritesApart { get; set; } = Environment.GetEnvironmentVariable("SHARPEMU_DISPATCH_OVERLAP_WRITES_APART") != "0"; + // SHARPEMU_DISPATCH_OVERLAP_ATOMICS_APART (on by default, =0 off): a marked dispatch whose buffers meet the group's + // only where both sides access buffers solely through atomics stays beside it; off, it is ordered after it. + internal static bool OverlapAtomicsApart { get; set; } = + Environment.GetEnvironmentVariable("SHARPEMU_DISPATCH_OVERLAP_ATOMICS_APART") != "0"; + internal static bool OverlapImageSpans { get; set; } = Environment.GetEnvironmentVariable("SHARPEMU_DISPATCH_OVERLAP_IMAGE_SPANS") != "0"; @@ -150,6 +178,8 @@ private void ResetGroup() _groupTouched.Clear(); _groupWritten.Clear(); _groupRead.Clear(); + _groupPlainWritten.Clear(); + _groupAtomic.Clear(); _groupConservative = false; _groupReadImages = false; _groupWroteImages = false; @@ -163,6 +193,8 @@ private void AddToGroup() _groupTouched.AddRange(_recordTouched); _groupWritten.AddRange(_recordWritten); _groupRead.AddRange(_recordRead); + _groupPlainWritten.AddRange(_recordPlainWritten); + _groupAtomic.AddRange(_recordAtomic); _groupConservative |= _recordConservative; _groupReadImages |= _recordReadsImages; _groupWroteImages |= _recordWritesImages; @@ -236,6 +268,8 @@ private void Collect(ResolvedDispatch record, in ShaderStageResources stage) _recordTouched.Clear(); _recordWritten.Clear(); _recordRead.Clear(); + _recordPlainWritten.Clear(); + _recordAtomic.Clear(); _recordConservative = false; _recordReadsImages = false; _recordWritesImages = false; @@ -293,6 +327,17 @@ private void Collect(ResolvedDispatch record, in ShaderStageResources stage) _recordWritten.Add(span); } + if (info.AtomicOnly) + { + _recordAtomic.Add(span); + continue; + } + + if (info.Written) + { + _recordPlainWritten.Add(span); + } + // A buffer the shader neither reads nor writes per its info counts as read. if (info.Read || info.Atomic || !info.Written) { @@ -353,6 +398,7 @@ private void Collect(ResolvedDispatch record, in ShaderStageResources stage) if (range.Written) { _recordWritten.Add(span); + _recordPlainWritten.Add(span); } } @@ -407,6 +453,7 @@ internal enum OverlapCause BufferReadAfterWrite, BufferWriteAfterRead, BufferWriteAfterWrite, + BufferAtomics, Image, ImageUnresolved, Count, @@ -441,6 +488,10 @@ public static void Count(ChainDecision decision) private static readonly long[] _overlapCauses = new long[(int)OverlapCause.Count]; private static long _overlapImagesApart; private static long _overlapWritesApart; + private static long _overlapAtomicsApart; + + /// <summary>A marked dispatch kept beside the group although both access the same bytes, each solely by atomics.</summary> + internal static void NoteOverlapAtomicsApart() => Interlocked.Increment(ref _overlapAtomicsApart); /// <summary>A marked dispatch kept beside the group although both write the same buffer bytes, neither reading them.</summary> internal static void NoteOverlapWritesApart() => Interlocked.Increment(ref _overlapWritesApart); @@ -468,7 +519,7 @@ public static string TakeOverlapReport() => FormattableString.Invariant($"overlap_by=[indirect:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.Indirect], 0)},raw:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.BufferReadAfterWrite], 0)},") + FormattableString.Invariant($"war:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.BufferWriteAfterRead], 0)},waw:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.BufferWriteAfterWrite], 0)},") + FormattableString.Invariant($"image:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.Image], 0)},image_unresolved:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.ImageUnresolved], 0)},") + - FormattableString.Invariant($"images_apart:{Interlocked.Exchange(ref _overlapImagesApart, 0)},writes_apart:{Interlocked.Exchange(ref _overlapWritesApart, 0)}]"); + FormattableString.Invariant($"images_apart:{Interlocked.Exchange(ref _overlapImagesApart, 0)},writes_apart:{Interlocked.Exchange(ref _overlapWritesApart, 0)},atomics:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.BufferAtomics], 0)},atomics_apart:{Interlocked.Exchange(ref _overlapAtomicsApart, 0)}]"); public static string TakeReport() => FormattableString.Invariant($"chain_open={Interlocked.Exchange(ref _decisions[(int)ChainDecision.Open], 0)} chain_start={Interlocked.Exchange(ref _decisions[(int)ChainDecision.Start], 0)} ") + diff --git a/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs b/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs index 256701583..ca6c83e63 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/ShaderStageResources.cs @@ -36,7 +36,9 @@ public readonly record struct BufferResourceInfo( uint MaxByteExtent, // The specialization's packed stride word (BufferResource.PackedStride): the executor matches a known write's // descriptor against it. Zero for a program the SPIR-V translator compiled with strides in shader data. - uint PackedStride = 0); + uint PackedStride = 0, + // Every access the program makes through the buffer is an atomic (BufferResource.PlainAccess unset). + bool AtomicOnly = false); // How a compiled program uses one image resource. public readonly record struct ImageResourceInfo(ImageResourceClass Class, bool Written); diff --git a/src/SharpEmu.ShaderCompiler/Resources/ResourceTracker.cs b/src/SharpEmu.ShaderCompiler/Resources/ResourceTracker.cs index ffe88efa8..dc2282302 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ResourceTracker.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ResourceTracker.cs @@ -1094,6 +1094,7 @@ private static void Merge(BufferResource resource, MemoryAccessInfo memory, uint resource.Read |= !write || atomic; resource.Written |= write; resource.Atomic |= atomic; + resource.PlainAccess |= !atomic; resource.Formatted |= memory.Formatted; resource.Scalar |= memory.Kind == MemoryResourceKind.ScalarBuffer; } diff --git a/src/SharpEmu.ShaderCompiler/Resources/ShaderResourceInfo.cs b/src/SharpEmu.ShaderCompiler/Resources/ShaderResourceInfo.cs index 0cb2c0beb..97d5a0d89 100644 --- a/src/SharpEmu.ShaderCompiler/Resources/ShaderResourceInfo.cs +++ b/src/SharpEmu.ShaderCompiler/Resources/ShaderResourceInfo.cs @@ -57,6 +57,8 @@ public sealed class BufferResource public bool Read { get; set; } public bool Written { get; set; } public bool Atomic { get; set; } + // A load or a store through the buffer that is not an atomic: without one, every access is an atomic. + public bool PlainAccess { get; set; } public bool Formatted { get; set; } public bool Scalar { get; set; } diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs index 3ec0060f7..5ae50e9ed 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs @@ -29,6 +29,11 @@ public sealed class DispatchChainTests : IDisposable private static BufferResourceInfo Read => new(true, false, false, false, false, 4); + private static BufferResourceInfo AtomicOnly => new(true, true, true, false, false, 4, AtomicOnly: true); + + // Atomics beside a load or a store of the same buffer. + private static BufferResourceInfo AtomicAndPlain => new(true, true, true, false, false, 4); + private void Dispatch(ulong submitId, BufferResourceInfo[] buffers, uint[][] descriptors) { _pipelines.Compute = ComputeProgram(Stage(Program(ShaderStageKind.Compute, buffers: buffers), buffers: descriptors)); @@ -261,6 +266,32 @@ private void DispatchImage(ulong submitId, ulong address, bool store) _executor.Dispatch(submitId, Banks(), 1, 1, 1, 0x41 | RenderExecutor.DispatchMayOverlapBit); } + // Two marked dispatches bumping the same counters, each through atomics alone, run beside each other as on the + // console (SHARPEMU_DISPATCH_OVERLAP_ATOMICS_APART=0 orders them). A load of the counters after their atomics, or a + // buffer the shader also loads or stores, is ordered either way. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void MarkedAtomicsOnTheSameBytesStayBesideEachOther(bool apart) + { + var saved = DispatchChain.OverlapAtomicsApart; + DispatchChain.OverlapAtomicsApart = apart; + try + { + DispatchMarked(1, [AtomicOnly], [BufferDescriptor(BufferA, 4, 16)]); + DispatchMarked(2, [AtomicOnly], [BufferDescriptor(BufferA + 0x10, 4, 4)]); + DispatchMarked(3, [Read], [BufferDescriptor(BufferA, 4, 16)]); + DispatchMarked(4, [AtomicAndPlain], [BufferDescriptor(BufferB, 4, 16)]); + DispatchMarked(5, [AtomicAndPlain], [BufferDescriptor(BufferB + 0x10, 4, 4)]); + + Assert.Equal([true, apart, false, true, false], _host.DispatchOverlaps); + } + finally + { + DispatchChain.OverlapAtomicsApart = saved; + } + } + [Fact] public void AnUndeferredHostKeepsTheAccessBarrierAfterEveryDispatch() { diff --git a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceTrackerTests.cs b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceTrackerTests.cs index fcf7ebb1f..5bccaa90f 100644 --- a/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceTrackerTests.cs +++ b/tests/SharpEmu.ShaderCompiler.Tests/Resources/ResourceTrackerTests.cs @@ -31,6 +31,21 @@ public void ImageAtomicOnTwoDataDwordsIsMarkedWide(string opcode, uint dmask, bo Assert.Equal(wide, image.Atomic64); } + // A buffer accessed only by atomics has no plain access; a load beside the atomic gives it one. + [Theory] + [InlineData(false, false)] + [InlineData(true, true)] + public void ABufferWithOnlyAtomicsHasNoPlainAccess(bool load, bool plain) + { + var plan = load + ? Extract(Program(BufferAtomicAdd(0, 0), BufferLoad(8, 0, 4), EndProgram(16))) + : Extract(Program(BufferAtomicAdd(0, 0), EndProgram(8))); + + var buffer = Assert.Single(plan.Info.Buffers); + Assert.True(buffer.Atomic); + Assert.Equal(plain, buffer.PlainAccess); + } + // A descriptor word that 40 branches each change on both sides is a web with 2^40 paths. Planning and evaluating // it must look at each node once: walking every path did not finish. [Fact] From 32a7bbf6369579ed7d854ddd2bb9c59a777e1b26 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 21:16:56 +0000 Subject: [PATCH 133/134] [GPU] Treat an image a marked dispatch only stores to as written, not read A sample of the orderings left after the atomics change found the image ones were a chain of ~30 different compute shaders (0x3C6342F9CA7E18C5, 0x633313A2D1C1E448, ...) each storing to the same image with no barrier between them, as one lighting pass split by tile class. KeepsOverlap counted every image a dispatch uses as read, so each store met the previous store as a read after a write. An image is now read only when the shader loads, samples or does atomics on it (ImageResource.Read/Atomic); two dispatches that only store to the same image meet as two buffer writes do, beside each other (SHARPEMU_DISPATCH_OVERLAP_WRITES_APART=0 orders them, counted image_waw). A load of an image a group member stored to still orders. --- .../Gpu/Rendering/DispatchChain.cs | 33 ++++++++++++------- .../Gpu/Rendering/DispatchChainTests.cs | 27 ++++++++++++++- 2 files changed, 47 insertions(+), 13 deletions(-) diff --git a/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs b/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs index 87c37d335..2c821cf11 100644 --- a/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs +++ b/src/SharpEmu.Libs/Gpu/Rendering/DispatchChain.cs @@ -39,7 +39,7 @@ internal sealed class DispatchChain private bool _groupWroteImages; // The data each image the group's and this dispatch's shaders use covers (OverlapImageSpans), and whether one of them // has none the request builders resolve. - private readonly List<GuestSpan> _groupImageTouched = new(); + private readonly List<GuestSpan> _groupImageRead = new(); private readonly List<GuestSpan> _groupImageWritten = new(); private bool _groupImagesUnresolved; // For the group's checks: the bytes read and written other than by atomics, and those of buffers every access of @@ -50,7 +50,7 @@ internal sealed class DispatchChain private readonly List<GuestSpan> _recordRead = new(); private readonly List<GuestSpan> _recordPlainWritten = new(); private readonly List<GuestSpan> _recordAtomic = new(); - private readonly List<GuestSpan> _recordImageTouched = new(); + private readonly List<GuestSpan> _recordImageRead = new(); private readonly List<GuestSpan> _recordImageWritten = new(); private bool _recordImagesUnresolved; private GuestSpan _recordIndirect; @@ -63,8 +63,8 @@ internal sealed class DispatchChain /// finishing before its consumer reads) becomes a race here. A marked dispatch that touches what one of them wrote, /// writes what one of them touched, or whose accesses (or theirs) are not all known is ordered after them instead, /// and counted (<see cref="DispatchChainTally.OverlapsOrdered"/>, by cause in the report). An image meets another - /// only where their data does (<see cref="OverlapImageSpans"/>), and two writes of the same buffer bytes that neither - /// reads are not ordered (<see cref="OverlapWritesApart"/>), nor atomics against atomics on buffers both sides access + /// only where their data does (<see cref="OverlapImageSpans"/>), and two writes of the same buffer or image bytes that + /// neither reads are not ordered (<see cref="OverlapWritesApart"/>), nor atomics against atomics on buffers both sides access /// solely through atomics (<see cref="OverlapAtomicsApart"/>). SHARPEMU_DISPATCH_OVERLAP_HAZARDS=0 runs every /// marked dispatch beside the ones before it again. /// </summary> @@ -128,10 +128,13 @@ public bool KeepsOverlap(bool marked) if (cause == OverlapCause.None && imagesMeet) { - // Two images meet only where their data does; one whose data is not resolved meets every other. + // Two images meet only where their data does; one whose data is not resolved meets every other. Images both + // sides only write meet as two buffer writes do (OverlapWritesApart). cause = !OverlapImageSpans || _recordImagesUnresolved || _groupImagesUnresolved ? OverlapCause.ImageUnresolved - : Overlaps(_recordImageTouched, _groupImageWritten) || Overlaps(_recordImageWritten, _groupImageTouched) - ? OverlapCause.Image : OverlapCause.None; + : Overlaps(_recordImageRead, _groupImageWritten) || Overlaps(_recordImageWritten, _groupImageRead) + ? OverlapCause.Image + : Overlaps(_recordImageWritten, _groupImageWritten) && !OverlapWritesApart ? OverlapCause.ImageWriteAfterWrite + : OverlapCause.None; if (cause == OverlapCause.None) { DispatchChainTally.NoteOverlapImagesApart(); @@ -183,7 +186,7 @@ private void ResetGroup() _groupConservative = false; _groupReadImages = false; _groupWroteImages = false; - _groupImageTouched.Clear(); + _groupImageRead.Clear(); _groupImageWritten.Clear(); _groupImagesUnresolved = false; } @@ -198,7 +201,7 @@ private void AddToGroup() _groupConservative |= _recordConservative; _groupReadImages |= _recordReadsImages; _groupWroteImages |= _recordWritesImages; - _groupImageTouched.AddRange(_recordImageTouched); + _groupImageRead.AddRange(_recordImageRead); _groupImageWritten.AddRange(_recordImageWritten); _groupImagesUnresolved |= _recordImagesUnresolved; } @@ -273,7 +276,7 @@ private void Collect(ResolvedDispatch record, in ShaderStageResources stage) _recordConservative = false; _recordReadsImages = false; _recordWritesImages = false; - _recordImageTouched.Clear(); + _recordImageRead.Clear(); _recordImageWritten.Clear(); _recordImagesUnresolved = false; _recordIndirect = default; @@ -371,7 +374,12 @@ private void Collect(ResolvedDispatch record, in ShaderStageResources stage) if (shapes is not null && index < shapes.Count && RenderExecutor.TryGetImageData(program, shapes[index], words, index, out var data)) { - _recordImageTouched.Add(data); + // An image the shader only stores to is not read (ImageResource.Read: loads, samples and atomics). + if (!written || shapes[index].Read || shapes[index].Atomic) + { + _recordImageRead.Add(data); + } + if (written) { _recordImageWritten.Add(data); @@ -455,6 +463,7 @@ internal enum OverlapCause BufferWriteAfterWrite, BufferAtomics, Image, + ImageWriteAfterWrite, ImageUnresolved, Count, } @@ -518,7 +527,7 @@ public static string TakeOverlapReport() => FormattableString.Invariant($"overlap_ordered=[hazard:{Interlocked.Exchange(ref _overlapsOrderedHazard, 0)},unknown:{Interlocked.Exchange(ref _overlapsOrderedUnknown, 0)}] ") + FormattableString.Invariant($"overlap_by=[indirect:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.Indirect], 0)},raw:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.BufferReadAfterWrite], 0)},") + FormattableString.Invariant($"war:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.BufferWriteAfterRead], 0)},waw:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.BufferWriteAfterWrite], 0)},") + - FormattableString.Invariant($"image:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.Image], 0)},image_unresolved:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.ImageUnresolved], 0)},") + + FormattableString.Invariant($"image:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.Image], 0)},image_waw:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.ImageWriteAfterWrite], 0)},image_unresolved:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.ImageUnresolved], 0)},") + FormattableString.Invariant($"images_apart:{Interlocked.Exchange(ref _overlapImagesApart, 0)},writes_apart:{Interlocked.Exchange(ref _overlapWritesApart, 0)},atomics:{Interlocked.Exchange(ref _overlapCauses[(int)OverlapCause.BufferAtomics], 0)},atomics_apart:{Interlocked.Exchange(ref _overlapAtomicsApart, 0)}]"); public static string TakeReport() => diff --git a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs index 5ae50e9ed..2f181f517 100644 --- a/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs +++ b/tests/SharpEmu.Libs.Tests/Gpu/Rendering/DispatchChainTests.cs @@ -246,10 +246,35 @@ public void AMarkedDispatchMeetsAnImageWrittenBesideItOnlyWhereTheirDataMeets(bo } } - private void DispatchImage(ulong submitId, ulong address, bool store) + // Two marked dispatches storing to the same image, neither reading it (tile classes of one lighting pass), stay beside + // each other; one that also loads the image it stores to is ordered after a store to it. + [Theory] + [InlineData(false, true, true)] + [InlineData(true, true, false)] + [InlineData(false, false, false)] + public void MarkedStoresToOneImageThatNeitherReadsStayBesideEachOther(bool secondLoads, bool apart, bool overlaps) + { + var saved = DispatchChain.OverlapWritesApart; + DispatchChain.OverlapWritesApart = apart; + try + { + const ulong written = 0x1_7000_0000; + DispatchImage(1, written, store: true); + DispatchImage(2, written, store: true, load: secondLoads); + + Assert.Equal([true, overlaps], _host.DispatchOverlaps); + } + finally + { + DispatchChain.OverlapWritesApart = saved; + } + } + + private void DispatchImage(ulong submitId, ulong address, bool store, bool load = false) { var image = new ImageResource { + Read = !store || load, ResourceClass = store ? SharpEmu.ShaderCompiler.Resources.ImageResourceClass.Storage : SharpEmu.ShaderCompiler.Resources.ImageResourceClass.Sampled, NumericClass = ImageNumericClass.Float, Dimension = ImageDimension.Dim2D, From c89a163339b1a8f5b72915dd5116d6176c48db11 Mon Sep 17 00:00:00 2001 From: kuba <xnetcat.dev@gmail.com> Date: Fri, 20 Nov 2026 22:26:03 +0000 Subject: [PATCH 134/134] [Docs] Describe the overlap narrowing switches and the write-guard read refusal --- docs/macos/configuration.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/macos/configuration.md b/docs/macos/configuration.md index 8745a1868..4d22fb1e5 100644 --- a/docs/macos/configuration.md +++ b/docs/macos/configuration.md @@ -144,6 +144,10 @@ undoes an optimization to isolate a miscompile: | `SHARPEMU_METAL_V2_POSTED_WORD_COPY_HOST_STORE` | on | How a posted word copy is applied. Upstream's Vulkan host stores the words on the host, which is sound there because GPU readers take a copy of their bytes when recorded. Metal reads guest memory in place, so the store is taken only when no recorded or submitted GPU work remains (`host_store`); otherwise the copy is refused as `busy` and runs as its dispatch, which readers read through as a pending copy. `0` posts every copy as a held command-processor write instead, which costs Demon's Souls about 20 ms a frame. | | `SHARPEMU_METAL_V2_CONCURRENT_OVERLAY_READS` | on | A look-ahead resolution, and the render thread's clean read, take words a pending command-processor write still owes from that write's overlay when it covers them whole, instead of abandoning the resolution or waiting for the GPU. Counted as `concurrent_overlay_reads` and `clean_overlay_reads`. `0` abandons and waits as before. | | `SHARPEMU_DISPATCH_OVERLAP_HAZARDS` | on | A dispatch the stream marks as free to overlap the ones before it (no barrier between them) is ordered after them when it reads what one of them wrote, writes what one of them touched, or either side's accesses are not all known. The console overlaps such dispatches too, but a dependency its timing hides is a race on the host. Counted as `overlap_ordered=[hazard:...,unknown:...]`. `0` honours every mark. | +| `SHARPEMU_DISPATCH_OVERLAP_WRITES_APART` | on | Two marked dispatches that only write the same buffer bytes or the same image, with no read on either side, stay beside each other. `0` orders them. | +| `SHARPEMU_DISPATCH_OVERLAP_ATOMICS_APART` | on | Two marked dispatches whose shared buffer bytes both sides touch only through atomics (a counter chain) stay beside each other. `0` orders them. | +| `SHARPEMU_DISPATCH_OVERLAP_IMAGE_SPANS` | on | Two images conflict for the overlap check only where their guest bytes meet. `0` treats any image written beside any image read or written as a conflict. | +| `SHARPEMU_GUARD_READS_REFUSE_PENDING` | on | A branch predicate word of a shader that writes memory (upstream's branch blocks for writers) is answered from the pending command-processor overlay or pending copy when a GPU write still owes it, and otherwise refused, so the shader keeps both paths of that branch. Counted as `guard_refused` in `clean_under_write`. `0` makes the render thread wait for the GPU and the look-ahead abandon, about 90 waits every 2 s in Demon's Souls. | | `SHARPEMU_METAL_V2_POSTED_WORD_COPY_EXACT_IMAGE` | on | A posted word copy is refused for an image only when an image's guest bytes lie in its destination. Sharing a page with an image is not enough (upstream 90d306cb1). `0` refuses any destination an image shares a page with. | ## Diagnostics