From 0f129b2f8bba754b3f10d455f1e7c812cd3f7136 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 28 Dec 2020 17:20:34 +0100 Subject: [PATCH 01/16] Moved internal types to ComputeSharp.__Internals --- .../Attributes/IComputeShaderSourceAttribute.cs | 2 +- .../Attributes/ShaderMethodSourceAttribute.cs | 2 +- .../Exceptions/MissingMethodSourceException.cs | 1 + src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs | 1 + .../IComputeShaderSourceGenerator.cs | 4 +++- .../ShaderMethodSourceGenerator.cs | 1 + 6 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/ComputeSharp.Core/Attributes/IComputeShaderSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/IComputeShaderSourceAttribute.cs index b1db45a8..fb77a534 100644 --- a/src/ComputeSharp.Core/Attributes/IComputeShaderSourceAttribute.cs +++ b/src/ComputeSharp.Core/Attributes/IComputeShaderSourceAttribute.cs @@ -5,7 +5,7 @@ using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; -namespace ComputeSharp +namespace ComputeSharp.__Internals { /// /// An attribute that contains info on a processed compute shader that can be executed. diff --git a/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs index 594e01ff..094c43ab 100644 --- a/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs +++ b/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs @@ -6,7 +6,7 @@ using System.Reflection; using ComputeSharp.Core.Extensions; using ComputeSharp.Exceptions; -namespace ComputeSharp +namespace ComputeSharp.__Internals { /// /// An attribute that contains info on a processed shader method that can be executed within a shader. diff --git a/src/ComputeSharp.Core/Exceptions/MissingMethodSourceException.cs b/src/ComputeSharp.Core/Exceptions/MissingMethodSourceException.cs index ddb6232e..c31a043b 100644 --- a/src/ComputeSharp.Core/Exceptions/MissingMethodSourceException.cs +++ b/src/ComputeSharp.Core/Exceptions/MissingMethodSourceException.cs @@ -1,6 +1,7 @@ using System; using System.Diagnostics.Contracts; using System.Text; +using ComputeSharp.__Internals; using ComputeSharp.Core.Extensions; #pragma warning disable CS0618 diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index 989207a2..de25b813 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -4,6 +4,7 @@ using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; +using ComputeSharp.__Internals; using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Renderer.Models; using Microsoft.Toolkit.Diagnostics; diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs index f80986f1..a90ba55c 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderSourceGenerator.cs @@ -3,6 +3,7 @@ using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; using System.Text; +using ComputeSharp.__Internals; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Mappings; using ComputeSharp.SourceGenerators.SyntaxRewriters; @@ -81,7 +82,8 @@ namespace ComputeSharp.SourceGenerators // Create the compilation unit with the source attribute var source = - CompilationUnit().AddAttributeLists( + CompilationUnit().AddUsings( + UsingDirective(IdentifierName("ComputeSharp.__Internals"))).AddAttributeLists( AttributeList(SingletonSeparatedList( Attribute(IdentifierName(typeof(IComputeShaderSourceAttribute).FullName)).AddArgumentListArguments( AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(structDeclarationSymbol.GetFullMetadataName()))), diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index 277ec2c5..7ce2bf63 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -3,6 +3,7 @@ using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; using System.Text; +using ComputeSharp.__Internals; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.SyntaxRewriters; using Microsoft.CodeAnalysis; From e6a1fbc0baa1e4a94aa9b24d22ab47ad7251dd35 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 28 Dec 2020 17:21:20 +0100 Subject: [PATCH 02/16] Added initial IComputeShaderHashCodeGenerator type --- samples/ComputeSharp.Sample.Shared/Program.cs | 2 +- .../IComputeShaderHashCodeGenerator.cs | 93 +++++++++++++++++++ 2 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs diff --git a/samples/ComputeSharp.Sample.Shared/Program.cs b/samples/ComputeSharp.Sample.Shared/Program.cs index db49f66a..78b04240 100644 --- a/samples/ComputeSharp.Sample.Shared/Program.cs +++ b/samples/ComputeSharp.Sample.Shared/Program.cs @@ -42,7 +42,7 @@ namespace ComputeSharp.Sample /// Kernel for . /// [AutoConstructor] - private readonly partial struct MainKernel : IComputeShader + internal readonly partial struct MainKernel : IComputeShader { private readonly ReadWriteBuffer buffer; diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs new file mode 100644 index 00000000..7cf539b8 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs @@ -0,0 +1,93 @@ +using System.Collections.Immutable; +using System.Linq; +using System.Text; +using ComputeSharp.SourceGenerators.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGenerators +{ + [Generator] + public class IComputeShaderHashCodeGenerator : ISourceGenerator + { + /// + public void Initialize(GeneratorInitializationContext context) + { + } + + /// + public void Execute(GeneratorExecutionContext context) + { + // Find all the struct declarations + ImmutableArray structDeclarations = ( + from tree in context.Compilation.SyntaxTrees + from structDeclaration in tree.GetRoot().DescendantNodes().OfType() + select structDeclaration).ToImmutableArray(); + + foreach (StructDeclarationSyntax structDeclaration in structDeclarations) + { + SemanticModel semanticModel = context.Compilation.GetSemanticModel(structDeclaration.SyntaxTree); + INamedTypeSymbol structDeclarationSymbol = semanticModel.GetDeclaredSymbol(structDeclaration)!; + + // Only process compute shader types + if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) continue; + + TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString()); + BlockSyntax block = Block(ReturnStatement(LiteralExpression(SyntaxKind.NumericLiteralExpression, ParseToken("0")))); + + // Create a static method to create the combined hashcode for a given shader type. + // This code takes a block syntax and produces a compilation unit as follows: + // + // using System; + // using System.ComponentModel; + // + // namespace ComputeSharp.__Internals + // { + // internal static partial class HashCodeProvider + // { + // [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)] + // [System.Obsolete("This method is intended for internal usage only")] + // public static int CombineHashCode(int hash, in ShaderType shader) + // { + // return ...; + // } + // } + // } + var source = + CompilationUnit().AddUsings( + UsingDirective(IdentifierName("System")), + UsingDirective(IdentifierName("System.ComponentModel"))).AddMembers( + NamespaceDeclaration(IdentifierName("ComputeSharp.__Internals")).AddMembers( + ClassDeclaration("HashCodeProvider").AddModifiers( + Token(SyntaxKind.InternalKeyword), + Token(SyntaxKind.StaticKeyword), + Token(SyntaxKind.PartialKeyword)).AddMembers( + MethodDeclaration( + PredefinedType(Token(SyntaxKind.IntKeyword)), + Identifier("CombineHash")).AddAttributeLists( + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( + AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( + AttributeArgument(LiteralExpression( + SyntaxKind.StringLiteralExpression, + Literal("This method is intended for internal usage only"))))))).AddModifiers( + Token(SyntaxKind.PublicKeyword), + Token(SyntaxKind.StaticKeyword)).AddParameterListParameters( + Parameter(Identifier("hash")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), + Parameter(Identifier("shader")).WithModifiers(TokenList(Token(SyntaxKind.InKeyword))).WithType(shaderType)) + .WithBody(block)))) + .NormalizeWhitespace() + .ToFullString(); + + // Add the method source attribute + context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); + } + } + } +} + From 0aeb912184f88d6e2fed5ab51f5ab2415415cdf2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 28 Dec 2020 17:44:47 +0100 Subject: [PATCH 03/16] Implemented hash logic for captured fields --- .../IComputeShaderHashCodeGenerator.cs | 61 ++++++++++++++++++- 1 file changed, 59 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs index 7cf539b8..11c178f6 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs @@ -1,7 +1,10 @@ -using System.Collections.Immutable; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.Contracts; using System.Linq; using System.Text; using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGenerators.Mappings; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -36,7 +39,41 @@ namespace ComputeSharp.SourceGenerators if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) continue; TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString()); - BlockSyntax block = Block(ReturnStatement(LiteralExpression(SyntaxKind.NumericLiteralExpression, ParseToken("0")))); + + BlockSyntax block = Block(); + + // Process all the captured delegate types + foreach (var fieldName in GetDelegateMemberNames(structDeclarationSymbol)) + { + // hash += hash << 5; + block = block.AddStatements(ExpressionStatement( + AssignmentExpression( + SyntaxKind.AddAssignmentExpression, + IdentifierName("hash"), + BinaryExpression(SyntaxKind.LeftShiftExpression, + IdentifierName("hash"), + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5)))))); + + // hash += shader.Field[#i].Method.GetHashCode(); + block = block.AddStatements(ExpressionStatement( + AssignmentExpression( + SyntaxKind.AddAssignmentExpression, + IdentifierName("hash"), + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("shader"), + IdentifierName(fieldName)), + IdentifierName("Method")), + IdentifierName("GetHashCode")))))); + } + + // return hash; + block = block.AddStatements(ReturnStatement(IdentifierName("hash"))); // Create a static method to create the combined hashcode for a given shader type. // This code takes a block syntax and produces a compilation unit as follows: @@ -88,6 +125,26 @@ namespace ComputeSharp.SourceGenerators context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); } } + + /// + /// Gets a sequence of captured delegate fields to process. + /// + /// The input instance to process. + /// A sequence of captured delegate members in . + [Pure] + private static IEnumerable GetDelegateMemberNames(INamedTypeSymbol structDeclarationSymbol) + { + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + { + INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type; + + if (typeSymbol.TypeKind != TypeKind.Delegate) continue; + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + yield return mapping ?? fieldSymbol.Name; + } + } } } From 30eac3239fc9c4345dc53c43ac0e53887b2960c2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 28 Dec 2020 17:53:53 +0100 Subject: [PATCH 04/16] Removed dynamic IL for shader hashcode --- .../Translation/ShaderHashCodeProvider.cs | 55 ++----------------- 1 file changed, 4 insertions(+), 51 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs index d065911d..d6139881 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs @@ -1,11 +1,7 @@ using System; -using System.Collections.Generic; using System.Diagnostics.Contracts; -using System.Linq; using System.Reflection; -using System.Reflection.Emit; using System.Runtime.CompilerServices; -using ComputeSharp.Shaders.Extensions; namespace ComputeSharp.Shaders.Translation { @@ -38,16 +34,11 @@ namespace ComputeSharp.Shaders.Translation { Id = HashCode.Combine(typeof(T)); - // Get the valid delegates for delegate checking - FieldInfo[] delegateFieldInfos = ( - from fieldInfo in typeof(T).GetFields() - where fieldInfo.FieldType.IsDelegate() - select fieldInfo).ToArray(); - - // If at least one delegate is present, build the hasher method - if (delegateFieldInfos.Length > 0) + // Get the generated hasher, if one if present + if (typeof(T).Assembly.GetType("ComputeSharp.__Internals.HashCodeProvider") is Type type && + type.GetMethod("CombineHash", new[] { typeof(int), typeof(T).MakeByRefType() }) is MethodInfo method) { - Hasher = BuildDynamicHasher(delegateFieldInfos); + Hasher = method.CreateDelegate>(); } } } @@ -80,43 +71,5 @@ namespace ComputeSharp.Shaders.Translation /// The final hash value for the input closure. private delegate int Hasher(int hash, in T shader) where T : struct, IComputeShader; - - /// - /// Builds a new instance for the target and sequence of values. - /// - /// The type of compute shader currently in use. - /// The list of captured fields to inspect. - [Pure] - private static Hasher BuildDynamicHasher(IReadOnlyCollection fieldInfos) - where T : struct, IComputeShader - { - return DynamicMethod>.New(il => - { - MethodInfo - getMethodInfo = typeof(Delegate).GetProperty(nameof(Delegate.Method))!.GetMethod!, - getHashCodeInfo = typeof(object).GetMethod(nameof(object.GetHashCode))!; - foreach (FieldInfo fieldInfo in fieldInfos) - { - // (hashcode << 5) + hashcode - il.Emit(OpCodes.Ldarg_1); - il.Emit(OpCodes.Ldc_I4_5); - il.Emit(OpCodes.Shl); - il.Emit(OpCodes.Ldarg_1); - il.Emit(OpCodes.Add); - - // hashcode += shader.Function[#].Method.GetHashCode(); - il.Emit(OpCodes.Ldarg_2); - il.Emit(OpCodes.Ldfld, fieldInfo); - il.EmitCall(OpCodes.Callvirt, getMethodInfo, null); - il.EmitCall(OpCodes.Callvirt, getHashCodeInfo, null); - il.Emit(OpCodes.Add); - il.Emit(OpCodes.Starg_S, (byte)1); - } - - // Return the computed hash - il.Emit(OpCodes.Ldarg_1); - il.Emit(OpCodes.Ret); - }); - } } } From 544a242bb0a927aa1a10ce88922e14f40095cc39 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 28 Dec 2020 18:23:28 +0100 Subject: [PATCH 05/16] Added initial IComputeShaderDataLoaderGenerator type --- .../IComputeShaderDataLoaderGenerator.cs | 119 ++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs new file mode 100644 index 00000000..321a72c7 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs @@ -0,0 +1,119 @@ +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Diagnostics.Contracts; +using System.Linq; +using System.Text; +using ComputeSharp.SourceGenerators.Extensions; +using ComputeSharp.SourceGenerators.Mappings; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.SourceGenerators +{ + [Generator] + public class IComputeShaderDataLoaderGenerator : ISourceGenerator + { + /// + public void Initialize(GeneratorInitializationContext context) + { + } + + /// + public void Execute(GeneratorExecutionContext context) + { + // Find all the struct declarations + ImmutableArray structDeclarations = ( + from tree in context.Compilation.SyntaxTrees + from structDeclaration in tree.GetRoot().DescendantNodes().OfType() + select structDeclaration).ToImmutableArray(); + + foreach (StructDeclarationSyntax structDeclaration in structDeclarations) + { + SemanticModel semanticModel = context.Compilation.GetSemanticModel(structDeclaration.SyntaxTree); + INamedTypeSymbol structDeclarationSymbol = semanticModel.GetDeclaredSymbol(structDeclaration)!; + + // Only process compute shader types + if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) continue; + + TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString()); + + BlockSyntax block = Block(); + + // Create a static method to create the combined hashcode for a given shader type. + // This code takes a block syntax and produces a compilation unit as follows: + // + // using System; + // using System.ComponentModel; + // + // namespace ComputeSharp.__Internals + // { + // internal static partial class DispatchDataLoader + // { + // [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)] + // [System.Obsolete("This method is intended for internal usage only")] + // public static void LoadDispatchData(GraphicsDevice device, in ShaderType shader, ref ulong r0, ref byte r1) + // { + // ... + // } + // } + // } + var source = + CompilationUnit().AddUsings( + UsingDirective(IdentifierName("System")), + UsingDirective(IdentifierName("System.ComponentModel"))).AddMembers( + NamespaceDeclaration(IdentifierName("ComputeSharp.__Internals")).AddMembers( + ClassDeclaration("DispatchDataLoader").AddModifiers( + Token(SyntaxKind.InternalKeyword), + Token(SyntaxKind.StaticKeyword), + Token(SyntaxKind.PartialKeyword)).AddMembers( + MethodDeclaration( + PredefinedType(Token(SyntaxKind.VoidKeyword)), + Identifier("LoadDispatchData")).AddAttributeLists( + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( + AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( + AttributeArgument(LiteralExpression( + SyntaxKind.StringLiteralExpression, + Literal("This method is intended for internal usage only"))))))).AddModifiers( + Token(SyntaxKind.PublicKeyword), + Token(SyntaxKind.StaticKeyword)).AddParameterListParameters( + Parameter(Identifier("device")).WithType(IdentifierName("ComputeSharp.Graphics.GraphicsDevice")), + Parameter(Identifier("shader")).WithModifiers(TokenList(Token(SyntaxKind.InKeyword))).WithType(shaderType), + Parameter(Identifier("r0")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ULongKeyword))), + Parameter(Identifier("r1")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .WithBody(block)))) + .NormalizeWhitespace() + .ToFullString(); + + // Add the method source attribute + context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); + } + } + + /// + /// Gets a sequence of captured delegate fields to process. + /// + /// The input instance to process. + /// A sequence of captured delegate members in . + [Pure] + private static IEnumerable GetDelegateMemberNames(INamedTypeSymbol structDeclarationSymbol) + { + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + { + INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type; + + if (typeSymbol.TypeKind != TypeKind.Delegate) continue; + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + yield return mapping ?? fieldSymbol.Name; + } + } + } +} + From 29e2931a8a757b8b038c372f7a6c3d7075c56b01 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 28 Dec 2020 18:37:36 +0100 Subject: [PATCH 06/16] Added proxy GraphicsResourceHelper helper type --- .../__Internals/GraphicsResourceHelper.cs | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs diff --git a/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs b/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs new file mode 100644 index 00000000..9d364b20 --- /dev/null +++ b/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs @@ -0,0 +1,62 @@ +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using ComputeSharp.Graphics; +using ComputeSharp.Graphics.Buffers.Abstract; +using TerraFX.Interop; + +namespace ComputeSharp.__Internals +{ + /// + /// A helper class with some proxy methods to expose to generated code in external projects. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This type is meant to be used from the source generator only")] + public static class GraphicsResourceHelper + { + /// + /// Validates the given buffer for usage with a specified device, and retrieves its GPU descriptor handle. + /// + /// The input instance to check. + /// The target instance in use. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong ValidateAndGetGpuDescriptorHandle(Buffer buffer, GraphicsDevice device) + where T : unmanaged + { + buffer.ThrowIfDisposed(); + buffer.ThrowIfDeviceMismatch(device); + + return Unsafe.As(ref Unsafe.AsRef(in buffer.D3D12GpuDescriptorHandle)); + } + + /// + /// Validates the given buffer for usage with a specified device, and retrieves its GPU descriptor handle. + /// + /// The input instance to check. + /// The target instance in use. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong ValidateAndGetGpuDescriptorHandle(Texture2D buffer, GraphicsDevice device) + where T : unmanaged + { + buffer.ThrowIfDisposed(); + buffer.ThrowIfDeviceMismatch(device); + + return Unsafe.As(ref Unsafe.AsRef(in buffer.D3D12GpuDescriptorHandle)); + } + + /// + /// Validates the given buffer for usage with a specified device, and retrieves its GPU descriptor handle. + /// + /// The input instance to check. + /// The target instance in use. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static ulong ValidateAndGetGpuDescriptorHandle(Texture3D buffer, GraphicsDevice device) + where T : unmanaged + { + buffer.ThrowIfDisposed(); + buffer.ThrowIfDeviceMismatch(device); + + return Unsafe.As(ref Unsafe.AsRef(in buffer.D3D12GpuDescriptorHandle)); + } + } +} From 2b2ec28597ec071a0a3f4c999fde2dfb7cb7858f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 28 Dec 2020 19:38:41 +0100 Subject: [PATCH 07/16] Implemented initial dispatch data loader SG logic --- .../IComputeShaderDataLoaderGenerator.cs | 32 +++++++++++++++++-- .../IComputeShaderHashCodeGenerator.cs | 1 - .../Mappings/HlslKnownSizes.cs | 16 ++++++++-- .../Mappings/HlslKnownTypes.cs | 12 +++++++ 4 files changed, 56 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs index 321a72c7..c911e3f7 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs @@ -2,6 +2,7 @@ using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; +using System.Runtime.CompilerServices; using System.Text; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Mappings; @@ -39,8 +40,34 @@ namespace ComputeSharp.SourceGenerators if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) continue; TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString()); - BlockSyntax block = Block(); + int + resourceOffset = 0, + rawDataOffset = 0; + + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + { + INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type; + string typeName = typeSymbol.GetFullMetadataName(); + + if (HlslKnownTypes.IsTypedResourceType(typeName)) + { + block = block.AddStatements(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"Unsafe.Add(ref r0, {resourceOffset++})"), + ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(shader.{fieldSymbol.Name}, device)")))); + } + else if (HlslKnownTypes.IsScalarOrVectorType(typeName)) + { + var info = HlslKnownSizes.GetTypeInfo(typeName); + + block = block.AddStatements(ExpressionStatement( + ParseExpression($"Unsafe.WriteUnaligned(ref Unsafe.Add(ref r1, {rawDataOffset}), shader.{fieldSymbol.Name})"))); + + rawDataOffset += info.Size; + } + } // Create a static method to create the combined hashcode for a given shader type. // This code takes a block syntax and produces a compilation unit as follows: @@ -63,7 +90,8 @@ namespace ComputeSharp.SourceGenerators var source = CompilationUnit().AddUsings( UsingDirective(IdentifierName("System")), - UsingDirective(IdentifierName("System.ComponentModel"))).AddMembers( + UsingDirective(IdentifierName("System.ComponentModel")), + UsingDirective(IdentifierName("System.Runtime.CompilerServices"))).AddMembers( NamespaceDeclaration(IdentifierName("ComputeSharp.__Internals")).AddMembers( ClassDeclaration("DispatchDataLoader").AddModifiers( Token(SyntaxKind.InternalKeyword), diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs index 11c178f6..bd2fbc6e 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs @@ -39,7 +39,6 @@ namespace ComputeSharp.SourceGenerators if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) continue; TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString()); - BlockSyntax block = Block(); // Process all the captured delegate types diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownSizes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownSizes.cs index 0736932b..e05ff7a8 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownSizes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownSizes.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Diagnostics.Contracts; using System.Numerics; namespace ComputeSharp.SourceGenerators.Mappings @@ -9,9 +10,9 @@ namespace ComputeSharp.SourceGenerators.Mappings internal static class HlslKnownSizes { /// - /// Gets the mapping of supported known sizes to HLSL type names. + /// The mapping of supported known sizes to HLSL type names. /// - public static IReadOnlyDictionary KnownSizes { get; } = new Dictionary + private static IReadOnlyDictionary KnownSizes = new Dictionary { [typeof(bool).FullName] = (4, 4), [typeof(int).FullName] = (4, 4), @@ -43,5 +44,16 @@ namespace ComputeSharp.SourceGenerators.Mappings [typeof(Double3).FullName] = (24, 8), [typeof(Double3).FullName] = (32, 8) }; + + /// + /// Gets the size and alignment info for a specified primitive type. + /// + /// The type name to get info for. + /// The size and and alignment for the input type. + [Pure] + public static (int Size, int Pack) GetTypeInfo(string typeName) + { + return KnownSizes[typeName]; + } } } diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index b4332b8e..43ba20b4 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -78,6 +78,18 @@ namespace ComputeSharp.SourceGenerators.Mappings }; } + /// + /// Checks whether or not a given type name matches a typed resource type. + /// + /// The input type name to check. + /// Whether or not represents a typed resource type. + public static bool IsScalarOrVectorType(string typeName) + { + return + KnownTypes.ContainsKey(typeName) && + typeName != typeof(ThreadIds).FullName; + } + /// /// Gets the mapped HLSL-compatible type name for the input type symbol. /// From 0133009c124abe47fb3083f366bd983242370636 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 28 Dec 2020 19:59:12 +0100 Subject: [PATCH 08/16] Switched to SG for loading dispatch data --- samples/ComputeSharp.Sample.Shared/Program.cs | 2 +- .../Translation/Models/DispatchData.cs | 15 ++- .../Translation/ShaderLoader{T}.IL.cs | 123 +++--------------- .../Translation/ShaderLoader{T}.cs | 5 +- .../IComputeShaderDataLoaderGenerator.cs | 7 +- 5 files changed, 37 insertions(+), 115 deletions(-) diff --git a/samples/ComputeSharp.Sample.Shared/Program.cs b/samples/ComputeSharp.Sample.Shared/Program.cs index 78b04240..b56d467d 100644 --- a/samples/ComputeSharp.Sample.Shared/Program.cs +++ b/samples/ComputeSharp.Sample.Shared/Program.cs @@ -44,7 +44,7 @@ namespace ComputeSharp.Sample [AutoConstructor] internal readonly partial struct MainKernel : IComputeShader { - private readonly ReadWriteBuffer buffer; + public readonly ReadWriteBuffer buffer; /// public void Execute(ThreadIds ids) diff --git a/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs b/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs index 4f1eb61f..ca016a1c 100644 --- a/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs +++ b/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs @@ -12,9 +12,9 @@ namespace ComputeSharp.Shaders.Translation.Models internal readonly ref struct DispatchData { /// - /// The array with the captured buffers. + /// The array (actually values) with the captured buffers. /// - private readonly D3D12_GPU_DESCRIPTOR_HANDLE[] resourcesArray; + private readonly ulong[] resourcesArray; /// /// The number of values in . @@ -34,11 +34,11 @@ namespace ComputeSharp.Shaders.Translation.Models /// /// Creates a new instance with the specified parameters. /// - /// The array with the captured buffers. + /// The array with the captured buffers. /// The number of instances in . /// The array with all the captured variables, with proper padding. /// The actual size in bytes to use from . - public DispatchData(D3D12_GPU_DESCRIPTOR_HANDLE[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize) + public DispatchData(ulong[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize) { this.resourcesArray = resourcesArray; this.variablesArray = variablesArray; @@ -54,9 +54,10 @@ namespace ComputeSharp.Shaders.Translation.Models [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray); + ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(this.resourcesArray); + ref D3D12_GPU_DESCRIPTOR_HANDLE r1 = ref Unsafe.As(ref r0); - return MemoryMarshal.CreateReadOnlySpan(ref r0, this.resourcesCount); + return MemoryMarshal.CreateReadOnlySpan(ref r1, this.resourcesCount); } } @@ -79,7 +80,7 @@ namespace ComputeSharp.Shaders.Translation.Models /// public void Dispose() { - ArrayPool.Shared.Return(this.resourcesArray); + ArrayPool.Shared.Return(this.resourcesArray); ArrayPool.Shared.Return(this.variablesArray); } } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs index 40ff7baa..270c40e1 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs @@ -1,20 +1,13 @@ -using System.Buffers; +using System; +using System.Buffers; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Reflection; -using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ComputeSharp.Graphics; -using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Helpers; -using ComputeSharp.Graphics.Interop; -using ComputeSharp.Shaders.Extensions; -using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Translation.Models; -using Microsoft.Toolkit.Diagnostics; using TerraFX.Interop; -using FX = TerraFX.Interop.Windows; namespace ComputeSharp.Shaders.Translation { @@ -26,21 +19,19 @@ namespace ComputeSharp.Shaders.Translation /// /// The to use to run the shader. /// The shader instance to load the data from. - /// A reference to the buffer with all the captured instances. + /// + /// A reference to the buffer with all the captured instances. + /// This is just represented as a reference, to avoid exposing the type publicly. + /// /// A reference to the buffer to use to store all the captured value types. - private delegate void DispatchDataLoader(GraphicsDevice device, in T shader, ref D3D12_GPU_DESCRIPTOR_HANDLE r0, ref byte r1); + /// The returned value indicates the total number of written bytes into . + private delegate int DispatchDataLoader(GraphicsDevice device, in T shader, ref ulong r0, ref byte r1); /// /// The number of captured graphics resources (buffers). /// private int totalResourceCount; - /// - /// The size in bytes of the buffer with the captured variables. - /// - /// Initially set to 3 values for X, Y and Z threads counts. - private int totalVariablesByteSize = 3 * sizeof(int); - /// /// The cached instance to load dispatch data before execution. /// @@ -63,10 +54,10 @@ namespace ComputeSharp.Shaders.Translation public DispatchData GetDispatchData(GraphicsDevice device, in T shader, int x, int y, int z) { // Resources and variables buffers - D3D12_GPU_DESCRIPTOR_HANDLE[] resources = ArrayPool.Shared.Rent(this.totalResourceCount); - byte[] variables = ArrayPool.Shared.Rent(this.totalVariablesByteSize); + ulong[] resources = ArrayPool.Shared.Rent(this.totalResourceCount); + byte[] variables = ArrayPool.Shared.Rent(4096); - ref D3D12_GPU_DESCRIPTOR_HANDLE r0 = ref MemoryMarshal.GetArrayDataReference(resources); + ref ulong r0 = ref MemoryMarshal.GetArrayDataReference(resources); ref byte r1 = ref MemoryMarshal.GetArrayDataReference(variables); // Set the x, y and z counters @@ -75,96 +66,22 @@ namespace ComputeSharp.Shaders.Translation Unsafe.Add(ref Unsafe.As(ref r1), 2) = z; // Invoke the dynamic method to extract the captured data - this.dispatchDataLoader!(device, in shader, ref r0, ref r1); + int totalVariablesByteSize = this.dispatchDataLoader!(device, in shader, ref r0, ref r1); - return new(resources, this.totalResourceCount, variables, this.totalVariablesByteSize); + return new(resources, this.totalResourceCount, variables, totalVariablesByteSize); } /// - /// Builds a new instance that loads the dispatch data for the current shader type. + /// Initializes the instance that loads the dispatch data for the current shader type. /// - private void BuildDispatchDataLoader() + private void InitializeDispatchDataLoader() { - // The delegate signature is . - // Due to how DynamicMethod is implemented (see notes in the XML docs for DynamicMethod.New), - // all offsets for the input arguments are shifted by one. Because of this, we have the following: - // - // ldarg.1 = GraphicsDevice - // ldarg.2 = in T shader - // ldarg.3 = ref D3D12_GPU_DESCRIPTOR_HANDLE r0 - // ldarg.4 = ref byte r1 - this.dispatchDataLoader = DynamicMethod.New(il => - { - foreach (FieldInfo fieldInfo in this.capturedFields) - { - if (HlslKnownTypes.IsKnownBufferType(fieldInfo.FieldType)) - { - // Load the offset address into the resource buffers - il.Emit(OpCodes.Ldarg_3); + // Get the generated data loader + Type[] argumentTypes = new[] { typeof(GraphicsDevice), typeof(T).MakeByRefType(), typeof(ulong).MakeByRefType(), typeof(byte).MakeByRefType() }; + Type type = typeof(T).Assembly.GetType("ComputeSharp.__Internals.DispatchDataLoader")!; + MethodInfo method = type.GetMethod("LoadDispatchData", argumentTypes)!; - if (totalResourceCount > 0) - { - il.EmitAddOffset(this.totalResourceCount); - } - - il.Emit(OpCodes.Ldarg_2); - il.EmitReadMember(fieldInfo); - - // Call NativeObject.ThrowIfDisposed() - il.Emit(OpCodes.Dup); - il.EmitCall(OpCodes.Callvirt, typeof(NativeObject).GetMethod( - nameof(NativeObject.ThrowIfDisposed), - BindingFlags.Instance | BindingFlags.NonPublic)!, null); - - // Call ThrowIfDeviceMismatch(GraphicsDevice) - il.Emit(OpCodes.Dup); - il.Emit(OpCodes.Ldarg_1); - il.EmitCall(OpCodes.Callvirt, fieldInfo.FieldType.GetMethod( - nameof(Buffer.ThrowIfDeviceMismatch), - BindingFlags.Instance | BindingFlags.NonPublic)!, null); - - // Access D3D12GpuDescriptorHandle - il.EmitReadMember(fieldInfo.FieldType.GetField( - nameof(Buffer.D3D12GpuDescriptorHandle), - BindingFlags.Instance | BindingFlags.NonPublic)!); - il.EmitStoreToAddress(typeof(D3D12_GPU_DESCRIPTOR_HANDLE)); - - this.totalResourceCount++; - } - else if (HlslKnownTypes.IsKnownScalarType(fieldInfo.FieldType) || - HlslKnownTypes.IsKnownVectorType(fieldInfo.FieldType)) - { - // Calculate the right offset with 16-bytes padding (HLSL constant buffer) - int elementSizeInBytes = Marshal.SizeOf(fieldInfo.FieldType); - - this.totalVariablesByteSize = AlignmentHelper.AlignToBoundary( - this.totalVariablesByteSize, - elementSizeInBytes, - FX.D3D12_COMMONSHADER_CONSTANT_BUFFER_PARTIAL_UPDATE_EXTENTS_BYTE_ALIGNMENT); - - // Load the target address into the variables buffer - il.Emit(OpCodes.Ldarg_S, (byte)4); - il.EmitAddOffset(totalVariablesByteSize); - - il.Emit(OpCodes.Ldarg_2); - il.EmitReadMember(fieldInfo); - il.EmitStoreToAddress(fieldInfo.FieldType); - - this.totalVariablesByteSize += elementSizeInBytes; - } - else ThrowHelper.ThrowArgumentException("Invalid captured member type"); - } - - il.Emit(OpCodes.Ret); - }); - - // After all the captured fields have been processed, ansure the reported byte size for - // the local variables is padded to the standard alignment for constant buffers. This is - // necessary to enable loading all the dispatch data after reinterpreting it to a sequence - // of values of size 16 bytes (in particular, Int4 is used), without reading out of bounds. - this.totalVariablesByteSize = AlignmentHelper.Pad( - this.totalVariablesByteSize, - FX.D3D12_COMMONSHADER_CONSTANT_BUFFER_PARTIAL_UPDATE_EXTENTS_BYTE_ALIGNMENT); + this.dispatchDataLoader = method.CreateDelegate(); } } } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs index de25b813..92ee855b 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -114,7 +114,7 @@ namespace ComputeSharp.Shaders.Translation @this.LoadFieldsInfo(box); @this.LoadMethodMetadata(); - @this.BuildDispatchDataLoader(); + @this.InitializeDispatchDataLoader(); return @this; } @@ -164,6 +164,7 @@ namespace ComputeSharp.Shaders.Translation this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.Constant(hlslType, hlslName, (int)this.constantBuffersCount++)); + this.totalResourceCount++; } else if (HlslKnownTypes.IsReadOnlyResourceType(fieldType)) { @@ -172,6 +173,7 @@ namespace ComputeSharp.Shaders.Translation this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.ReadOnly(hlslType, hlslName, (int)this.readOnlyBuffersCount++)); + this.totalResourceCount++; } else if (HlslKnownTypes.IsReadWriteResourceType(fieldType)) { @@ -180,6 +182,7 @@ namespace ComputeSharp.Shaders.Translation this.d3D12DescriptorRanges1.Add(d3D12DescriptorRange1); this.capturedFields.Add(fieldInfo); this.hlslResourceInfo.Add(new HlslResourceInfo.ReadWrite(hlslType, hlslName, (int)this.readWriteBuffersCount++)); + this.totalResourceCount++; } else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType)) { diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs index c911e3f7..453a5b40 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs @@ -2,7 +2,6 @@ using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; -using System.Runtime.CompilerServices; using System.Text; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Mappings; @@ -69,6 +68,8 @@ namespace ComputeSharp.SourceGenerators } } + block = block.AddStatements(ReturnStatement(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1024)))); + // Create a static method to create the combined hashcode for a given shader type. // This code takes a block syntax and produces a compilation unit as follows: // @@ -81,7 +82,7 @@ namespace ComputeSharp.SourceGenerators // { // [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)] // [System.Obsolete("This method is intended for internal usage only")] - // public static void LoadDispatchData(GraphicsDevice device, in ShaderType shader, ref ulong r0, ref byte r1) + // public static int LoadDispatchData(GraphicsDevice device, in ShaderType shader, ref ulong r0, ref byte r1) // { // ... // } @@ -98,7 +99,7 @@ namespace ComputeSharp.SourceGenerators Token(SyntaxKind.StaticKeyword), Token(SyntaxKind.PartialKeyword)).AddMembers( MethodDeclaration( - PredefinedType(Token(SyntaxKind.VoidKeyword)), + PredefinedType(Token(SyntaxKind.IntKeyword)), Identifier("LoadDispatchData")).AddAttributeLists( AttributeList(SingletonSeparatedList( Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( From 0c553d5b092c08acc49e298b749f98e37535a82f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 28 Dec 2020 20:02:28 +0100 Subject: [PATCH 09/16] Removed leftover IL generation code --- .../Extensions/ILGeneratorExtensions.cs | 107 ------------------ .../Extensions/TypeExtensions.cs | 21 ---- .../Helpers/DynamicMethod{T}.cs | 58 ---------- ....IL.cs => ShaderLoader{T}.DispatchData.cs} | 0 .../DynamicMethodTests.cs | 29 ----- 5 files changed, 215 deletions(-) delete mode 100644 src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs delete mode 100644 src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs delete mode 100644 src/ComputeSharp.Shaders/Helpers/DynamicMethod{T}.cs rename src/ComputeSharp.Shaders/Translation/{ShaderLoader{T}.IL.cs => ShaderLoader{T}.DispatchData.cs} (100%) delete mode 100644 tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs diff --git a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs deleted file mode 100644 index 816911bc..00000000 --- a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs +++ /dev/null @@ -1,107 +0,0 @@ -using System; -using System.Reflection; -using System.Reflection.Emit; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using Microsoft.Toolkit.Diagnostics; - -namespace ComputeSharp.Shaders.Extensions -{ - /// - /// A that provides extension methods for the type. - /// - internal static class ILGeneratorExtensions - { - /// - /// Puts the appropriate , , or instruction to read a member onte the stream of instructions. - /// - /// The input instance to use to emit instructions. - /// The member to read. - public static void EmitReadMember(this ILGenerator il, MemberInfo member) - { - switch (member) - { - case FieldInfo field: - il.Emit(field.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, field); - break; - case PropertyInfo property when property.CanRead: - il.EmitCall(property.GetMethod!.IsStatic ? OpCodes.Call : OpCodes.Callvirt, property.GetMethod, null); - break; - default: ThrowHelper.ThrowArgumentException("The input MemberInfo instance can't be read"); return; - } - } - - /// - /// Puts the appropriate , and instructions to advance a reference onto the stream of instructions. - /// - /// The type of reference at the top of the stack. - /// The input instance to use to emit instructions. - /// The offset to use to advance the current reference on top of the execution stack. - public static void EmitAddOffset(this ILGenerator il, int offset) => il.EmitAddOffset(Unsafe.SizeOf() * offset); - - /// - /// Puts the appropriate , and instructions to advance a reference onto the stream of instructions. - /// - /// The input instance to use to emit instructions. - /// The offset in bytes to use to advance the current reference on top of the execution stack. - public static void EmitAddOffset(this ILGenerator il, int offset) - { - // Push the offset to the stack - if (offset < -128) il.Emit(OpCodes.Ldc_I4, offset); - else if (offset < 0) il.Emit(OpCodes.Ldc_I4_S, (sbyte)offset); - else if (offset <= 8) - { - il.Emit(offset switch - { - 0 => OpCodes.Ldc_I4_0, - 1 => OpCodes.Ldc_I4_1, - 2 => OpCodes.Ldc_I4_2, - 3 => OpCodes.Ldc_I4_3, - 4 => OpCodes.Ldc_I4_4, - 5 => OpCodes.Ldc_I4_5, - 6 => OpCodes.Ldc_I4_6, - 7 => OpCodes.Ldc_I4_7, - 8 => OpCodes.Ldc_I4_8, - _ => ThrowHelper.ThrowArgumentException("Invalid offset value") - }); - } - else if (offset <= 127) il.Emit(OpCodes.Ldc_I4_S, (byte)offset); - else il.Emit(OpCodes.Ldc_I4, offset); - - // Converts the offset to native int and adds to the address - il.Emit(OpCodes.Conv_I); - il.Emit(OpCodes.Add); - } - - /// - /// Puts the appropriate or instruction to write to a reference onto the stream of instructions. - /// - /// The input instance to use to emit instructions. - /// The type of value being written to the current reference on top of the execution stack. - public static void EmitStoreToAddress(this ILGenerator il, Type type) - { - if (type.IsValueType) - { - // Pick the optimal opcode to set a value type - OpCode opcode = Marshal.SizeOf(type) switch - { - // Use the faster op codes for sizes <= 8 - 1 when type == typeof(byte) || type == typeof(sbyte) => OpCodes.Stind_I1, - 2 when type == typeof(short) || type == typeof(ushort) => OpCodes.Stind_I2, - 4 when type == typeof(float) => OpCodes.Stind_R4, - 4 when type == typeof(int) || type == typeof(uint) => OpCodes.Stind_I4, - 8 when type == typeof(double) => OpCodes.Stind_R8, - 8 when type == typeof(long) || type == typeof(ulong) => OpCodes.Stind_I8, - - // Default to stobj for all other value types - _ => OpCodes.Stobj - }; - - // Also pass the type token if stobj is used - if (opcode == OpCodes.Stobj) il.Emit(opcode, type); - else il.Emit(opcode); - } - else il.Emit(OpCodes.Stind_Ref); - } - } -} diff --git a/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs b/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs deleted file mode 100644 index 72771697..00000000 --- a/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Diagnostics.Contracts; - -namespace ComputeSharp.Shaders.Extensions -{ - /// - /// A that provides extension methods for the type. - /// - internal static class TypeExtensions - { - /// - /// Gets whether or not the input represents a . - /// - /// The input type to analyze. - [Pure] - public static bool IsDelegate(this Type type) - { - return type.IsSubclassOf(typeof(Delegate)); - } - } -} diff --git a/src/ComputeSharp.Shaders/Helpers/DynamicMethod{T}.cs b/src/ComputeSharp.Shaders/Helpers/DynamicMethod{T}.cs deleted file mode 100644 index 7a1a6ec0..00000000 --- a/src/ComputeSharp.Shaders/Helpers/DynamicMethod{T}.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System.Diagnostics.Contracts; -using System.Linq; - -namespace System.Reflection.Emit -{ - /// - /// A that can be used to easily create dynamic methods. - /// - /// The type of that will be used to wrap the new methods. - internal static class DynamicMethod - where T : Delegate - { - /// - /// The return type of the . - /// - private static readonly Type ReturnType; - - /// - /// The types of the arguments of the . - /// - private static readonly Type[] ParameterTypes; - - /// - /// Loads all the necessary info for the current parameter. - /// - static DynamicMethod() - { - MethodInfo method = typeof(T).GetMethod("Invoke")!; - - ReturnType = method.ReturnType; - ParameterTypes = new[] { typeof(object) }.Concat(method.GetParameters().Select(static p => p.ParameterType)).ToArray(); - } - - /// - /// Creates a new for the target owner. For performance reasons, - /// the underlying dynamic method will be created with an extra parameter, and then bound to - /// a instance. This is to emulate the behavior of instance methods, which unlike static ones - /// don't need to go through the shuffle thunk when the delegate is invoked. This would be needed to redirect the - /// invocation to a stub that performs parameters swapping, as the Invoke method is an instance one with the parameters - /// starting from offset 1, while the target static method would expect them to start from offset 0. This solution - /// allows the delegate created for the dynamic method to avoid having a shuffle thunk at all, and with it only having - /// to replace the hidden instance argument when being invoked, resulting in much better performance. Because of this, - /// it is expected that will emit the bytecode assuming that there is an extra unused argument - /// at offset 0. As a result of this, all argument load and store opcodes will need to be shifted by one position forwards. - /// - /// An that builds the IL bytecode for the new method. - /// A new dynamic method wrapped as a . - [Pure] - public static T New(Action builder) - { - DynamicMethod method = new(string.Empty, ReturnType, ParameterTypes, true); - - builder(method.GetILGenerator()); - - return method.CreateDelegate(null); - } - } -} diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs similarity index 100% rename from src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs rename to src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.DispatchData.cs diff --git a/tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs b/tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs deleted file mode 100644 index 0c1a5453..00000000 --- a/tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; -using System.Reflection.Emit; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace ComputeSharp.Tests.Internals -{ - [TestClass] - [TestCategory("DynamicMethod")] - public class DynamicMethodTests - { - [TestMethod] - public void TestFunc() - { - Func square = DynamicMethod>.New(il => - { - // Due to the instance method trick, the first parameter is at offset 1. - // See the docs on DynamicMethod.New for more info on how this works. - il.Emit(OpCodes.Ldarg_1); - il.Emit(OpCodes.Dup); - il.Emit(OpCodes.Mul); - il.Emit(OpCodes.Ret); - }); - - int result = square(2); // result = 2 * 2 - - Assert.IsTrue(result == 4); - } - } -} From 5b2f90e368009b5f880256baa6b9193fce45453c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 28 Dec 2020 22:21:55 +0100 Subject: [PATCH 10/16] Fixed padding/alignment in dispatch data loader --- .../Helpers/AlignmentHelper.cs | 2 +- .../Buffers/ConstantBuffer{T}.cs | 1 + .../ComputeSharp.SourceGenerators.csproj | 1 + .../IComputeShaderDataLoaderGenerator.cs | 20 +++++++++++++++++-- 4 files changed, 21 insertions(+), 3 deletions(-) rename src/{ComputeSharp.Graphics => ComputeSharp.Core}/Helpers/AlignmentHelper.cs (97%) diff --git a/src/ComputeSharp.Graphics/Helpers/AlignmentHelper.cs b/src/ComputeSharp.Core/Helpers/AlignmentHelper.cs similarity index 97% rename from src/ComputeSharp.Graphics/Helpers/AlignmentHelper.cs rename to src/ComputeSharp.Core/Helpers/AlignmentHelper.cs index 6191c0c3..20baf93f 100644 --- a/src/ComputeSharp.Graphics/Helpers/AlignmentHelper.cs +++ b/src/ComputeSharp.Core/Helpers/AlignmentHelper.cs @@ -1,7 +1,7 @@ using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; -namespace ComputeSharp.Graphics.Helpers +namespace ComputeSharp.Core.Helpers { /// /// A with helper methods to work with alignment and padding. diff --git a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs index 363c2a9a..e95116b7 100644 --- a/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs +++ b/src/ComputeSharp.Graphics/Buffers/ConstantBuffer{T}.cs @@ -1,6 +1,7 @@ using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; +using ComputeSharp.Core.Helpers; using ComputeSharp.Exceptions; using ComputeSharp.Graphics; using ComputeSharp.Graphics.Buffers.Abstract; diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index d2b96445..566c816a 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -21,6 +21,7 @@ + diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs index 453a5b40..4f513246 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs @@ -3,6 +3,7 @@ using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; using System.Text; +using ComputeSharp.Core.Helpers; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Mappings; using Microsoft.CodeAnalysis; @@ -42,7 +43,7 @@ namespace ComputeSharp.SourceGenerators BlockSyntax block = Block(); int resourceOffset = 0, - rawDataOffset = 0; + rawDataOffset = sizeof(int) * 3; foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { @@ -61,6 +62,15 @@ namespace ComputeSharp.SourceGenerators { var info = HlslKnownSizes.GetTypeInfo(typeName); + // Calculate the right offset with 16-bytes padding (HLSL constant buffer). + // Since we're in a constant buffer, we need to both pad the starting offset + // to be aligned to the packing size of the type, and also to align the initial + // offset to ensure that values do not cross 16 bytes boundaries either. + rawDataOffset = AlignmentHelper.AlignToBoundary( + AlignmentHelper.Pad(rawDataOffset, info.Pack), + info.Size, + 16); + block = block.AddStatements(ExpressionStatement( ParseExpression($"Unsafe.WriteUnaligned(ref Unsafe.Add(ref r1, {rawDataOffset}), shader.{fieldSymbol.Name})"))); @@ -68,7 +78,13 @@ namespace ComputeSharp.SourceGenerators } } - block = block.AddStatements(ReturnStatement(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1024)))); + // After all the captured fields have been processed, ansure the reported byte size for + // the local variables is padded to the standard alignment for constant buffers. This is + // necessary to enable loading all the dispatch data after reinterpreting it to a sequence + // of values of size 16 bytes (in particular, Int4 is used), without reading out of bounds. + rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); + + block = block.AddStatements(ReturnStatement(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(rawDataOffset)))); // Create a static method to create the combined hashcode for a given shader type. // This code takes a block syntax and produces a compilation unit as follows: From 4d3e744f309c5e4746e19b505cf37fbb097ced4f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 28 Dec 2020 22:40:22 +0100 Subject: [PATCH 11/16] Code refactoring to source generators --- .../IComputeShaderDataLoaderGenerator.cs | 92 +++++++++---------- .../IComputeShaderHashCodeGenerator.cs | 51 +++------- 2 files changed, 54 insertions(+), 89 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs index 4f513246..72af86c8 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs @@ -40,51 +40,7 @@ namespace ComputeSharp.SourceGenerators if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) continue; TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString()); - BlockSyntax block = Block(); - int - resourceOffset = 0, - rawDataOffset = sizeof(int) * 3; - - foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) - { - INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type; - string typeName = typeSymbol.GetFullMetadataName(); - - if (HlslKnownTypes.IsTypedResourceType(typeName)) - { - block = block.AddStatements(ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"Unsafe.Add(ref r0, {resourceOffset++})"), - ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(shader.{fieldSymbol.Name}, device)")))); - } - else if (HlslKnownTypes.IsScalarOrVectorType(typeName)) - { - var info = HlslKnownSizes.GetTypeInfo(typeName); - - // Calculate the right offset with 16-bytes padding (HLSL constant buffer). - // Since we're in a constant buffer, we need to both pad the starting offset - // to be aligned to the packing size of the type, and also to align the initial - // offset to ensure that values do not cross 16 bytes boundaries either. - rawDataOffset = AlignmentHelper.AlignToBoundary( - AlignmentHelper.Pad(rawDataOffset, info.Pack), - info.Size, - 16); - - block = block.AddStatements(ExpressionStatement( - ParseExpression($"Unsafe.WriteUnaligned(ref Unsafe.Add(ref r1, {rawDataOffset}), shader.{fieldSymbol.Name})"))); - - rawDataOffset += info.Size; - } - } - - // After all the captured fields have been processed, ansure the reported byte size for - // the local variables is padded to the standard alignment for constant buffers. This is - // necessary to enable loading all the dispatch data after reinterpreting it to a sequence - // of values of size 16 bytes (in particular, Int4 is used), without reading out of bounds. - rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); - - block = block.AddStatements(ReturnStatement(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(rawDataOffset)))); + BlockSyntax block = Block(GetDispatchDataLoadingStatements(structDeclarationSymbol)); // Create a static method to create the combined hashcode for a given shader type. // This code takes a block syntax and produces a compilation unit as follows: @@ -141,23 +97,57 @@ namespace ComputeSharp.SourceGenerators } /// - /// Gets a sequence of captured delegate fields to process. + /// Gets a sequence of statements to load the dispatch data for a given shader /// /// The input instance to process. - /// A sequence of captured delegate members in . + /// The sequence of instances to load shader dispatch data. [Pure] - private static IEnumerable GetDelegateMemberNames(INamedTypeSymbol structDeclarationSymbol) + private static IEnumerable GetDispatchDataLoadingStatements(INamedTypeSymbol structDeclarationSymbol) { + int + resourceOffset = 0, + rawDataOffset = sizeof(int) * 3; + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { INamedTypeSymbol typeSymbol = (INamedTypeSymbol)fieldSymbol.Type; + string typeName = typeSymbol.GetFullMetadataName(); - if (typeSymbol.TypeKind != TypeKind.Delegate) continue; + if (HlslKnownTypes.IsTypedResourceType(typeName)) + { + yield return ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"Unsafe.Add(ref r0, {resourceOffset++})"), + ParseExpression($"GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(shader.{fieldSymbol.Name}, device)"))); + } + else if (HlslKnownTypes.IsScalarOrVectorType(typeName)) + { + var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName); - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + // Calculate the right offset with 16-bytes padding (HLSL constant buffer). + // Since we're in a constant buffer, we need to both pad the starting offset + // to be aligned to the packing size of the type, and also to align the initial + // offset to ensure that values do not cross 16 bytes boundaries either. + rawDataOffset = AlignmentHelper.AlignToBoundary( + AlignmentHelper.Pad(rawDataOffset, fieldPack), + fieldSize, + 16); - yield return mapping ?? fieldSymbol.Name; + yield return ExpressionStatement( + ParseExpression($"Unsafe.WriteUnaligned(ref Unsafe.Add(ref r1, {rawDataOffset}), shader.{fieldSymbol.Name})")); + + rawDataOffset += fieldSize; + } } + + // After all the captured fields have been processed, ansure the reported byte size for + // the local variables is padded to the standard alignment for constant buffers. This is + // necessary to enable loading all the dispatch data after reinterpreting it to a sequence + // of values of size 16 bytes (in particular, Int4 is used), without reading out of bounds. + rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); + + yield return ReturnStatement(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(rawDataOffset))); } } } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs index bd2fbc6e..9fe81a0f 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs @@ -39,40 +39,7 @@ namespace ComputeSharp.SourceGenerators if (!structDeclarationSymbol.Interfaces.Any(static interfaceSymbol => interfaceSymbol.Name == nameof(IComputeShader))) continue; TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString()); - BlockSyntax block = Block(); - - // Process all the captured delegate types - foreach (var fieldName in GetDelegateMemberNames(structDeclarationSymbol)) - { - // hash += hash << 5; - block = block.AddStatements(ExpressionStatement( - AssignmentExpression( - SyntaxKind.AddAssignmentExpression, - IdentifierName("hash"), - BinaryExpression(SyntaxKind.LeftShiftExpression, - IdentifierName("hash"), - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5)))))); - - // hash += shader.Field[#i].Method.GetHashCode(); - block = block.AddStatements(ExpressionStatement( - AssignmentExpression( - SyntaxKind.AddAssignmentExpression, - IdentifierName("hash"), - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("shader"), - IdentifierName(fieldName)), - IdentifierName("Method")), - IdentifierName("GetHashCode")))))); - } - - // return hash; - block = block.AddStatements(ReturnStatement(IdentifierName("hash"))); + BlockSyntax block = Block(GetDelegateHashCodeStatements(structDeclarationSymbol)); // Create a static method to create the combined hashcode for a given shader type. // This code takes a block syntax and produces a compilation unit as follows: @@ -126,12 +93,12 @@ namespace ComputeSharp.SourceGenerators } /// - /// Gets a sequence of captured delegate fields to process. + /// Gets a sequence of statements to process the hashcode of the captured delegates. /// /// The input instance to process. - /// A sequence of captured delegate members in . + /// The sequence of instances to hash the captured delegates. [Pure] - private static IEnumerable GetDelegateMemberNames(INamedTypeSymbol structDeclarationSymbol) + private static IEnumerable GetDelegateHashCodeStatements(INamedTypeSymbol structDeclarationSymbol) { foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { @@ -141,8 +108,16 @@ namespace ComputeSharp.SourceGenerators _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - yield return mapping ?? fieldSymbol.Name; + string fieldName = mapping ?? fieldSymbol.Name; + + // hash += hash << 5; + yield return ExpressionStatement(ParseExpression($"hash += hash << 5")); + + // hash += shader.Field[#i].Method.GetHashCode(); + yield return ExpressionStatement(ParseExpression($"hash += shader.{fieldName}.Method.GetHashCode()")); } + + yield return ReturnStatement(IdentifierName("hash")); } } } From f7d998ef308945071f2a6446a9b2d481c033ae10 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 28 Dec 2020 22:46:33 +0100 Subject: [PATCH 12/16] Skipped hashcode providers with no delegates --- .../IComputeShaderHashCodeGenerator.cs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs index 9fe81a0f..2632d94f 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs @@ -4,7 +4,6 @@ using System.Diagnostics.Contracts; using System.Linq; using System.Text; using ComputeSharp.SourceGenerators.Extensions; -using ComputeSharp.SourceGenerators.Mappings; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -41,6 +40,8 @@ namespace ComputeSharp.SourceGenerators TypeSyntax shaderType = ParseTypeName(structDeclarationSymbol.ToDisplayString()); BlockSyntax block = Block(GetDelegateHashCodeStatements(structDeclarationSymbol)); + if (block.Statements.Count == 1) continue; + // Create a static method to create the combined hashcode for a given shader type. // This code takes a block syntax and produces a compilation unit as follows: // @@ -106,15 +107,11 @@ namespace ComputeSharp.SourceGenerators if (typeSymbol.TypeKind != TypeKind.Delegate) continue; - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - - string fieldName = mapping ?? fieldSymbol.Name; - // hash += hash << 5; yield return ExpressionStatement(ParseExpression($"hash += hash << 5")); // hash += shader.Field[#i].Method.GetHashCode(); - yield return ExpressionStatement(ParseExpression($"hash += shader.{fieldName}.Method.GetHashCode()")); + yield return ExpressionStatement(ParseExpression($"hash += shader.{fieldSymbol.Name}.Method.GetHashCode()")); } yield return ReturnStatement(IdentifierName("hash")); From 400a2f4ab36b00432ca484f7b685fd4e36be90a8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 29 Dec 2020 00:33:23 +0100 Subject: [PATCH 13/16] Fixed image processing sample --- .../Processors/HlslBokehBlurProcessor.cs | 87 +++++++++++++- .../HlslBokehBlurProcessor{TPixel}.cs | 86 +------------- .../Processors/HlslGaussianBlurProcessor.cs | 79 ++++++++++++- .../HlslGaussianBlurProcessor{TPixel}.cs | 110 +++--------------- 4 files changed, 183 insertions(+), 179 deletions(-) diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs index c756217e..84e05a55 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor.cs @@ -1,4 +1,5 @@ -using SixLabors.ImageSharp; +using System.Numerics; +using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; @@ -7,7 +8,7 @@ namespace ComputeSharp.BokehBlur.Processors /// /// Applies bokeh blur processing to the image. /// - public sealed class HlslBokehBlurProcessor : IImageProcessor + public sealed partial class HlslBokehBlurProcessor : IImageProcessor { /// /// The default radius used by the parameterless constructor. @@ -63,5 +64,87 @@ namespace ComputeSharp.BokehBlur.Processors { return new HlslBokehBlurProcessor(this, configuration, source, sourceRectangle); } + + /// + /// Kernel for the vertical convolution pass. + /// + [AutoConstructor] + internal partial struct VerticalConvolutionProcessor : IComputeShader + { + public int width; + public int maxY; + public int maxX; + public int kernelLength; + + public ReadOnlyBuffer source; + public ReadWriteBuffer target; + public ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) + { + Vector4 real = Vector4.Zero; + Vector4 imaginary = Vector4.Zero; + int radiusY = kernelLength >> 1; + int sourceOffsetColumnBase = ids.X; + + for (int i = 0; i < kernelLength; i++) + { + int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); + int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); + Vector4 color = source[offsetY * width + offsetX]; + Complex64 factors = kernel[i]; + + real += factors.Real * color; + imaginary += factors.Imaginary * color; + } + + int offsetXY = ids.Y * width + ids.X; + + target[offsetXY].Real = real; + target[offsetXY].Imaginary = imaginary; + } + } + + /// + /// Kernel for the horizontal convolution pass. + /// + [AutoConstructor] + internal partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader + { + public int width; + public int maxY; + public int maxX; + public int kernelLength; + public float z; + public float w; + + public ReadWriteBuffer source; + public ReadWriteBuffer target; + public ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) + { + Vector4 real = Vector4.Zero; + Vector4 imaginary = Vector4.Zero; + int radiusX = kernelLength >> 1; + int sourceOffsetColumnBase = ids.X; + int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); + + for (int i = 0; i < kernelLength; i++) + { + int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); + var offsetXY = offsetY * width + offsetX; + ComplexVector4 source4 = source[offsetXY]; + Complex64 factors = kernel[i]; + + real += factors.Real * source4.Real - factors.Imaginary * source4.Imaginary; + imaginary += factors.Real * source4.Imaginary + factors.Imaginary * source4.Real; + } + + target[ids.Y * width + ids.X] += real * z + imaginary * w; + } + } } } diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs index f22b9abd..bbc41abb 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor{TPixel}.cs @@ -301,7 +301,7 @@ namespace ComputeSharp.BokehBlur.Processors int height = Source.Height; int width = Source.Width; - VerticalConvolutionProcessor shader = new( + HlslBokehBlurProcessor.VerticalConvolutionProcessor shader = new( width, maxY: height - 1, maxX: width - 1, @@ -313,47 +313,6 @@ namespace ComputeSharp.BokehBlur.Processors Gpu.Default.For(width, height, in shader); } - /// - /// Kernel for . - /// - [AutoConstructor] - private partial struct VerticalConvolutionProcessor : IComputeShader - { - public int width; - public int maxY; - public int maxX; - public int kernelLength; - - public ReadOnlyBuffer source; - public ReadWriteBuffer target; - public ReadOnlyBuffer kernel; - - /// - public void Execute(ThreadIds ids) - { - Vector4 real = Vector4.Zero; - Vector4 imaginary = Vector4.Zero; - int radiusY = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; - - for (int i = 0; i < kernelLength; i++) - { - int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); - Vector4 color = source[offsetY * width + offsetX]; - Complex64 factors = kernel[i]; - - real += factors.Real * color; - imaginary += factors.Imaginary * color; - } - - int offsetXY = ids.Y * width + ids.X; - - target[offsetXY].Real = real; - target[offsetXY].Imaginary = imaginary; - } - } - /// /// Performs an horizontal 1D complex convolution with the specified parameters. /// @@ -373,7 +332,7 @@ namespace ComputeSharp.BokehBlur.Processors int height = Source.Height; int width = Source.Width; - HorizontalConvolutionAndAccumulatePartialsProcessor shader = new( + HlslBokehBlurProcessor.HorizontalConvolutionAndAccumulatePartialsProcessor shader = new( width, maxY: height - 1, maxX: width - 1, @@ -387,47 +346,6 @@ namespace ComputeSharp.BokehBlur.Processors Gpu.Default.For(width, height, in shader); } - /// - /// Kernel for . - /// - [AutoConstructor] - private partial struct HorizontalConvolutionAndAccumulatePartialsProcessor : IComputeShader - { - public int width; - public int maxY; - public int maxX; - public int kernelLength; - public float z; - public float w; - - public ReadWriteBuffer source; - public ReadWriteBuffer target; - public ReadOnlyBuffer kernel; - - /// - public void Execute(ThreadIds ids) - { - Vector4 real = Vector4.Zero; - Vector4 imaginary = Vector4.Zero; - int radiusX = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; - int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); - - for (int i = 0; i < kernelLength; i++) - { - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); - var offsetXY = offsetY * width + offsetX; - ComplexVector4 source4 = source[offsetXY]; - Complex64 factors = kernel[i]; - - real += factors.Real * source4.Real - factors.Imaginary * source4.Imaginary; - imaginary += factors.Real * source4.Imaginary + factors.Imaginary * source4.Real; - } - - target[ids.Y * width + ids.X] += real * z + imaginary * w; - } - } - /// /// Applies the gamma correction/highlight to the input pixel buffer and returns an instance with values. /// diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs index f7aca904..b0d22c81 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor.cs @@ -1,4 +1,5 @@ -using SixLabors.ImageSharp; +using System.Numerics; +using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing.Processors; @@ -7,7 +8,7 @@ namespace ComputeSharp.BokehBlur.Processors /// /// Defines Gaussian blur by a (Sigma, Radius) pair. /// - public sealed class HlslGaussianBlurProcessor : IImageProcessor + public sealed partial class HlslGaussianBlurProcessor : IImageProcessor { /// /// The default value for . @@ -52,5 +53,79 @@ namespace ComputeSharp.BokehBlur.Processors { return new HlslGaussianBlurProcessor(this, configuration, source, sourceRectangle); } + + /// + /// Kernel for the vertical convolution pass. + /// + [AutoConstructor] + internal readonly partial struct VerticalConvolutionProcessor : IComputeShader + { + public readonly int width; + public readonly int maxY; + public readonly int maxX; + public readonly int kernelLength; + + public readonly ReadWriteBuffer source; + public readonly ReadWriteBuffer target; + public readonly ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) + { + Vector4 result = Vector4.Zero; + int radiusY = kernelLength >> 1; + int sourceOffsetColumnBase = ids.X; + + for (int i = 0; i < kernelLength; i++) + { + int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); + int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); + Vector4 color = source[offsetY * width + offsetX]; + + result += kernel[i] * color; + } + + int offsetXY = ids.Y * width + ids.X; + target[offsetXY] = result; + } + } + + /// + /// Kernel for the horizontal convolution pass. + /// + [AutoConstructor] + internal readonly partial struct HorizontalConvolutionProcessor : IComputeShader + { + public readonly int width; + public readonly int maxY; + public readonly int maxX; + public readonly int kernelLength; + + public readonly ReadWriteBuffer source; + public readonly ReadWriteBuffer target; + public readonly ReadOnlyBuffer kernel; + + /// + public void Execute(ThreadIds ids) + { + Vector4 result = Vector4.Zero; + int radiusX = kernelLength >> 1; + int sourceOffsetColumnBase = ids.X; + int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); + int offsetXY; + + for (int i = 0; i < kernelLength; i++) + { + int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); + offsetXY = offsetY * width + offsetX; + Vector4 color = source[offsetXY]; + + result += kernel[i] * color; + } + + offsetXY = ids.Y * width + ids.X; + target[offsetXY] = result; + } + } } } diff --git a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs index 31ca80cc..4ea8671c 100644 --- a/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs +++ b/samples/ComputeSharp.ImageProcessing/Processors/HlslGaussianBlurProcessor{TPixel}.cs @@ -13,7 +13,7 @@ namespace ComputeSharp.BokehBlur.Processors /// Applies Gaussian blur processing to an image. /// /// The pixel format. - internal class HlslGaussianBlurProcessor : ImageProcessor + internal sealed class HlslGaussianBlurProcessor : ImageProcessor where TPixel : unmanaged, IPixel { /// @@ -124,51 +124,16 @@ namespace ComputeSharp.BokehBlur.Processors int height = Source.Height; int width = Source.Width; - Gpu.Default.For(width, height, new VerticalConvolutionProcessor - { - width = width, - maxY = height - 1, - maxX = width - 1, - kernelLength = kernel.Length, - source = source, - target = target, - kernel = kernel - }); - } + HlslGaussianBlurProcessor.VerticalConvolutionProcessor shader = new( + width, + maxY: height - 1, + maxX: width - 1, + kernel.Length, + source, + target, + kernel); - /// - /// Kernel for . - /// - private struct VerticalConvolutionProcessor : IComputeShader - { - public int width; - public int maxY; - public int maxX; - public int kernelLength; - - public ReadWriteBuffer source; - public ReadWriteBuffer target; - public ReadOnlyBuffer kernel; - - /// - public void Execute(ThreadIds ids) - { - Vector4 result = Vector4.Zero; - int radiusY = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; - - for (int i = 0; i < kernelLength; i++) - { - int offsetY = Hlsl.Clamp(ids.Y + i - radiusY, 0, maxY); - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase, 0, maxX); - Vector4 color = source[offsetY * width + offsetX]; - - result += kernel[i] * color; - } - - int offsetXY = ids.Y * width + ids.X; - target[offsetXY] = result; - } + Gpu.Default.For(width, height, in shader); } /// @@ -186,53 +151,16 @@ namespace ComputeSharp.BokehBlur.Processors int height = Source.Height; int width = Source.Width; - Gpu.Default.For(width, height, new HorizontalConvolutionProcessor - { - width = width, - maxY = height - 1, - maxX = width - 1, - kernelLength = kernel.Length, - source = source, - target = target, - kernel = kernel - }); - } + HlslGaussianBlurProcessor.HorizontalConvolutionProcessor shader = new( + width, + maxY: height - 1, + maxX: width - 1, + kernel.Length, + source, + target, + kernel); - /// - /// Kernel for . - /// - private struct HorizontalConvolutionProcessor : IComputeShader - { - public int width; - public int maxY; - public int maxX; - public int kernelLength; - - public ReadWriteBuffer source; - public ReadWriteBuffer target; - public ReadOnlyBuffer kernel; - - /// - public void Execute(ThreadIds ids) - { - Vector4 result = Vector4.Zero; - int radiusX = kernelLength >> 1; - int sourceOffsetColumnBase = ids.X; - int offsetY = Hlsl.Clamp(ids.Y, 0, maxY); - int offsetXY; - - for (int i = 0; i < kernelLength; i++) - { - int offsetX = Hlsl.Clamp(sourceOffsetColumnBase + i - radiusX, 0, maxX); - offsetXY = offsetY * width + offsetX; - Vector4 color = source[offsetXY]; - - result += kernel[i] * color; - } - - offsetXY = ids.Y * width + ids.X; - target[offsetXY] = result; - } + Gpu.Default.For(width, height, in shader); } } } From c873762ef0089bedcf9a8e55b7741a1082d97a47 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 29 Dec 2020 00:36:13 +0100 Subject: [PATCH 14/16] Fixed benchmark sample --- samples/ComputeSharp.Benchmark/Dnn.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/samples/ComputeSharp.Benchmark/Dnn.cs b/samples/ComputeSharp.Benchmark/Dnn.cs index 8ab2cfaa..c6a3cc53 100644 --- a/samples/ComputeSharp.Benchmark/Dnn.cs +++ b/samples/ComputeSharp.Benchmark/Dnn.cs @@ -73,15 +73,15 @@ namespace ComputeSharp.Benchmark /// Kernel for . /// [AutoConstructor] - private readonly partial struct FullyConnectedForwardKernel : IComputeShader + public readonly partial struct FullyConnectedForwardKernel : IComputeShader { - private readonly int n; - private readonly int m; - private readonly int p; - private readonly ReadOnlyBuffer x; - private readonly ReadOnlyBuffer w; - private readonly ReadOnlyBuffer b; - private readonly ReadWriteBuffer y; + public readonly int n; + public readonly int m; + public readonly int p; + public readonly ReadOnlyBuffer x; + public readonly ReadOnlyBuffer w; + public readonly ReadOnlyBuffer b; + public readonly ReadWriteBuffer y; /// public void Execute(ThreadIds ids) From d06e8fd3edef6bc8ba909bbe9614e0a679e42837 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 29 Dec 2020 00:52:33 +0100 Subject: [PATCH 15/16] Minor code refactoring --- .../{ => __Internals}/IComputeShaderSourceAttribute.cs | 2 +- .../{ => __Internals}/ShaderMethodSourceAttribute.cs | 2 +- .../Helpers/__Internals/GraphicsResourceHelper.cs | 8 +++++++- .../ComputeSharp.SourceGenerators.csproj | 6 +++--- .../IComputeShaderDataLoaderGenerator.cs | 4 ++-- .../IComputeShaderHashCodeGenerator.cs | 4 ++-- 6 files changed, 16 insertions(+), 10 deletions(-) rename src/ComputeSharp.Core/Attributes/{ => __Internals}/IComputeShaderSourceAttribute.cs (97%) rename src/ComputeSharp.Core/Attributes/{ => __Internals}/ShaderMethodSourceAttribute.cs (98%) diff --git a/src/ComputeSharp.Core/Attributes/IComputeShaderSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs similarity index 97% rename from src/ComputeSharp.Core/Attributes/IComputeShaderSourceAttribute.cs rename to src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs index fb77a534..163d3d5d 100644 --- a/src/ComputeSharp.Core/Attributes/IComputeShaderSourceAttribute.cs +++ b/src/ComputeSharp.Core/Attributes/__Internals/IComputeShaderSourceAttribute.cs @@ -13,7 +13,7 @@ namespace ComputeSharp.__Internals /// This attribute is not meant to be directly used by applications using ComputeSharp. [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This attribute is meant to be used from the source generator only")] + [Obsolete("This attribute is not intended to be used directly by user code")] public sealed class IComputeShaderSourceAttribute : Attribute { /// diff --git a/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs b/src/ComputeSharp.Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs similarity index 98% rename from src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs rename to src/ComputeSharp.Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs index 094c43ab..195ea4d2 100644 --- a/src/ComputeSharp.Core/Attributes/ShaderMethodSourceAttribute.cs +++ b/src/ComputeSharp.Core/Attributes/__Internals/ShaderMethodSourceAttribute.cs @@ -15,7 +15,7 @@ namespace ComputeSharp.__Internals /// This attribute is not meant to be directly used by applications using ComputeSharp. [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This attribute is meant to be used from the source generator only")] + [Obsolete("This attribute is not intended to be used directly by user code")] public sealed class ShaderMethodSourceAttribute : Attribute { /// diff --git a/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs b/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs index 9d364b20..cf210dd2 100644 --- a/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs +++ b/src/ComputeSharp.Graphics/Helpers/__Internals/GraphicsResourceHelper.cs @@ -11,7 +11,7 @@ namespace ComputeSharp.__Internals /// A helper class with some proxy methods to expose to generated code in external projects. /// [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("This type is meant to be used from the source generator only")] + [Obsolete("This type is not intended to be used directly by user code")] public static class GraphicsResourceHelper { /// @@ -19,6 +19,8 @@ namespace ComputeSharp.__Internals /// /// The input instance to check. /// The target instance in use. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong ValidateAndGetGpuDescriptorHandle(Buffer buffer, GraphicsDevice device) where T : unmanaged @@ -34,6 +36,8 @@ namespace ComputeSharp.__Internals /// /// The input instance to check. /// The target instance in use. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong ValidateAndGetGpuDescriptorHandle(Texture2D buffer, GraphicsDevice device) where T : unmanaged @@ -49,6 +53,8 @@ namespace ComputeSharp.__Internals /// /// The input instance to check. /// The target instance in use. + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be called directly by user code")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong ValidateAndGetGpuDescriptorHandle(Texture3D buffer, GraphicsDevice device) where T : unmanaged diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 566c816a..04f729f7 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -1,4 +1,4 @@ - + netstandard2.0 @@ -15,9 +15,9 @@ and to match members based on full name, so the types being in the generator assembly are not an issue.--> - - + + diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs index 72af86c8..66bcaf40 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs @@ -53,7 +53,7 @@ namespace ComputeSharp.SourceGenerators // internal static partial class DispatchDataLoader // { // [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)] - // [System.Obsolete("This method is intended for internal usage only")] + // [System.Obsolete("This method is not intended to be called directly by user code")] // public static int LoadDispatchData(GraphicsDevice device, in ShaderType shader, ref ulong r0, ref byte r1) // { // ... @@ -80,7 +80,7 @@ namespace ComputeSharp.SourceGenerators Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( AttributeArgument(LiteralExpression( SyntaxKind.StringLiteralExpression, - Literal("This method is intended for internal usage only"))))))).AddModifiers( + Literal("This method is not intended to be called directly by user code"))))))).AddModifiers( Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword)).AddParameterListParameters( Parameter(Identifier("device")).WithType(IdentifierName("ComputeSharp.Graphics.GraphicsDevice")), diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs index 2632d94f..654e3f7f 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs @@ -53,7 +53,7 @@ namespace ComputeSharp.SourceGenerators // internal static partial class HashCodeProvider // { // [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)] - // [System.Obsolete("This method is intended for internal usage only")] + // [System.Obsolete("This method is not intended to be called directly by user code")] // public static int CombineHashCode(int hash, in ShaderType shader) // { // return ...; @@ -79,7 +79,7 @@ namespace ComputeSharp.SourceGenerators Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( AttributeArgument(LiteralExpression( SyntaxKind.StringLiteralExpression, - Literal("This method is intended for internal usage only"))))))).AddModifiers( + Literal("This method is not intended to be called directly by user code"))))))).AddModifiers( Token(SyntaxKind.PublicKeyword), Token(SyntaxKind.StaticKeyword)).AddParameterListParameters( Parameter(Identifier("hash")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), From 4e39eb0ab8afb0c0b8eb00d338530b5e714a74bf Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 29 Dec 2020 01:11:39 +0100 Subject: [PATCH 16/16] Added attributes to generated classes --- .../IComputeShaderDataLoaderGenerator.cs | 24 ++++++++++++++++--- .../IComputeShaderHashCodeGenerator.cs | 21 ++++++++++++++-- 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs index 66bcaf40..bc1b3312 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderDataLoaderGenerator.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; @@ -31,6 +32,19 @@ namespace ComputeSharp.SourceGenerators from structDeclaration in tree.GetRoot().DescendantNodes().OfType() select structDeclaration).ToImmutableArray(); + // Type attributes + AttributeListSyntax[] attributes = new[] + { + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( + AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( + AttributeArgument(LiteralExpression( + SyntaxKind.StringLiteralExpression, + Literal("This type is not intended to be used directly by user code")))))) + }; + foreach (StructDeclarationSyntax structDeclaration in structDeclarations) { SemanticModel semanticModel = context.Compilation.GetSemanticModel(structDeclaration.SyntaxTree); @@ -69,7 +83,7 @@ namespace ComputeSharp.SourceGenerators ClassDeclaration("DispatchDataLoader").AddModifiers( Token(SyntaxKind.InternalKeyword), Token(SyntaxKind.StaticKeyword), - Token(SyntaxKind.PartialKeyword)).AddMembers( + Token(SyntaxKind.PartialKeyword)).AddAttributeLists(attributes).AddMembers( MethodDeclaration( PredefinedType(Token(SyntaxKind.IntKeyword)), Identifier("LoadDispatchData")).AddAttributeLists( @@ -87,10 +101,14 @@ namespace ComputeSharp.SourceGenerators Parameter(Identifier("shader")).WithModifiers(TokenList(Token(SyntaxKind.InKeyword))).WithType(shaderType), Parameter(Identifier("r0")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ULongKeyword))), Parameter(Identifier("r1")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .WithBody(block)))) + .WithBody(block))) + .WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList()))) .NormalizeWhitespace() .ToFullString(); + // Clear the attribute list to avoid duplicates + attributes = Array.Empty(); + // Add the method source attribute context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); } diff --git a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs index 654e3f7f..ae194820 100644 --- a/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IComputeShaderHashCodeGenerator.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; @@ -29,6 +30,19 @@ namespace ComputeSharp.SourceGenerators from structDeclaration in tree.GetRoot().DescendantNodes().OfType() select structDeclaration).ToImmutableArray(); + // Type attributes + AttributeListSyntax[] attributes = new[] + { + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("EditorBrowsable")).AddArgumentListArguments( + AttributeArgument(ParseExpression("EditorBrowsableState.Never"))))), + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("Obsolete")).AddArgumentListArguments( + AttributeArgument(LiteralExpression( + SyntaxKind.StringLiteralExpression, + Literal("This type is not intended to be used directly by user code")))))) + }; + foreach (StructDeclarationSyntax structDeclaration in structDeclarations) { SemanticModel semanticModel = context.Compilation.GetSemanticModel(structDeclaration.SyntaxTree); @@ -68,7 +82,7 @@ namespace ComputeSharp.SourceGenerators ClassDeclaration("HashCodeProvider").AddModifiers( Token(SyntaxKind.InternalKeyword), Token(SyntaxKind.StaticKeyword), - Token(SyntaxKind.PartialKeyword)).AddMembers( + Token(SyntaxKind.PartialKeyword)).AddAttributeLists(attributes).AddMembers( MethodDeclaration( PredefinedType(Token(SyntaxKind.IntKeyword)), Identifier("CombineHash")).AddAttributeLists( @@ -88,6 +102,9 @@ namespace ComputeSharp.SourceGenerators .NormalizeWhitespace() .ToFullString(); + // Clear the attribute list to avoid duplicates + attributes = Array.Empty(); + // Add the method source attribute context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8)); }