diff --git a/shadercompiler/CMakeLists.txt b/shadercompiler/CMakeLists.txt index 0d48454d3..9159c9efc 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/ForwardDeclarationTest.cpp tests/GlobalInputTest.cpp tests/MetalConversionTest.cpp 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 6e32a18b1..4f86fbf15 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; @@ -947,7 +949,7 @@ void CollectGlobals( } } - PatchGlobalsInFunctions( functions, cbuffer->GetSymbol(), state.AllocateNameWithPrefix( "cbuffer" ), members ); + PatchGlobalsInFunctions( functions, cbuffer->GetSymbol(), state.AllocateGlobalName( "cbuffer" ), members ); } } @@ -2301,7 +2303,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; @@ -2362,7 +2364,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() ) ); @@ -2371,7 +2373,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 ); @@ -2387,7 +2389,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 ); @@ -2494,7 +2496,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 ); @@ -2510,7 +2512,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 ); @@ -2798,6 +2800,10 @@ ASTNode* PatchShader( PatchShaderType shaderType, ASTNode* callNode, ParserState { ZoneScoped; + // 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(); if( !entryPointSymbol || !entryPointSymbol->definition ) { @@ -2815,8 +2821,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 ); @@ -2895,7 +2903,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 ); @@ -2923,7 +2931,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(); @@ -3051,7 +3059,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 ); @@ -5110,16 +5118,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 ) { @@ -5183,6 +5181,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/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/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/OutputHLSL.cpp b/shadercompiler/OutputHLSL.cpp index c45221bf1..fb0397675 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; } @@ -1303,11 +1278,56 @@ 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_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 ) + { + if( ShouldWriteToMSL( node->GetChild( i ) ) ) + { + return true; + } + } + return false; + default: + // 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; + } +} + 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 +1900,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( ShouldWriteToMSL( node->GetChild( i ) ) ) + { + os << Child( i ); + } + } + os << Unindent() << Endl(); os << "};" << Endl(); } break; @@ -1901,6 +1929,10 @@ CodeStream& operator<<( CodeStream& os, const MSL& msl ) case NT_PROGRAM: for( unsigned i = 0; i < node->GetChildrenCount(); ++i ) { + if( !ShouldWriteToMSL( node->GetChild( i ) ) ) + { + continue; + } os << Child( i ); if( node->GetChild( i ) && node->GetChild( i )->GetNodeType() == NT_FUNCTION_HEADER ) { diff --git a/shadercompiler/ParserState.cpp b/shadercompiler/ParserState.cpp index 0a06457ff..f27225e0b 100644 --- a/shadercompiler/ParserState.cpp +++ b/shadercompiler/ParserState.cpp @@ -878,20 +878,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; @@ -921,32 +907,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 ae70ebbb6..05d922ca6 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 ); + + // 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 ); + + // 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 ); + InlineString AllocateLocalName( const InlineString& prefix ); + char* AllocateString( size_t size ); void ShowMessage( const FileLocation& location, int32_t errorCode, ... ); @@ -299,6 +313,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..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 ); } @@ -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..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 ); @@ -58,7 +62,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/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/TextureFunctionConversionDX11.cpp b/shadercompiler/TextureFunctionConversionDX11.cpp index b1153a514..a8833379b 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 new file mode 100644 index 000000000..82ace7068 --- /dev/null +++ b/shadercompiler/tests/DeterminismTest.cpp @@ -0,0 +1,285 @@ +// Copyright © 2026 CCP ehf. + +// 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 ) +{ + 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 +} + +TEST( Determinism, MetalPatchedShaderDoesNotDependOnEarlierStrings ) +{ + // 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."; + } + // 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 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."; + } + // 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 ); + } + } +} + +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 ) +{ + // 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 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;