Repository navigation
[Sync] Merge upstream f1af467a6 and port its Vulkan changes to Metal - #53
Merged
Merged
Conversation
…line prewarm fixes (#1144)
… 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.
…ite 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.
… 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.
# Conflicts: # docs/macos/configuration.md # src/SharpEmu.Libs/Gpu/Pipelines/ShaderPrewarmCompiler.cs # src/SharpEmu.ShaderCompiler.Metal/Gen5MslCodegenOptions.cs # src/graphics/SharpEmu.Gpu.Metal/V2/MetalShaderPrewarm.cs
…etal for upstream f1af467
…se 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 (99f9fe9) 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.
…cy 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.
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).
…em again Port of upstream's bulk heap record reads (VulkanVideoPresenter.BindlessHeap.cs, 7cf0ac5 / 99f9fe9) 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.
…slator 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).
…ompare, 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).
…the chain, heap bulk reads and mark dedup on Metal for upstream f1af467
… 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.
…nd 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.
…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.
…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.
… the held-write cost, and overlap-marked dispatches ordered on a shared range
…ispatch overlap hazards switches
…d 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 (565323e) 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].
… 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.
…y 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).
… 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.
…se GPU-owned words, marked dispatches ordered only on real hazards
…ables stay on the interpreted device-address ranges
There was a problem hiding this comment.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.
📦 Build artifacts —
|
| Platform | Download |
|---|---|
| macOS (osx-x64) | sharpemu-osx-x64-05566f8 |
| macOS app bundle (osx-x64) | sharpemu-osx-x64-app-05566f8 |
From build run #469. Downloads require a GitHub login and expire after 90 days.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Before submitting
Please read our contribution guidelines before opening a pull request:
➡️ CONTRIBUTING.md
By opening this pull request, you confirm that you have read and agree to follow the contribution guidelines.
Summary
Merges upstream sharpemu/sharpemu main up to f1af467 (58 commits past 1cebe9a) and ports what upstream wrote for its Vulkan host to Metal. Nothing upstream added in this range is left as a refusal on Metal unless Metal has no equivalent; those cases are listed under "No port needed".
What needed a port
Each item is on by default and has an off-switch in
docs/macos/configuration.md.simd_sum/min/max/and/or/xorfor the wave32 row scan), a stand-in for the device clock, and scalar data read on the device.SHARPEMU_LINKED_COMPILE_WAIT_MSand is then counted and logged, never skipped silently.busy).Fixes found by the game checks
ShaderPipelineCachemethods no longer implemented their interface members, and the interface defaults answered. Fixed, with a reflection test over every class that shadows an interface default this way.HostKernelCopySceneTestsfailed 7 of 8 times; main 0 of 8). A dispatch marked as free to overlap is now ordered after the ones before it when it reads what they wrote; pairs that only write, or only touch shared bytes through atomics, stay side by side.How conflicts were resolved
src/SharpEmu.Libs/Gpu) upstream's changes are taken and this fork's dispatch and draw look-ahead is kept beside them.SHARPEMU_INDIRECT_INSTANCE_INHERIT=1restores the fork's behaviour.SharpEmu.Libsinto the Vulkan project, which the macOS build does not include.docs/macos/configuration.md: both sides' rows kept.No port needed
Testing
Tip c89a163, against main 5cb184e, base M4 with 24 GB.
uvx reuse lintclean; Release build 0 errors; Python build-tool tests pass.dotnet testper project: all pass (Libs 11527, ShaderCompiler.Metal 5063, ShaderCompiler 2932, Gpu.Metal 2210, Host.Memory 487, Application 124, GpuRemote 59, GpuSplit 44, SourceGenerators 36, Fonts 13).MappedCopyProtectionTests.GuestPermissionChangeCannotBeMisclassifiedAsTemporaryReadonlyfailed once in the full run and passed three reruns.SHARPEMU_TEST_REQUIRE_DEVICE=1: ShaderCompiler.Metal 5063 pass. Gpu.Metal 2206 pass, 4 fail: threeMetalClearFoldingTeststhat fail the same way on main, andMetalImageBudgetTests.TheHostReadingIsLive, which asserts the test host's footprint is below physical memory and fails in a full device run on this machine.HostKernelCopySceneTests.ATableCopyWhoseResultIsAlreadyThereIsNotRunAndItsReaderDoesNotWait(identical: False)on the device: 8 of 8 (main 8 of 8; the sync before the ordering fix 1 of 8).Games, same input plan on both builds, frames compared at full size:
Smoke-set fps is the median of the second half of a run; final frames match main (Superliminal differs by camera position only). Demon's Souls stop frames differ from main by 1.9/255 mean, the same as two main runs differ. No fatal line in any run.
Demon's Souls is 3-4 % behind main at the spawn point, inside the run-to-run noise of about 5 %. What is left is the GPU cost of ordering the dispatches that read what an unordered neighbour wrote; with that ordering off the build matches main, and main races in those chains.
Silent Hill runs at 2 fps on both builds with a fresh data root (known state); GPU encoder time per frame is equal (43.9 ms here, 45.6 ms on main).
Not covered
kIOGPUCommandBufferCallbackErrorTimeout) and the host waited for it forever (MetalGpuWorker.WaitForSignal, unchanged by this PR; a failed submission should end the run with an error, which is not done here). One ended at 153 s with the fatal "The buffer range starts in unmapped memory" for a draw's vertex buffer (address 0x7000000001), in a run with a readback diagnostic switched on. main had neither in 10 runs; that is too few to say the rates differ.Checklist
By submitting this pull request, you confirm that:
CONTRIBUTING.md.N/A.N/A).