Switch LoadDispatchData method to indented writer

このコミットが含まれているのは:
Sergio Pedri committed 2023-10-14 00:35:03 +02:00
1 親 6900923431
コミット d9eb477c1c
4ファイル変更
+115 -245

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

+32
ファイルの表示
@@ -1,4 +1,5 @@
using System;
using System.Runtime.CompilerServices;
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.SourceGeneration.Extensions;
@@ -52,6 +53,37 @@ internal static class IndentedTextWriterExtensions
}
}
/// <summary>
/// Writes a new line into the target writer depending on an input condition.
/// </summary>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
/// <param name="content">The content to write.</param>
/// <param name="condition">The condition to use to decide whether or not to write a new line.</param>
public static void WriteLineIf(this IndentedTextWriter writer, string content, bool condition)
{
if (condition)
{
writer.WriteLine(content);
}
}
/// <summary>
/// Writes a new line into the target writer depending on an input condition.
/// </summary>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
/// <param name="handler">The interpolated string handler with content to write.</param>
/// <param name="condition">The condition to use to decide whether or not to write a new line.</param>
public static void WriteLineIf(
this IndentedTextWriter writer,
[InterpolatedStringHandlerArgument(nameof(writer))] ref IndentedTextWriter.WriteInterpolatedStringHandler handler,
bool condition)
{
if (condition)
{
writer.WriteLine(ref handler);
}
}
/// <summary>
/// Writes a series of members separated by one line between each of them.
/// </summary>
@@ -13,13 +13,13 @@ partial class IShaderGenerator
/// <summary>
/// Writes the <c>BuildHlslSource</c> method.
/// </summary>
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="info">The input <see cref="ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteSyntax(ShaderInfo info, IndentedTextWriter writer)
{
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(GeneratorName);
writer.WriteLine($"readonly void global::ComputeSharp.__Internals.IShader.BuildHlslSource(out string hlslSource)");
writer.WriteLine("readonly void global::ComputeSharp.__Internals.IShader.BuildHlslSource(out string hlslSource)");
using (writer.WriteBlock())
{
+69 -236
ファイルの表示
@@ -1,12 +1,6 @@
using System.Collections.Immutable;
using ComputeSharp.__Internals;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
@@ -17,252 +11,91 @@ partial class IShaderGenerator
partial class LoadDispatchData
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.
/// Writes the <c>LoadDispatchData</c> method.
/// </summary>
/// <param name="isPixelShaderLike">Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture.</param>
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
/// <param name="resourceCount">The total number of captured resources in the shader.</param>
/// <param name="root32BitConstantsCount">The total number of needed 32 bit constants in the shader root signature.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(
bool isPixelShaderLike,
ImmutableArray<FieldInfo> fieldInfos,
int resourceCount,
int root32BitConstantsCount)
/// <param name="info">The input <see cref="ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="writer">The <see cref="IndentedTextWriter"/> instance to write into.</param>
public static void WriteSyntax(ShaderInfo info, IndentedTextWriter writer)
{
// This code produces a method declaration as follows:
//
// readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData<TLoader>(ref TLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z)
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.VoidKeyword)),
Identifier("LoadDispatchData"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddTypeParameterListParameters(TypeParameter(Identifier("TLoader")))
.AddParameterListParameters(
Parameter(Identifier("loader"))
.AddModifiers(Token(SyntaxKind.RefKeyword))
.WithType(IdentifierName("TLoader")),
Parameter(Identifier("device")).WithType(IdentifierName("global::ComputeSharp.GraphicsDevice")),
Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
.WithBody(Block(GetDispatchDataLoadingStatements(isPixelShaderLike, fieldInfos, resourceCount, root32BitConstantsCount)));
}
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(GeneratorName);
writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
writer.WriteLine("readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData<TLoader>(ref TLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z)");
/// <summary>
/// Gets a sequence of statements to load the dispatch data for a given shader.
/// </summary>
/// <param name="isPixelShaderLike">Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture.</param>
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
/// <param name="resourceCount">The total number of captured resources in the shader.</param>
/// <param name="root32BitConstantsCount">The total number of needed 32 bit constants in the shader root signature.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
private static ImmutableArray<StatementSyntax> GetDispatchDataLoadingStatements(
bool isPixelShaderLike,
ImmutableArray<FieldInfo> fieldInfos,
int resourceCount,
int root32BitConstantsCount)
{
using ImmutableArrayBuilder<StatementSyntax> statements = new();
// global::System.Span<uint> span0 = stackalloc uint[<VARIABLES>];
statements.Add(
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("global::System.Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword))))
.AddVariables(
VariableDeclarator(Identifier("span0"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount)))))))))));
if (resourceCount > 0)
using (writer.WriteBlock())
{
// global::System.Span<ulong> span1 = stackalloc ulong[<RESOURCES>];
statements.Add(
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("global::System.Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword))))
.AddVariables(
VariableDeclarator(Identifier("span1"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceCount)))))))))));
}
int numberOfResources = info.DispatchMetadata.ResourceDescriptors.Length;
// ref uint r0 = ref span0[0];
statements.Add(
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r0"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))))))))));
writer.WriteLine($"global::System.Span<uint> span0 = stackalloc uint[{info.DispatchData.Root32BitConstantCount}];");
writer.WriteLineIf($"global::System.Span<ulong> span1 = stackalloc ulong[{numberOfResources}];", numberOfResources > 0);
writer.WriteLine("ref uint r0 = ref span0[0];");
writer.WriteLineIf("ref ulong r1 = ref span1[0];", numberOfResources > 0);
if (resourceCount > 0)
{
// ref ulong r1 = ref span1[0];
statements.Add(
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r1"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span1"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))))))))));
}
// Append the statements for the dispatch ranges
writer.WriteLine("span0[0] = (uint)x;");
writer.WriteLine("span0[1] = (uint)y;");
writer.WriteLineIf("span0[2] = (uint)z;", !info.DispatchData.IsPixelShaderLike);
// Append the statements for the dispatch ranges:
//
// span0[0] = (uint)x;
// span0[1] = (uint)y;
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x")))));
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("y")))));
// If the shader is a compute shader, also track the bounds on the Z axis:
//
// span0[2] = (uint)z;
if (!isPixelShaderLike)
{
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z")))));
}
// Generate loading statements for each captured field
foreach (FieldInfo fieldInfo in fieldInfos)
{
switch (fieldInfo)
// Generate loading statements for each captured field
foreach (FieldInfo fieldInfo in info.DispatchData.FieldInfos)
{
case FieldInfo.Resource resource:
switch (fieldInfo)
{
case FieldInfo.Resource resource:
// Validate the resource and get a handle for it. This will generate:
//
// global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, <OFFSET>) =
// global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(<FIELD_NAME>, device);
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resource.Offset})"),
ParseExpression($"global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({resource.FieldName}, device)"))));
break;
case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive:
// Validate the resource and get a handle for it
writer.WriteLine(
$"global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resource.Offset}) = " +
$"global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({resource.FieldName}, device);");
break;
case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive:
// Read a boolean value and cast it to Bool first, which will apply the correct size expansion. This will generate the following:
//
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Bool>(
// ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)<OFFSET>)) = (global::ComputeSharp.Bool)<FIELD_PATH>
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Bool>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))"),
ParseExpression($"(global::ComputeSharp.Bool){string.Join(".", primitive.FieldPath)}"))));
break;
case FieldInfo.Primitive primitive:
// Read a boolean value and cast it to Bool first, which will apply the correct size expansion
writer.WriteLine(
$"global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Bool>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset})) = " +
$"(global::ComputeSharp.Bool){string.Join(".", primitive.FieldPath)};");
break;
case FieldInfo.Primitive primitive:
// Read a primitive value and serialize it into the target buffer. This will generate:
//
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::<TYPE_NAME>>(
// ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)<OFFSET>)) = <FIELD_PATH>
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<uint, global::{primitive.TypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))"),
ParseExpression($"{string.Join(".", primitive.FieldPath)}"))));
break;
// Read a primitive value and serialize it into the target buffer
writer.WriteLine(
$"global::System.Runtime.CompilerServices.Unsafe.As<uint, global::{primitive.TypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset})) = " +
$"{string.Join(".", primitive.FieldPath)};");
break;
case FieldInfo.NonLinearMatrix matrix:
string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}";
string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__row0";
case FieldInfo.NonLinearMatrix matrix:
string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}";
string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__row0";
// Declare a local to index into individual rows. This will generate:
//
// ref <ROW_TYPE> <ROW_NAME> = ref global::System.Runtime.CompilerServices.Unsafe.As<global::<TYPE_NAME>, <ROW_TYPE_NAME>>(
// ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in <FIELD_PATH>));
statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As<global::{matrix.TypeName}, {rowTypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", matrix.FieldPath)}));"));
// Declare a local to index into individual rows. This will generate:
//
// ref <ROW_TYPE> <ROW_NAME> = ref global::System.Runtime.CompilerServices.Unsafe.As<global::<TYPE_NAME>, <ROW_TYPE_NAME>>(
// ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in <FIELD_PATH>));
writer.WriteLine(
$"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As<global::{matrix.TypeName}, {rowTypeName}>(" +
$"ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", matrix.FieldPath)}));");
// Generate the loading code for each individual row, with proper alignment.
// This will result in the following (assuming Float2x3 m):
//
// ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As<global::ComputeSharp.Float2x3, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m));
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0);
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1);
for (int j = 0; j < matrix.Rows; j++)
{
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<uint, {rowTypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]}))"),
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})"))));
}
// Generate the loading code for each individual row, with proper alignment.
// This will result in the following (assuming Float2x3 m):
//
// ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As<global::ComputeSharp.Float2x3, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m));
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0);
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::ComputeSharp.Float3>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1);
for (int j = 0; j < matrix.Rows; j++)
{
writer.WriteLine(
$"global::System.Runtime.CompilerServices.Unsafe.As<uint, {rowTypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]})) = " +
$"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j});");
}
break;
break;
}
}
// Load the prepared buffers
writer.WriteLine("loader.LoadCapturedValues(span0);");
writer.WriteLineIf("loader.LoadCapturedResources(span1);", numberOfResources > 0);
}
// loader.LoadCapturedValues(span0);
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("loader"),
IdentifierName("LoadCapturedValues")))
.AddArgumentListArguments(Argument(IdentifierName("span0")))));
if (resourceCount > 0)
{
// loader.LoadCapturedResources(span1);
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("loader"),
IdentifierName("LoadCapturedResources")))
.AddArgumentListArguments(Argument(IdentifierName("span1")))));
}
return statements.ToImmutable();
}
}
}
+12 -7
ファイルの表示
@@ -125,14 +125,19 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
// Generate the LoadDispatchData() methods
context.RegisterSourceOutput(shaderInfoWithErrors, static (context, item) =>
{
MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax(
item.DispatchData.IsPixelShaderLike,
item.DispatchData.FieldInfos,
item.DispatchData.ResourceCount,
item.DispatchData.Root32BitConstantCount);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, loadDispatchDataMethod, addSkipLocalsInitAttribute: true);
using ImmutableArrayBuilder<IndentedTextWriter.Callback<ShaderInfo>> declaredMembers = new();
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadDispatchData)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
declaredMembers.Add(LoadDispatchData.WriteSyntax);
using IndentedTextWriter writer = new();
item.Hierarchy.WriteSyntax(
state: item,
writer: writer,
baseTypes: ReadOnlySpan<string>.Empty,
memberCallbacks: declaredMembers.WrittenSpan);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadDispatchData)}.g.cs", writer.ToString());
});
// Generate the BuildHlslSource() methods