From 3b760f02d45017c4cfb021f9fe371b3d7fb226be Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 8 May 2022 15:39:40 +0200 Subject: [PATCH] Enable generation for ID2D1Shader.LoadInputDescriptions API --- .../AnalyzerReleases.Shipped.md | 2 + .../ComputeSharp.D2D1.SourceGenerators.csproj | 1 + .../Diagnostics/DiagnosticDescriptors.cs | 32 ++++ ...haderGenerator.CreateGetInputTypeMethod.cs | 2 +- ...reateLoadInputDescriptionsMethod.Syntax.cs | 148 ++++++++++++++++++ ...rator.CreateLoadInputDescriptionsMethod.cs | 90 +++++++++++ .../ID2D1ShaderGenerator.cs | 36 +++++ .../Models/InputDescription.cs | 9 ++ .../Models/InputDescriptionsInfo.cs | 31 ++++ .../ComputeSharp.SourceGeneration.projitems | 1 + .../Extensions/AttributeDataExtensions.cs | 35 +++++ 11 files changed, 386 insertions(+), 1 deletion(-) create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescription.cs create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescriptionsInfo.cs create mode 100644 src/ComputeSharp.SourceGeneration/Extensions/AttributeDataExtensions.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md index 6cbb9ede..89d1c79e 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.D2D1.SourceGenerators/AnalyzerReleases.Shipped.md @@ -48,3 +48,5 @@ CMPSD2D0038 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github CMPSD2D0039 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0040 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) CMPSD2D0041 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0042 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) +CMPSD2D0043 | ComputeSharp.D2D1.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj index 2716303d..878c9c54 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj @@ -67,6 +67,7 @@ + diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 1ad3ab02..9a54a56e 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -586,4 +586,36 @@ internal static class DiagnosticDescriptors isEnabledByDefault: true, description: "D2D1 shaders can only use supported types (some .NET primitives and vector types, HLSL primitive, vector and matrix types, and custom types containing these types can be used).", helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for a shader with an out of range input description index (or more). + /// + /// Format: "The D2D1 shader of type {0} is using some out of range input description indices". + /// + /// + public static readonly DiagnosticDescriptor OutOfRangeInputDescriptionIndex = new DiagnosticDescriptor( + id: "CMPSD2D0042", + title: "Our of range D2D1 shader input description indices", + messageFormat: "The D2D1 shader of type {0} is using some out of range input description indices", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A D2D1 shader must have all the indices of its input descriptions in the valid range (between 0 and the number of declared inputs).", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); + + /// + /// Gets a for repeated indices for D2D input descriptions. + /// + /// Format: "The D2D1 shader of type {0} is using repeated indices for some of its [D2DInputDescription] attributes". + /// + /// + public static readonly DiagnosticDescriptor RepeatedD2DInputDescriptionIndices = new DiagnosticDescriptor( + id: "CMPSD2D0043", + title: "Repeated D2D1 shader input description indices", + messageFormat: "The D2D1 shader of type {0} is using repeated indices for some of its [D2DInputDescription] attributes", + category: "ComputeSharp.D2D1.Shaders", + defaultSeverity: DiagnosticSeverity.Error, + isEnabledByDefault: true, + description: "A D2D1 shader must only have unique indices for all of its [D2DInputDescription] attributes.", + helpLinkUri: "https://github.com/Sergio0694/ComputeSharp"); } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs index f4798fdf..5c45d3a8 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateGetInputTypeMethod.cs @@ -19,12 +19,12 @@ partial class ID2D1ShaderGenerator /// /// Extracts the input info for the current shader. /// - /// The collection of produced instances. /// The input instance to process. /// The number of shader inputs to declare. /// The indicess of the simple shader inputs. /// The indices of the complex shader inputs. /// The combined and serialized input types for each available input. + /// The collection of produced instances. public static void GetInfo( INamedTypeSymbol structDeclarationSymbol, out int inputCount, diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs new file mode 100644 index 00000000..8d4ae132 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.Syntax.cs @@ -0,0 +1,148 @@ +using System.Collections.Immutable; +using ComputeSharp.D2D1.__Internals; +using ComputeSharp.D2D1.SourceGenerators.Models; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +#pragma warning disable CS0618 + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + private static partial class LoadInputDescriptions + { + /// + /// Creates a instance for the LoadInputDescriptions method. + /// + /// The input descriptions info gathered for the current shader. + /// The resulting instance for the LoadInputDescriptions method. + public static MethodDeclarationSyntax GetSyntax(InputDescriptionsInfo inputDescriptionsInfo) + { + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadInputDescriptions(ref TLoader loader) + // { + // + // } + return + MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier(nameof(LoadInputDescriptions))) + .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(inputDescriptionsInfo.InputDescriptions))); + } + + /// + /// Gets a sequence of statements to load the input descriptions for a given shader. + /// + /// The array of values for all available input descriptions. + /// The sequence of instances to load shader dispatch data. + private static ImmutableArray GetInputDescriptionsLoadingStatements(ImmutableArray inputDescriptions) + { + // If there are no input descriptions available, just load an empty buffer + if (inputDescriptions.IsEmpty) + { + // loader.LoadInputDescriptions(default); + return + ImmutableArray.Create( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("loader"), + IdentifierName("LoadInputDescriptions"))) + .AddArgumentListArguments(Argument( + LiteralExpression( + SyntaxKind.DefaultLiteralExpression, + Token(SyntaxKind.DefaultKeyword)))))); + } + + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + + // The size of the buffer with the input descriptions is the number of input descriptions, times the size of each + // input description, which is a struct containing three int-sized fields (index, filter, and level of detail). + int inputDescriptionSizeInBytes = inputDescriptions.Length * sizeof(int) * 3; + + // global::System.Span data = stackalloc byte[]; + statements.Insert(0, + LocalDeclarationStatement( + VariableDeclaration( + GenericName(Identifier("global::System.Span")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) + .AddVariables( + VariableDeclarator(Identifier("data")) + .WithInitializer(EqualsValueClause( + StackAllocArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) + .AddRankSpecifiers( + ArrayRankSpecifier(SingletonSeparatedList( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(inputDescriptionSizeInBytes))))))))))); + + // ref byte r0 = ref data[0]; + statements.Insert(1, + 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 input description + foreach (InputDescription inputDescription in inputDescriptions) + { + // Write the index of the current input 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)inputDescription.Index))))); + + // Write the filter of the current input 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)inputDescription.Filter))))); + + // Write the level of detail of the current input description: + // + // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint) + 8)) = ; + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){offset + 8}))"), + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal((int)inputDescription.LevelOfDetail))))); + + offset += sizeof(int) * 3; + } + + // loader.LoadInputDescriptions(data); + statements.Add( + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("loader"), + IdentifierName("LoadInputDescriptions"))) + .AddArgumentListArguments(Argument(IdentifierName("data"))))); + + return statements.ToImmutable(); + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs new file mode 100644 index 00000000..44f3fc46 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadInputDescriptionsMethod.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; +using Microsoft.CodeAnalysis; +using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class ID2D1ShaderGenerator +{ + /// + /// A helper with all logic to generate the LoadInputDescriptions method. + /// + private static partial class LoadInputDescriptions + { + /// + /// Extracts the input descriptions for the current shader. + /// + /// The input instance to process. + /// The produced input descriptions for the shader. + /// The collection of produced instances. + public static void GetInfo( + INamedTypeSymbol structDeclarationSymbol, + out ImmutableArray inputDescriptions, + out ImmutableArray diagnostics) + { + int inputCount = 0; + ImmutableArray.Builder inputDescriptionsBuilder = ImmutableArray.CreateBuilder(); + ImmutableArray.Builder diagnosticsBuilder = ImmutableArray.CreateBuilder(); + + foreach (AttributeData attributeData in structDeclarationSymbol.GetAttributes()) + { + switch (attributeData.AttributeClass?.GetFullMetadataName()) + { + case "ComputeSharp.D2D1.D2DInputCountAttribute": + inputCount = (int)attributeData.ConstructorArguments[0].Value!; + break; + case "ComputeSharp.D2D1.D2DInputDescriptionAttribute": + if (attributeData.ConstructorArguments.Length == 2) + { + int index = (int)attributeData.ConstructorArguments[0].Value!; + D2D1Filter filter = (D2D1Filter)attributeData.ConstructorArguments[1].Value!; + + _ = attributeData.TryGetNamedArgument("LevelOfDetail", out int levelOfDetail); + + inputDescriptionsBuilder.Add(new InputDescription((uint)index, filter, levelOfDetail)); + } + break; + default: + break; + } + } + + inputDescriptions = ImmutableArray.Empty; + + // Validate the input count (ignore if invalid, this will be validated by the HLSL source generator) + if (inputCount is not (>= 0 and <= 8)) + { + goto End; + } + + // All simple indices must be in range + if (inputDescriptionsBuilder.Any(description => description.Index >= inputCount)) + { + diagnosticsBuilder.Add(OutOfRangeInputDescriptionIndex, structDeclarationSymbol, structDeclarationSymbol); + + goto End; + } + + HashSet inputDescriptionIndices = new(inputDescriptionsBuilder.Select(description => description.Index)); + + // All input description indices must be unique + if (inputDescriptionIndices.Count != inputDescriptionsBuilder.Count) + { + diagnosticsBuilder.Add(RepeatedD2DInputDescriptionIndices, structDeclarationSymbol, structDeclarationSymbol); + + goto End; + } + + inputDescriptions = inputDescriptionsBuilder.ToImmutable(); + + End: + diagnostics = diagnosticsBuilder.ToImmutable(); + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index a972cbf5..b3314ae2 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -269,5 +269,41 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(GetOutputBuffer)}", compilationUnit.ToFullString()); }); + + // Get the input description data, which can also be computed separately from all other generation steps. + IncrementalValuesProvider<(HierarchyInfo Hierarchy, Result Info)> inputDescriptionsInfoWithErrors = + shaderDeclarations + .Select(static (item, token) => + { + // LoadInputDescriptions() info + LoadInputDescriptions.GetInfo( + item.Symbol, + out ImmutableArray inputDescriptions, + out ImmutableArray diagnostics); + + token.ThrowIfCancellationRequested(); + + InputDescriptionsInfo inputDescriptionsInfo = new(inputDescriptions); + + return (item.Hierarchy, new Result(inputDescriptionsInfo, diagnostics)); + }); + + // Output the diagnostics + context.ReportDiagnostics(inputDescriptionsInfoWithErrors.Select(static (item, token) => item.Info.Errors)); + + // Get the filtered sequence to enable caching + IncrementalValuesProvider<(HierarchyInfo Hierarchy, InputDescriptionsInfo Info)> inputDescriptionsInfo = + inputDescriptionsInfoWithErrors + .Select(static (item, token) => (item.Hierarchy, item.Info.Value)) + .WithComparers(HierarchyInfo.Comparer.Default, InputDescriptionsInfo.Comparer.Default); + + // Generate the LoadInputDescriptions() methods + context.RegisterSourceOutput(inputDescriptionsInfo.Combine(canUseSkipLocalsInit), static (context, item) => + { + MethodDeclarationSyntax loadInputDescriptionsMethod = LoadInputDescriptions.GetSyntax(item.Left.Info); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, loadInputDescriptionsMethod, item.Right); + + context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadInputDescriptions)}", compilationUnit.ToFullString()); + }); } } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescription.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescription.cs new file mode 100644 index 00000000..29d20cc9 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescription.cs @@ -0,0 +1,9 @@ +namespace ComputeSharp.D2D1.SourceGenerators.Models; + +/// +/// A model representing an input description for a shader. +/// +/// The index of the input resource the description if for. +/// The input filter to use. +/// The level of detail to use. +internal sealed record InputDescription(uint Index, D2D1Filter Filter, int LevelOfDetail); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescriptionsInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescriptionsInfo.cs new file mode 100644 index 00000000..3ac7001b --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/InputDescriptionsInfo.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; + +namespace ComputeSharp.D2D1.SourceGenerators.Models; + +/// +/// A model representing gathered input descriptions for a shader. +/// +/// The input types for a given shader. +internal sealed record InputDescriptionsInfo(ImmutableArray InputDescriptions) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : Comparer + { + /// + protected override void AddToHashCode(ref HashCode hashCode, InputDescriptionsInfo obj) + { + hashCode.AddRange(obj.InputDescriptions); + } + + /// + protected override bool AreEqual(InputDescriptionsInfo x, InputDescriptionsInfo y) + { + return x.InputDescriptions.SequenceEqual(y.InputDescriptions); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems index 30b2bcf1..948079f9 100644 --- a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems +++ b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems @@ -9,6 +9,7 @@ ComputeSharp.SourceGeneration + diff --git a/src/ComputeSharp.SourceGeneration/Extensions/AttributeDataExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/AttributeDataExtensions.cs new file mode 100644 index 00000000..37436b1c --- /dev/null +++ b/src/ComputeSharp.SourceGeneration/Extensions/AttributeDataExtensions.cs @@ -0,0 +1,35 @@ +using System.Collections.Generic; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.SourceGeneration.Extensions; + +/// +/// Extension methods for the type. +/// +internal static class AttributeDataExtensions +{ + /// + /// Tries to get a given named argument value from an instance, if present. + /// + /// The type of argument to check. + /// The target instance to check. + /// The name of the argument to check. + /// The resulting argument value, if present. + /// Whether or not contains an argument named with a valid value. + public static bool TryGetNamedArgument(this AttributeData attributeData, string name, out T? value) + { + foreach (KeyValuePair properties in attributeData.NamedArguments) + { + if (properties.Key == name) + { + value = (T?)properties.Value.Value; + + return true; + } + } + + value = default; + + return false; + } +}