Implement ID2D1Shader.LoadDispatchData generator
このコミットが含まれているのは:
1 親
2212b8716d
コミット
e68861e679
7ファイル変更
+432
-33
検索条件に一致するファイルはありません
+3
@@ -61,6 +61,9 @@
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\UInt\UIntMxN.g.cs" Link="ComputeSharp.Core\Primitives\UInt\UIntMxN.g.cs" />
|
||||
<Compile Include="..\ComputeSharp.Core\Primitives\MatrixIndex.cs" Link="ComputeSharp.Core\Primitives\MatrixIndex.cs" />
|
||||
|
||||
<!-- ComputeSharp APIs -->
|
||||
<Compile Include="..\ComputeSharp\Core\Helpers\AlignmentHelper.cs" Link="ComputeSharp\Core\Helpers\AlignmentHelper.cs" />
|
||||
|
||||
<!-- ComputeSharp.D2D1Interop APIs -->
|
||||
<Compile Include="..\ComputeSharp.D2D1Interop\Attributes\Profiles\D2D1ShaderProfile.cs" Link="ComputeSharp.D2D1Interop\Attributes\Profiles\D2D1ShaderProfile.cs" />
|
||||
<Compile Include="..\ComputeSharp.D2D1Interop\Attributes\D2DEmbeddedBytecodeAttribute.cs" Link="ComputeSharp.D2D1Interop\Attributes\D2DEmbeddedBytecodeAttribute.cs" />
|
||||
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.D2D1Interop.__Internals;
|
||||
using ComputeSharp.D2D1Interop.SourceGenerators.Models;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
namespace ComputeSharp.D2D1Interop.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
partial class ID2D1ShaderGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
private static partial class LoadDispatchData
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.
|
||||
/// </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>
|
||||
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.</returns>
|
||||
public static MethodDeclarationSyntax GetSyntax(ImmutableArray<FieldInfo> fieldInfos, int root32BitConstantsCount)
|
||||
{
|
||||
// This code produces a method declaration as follows:
|
||||
//
|
||||
// readonly void global::ComputeSharp.D2D1Interop.__Internals.ID2D1Shader.LoadDispatchData<TLoader>(ref TLoader loader)
|
||||
// {
|
||||
// <BODY>
|
||||
// }
|
||||
return
|
||||
MethodDeclaration(
|
||||
PredefinedType(Token(SyntaxKind.VoidKeyword)),
|
||||
Identifier("LoadDispatchData"))
|
||||
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.D2D1Interop.__Internals.{nameof(ID2D1Shader)}")))
|
||||
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
|
||||
.AddTypeParameterListParameters(TypeParameter(Identifier("TLoader")))
|
||||
.AddParameterListParameters(Parameter(Identifier("loader")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("TLoader")))
|
||||
.WithBody(Block(GetDispatchDataLoadingStatements(fieldInfos, root32BitConstantsCount)));
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
|
||||
private static ImmutableArray<StatementSyntax> GetDispatchDataLoadingStatements(ImmutableArray<FieldInfo> fieldInfos, int root32BitConstantsCount)
|
||||
{
|
||||
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
|
||||
|
||||
// Generate loading statements for each captured field
|
||||
foreach (FieldInfo fieldInfo in fieldInfos)
|
||||
{
|
||||
switch (fieldInfo)
|
||||
{
|
||||
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;
|
||||
|
||||
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)}));"));
|
||||
|
||||
// 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})"))));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// global::System.Span<uint> span0 = stackalloc uint[<VARIABLES>];
|
||||
statements.Insert(0,
|
||||
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)))))))))));
|
||||
|
||||
// ref uint r0 = ref span0[0];
|
||||
statements.Insert(1,
|
||||
LocalDeclarationStatement(
|
||||
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword))))
|
||||
.AddVariables(
|
||||
VariableDeclarator(Identifier("r0"))
|
||||
.WithInitializer(EqualsValueClause(
|
||||
RefExpression(
|
||||
ElementAccessExpression(IdentifierName("span0"))
|
||||
.AddArgumentListArguments(Argument(
|
||||
LiteralExpression(
|
||||
SyntaxKind.NumericLiteralExpression,
|
||||
Literal(0))))))))));
|
||||
|
||||
// loader.LoadCapturedValues(span0);
|
||||
statements.Add(
|
||||
ExpressionStatement(
|
||||
InvocationExpression(
|
||||
MemberAccessExpression(
|
||||
SyntaxKind.SimpleMemberAccessExpression,
|
||||
IdentifierName("loader"),
|
||||
IdentifierName("LoadCapturedValues")))
|
||||
.AddArgumentListArguments(Argument(IdentifierName("span0")))));
|
||||
|
||||
return statements.ToImmutable();
|
||||
}
|
||||
}
|
||||
}
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using System.Runtime.CompilerServices;
|
||||
using ComputeSharp.Core.Helpers;
|
||||
using ComputeSharp.D2D1Interop.SourceGenerators.Diagnostics;
|
||||
using ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
|
||||
using ComputeSharp.D2D1Interop.SourceGenerators.Mappings;
|
||||
using ComputeSharp.D2D1Interop.SourceGenerators.Models;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using static ComputeSharp.D2D1Interop.SourceGenerators.Diagnostics.DiagnosticDescriptors;
|
||||
|
||||
namespace ComputeSharp.D2D1Interop.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class ID2D1ShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// A helper with all logic to generate the <c>LoadDispatchData</c> method.
|
||||
/// </summary>
|
||||
private static partial class LoadDispatchData
|
||||
{
|
||||
/// <summary>
|
||||
/// Explores a given type hierarchy and generates statements to load fields.
|
||||
/// </summary>
|
||||
/// <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="diagnostics">The resulting diagnostics from the processing operation.</param>
|
||||
/// <returns>The sequence of <see cref="FieldInfo"/> instances for all captured resources and values.</returns>
|
||||
public static ImmutableArray<FieldInfo> GetInfo(
|
||||
ITypeSymbol structDeclarationSymbol,
|
||||
out int root32BitConstantCount,
|
||||
out ImmutableArray<Diagnostic> diagnostics)
|
||||
{
|
||||
// Helper method that uses boxes instead of ref-s (illegal in enumerators)
|
||||
static IEnumerable<FieldInfo> GetCapturedFieldInfos(
|
||||
ITypeSymbol currentTypeSymbol,
|
||||
ImmutableArray<string> fieldPath,
|
||||
StrongBox<int> rawDataOffset)
|
||||
{
|
||||
bool isFirstField = true;
|
||||
|
||||
foreach (
|
||||
IFieldSymbol fieldSymbol in
|
||||
from fieldSymbol in currentTypeSymbol.GetMembers().OfType<IFieldSymbol>()
|
||||
where fieldSymbol.Type is INamedTypeSymbol { IsStatic: false } &&
|
||||
!fieldSymbol.IsConst && !fieldSymbol.IsStatic &&
|
||||
!fieldSymbol.IsFixedSizeBuffer
|
||||
select fieldSymbol)
|
||||
{
|
||||
string fieldName = fieldSymbol.Name;
|
||||
string typeName = fieldSymbol.Type.GetFullMetadataName();
|
||||
|
||||
// Disambiguates the name of target fields against the current input parameters
|
||||
if (fieldName is "loader")
|
||||
{
|
||||
fieldName = $"this.{fieldName}";
|
||||
}
|
||||
|
||||
// The first item in each nested struct needs to be aligned to 16 bytes
|
||||
if (isFirstField && fieldPath.Length > 0)
|
||||
{
|
||||
rawDataOffset.Value = AlignmentHelper.Pad(rawDataOffset.Value, 16);
|
||||
|
||||
isFirstField = false;
|
||||
}
|
||||
|
||||
if (HlslKnownTypes.IsKnownHlslType(typeName))
|
||||
{
|
||||
yield return GetHlslKnownTypeFieldInfo(fieldPath.Add(fieldName), typeName, ref rawDataOffset.Value);
|
||||
}
|
||||
else if (fieldSymbol.Type.IsUnmanagedType)
|
||||
{
|
||||
// Custom struct type defined by the user
|
||||
foreach (var fieldInfo in GetCapturedFieldInfos(fieldSymbol.Type, fieldPath.Add(fieldName), rawDataOffset))
|
||||
{
|
||||
yield return fieldInfo;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ImmutableArray<Diagnostic>.Builder builder = ImmutableArray.CreateBuilder<Diagnostic>();
|
||||
|
||||
// Setup the resource and byte offsets for tracking
|
||||
StrongBox<int> rawDataOffsetAsBox = new();
|
||||
|
||||
// Traverse all shader fields and gather info, and update the tracking offsets
|
||||
ImmutableArray<FieldInfo> fieldInfos = GetCapturedFieldInfos(
|
||||
structDeclarationSymbol,
|
||||
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);
|
||||
|
||||
// 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;
|
||||
|
||||
if (rootSignatureDwordSize > 64)
|
||||
{
|
||||
builder.Add(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol);
|
||||
}
|
||||
|
||||
diagnostics = builder.ToImmutable();
|
||||
|
||||
return fieldInfos;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets info on a given captured HLSL primitive type (either a scalar, a vector or a matrix).
|
||||
/// </summary>
|
||||
/// <param name="fieldPath">The current path of the field with respect to the shader instance.</param>
|
||||
/// <param name="typeName">The type name currently being read.</param>
|
||||
/// <param name="rawDataOffset">The current offset within the loaded data buffer.</param>
|
||||
private static FieldInfo GetHlslKnownTypeFieldInfo(
|
||||
ImmutableArray<string> fieldPath,
|
||||
string typeName,
|
||||
ref int rawDataOffset)
|
||||
{
|
||||
// For scalar, vector and linear matrix types, serialize the value normally.
|
||||
// Only the initial alignment needs to be considered, while data is packed.
|
||||
var (fieldSize, fieldPack) = HlslKnownSizes.GetTypeInfo(typeName);
|
||||
|
||||
// Check if the current type is a matrix type with more than one row. In this
|
||||
// case, each row is aligned as if it was a separate array, so the start of
|
||||
// each row needs to be at a multiple of 16 bytes (a float4 register).
|
||||
if (HlslKnownTypes.IsNonLinearMatrixType(typeName, out string? elementName, out int rows, out int columns))
|
||||
{
|
||||
ImmutableArray<int>.Builder builder = ImmutableArray.CreateBuilder<int>(rows);
|
||||
|
||||
for (int j = 0; j < rows; j++)
|
||||
{
|
||||
int startingRawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
|
||||
|
||||
builder.Add(startingRawDataOffset);
|
||||
|
||||
rawDataOffset = startingRawDataOffset + fieldPack * columns;
|
||||
}
|
||||
|
||||
return new FieldInfo.NonLinearMatrix(
|
||||
fieldPath,
|
||||
typeName,
|
||||
elementName!,
|
||||
rows,
|
||||
columns,
|
||||
builder.MoveToImmutable());
|
||||
}
|
||||
else
|
||||
{
|
||||
// Calculate the right offset with 16-bytes padding (HLSL constant buffer).
|
||||
// Since we're in a constant buffer, we need to both pad the starting offset
|
||||
// to be aligned to the packing size of the type, and also to align the initial
|
||||
// offset to ensure that values do not cross 16 bytes boundaries either.
|
||||
int startingRawDataOffset = AlignmentHelper.AlignToBoundary(
|
||||
AlignmentHelper.Pad(rawDataOffset, fieldPack),
|
||||
fieldSize,
|
||||
16);
|
||||
|
||||
rawDataOffset = startingRawDataOffset + fieldSize;
|
||||
|
||||
return new FieldInfo.Primitive(fieldPath, typeName, startingRawDataOffset);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
-9
@@ -1,30 +1,27 @@
|
||||
using System.Collections.Generic;
|
||||
using ComputeSharp.D2D1Interop.__Internals;
|
||||
using ComputeSharp.D2D1Interop.SourceGenerators.Models;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
|
||||
|
||||
#pragma warning disable CS0618
|
||||
|
||||
namespace ComputeSharp.D2D1Interop.SourceGenerators;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public sealed partial class ID2D1ShaderGenerator
|
||||
partial class ID2D1ShaderGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the shader type for a given shader, if any.
|
||||
/// </summary>
|
||||
/// <param name="typeSymbol">The input <see cref="INamedTypeSymbol"/> instance to check.</param>
|
||||
/// <param name="d2D1ShaderSymbol">The <see cref="INamedTypeSymbol"/> instance for <see cref="ID2D1Shader"/>.</param>
|
||||
/// <returns>Whether or not <paramref name="typeSymbol"/> implements <paramref name="d2D1ShaderSymbol"/>.</returns>
|
||||
private static bool IsD2D1ShaderType(INamedTypeSymbol typeSymbol, INamedTypeSymbol d2D1ShaderSymbol)
|
||||
/// <param name="d2D1PixelShaderSymbol">The <see cref="INamedTypeSymbol"/> instance for <see cref="ID2D1PixelShader"/>.</param>
|
||||
/// <returns>Whether or not <paramref name="typeSymbol"/> implements <paramref name="d2D1PixelShaderSymbol"/>.</returns>
|
||||
private static bool IsD2D1PixelShaderType(INamedTypeSymbol typeSymbol, INamedTypeSymbol d2D1PixelShaderSymbol)
|
||||
{
|
||||
foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.Interfaces)
|
||||
{
|
||||
if (interfaceSymbol.Name == nameof(ID2D1Shader) &&
|
||||
SymbolEqualityComparer.Default.Equals(interfaceSymbol, d2D1ShaderSymbol))
|
||||
if (interfaceSymbol.Name == nameof(ID2D1PixelShader) &&
|
||||
SymbolEqualityComparer.Default.Equals(interfaceSymbol, d2D1PixelShaderSymbol))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
using System.Collections.Immutable;
|
||||
using ComputeSharp.D2D1Interop.SourceGenerators.Diagnostics;
|
||||
using ComputeSharp.D2D1Interop.SourceGenerators.Extensions;
|
||||
using ComputeSharp.D2D1Interop.SourceGenerators.Models;
|
||||
using Microsoft.CodeAnalysis;
|
||||
using Microsoft.CodeAnalysis.CSharp;
|
||||
using Microsoft.CodeAnalysis.CSharp.Syntax;
|
||||
|
||||
namespace ComputeSharp.D2D1Interop.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A source generator creating data loaders for the <see cref="ID2D1PixelShader"/> type.
|
||||
/// </summary>
|
||||
[Generator]
|
||||
public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||
{
|
||||
// Check whether [SkipLocalsInit] can be used
|
||||
IncrementalValueProvider<bool> canUseSkipLocalsInit =
|
||||
context.CompilationProvider
|
||||
.Select(static (compilation, token) =>
|
||||
compilation.Options is CSharpCompilationOptions { AllowUnsafe: true } &&
|
||||
compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.SkipLocalsInitAttribute") is not null);
|
||||
|
||||
// Get all declared struct types and their type symbols
|
||||
IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol)> structDeclarations =
|
||||
context.SyntaxProvider
|
||||
.CreateSyntaxProvider(
|
||||
static (node, token) => node is StructDeclarationSyntax structDeclaration,
|
||||
static (context, token) => (
|
||||
(StructDeclarationSyntax)context.Node,
|
||||
Symbol: (INamedTypeSymbol?)context.SemanticModel.GetDeclaredSymbol(context.Node, token)))
|
||||
.Where(static pair => pair.Symbol is { Interfaces.IsEmpty: false })!;
|
||||
|
||||
// Get the symbol for the ID2D1PixelShader interface
|
||||
IncrementalValueProvider<INamedTypeSymbol> pixelShaderInterface =
|
||||
context.CompilationProvider
|
||||
.Select(static (compilation, token) => compilation.GetTypeByMetadataName(typeof(ID2D1PixelShader).FullName)!);
|
||||
|
||||
// Filter struct declarations that implement the shader interface, and also gather the hierarchy info
|
||||
IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol, HierarchyInfo Hierarchy)> shaderDeclarations =
|
||||
structDeclarations
|
||||
.Combine(pixelShaderInterface)
|
||||
.Where(static item => IsD2D1PixelShaderType(item.Left.Symbol, item.Right))
|
||||
.Select(static (item, token) => (item.Left.Syntax, item.Left.Symbol, HierarchyInfo.From(item.Left.Symbol)));
|
||||
|
||||
// Get the dispatch data, HLSL source and embedded bytecode info. This info is computed on the
|
||||
// same step as parts are shared in following sub-branches in the incremental generator pipeline.
|
||||
IncrementalValuesProvider<(Result<DispatchDataInfo> Dispatch, Result<HlslShaderSourceInfo> Hlsl, Result<ThreadIdsInfo> ThreadIds)> shaderInfoWithErrors =
|
||||
shaderDeclarations
|
||||
.Combine(context.CompilationProvider)
|
||||
.Select(static (item, token) =>
|
||||
{
|
||||
// LoadDispatchData() info
|
||||
ImmutableArray<FieldInfo> fieldInfos = LoadDispatchData.GetInfo(
|
||||
item.Left.Symbol,
|
||||
out int root32BitConstantCount,
|
||||
out ImmutableArray<Diagnostic> dispatchDataDiagnostics);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
DispatchDataInfo dispatchDataInfo = new(
|
||||
item.Left.Hierarchy,
|
||||
fieldInfos,
|
||||
root32BitConstantCount);
|
||||
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// TODO
|
||||
|
||||
return (
|
||||
new Result<DispatchDataInfo>(dispatchDataInfo, dispatchDataDiagnostics),
|
||||
new Result<HlslShaderSourceInfo>(null!, ImmutableArray<Diagnostic>.Empty),
|
||||
new Result<ThreadIdsInfo>(null!, ImmutableArray<Diagnostic>.Empty));
|
||||
});
|
||||
|
||||
// Output the diagnostics
|
||||
context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.Dispatch.Errors));
|
||||
context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.Hlsl.Errors));
|
||||
context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.ThreadIds.Errors));
|
||||
|
||||
// Filter all items to enable caching at a coarse level, and remove diagnostics
|
||||
IncrementalValuesProvider<(DispatchDataInfo Dispatch, HlslShaderSourceInfo Hlsl, ThreadIdsInfo ThreadIds)> shaderInfo =
|
||||
shaderInfoWithErrors
|
||||
.Select(static (item, token) => (item.Dispatch.Value, item.Hlsl.Value, item.ThreadIds.Value))
|
||||
.WithComparers(DispatchDataInfo.Comparer.Default, HlslShaderSourceInfo.Comparer.Default, ThreadIdsInfo.Comparer.Default);
|
||||
|
||||
// Get a filtered sequence to enable caching
|
||||
IncrementalValuesProvider<DispatchDataInfo> dispatchDataInfo =
|
||||
shaderInfo
|
||||
.Select(static (item, token) => item.Dispatch)
|
||||
.WithComparer(DispatchDataInfo.Comparer.Default);
|
||||
|
||||
// Generate the LoadDispatchData() methods
|
||||
context.RegisterSourceOutput(dispatchDataInfo.Combine(canUseSkipLocalsInit), static (context, item) =>
|
||||
{
|
||||
MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax(item.Left.FieldInfos, item.Left.Root32BitConstantCount);
|
||||
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, loadDispatchDataMethod, item.Right);
|
||||
|
||||
context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadDispatchData)}", compilationUnit.ToFullString());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace ComputeSharp.D2D1Interop.SourceGenerators;
|
||||
|
||||
/// <summary>
|
||||
/// A source generator creating data loaders for the <see cref="ID2D1PixelShader"/> type.
|
||||
/// </summary>
|
||||
[Generator]
|
||||
public sealed partial class IShaderGenerator : IIncrementalGenerator
|
||||
{
|
||||
/// <inheritdoc/>
|
||||
public void Initialize(IncrementalGeneratorInitializationContext context)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
@@ -9,15 +9,11 @@ namespace ComputeSharp.D2D1Interop.SourceGenerators.Models;
|
||||
/// A model representing gathered info on a shader dispatch data.
|
||||
/// </summary>
|
||||
/// <param name="Hierarchy">The hierarchy data for the shader.</param>
|
||||
/// <param name="Type">The shader interface type.</param>
|
||||
/// <param name="FieldInfos">The description on shader instance fields.</param>
|
||||
/// <param name="ResourceCount">The total number of captured resources.</param>
|
||||
/// <param name="Root32BitConstantCount">The size of the shader root signature, in 32 bit constants.</param>
|
||||
internal sealed record DispatchDataInfo(
|
||||
HierarchyInfo Hierarchy,
|
||||
Type Type,
|
||||
ImmutableArray<FieldInfo> FieldInfos,
|
||||
int ResourceCount,
|
||||
int Root32BitConstantCount)
|
||||
{
|
||||
/// <summary>
|
||||
@@ -50,9 +46,7 @@ internal sealed record DispatchDataInfo(
|
||||
|
||||
return
|
||||
HierarchyInfo.Comparer.Default.Equals(x.Hierarchy, y.Hierarchy) &&
|
||||
x.Type == y.Type &&
|
||||
x.FieldInfos.SequenceEqual(y.FieldInfos, FieldInfo.Comparer.Default) &&
|
||||
x.ResourceCount == y.ResourceCount &&
|
||||
x.Root32BitConstantCount == y.Root32BitConstantCount;
|
||||
}
|
||||
|
||||
@@ -62,9 +56,7 @@ internal sealed record DispatchDataInfo(
|
||||
HashCode hashCode = default;
|
||||
|
||||
hashCode.Add(HierarchyInfo.Comparer.Default.GetHashCode(obj.Hierarchy));
|
||||
hashCode.Add(obj.Type);
|
||||
hashCode.AddRange(obj.FieldInfos, FieldInfo.Comparer.Default);
|
||||
hashCode.Add(obj.ResourceCount);
|
||||
hashCode.Add(obj.Root32BitConstantCount);
|
||||
|
||||
return hashCode.ToHashCode();
|
||||
|
||||
新しいイシューから参照
ユーザーをブロックする