From b17b7c70feee2c7aa4f1609e0d0b487a52811380 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 23 Sep 2023 15:49:45 +0200 Subject: [PATCH] Generate resource texture descriptions as ReadOnlyMemory --- .../ComputeSharp.D2D1.SourceGenerators.csproj | 1 + ....CreateInputDescriptionsProperty.Syntax.cs | 7 +- ...esourceTextureDescriptionsMethod.Syntax.cs | 193 +++++++++--------- ...teLoadResourceTextureDescriptionsMethod.cs | 2 +- .../ID2D1ShaderGenerator.cs | 6 +- .../Models/ResourceTextureDescription.cs | 2 +- .../Interfaces/__Internals/ID2D1Shader.cs | 7 + .../Interop/D2D1ResourceTextureDescription.cs | 11 + .../D2D1PixelShaderTests.cs | 16 +- 9 files changed, 128 insertions(+), 117 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj index 67129912..10b3bff1 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj @@ -86,6 +86,7 @@ + diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs index 08312b7a..53127aed 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateInputDescriptionsProperty.Syntax.cs @@ -46,10 +46,7 @@ partial class ID2D1ShaderGenerator // This code produces a method declaration as follows: // - // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadInputDescriptions(ref TLoader loader) - // { - // - // } + // readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.InputDescriptions => ; return PropertyDeclaration( GenericName(Identifier("global::System.ReadOnlyMemory")) @@ -110,7 +107,7 @@ partial class ID2D1ShaderGenerator // Declare the singleton property to get the memory instance: // - // /// The singleton instance for the memory manager. + // /// The singleton array instance. // public static readonly global::ComputeSharp.D2D1.Interop.D2D1InputDescription[] InputDescriptions = { }; FieldDeclarationSyntax fieldDeclaration = FieldDeclaration( diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.Syntax.cs index 805f7726..a0aff034 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.Syntax.cs @@ -1,7 +1,8 @@ -using System.Collections.Immutable; +using System; using ComputeSharp.D2D1.__Internals; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Helpers; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; @@ -17,124 +18,118 @@ partial class ID2D1ShaderGenerator private static partial class LoadResourceTextureDescriptions { /// - /// Creates a instance for the LoadResourceTextureDescriptions method. + /// Creates a instance for the ResourceTextureDescriptions property. /// /// The resource texture descriptions info gathered for the current shader. - /// The resulting instance for the LoadResourceTextureDescriptions method. - public static MethodDeclarationSyntax GetSyntax(ResourceTextureDescriptionsInfo resourceTextureDescriptionsInfo) + /// Any additional instances needed by the generated code, if needed. + /// The resulting instance for the ResourceTextureDescriptions property. + public static PropertyDeclarationSyntax GetSyntax(ResourceTextureDescriptionsInfo resourceTextureDescriptionsInfo, out TypeDeclarationSyntax[] additionalTypes) { + ExpressionSyntax memoryExpression; + + // If there are no resource texture descriptions, just return a default expression. + // Otherwise, declare the shared array and return it from the property. + if (resourceTextureDescriptionsInfo.ResourceTextureDescriptions.Length == 0) + { + memoryExpression = LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)); + additionalTypes = Array.Empty(); + } + else + { + memoryExpression = MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("Data"), + IdentifierName("ResourceTextureDescriptions")); + + additionalTypes = new[] { GetArrayDeclaration(resourceTextureDescriptionsInfo) }; + } + // This code produces a method declaration as follows: // - // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadResourceTextureDescriptions(ref TLoader loader) - // { - // - // } + // readonly global::System.ReadOnlyMemory global::ComputeSharp.D2D1.__Internals.ID2D1Shader.ResourceTextureDescriptions => ; return - MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier(nameof(LoadResourceTextureDescriptions))) + PropertyDeclaration( + GenericName(Identifier("global::System.ReadOnlyMemory")) + .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription")), + Identifier("ResourceTextureDescriptions")) .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1.__Internals.{nameof(ID2D1Shader)}"))) .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .AddTypeParameterListParameters(TypeParameter(Identifier("TLoader"))) - .AddParameterListParameters(Parameter(Identifier("loader")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("TLoader"))) - .WithBody(Block(GetInputDescriptionsLoadingStatements(resourceTextureDescriptionsInfo.ResourceTextureDescriptions))); + .WithExpressionBody(ArrowExpressionClause(memoryExpression)) + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)); } /// - /// Gets a sequence of statements to load the resource texture descriptions for a given shader. + /// Gets the array declaration for the given resource texture descriptions. /// - /// The array of values for all available resource texture descriptions. - /// The sequence of instances to load the resource texture descriptions data. - private static ImmutableArray GetInputDescriptionsLoadingStatements(ImmutableArray resourceTextureDescriptionsInfo) + /// The resource texture descriptions info gathered for the current shader. + /// The array declaration for the given resource texture descriptions. + private static TypeDeclarationSyntax GetArrayDeclaration(ResourceTextureDescriptionsInfo resourceTextureDescriptionsInfo) { - // If there are no resource texture descriptions available, just load an empty buffer - if (resourceTextureDescriptionsInfo.IsEmpty) + using ImmutableArrayBuilder resourceTextureDescriptionExpressions = ImmutableArrayBuilder.Rent(); + + foreach (ResourceTextureDescription resourceTextureDescription in resourceTextureDescriptionsInfo.ResourceTextureDescriptions) { - // loader.LoadResourceTextureDescriptions(default); - return - ImmutableArray.Create( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("loader"), - IdentifierName("LoadResourceTextureDescriptions"))) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.DefaultLiteralExpression, - Token(SyntaxKind.DefaultKeyword)))))); + // Create the description expression: + // + // new(, ) + resourceTextureDescriptionExpressions.Add( + ImplicitObjectCreationExpression() + .AddArgumentListArguments( + Argument(LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(resourceTextureDescription.Index))), + Argument(LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(resourceTextureDescription.Rank))))); } - using ImmutableArrayBuilder statements = ImmutableArrayBuilder.Rent(); - - // The size of the buffer with the resource texture descriptions is the number of resurce textures descriptions, - // times the size of each input description, which is a struct containing two int-sized fields (index and rank). - int resourceTextureDescriptionSizeInBytes = resourceTextureDescriptionsInfo.Length * sizeof(int) * 2; - - // global::System.Span data = stackalloc byte[]; - statements.Add( - LocalDeclarationStatement( + // Declare the singleton property to get the memory instance: + // + // /// The singleton array instance. + // public static readonly global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription[] ResourceTextureDescriptions = { }; + FieldDeclarationSyntax fieldDeclaration = + FieldDeclaration( VariableDeclaration( - GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + ArrayType(IdentifierName("global::ComputeSharp.D2D1.Interop.D2D1ResourceTextureDescription")) + .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) .AddVariables( - VariableDeclarator(Identifier("data")) + VariableDeclarator(Identifier("ResourceTextureDescriptions")) .WithInitializer(EqualsValueClause( - StackAllocArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) - .AddRankSpecifiers( - ArrayRankSpecifier(SingletonSeparatedList( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceTextureDescriptionSizeInBytes))))))))))); + InitializerExpression(SyntaxKind.ArrayInitializerExpression) + .AddExpressions(resourceTextureDescriptionExpressions.ToArray()))))) + .AddModifiers( + Token(SyntaxKind.PublicKeyword), + Token(SyntaxKind.StaticKeyword), + Token(SyntaxKind.ReadOnlyKeyword)) + .WithLeadingTrivia(Comment("""/// The singleton array instance.""")); - // ref byte r0 = ref data[0]; - statements.Add( - LocalDeclarationStatement( - VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("r0")) - .WithInitializer(EqualsValueClause( - RefExpression( - ElementAccessExpression(IdentifierName("data")) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))))))))); - - int offset = 0; - - // Generate loading statements for each resource texture description - foreach (ResourceTextureDescription resourceTextureDescription in resourceTextureDescriptionsInfo) - { - // Write the index of the current resource texture description: - // - // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint))) = ; - statements.Add(ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){offset}))"), - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal((int)resourceTextureDescription.Index))))); - - // Write the rank of the current resource texture description: - // - // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint) + 4)) = ; - statements.Add(ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){offset + 4}))"), - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal((int)resourceTextureDescription.Rank))))); - - offset += sizeof(int) * 2; - } - - // loader.LoadInputDescriptions(data); - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("loader"), - IdentifierName("LoadResourceTextureDescriptions"))) - .AddArgumentListArguments(Argument(IdentifierName("data"))))); - - return statements.ToImmutable(); + // Create the container type declaration: + // + // /// + // /// A container type for input descriptions. + // /// + // [global::System.CodeDom.Compiler.GeneratedCode("...", "...")] + // [global::System.Diagnostics.DebuggerNonUserCode] + // [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + // file static class Data + // { + // + // } + return + ClassDeclaration("Data") + .AddModifiers(Token(SyntaxKind.FileKeyword), Token(SyntaxKind.StaticKeyword)) + .AddAttributeLists( + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments( + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).FullName))), + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(ID2D1ShaderGenerator).Assembly.GetName().Version.ToString())))))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage"))))) + .AddMembers(fieldDeclaration) + .WithLeadingTrivia( + Comment("/// "), + Comment("/// A container type for resource texture descriptions."), + Comment("/// ")); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs index 726f08b4..f5514c82 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadResourceTextureDescriptionsMethod.cs @@ -76,7 +76,7 @@ partial class ID2D1ShaderGenerator { foreach ((int? index, int rank) in resourceTextureInfos.WrittenSpan) { - resourceTextureDescriptionsBuilder.Add(new ResourceTextureDescription((uint)(index ?? 0), (uint)rank)); + resourceTextureDescriptionsBuilder.Add(new ResourceTextureDescription(index ?? 0, rank)); } resourceTextureDescriptions = resourceTextureDescriptionsBuilder.ToImmutable(); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index 93f432e5..27e7c015 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -265,7 +265,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator // Generate the InputTypes properties context.RegisterSourceOutput(inputTypesInfo, static (context, item) => { - MemberDeclarationSyntax inputTypesProperty = InputTypes.GetSyntax(item.InputTypes.InputTypes, out TypeDeclarationSyntax[] additionalTypes); + PropertyDeclarationSyntax inputTypesProperty = InputTypes.GetSyntax(item.InputTypes.InputTypes, out TypeDeclarationSyntax[] additionalTypes); CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, inputTypesProperty, canUseSkipLocalsInit: false, additionalMemberDeclarations: additionalTypes); context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(InputTypes)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); @@ -279,8 +279,8 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator // Generate the LoadResourceTextureDescriptions() methods context.RegisterSourceOutput(resourceTextureDescriptionsInfo, static (context, item) => { - MethodDeclarationSyntax getInputTypeMethod = LoadResourceTextureDescriptions.GetSyntax(item.ResourceTextureDescriptions); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, getInputTypeMethod, canUseSkipLocalsInit: false); + PropertyDeclarationSyntax resourceTextureDescriptionsProperty = LoadResourceTextureDescriptions.GetSyntax(item.ResourceTextureDescriptions, out TypeDeclarationSyntax[] additionalTypes); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMember(item.Hierarchy, resourceTextureDescriptionsProperty, canUseSkipLocalsInit: false, additionalMemberDeclarations: additionalTypes); context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadResourceTextureDescriptions)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); }); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescription.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescription.cs index 65eee9b3..c14ed920 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescription.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/ResourceTextureDescription.cs @@ -5,4 +5,4 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models; /// /// The index of the resource texture resource the description is for. /// The rank of the resource texture. -internal sealed record ResourceTextureDescription(uint Index, uint Rank); \ No newline at end of file +internal sealed record ResourceTextureDescription(int Index, int Rank); \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs index f5ca18f5..1a3b6d8d 100644 --- a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs +++ b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs @@ -91,6 +91,13 @@ public interface ID2D1Shader [Obsolete("This method is not intended to be used directly by user code")] ReadOnlyMemory InputDescriptions { get; } + /// + /// Gets the resource texture descriptions for the shader. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + [Obsolete("This method is not intended to be used directly by user code")] + ReadOnlyMemory ResourceTextureDescriptions { get; } + /// /// Loads the resource texture descriptions for the shader, if any. /// diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureDescription.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureDescription.cs index f842ec65..ce924f0a 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureDescription.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ResourceTextureDescription.cs @@ -19,6 +19,17 @@ public readonly struct D2D1ResourceTextureDescription /// private readonly int dimensions; + /// + /// Creates a new instance with the specified parameters. + /// + /// The index of the resource texture the description belongs to. + /// The number of dimensions of the resource texture the description belongs to. + public D2D1ResourceTextureDescription(int index, int dimensions) + { + this.index = index; + this.dimensions = dimensions; + } + /// /// Gets the index of the resource texture the description belongs to. /// diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs index 815651b5..689e3890 100644 --- a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs @@ -222,16 +222,16 @@ public partial class D2D1PixelShaderTests ReadOnlySpan span = resourceTextureDescriptions.Span; - Assert.AreEqual(span[0].Index, 5); + Assert.AreEqual(span[0].Index, 4); Assert.AreEqual(span[0].Dimensions, 1); - Assert.AreEqual(span[1].Index, 6); + Assert.AreEqual(span[1].Index, 5); Assert.AreEqual(span[1].Dimensions, 2); - Assert.AreEqual(span[2].Index, 7); + Assert.AreEqual(span[2].Index, 6); Assert.AreEqual(span[2].Dimensions, 3); - Assert.AreEqual(span[3].Index, 8); + Assert.AreEqual(span[3].Index, 7); Assert.AreEqual(span[3].Dimensions, 2); } @@ -246,16 +246,16 @@ public partial class D2D1PixelShaderTests { float number; - [D2DResourceTextureIndex(5)] + [D2DResourceTextureIndex(4)] D2D1ResourceTexture1D myTexture1; - [D2DResourceTextureIndex(6)] + [D2DResourceTextureIndex(5)] D2D1ResourceTexture2D myTexture2; - [D2DResourceTextureIndex(7)] + [D2DResourceTextureIndex(6)] D2D1ResourceTexture3D myTexture3; - [D2DResourceTextureIndex(8)] + [D2DResourceTextureIndex(7)] D2D1ResourceTexture2D myTexture4; public Float4 Execute()