Skip to content

Shader Compiler determinism - #166

Open
ccpisheden wants to merge 11 commits into
mainfrom
shadercompiler-determinism
Open

ccpisheden wants to merge 11 commits into
mainfrom
shadercompiler-determinism

Conversation

@ccpisheden

@ccpisheden ccpisheden commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

ShaderCompiler had multiple issues that caused its output to be non-deterministic. This PR fixes the determinism of:

  • different runs on the same machine. Uninitialized memory and a threading race condition produced slightly different permutation data from run to run.
  • runs on different machines. Line breaks differing in the input source code would produce different source hashes in the output binaries.
  • permutation compilation within a single effect file. Due to inconsistent MSL source code generation and state leaking between permutation compilations affecting the shader cache key, many opportunities for eliminating duplicate permutations were missed.

Each fix is in a different commit and is easier to review per commit:

  1. String references were left uninitialized. This caused DX12 raytracing libraries to produce non-deterministic results. Simple single-line fix.

  2. Source hashing now ignores carriage returns (\r). This fixes the source hashes differing depending on if files are checked out with "\r\n" or "\n" line breaks, which depends on Git/Perforce settings and OS.

  3. The Metal compiler now assigns generated names in a deterministic way. Before, identical permutations produced different binaries because they assigned different generated names to the generated MSL code. Together with threading, which exact permutation we compiled determined which binary we got. Even worse, this prevented deduplication, inflating the size by needing to store these duplicates. This fix separates global and local name allocation, and makes them both not depend on the compilation order or the number of strings allocated so far.

  4. Commit 4 is just a merge of main.

  5. The Metal compiler now produces more consistent MSL code and uses this MSL code as the shader cache key. The previous code would build the cache key before patching the shader. The patching then permanently modified the global resources it encountered, causing subsequent (pre-patch) cache keys to be different, even if the actual source code fed to metal.exe was identical for both. In addition, trimmed unused functions and struct members still had subtle side effects on the exact generated MSL source code, making two otherwise equal shader permutations differ by a few line endings and #line hints. This fix addresses both issues: Unused definitions no longer leave any trace in the generated MSL source code, allowing the generated source code to be used directly as a perfect cache key, allowing more permutations to be skipped before expensive metal.exe compilation.

Results

DX11 is only affected by the second fix, and otherwise produces identical results as before.

DX12 is affected by the first two fixes. Fixing the uninitialized memory issue allows deduplication to be more effective, reducing disk file size of the compiled shaders by ~3.5%.

For Metal, the gains are significant. Metal now has the same number of unique shader permutations as DX12 (DX11 has half as many due to not supporting bindless textures). As an example, compiling the permutation-heavy Quad shaders, many more permutations can now be deduplicated, saving both compilation work and disk space.

  • The Metal compilation time is ~27% shorter thanks to cache keys now being deterministic and consistent, allowing many invocations of metal.exe to be skipped. This should reduce the TeamCity compile times by over an hour.
  • The total file size of the compiled Metal effect files has been reduced by ~13%, saving around 74 MBs as the compiled Quad shaders alone accounted for 566 MB before this fix.

Caveats

  • This PR does NOT address the debug listings being non-deterministic, as the listings are only for debugging.
  • As this changes both the shader compiler and source hash calculation, merging this will cause all shaders to be recompiled once. However, future compilations should

Linked issue (optional)

None, done on my own initiative.

Testing

  • Many new unit tests for determinism have been added. All tests pass.
  • Recompiling shaders shows that they are now deterministic.
  • Timing compilation jobs and counting metal.exe invocations confirms performance gains.

AI assistance

Initial diagnosis by Claude. Changes heavily guided by me, as Claude loves to introduce hidden state to patch issues instead of fixing the actual root cause.

No AI used in writing this PR, to show that I understand the changes.

