Cleanup the D2D1 generator constant buffer code

Also bumps the maximum constant buffer size
このコミットが含まれているのは:
Sergio Pedri committed 2022-08-08 01:33:38 +02:00
1 親 c9b4bf3431
コミット b51b002a3a
12ファイル変更
+44 -56

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

+3 -3
ファイルの表示
@@ -430,17 +430,17 @@ internal static class DiagnosticDescriptors
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a shader with a root signature that is too large.
/// <para>
/// Format: <c>"The D2D1 shader of type {0} has exceeded the maximum allowed size for captured values and resources"</c>.
/// Format: <c>"The D2D1 shader of type {0} has exceeded the maximum allowed size for captured values"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor ShaderDispatchDataSizeExceeded = new DiagnosticDescriptor(
id: "CMPSD2D0032",
title: "Shader dispatch data size exceeded",
messageFormat: "The D2D1 shader of type {0} has exceeded the maximum allowed size for captured values and resources",
messageFormat: "The D2D1 shader of type {0} has exceeded the maximum allowed size for captured values",
category: "ComputeSharp.D2D1.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "The D2D1 shader of type {0} has exceeded the maximum allowed size for captured values and resources.",
description: "The D2D1 shader of type {0} has exceeded the maximum allowed size for captured values.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
@@ -34,16 +34,16 @@ partial class ID2D1ShaderGenerator
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddTypeParameterListParameters(TypeParameter(Identifier("TLoader")))
.AddParameterListParameters(Parameter(Identifier("loader")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("TLoader")))
.WithBody(Block(GetDispatchDataLoadingStatements(dispatchInfo.FieldInfos, dispatchInfo.Root32BitConstantCount)));
.WithBody(Block(GetDispatchDataLoadingStatements(dispatchInfo.FieldInfos, dispatchInfo.ConstantBufferSizeInBytes)));
}
/// <summary>
/// Gets a sequence of statements to load the dispatch data for a given shader.
/// </summary>
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
/// <param name="root32BitConstantsCount">The total number of needed 32 bit constants in the shader root signature.</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>
private static ImmutableArray<StatementSyntax> GetDispatchDataLoadingStatements(ImmutableArray<FieldInfo> fieldInfos, int root32BitConstantsCount)
private static ImmutableArray<StatementSyntax> GetDispatchDataLoadingStatements(ImmutableArray<FieldInfo> fieldInfos, int constantBufferSizeInBytes)
{
// If there are no fields, just load an empty buffer
if (fieldInfos.IsEmpty)
@@ -74,12 +74,12 @@ partial class ID2D1ShaderGenerator
// Read a primitive value and serialize it into the target buffer. This will generate:
//
// global::System.Runtime.CompilerServices.Unsafe.As<uint, global::<TYPE_NAME>>(
// global::System.Runtime.CompilerServices.Unsafe.As<byte, 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($"global::System.Runtime.CompilerServices.Unsafe.As<byte, global::{primitive.TypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))"),
ParseExpression($"{string.Join(".", primitive.FieldPath)}"))));
break;
@@ -97,39 +97,39 @@ partial class ID2D1ShaderGenerator
// 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);
// global::System.Runtime.CompilerServices.Unsafe.As<byte, 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<byte, 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.As<byte, {rowTypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]}))"),
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})"))));
}
break;
}
}
// global::System.Span<uint> data = stackalloc uint[<VARIABLES>];
// global::System.Span<byte> data = stackalloc byte[<CONSTANT_BUFFER_SIZE>];
statements.Insert(0,
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("global::System.Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword))))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.AddVariables(
VariableDeclarator(Identifier("data"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword)))
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount)))))))))));
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(constantBufferSizeInBytes)))))))))));
// ref uint r0 = ref data[0];
// ref byte r0 = ref data[0];
statements.Insert(1,
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword))))
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r0"))
.WithInitializer(EqualsValueClause(
@@ -25,12 +25,12 @@ partial class ID2D1ShaderGenerator
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="structDeclarationSymbol">The current shader type being explored.</param>
/// <param name="root32BitConstantCount">The total number of needed 32 bit constants in the shader root signature.</param>
/// <param name="constantBufferSizeInBytes">The size of the shader constant buffer.</param>
/// <returns>The sequence of <see cref="FieldInfo"/> instances for all captured resources and values.</returns>
public static ImmutableArray<FieldInfo> GetInfo(
ImmutableArray<Diagnostic>.Builder diagnostics,
ITypeSymbol structDeclarationSymbol,
out int root32BitConstantCount)
out int constantBufferSizeInBytes)
{
// Helper method that uses boxes instead of ref-s (illegal in enumerators)
static IEnumerable<FieldInfo> GetCapturedFieldInfos(
@@ -87,23 +87,14 @@ partial class ID2D1ShaderGenerator
ImmutableArray<string>.Empty,
rawDataOffsetAsBox).ToImmutableArray();
// After all the captured fields have been processed, ansure the reported byte size for
// the local variables is padded to a multiple of a 32 bit value. This is necessary to
// enable loading all the dispatch data after reinterpreting it to a sequence of values
// of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds.
root32BitConstantCount = AlignmentHelper.Pad(rawDataOffsetAsBox.Value, sizeof(int)) / sizeof(int);
constantBufferSizeInBytes = rawDataOffsetAsBox.Value;
// A shader root signature has a maximum size of 64 DWORDs, so 256 bytes.
// Loaded values in the root signature have the following costs:
// - Root constants cost 1 DWORD each, since they are 32-bit values.
// - Descriptor tables cost 1 DWORD each.
// - Root descriptors (64-bit GPU virtual addresses) cost 2 DWORDs each.
// So here we check whether the current signature respects that constraint,
// and emit a build error otherwise. For more info on this, see the docs here:
// https://docs.microsoft.com/windows/win32/direct3d12/root-signature-limits.
int rootSignatureDwordSize = root32BitConstantCount;
// The maximum size for a constant buffer is 64KB
const int D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT = 4096;
const int MaximumConstantBufferSize = D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT * 4 * sizeof(float);
if (rootSignatureDwordSize > 64)
// Emit a diagnostic if the shader constant buffer is too large
if (constantBufferSizeInBytes > MaximumConstantBufferSize)
{
diagnostics.Add(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol);
}
+2 -2
ファイルの表示
@@ -64,11 +64,11 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
ImmutableArray<FieldInfo> fieldInfos = LoadDispatchData.GetInfo(
diagnostics,
item.Left.Symbol,
out int root32BitConstantCount);
out int constantBufferSizeInBytes);
token.ThrowIfCancellationRequested();
DispatchDataInfo dispatchDataInfo = new(fieldInfos, root32BitConstantCount);
DispatchDataInfo dispatchDataInfo = new(fieldInfos, constantBufferSizeInBytes);
// Get the input info for GetInputInfo()
GetInputType.GetInfo(
+4 -4
ファイルの表示
@@ -10,8 +10,8 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models;
/// A model representing gathered info on a shader dispatch data.
/// </summary>
/// <param name="FieldInfos">The description on shader instance fields.</param>
/// <param name="Root32BitConstantCount">The size of the shader root signature, in 32 bit constants.</param>
internal sealed record DispatchDataInfo(ImmutableArray<FieldInfo> FieldInfos, int Root32BitConstantCount)
/// <param name="ConstantBufferSizeInBytes">The size of the shader constant buffer.</param>
internal sealed record DispatchDataInfo(ImmutableArray<FieldInfo> FieldInfos, int ConstantBufferSizeInBytes)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="DispatchDataInfo"/>.
@@ -22,7 +22,7 @@ internal sealed record DispatchDataInfo(ImmutableArray<FieldInfo> FieldInfos, in
protected override void AddToHashCode(ref HashCode hashCode, DispatchDataInfo obj)
{
hashCode.AddRange(obj.FieldInfos, FieldInfo.Comparer.Default);
hashCode.Add(obj.Root32BitConstantCount);
hashCode.Add(obj.ConstantBufferSizeInBytes);
}
/// <inheritdoc/>
@@ -30,7 +30,7 @@ internal sealed record DispatchDataInfo(ImmutableArray<FieldInfo> FieldInfos, in
{
return
x.FieldInfos.SequenceEqual(y.FieldInfos, FieldInfo.Comparer.Default) &&
x.Root32BitConstantCount == y.Root32BitConstantCount;
x.ConstantBufferSizeInBytes == y.ConstantBufferSizeInBytes;
}
}
}
+1 -1
ファイルの表示
@@ -14,5 +14,5 @@ public interface ID2D1DispatchDataLoader
/// Loads the captured values used by the D2D1 shader to be dispatched.
/// </summary>
/// <param name="data">The sequence of serialized captured values.</param>
void LoadConstantBuffer(ReadOnlySpan<uint> data);
void LoadConstantBuffer(ReadOnlySpan<byte> data);
}
+2 -2
ファイルの表示
@@ -28,9 +28,9 @@ internal unsafe struct D2D1BufferSizeDispatchDataLoader : ID2D1DispatchDataLoade
}
/// <inheritdoc/>
void ID2D1DispatchDataLoader.LoadConstantBuffer(ReadOnlySpan<uint> data)
void ID2D1DispatchDataLoader.LoadConstantBuffer(ReadOnlySpan<byte> data)
{
this.size = data.Length * sizeof(uint);
this.size = data.Length;
}
/// <summary>
+2 -2
ファイルの表示
@@ -29,8 +29,8 @@ internal struct D2D1ByteArrayDispatchDataLoader : ID2D1DispatchDataLoader
}
/// <inheritdoc/>
void ID2D1DispatchDataLoader.LoadConstantBuffer(ReadOnlySpan<uint> data)
void ID2D1DispatchDataLoader.LoadConstantBuffer(ReadOnlySpan<byte> data)
{
this.data = MemoryMarshal.AsBytes(data).ToArray();
this.data = data.ToArray();
}
}
+3 -6
ファイルの表示
@@ -1,6 +1,5 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.D2D1.__Internals;
using TerraFX.Interop.DirectX;
@@ -66,13 +65,11 @@ internal unsafe struct D2D1ByteBufferDispatchDataLoader : ID2D1DispatchDataLoade
}
/// <inheritdoc/>
void ID2D1DispatchDataLoader.LoadConstantBuffer(ReadOnlySpan<uint> data)
void ID2D1DispatchDataLoader.LoadConstantBuffer(ReadOnlySpan<byte> data)
{
ReadOnlySpan<byte> constantBuffer = MemoryMarshal.Cast<uint, byte>(data);
if (constantBuffer.TryCopyTo(new Span<byte>(this.buffer, this.length)))
if (data.TryCopyTo(new Span<byte>(this.buffer, this.length)))
{
this.writtenBytes = constantBuffer.Length;
this.writtenBytes = data.Length;
}
}
}
+2 -2
ファイルの表示
@@ -29,10 +29,10 @@ internal readonly unsafe struct D2D1DrawInfoDispatchDataLoader : ID2D1DispatchDa
}
/// <inheritdoc/>
void ID2D1DispatchDataLoader.LoadConstantBuffer(ReadOnlySpan<uint> data)
void ID2D1DispatchDataLoader.LoadConstantBuffer(ReadOnlySpan<byte> data)
{
this.d2D1DrawInfo->SetPixelShaderConstantBuffer(
buffer: (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(data)),
bufferCount: (uint)data.Length * sizeof(uint));
bufferCount: (uint)data.Length);
}
}
+2 -2
ファイルの表示
@@ -30,7 +30,7 @@ internal readonly unsafe struct D2D1EffectDispatchDataLoader : ID2D1DispatchData
}
/// <inheritdoc/>
void ID2D1DispatchDataLoader.LoadConstantBuffer(ReadOnlySpan<uint> data)
void ID2D1DispatchDataLoader.LoadConstantBuffer(ReadOnlySpan<byte> data)
{
if (data.IsEmpty)
{
@@ -41,6 +41,6 @@ internal readonly unsafe struct D2D1EffectDispatchDataLoader : ID2D1DispatchData
index: 0,
type: D2D1_PROPERTY_TYPE.D2D1_PROPERTY_TYPE_BLOB,
data: (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(data)),
dataSize: (uint)data.Length * sizeof(uint)).Assert();
dataSize: (uint)data.Length).Assert();
}
}
+1 -1
ファイルの表示
@@ -105,7 +105,7 @@ partial class IShaderGenerator
resourceCount = resourceOffsetAsBox.Value;
// After all the captured fields have been processed, ansure the reported byte size for
// After all the captured fields have been processed, ensure the reported byte size for
// the local variables is padded to a multiple of a 32 bit value. This is necessary to
// enable loading all the dispatch data after reinterpreting it to a sequence of values
// of size 32 bits (via SetComputeRoot32BitConstants), without reading out of bounds.