Merge pull request #652 from Sergio0694/dev/primary-constructors-resources

Support primary constructor parameters for DX12 shader resources
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2023-11-20 22:35:42 +01:00
コミット 531e3c3b35
13ファイル変更
+218 -112

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

+1 -1
ファイルの表示
@@ -3,7 +3,7 @@ using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
#pragma warning disable CA1063
#pragma warning disable CA1063, IDE0052
namespace ComputeSharp.Benchmark.Blas;
@@ -69,12 +69,12 @@ partial class D2DPixelShaderDescriptorGenerator
}
/// <summary>
/// Registers a callback to generate an additional type, if needed.
/// Registers a callback to generate additional types, if needed.
/// </summary>
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="callbacks">The registered callbacks to generate additional types.</param>
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
public static void RegisterAdditionalTypeSyntax(
public static void RegisterAdditionalTypesSyntax(
D2D1ShaderInfo info,
ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks,
ImmutableHashSetBuilder<string> usingDirectives)
@@ -36,12 +36,12 @@ partial class D2DPixelShaderDescriptorGenerator
}
/// <summary>
/// Registers a callback to generate an additional type, if needed.
/// Registers a callback to generate additional types, if needed.
/// </summary>
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="callbacks">The registered callbacks to generate additional types.</param>
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
public static void RegisterAdditionalTypeSyntax(
public static void RegisterAdditionalTypesSyntax(
D2D1ShaderInfo info,
ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks,
ImmutableHashSetBuilder<string> usingDirectives)
@@ -34,12 +34,12 @@ partial class D2DPixelShaderDescriptorGenerator
}
/// <summary>
/// Registers a callback to generate an additional type, if needed.
/// Registers a callback to generate additional types, if needed.
/// </summary>
/// <param name="info">The input <see cref="D2D1ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="callbacks">The registered callbacks to generate additional types.</param>
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
public static void RegisterAdditionalTypeSyntax(
public static void RegisterAdditionalTypesSyntax(
D2D1ShaderInfo info,
ImmutableArrayBuilder<IndentedTextWriter.Callback<D2D1ShaderInfo>> callbacks,
ImmutableHashSetBuilder<string> usingDirectives)
+3 -3
ファイルの表示
@@ -236,9 +236,9 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene
using ImmutableHashSetBuilder<string> usingDirectives = new();
ConstantBufferSyntaxProcessor.RegisterAdditionalTypesSyntax(GeneratorName, BindingDirection.TwoWay, item, additionalTypes, usingDirectives);
InputDescriptions.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);
InputTypes.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);
HlslBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);
InputDescriptions.RegisterAdditionalTypesSyntax(item, additionalTypes, usingDirectives);
InputTypes.RegisterAdditionalTypesSyntax(item, additionalTypes, usingDirectives);
HlslBytecode.RegisterAdditionalTypesSyntax(item, additionalTypes, usingDirectives);
using IndentedTextWriter writer = new();
@@ -119,7 +119,7 @@ partial class ConstantBufferSyntaxProcessor
string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName();
writer.WriteLine($"""/// <summary>""");
writer.WriteLine($"""/// A type containing marshalling logic for shaders of type <see cref="{fullyQualifiedTypeName}"/>.""");
writer.WriteLine($"""/// A type containing marshalling logic for the constant buffer in shaders of type <see cref="{fullyQualifiedTypeName}"/>.""");
writer.WriteLine($"""/// </summary>""");
writer.WriteGeneratedAttributes(ConstantBufferSyntaxProcessor.generatorName!, useFullyQualifiedTypeNames: false);
writer.WriteLine($"""file static class ConstantBufferMarshaller""");
@@ -34,12 +34,12 @@ partial class ComputeShaderDescriptorGenerator
}
/// <summary>
/// Registers a callback to generate an additional type, if needed.
/// Registers a callback to generate additional types, if needed.
/// </summary>
/// <param name="info">The input <see cref="ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="callbacks">The registered callbacks to generate additional types.</param>
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
public static void RegisterAdditionalTypeSyntax(
public static void RegisterAdditionalTypesSyntax(
ShaderInfo info,
ImmutableArrayBuilder<IndentedTextWriter.Callback<ShaderInfo>> callbacks,
ImmutableHashSetBuilder<string> usingDirectives)
@@ -1,60 +0,0 @@
using System.Collections.Immutable;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Mappings;
using ComputeSharp.SourceGenerators.Models;
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
partial class ComputeShaderDescriptorGenerator
{
/// <summary>
/// A helper with all logic to generate the <c>ResourceDescriptorRanges</c> property.
/// </summary>
private static partial class ResourceDescriptorRanges
{
/// <summary>
/// Gets the data related to the shader metadata for a given shader type.
/// </summary>
/// <param name="isImplicitTextureUsed">Indicates whether the current shader uses an implicit texture.</param>
/// <param name="isSamplerUsed">Whether the static sampler is used by the shader.</param>
/// <param name="resources">The sequence of captured resources for the shader.</param>
/// <returns>The metadata info for the shader.</returns>
public static ImmutableArray<ResourceDescriptor> GetInfo(
bool isImplicitTextureUsed,
bool isSamplerUsed,
ImmutableArray<ResourceInfo> resources)
{
using ImmutableArrayBuilder<ResourceDescriptor> descriptors = new();
int constantBufferOffset = 1;
int readOnlyResourceOffset = 0;
int readWriteResourceOffset = 0;
// Add the implicit texture descriptor, if needed
if (isImplicitTextureUsed)
{
descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++));
}
// Populate the sequence of resource descriptors
foreach (ResourceInfo resource in resources)
{
if (HlslKnownTypes.IsConstantBufferType(resource.TypeName))
{
descriptors.Add(new ResourceDescriptor(2, constantBufferOffset++));
}
else if (HlslKnownTypes.IsReadOnlyTypedResourceType(resource.TypeName))
{
descriptors.Add(new ResourceDescriptor(0, readOnlyResourceOffset++));
}
else
{
descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++));
}
}
return descriptors.ToImmutable();
}
}
}
@@ -0,0 +1,124 @@
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGenerators.Models;
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
partial class ComputeShaderDescriptorGenerator
{
/// <inheritdoc/>
partial class Resources
{
/// <summary>
/// Writes the <c>LoadGraphicsResources</c> method.
/// </summary>
/// <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)
{
string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(GeneratorName);
writer.WriteLine($"static void global::ComputeSharp.Descriptors.IComputeShaderDescriptor<{typeName}>.LoadGraphicsResources<TLoader>(in {typeName} shader, ref TLoader loader)");
using (writer.WriteBlock())
{
// Nothing to do if there are no resources
if (info.Resources.IsEmpty)
{
return;
}
// Delegate to the generated loader type
writer.WriteLine("global::ComputeSharp.Generated.GraphicsResourcesLoader.LoadGraphicsResources(in shader, ref loader);");
}
}
/// <summary>
/// Registers a callback to generate additional types, if needed.
/// </summary>
/// <param name="info">The input <see cref="ShaderInfo"/> instance with gathered shader info.</param>
/// <param name="callbacks">The registered callbacks to generate additional types.</param>
/// <param name="usingDirectives">The using directives needed by the generated code.</param>
public static void RegisterAdditionalTypesSyntax(
ShaderInfo info,
ImmutableArrayBuilder<IndentedTextWriter.Callback<ShaderInfo>> callbacks,
ImmutableHashSetBuilder<string> usingDirectives)
{
// If there are no resources, there's no need for any additional types
if (info.Resources.IsEmpty)
{
return;
}
_ = usingDirectives.Add("global::System.CodeDom.Compiler");
_ = usingDirectives.Add("global::System.Diagnostics");
_ = usingDirectives.Add("global::System.Diagnostics.CodeAnalysis");
_ = usingDirectives.Add("global::System.Runtime.CompilerServices");
_ = usingDirectives.Add("global::ComputeSharp.Descriptors");
// Declare the GraphicsResourcesLoader type
static void Callback(ShaderInfo info, IndentedTextWriter writer)
{
string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName();
writer.WriteLine($"""/// <summary>""");
writer.WriteLine($"""/// A type containing loading logic for graphics resources in shaders of type <see cref="{fullyQualifiedTypeName}"/>.""");
writer.WriteLine($"""/// </summary>""");
writer.WriteGeneratedAttributes(GeneratorName, useFullyQualifiedTypeNames: false);
writer.WriteLine($"""file static class GraphicsResourcesLoader""");
using (writer.WriteBlock())
{
// Define the FromManaged method (managed shader type to native constant buffer)
writer.WriteLine($$"""/// <inheritdoc cref="IComputeShaderDescriptor{T}.LoadGraphicsResources"/>""");
writer.WriteLine($"""[MethodImpl(MethodImplOptions.AggressiveInlining)]""");
writer.WriteLine($"public static void LoadGraphicsResources<TLoader>(in {fullyQualifiedTypeName} shader, ref TLoader loader)");
writer.WriteLine(" where TLoader : struct, IGraphicsResourceLoader");
using (writer.WriteBlock())
{
// Generate loading statements for each captured resource.
// Each loading statement will invoke the generated accessor.
for (int i = 0; i < info.Resources.Length; i++)
{
writer.WriteLine($"loader.LoadGraphicsResource(shader.{info.Resources[i].FieldName}(), {i});");
}
}
// Define all field accessors (always used, just like for constant buffer fields, see remarks there)
foreach (ResourceInfo resourceInfo in info.Resources)
{
writer.WriteLine();
// Generate the correct field accessor depending on whether the field can be referenced directly
if (resourceInfo.UnspeakableName is null)
{
writer.WriteLine($"""
/// <inheritdoc cref="{fullyQualifiedTypeName}.{resourceInfo.FieldName}"/>
/// <param name="shader">The input <see cref="{fullyQualifiedTypeName}"/> value.</param>
/// <returns>A reference to <see cref="{fullyQualifiedTypeName}.{resourceInfo.FieldName}"/>.</returns>
[UnsafeAccessor(UnsafeAccessorKind.Field)]
private static extern ref readonly {resourceInfo.FieldType} {resourceInfo.FieldName}(this ref readonly {fullyQualifiedTypeName} value);
""", isMultiline: true);
}
else
{
writer.WriteLine($"""
/// <summary>Gets a reference to the unspeakable field "{resourceInfo.FieldName}" of type <see cref="{fullyQualifiedTypeName}"/>.</summary>
/// <param name="shader">The input <see cref="{fullyQualifiedTypeName}"/> value.</param>
/// <returns>A reference to the unspeakable field "{resourceInfo.FieldName}".</returns>
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "{resourceInfo.UnspeakableName}")]
private static extern ref readonly {resourceInfo.FieldType} {resourceInfo.FieldName}(this ref readonly {fullyQualifiedTypeName} value);
""", isMultiline: true);
}
}
}
}
callbacks.Add(Callback);
}
}
}
+67 -22
ファイルの表示
@@ -4,6 +4,7 @@ using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Mappings;
using ComputeSharp.SourceGeneration.Models;
using ComputeSharp.SourceGeneration.SyntaxProcessors;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors;
@@ -16,50 +17,85 @@ partial class ComputeShaderDescriptorGenerator
/// <summary>
/// A helper with all logic to generate the resources loading code.
/// </summary>
private static class Resources
private static partial class Resources
{
/// <summary>
/// Explores a given type hierarchy and generates statements to load fields.
/// Gathers info on all resources captured by a given shader type.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
/// <param name="structDeclarationSymbol">The current shader type being explored.</param>
/// <param name="isImplicitTextureUsed">Indicates whether the current shader uses an implicit texture.</param>
/// <param name="constantBufferSizeInBytes">The size of the shader constant buffer.</param>
/// <param name="resources">The sequence of <see cref="ResourceInfo"/> instances for all captured resources.</param>
/// <param name="resourceDescriptors">The sequence of <see cref="ResourceDescriptor"/> instances for all captured resources.</param>
public static void GetInfo(
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
Compilation compilation,
ITypeSymbol structDeclarationSymbol,
bool isImplicitTextureUsed,
int constantBufferSizeInBytes,
out ImmutableArray<ResourceInfo> resources)
out ImmutableArray<ResourceInfo> resources,
out ImmutableArray<ResourceDescriptor> resourceDescriptors)
{
using ImmutableArrayBuilder<ResourceInfo> resourceBuilder = new();
using ImmutableArrayBuilder<ResourceDescriptor> resourceDescriptorBuilder = new();
int constantBufferOffset = 1;
int readOnlyResourceOffset = 0;
int readWriteResourceOffset = 0;
// Add the implicit texture descriptor, if needed
if (isImplicitTextureUsed)
{
resourceDescriptorBuilder.Add(new ResourceDescriptor(1, readWriteResourceOffset++));
}
foreach (ISymbol memberSymbol in structDeclarationSymbol.GetMembers())
{
// Only process instance fields
if (memberSymbol is not IFieldSymbol { Type: INamedTypeSymbol { IsStatic: false }, IsConst: false, IsStatic: false, IsFixedSizeBuffer: false, IsImplicitlyDeclared: false } fieldSymbol)
if (memberSymbol is not IFieldSymbol { Type: INamedTypeSymbol { IsStatic: false } typeSymbol, IsConst: false, IsStatic: false, IsFixedSizeBuffer: false } fieldSymbol)
{
continue;
}
// Skip fields of not accessible types (the analyzer will handle this just like other fields)
if (!fieldSymbol.Type.IsAccessibleFromCompilationAssembly(compilation))
if (!typeSymbol.IsAccessibleFromCompilationAssembly(compilation))
{
continue;
}
string fieldName = fieldSymbol.Name;
string typeName = fieldSymbol.Type.GetFullyQualifiedMetadataName();
// Try to get the name to use for the field and the accessor
if (!ConstantBufferSyntaxProcessor.TryGetFieldAccessorName(fieldSymbol, out string? fieldName, out string? unspeakableName))
{
continue;
}
string typeName = typeSymbol.GetFullyQualifiedMetadataName();
// Check if the field is a resource (note: resources can only be top level fields)
if (HlslKnownTypes.IsTypedResourceType(typeName))
{
resourceBuilder.Add(new ResourceInfo(fieldName, typeName));
resourceBuilder.Add(new ResourceInfo(fieldName, GetResourceTypeName(typeSymbol), unspeakableName));
// Populate the resource descriptors as well
if (HlslKnownTypes.IsConstantBufferType(typeName))
{
resourceDescriptorBuilder.Add(new ResourceDescriptor(2, constantBufferOffset++));
}
else if (HlslKnownTypes.IsReadOnlyTypedResourceType(typeName))
{
resourceDescriptorBuilder.Add(new ResourceDescriptor(0, readOnlyResourceOffset++));
}
else
{
resourceDescriptorBuilder.Add(new ResourceDescriptor(1, readWriteResourceOffset++));
}
}
}
resources = resourceBuilder.ToImmutable();
resourceDescriptors = resourceDescriptorBuilder.ToImmutable();
// A shader root signature has a maximum size of 64 DWORDs, so 256 bytes.
// Loaded values in the root signature have the following costs:
@@ -76,26 +112,35 @@ partial class ComputeShaderDescriptorGenerator
}
/// <summary>
/// Writes the <c>LoadGraphicsResources</c> method.
/// Gets the name of a given resource field type.
/// </summary>
/// <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)
/// <param name="typeSymbol">The input field type to inspect.</param>
/// <returns>The fully qualified resource type name, nicely formatted.</returns>
private static string GetResourceTypeName(INamedTypeSymbol typeSymbol)
{
string typeName = info.Hierarchy.Hierarchy[0].QualifiedName;
using ImmutableArrayBuilder<char> builder = new();
writer.WriteLine("/// <inheritdoc/>");
writer.WriteGeneratedAttributes(GeneratorName);
writer.WriteLine($"static void global::ComputeSharp.Descriptors.IComputeShaderDescriptor<{typeName}>.LoadGraphicsResources<TLoader>(in {typeName} shader, ref TLoader loader)");
// Add the type name (we'll add the ComputeSharp namespace, so no need for fully qualified type names)
builder.AddRange(typeSymbol.Name.AsSpan());
builder.Add('<');
using (writer.WriteBlock())
_ = HlslKnownTypes.TryGetMappedName(typeSymbol.TypeArguments[0].GetFullyQualifiedMetadataName(), out string? mappedName);
// We always have at least one type argument, so first append it. We either append the mapped
// type name (ie. the friendly primitive or HLSL type name), or the fully qualified type name.
builder.AddRange((mappedName ?? typeSymbol.TypeArguments[0].GetFullyQualifiedName(includeGlobal: true)).AsSpan());
// If the resource also has a pixel type, append that too.
// We only need the name again, as the namespace is imported.
if (typeSymbol.TypeArguments is [_, INamedTypeSymbol pixelTypeSymbol])
{
// Generate loading statements for each captured resource
for (int i = 0; i < info.Resources.Length; i++)
{
writer.WriteLine($"loader.LoadGraphicsResource(shader.{info.Resources[i].FieldName}, {i});");
}
builder.AddRange(", ".AsSpan());
builder.AddRange(pixelTypeSymbol.Name.AsSpan());
}
builder.Add('>');
return builder.ToString();
}
}
}
+10 -15
ファイルの表示
@@ -69,16 +69,6 @@ public sealed partial class ComputeShaderDescriptorGenerator : IIncrementalGener
token.ThrowIfCancellationRequested();
// Get the resources info
Resources.GetInfo(
diagnostics,
context.SemanticModel.Compilation,
typeSymbol,
constantBufferSizeInBytes,
out ImmutableArray<ResourceInfo> resourceInfo);
token.ThrowIfCancellationRequested();
// Thread group size info
NumThreads.GetInfo(
diagnostics,
@@ -105,11 +95,15 @@ public sealed partial class ComputeShaderDescriptorGenerator : IIncrementalGener
token.ThrowIfCancellationRequested();
// Resource descriptor ranges info
ImmutableArray<ResourceDescriptor> resourceDescriptors = ResourceDescriptorRanges.GetInfo(
// Get the resources info
Resources.GetInfo(
diagnostics,
context.SemanticModel.Compilation,
typeSymbol,
isImplicitTextureUsed,
isSamplerUsed,
resourceInfo);
constantBufferSizeInBytes,
out ImmutableArray<ResourceInfo> resourceInfo,
out ImmutableArray<ResourceDescriptor> resourceDescriptors);
token.ThrowIfCancellationRequested();
@@ -174,8 +168,9 @@ public sealed partial class ComputeShaderDescriptorGenerator : IIncrementalGener
using ImmutableHashSetBuilder<string> usingDirectives = new();
ConstantBufferSyntaxProcessor.RegisterAdditionalTypesSyntax(GeneratorName, BindingDirection.OneWay, item, additionalTypes, usingDirectives);
Resources.RegisterAdditionalTypesSyntax(item, additionalTypes, usingDirectives);
ResourceDescriptorRanges.RegisterAdditionalDataMemberSyntax(item, additionalTypes, usingDirectives);
HlslBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives);
HlslBytecode.RegisterAdditionalTypesSyntax(item, additionalTypes, usingDirectives);
using IndentedTextWriter writer = new();
+3 -2
ファイルの表示
@@ -4,5 +4,6 @@ namespace ComputeSharp.SourceGenerators.Models;
/// A model describing a captured resource (either a buffer or a texture).
/// </summary>
/// <param name="FieldName">The name of the resource field.</param>
/// <param name="TypeName">The full metadata name for the resource type.</param>
public sealed record ResourceInfo(string FieldName, string TypeName);
/// <param name="FieldType">The fully qualified type name of the field.</param>
/// <param name="UnspeakableName">The unspeakable name of the field, if present.</param>
public sealed record ResourceInfo(string FieldName, string FieldType, string? UnspeakableName);
+1
ファイルの表示
@@ -5,6 +5,7 @@ namespace ComputeSharp;
/// </summary>
/// <typeparam name="T">The pixel type, when stored in memory (either on the CPU or the GPU side).</typeparam>
/// <typeparam name="TPixel">The type of pixel when normalized and used within a shader.</typeparam>
/// <remarks>This interface is not meant to be implemented by user defined types.</remarks>
public interface IPixel<T, TPixel>
where T : unmanaged, IPixel<T, TPixel>
where TPixel : unmanaged