From 83aadf853ef4b7a305f1c1a0fa4c9e776ae3141f Mon Sep 17 00:00:00 2001 From: ccpisheden Date: Fri, 27 Nov 2026 03:31:02 +0100 Subject: [PATCH 1/8] Shader compiler: default string references to invalid 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 --- shadercompiler/CMakeLists.txt | 1 + shadercompiler/StringTable.h | 2 +- shadercompiler/tests/DeterminismTest.cpp | 5 +++++ 3 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 shadercompiler/tests/DeterminismTest.cpp diff --git a/shadercompiler/CMakeLists.txt b/shadercompiler/CMakeLists.txt index 0f843d4ca..2dddb94f5 100644 --- a/shadercompiler/CMakeLists.txt +++ b/shadercompiler/CMakeLists.txt @@ -69,6 +69,7 @@ set(_SOURCES set(_TEST_SOURCES tests/Bindless.cpp + tests/DeterminismTest.cpp tests/GlobalInputTest.cpp tests/MetalConversionTest.cpp tests/RayTracingTest.cpp diff --git a/shadercompiler/StringTable.h b/shadercompiler/StringTable.h index f93e6c1b6..13f5e8d72 100644 --- a/shadercompiler/StringTable.h +++ b/shadercompiler/StringTable.h @@ -19,7 +19,7 @@ class StringReference } private: - uint32_t reference; + uint32_t reference = 0xffffffff; // invalid until assigned, so an unset reference never saves garbage friend class StringTable; }; diff --git a/shadercompiler/tests/DeterminismTest.cpp b/shadercompiler/tests/DeterminismTest.cpp new file mode 100644 index 000000000..b6e8bfb0e --- /dev/null +++ b/shadercompiler/tests/DeterminismTest.cpp @@ -0,0 +1,5 @@ +// Copyright © 2026 CCP ehf. + +// Compiled shaders and listings must not depend on thread timing or on leftover memory. + +#include "gtest/gtest.h" From b5439f0f32dae32bf8a1722213ddd64e85bed463 Mon Sep 17 00:00:00 2001 From: ccpisheden Date: Fri, 27 Nov 2026 04:23:43 +0100 Subject: [PATCH 2/8] Shader compiler: source hash ignores line endings 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. --- shadercompiler/ModifiedTime.cpp | 19 ++++++++++- shadercompiler/tests/DeterminismTest.cpp | 43 ++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/shadercompiler/ModifiedTime.cpp b/shadercompiler/ModifiedTime.cpp index 4dbee5566..f9e685c09 100644 --- a/shadercompiler/ModifiedTime.cpp +++ b/shadercompiler/ModifiedTime.cpp @@ -112,6 +112,23 @@ bool CheckHash( const HashCheckArguments& query ) return true; } +// Hashes file contents without CR characters, so the hash doesn't depend on how the sources +// were synced: CRLF on Windows clients, LF on macOS/Linux or from a Git checkout. +void AddWithoutCarriageReturns( MD5& md5, const char* data, size_t size ) +{ + const char* start = data; + const char* end = data + size; + for( const char* p = data; p < end; ++p ) + { + if( *p == '\r' ) + { + md5.add( start, p - start ); + start = p + 1; + } + } + md5.add( start, end - start ); +} + void GetSourceHash( const char* sourcePath, const char* parentData, const char* rootPath, CachingIncludeHandler::IncludeType includeType, std::set& visited, MD5& md5 ) { if( visited.find( sourcePath ) != end( visited ) ) @@ -121,7 +138,7 @@ void GetSourceHash( const char* sourcePath, const char* parentData, const char* visited.insert( sourcePath ); if( auto opened = s_includeHandler.Open( sourcePath, includeType, parentData, rootPath ) ) { - md5.add( opened->data, opened->size ); + AddWithoutCarriageReturns( md5, opened->data, opened->size ); std::cmatch match; auto begin = opened->data; diff --git a/shadercompiler/tests/DeterminismTest.cpp b/shadercompiler/tests/DeterminismTest.cpp index b6e8bfb0e..468cb5137 100644 --- a/shadercompiler/tests/DeterminismTest.cpp +++ b/shadercompiler/tests/DeterminismTest.cpp @@ -2,4 +2,47 @@ // Compiled shaders and listings must not depend on thread timing or on leftover memory. +#include +#include +#include +#include + #include "gtest/gtest.h" +#include "Macro.h" +#include "ModifiedTime.h" + +TEST( Determinism, SourceHashIgnoresLineEndings ) +{ + std::error_code ignored; + auto temp = std::filesystem::temp_directory_path( ignored ); + if( temp.empty() ) + { + GTEST_SKIP() << "Skipping test: no temp folder"; + } + auto folder = temp / ( "ShaderCompilerDeterminismTest-" + std::to_string( std::chrono::steady_clock::now().time_since_epoch().count() ) ); + std::filesystem::create_directories( folder, ignored ); + + // Each file has its own name: the include handler caches files by path. + bool writeFailed = false; + auto hash = [&]( const char* name, const char* contents ) { + auto path = ( folder / name ).string(); + FILE* f = nullptr; + writeFailed |= fopen_s( &f, path.c_str(), "wb" ) || fwrite( contents, strlen( contents ), 1, f ) != 1; + if( f ) + { + fclose( f ); + } + return GetSourceHash( path.c_str(), {} ); + }; + auto lf = hash( "lf.fx", "float a;\nfloat b;\n" ); + auto crlf = hash( "crlf.fx", "float a;\r\nfloat b;\r\n" ); + auto actuallyDifferent = hash( "actuallyDifferent.fx", "float a;\nfloat c;\n" ); + std::filesystem::remove_all( folder, ignored ); + if( writeFailed ) + { + GTEST_SKIP() << "Skipping test: can't write test files to " << folder.string(); + } + + EXPECT_EQ( lf, crlf ); // only differ by line breaks + EXPECT_NE( actuallyDifferent, crlf ); // the file is actually read and hashed +} From 12c0cbbd12ba6d6505f9572b2be1b10f37bfc28d Mon Sep 17 00:00:00 2001 From: ccpisheden Date: Fri, 27 Nov 2026 17:29:15 +0100 Subject: [PATCH 3/8] Shader compiler: separate global and local generated names 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 --- shadercompiler/EffectCompilerDX11.cpp | 4 +- shadercompiler/EffectCompilerMetal.cpp | 31 ++-- shadercompiler/HLSLParser.y | 8 +- shadercompiler/ParserState.cpp | 71 +++++---- shadercompiler/ParserState.h | 22 ++- shadercompiler/ParserUtils.cpp | 8 +- shadercompiler/ParserUtils.h | 2 +- .../TextureFunctionConversionDX11.cpp | 4 +- shadercompiler/tests/DeterminismTest.cpp | 140 ++++++++++++++++++ 9 files changed, 226 insertions(+), 64 deletions(-) diff --git a/shadercompiler/EffectCompilerDX11.cpp b/shadercompiler/EffectCompilerDX11.cpp index 1ad97abea..1ec5f9ee6 100644 --- a/shadercompiler/EffectCompilerDX11.cpp +++ b/shadercompiler/EffectCompilerDX11.cpp @@ -324,7 +324,7 @@ static PatchAction PatchShader( InputStageType shaderStage, ASTNode* callNode, P // return type os << functionHeader->GetType(); // name - InlineString name = state.AllocateName(); + InlineString name = state.AllocateGlobalName(); os << ' ' << name << "( "; bool first = true; @@ -376,7 +376,7 @@ static PatchAction PatchShader( InputStageType shaderStage, ASTNode* callNode, P { if( callNode->GetChildrenCount() <= uniformIndex && functionHeader->GetChild( i )->GetChildOrNull( 1 ) != nullptr ) { - InlineString uniformName = state.AllocateName(); + InlineString uniformName = state.AllocateGlobalName(); Type type = functionHeader->GetChild( i )->GetType(); type.storageClass = 0; os << type << ' ' << uniformName << " = " << HLSL{ functionHeader->GetChild( i )->GetChildOrNull( 1 ), nullptr }; diff --git a/shadercompiler/EffectCompilerMetal.cpp b/shadercompiler/EffectCompilerMetal.cpp index 501c9c839..af09975bc 100644 --- a/shadercompiler/EffectCompilerMetal.cpp +++ b/shadercompiler/EffectCompilerMetal.cpp @@ -854,7 +854,7 @@ void CollectGlobals( } } - PatchGlobalsInFunctions( functions, cbuffer->GetSymbol(), state.AllocateNameWithPrefix( "cbuffer" ), members ); + PatchGlobalsInFunctions( functions, cbuffer->GetSymbol(), state.AllocateGlobalName( "cbuffer" ), members ); } } @@ -2208,7 +2208,7 @@ bool AutoAssignRegisters( ParserState& state, ASTNode* callNode ) ASTNode* NewStructMember( ParserState& state, Symbol* sourceSymbol ) { - auto symbol = state.GetSymbolTable().AddSymbol( state.AllocateNameWithPrefix( sourceSymbol->name ) ); + auto symbol = state.GetSymbolTable().AddSymbol( state.AllocateLocalName( sourceSymbol->name ) ); auto nameDecl = state.NewNode( NT_NAME_DECLARATION ); symbol->definition = nameDecl; symbol->type = sourceSymbol->type; @@ -2269,7 +2269,7 @@ void GatherSystemFields( ASTNode* destStruct, std::vector& accessors, auto it = s_systemSemantics.find( name->GetSymbol()->semantic ); if( it != s_systemSemantics.end() ) { - auto param = NewFunctionParameter( state, name->GetType() ); + auto param = NewFunctionParameter( state, name->GetType(), state.AllocateLocalName() ); param->GetSymbol()->registerSpecifier[{}] = MetalSystemSemantics( it->second ); destStruct->AddChild( param ); argumentAccessors.push_back( NewVarIdentifier( state, param->GetSymbol() ) ); @@ -2278,7 +2278,7 @@ void GatherSystemFields( ASTNode* destStruct, std::vector& accessors, // subtract base_vertex from vertex_id to match dx12 behaviour for SV_VertexID if( name->GetSymbol()->semantic == "SV_VertexID" ) { - auto base_param = NewFunctionParameter( state, hlsl::uint_t ); + auto base_param = NewFunctionParameter( state, hlsl::uint_t, state.AllocateLocalName() ); base_param->GetSymbol()->registerSpecifier[{}] = MetalSystemSemantics( MetalSystemSemanticsType::Enum::base_vertex ); destStruct->AddChild( base_param ); @@ -2294,7 +2294,7 @@ void GatherSystemFields( ASTNode* destStruct, std::vector& accessors, // subtract base_instance from instance_id to match dx12 behaviour for SV_InstanceID if( name->GetSymbol()->semantic == "SV_InstanceID" ) { - auto base_param = NewFunctionParameter( state, hlsl::uint_t ); + auto base_param = NewFunctionParameter( state, hlsl::uint_t, state.AllocateLocalName() ); base_param->GetSymbol()->registerSpecifier[{}] = MetalSystemSemantics( MetalSystemSemanticsType::Enum::base_instance ); destStruct->AddChild( base_param ); @@ -2401,7 +2401,7 @@ void GatherSystemInputs( ASTNode* destStruct, std::vector& accessors, // subtract base_vertex from vertex_id to match dx12 behaviour for SV_VertexID if( symbol->semantic == "SV_VertexID" ) { - auto param = NewFunctionParameter( state, hlsl::uint_t ); + auto param = NewFunctionParameter( state, hlsl::uint_t, state.AllocateLocalName() ); param->GetSymbol()->registerSpecifier[{}] = MetalSystemSemantics( MetalSystemSemanticsType::Enum::base_vertex ); destStruct->AddChild( param ); @@ -2417,7 +2417,7 @@ void GatherSystemInputs( ASTNode* destStruct, std::vector& accessors, // subtract base_instance from instance_id to match dx12 behaviour for SV_InstanceID if( symbol->semantic == "SV_InstanceID" ) { - auto param = NewFunctionParameter( state, hlsl::uint_t ); + auto param = NewFunctionParameter( state, hlsl::uint_t, state.AllocateLocalName() ); param->GetSymbol()->registerSpecifier[{}] = MetalSystemSemantics( MetalSystemSemanticsType::Enum::base_instance ); destStruct->AddChild( param ); @@ -2705,6 +2705,11 @@ ASTNode* PatchShader( PatchShaderType shaderType, ASTNode* callNode, ParserState { ZoneScoped; + // Permutations whose stage is the same before patching share one compile (see + // EffectCompilerMetal::CompileEffect), so the names generated here must not depend on the + // rest of the permutation: they are numbered from zero for every patch. + state.ResetLocalNames(); + Symbol* entryPointSymbol = callNode->GetSymbol(); if( !entryPointSymbol || !entryPointSymbol->definition ) { @@ -2722,8 +2727,10 @@ ASTNode* PatchShader( PatchShaderType shaderType, ASTNode* callNode, ParserState state.GetCurrentLocation().fileName = shaderName.stringValue; state.GetCurrentLocation().lineNumber = 1; - ASTNode* inputsStruct = NewStruct( state, state.AllocateNameWithPrefix( "StageInData" ) ); - ASTNode* outputsStruct = NewStruct( state, state.AllocateNameWithPrefix( "StageOutData" ) ); + // Every patch numbers its names from zero, so other stages' patches have structs with the same + // names. Each stage's code only contains its own. + ASTNode* inputsStruct = NewStruct( state, state.AllocateLocalName( "StageInData" ), ALLOW_OVERRIDES ); + ASTNode* outputsStruct = NewStruct( state, state.AllocateLocalName( "StageOutData" ), ALLOW_OVERRIDES ); auto header = state.NewNode( NT_FUNCTION_HEADER, shaderName ); auto shaderSymbol = state.GetSymbolTable().AddSymbol( shaderName.stringValue, ALLOW_OVERRIDES ); @@ -2802,7 +2809,7 @@ ASTNode* PatchShader( PatchShaderType shaderType, ASTNode* callNode, ParserState { // Local variable for return value - auto declList = NewVarDeclaration( state, functionHeader->GetType(), state.AllocateNameWithPrefix( "result" ) ); + auto declList = NewVarDeclaration( state, functionHeader->GetType(), state.AllocateLocalName( "result" ) ); auto nameSymbol = declList->GetChild( 0 )->GetSymbol(); shaderBody->AddChild( declList ); @@ -2830,7 +2837,7 @@ ASTNode* PatchShader( PatchShaderType shaderType, ASTNode* callNode, ParserState state.GetTree()->AddChild( inputsStruct ); // Add [[stage_in]] parameter. - auto stageIn = NewFunctionParameter( state, TypeFromSymbol( inputsStruct->GetSymbol() ), state.AllocateNameWithPrefix( "stageIn" ) ); + auto stageIn = NewFunctionParameter( state, TypeFromSymbol( inputsStruct->GetSymbol() ), state.AllocateLocalName( "stageIn" ) ); header->AddChild( stageIn ); stageInSymbol = stageIn->GetSymbol(); @@ -2958,7 +2965,7 @@ ASTNode* PatchShader( PatchShaderType shaderType, ASTNode* callNode, ParserState header->SetType( TypeFromSymbol( outputsStruct->GetSymbol() ) ); // Create a local variable for outputs - auto resultDeclList = NewVarDeclaration( state, TypeFromSymbol( outputsStruct->GetSymbol() ), state.AllocateNameWithPrefix( "stageOut" ) ); + auto resultDeclList = NewVarDeclaration( state, TypeFromSymbol( outputsStruct->GetSymbol() ), state.AllocateLocalName( "stageOut" ) ); auto resultSymbol = resultDeclList->GetChild( 0 )->GetSymbol(); shaderBody->AddChild( resultDeclList ); diff --git a/shadercompiler/HLSLParser.y b/shadercompiler/HLSLParser.y index 406de77af..87102b978 100644 --- a/shadercompiler/HLSLParser.y +++ b/shadercompiler/HLSLParser.y @@ -2200,7 +2200,7 @@ struct_specifier(A) ::= OP_STRUCT(B) enter_block OP_LEFT_BRACE OP_RIGHT_BRACE. parserState->GetSymbolTable().LeaveScope(); - Symbol* symbol = parserState->GetSymbolTable().AddSymbol( parserState->AllocateName() ); + Symbol* symbol = parserState->GetSymbolTable().AddSymbol( parserState->AllocateGlobalName() ); symbol->definition = A; symbol->isTypeName = true; @@ -2242,7 +2242,7 @@ struct_specifier(A) ::= OP_STRUCT enter_block OP_LEFT_BRACE struct_declaration_l A = C; - Symbol* symbol = parserState->GetSymbolTable().AddSymbol( parserState->AllocateName() ); + Symbol* symbol = parserState->GetSymbolTable().AddSymbol( parserState->AllocateGlobalName() ); symbol->definition = C; symbol->isTypeName = true; @@ -3069,7 +3069,7 @@ cbuffer_declaration(A) ::= buffer_type(T) register_specifier(R) OP_LEFT_BRACE cb { A = B; A->SetToken( &T ); - Symbol* symbol = parserState->GetSymbolTable().AddBufferSymbol( parserState->AllocateName() ); + Symbol* symbol = parserState->GetSymbolTable().AddBufferSymbol( parserState->AllocateGlobalName() ); symbol->registerSpecifier[R.shaderProfile] = R; A->SetSymbol( symbol ); A->SetLocation( T.fileLocation ); @@ -3079,7 +3079,7 @@ cbuffer_declaration(A) ::= buffer_type(T) OP_LEFT_BRACE cbuffer_members(B) OP_R { A = B; A->SetToken( &T ); - A->SetSymbol( parserState->GetSymbolTable().AddBufferSymbol( parserState->AllocateName() ) ); + A->SetSymbol( parserState->GetSymbolTable().AddBufferSymbol( parserState->AllocateGlobalName() ) ); A->SetLocation( T.fileLocation ); } diff --git a/shadercompiler/ParserState.cpp b/shadercompiler/ParserState.cpp index 3e604aec0..35bebe0c1 100644 --- a/shadercompiler/ParserState.cpp +++ b/shadercompiler/ParserState.cpp @@ -859,20 +859,6 @@ FileLocation& ParserState::GetCurrentLocation() return m_fileStack.back().location; } -InlineString ParserState::AllocateName() -{ - const char* format = "_new_symbol_%04i"; - size_t len = strlen( format ) + 1; - char* newName = new char[len]; -#if _WIN32 - sprintf_s( newName, len, format, m_strings.size() ); -#else - snprintf( newName, len, format, m_strings.size() ); -#endif - m_strings.push_back( newName ); - return MakeInlineString( newName, newName + len - 1 ); -} - InlineString ParserState::AllocateName( const char* name ) { size_t len = strlen( name ) + 1; @@ -902,32 +888,45 @@ InlineString ParserState::AllocateName( const InlineString& name ) return MakeInlineString( newName, newName + len - 1 ); } -InlineString ParserState::AllocateNameWithPrefix( const char* prefix ) +namespace { - const char* format = "__%s_%04i"; - size_t len = strlen( format ) - 2 + strlen( prefix ) + 1; - char* newName = new char[len]; -#if _WIN32 - sprintf_s( newName, len, format, prefix, m_strings.size() ); -#else - snprintf( newName, len, format, prefix, m_strings.size() ); -#endif - m_strings.push_back( newName ); - return MakeInlineString( newName, newName + len - 1 ); +// stem + marker + number, e.g. "__pos_" + "p" + "0003". +std::string NumberedName( const std::string& stem, const char* marker, unsigned number ) +{ + char suffix[32]; + snprintf( suffix, sizeof( suffix ), "%s%04u", marker, number ); + return stem + suffix; +} } -InlineString ParserState::AllocateNameWithPrefix( const InlineString& prefix ) +InlineString ParserState::AllocateGlobalName() { - const char* format = "__%s_%04i"; - size_t len = strlen( format ) - 2 + ( prefix.end - prefix.start ) + 1; - char* newName = new char[len]; -#if _WIN32 - sprintf_s( newName, len, format, ToString( prefix ).c_str(), m_strings.size() ); -#else - snprintf( newName, len, format, ToString( prefix ).c_str(), m_strings.size() ); -#endif - m_strings.push_back( newName ); - return MakeInlineString( newName, newName + len - 1 ); + return AllocateName( NumberedName( "_new_symbol_", "", m_globalNameCount++ ).c_str() ); +} + +InlineString ParserState::AllocateGlobalName( const char* prefix ) +{ + return AllocateName( NumberedName( std::string( "__" ) + prefix + "_", "", m_globalNameCount++ ).c_str() ); +} + +void ParserState::ResetLocalNames() +{ + m_localNameCount = 0; +} + +InlineString ParserState::AllocateLocalName() +{ + return AllocateName( NumberedName( "_new_symbol_", "p", m_localNameCount++ ).c_str() ); +} + +InlineString ParserState::AllocateLocalName( const char* prefix ) +{ + return AllocateName( NumberedName( std::string( "__" ) + prefix + "_", "p", m_localNameCount++ ).c_str() ); +} + +InlineString ParserState::AllocateLocalName( const InlineString& prefix ) +{ + return AllocateLocalName( ToString( prefix ).c_str() ); } char* ParserState::AllocateString( size_t size ) diff --git a/shadercompiler/ParserState.h b/shadercompiler/ParserState.h index 73cdc73d7..ac521ed56 100644 --- a/shadercompiler/ParserState.h +++ b/shadercompiler/ParserState.h @@ -213,11 +213,25 @@ class ParserState FileLocation& GetCurrentLocation(); - InlineString AllocateName(); + // Copies of existing names. InlineString AllocateName( const char* name ); InlineString AllocateName( const InlineString& name ); - InlineString AllocateNameWithPrefix( const char* prefix ); - InlineString AllocateNameWithPrefix( const InlineString& prefix ); + + // Generated names that are unique within the whole permutation: "_new_symbol_0012" or, with + // a prefix, "__cbuffer_0013". Numbered by their own counter, so other string allocations + // (e.g. token pasting) don't renumber them. + InlineString AllocateGlobalName(); + InlineString AllocateGlobalName( const char* prefix ); + + // Generated names numbered from the last ResetLocalNames(): "_new_symbol_p0000" or, with a + // prefix, "__pos_p0003". The "p" keeps them from matching any global name. Used by the Metal + // compiler's stage patching: permutations whose stage is the same before patching share one + // compile, so the names patching generates must not depend on the rest of the permutation. + void ResetLocalNames(); + InlineString AllocateLocalName(); + InlineString AllocateLocalName( const char* prefix ); + InlineString AllocateLocalName( const InlineString& prefix ); + char* AllocateString( size_t size ); void ShowMessage( const FileLocation& location, int32_t errorCode, ... ); @@ -298,6 +312,8 @@ class ParserState bool m_inDiscoverMode; std::vector m_strings; + unsigned m_globalNameCount = 0; + unsigned m_localNameCount = 0; std::set m_dx9TextureFunctions; std::map m_dx9Functions; }; diff --git a/shadercompiler/ParserUtils.cpp b/shadercompiler/ParserUtils.cpp index a3c313409..8aa58994e 100644 --- a/shadercompiler/ParserUtils.cpp +++ b/shadercompiler/ParserUtils.cpp @@ -1044,10 +1044,10 @@ void CreateGlobalsCB( ParserState& state ) } } -ASTNode* NewStruct( ParserState& state, const InlineString& name ) +ASTNode* NewStruct( ParserState& state, const InlineString& name, OverrideBehavior overrideBehavior ) { auto structDecl = state.NewNode( NT_STRUCT ); - auto symbol = state.GetSymbolTable().AddSymbol( name ? name : state.AllocateName() ); + auto symbol = state.GetSymbolTable().AddSymbol( name ? name : state.AllocateGlobalName(), overrideBehavior ); symbol->isTypeName = true; symbol->definition = structDecl; structDecl->SetSymbol( symbol ); @@ -1145,7 +1145,7 @@ ASTNode* NewConditionalExpression( ParserState& state, ASTNode* condition, ASTNo ASTNode* NewVarDeclaration( ParserState& state, const Type& type, const InlineString& name ) { auto nameDecl = state.NewNode( NT_NAME_DECLARATION ); - auto nameSymbol = state.GetSymbolTable().AddSymbol( name ? name : state.AllocateName() ); + auto nameSymbol = state.GetSymbolTable().AddSymbol( name ? name : state.AllocateGlobalName() ); nameDecl->SetSymbol( nameSymbol ); nameSymbol->type = type; @@ -1217,7 +1217,7 @@ ASTNode* NewReturn( ParserState& state, ASTNode* expr ) ASTNode* NewFunctionParameter( ParserState& state, const Type& type, const InlineString& name ) { auto param = state.NewNode( NT_FUNCTION_PARAMETER ); - auto symbol = state.GetSymbolTable().AddSymbol( name ? name : state.AllocateName() ); + auto symbol = state.GetSymbolTable().AddSymbol( name ? name : state.AllocateGlobalName() ); symbol->type = type; symbol->definition = param; param->SetType( symbol->type ); diff --git a/shadercompiler/ParserUtils.h b/shadercompiler/ParserUtils.h index f07f5e632..0c7b51b68 100644 --- a/shadercompiler/ParserUtils.h +++ b/shadercompiler/ParserUtils.h @@ -58,7 +58,7 @@ extern void SortProgramNodes( ASTNode* root ); extern void CreateGlobalsCB( ParserState& state ); -ASTNode* NewStruct( ParserState& state, const InlineString& name = InlineString() ); +ASTNode* NewStruct( ParserState& state, const InlineString& name = InlineString(), OverrideBehavior overrideBehavior = DISALOW_OVERRIDES ); ASTNode* NewVarIdentifier( ParserState& state, Symbol* var ); ASTNode* NewLiteralConst( ParserState& state, float value ); diff --git a/shadercompiler/TextureFunctionConversionDX11.cpp b/shadercompiler/TextureFunctionConversionDX11.cpp index f61a52a8c..2c27b2fa1 100644 --- a/shadercompiler/TextureFunctionConversionDX11.cpp +++ b/shadercompiler/TextureFunctionConversionDX11.cpp @@ -151,7 +151,7 @@ static Symbol* FindTextureToSampler( ParserState& state, ASTNode* sampler, std:: } else if( sampler->GetSymbol()->definition && sampler->GetSymbol()->definition->GetNodeType() == NT_FUNCTION_PARAMETER ) { - InlineString str = state.AllocateName(); + InlineString str = state.AllocateGlobalName(); texture = state.GetSymbolTable().AddSymbol( str ); texture->type.FromTokenType( usedType ); if( !sampler->GetSymbol()->registerSpecifier.empty() ) @@ -234,7 +234,7 @@ static ASTNode* FindDX9TexSampleCalls( ParserState& state, { // we have a local symbol with the same name as the texture // rename it - otherSymbol->name = state.AllocateName(); + otherSymbol->name = state.AllocateGlobalName(); } ScannerToken token; token.fileLocation.fileName.start = token.fileLocation.fileName.end = nullptr; diff --git a/shadercompiler/tests/DeterminismTest.cpp b/shadercompiler/tests/DeterminismTest.cpp index 468cb5137..cb47bd85b 100644 --- a/shadercompiler/tests/DeterminismTest.cpp +++ b/shadercompiler/tests/DeterminismTest.cpp @@ -2,14 +2,20 @@ // Compiled shaders and listings must not depend on thread timing or on leftover memory. +#include #include #include #include #include #include "gtest/gtest.h" +#include "EffectCompilerMetal.h" +#if _WIN32 +#include "EffectCompilerDX12.h" +#endif #include "Macro.h" #include "ModifiedTime.h" +#include "TesingUtils.h" TEST( Determinism, SourceHashIgnoresLineEndings ) { @@ -46,3 +52,137 @@ TEST( Determinism, SourceHashIgnoresLineEndings ) EXPECT_EQ( lf, crlf ); // only differ by line breaks EXPECT_NE( actuallyDifferent, crlf ); // the file is actually read and hashed } + +TEST( Determinism, MetalPatchedShaderDoesNotDependOnEarlierStrings ) +{ + // Metal shares one compile between permutations whose shader is the same before patching, so + // patching must generate the same code for them. Token pasting allocates strings in the parser, + // which used to change the numbers of the names that patching generates. + if( !g_metalCompilerAvailable ) + { + GTEST_SKIP() << "Skipping test: Metal compiler is not available."; + } + // Both sources have the same #define line, so the #line numbers in the generated code match. + const char* withoutMacro = R"SRC( +#define CAT( a, b ) a ## b +float4 p0; +struct VsIn { float4 pos: POSITION; float2 uv: TEXCOORD0; }; +struct VsOut { float4 pos: SV_Position; float2 uv: TEXCOORD0; }; +VsOut vs( VsIn input ) { VsOut o; o.pos = input.pos; o.uv = input.uv; return o; } +float4 ps( VsOut input ): SV_Target { return ( p0 + p0 ) * input.uv.x; } +technique t0 { pass p0 { vertexshader = compile vs_3_0 vs(); pixelshader = compile ps_3_0 ps(); } } +)SRC"; + const char* withMacro = R"SRC( +#define CAT( a, b ) a ## b +float4 p0; +struct VsIn { float4 pos: POSITION; float2 uv: TEXCOORD0; }; +struct VsOut { float4 pos: SV_Position; float2 uv: TEXCOORD0; }; +VsOut vs( VsIn input ) { VsOut o; o.pos = input.pos; o.uv = input.uv; return o; } +float4 ps( VsOut input ): SV_Target { return ( CAT( p, 0 ) + CAT( p, 0 ) ) * input.uv.x; } +technique t0 { pass p0 { vertexshader = compile vs_3_0 vs(); pixelshader = compile ps_3_0 ps(); } } +)SRC"; + auto a = Compile( withoutMacro ); + auto b = Compile( withMacro ); + ASSERT_EQ( a.techniques.size(), 1u ); + ASSERT_EQ( b.techniques.size(), 1u ); + auto& stagesA = a.techniques[0].passes[0].stages; + auto& stagesB = b.techniques[0].passes[0].stages; + ASSERT_EQ( stagesA.size(), stagesB.size() ); + for( size_t i = 0; i < stagesA.size(); ++i ) + { + auto& sourceA = stagesA[i].source; + auto& sourceB = stagesB[i].source; + EXPECT_NE( sourceA.find( "_p0000" ), std::string::npos ) << "stage " << i << ": patching should generate locally numbered names"; + auto diff = std::mismatch( sourceA.begin(), sourceA.end(), sourceB.begin(), sourceB.end() ); + if( diff.first != sourceA.end() || diff.second != sourceB.end() ) + { + auto at = size_t( diff.first - sourceA.begin() ); + auto from = at > 200 ? at - 200 : 0; + ADD_FAILURE() << "stage " << i << " differs at " << at << ":\n" + << sourceA.substr( from, 300 ) << "\n----- vs -----\n" + << sourceB.substr( from, 300 ); + } + } +} + +TEST( Determinism, MetalPatchedShaderDoesNotDependOnEarlierStages ) +{ + // Patching numbers its names from zero for every stage. Otherwise a stage's names would depend + // on how many names the patches of earlier stages generated, which differs between + // permutations that share the stage's compile. + if( !g_metalCompilerAvailable ) + { + GTEST_SKIP() << "Skipping test: Metal compiler is not available."; + } + // t0's vertex shader has one input in the first source and three in the second (same line, so + // the #line numbers match). t1 is the same in both. + const char* fewInputs = R"SRC( +struct VsIn { float4 pos: POSITION; float2 uv: TEXCOORD0; }; +struct VsOut { float4 pos: SV_Position; float2 uv: TEXCOORD0; }; +float4 vsFirst( float4 pos: POSITION ): SV_Position { return pos; } +VsOut vs( VsIn input ) { VsOut o; o.pos = input.pos; o.uv = input.uv; return o; } +float4 ps( VsOut input ): SV_Target { return float4( input.uv, 0.0, 1.0 ); } +technique t0 { pass p0 { vertexshader = compile vs_3_0 vsFirst(); pixelshader = compile ps_3_0 ps(); } } +technique t1 { pass p0 { vertexshader = compile vs_3_0 vs(); pixelshader = compile ps_3_0 ps(); } } +)SRC"; + const char* moreInputs = R"SRC( +struct VsIn { float4 pos: POSITION; float2 uv: TEXCOORD0; }; +struct VsOut { float4 pos: SV_Position; float2 uv: TEXCOORD0; }; +float4 vsFirst( float4 pos: POSITION, float4 c: COLOR0, float2 t: TEXCOORD1 ): SV_Position { return pos + c + t.xyxy; } +VsOut vs( VsIn input ) { VsOut o; o.pos = input.pos; o.uv = input.uv; return o; } +float4 ps( VsOut input ): SV_Target { return float4( input.uv, 0.0, 1.0 ); } +technique t0 { pass p0 { vertexshader = compile vs_3_0 vsFirst(); pixelshader = compile ps_3_0 ps(); } } +technique t1 { pass p0 { vertexshader = compile vs_3_0 vs(); pixelshader = compile ps_3_0 ps(); } } +)SRC"; + auto a = Compile( fewInputs ); + auto b = Compile( moreInputs ); + ASSERT_EQ( a.techniques.size(), 2u ); + ASSERT_EQ( b.techniques.size(), 2u ); + auto& stagesA = a.techniques[1].passes[0].stages; + auto& stagesB = b.techniques[1].passes[0].stages; + ASSERT_EQ( stagesA.size(), stagesB.size() ); + for( size_t i = 0; i < stagesA.size(); ++i ) + { + auto& sourceA = stagesA[i].source; + auto& sourceB = stagesB[i].source; + auto diff = std::mismatch( sourceA.begin(), sourceA.end(), sourceB.begin(), sourceB.end() ); + if( diff.first != sourceA.end() || diff.second != sourceB.end() ) + { + auto at = size_t( diff.first - sourceA.begin() ); + auto from = at > 200 ? at - 200 : 0; + ADD_FAILURE() << "t1 stage " << i << " differs at " << at << ":\n" + << sourceA.substr( from, 300 ) << "\n----- vs -----\n" + << sourceB.substr( from, 300 ); + } + } +} + +#if _WIN32 +TEST( Determinism, GeneratedNamesDoNotDependOnMacroUse ) +{ + // Token pasting allocates strings in the parser; that must not renumber generated names. + // Uniform arguments make the compiler wrap the entry point in a function with a generated name. + const char* withoutMacro = R"SRC( +float4 p0; +float4 vs(): SV_Position { return float4( 0.0, 0.0, 0.0, 1.0 ); } +float4 ps( uniform float scale ): SV_Target { return ( p0 + p0 ) * scale; } +technique t0 { pass p0 { vertexshader = compile vs_3_0 vs(); pixelshader = compile ps_3_0 ps( 2.0 ); } } +)SRC"; + const char* withMacro = R"SRC( +#define CAT( a, b ) a ## b +float4 p0; +float4 vs(): SV_Position { return float4( 0.0, 0.0, 0.0, 1.0 ); } +float4 ps( uniform float scale ): SV_Target { return ( CAT( p, 0 ) + CAT( p, 0 ) ) * scale; } +technique t0 { pass p0 { vertexshader = compile vs_3_0 vs(); pixelshader = compile ps_3_0 ps( 2.0 ); } } +)SRC"; + auto a = Compile( withoutMacro ); + auto b = Compile( withMacro ); + auto name = []( const EffectData& data ) { + auto& source = data.techniques[0].passes[0].stages[1].source; + auto start = source.find( "_new_symbol_" ); + return start == std::string::npos ? std::string() : source.substr( start, 16 ); + }; + ASSERT_FALSE( name( a ).empty() ); + EXPECT_EQ( name( a ), name( b ) ); +} +#endif From d51f106cc303b5f22f1aa8981b9cb74fd299d4da Mon Sep 17 00:00:00 2001 From: ccpisheden Date: Sat, 28 Nov 2026 01:04:08 +0100 Subject: [PATCH 4/8] Shader compiler: key the Metal stage cache on the patched source 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 --- shadercompiler/EffectCompilerMetal.cpp | 16 ++-- shadercompiler/OutputHLSL.cpp | 52 +++++++++++- shadercompiler/tests/DeterminismTest.cpp | 102 ++++++++++++++++++++++- shadercompiler/tests/TesingUtils.h | 4 +- 4 files changed, 156 insertions(+), 18 deletions(-) diff --git a/shadercompiler/EffectCompilerMetal.cpp b/shadercompiler/EffectCompilerMetal.cpp index eeae09811..beac2ac26 100644 --- a/shadercompiler/EffectCompilerMetal.cpp +++ b/shadercompiler/EffectCompilerMetal.cpp @@ -882,7 +882,9 @@ void CollectGlobals( if( !globalsStruct ) { InlineString name = MakeInlineString( "GlobalsData" ); - globalsStruct = new ASTNode( NT_STRUCT, node->GetLocation(), node->GetScope(), nullptr ); + // The GlobalsData struct has no proper location, so give it a dummy one. + FileLocation location{ 1, name }; + globalsStruct = new ASTNode( NT_STRUCT, location, node->GetScope(), nullptr ); RegisterSpecifier reg; reg.shaderProfile.start = nullptr; @@ -5117,16 +5119,6 @@ bool EffectCompilerMetal::CompileEffect( const char* source, size_t sourceLength RemapSystemSemanticsDXtoMetal( shaderNode->GetChild( 1 ) ); - std::string shaderCacheKey; - { - state.GetSymbolTable().ResetUsedFlag(); - MarkUsedSymbols( shaderNode->GetChild( 1 ), state ); - - CompilerInputStream os( state, ShadingLanguage::MSL ); - os << MSL{ state.GetTree(), &state.GetSymbolTable() }; - shaderCacheKey = os.str(); - state.GetSymbolTable().ResetUsedFlag(); - } PatchShaderType patchShaderType; switch( stage.type ) { @@ -5190,6 +5182,8 @@ bool EffectCompilerMetal::CompileEffect( const char* source, size_t sourceLength os << AtomicFn{ "xor", "Xor" }; os << MSL{ state.GetTree(), &state.GetSymbolTable() }; + // Key on the exact source code that we intend to feed to the Metal compiler. + std::string shaderCacheKey = os.str(); // Let only one thread compile this permutation. bool needsToCompile = false; diff --git a/shadercompiler/OutputHLSL.cpp b/shadercompiler/OutputHLSL.cpp index c45221bf1..f982045fb 100644 --- a/shadercompiler/OutputHLSL.cpp +++ b/shadercompiler/OutputHLSL.cpp @@ -73,6 +73,38 @@ bool HasUsedDeclarations( ASTNode* node ) return false; } +// Returns true for declarations (top-level or struct members) that the MSL writer would not write anything for. +bool IsUnusedDeclaration( ASTNode* node ) +{ + if( !node ) + { + return false; + } + switch( node->GetNodeType() ) + { + case NT_TECHNIQUE: + return true; + case NT_FUNCTION_DEFINITION: + return !node->GetChild( 0 )->GetSymbol()->used; + case NT_FUNCTION_HEADER: + case NT_STRUCT: + case NT_NAME_DECLARATION: + return node->GetSymbol() && !node->GetSymbol()->used; + case NT_VAR_DECLARATION_LIST: + case NT_STRUCT_MEMBER: + for( unsigned i = 0; i < node->GetChildrenCount(); ++i ) + { + if( !IsUnusedDeclaration( node->GetChild( i ) ) ) + { + return false; + } + } + return true; + default: + return false; + } +} + std::map s_operators = { { OP_MUL_ASSIGN, "*=" }, { OP_DIV_ASSIGN, "/=" }, @@ -1307,7 +1339,11 @@ CodeStream& operator<<( CodeStream& os, const MSL& msl ) { auto node = msl.node; - os << node->GetLocation(); + // Children write their own locations, so the program's location (that of its first declaration) is never needed. + if( node->GetNodeType() != NT_PROGRAM ) + { + os << node->GetLocation(); + } auto Child = [&]( size_t index ) -> MSL { return XSLChild( msl, index ); }; @@ -1880,7 +1916,15 @@ CodeStream& operator<<( CodeStream& os, const MSL& msl ) { os << "struct " << " " << node->GetSymbol()->name << Endl(); os << "{" << Endl(); - os << Indent() << Children( msl, "" ) << Unindent() << Endl(); + os << Indent(); + for( unsigned i = 0; i < node->GetChildrenCount(); ++i ) + { + if( !IsUnusedDeclaration( node->GetChild( i ) ) ) + { + os << Child( i ); + } + } + os << Unindent() << Endl(); os << "};" << Endl(); } break; @@ -1901,6 +1945,10 @@ CodeStream& operator<<( CodeStream& os, const MSL& msl ) case NT_PROGRAM: for( unsigned i = 0; i < node->GetChildrenCount(); ++i ) { + if( IsUnusedDeclaration( node->GetChild( i ) ) ) + { + continue; + } os << Child( i ); if( node->GetChild( i ) && node->GetChild( i )->GetNodeType() == NT_FUNCTION_HEADER ) { diff --git a/shadercompiler/tests/DeterminismTest.cpp b/shadercompiler/tests/DeterminismTest.cpp index cb47bd85b..4ccfa6c81 100644 --- a/shadercompiler/tests/DeterminismTest.cpp +++ b/shadercompiler/tests/DeterminismTest.cpp @@ -55,9 +55,9 @@ TEST( Determinism, SourceHashIgnoresLineEndings ) TEST( Determinism, MetalPatchedShaderDoesNotDependOnEarlierStrings ) { - // Metal shares one compile between permutations whose shader is the same before patching, so - // patching must generate the same code for them. Token pasting allocates strings in the parser, - // which used to change the numbers of the names that patching generates. + // Metal shares one compile between permutations whose patched shader is the same, so patching + // must generate the same code for them. Token pasting allocates strings in the parser, which + // used to change the numbers of the names that patching generates. if( !g_metalCompilerAvailable ) { GTEST_SKIP() << "Skipping test: Metal compiler is not available."; @@ -157,6 +157,102 @@ technique t1 { pass p0 { vertexshader = compile vs_3_0 vs(); pixelshader = compi } } +TEST( Determinism, MetalUnusedDeclarationsLeaveNoTrace ) +{ + // Permutations differ in which declarations they have. Metal shares one compile between + // permutations whose generated code is the same, so declarations a stage doesn't use must not + // leave anything (such as #line directives) in its code. + if( !g_metalCompilerAvailable ) + { + GTEST_SKIP() << "Skipping test: Metal compiler is not available."; + } + // The WITH_UNUSED permutation adds one unused declaration of each kind. The unused function comes + // first, as it is the program's first declaration. unusedGlobal ends up as an unused member of + // the globals struct, which usedGlobal keeps in the code. + const char* source = R"SRC( +#if WITH_UNUSED +struct UnusedStruct { float4 v; }; +UnusedStruct unusedFunction( float4 v ) { UnusedStruct s; s.v = v; return s; } +float4 unusedPrototype( float4 v ); +float4 unusedGlobal; +Texture2D unusedTexture; +SamplerState unusedSampler; +#endif + +float4 usedGlobal; +struct VsIn { float4 pos: POSITION; float2 uv: TEXCOORD0; }; +struct VsOut { float4 pos: SV_Position; float2 uv: TEXCOORD0; }; +VsOut vs( VsIn input ) { VsOut o; o.pos = input.pos; o.uv = input.uv; return o; } +float4 ps( VsOut input ): SV_Target { return usedGlobal * input.uv.x; } + +technique t0 { pass p0 { vertexshader = compile vs_3_0 vs(); pixelshader = compile ps_3_0 ps(); } } +)SRC"; + auto a = Compile( source, { { "WITH_UNUSED", "1" } } ); + auto b = Compile( source, { { "WITH_UNUSED", "0" } } ); + ASSERT_EQ( a.techniques.size(), 1u ); + ASSERT_EQ( b.techniques.size(), 1u ); + auto& stagesA = a.techniques[0].passes[0].stages; + auto& stagesB = b.techniques[0].passes[0].stages; + ASSERT_EQ( stagesA.size(), stagesB.size() ); + for( size_t i = 0; i < stagesA.size(); ++i ) + { + auto& sourceA = stagesA[i].source; + auto& sourceB = stagesB[i].source; + auto diff = std::mismatch( sourceA.begin(), sourceA.end(), sourceB.begin(), sourceB.end() ); + if( diff.first != sourceA.end() || diff.second != sourceB.end() ) + { + auto at = size_t( diff.first - sourceA.begin() ); + auto from = at > 200 ? at - 200 : 0; + ADD_FAILURE() << "stage " << i << " differs at " << at << ":\n" + << sourceA.substr( from, 300 ) << "\n----- vs -----\n" + << sourceB.substr( from, 300 ); + } + } +} + +TEST( Determinism, MetalLineDirectivesAreFollowedByCode ) +{ + // A #line directive with no code after it comes from a node that wrote nothing, such as an unused + // declaration or a technique. Those can differ between permutations, so they must not be written. + if( !g_metalCompilerAvailable ) + { + GTEST_SKIP() << "Skipping test: Metal compiler is not available."; + } + // One unused declaration of each kind, and a technique. unusedGlobal ends up as an unused member of + // the globals struct, which usedGlobal keeps in the code. + const char* source = R"SRC( +struct UnusedStruct { float4 v; }; +UnusedStruct unusedFunction( float4 v ) { UnusedStruct s; s.v = v; return s; } +float4 unusedPrototype( float4 v ); +float4 unusedGlobal; +Texture2D unusedTexture; +SamplerState unusedSampler; + +float4 usedGlobal; +struct VsIn { float4 pos: POSITION; float2 uv: TEXCOORD0; }; +struct VsOut { float4 pos: SV_Position; float2 uv: TEXCOORD0; }; +VsOut vs( VsIn input ) { VsOut o; o.pos = input.pos; o.uv = input.uv; return o; } +float4 ps( VsOut input ): SV_Target { return usedGlobal * input.uv.x; } + +technique t0 { pass p0 { vertexshader = compile vs_3_0 vs(); pixelshader = compile ps_3_0 ps(); } } +)SRC"; + auto data = Compile( source ); + ASSERT_EQ( data.techniques.size(), 1u ); + auto& stages = data.techniques[0].passes[0].stages; + for( size_t i = 0; i < stages.size(); ++i ) + { + auto& code = stages[i].source; + for( size_t pos = code.find( "#line " ); pos != std::string::npos; pos = code.find( "#line ", pos + 1 ) ) + { + auto next = code.find( '\n', pos ); + ASSERT_NE( next, std::string::npos ); + auto nextLine = code.substr( next + 1, code.find( '\n', next + 1 ) - next - 1 ); + EXPECT_FALSE( nextLine.empty() || nextLine.rfind( "#line ", 0 ) == 0 ) + << "stage " << i << ": " << code.substr( pos, next - pos ) << " is not followed by code"; + } + } +} + #if _WIN32 TEST( Determinism, GeneratedNamesDoNotDependOnMacroUse ) { diff --git a/shadercompiler/tests/TesingUtils.h b/shadercompiler/tests/TesingUtils.h index 10aa9d314..a514b7d11 100644 --- a/shadercompiler/tests/TesingUtils.h +++ b/shadercompiler/tests/TesingUtils.h @@ -26,14 +26,14 @@ bool Compiles( const char* src ) } template -EffectData Compile( const char* src ) +EffectData Compile( const char* src, const std::vector& defines = {} ) { Compiler compiler; auto created = compiler.Create(); [created] { ASSERT_TRUE( created ) << "Failed to create a compiler object: the environment is not set up correctly"; }(); EffectData data; - auto compiled = compiler.CompileEffect( src + 1, strlen( src ), {}, data, nullptr ); + auto compiled = compiler.CompileEffect( src + 1, strlen( src ), defines, data, nullptr ); g_messages.Flush(); [compiled] { ASSERT_TRUE( compiled ); }(); return data; From 5fb2a3607aa2cba7cf1288f4063001c873be7593 Mon Sep 17 00:00:00 2001 From: ccpisheden Date: Mon, 30 Nov 2026 17:21:42 +0100 Subject: [PATCH 5/8] Shader compiler: correct the reasoning in the local name comments 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 --- shadercompiler/EffectCompilerMetal.cpp | 5 ++--- shadercompiler/ParserState.h | 14 +++++++------- shadercompiler/tests/DeterminismTest.cpp | 13 +++++++------ 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/shadercompiler/EffectCompilerMetal.cpp b/shadercompiler/EffectCompilerMetal.cpp index beac2ac26..4f86fbf15 100644 --- a/shadercompiler/EffectCompilerMetal.cpp +++ b/shadercompiler/EffectCompilerMetal.cpp @@ -2800,9 +2800,8 @@ ASTNode* PatchShader( PatchShaderType shaderType, ASTNode* callNode, ParserState { ZoneScoped; - // Permutations whose stage is the same before patching share one compile (see - // EffectCompilerMetal::CompileEffect), so the names generated here must not depend on the - // rest of the permutation: they are numbered from zero for every patch. + // Reset the per-stage local name allocator so that the name allocation is consistent for later + // stages (e.g. pixel shader), even if the previous stages are different (e.g. vertex). state.ResetLocalNames(); Symbol* entryPointSymbol = callNode->GetSymbol(); diff --git a/shadercompiler/ParserState.h b/shadercompiler/ParserState.h index a9f24605a..05d922ca6 100644 --- a/shadercompiler/ParserState.h +++ b/shadercompiler/ParserState.h @@ -217,16 +217,16 @@ class ParserState InlineString AllocateName( const char* name ); InlineString AllocateName( const InlineString& name ); - // Generated names that are unique within the whole permutation: "_new_symbol_0012" or, with - // a prefix, "__cbuffer_0013". Numbered by their own counter, so other string allocations - // (e.g. token pasting) don't renumber them. + // Used to generate names that are "global", i.e. the same for all stages in the permutation. + // These are globally available things, such as textures, cbuffers, entrypoints, etc. InlineString AllocateGlobalName(); InlineString AllocateGlobalName( const char* prefix ); - // Generated names numbered from the last ResetLocalNames(): "_new_symbol_p0000" or, with a - // prefix, "__pos_p0003". The "p" keeps them from matching any global name. Used by the Metal - // compiler's stage patching: permutations whose stage is the same before patching share one - // compile, so the names patching generates must not depend on the rest of the permutation. + // Used to generate names that are local to a specific shader stage. The name allocator is reset + // between each stage. This ensures that the names generated for later shader stages are not + // affected by allocations in earlier stages. Otherwise, two permutations with identical pixel + // shaders but different vertex shaders can allocate different names for the pixel shaders, + // causing a cache miss on otherwise identical shaders. void ResetLocalNames(); InlineString AllocateLocalName(); InlineString AllocateLocalName( const char* prefix ); diff --git a/shadercompiler/tests/DeterminismTest.cpp b/shadercompiler/tests/DeterminismTest.cpp index 4ccfa6c81..82ace7068 100644 --- a/shadercompiler/tests/DeterminismTest.cpp +++ b/shadercompiler/tests/DeterminismTest.cpp @@ -55,9 +55,9 @@ TEST( Determinism, SourceHashIgnoresLineEndings ) TEST( Determinism, MetalPatchedShaderDoesNotDependOnEarlierStrings ) { - // Metal shares one compile between permutations whose patched shader is the same, so patching - // must generate the same code for them. Token pasting allocates strings in the parser, which - // used to change the numbers of the names that patching generates. + // Patching must not depend on the parser's string count. Macro expansion is used in this test + // to allocate additional strings in the parser, which are then checked to not have any impact + // on the output. if( !g_metalCompilerAvailable ) { GTEST_SKIP() << "Skipping test: Metal compiler is not available."; @@ -107,9 +107,10 @@ technique t0 { pass p0 { vertexshader = compile vs_3_0 vs(); pixelshader = compi TEST( Determinism, MetalPatchedShaderDoesNotDependOnEarlierStages ) { - // Patching numbers its names from zero for every stage. Otherwise a stage's names would depend - // on how many names the patches of earlier stages generated, which differs between - // permutations that share the stage's compile. + // Patching must produce patched names that are consistent and deterministic for every shader + // stage, regardless of any previous stages. Otherwise, a stage's names would depend on how many + // names the earlier stages of the same permutation generated. This could lead to e.g. a shared + // pixel shader getting different names assigned if the vertex shaders are different. if( !g_metalCompilerAvailable ) { GTEST_SKIP() << "Skipping test: Metal compiler is not available."; From 616d841ec16497c6901ea1cb41e03f3599dac99e Mon Sep 17 00:00:00 2001 From: ccpisheden Date: Mon, 30 Nov 2026 18:05:57 +0100 Subject: [PATCH 6/8] Shader compiler: rename IsUnusedDeclaration to ShouldWriteToMSL 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 --- shadercompiler/OutputHLSL.cpp | 70 ++++++++++++++++++----------------- 1 file changed, 36 insertions(+), 34 deletions(-) diff --git a/shadercompiler/OutputHLSL.cpp b/shadercompiler/OutputHLSL.cpp index f982045fb..cf6e727e7 100644 --- a/shadercompiler/OutputHLSL.cpp +++ b/shadercompiler/OutputHLSL.cpp @@ -73,38 +73,6 @@ bool HasUsedDeclarations( ASTNode* node ) return false; } -// Returns true for declarations (top-level or struct members) that the MSL writer would not write anything for. -bool IsUnusedDeclaration( ASTNode* node ) -{ - if( !node ) - { - return false; - } - switch( node->GetNodeType() ) - { - case NT_TECHNIQUE: - return true; - case NT_FUNCTION_DEFINITION: - return !node->GetChild( 0 )->GetSymbol()->used; - case NT_FUNCTION_HEADER: - case NT_STRUCT: - case NT_NAME_DECLARATION: - return node->GetSymbol() && !node->GetSymbol()->used; - case NT_VAR_DECLARATION_LIST: - case NT_STRUCT_MEMBER: - for( unsigned i = 0; i < node->GetChildrenCount(); ++i ) - { - if( !IsUnusedDeclaration( node->GetChild( i ) ) ) - { - return false; - } - } - return true; - default: - return false; - } -} - std::map s_operators = { { OP_MUL_ASSIGN, "*=" }, { OP_DIV_ASSIGN, "/=" }, @@ -1335,6 +1303,40 @@ static const char* MSLCompareFunc( uint8_t func ) } } +// Returns true for declarations (top-level or struct members) that the MSL writer needs to +// include in the generated MSL code. For declarations that return false for this function, +// nothing must be emitted at all to ensure consistent, cacheable MSL source code is generated. +static bool ShouldWriteToMSL( ASTNode* node ) +{ + if( !node ) + { + return true; + } + switch( node->GetNodeType() ) + { + case NT_TECHNIQUE: + return false; + case NT_FUNCTION_DEFINITION: + return node->GetChild( 0 )->GetSymbol()->used; + case NT_FUNCTION_HEADER: + case NT_STRUCT: + case NT_NAME_DECLARATION: + return !node->GetSymbol() || node->GetSymbol()->used; + case NT_VAR_DECLARATION_LIST: + case NT_STRUCT_MEMBER: + for( unsigned i = 0; i < node->GetChildrenCount(); ++i ) + { + if( ShouldWriteToMSL( node->GetChild( i ) ) ) + { + return true; + } + } + return false; + default: + return true; + } +} + CodeStream& operator<<( CodeStream& os, const MSL& msl ) { auto node = msl.node; @@ -1919,7 +1921,7 @@ CodeStream& operator<<( CodeStream& os, const MSL& msl ) os << Indent(); for( unsigned i = 0; i < node->GetChildrenCount(); ++i ) { - if( !IsUnusedDeclaration( node->GetChild( i ) ) ) + if( ShouldWriteToMSL( node->GetChild( i ) ) ) { os << Child( i ); } @@ -1945,7 +1947,7 @@ CodeStream& operator<<( CodeStream& os, const MSL& msl ) case NT_PROGRAM: for( unsigned i = 0; i < node->GetChildrenCount(); ++i ) { - if( IsUnusedDeclaration( node->GetChild( i ) ) ) + if( !ShouldWriteToMSL( node->GetChild( i ) ) ) { continue; } From d983b9ed45abf04f49768e84cfc903cb9f5f389e Mon Sep 17 00:00:00 2001 From: ccpisheden Date: Mon, 30 Nov 2026 18:06:59 +0100 Subject: [PATCH 7/8] Shader compiler: merge the HasUsedDeclarations copies into HasUsedMembers 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 --- shadercompiler/OutputHLSL.cpp | 27 +-------------------------- shadercompiler/ParserUtils.cpp | 8 ++++---- shadercompiler/ParserUtils.h | 4 ++++ 3 files changed, 9 insertions(+), 30 deletions(-) diff --git a/shadercompiler/OutputHLSL.cpp b/shadercompiler/OutputHLSL.cpp index cf6e727e7..acd11ffd2 100644 --- a/shadercompiler/OutputHLSL.cpp +++ b/shadercompiler/OutputHLSL.cpp @@ -48,31 +48,6 @@ CodeStream& operator<<( CodeStream& os, const Children& children ) return os; } -bool HasUsedDeclarations( ASTNode* node ) -{ - for( unsigned i = 0; i < node->GetChildrenCount(); ++i ) - { - if( node->GetChild( i ) ) - { - if( node->GetChild( i )->GetNodeType() == NT_VAR_DECLARATION_LIST ) - { - if( HasUsedDeclarations( node->GetChild( i ) ) ) - { - return true; - } - } - else if( node->GetChild( i )->GetNodeType() == NT_NAME_DECLARATION ) - { - if( node->GetChild( i )->GetSymbol() && node->GetChild( i )->GetSymbol()->used ) - { - return true; - } - } - } - } - return false; -} - std::map s_operators = { { OP_MUL_ASSIGN, "*=" }, { OP_DIV_ASSIGN, "/=" }, @@ -1146,7 +1121,7 @@ CodeStream& operator<<( CodeStream& os, const HLSL& hlsl ) os << ";" << Endl(); break; case NT_CBUFFER: { - if( !HasUsedDeclarations( node ) ) + if( !HasUsedMembers( node ) ) { break; } diff --git a/shadercompiler/ParserUtils.cpp b/shadercompiler/ParserUtils.cpp index 8aa58994e..002a8bdf2 100644 --- a/shadercompiler/ParserUtils.cpp +++ b/shadercompiler/ParserUtils.cpp @@ -218,7 +218,7 @@ void MarkUsedSymbols( ASTNode* entryPoint, SymbolTable& symbols ) } } -static bool HasUsedDeclarations( ASTNode* node ) +bool HasUsedMembers( ASTNode* node ) { for( unsigned i = 0; i < node->GetChildrenCount(); ++i ) { @@ -228,7 +228,7 @@ static bool HasUsedDeclarations( ASTNode* node ) if( child->GetNodeType() == NT_VAR_DECLARATION_LIST || child->GetNodeType() == NT_STRUCT_MEMBER ) { - if( HasUsedDeclarations( child ) ) + if( HasUsedMembers( child ) ) { return true; } @@ -253,7 +253,7 @@ static void MarkCBuffersAndStructsUsed( ASTNode* node, SymbolTable& symbols ) } if( node->GetNodeType() == NT_STRUCT ) { - if( HasUsedDeclarations( node ) ) + if( HasUsedMembers( node ) ) { MarkUsedSymbols( node, symbols ); } @@ -272,7 +272,7 @@ static void MarkCBuffersAndStructsUsed( ASTNode* node, SymbolTable& symbols ) }; if( node->GetNodeType() == NT_CBUFFER && !IsGlobals() ) { - if( HasUsedDeclarations( node ) ) + if( HasUsedMembers( node ) ) { MarkUsedSymbols( node, symbols ); } diff --git a/shadercompiler/ParserUtils.h b/shadercompiler/ParserUtils.h index 0c7b51b68..cd70c0175 100644 --- a/shadercompiler/ParserUtils.h +++ b/shadercompiler/ParserUtils.h @@ -41,6 +41,10 @@ extern std::string ToString( const InlineString& string ); extern void MarkUsedSymbols( ASTNode* entryPoint, ParserState& state ); +// Returns true if any member of a cbuffer or struct is used: a name declared directly in the node, +// or in one of its declaration lists or struct members. +extern bool HasUsedMembers( ASTNode* node ); + extern bool ComputeMemberType( const Type& leftType, const InlineString& member, Type& type, Symbol*& symbol ); extern int GetCBufferIndex( const InlineString& name ); From a14069882833866c1d2e3b66cf8561dc20cd8ad2 Mon Sep 17 00:00:00 2001 From: ccpisheden Date: Tue, 1 Dec 2026 12:45:41 +0100 Subject: [PATCH 8/8] Shader compiler: fail on unhandled node types in ShouldWriteToMSL 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 --- shadercompiler/OutputHLSL.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/shadercompiler/OutputHLSL.cpp b/shadercompiler/OutputHLSL.cpp index acd11ffd2..fb0397675 100644 --- a/shadercompiler/OutputHLSL.cpp +++ b/shadercompiler/OutputHLSL.cpp @@ -1297,6 +1297,9 @@ static bool ShouldWriteToMSL( ASTNode* node ) case NT_STRUCT: case NT_NAME_DECLARATION: return !node->GetSymbol() || node->GetSymbol()->used; + case NT_FUNCTION_PARAMETER: + // System value fields that stage patching adds to the stage input and output structs. + return true; case NT_VAR_DECLARATION_LIST: case NT_STRUCT_MEMBER: for( unsigned i = 0; i < node->GetChildrenCount(); ++i ) @@ -1308,7 +1311,11 @@ static bool ShouldWriteToMSL( ASTNode* node ) } return false; default: - return true; + // Writing a declaration that isn't needed would make otherwise identical permutations + // differ, breaking deduplication without any error. Every declaration type must be + // handled explicitly above, so fail loudly instead. + assert( false && "ShouldWriteToMSL: unhandled node type" ); + return false; } }