Initial implementation of LoadResourceTextureDescriptions generator

このコミットが含まれているのは:
Sergio Pedri committed 2022-08-08 15:45:44 +02:00
1 親 b28d3f2500
コミット 8b42c7011e
12ファイル変更
+437 -15

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

@@ -42,7 +42,7 @@ partial class ID2D1ShaderGenerator
/// </summary>
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
/// <param name="constantBufferSizeInBytes">The size of the shader constant buffer.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load the shader dispatch data.</returns>
private static ImmutableArray<StatementSyntax> GetDispatchDataLoadingStatements(ImmutableArray<FieldInfo> fieldInfos, int constantBufferSizeInBytes)
{
// If there are no fields, just load an empty buffer
@@ -41,7 +41,7 @@ partial class ID2D1ShaderGenerator
/// 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>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load the input descriptions data.</returns>
private static ImmutableArray<StatementSyntax> GetInputDescriptionsLoadingStatements(ImmutableArray<InputDescription> inputDescriptions)
{
// If there are no input descriptions available, just load an empty buffer
@@ -127,7 +127,7 @@ partial class ID2D1ShaderGenerator
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)))));
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(inputDescription.LevelOfDetail)))));
offset += sizeof(int) * 3;
}
@@ -0,0 +1,139 @@
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 LoadResourceTextureDescriptions
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadResourceTextureDescriptions</c> method.
/// </summary>
/// <param name="resourceTextureDescriptionsInfo">The resource texture descriptions info gathered for the current shader.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadResourceTextureDescriptions</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(ResourceTextureDescriptionsInfo resourceTextureDescriptionsInfo)
{
// This code produces a method declaration as follows:
//
// readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadResourceTextureDescriptions<TLoader>(ref TLoader loader)
// {
// <BODY>
// }
return
MethodDeclaration(PredefinedType(Token(SyntaxKind.VoidKeyword)), Identifier(nameof(LoadResourceTextureDescriptions)))
.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)));
}
/// <summary>
/// Gets a sequence of statements to load the resource texture descriptions for a given shader.
/// </summary>
/// <param name="resourceTextureDescriptionsInfo">The array of <see cref="ResourceTextureDescriptionsInfo"/> values for all available resource texture descriptions.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load the resource texture descriptions data.</returns>
private static ImmutableArray<StatementSyntax> GetInputDescriptionsLoadingStatements(ImmutableArray<ResourceTextureDescription> resourceTextureDescriptionsInfo)
{
// If there are no resource texture descriptions available, just load an empty buffer
if (resourceTextureDescriptionsInfo.IsEmpty)
{
// loader.LoadResourceTextureDescriptions(default);
return
ImmutableArray.Create<StatementSyntax>(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("loader"),
IdentifierName("LoadResourceTextureDescriptions")))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.DefaultLiteralExpression,
Token(SyntaxKind.DefaultKeyword))))));
}
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
// 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<byte> data = stackalloc byte[<RESOURCE_TEXTURE_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(resourceTextureDescriptionSizeInBytes)))))))))));
// 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 resource texture description
foreach (ResourceTextureDescription resourceTextureDescription in resourceTextureDescriptionsInfo)
{
// Write the index of the current resource texture 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)resourceTextureDescription.Index)))));
// Write the rank of the current resource texture 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)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();
}
}
}
@@ -0,0 +1,100 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using ComputeSharp.D2D1.SourceGenerators.Models;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Mappings;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.D2D1.SourceGenerators;
/// <inheritdoc/>
partial class ID2D1ShaderGenerator
{
/// <summary>
/// A helper with all logic to generate the <c>LoadResourceTextureDescriptions</c> method.
/// </summary>
private static partial class LoadResourceTextureDescriptions
{
/// <summary>
/// Extracts the resource texture descriptions 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 inputs for the shader.</param>
/// <param name="resourceTextureDescriptions">The produced resource texture descriptions for the shader.</param>
public static void GetInfo(
ImmutableArray<Diagnostic>.Builder diagnostics,
INamedTypeSymbol structDeclarationSymbol,
int inputCount,
out ImmutableArray<ResourceTextureDescription> resourceTextureDescriptions)
{
ImmutableArray<(string Name, uint Index, uint Rank)>.Builder resourceTextureInfos = ImmutableArray.CreateBuilder<(string, uint, uint)>();
foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>())
{
// Only look for fields of a named type symbol (diagnostics is emitted by the HLSL rewriter if it's not the case).
// We're only looking for instance fields of unmanaged types in this case (as resource textures are structs).
if (fieldSymbol is not { IsStatic: false, Type: INamedTypeSymbol { IsUnmanagedType: true } typeSymbol })
{
continue;
}
string metadataName = typeSymbol.GetFullMetadataName();
// Check that the field is a resource texture type (if not, it will be processed by the HLSL rewriter too)
if (HlslKnownTypes.IsResourceTextureType(metadataName))
{
// The type name will be either Texture1D, Texture2D or Texture3D
string typeName = HlslKnownTypes.GetMappedName(typeSymbol);
uint rank = uint.Parse(typeName.Substring(typeName.Length - 2, 1));
uint index = uint.MaxValue;
// Get the index from the [D2DResourceTextureIndex] attribute over the field
if (fieldSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DResourceTextureIndexAttribute", out AttributeData? attributeData))
{
// If the constructor argument isn't available, it means the code is invalid. Just do nothing then, as the
// user will have to fix that to get the code to compile anyway. This way the generator won't crash too.
_ = attributeData!.TryGetConstructorArgument(0, out index);
}
else
{
// If the attribute is missing, emit a diagnostic
// TODO
}
_ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping);
resourceTextureInfos.Add((mapping ?? fieldSymbol.Name, index, rank));
}
}
// Extract the resource texture descriptions for the rest of the pipeline
resourceTextureDescriptions = resourceTextureInfos.Select(static info => new ResourceTextureDescription(info.Index, info.Rank)).ToImmutableArray();
// Validate that the resource texture indices don't overlap with the shader inputs
if (resourceTextureInfos.Any(info => info.Index < inputCount))
{
// TODO: overlap with textures
return;
}
// Validate that no resource texture has an index greater than or equal to 16
if (resourceTextureInfos.Any(info => info.Index >= 16))
{
// TODO: diagnostic
return;
}
HashSet<uint> resourceTextureIndices = new(resourceTextureInfos.Select(info => info.Index));
// All input description indices must be unique
if (resourceTextureIndices.Count != resourceTextureInfos.Count)
{
// TODO: diagnostic
}
}
}
}
+31 -6
ファイルの表示
@@ -51,9 +51,9 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
.Where(static item => IsD2D1PixelShaderType(item.Left.Symbol, item.Right))
.Select(static (item, token) => (item.Left.Syntax, item.Left.Symbol, HierarchyInfo.From(item.Left.Symbol)));
// Get the dispatch data, input types, HLSL source and embedded bytecode info. This info is computed
// on the same step as parts are shared in following sub-branches in the incremental generator pipeline.
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, InputTypesInfo InputTypes, HlslShaderSourceInfo Source, ImmutableArray<Diagnostic> Diagnostics)> shaderInfoWithErrors =
// Get the dispatch data, input types, resource texture descriptions, HLSL source and embedded bytecode info. This info
// is computed on the same step as parts are shared in following sub-branches in the incremental generator pipeline.
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, InputTypesInfo InputTypes, ResourceTextureDescriptionsInfo ResourceTextureDescriptions, HlslShaderSourceInfo Source, ImmutableArray<Diagnostic> Diagnostics)> shaderInfoWithErrors =
shaderDeclarations
.Combine(context.CompilationProvider)
.Select(static (item, token) =>
@@ -81,6 +81,15 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
InputTypesInfo inputTypesInfo = new(inputTypes);
// Get the resource texture info for LoadResourceTextureDescriptions()
LoadResourceTextureDescriptions.GetInfo(
diagnostics,
item.Left.Symbol,
inputCount,
out ImmutableArray<ResourceTextureDescription> resourceTextureDescriptions);
ResourceTextureDescriptionsInfo resourceTextureDescriptionsInfo = new(resourceTextureDescriptions);
// Get HLSL source for BuildHlslSource()
string hlslSource = BuildHlslSource.GetHlslSource(
diagnostics,
@@ -111,6 +120,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
item.Left.Hierarchy,
dispatchDataInfo,
inputTypesInfo,
resourceTextureDescriptionsInfo,
sourceInfo,
diagnostics.ToImmutableArray());
});
@@ -128,10 +138,10 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
context.ReportDiagnostics(d2DCompileOptionsAtAssemblyLevelErrors.Select(static (item, token) => item));
// Filter all items to enable caching at a coarse level, and remove diagnostics
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, InputTypesInfo InputTypes, HlslShaderSourceInfo Source)> shaderInfo =
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch, InputTypesInfo InputTypes, ResourceTextureDescriptionsInfo ResourceTextureDescriptions, HlslShaderSourceInfo Source)> shaderInfo =
shaderInfoWithErrors
.Select(static (item, token) => (item.Hierarchy, item.Dispatch, item.InputTypes, item.Source))
.WithComparers(HierarchyInfo.Comparer.Default, DispatchDataInfo.Comparer.Default, InputTypesInfo.Comparer.Default, EqualityComparer<HlslShaderSourceInfo>.Default);
.Select(static (item, token) => (item.Hierarchy, item.Dispatch, item.InputTypes, item.ResourceTextureDescriptions, item.Source))
.WithComparers(HierarchyInfo.Comparer.Default, DispatchDataInfo.Comparer.Default, InputTypesInfo.Comparer.Default, ResourceTextureDescriptionsInfo.Comparer.Default, EqualityComparer<HlslShaderSourceInfo>.Default);
// Filter items to enable caching for the input count methods
IncrementalValuesProvider<(HierarchyInfo Hierarchy, int InputCount)> inputCountInfo =
@@ -163,6 +173,21 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(GetInputType)}", compilationUnit.GetText(Encoding.UTF8));
});
// Get a filtered sequence to enable caching
IncrementalValuesProvider<(HierarchyInfo Hierarchy, ResourceTextureDescriptionsInfo ResourceTextureDescriptions)> resourceTextureDescriptionsInfo =
shaderInfo
.Select(static (item, token) => (item.Hierarchy, item.ResourceTextureDescriptions))
.WithComparers(HierarchyInfo.Comparer.Default, ResourceTextureDescriptionsInfo.Comparer.Default);
// Generate the LoadResourceTextureDescriptions() methods
context.RegisterSourceOutput(resourceTextureDescriptionsInfo.Combine(canUseSkipLocalsInit), static (context, item) =>
{
MethodDeclarationSyntax getInputTypeMethod = LoadResourceTextureDescriptions.GetSyntax(item.Left.ResourceTextureDescriptions);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, getInputTypeMethod, canUseSkipLocalsInit: false);
context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadResourceTextureDescriptions)}", compilationUnit.GetText(Encoding.UTF8));
});
// Get a filtered sequence to enable caching
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo Dispatch)> dispatchDataInfo =
shaderInfo
+1 -1
ファイルの表示
@@ -3,7 +3,7 @@
/// <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="Index">The index of the input resource the description is 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);
+1 -1
ファイルの表示
@@ -8,7 +8,7 @@ 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>
/// <param name="InputDescriptions">The input descriptions for a given shader.</param>
internal sealed record InputDescriptionsInfo(ImmutableArray<InputDescription> InputDescriptions)
{
/// <summary>
+8
ファイルの表示
@@ -0,0 +1,8 @@
namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// <summary>
/// A model representing a resource texture description for a shader.
/// </summary>
/// <param name="Index">The index of the resource texture resource the description is for.</param>
/// <param name="Rank">The rank of the resource texture.</param>
internal sealed record ResourceTextureDescription(uint Index, uint Rank);
+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 resource texture descriptions for a shader.
/// </summary>
/// <param name="ResourceTextureDescriptions">The resource textures for the current shader.</param>
internal sealed record ResourceTextureDescriptionsInfo(ImmutableArray<ResourceTextureDescription> ResourceTextureDescriptions)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="ResourceTextureDescriptionsInfo"/>.
/// </summary>
public sealed class Comparer : Comparer<ResourceTextureDescriptionsInfo, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, ResourceTextureDescriptionsInfo obj)
{
hashCode.AddRange(obj.ResourceTextureDescriptions);
}
/// <inheritdoc/>
protected override bool AreEqual(ResourceTextureDescriptionsInfo x, ResourceTextureDescriptionsInfo y)
{
return x.ResourceTextureDescriptions.SequenceEqual(y.ResourceTextureDescriptions);
}
}
}