diff --git a/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs
index 262e6aa2..41770120 100644
--- a/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs
+++ b/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs
@@ -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
}
}
+ ///
+ /// Writes a new line into the target writer depending on an input condition.
+ ///
+ /// The instance to write into.
+ /// The content to write.
+ /// The condition to use to decide whether or not to write a new line.
+ public static void WriteLineIf(this IndentedTextWriter writer, string content, bool condition)
+ {
+ if (condition)
+ {
+ writer.WriteLine(content);
+ }
+ }
+
+ ///
+ /// Writes a new line into the target writer depending on an input condition.
+ ///
+ /// The instance to write into.
+ /// The interpolated string handler with content to write.
+ /// The condition to use to decide whether or not to write a new line.
+ public static void WriteLineIf(
+ this IndentedTextWriter writer,
+ [InterpolatedStringHandlerArgument(nameof(writer))] ref IndentedTextWriter.WriteInterpolatedStringHandler handler,
+ bool condition)
+ {
+ if (condition)
+ {
+ writer.WriteLine(ref handler);
+ }
+ }
+
///
/// Writes a series of members separated by one line between each of them.
///
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs
index a5f53439..ec8aefcf 100644
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs
@@ -13,13 +13,13 @@ partial class IShaderGenerator
///
/// Writes the BuildHlslSource method.
///
- /// The input instance with gathered shader info.
+ /// The input instance with gathered shader info.
/// The instance to write into.
public static void WriteSyntax(ShaderInfo info, IndentedTextWriter writer)
{
writer.WriteLine("/// ");
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())
{
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs
index 71cb2dcb..ebf5a4f3 100644
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs
@@ -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
{
///
- /// Creates a instance for the LoadDispatchDataMethod method.
+ /// Writes the LoadDispatchData method.
///
- /// Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture.
- /// The array of values for all captured fields.
- /// The total number of captured resources in the shader.
- /// The total number of needed 32 bit constants in the shader root signature.
- /// The resulting instance for the LoadDispatchDataMethod method.
- public static MethodDeclarationSyntax GetSyntax(
- bool isPixelShaderLike,
- ImmutableArray fieldInfos,
- int resourceCount,
- int root32BitConstantsCount)
+ /// The input instance with gathered shader info.
+ /// The instance to write into.
+ public static void WriteSyntax(ShaderInfo info, IndentedTextWriter writer)
{
- // This code produces a method declaration as follows:
- //
- // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData(ref TLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z)
- // {
- //
- // }
- 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("/// ");
+ writer.WriteGeneratedAttributes(GeneratorName);
+ writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]");
+ writer.WriteLine("readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData(ref TLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z)");
- ///
- /// Gets a sequence of statements to load the dispatch data for a given shader.
- ///
- /// Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture.
- /// The array of values for all captured fields.
- /// The total number of captured resources in the shader.
- /// The total number of needed 32 bit constants in the shader root signature.
- /// The sequence of instances to load shader dispatch data.
- private static ImmutableArray GetDispatchDataLoadingStatements(
- bool isPixelShaderLike,
- ImmutableArray fieldInfos,
- int resourceCount,
- int root32BitConstantsCount)
- {
- using ImmutableArrayBuilder statements = new();
-
- // global::System.Span span0 = stackalloc uint[];
- 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(
- LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount)))))))))));
-
- if (resourceCount > 0)
+ using (writer.WriteBlock())
{
- // global::System.Span span1 = stackalloc ulong[];
- 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(
- 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 span0 = stackalloc uint[{info.DispatchData.Root32BitConstantCount}];");
+ writer.WriteLineIf($"global::System.Span 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, ) =
- // global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(, 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(
- // ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint))) = (global::ComputeSharp.Bool)
- statements.Add(ExpressionStatement(
- AssignmentExpression(
- SyntaxKind.SimpleAssignmentExpression,
- ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(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(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>(
- // 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){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(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 = ref global::System.Runtime.CompilerServices.Unsafe.As, >(
- // ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in ));
- statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", matrix.FieldPath)}));"));
+ // Declare a local to index into individual rows. This will generate:
+ //
+ // ref = ref global::System.Runtime.CompilerServices.Unsafe.As, >(
+ // ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in ));
+ writer.WriteLine(
+ $"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(" +
+ $"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(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m));
- // global::System.Runtime.CompilerServices.Unsafe.As(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(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(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(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m));
+ // global::System.Runtime.CompilerServices.Unsafe.As(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(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(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();
}
}
}
\ No newline at end of file
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs
index d5f46e98..2c092913 100644
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs
@@ -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> 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.Empty,
+ memberCallbacks: declaredMembers.WrittenSpan);
+
+ context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadDispatchData)}.g.cs", writer.ToString());
});
// Generate the BuildHlslSource() methods