ccpisheden and others added 4 commits November 27, 2026 03:31
StringReference had no constructor, so a reference that was never
assigned saved whatever was in memory as a string table offset. This made
the output of DX12 raytracing libraries vary between runs, including
which permutations were deduplicated. It now defaults to
INVALID_REFERENCE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
GetSourceHash() hashed the raw bytes of the .fx and its includes, so the same sources synced with CRLF and LF gave different .sm_* headers. Drop every CR from the hashed contents. Only the header hash changes, not the compiled code.

Also adds a test for this.
The Metal compiler shares one compile between permutations whose stage is
the same before PatchShader, but patching generated names (__StageInData_NNNN,
__pos_NNNN, ...) numbered by ParserState::m_strings.size(), which differs per
permutation. Whichever permutation compiled first supplied the stored code,
so .sm_* files differed between runs.

Generated names now come from two explicit sets of functions:
- AllocateGlobalName(): unique within the permutation, numbered by their own
  counter instead of the parser's string count, so token pasting etc. no
  longer renumber them (_new_symbol_NNNN, __cbuffer_NNNN).
- AllocateLocalName(): numbered from ResetLocalNames(), which PatchShader
  calls first, in a form no global name can take (__pos_p0003). Stages that
  share a compile now generate identical code.
The two stage structs are created with ALLOW_OVERRIDES, since every stage's
patch now gives them the same names; NewStruct takes an optional
OverrideBehavior.

Tests: Determinism.MetalPatchedShaderDoesNotDependOnEarlierStrings,
MetalPatchedShaderDoesNotDependOnEarlierStages and
GeneratedNamesDoNotDependOnMacroUse.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…inism

# Conflicts:
#	shadercompiler/CMakeLists.txt
@ccpisheden
ccpisheden marked this pull request as ready for review November 27, 2026 23:07
@ccpisheden
ccpisheden force-pushed the shadercompiler-determinism branch from 92625a6 to 59014a1 Compare November 28, 2026 00:04
The Metal stage cache used the unpatched source as its key. That source
also depends on what earlier stages patched in the shared syntax tree
(constant buffer registers, packed types), so stages that compile to
identical code got different keys and ran metal.exe again.

Key on the exact source code that is fed to the Metal compiler instead.
For that to match across permutations, the MSL writer now skips unused
declarations, struct members and techniques entirely instead of writing
only their #line directives, and no longer writes the program's own
location. The generated GlobalsData struct gets a dummy location instead
of that of its first global. Permutations differ in which declarations
they have, so these markers made the source differ even when the
generated code was identical.

On SpaceObject/V5/quad (48 effects, Metal, all three quality settings)
this cuts compile time by 27% with byte-identical output.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ccpisheden
ccpisheden force-pushed the shadercompiler-determinism branch from 59014a1 to d51f106 Compare November 28, 2026 03:34
@ccpisheden ccpisheden changed the title ShaderCompiler determinism Shader Compiler determinism Nov 28, 2026
ccpisheden and others added 4 commits November 30, 2026 17:21
The comments said names generated by earlier permutations affected later
ones. Each permutation has its own ParserState, so nothing leaks between
them: a stage's generated names depended on the earlier stages of its own
permutation, so an identical stage in two permutations got different code
and couldn't share one compile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The function was negated at one of its call sites. It now returns true for
declarations the MSL writer writes, and is a static helper next to the MSL
writer, its only user.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…bers

OutputHLSL.cpp and ParserUtils.cpp each had a function with this name. The
ParserUtils one also recurses into struct members, which never appear
directly in a cbuffer, so it gives the same result for the HLSL writer's
cbuffer check. It is renamed HasUsedMembers, as it is only called on
cbuffers and structs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Writing a declaration the MSL doesn't need makes otherwise identical permutations differ and silently breaks the Metal stage deduplication, so unhandled node types now assert and return false instead of defaulting to true. NT_FUNCTION_PARAMETER (system value fields added to the stage structs) is handled explicitly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants