diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs
index 7d89a486..f9259a85 100644
--- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs
+++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs
@@ -22,6 +22,14 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
///
public void Initialize(IncrementalGeneratorInitializationContext context)
{
+ // Check whether [SkipLocalsInit] can be used
+ IncrementalValueProvider canUseSkipLocalsInit =
+ context.CompilationProvider
+ .Select(static (compilation, _) =>
+ compilation.Options is CSharpCompilationOptions { AllowUnsafe: true } &&
+ compilation.HasAccessibleTypeWithMetadataName("System.Runtime.CompilerServices.SkipLocalsInitAttribute"));
+
+ // Discover all shader types and extract all the necessary info from each of them
IncrementalValuesProvider shaderInfoWithErrors =
context.SyntaxProvider
.CreateSyntaxProvider(
@@ -123,14 +131,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
})
.Where(static item => item is not null)!;
- // Check whether [SkipLocalsInit] can be used
- IncrementalValueProvider canUseSkipLocalsInit =
- context.CompilationProvider
- .Select(static (compilation, _) =>
- compilation.Options is CSharpCompilationOptions { AllowUnsafe: true } &&
- compilation.HasAccessibleTypeWithMetadataName("System.Runtime.CompilerServices.SkipLocalsInitAttribute"));
-
- // Output the diagnostics
+ // Output the diagnostics, if any
context.ReportDiagnostics(
shaderInfoWithErrors
.Select(static (item, _) => item.Diagnostcs)
@@ -258,7 +259,7 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator
// Output the diagnostics
context.ReportDiagnostics(embeddedBytecodeDiagnostics);
- // Get the filtered sequence to enable caching
+ // Get the LoadBytecode() info (hierarchy and compiled bytecode)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo)> embeddedBytecode =
embeddedBytecodeWithErrors
.Select(static (item, _) => (item.Hierarchy, item.BytecodeInfo));
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs
index e2ce418e..974dcb73 100644
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs
@@ -18,10 +18,9 @@ partial class IShaderGenerator
///
/// Creates a instance for the GetDispatchId method.
///
- /// The names of all instance fields within the current shader type.\
- /// Indicates whether or not dynamic shaders are supported.
+ /// The names of all instance fields within the current shader type.
/// The resulting instance for the GetDispatchId method.
- public static MethodDeclarationSyntax GetSyntax(ImmutableArray delegateFieldNames, bool supportsDynamicShaders)
+ public static MethodDeclarationSyntax GetSyntax(ImmutableArray 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));
}
///
/// Gets a instance with the logic to compute the hashcode of a given shader type.
///
/// The names of all instance fields within the current shader type.
- /// Indicates whether or not dynamic shaders are supported.
/// The instance to hash the input shader.
- private static BlockSyntax GetShaderHashCodeBody(ImmutableArray delegateFieldNames, bool supportsDynamicShaders)
+ private static BlockSyntax GetShaderHashCodeBody(ImmutableArray delegateFieldNames)
{
- if (delegateFieldNames.Length == 0 || !supportsDynamicShaders)
+ if (delegateFieldNames.Length == 0)
{
// return 0;
return
@@ -56,17 +54,18 @@ partial class IShaderGenerator
Literal(0))));
}
- List blockStatements = new(4);
-
- // global::System.HashCode hashCode = default;
- blockStatements.Add(LocalDeclarationStatement(
+ List 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)
{
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs
index 1d3a8c4d..53b0caa3 100644
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs
@@ -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
///
/// Creates a instance for the LoadDispatchDataMethod method.
///
- /// The type of shader interface urrently being processed.
+ /// The type of shader interface currently being processed.
/// The array of values for all captured fields.
/// The total number of captured resources in the shader.
/// The total number of needed 32 bit constants in the shader root signature.
/// The resulting instance for the LoadDispatchDataMethod method.
public static MethodDeclarationSyntax GetSyntax(
- Type shaderInterfaceType,
+ ShaderType shaderType,
ImmutableArray 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)));
}
///
/// Gets a sequence of statements to load the dispatch data for a given shader.
///
- /// The type of shader interface urrently being processed.
+ /// The type of shader interface currently being processed.
/// The array of values for all captured fields.
/// The total number of captured resources in the shader.
/// The total number of needed 32 bit constants in the shader root signature.
/// The sequence of instances to load shader dispatch data.
private static ImmutableArray GetDispatchDataLoadingStatements(
- Type shaderInterfaceType,
+ ShaderType shaderType,
ImmutableArray fieldInfos,
int resourceCount,
int root32BitConstantsCount)
{
ImmutableArray.Builder statements = ImmutableArray.CreateBuilder();
- bool isComputeShader = shaderInterfaceType == typeof(IComputeShader);
+ bool isComputeShader = shaderType == ShaderType.ComputeShader;
// Append the statements for the dispatch ranges:
//
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs
index 932c1e3a..33bd6a0f 100644
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs
@@ -25,14 +25,14 @@ partial class IShaderGenerator
/// Explores a given type hierarchy and generates statements to load fields.
///
/// The current shader type being explored.
- /// The type of shader interface urrently being processed.
+ /// The type of shader currently being processed.
/// The total number of captured resources in the shader.
/// The total number of needed 32 bit constants in the shader root signature.
/// The resulting diagnostics from the processing operation.
/// The sequence of instances for all captured resources and values.
public static ImmutableArray GetInfo(
ITypeSymbol structDeclarationSymbol,
- Type shaderInterfaceType,
+ ShaderType shaderType,
out int resourceCount,
out int root32BitConstantCount,
out ImmutableArray 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 resourceOffsetAsBox = new();
StrongBox rawDataOffsetAsBox = new(initialRawDataOffset);
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs
index 77462b98..62efe0a5 100644
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs
@@ -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.
///
/// The input instance to check.
- /// The instance for .
- /// The instance for .
- /// Either or , or .
- private static Type? GetShaderType(
- INamedTypeSymbol typeSymbol,
- INamedTypeSymbol iComputeShaderSymbol,
- INamedTypeSymbol iPixelShaderSymbol)
+ /// The instance currently in use.
+ /// The shader type for , or .
+ 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) &&
- SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, iPixelShaderSymbol))
+ if (SymbolEqualityComparer.Default.Equals(interfaceSymbol, computeShaderSymbol))
+ {
+ return ShaderType.ComputeShader;
+ }
+ }
+ else if (interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) })
{
- return typeof(IPixelShader<>);
+ INamedTypeSymbol pixelShaderSymbol = compilation.GetTypeByMetadataName("ComputeSharp.IPixelShader`1")!;
+
+ if (SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, pixelShaderSymbol))
+ {
+ return ShaderType.PixelShader;
+ }
}
}
return null;
}
+ ///
+ /// Checks whether dynamic shaders are supported in a given compilation.
+ ///
+ /// The instance currently in use.
+ /// Whether dynamic shaders are supported in the input compilation.
+ private static bool IsDynamicCompilationSupported(Compilation compilation)
+ {
+ return compilation.ReferencedAssemblyNames.Any(static identity => identity.Name is "ComputeSharp.Dynamic");
+ }
+
///
/// Creates a instance wrapping the given method.
///
diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs
index 9f0a1608..6d112bd5 100644
--- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs
+++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs
@@ -25,188 +25,178 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
// Check whether [SkipLocalsInit] can be used
IncrementalValueProvider 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 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 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(),
+ static (context, token) =>
+ {
+ StructDeclarationSyntax typeDeclaration = (StructDeclarationSyntax)context.Node;
- // Get the symbol for the IComputeShader and IPixelShader 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.Builder diagnostics = ImmutableArray.CreateBuilder();
+
+ // GetDispatchId() info
+ ImmutableArray dispatchIdInfo = GetDispatchId.GetInfo(typeSymbol);
+
+ token.ThrowIfCancellationRequested();
+
+ // LoadDispatchData() info
+ ImmutableArray fieldInfos = LoadDispatchData.GetInfo(
+ typeSymbol,
+ shaderType,
+ out int resourceCount,
+ out int root32BitConstantCount,
+ out ImmutableArray dispatchDataDiagnostics);
+
+ token.ThrowIfCancellationRequested();
+
+ // BuildHlslSource() info
+ HlslShaderSourceInfo hlslSourceInfo = BuildHlslSource.GetInfo(
+ context.SemanticModel.Compilation,
+ typeDeclaration,
+ typeSymbol,
+ out ImmutableArray 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 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.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 Dispatch, Result Hlsl, Result ThreadIds)> shaderInfoWithErrors =
- shaderDeclarations
- .Combine(supportsDynamicShaders)
- .Combine(context.CompilationProvider)
- .Select(static (item, token) =>
- {
- // LoadDispatchData() info
- ImmutableArray fieldInfos = LoadDispatchData.GetInfo(
- item.Left.Left.Symbol,
- item.Left.Left.Type,
- out int resourceCount,
- out int root32BitConstantCount,
- out ImmutableArray 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 hlslSourceDiagnostics);
-
- token.ThrowIfCancellationRequested();
-
- // TryGetBytecode() info
- ThreadIdsInfo threadIds = LoadBytecode.GetInfo(
- item.Left.Left.Symbol,
- !hlslSourceInfo.Delegates.IsEmpty,
- item.Left.Right,
- out ImmutableArray 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, dispatchDataDiagnostics),
- new Result(hlslSourceInfo, hlslSourceDiagnostics),
- new Result(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 =
- 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 fixup);
- CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, tryGetBytecodeMethod, canUseSkipLocalsInit: false);
+ MethodDeclarationSyntax tryGetBytecodeMethod = LoadBytecode.GetSyntax(item.Info.EmbeddedBytecode, item.SupportsDynamicShaders, out Func 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);
});
}
}
diff --git a/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs
index 4bb4d834..e733ea62 100644
--- a/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs
+++ b/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs
@@ -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;
///
/// A model representing gathered info on a shader dispatch data.
///
-/// The hierarchy data for the shader.
/// The shader interface type.
/// The description on shader instance fields.
/// The total number of captured resources.
/// The size of the shader root signature, in 32 bit constants.
internal sealed record DispatchDataInfo(
- HierarchyInfo Hierarchy,
- Type Type,
+ ShaderType Type,
ImmutableArray FieldInfos,
int ResourceCount,
int Root32BitConstantCount)
@@ -36,7 +33,6 @@ internal sealed record DispatchDataInfo(
///
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 &&
diff --git a/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs b/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs
new file mode 100644
index 00000000..fa4613f3
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs
@@ -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;
+
+///
+/// A model representing all necessary info for a full generation pass for a shader.
+///
+/// The hierarchy info for the shader type.
+/// The gathered dispatch id for the shader type.
+/// The gathered shader dispatch data.
+/// The gathered shader dispatch metadata.
+/// The processed HLSL source for the shader.
+/// The thread ids for the shader, if compilation is requested.
+/// The discovered diagnostics, if any.
+internal sealed record ShaderInfo(
+ HierarchyInfo Hierarchy,
+ DispatchIdInfo DispatchId,
+ DispatchDataInfo DispatchData,
+ DispatchMetadataInfo DispatchMetadata,
+ HlslShaderSourceInfo HlslShaderSource,
+ ThreadIdsInfo ThreadIds,
+ ImmutableArray Diagnostcs)
+{
+ ///
+ public bool Equals(ShaderInfo? obj) => Comparer.Default.Equals(this, obj);
+
+ ///
+ public override int GetHashCode() => Comparer.Default.GetHashCode(this);
+
+ ///
+ /// An implementation for .
+ ///
+ private sealed class Comparer : Comparer
+ {
+ ///
+ 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);
+ }
+
+ ///
+ 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);
+ }
+ }
+}
diff --git a/src/ComputeSharp.SourceGenerators/Models/ShaderType.cs b/src/ComputeSharp.SourceGenerators/Models/ShaderType.cs
new file mode 100644
index 00000000..f70a62c0
--- /dev/null
+++ b/src/ComputeSharp.SourceGenerators/Models/ShaderType.cs
@@ -0,0 +1,17 @@
+namespace ComputeSharp.SourceGenerators.Models;
+
+///
+/// Indicates a type of shader being processed.
+///
+public enum ShaderType
+{
+ ///
+ /// A compute shader.
+ ///
+ ComputeShader,
+
+ ///
+ /// A pixel shader.
+ ///
+ PixelShader
+}
\ No newline at end of file