Remove symbols from IShaderGenerator pipeline

このコミットが含まれているのは:
Sergio Pedri committed 2022-09-17 20:35:38 +02:00
1 親 9eac3c779d
コミット a205efe6fa
9ファイル変更
+283 -203

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

+11 -12
ファイルの表示
@@ -18,10 +18,9 @@ partial class IShaderGenerator
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.
/// </summary>
/// <param name="delegateFieldNames">The names of all <see cref="System.Delegate"/> instance fields within the current shader type.</param>\
/// <param name="supportsDynamicShaders">Indicates whether or not dynamic shaders are supported.</param>
/// <param name="delegateFieldNames">The names of all <see cref="System.Delegate"/> instance fields within the current shader type.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(ImmutableArray<string> delegateFieldNames, bool supportsDynamicShaders)
public static MethodDeclarationSyntax GetSyntax(ImmutableArray<string> delegateFieldNames)
{
// This code produces a method declaration as follows:
//
@@ -35,18 +34,17 @@ partial class IShaderGenerator
Identifier("GetDispatchId"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.WithBody(GetShaderHashCodeBody(delegateFieldNames, supportsDynamicShaders));
.WithBody(GetShaderHashCodeBody(delegateFieldNames));
}
/// <summary>
/// Gets a <see cref="BlockSyntax"/> instance with the logic to compute the hashcode of a given shader type.
/// </summary>
/// <param name="delegateFieldNames">The names of all <see cref="System.Delegate"/> instance fields within the current shader type.</param>
/// <param name="supportsDynamicShaders">Indicates whether or not dynamic shaders are supported.</param>
/// <returns>The <see cref="BlockSyntax"/> instance to hash the input shader.</returns>
private static BlockSyntax GetShaderHashCodeBody(ImmutableArray<string> delegateFieldNames, bool supportsDynamicShaders)
private static BlockSyntax GetShaderHashCodeBody(ImmutableArray<string> delegateFieldNames)
{
if (delegateFieldNames.Length == 0 || !supportsDynamicShaders)
if (delegateFieldNames.Length == 0)
{
// return 0;
return
@@ -56,17 +54,18 @@ partial class IShaderGenerator
Literal(0))));
}
List<StatementSyntax> blockStatements = new(4);
// global::System.HashCode hashCode = default;
blockStatements.Add(LocalDeclarationStatement(
List<StatementSyntax> blockStatements = new(4)
{
// global::System.HashCode hashCode = default;
LocalDeclarationStatement(
VariableDeclaration(IdentifierName("global::System.HashCode"))
.AddVariables(
VariableDeclarator(Identifier("hashCode"))
.WithInitializer(EqualsValueClause(
LiteralExpression(
SyntaxKind.DefaultLiteralExpression,
Token(SyntaxKind.DefaultKeyword)))))));
Token(SyntaxKind.DefaultKeyword))))))
};
foreach (string fieldName in delegateFieldNames)
{
@@ -1,5 +1,4 @@
using System;
using System.Collections.Immutable;
using System.Collections.Immutable;
using ComputeSharp.__Internals;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis.CSharp;
@@ -19,13 +18,13 @@ partial class IShaderGenerator
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.
/// </summary>
/// <param name="shaderInterfaceType">The type of shader interface urrently being processed.</param>
/// <param name="shaderType">The type of shader interface currently being processed.</param>
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
/// <param name="resourceCount">The total number of captured resources in the shader.</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(
Type shaderInterfaceType,
ShaderType shaderType,
ImmutableArray<FieldInfo> fieldInfos,
int resourceCount,
int root32BitConstantsCount)
@@ -51,25 +50,25 @@ partial class IShaderGenerator
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(shaderInterfaceType, fieldInfos, resourceCount, root32BitConstantsCount)));
.WithBody(Block(GetDispatchDataLoadingStatements(shaderType, fieldInfos, resourceCount, root32BitConstantsCount)));
}
/// <summary>
/// Gets a sequence of statements to load the dispatch data for a given shader.
/// </summary>
/// <param name="shaderInterfaceType">The type of shader interface urrently being processed.</param>
/// <param name="shaderType">The type of shader interface currently being processed.</param>
/// <param name="fieldInfos">The array of <see cref="FieldInfo"/> values for all captured fields.</param>
/// <param name="resourceCount">The total number of captured resources in the shader.</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(
Type shaderInterfaceType,
ShaderType shaderType,
ImmutableArray<FieldInfo> fieldInfos,
int resourceCount,
int root32BitConstantsCount)
{
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
bool isComputeShader = shaderInterfaceType == typeof(IComputeShader);
bool isComputeShader = shaderType == ShaderType.ComputeShader;
// Append the statements for the dispatch ranges:
//
+3 -3
ファイルの表示
@@ -25,14 +25,14 @@ partial class IShaderGenerator
/// Explores a given type hierarchy and generates statements to load fields.
/// </summary>
/// <param name="structDeclarationSymbol">The current shader type being explored.</param>
/// <param name="shaderInterfaceType">The type of shader interface urrently being processed.</param>
/// <param name="shaderType">The type of shader currently being processed.</param>
/// <param name="resourceCount">The total number of captured resources in the shader.</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,
Type shaderInterfaceType,
ShaderType shaderType,
out int resourceCount,
out int root32BitConstantCount,
out ImmutableArray<DiagnosticInfo> diagnostics)
@@ -92,7 +92,7 @@ partial class IShaderGenerator
// Setup the resource and byte offsets for tracking. Pixel shaders have only two
// implicitly captured int values, as they're always dispatched over a 2D texture.
bool isComputeShader = shaderInterfaceType == typeof(IComputeShader);
bool isComputeShader = shaderType == ShaderType.ComputeShader;
int initialRawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2);
StrongBox<int> resourceOffsetAsBox = new();
StrongBox<int> rawDataOffsetAsBox = new(initialRawDataOffset);
+30 -17
ファイルの表示
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using ComputeSharp.SourceGeneration.Models;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -15,33 +16,45 @@ partial class IShaderGenerator
/// 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="iComputeShaderSymbol">The <see cref="INamedTypeSymbol"/> instance for <see cref="IComputeShader"/>.</param>
/// <param name="iPixelShaderSymbol">The <see cref="INamedTypeSymbol"/> instance for <see cref="IPixelShader{TPixel}"/>.</param>
/// <returns>Either <see cref="IComputeShader"/> or <see cref="IPixelShader{TPixel}"/>, or <see langword="null"/>.</returns>
private static Type? GetShaderType(
INamedTypeSymbol typeSymbol,
INamedTypeSymbol iComputeShaderSymbol,
INamedTypeSymbol iPixelShaderSymbol)
/// <param name="compilation">The <see cref="Compilation"/> instance currently in use.</param>
/// <returns>The shader type for <paramref name="typeSymbol"/>, or <see langword="null"/>.</returns>
private static ShaderType? GetShaderType(INamedTypeSymbol typeSymbol, Compilation compilation)
{
foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.AllInterfaces)
{
if (interfaceSymbol.Name == nameof(IComputeShader) &&
SymbolEqualityComparer.Default.Equals(interfaceSymbol, iComputeShaderSymbol))
if (interfaceSymbol.Name == nameof(IComputeShader))
{
return typeof(IComputeShader);
}
INamedTypeSymbol computeShaderSymbol = compilation.GetTypeByMetadataName("ComputeSharp.IComputeShader")!;
if (interfaceSymbol.IsGenericType &&
interfaceSymbol.Name == nameof(IPixelShader<byte>) &&
SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, iPixelShaderSymbol))
if (SymbolEqualityComparer.Default.Equals(interfaceSymbol, computeShaderSymbol))
{
return ShaderType.ComputeShader;
}
}
else if (interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) })
{
return typeof(IPixelShader<>);
INamedTypeSymbol pixelShaderSymbol = compilation.GetTypeByMetadataName("ComputeSharp.IPixelShader`1")!;
if (SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, pixelShaderSymbol))
{
return ShaderType.PixelShader;
}
}
}
return null;
}
/// <summary>
/// Checks whether dynamic shaders are supported in a given compilation.
/// </summary>
/// <param name="compilation">The <see cref="Compilation"/> instance currently in use.</param>
/// <returns>Whether dynamic shaders are supported in the input compilation.</returns>
private static bool IsDynamicCompilationSupported(Compilation compilation)
{
return compilation.ReferencedAssemblyNames.Any(static identity => identity.Name is "ComputeSharp.Dynamic");
}
/// <summary>
/// Creates a <see cref="CompilationUnitSyntax"/> instance wrapping the given method.
/// </summary>
+139 -148
ファイルの表示
@@ -25,188 +25,178 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
// Check whether [SkipLocalsInit] can be used
IncrementalValueProvider<bool> canUseSkipLocalsInit =
context.CompilationProvider
.Select(static (compilation, token) =>
.Select(static (compilation, _) =>
compilation.Options is CSharpCompilationOptions { AllowUnsafe: true } &&
compilation.HasAccessibleTypeWithMetadataName("System.Runtime.CompilerServices.SkipLocalsInitAttribute"));
// Check whether or not dynamic shaders are supported
IncrementalValueProvider<bool> supportsDynamicShaders =
context.CompilationProvider
.Select(static (compilation, token) => compilation.ReferencedAssemblyNames.Any(
static identity => identity.Name is "ComputeSharp.Dynamic"));
.Select(static (compilation, _) => IsDynamicCompilationSupported(compilation));
// Get all declared struct types and their type symbols
IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol)> structDeclarations =
// Discover all shader types and extract all the necessary info from each of them
IncrementalValuesProvider<ShaderInfo> shaderInfoWithErrors =
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 })!;
static (node, _) => node.IsTypeDeclarationWithOrPotentiallyWithBaseTypes<StructDeclarationSyntax>(),
static (context, token) =>
{
StructDeclarationSyntax typeDeclaration = (StructDeclarationSyntax)context.Node;
// Get the symbol for the IComputeShader and IPixelShader<TPixel> interfaces
IncrementalValueProvider<(INamedTypeSymbol Compute, INamedTypeSymbol Pixel) > shaderInterfaces =
context.CompilationProvider
.Select(static (compilation, token) => (
Compute: compilation.GetTypeByMetadataName(typeof(IComputeShader).FullName)!,
Pixel: compilation.GetTypeByMetadataName(typeof(IPixelShader<>).FullName)!));
// If the type symbol doesn't have at least one interface, it can't possibly be a shader type
if (context.SemanticModel.GetDeclaredSymbol(typeDeclaration, token) is not INamedTypeSymbol { AllInterfaces.Length: > 0 } typeSymbol)
{
return default;
}
// Filter struct declarations that implement a shader interface, and also gather the hierarchy info and shader type
IncrementalValuesProvider<(StructDeclarationSyntax Syntax, INamedTypeSymbol Symbol, HierarchyInfo Hierarchy, Type Type)> shaderDeclarations =
structDeclarations
.Combine(shaderInterfaces)
.Select(static (item, token) => (item.Left, Type: GetShaderType(item.Left.Symbol, item.Right.Compute, item.Right.Pixel)))
.Where(static item => item.Type is not null)
.Select(static (item, token) => (item.Left.Syntax, item.Left.Symbol, HierarchyInfo.From(item.Left.Symbol), item.Type!));
// Get the shader type, or return if none is present
if (GetShaderType(typeSymbol, context.SemanticModel.Compilation) is not ShaderType shaderType)
{
return default;
}
// Get the hierarchy info and delegate field names for each shader type
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchIdInfo Info)> hierarchyAndDispatchIdInfo =
shaderDeclarations
.Select(static (item, token) => (item.Hierarchy, new DispatchIdInfo(GetDispatchId.GetInfo(item.Symbol))));
ImmutableArray<DiagnosticInfo>.Builder diagnostics = ImmutableArray.CreateBuilder<DiagnosticInfo>();
// GetDispatchId() info
ImmutableArray<string> dispatchIdInfo = GetDispatchId.GetInfo(typeSymbol);
token.ThrowIfCancellationRequested();
// LoadDispatchData() info
ImmutableArray<FieldInfo> fieldInfos = LoadDispatchData.GetInfo(
typeSymbol,
shaderType,
out int resourceCount,
out int root32BitConstantCount,
out ImmutableArray<DiagnosticInfo> dispatchDataDiagnostics);
token.ThrowIfCancellationRequested();
// BuildHlslSource() info
HlslShaderSourceInfo hlslSourceInfo = BuildHlslSource.GetInfo(
context.SemanticModel.Compilation,
typeDeclaration,
typeSymbol,
out ImmutableArray<DiagnosticInfo> hlslSourceDiagnostics);
token.ThrowIfCancellationRequested();
// GetDispatchMetadata() info
DispatchMetadataInfo dispatchMetadataInfo = LoadDispatchMetadata.GetInfo(
root32BitConstantCount,
hlslSourceInfo.ImplicitTextureType is not null,
hlslSourceInfo.IsSamplerUsed,
fieldInfos);
token.ThrowIfCancellationRequested();
// TryGetBytecode() info
ThreadIdsInfo threadIds = LoadBytecode.GetInfo(
typeSymbol,
!hlslSourceInfo.Delegates.IsEmpty,
IsDynamicCompilationSupported(context.SemanticModel.Compilation),
out ImmutableArray<DiagnosticInfo> threadIdsDiagnostics);
token.ThrowIfCancellationRequested();
// Ensure the bytecode generation is disabled if any errors are present
if (!dispatchDataDiagnostics.IsDefaultOrEmpty ||
!hlslSourceDiagnostics.IsDefaultOrEmpty)
{
threadIds = new ThreadIdsInfo(true, 0, 0, 0);
}
return new ShaderInfo(
Hierarchy: HierarchyInfo.From(typeSymbol),
DispatchId: new DispatchIdInfo(dispatchIdInfo),
DispatchData: new DispatchDataInfo(
shaderType,
fieldInfos,
resourceCount,
root32BitConstantCount),
DispatchMetadata: dispatchMetadataInfo,
HlslShaderSource: hlslSourceInfo,
ThreadIds: threadIds,
Diagnostcs: diagnostics.ToImmutable());
})
.Where(static item => item is not null)!;
// Output the diagnostics, if any
context.ReportDiagnostics(
shaderInfoWithErrors
.Select(static (item, _) => item.Diagnostcs)
.WithComparer(EqualityComparer<DiagnosticInfo>.Default.ForImmutableArray()));
// Get the GetDispatchId() info (hierarchy and dispatch id info)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchIdInfo DispatchId)> dispatchIdInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.DispatchId));
// Generate the GetDispatchId() methods
context.RegisterSourceOutput(hierarchyAndDispatchIdInfo.Combine(supportsDynamicShaders), static (context, item) =>
context.RegisterSourceOutput(dispatchIdInfo, static (context, item) =>
{
MethodDeclarationSyntax getDispatchIdMethod = GetDispatchId.GetSyntax(item.Left.Info.Delegates, item.Right);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, getDispatchIdMethod, canUseSkipLocalsInit: false);
MethodDeclarationSyntax getDispatchIdMethod = GetDispatchId.GetSyntax(item.DispatchId.Delegates);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getDispatchIdMethod, canUseSkipLocalsInit: false);
context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(GetDispatchId)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
context.AddSource($"{item.Hierarchy.FilenameHint}.{nameof(GetDispatchId)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// 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(supportsDynamicShaders)
.Combine(context.CompilationProvider)
.Select(static (item, token) =>
{
// LoadDispatchData() info
ImmutableArray<FieldInfo> fieldInfos = LoadDispatchData.GetInfo(
item.Left.Left.Symbol,
item.Left.Left.Type,
out int resourceCount,
out int root32BitConstantCount,
out ImmutableArray<DiagnosticInfo> dispatchDataDiagnostics);
token.ThrowIfCancellationRequested();
DispatchDataInfo dispatchDataInfo = new(
item.Left.Left.Hierarchy,
item.Left.Left.Type,
fieldInfos,
resourceCount,
root32BitConstantCount);
token.ThrowIfCancellationRequested();
// BuildHlslSource() info
HlslShaderSourceInfo hlslSourceInfo = BuildHlslSource.GetInfo(
item.Right,
item.Left.Left.Syntax,
item.Left.Left.Symbol,
out ImmutableArray<DiagnosticInfo> hlslSourceDiagnostics);
token.ThrowIfCancellationRequested();
// TryGetBytecode() info
ThreadIdsInfo threadIds = LoadBytecode.GetInfo(
item.Left.Left.Symbol,
!hlslSourceInfo.Delegates.IsEmpty,
item.Left.Right,
out ImmutableArray<DiagnosticInfo> threadIdsDiagnostics);
token.ThrowIfCancellationRequested();
// Ensure the bytecode generation is disabled if any errors are present
if (!dispatchDataDiagnostics.IsDefaultOrEmpty ||
!hlslSourceDiagnostics.IsDefaultOrEmpty)
{
threadIds = new ThreadIdsInfo(true, 0, 0, 0);
}
return (
new Result<DispatchDataInfo>(dispatchDataInfo, dispatchDataDiagnostics),
new Result<HlslShaderSourceInfo>(hlslSourceInfo, hlslSourceDiagnostics),
new Result<ThreadIdsInfo>(threadIds, threadIdsDiagnostics));
});
// 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 =
// Get the LoadDispatchData() info (hierarchy and dispatch data info)
IncrementalValuesProvider<((HierarchyInfo Hierarchy, DispatchDataInfo DispatchData) Info, bool CanUseSkipLocalsInit) > dispatchDataInfo =
shaderInfoWithErrors
.Select(static (item, token) => (item.Dispatch.Value, item.Hlsl.Value, item.ThreadIds.Value));
// Get a filtered sequence to enable caching
IncrementalValuesProvider<DispatchDataInfo> dispatchDataInfo =
shaderInfo
.Select(static (item, token) => item.Dispatch);
.Select(static (item, _) => (item.Hierarchy, item.DispatchData))
.Combine(canUseSkipLocalsInit);
// Generate the LoadDispatchData() methods
context.RegisterSourceOutput(dispatchDataInfo.Combine(canUseSkipLocalsInit), static (context, item) =>
context.RegisterSourceOutput(dispatchDataInfo, static (context, item) =>
{
MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax(
item.Left.Type,
item.Left.FieldInfos,
item.Left.ResourceCount,
item.Left.Root32BitConstantCount);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, loadDispatchDataMethod, canUseSkipLocalsInit: item.Right);
item.Info.DispatchData.Type,
item.Info.DispatchData.FieldInfos,
item.Info.DispatchData.ResourceCount,
item.Info.DispatchData.Root32BitConstantCount);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Info.Hierarchy, loadDispatchDataMethod, item.CanUseSkipLocalsInit);
context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadDispatchData)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
context.AddSource($"{item.Info.Hierarchy.FilenameHint}.{nameof(LoadDispatchData)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Get the filtered sequence to enable caching
IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo SourceInfo, bool SupportsDynamicShaders)> hlslSourceInfo =
shaderInfo
.Combine(supportsDynamicShaders)
.Select(static (item, token) => (item.Left.Dispatch.Hierarchy, item.Left.Hlsl, item.Right));
// Get the BuildHlslSource info (hierarchy, HLSL source and parsing options)
IncrementalValuesProvider<((HierarchyInfo Hierarchy, HlslShaderSourceInfo HlslShaderSource) Info, (bool CanUseSkipLocalsInit, bool SupportsDynamicShaders) Options)> hlslSourceInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.HlslShaderSource))
.Combine(canUseSkipLocalsInit.Combine(supportsDynamicShaders));
// Generate the BuildHlslSource() methods
context.RegisterSourceOutput(hlslSourceInfo.Combine(canUseSkipLocalsInit), static (context, item) =>
context.RegisterSourceOutput(hlslSourceInfo, static (context, item) =>
{
MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.Left.SourceInfo, item.Left.SupportsDynamicShaders, item.Left.Hierarchy.Hierarchy.Length);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, canUseSkipLocalsInit: item.Right);
MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.Info.HlslShaderSource, item.Options.SupportsDynamicShaders, item.Info.Hierarchy.Hierarchy.Length);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Info.Hierarchy, buildHlslStringMethod, item.Options.CanUseSkipLocalsInit);
context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(BuildHlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
context.AddSource($"{item.Info.Hierarchy.FilenameHint}.{nameof(BuildHlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Get the dispatch metadata info
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchMetadataInfo MetadataInfo)> dispatchMetadataInfo =
shaderInfo
.Select(static (item, token) =>
{
DispatchMetadataInfo dispatchMetadataInfo = LoadDispatchMetadata.GetInfo(
item.Dispatch.Root32BitConstantCount,
item.Hlsl.ImplicitTextureType is not null,
item.Hlsl.IsSamplerUsed,
item.Dispatch.FieldInfos);
token.ThrowIfCancellationRequested();
return (item.Dispatch.Hierarchy, dispatchMetadataInfo);
});
// Get the LoadDispatchMetadata() info (hierarchy and dispatch metadata info)
IncrementalValuesProvider<((HierarchyInfo Hierarchy, DispatchMetadataInfo DispatchMetadata) Info, bool CanUseSkipLocalsInit)> dispatchMetadataInfo =
shaderInfoWithErrors
.Select(static (item, _) => (item.Hierarchy, item.DispatchMetadata))
.Combine(canUseSkipLocalsInit);
// Generate the LoadDispatchMetadata() methods
context.RegisterSourceOutput(dispatchMetadataInfo.Combine(canUseSkipLocalsInit), static (context, item) =>
context.RegisterSourceOutput(dispatchMetadataInfo, static (context, item) =>
{
MethodDeclarationSyntax buildHlslStringMethod = LoadDispatchMetadata.GetSyntax(item.Left.MetadataInfo);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, canUseSkipLocalsInit: item.Right);
MethodDeclarationSyntax buildHlslStringMethod = LoadDispatchMetadata.GetSyntax(item.Info.DispatchMetadata);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Info.Hierarchy, buildHlslStringMethod, item.CanUseSkipLocalsInit);
context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadDispatchMetadata)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
context.AddSource($"{item.Info.Hierarchy.FilenameHint}.{nameof(LoadDispatchMetadata)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Transform the raw HLSL source to compile
// Transform the raw HLSL source to compile (this step aggregates the HLSL source to ensure compilation is only done for actual HLSL changes)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, string Hlsl, ThreadIdsInfo ThreadIds)> shaderBytecodeInfo =
shaderInfo
.Select(static (item, token) => (item.Dispatch.Hierarchy, BuildHlslSource.GetNonDynamicHlslSource(item.Hlsl), item.ThreadIds));
shaderInfoWithErrors
.Select(static (item, token) => (item.Hierarchy, BuildHlslSource.GetNonDynamicHlslSource(item.HlslShaderSource), item.ThreadIds));
// Compile the requested shader bytecodes
IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo, DeferredDiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors =
IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo EmbeddedBytecode, DeferredDiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors =
shaderBytecodeInfo
.Select(static (item, token) =>
{
@@ -239,19 +229,20 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
// Output the diagnostics
context.ReportDiagnostics(embeddedBytecodeDiagnostics);
// Get the filtered sequence to enable caching
IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo)> embeddedBytecode =
// Get the TryGetBytecode() info (hierarchy and compiled bytecode)
IncrementalValuesProvider<((HierarchyInfo Hierarchy, EmbeddedBytecodeInfo EmbeddedBytecode) Info, bool SupportsDynamicShaders)> embeddedBytecodeInfo =
embeddedBytecodeWithErrors
.Select(static (item, token) => (item.Hierarchy, item.BytecodeInfo));
.Select(static (item, token) => (item.Hierarchy, item.EmbeddedBytecode))
.Combine(supportsDynamicShaders);
// Generate the TryGetBytecode() methods
context.RegisterSourceOutput(embeddedBytecode.Combine(supportsDynamicShaders), static (context, item) =>
context.RegisterSourceOutput(embeddedBytecodeInfo, static (context, item) =>
{
MethodDeclarationSyntax tryGetBytecodeMethod = LoadBytecode.GetSyntax(item.Left.BytecodeInfo, item.Right, out Func<SyntaxNode, SourceText> fixup);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, tryGetBytecodeMethod, canUseSkipLocalsInit: false);
MethodDeclarationSyntax tryGetBytecodeMethod = LoadBytecode.GetSyntax(item.Info.EmbeddedBytecode, item.SupportsDynamicShaders, out Func<SyntaxNode, SourceText> fixup);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Info.Hierarchy, tryGetBytecodeMethod, canUseSkipLocalsInit: false);
SourceText text = fixup(compilationUnit);
context.AddSource($"{item.Left.Hierarchy.FilenameHint}.{nameof(LoadBytecode)}.g.cs", text);
context.AddSource($"{item.Info.Hierarchy.FilenameHint}.{nameof(LoadBytecode)}.g.cs", text);
});
}
}
+1 -6
ファイルの表示
@@ -3,21 +3,18 @@ using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Models;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// 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,
ShaderType Type,
ImmutableArray<FieldInfo> FieldInfos,
int ResourceCount,
int Root32BitConstantCount)
@@ -36,7 +33,6 @@ internal sealed record DispatchDataInfo(
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, DispatchDataInfo obj)
{
hashCode.Add(obj.Hierarchy);
hashCode.Add(obj.Type);
hashCode.AddRange(obj.FieldInfos);
hashCode.Add(obj.ResourceCount);
@@ -47,7 +43,6 @@ internal sealed record DispatchDataInfo(
protected override bool AreEqual(DispatchDataInfo x, DispatchDataInfo y)
{
return
x.Hierarchy == y.Hierarchy &&
x.Type == y.Type &&
x.FieldInfos.SequenceEqual(y.FieldInfos) &&
x.ResourceCount == y.ResourceCount &&
+65
ファイルの表示
@@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using ComputeSharp.SourceGeneration.Models;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model representing all necessary info for a full generation pass for a shader.
/// </summary>
/// <param name="Hierarchy">The hierarchy info for the shader type.</param>
/// <param name="DispatchId">The gathered dispatch id for the shader type.</param>
/// <param name="DispatchData">The gathered shader dispatch data.</param>
/// <param name="DispatchMetadata">The gathered shader dispatch metadata.</param>
/// <param name="HlslShaderSource">The processed HLSL source for the shader.</param>
/// <param name="ThreadIds">The thread ids for the shader, if compilation is requested.</param>
/// <param name="Diagnostcs">The discovered diagnostics, if any.</param>
internal sealed record ShaderInfo(
HierarchyInfo Hierarchy,
DispatchIdInfo DispatchId,
DispatchDataInfo DispatchData,
DispatchMetadataInfo DispatchMetadata,
HlslShaderSourceInfo HlslShaderSource,
ThreadIdsInfo ThreadIds,
ImmutableArray<DiagnosticInfo> Diagnostcs)
{
/// <inheritdoc/>
public bool Equals(ShaderInfo? obj) => Comparer.Default.Equals(this, obj);
/// <inheritdoc/>
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="ShaderInfo"/>.
/// </summary>
private sealed class Comparer : Comparer<ShaderInfo, Comparer>
{
/// <inheritdoc/>
protected override void AddToHashCode(ref HashCode hashCode, ShaderInfo obj)
{
hashCode.Add(obj.Hierarchy);
hashCode.Add(obj.DispatchId);
hashCode.Add(obj.DispatchData);
hashCode.Add(obj.DispatchMetadata);
hashCode.Add(obj.HlslShaderSource);
hashCode.Add(obj.ThreadIds);
hashCode.AddRange(obj.Diagnostcs);
}
/// <inheritdoc/>
protected override bool AreEqual(ShaderInfo x, ShaderInfo y)
{
return
x.Hierarchy == y.Hierarchy &&
x.DispatchId == y.DispatchId &&
x.DispatchData == y.DispatchData &&
x.DispatchMetadata == y.DispatchMetadata &&
x.HlslShaderSource == y.HlslShaderSource &&
x.ThreadIds == y.ThreadIds &&
x.Diagnostcs.SequenceEqual(y.Diagnostcs);
}
}
}
+17
ファイルの表示
@@ -0,0 +1,17 @@
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// Indicates a type of shader being processed.
/// </summary>
public enum ShaderType
{
/// <summary>
/// A compute shader.
/// </summary>
ComputeShader,
/// <summary>
/// A pixel shader.
/// </summary>
PixelShader
}