From 06111edacb0eed90c63521c5029eb2704f9cfdd8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 14 Jul 2021 19:58:13 +0200 Subject: [PATCH] Enabled methods import for captured delegates --- ...erGenerator.CreateBuildHlslStringMethod.cs | 128 +++++++++++------- ...derMethodSourceAttribute.HlslGeneration.cs | 38 ++++++ .../MetaprogrammingTests.cs | 36 +++++ 3 files changed, 150 insertions(+), 52 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index cbda6b4d..c345ff3c 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -53,7 +53,7 @@ namespace ComputeSharp.SourceGenerators var pixelShaderTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes, isComputeShader).ToArray(); var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); - var (entryPoint, processedMethods, forwardDeclarations, accessesStaticSampler) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); + var (entryPoint, processedMethods, accessesStaticSampler) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); var implicitSamplerField = accessesStaticSampler ? ("SamplerState", "__sampler") : default((string, string)?); var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); var processedConstants = GetProcessedConstants(constantDefinitions); @@ -70,7 +70,6 @@ namespace ComputeSharp.SourceGenerators pixelShaderTextureType, accessesStaticSampler, sharedBuffers, - forwardDeclarations, processedMethods, entryPoint, out isHashSetDirectiveNeeded); @@ -301,7 +300,7 @@ namespace ComputeSharp.SourceGenerators /// Indicates whether or not represents a compute shader. /// A sequence of processed methods in , and the entry point. [Pure] - private static (string EntryPoint, IEnumerable Methods, IEnumerable Declarations, bool IsSamplerUser) GetProcessedMethods( + private static (string EntryPoint, IEnumerable<(string Signature, string Definition)> ProcessedMethods, bool IsSamplerUser) GetProcessedMethods( GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, @@ -318,8 +317,7 @@ namespace ComputeSharp.SourceGenerators select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); string? entryPoint = null; - List methods = new(); - List declarations = new(); + List<(string, string)> processedMethods = new(); bool isSamplerUsed = false; foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) @@ -356,8 +354,9 @@ namespace ComputeSharp.SourceGenerators // Emit the extracted local functions first foreach (var localFunction in shaderSourceRewriter.LocalFunctions) { - methods.Add(localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()); - declarations.Add(localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString()); + processedMethods.Add(( + localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString())); } // If the method is the shader entry point, do additional processing @@ -373,19 +372,21 @@ namespace ComputeSharp.SourceGenerators } else { - methods.Add(processedMethod.NormalizeWhitespace(eol: "\n").ToFullString()); - declarations.Add(processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString()); + processedMethods.Add(( + processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + processedMethod.NormalizeWhitespace(eol: "\n").ToFullString())); } } // Process static methods as well foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values) { - methods.Add(staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()); - declarations.Add(staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString()); + processedMethods.Add(( + staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); } - return (entryPoint!, methods, declarations, isSamplerUsed); + return (entryPoint!, processedMethods, isSamplerUsed); } /// @@ -468,7 +469,6 @@ namespace ComputeSharp.SourceGenerators /// The type of the implicit target texture, if present. /// Whether the static sampler is used by the shader. /// The sequence of shared buffers declared by the shader. - /// The sequence of forward method declarations. /// The sequence of processed methods used by the shader. /// The body of the entry point of the shader. /// Indicates whether or not the directive for is needed. @@ -482,8 +482,7 @@ namespace ComputeSharp.SourceGenerators string? implicitTextureType, bool isSamplerUsed, IEnumerable<(string Name, string Type, int? Count)> sharedBuffers, - IEnumerable forwardDeclarations, - IEnumerable processedMethods, + IEnumerable<(string Signature, string Definition)> processedMethods, string executeMethod, out bool isHashSetDirectiveNeeded) { @@ -538,31 +537,8 @@ namespace ComputeSharp.SourceGenerators } } - // Go through all existing delegate fields, if any - foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) - { - // ShaderMethodSourceAttribute __Attribute = ShaderMethodSourceAttribute.GetForDelegate(, ""); - statements.Add( - LocalDeclarationStatement(VariableDeclaration(IdentifierName(nameof(ShaderMethodSourceAttribute))) - .AddVariables( - VariableDeclarator(Identifier($"__{fieldName}Attribute")) - .WithInitializer( - EqualsValueClause( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(nameof(ShaderMethodSourceAttribute)), - IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate)))) - .AddArgumentListArguments( - Argument(IdentifierName(fieldName)), - Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName))))))))); - - capturedDelegates++; - prologueStatements++; - } - // Declare the hashsets to track imported members and types from delegates, if needed - if (capturedDelegates > 0) + if (instanceFields.Any(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) { void DeclareMapping(int index, string name, IEnumerable items) { @@ -596,7 +572,30 @@ namespace ComputeSharp.SourceGenerators DeclareMapping(0, "__typeNames", declaredTypes.Select(static t => t.Name)); DeclareMapping(1, "__constantNames", definedConstants.Select(static t => t.Name)); - DeclareMapping(2, "__methodNames", forwardDeclarations); + DeclareMapping(2, "__methodNames", processedMethods.Select(static t => t.Signature)); + + // Go through all existing delegate fields, if any + foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) + { + // ShaderMethodSourceAttribute __Attribute = ShaderMethodSourceAttribute.GetForDelegate(, ""); + statements.Add( + LocalDeclarationStatement(VariableDeclaration(IdentifierName(nameof(ShaderMethodSourceAttribute))) + .AddVariables( + VariableDeclarator(Identifier($"__{fieldName}Attribute")) + .WithInitializer( + EqualsValueClause( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName(nameof(ShaderMethodSourceAttribute)), + IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate)))) + .AddArgumentListArguments( + Argument(IdentifierName(fieldName)), + Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName))))))))); + + capturedDelegates++; + prologueStatements++; + } } isHashSetDirectiveNeeded = capturedDelegates > 0; @@ -660,9 +659,7 @@ namespace ComputeSharp.SourceGenerators // Declared types from captured delegates foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) { - AppendLF(); AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);"); - AppendLF(); } // Captured variables @@ -739,23 +736,50 @@ namespace ComputeSharp.SourceGenerators } // Forward declarations - if (forwardDeclarations is not null) + foreach (var (forwardDeclaration, _) in processedMethods) { - foreach (var forwardDeclaration in forwardDeclarations) + AppendLF(); + AppendLineAndLF(forwardDeclaration); + } + + // Forward declarations from captured delegates + foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendForwardDeclarations(ref builder, __methodNames);"); + } + + // Remove all forward declarations from methods that are embedded into the shader. + // This is necessary to avoid duplicate definitions from methods from delegates. + if (capturedDelegates > 0) + { + // .Add(""); + foreach (var (forwardDeclaration, _) in processedMethods) { - AppendLF(); - AppendLineAndLF(forwardDeclaration); + FlushText(); + + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("__methodNames"), + IdentifierName("Remove"))) + .AddArgumentListArguments(Argument( + LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration)))))); } } // Captured methods - if (processedMethods is not null) + foreach (var (_, method) in processedMethods) { - foreach (var method in processedMethods) - { - AppendLF(); - AppendLineAndLF(method); - } + AppendLF(); + AppendLineAndLF(method); + } + + // Captured methods from captured delegates + foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) + { + AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);"); } // Captured delegate methods diff --git a/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs b/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs index 9e79aa98..be523c2c 100644 --- a/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs +++ b/src/ComputeSharp/Core/Attributes/__Internals/ShaderMethodSourceAttribute.HlslGeneration.cs @@ -33,7 +33,45 @@ namespace ComputeSharp.__Internals { if (mapping.Add(type.Key)) { + builder.Append("\n"); builder.Append(type.Value); + builder.Append("\n"); + } + } + } + + /// + /// Appends the discovered forward declarations for the current method. + /// + /// The target instance to write to. + /// The mapping of already discovered type names. + public void AppendForwardDeclarations(ref ArrayPoolStringBuilder builder, HashSet mapping) + { + foreach (KeyValuePair method in this.methods) + { + if (mapping.Add(method.Key)) + { + builder.Append("\n"); + builder.Append(method.Key); + builder.Append("\n"); + } + } + } + + /// + /// Appends the discovered methods for the current method. + /// + /// The target instance to write to. + /// The mapping of already discovered type names. + public void AppendMethods(ref ArrayPoolStringBuilder builder, HashSet mapping) + { + foreach (KeyValuePair method in this.methods) + { + if (mapping.Remove(method.Key)) + { + builder.Append("\n"); + builder.Append(method.Value); + builder.Append("\n"); } } } diff --git a/tests/ComputeSharp.Tests/MetaprogrammingTests.cs b/tests/ComputeSharp.Tests/MetaprogrammingTests.cs index 9d5bf688..70bb9d22 100644 --- a/tests/ComputeSharp.Tests/MetaprogrammingTests.cs +++ b/tests/ComputeSharp.Tests/MetaprogrammingTests.cs @@ -56,6 +56,14 @@ namespace ComputeSharp.Tests public int A; public int B; } + + [ShaderMethod] + public static int FunctionWithLocalFunctionAndStaticMethod(int x) + { + static int AddTwo(int x) => x + 2; + + return Square(3 + AddOne(x) + AddTwo(x)); + } } [CombinatorialTestMethod] @@ -200,5 +208,33 @@ namespace ComputeSharp.Tests Assert.AreEqual(result[i].Y, Activations.FunctionWithTypes(i).Y); } } + + [AutoConstructor] + internal readonly partial struct DelegateWithLocalFunctionsAndStaticMethodsShader : IComputeShader + { + public readonly ReadWriteBuffer buffer; + public readonly Func activation; + + public void Execute() + { + buffer[ThreadIds.X] = Activations.AddOne(ThreadIds.X) + activation(ThreadIds.X); + } + } + + [CombinatorialTestMethod] + [AllDevices] + public unsafe void DelegateWithLocalFunctionsAndStaticMethods(Device device) + { + using ReadWriteBuffer buffer = device.Get().AllocateReadWriteBuffer(100); + + device.Get().For(100, new DelegateWithLocalFunctionsAndStaticMethodsShader(buffer, Activations.FunctionWithLocalFunctionAndStaticMethod)); + + int[] result = buffer.ToArray(); + + for (int i = 0; i < 100; i++) + { + Assert.AreEqual(result[i], Activations.AddOne(i) + Activations.FunctionWithLocalFunctionAndStaticMethod(i)); + } + } } }