Enable generation for ID2D1Shader.LoadInputDescriptions API

このコミットが含まれているのは:
Sergio Pedri committed 2022-05-08 18:40:26 +02:00
1 親 54d7cb53e2
コミット 3b760f02d4
11ファイル変更
+386 -1

検索条件に一致するファイルはありません

+2
ファイルの表示
@@ -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)
+1
ファイルの表示
@@ -67,6 +67,7 @@
<Compile Include="..\ComputeSharp.D2D1\Attributes\Enums\D2D1ShaderProfile.cs" Link="ComputeSharp.D2D1\Attributes\Enums\D2D1ShaderProfile.cs" />
<Compile Include="..\ComputeSharp.D2D1\Attributes\Enums\D2D1BufferPrecision.cs" Link="ComputeSharp.D2D1\Attributes\Enums\D2D1BufferPrecision.cs" />
<Compile Include="..\ComputeSharp.D2D1\Attributes\Enums\D2D1ChannelDepth.cs" Link="ComputeSharp.D2D1\Attributes\Enums\D2D1ChannelDepth.cs" />
<Compile Include="..\ComputeSharp.D2D1\Attributes\Enums\D2D1Filter.cs" Link="ComputeSharp.D2D1\Attributes\Enums\D2D1Filter.cs" />
<Compile Include="..\ComputeSharp.D2D1\Attributes\D2DEmbeddedBytecodeAttribute.cs" Link="ComputeSharp.D2D1\Attributes\D2DEmbeddedBytecodeAttribute.cs" />
<Compile Include="..\ComputeSharp.D2D1\Attributes\D2DInputComplexAttribute.cs" Link="ComputeSharp.D2D1\Attributes\D2DInputComplexAttribute.cs" />
<Compile Include="..\ComputeSharp.D2D1\Attributes\D2DInputCountAttribute.cs" Link="ComputeSharp.D2D1\Attributes\D2DInputCountAttribute.cs" />
+32
ファイルの表示
@@ -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");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a shader with an out of range input description index (or more).
/// <para>
/// Format: <c>"The D2D1 shader of type {0} is using some out of range input description indices"</c>.
/// </para>
/// </summary>
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");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for repeated indices for D2D input descriptions.
/// <para>
/// Format: <c>"The D2D1 shader of type {0} is using repeated indices for some of its [D2DInputDescription] attributes"</c>.
/// </para>
/// </summary>
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");
}
@@ -19,12 +19,12 @@ partial class ID2D1ShaderGenerator
/// <summary>
/// Extracts the input info for the current shader.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="inputCount">The number of shader inputs to declare.</param>
/// <param name="inputSimpleIndices">The indicess of the simple shader inputs.</param>
/// <param name="inputComplexIndices">The indices of the complex shader inputs.</param>
/// <param name="combinedInputTypes">The combined and serialized input types for each available input.</param>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
public static void GetInfo(
INamedTypeSymbol structDeclarationSymbol,
out int inputCount,
@@ -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;
/// <inheritdoc/>
partial class ID2D1ShaderGenerator
{
/// <inheritoc/>
private static partial class LoadInputDescriptions
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadInputDescriptions</c> method.
/// </summary>
/// <param name="inputDescriptionsInfo">The input descriptions info gathered for the current shader.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadInputDescriptions</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(InputDescriptionsInfo inputDescriptionsInfo)
{
// This code produces a method declaration as follows:
//
// readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadInputDescriptions<TLoader>(ref TLoader loader)
// {
// <BODY>
// }
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)));
}
/// <summary>
/// Gets a sequence of statements to load the input descriptions for a given shader.
/// </summary>
/// <param name="inputDescriptions">The array of <see cref="InputDescription"/> values for all available input descriptions.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
private static ImmutableArray<StatementSyntax> GetInputDescriptionsLoadingStatements(ImmutableArray<InputDescription> inputDescriptions)
{
// If there are no input descriptions available, just load an empty buffer
if (inputDescriptions.IsEmpty)
{
// loader.LoadInputDescriptions(default);
return
ImmutableArray.Create<StatementSyntax>(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("loader"),
IdentifierName("LoadInputDescriptions")))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.DefaultLiteralExpression,
Token(SyntaxKind.DefaultKeyword))))));
}
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
// 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<byte> data = stackalloc byte[<INPUT_DESCRIPTIONS_SIZE>];
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<ExpressionSyntax>(
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<byte, uint>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)<OFFSET>)) = <INDEX>;
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(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<byte, uint>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)<OFFSET> + 4)) = <FILTER>;
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(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<byte, uint>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)<OFFSET> + 8)) = <LEVEL_OF_DETAIL>;
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<byte, uint>(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();
}
}
}
@@ -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;
/// <inheritdoc/>
partial class ID2D1ShaderGenerator
{
/// <summary>
/// A helper with all logic to generate the <c>LoadInputDescriptions</c> method.
/// </summary>
private static partial class LoadInputDescriptions
{
/// <summary>
/// Extracts the input descriptions for the current shader.
/// </summary>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="inputDescriptions">The produced input descriptions for the shader.</param>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
public static void GetInfo(
INamedTypeSymbol structDeclarationSymbol,
out ImmutableArray<InputDescription> inputDescriptions,
out ImmutableArray<Diagnostic> diagnostics)
{
int inputCount = 0;
ImmutableArray<InputDescription>.Builder inputDescriptionsBuilder = ImmutableArray.CreateBuilder<InputDescription>();
ImmutableArray<Diagnostic>.Builder diagnosticsBuilder = ImmutableArray.CreateBuilder<Diagnostic>();
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<InputDescription>.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<uint> 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();
}
}
}
+36
ファイルの表示
@@ -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<InputDescriptionsInfo> Info)> inputDescriptionsInfoWithErrors =
shaderDeclarations
.Select(static (item, token) =>
{
// LoadInputDescriptions() info
LoadInputDescriptions.GetInfo(
item.Symbol,
out ImmutableArray<InputDescription> inputDescriptions,
out ImmutableArray<Diagnostic> diagnostics);
token.ThrowIfCancellationRequested();
InputDescriptionsInfo inputDescriptionsInfo = new(inputDescriptions);
return (item.Hierarchy, new Result<InputDescriptionsInfo>(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());
});
}
}
+9
ファイルの表示
@@ -0,0 +1,9 @@
namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <summary>
/// A model representing an input description for a shader.
/// </summary>
/// <param name="Index">The index of the input resource the description if for.</param>
/// <param name="Filter">The input filter to use.</param>
/// <param name="LevelOfDetail">The level of detail to use.</param>
internal sealed record InputDescription(uint Index, D2D1Filter Filter, int LevelOfDetail);
+31
ファイルの表示
@@ -0,0 +1,31 @@
using System;
using System.Collections.Immutable;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <summary>
/// A model representing gathered input descriptions for a shader.
/// </summary>
/// <param name="InputDescriptions">The input types for a given shader.</param>
internal sealed record InputDescriptionsInfo(ImmutableArray<InputDescription> InputDescriptions)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="InputDescriptionsInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<InputDescriptionsInfo, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, InputDescriptionsInfo obj)
{
hashCode.AddRange(obj.InputDescriptions);
}
/// <inheritdoc/>
protected override bool AreEqual(InputDescriptionsInfo x, InputDescriptionsInfo y)
{
return x.InputDescriptions.SequenceEqual(y.InputDescriptions);
}
}
}
+1
ファイルの表示
@@ -9,6 +9,7 @@
<Import_RootNamespace>ComputeSharp.SourceGeneration</Import_RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)Extensions\AttributeDataExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\DiagnosticsExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\HashCodeExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Extensions\IEqualityComparerExtensions.cs" />
+35
ファイルの表示
@@ -0,0 +1,35 @@
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.SourceGeneration.Extensions;
/// <summary>
/// Extension methods for the <see cref="AttributeData"/> type.
/// </summary>
internal static class AttributeDataExtensions
{
/// <summary>
/// Tries to get a given named argument value from an <see cref="AttributeData"/> instance, if present.
/// </summary>
/// <typeparam name="T">The type of argument to check.</typeparam>
/// <param name="attributeData">The target <see cref="AttributeData"/> instance to check.</param>
/// <param name="name">The name of the argument to check.</param>
/// <param name="value">The resulting argument value, if present.</param>
/// <returns>Whether or not <paramref name="attributeData"/> contains an argument named <paramref name="name"/> with a valid value.</returns>
public static bool TryGetNamedArgument<T>(this AttributeData attributeData, string name, out T? value)
{
foreach (KeyValuePair<string, TypedConstant> properties in attributeData.NamedArguments)
{
if (properties.Key == name)
{
value = (T?)properties.Value.Value;
return true;
}
}
value = default;
return false;
}
}