Switch LoadDispatchMetadata() to incremental

このコミットが含まれているのは:
Sergio Pedri committed 2021-12-08 11:17:05 +01:00
1 親 f2a556e63b
コミット c6172032bd
5ファイル変更
+326 -1

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

@@ -0,0 +1,182 @@
using System;
using System.Collections.Immutable;
using ComputeSharp.__Internals;
using ComputeSharp.SourceGenerators.Mappings;
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;
/// <inheritdoc/>
public sealed partial class IShaderGenerator2
{
/// <summary>
/// Gets the data related to the shader metadata for a given shader type.
/// </summary>
/// <param name="root32BitConstantCount">The total number of needed 32 bit constants in the shader root signature.</param>
/// <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="capturedFields">The sequence of captured fields for the shader.</param>
/// <returns>The metadata info for the shader.</returns>
private static DispatchMetadataInfo GetDispatchMetadataInfo(
int root32BitConstantCount,
bool isImplicitTextureUsed,
bool isSamplerUsed,
ImmutableArray<FieldInfo> capturedFields)
{
ImmutableArray<ResourceDescriptor>.Builder descriptors = ImmutableArray.CreateBuilder<ResourceDescriptor>();
int constantBufferOffset = 1;
int readOnlyResourceOffset = 0;
int readWriteResourceOffset = 0;
int resourceOffset = 0;
// Add the implicit texture descriptor, if needed
if (isImplicitTextureUsed)
{
descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++, resourceOffset++));
}
// Populate the sequence of resource descriptors
foreach (FieldInfo.Resource resource in capturedFields.OfType<FieldInfo.Resource>())
{
if (HlslKnownTypes.IsConstantBufferType(resource.TypeName))
{
descriptors.Add(new ResourceDescriptor(2, constantBufferOffset++, resourceOffset++));
}
else if (HlslKnownTypes.IsReadOnlyTypedResourceType(resource.TypeName))
{
descriptors.Add(new ResourceDescriptor(0, readOnlyResourceOffset++, resourceOffset++));
}
else
{
descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++, resourceOffset++));
}
}
return new(
root32BitConstantCount,
isSamplerUsed,
descriptors.ToImmutable());
}
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.
/// </summary>
/// <param name="metadataInfo">The dispatch metadata for the current shader..</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.</returns>
private static MethodDeclarationSyntax CreateLoadDispatchMetadataMethod(DispatchMetadataInfo metadataInfo)
{
// This code produces a method declaration as follows:
//
// readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata<TMetadataLoader>(ref TMetadataLoader loader, out global::System.IntPtr result)
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.VoidKeyword)),
Identifier("LoadDispatchMetadata"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddTypeParameterListParameters(TypeParameter(Identifier("TMetadataLoader")))
.AddParameterListParameters(
Parameter(Identifier("loader"))
.AddModifiers(Token(SyntaxKind.RefKeyword))
.WithType(IdentifierName("TMetadataLoader")),
Parameter(Identifier("result"))
.AddModifiers(Token(SyntaxKind.OutKeyword))
.WithType(IdentifierName($"global::System.{typeof(IntPtr).Name}")))
.WithBody(Block(GetDispatchMetadataLoadingStatements(metadataInfo)));
}
/// <summary>
/// Gets a sequence of statements to load the dispatch metadata for a given shader type.
/// </summary>
/// <param name="metadataInfo">The dispatch metadata for the current shader..</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
private static ImmutableArray<StatementSyntax> GetDispatchMetadataLoadingStatements(DispatchMetadataInfo metadataInfo)
{
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
// global::System.Span<byte> span0 = stackalloc byte[5];
statements.Add(
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("global::System.Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.AddVariables(
VariableDeclarator(Identifier("span0"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5)))))))))));
// Compute the total number of resources
int totalResourcesCount = metadataInfo.ResourceDescriptors.Length;
// Span<global::ComputeSharp.__Internals.ResourceDescriptor> span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[<ADJUSTED_COUNT>];
statements.Add(
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("global::System.Span"))
.AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")))
.AddVariables(
VariableDeclarator(Identifier("span1"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount)))))))))));
// ref byte r0 = ref span0[0];
statements.Add(
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r0"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))))))))));
// ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0];
statements.Add(
LocalDeclarationStatement(
VariableDeclaration(RefType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")))
.AddVariables(
VariableDeclarator(Identifier("r1"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span1"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))))))))));
// Serialized shader metadata
statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned<int>(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {metadataInfo.Root32BitConstantCount});"));
statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned<bool>(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {metadataInfo.IsSamplerUsed.ToString().ToLowerInvariant()});"));
// Populate the sequence of resource descriptors
foreach (ResourceDescriptor descriptor in metadataInfo.ResourceDescriptors)
{
statements.Add(ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create({descriptor.TypeId}, {descriptor.RegisterOffset}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {descriptor.Offset}));"));
}
// Invoke the value delegate to create the opaque root signature handle
statements.Add(ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);"));
return statements.ToImmutable();
}
}
+24
ファイルの表示
@@ -148,6 +148,30 @@ public sealed partial class IShaderGenerator2 : IIncrementalGenerator
context.AddSource($"{item.Left.Hierarchy.FilenameHint}.BuildHlslString", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8));
});
// Get the dispatch metadata info
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchMetadataInfo MetadataInfo)> dispatchMetadataInfo =
dispatchDataInfo
.Collect()
.Combine(dynamicSourceInfo.Collect())
.SelectMany(static (item, token) => item.Left.Zip(item.Right, static (left, right) => (DataInfo: left, right.SourceInfo)))
.Select(static (item, token) => (
item.DataInfo.Hierarchy,
GetDispatchMetadataInfo(
item.DataInfo.Root32BitConstantCount,
item.SourceInfo.ImplicitTextureType is not null,
item.SourceInfo.IsSamplerUsed,
item.DataInfo.FieldInfos)))
.WithComparers(HierarchyInfo.Comparer.Default, DispatchMetadataInfo.Comparer.Default);
// Generate the LoadDispatchMetadata() methods
context.RegisterSourceOutput(dispatchMetadataInfo.Combine(canUseSkipLocalsInit), static (context, item) =>
{
MethodDeclarationSyntax buildHlslStringMethod = CreateLoadDispatchMetadataMethod(item.Left.MetadataInfo);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, item.Right);
context.AddSource($"{item.Left.Hierarchy.FilenameHint}.LoadDispatchMetadata", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8));
});
}
/// <summary>
+1 -1
ファイルの表示
@@ -67,7 +67,7 @@ public sealed partial class IShaderGenerator : ISourceGenerator
{
// getDispatchIdMethod,
// loadDispatchDataMethod,
loadDispatchMetadataMethod,
//loadDispatchMetadataMethod,
//buildHlslStringMethod,
tryGetBytecodeMethod
};
+65
ファイルの表示
@@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.SourceGenerators.Extensions;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model containing info on shader dispatch metadata.
/// </summary>
/// <param name="Root32BitConstantCount">The size of the shader root signature, in 32 bit constants.</param>
/// <param name="IsSamplerUsed">Whether or not the static sampler is used.</param>
/// <param name="ResourceDescriptors">The sequence of resource descriptors for the shader.</param>
internal sealed record DispatchMetadataInfo(
int Root32BitConstantCount,
bool IsSamplerUsed,
ImmutableArray<ResourceDescriptor> ResourceDescriptors)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="DispatchMetadataInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<DispatchMetadataInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(DispatchMetadataInfo? x, DispatchMetadataInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return
x.Root32BitConstantCount == y.Root32BitConstantCount &&
x.IsSamplerUsed == y.IsSamplerUsed &&
x.ResourceDescriptors.SequenceEqual(y.ResourceDescriptors, ResourceDescriptor.Comparer.Default);
}
/// <inheritdoc/>
public int GetHashCode(DispatchMetadataInfo obj)
{
HashCode hashCode = default;
hashCode.Add(obj.Root32BitConstantCount);
hashCode.Add(obj.IsSamplerUsed);
hashCode.AddRange(obj.ResourceDescriptors, ResourceDescriptor.Comparer.Default);
return hashCode.ToHashCode();
}
}
}
+54
ファイルの表示
@@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A resource descriptor for a captured resource in a shader.
/// </summary>
/// <param name="TypeId">The type id for the resource.</param>
/// <param name="RegisterOffset">The offset of the resource in its containing register.</param>
/// <param name="Offset">The offset of the resource descriptor in the shader root signature.</param>
internal sealed record ResourceDescriptor(int TypeId, int RegisterOffset, int Offset)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="ResourceDescriptor"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<ResourceDescriptor>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(ResourceDescriptor? x, ResourceDescriptor? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return
x.TypeId == y.TypeId &&
x.RegisterOffset == y.RegisterOffset &&
x.Offset == y.Offset;
}
/// <inheritdoc/>
public int GetHashCode(ResourceDescriptor obj)
{
return HashCode.Combine(obj.TypeId, obj.RegisterOffset, obj.Offset);
}
}
}