Remove IShader.GetDispatchId() infrastructure

このコミットが含まれているのは:
Sergio Pedri committed 2023-10-13 10:58:57 +02:00
1 親 9acb650627
コミット 3db275a157
19ファイル変更
+14 -709

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

-1
ファイルの表示
@@ -49,7 +49,6 @@ CMPS0039 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Ser
CMPS0040 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0041 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0042 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0043 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0044 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0045 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0046 | ComputeSharp.Shaders | Error | [Documentation](https://github.com/Sergio0694/ComputeSharp)
-16
ファイルの表示
@@ -586,22 +586,6 @@ partial class DiagnosticDescriptors
description: "A shader type cannot implement more than one shader interface.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for a dynamic shader annotated as an embedded bytecode.
/// <para>
/// Format: <c>"The shader of type {0} cannot be precompiled, as it is dynamic (it captures delegate fields)"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor EmbeddedBytecodeWithDynamicShader = new DiagnosticDescriptor(
id: "CMPS0043",
title: "Embedded bytecode for dynamic shader",
messageFormat: "The shader of type {0} cannot be precompiled, as it is dynamic (it captures delegate fields)",
category: "ComputeSharp.Shaders",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "A shader type cannot be precompiled if it captures one or more delegate values.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an embedded bytecode shader with invalid thread ids values.
/// <para>
@@ -1,4 +1,3 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text;
using ComputeSharp.__Internals;
@@ -88,15 +87,9 @@ partial class IShaderGenerator
using ImmutableArrayBuilder<StatementSyntax> statements = new();
StringBuilder textBuilder = new();
int capturedDelegates = 0;
int prologueStatements = 0;
int sizeHint = 64;
void AppendLF()
{
_ = textBuilder.Append('\n');
}
void AppendLine(string text)
{
_ = textBuilder.Append(text);
@@ -132,67 +125,6 @@ partial class IShaderGenerator
}
}
// Declare the hashsets to track imported members and types from delegates, if needed
if (!hlslSourceInfo.Delegates.IsEmpty)
{
void DeclareMapping(int index, string name, IEnumerable<string> items)
{
// global::System.Collections.Generic.HashSet<string> <NAME> = new();
statements.Insert(index,
LocalDeclarationStatement(VariableDeclaration(
GenericName(Identifier("global::System.Collections.Generic.HashSet"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.StringKeyword))))
.AddVariables(
VariableDeclarator(Identifier(name))
.WithInitializer(EqualsValueClause(ImplicitObjectCreationExpression())))));
prologueStatements++;
// <NAME>.Add("<ITEM>");
foreach (string item in items)
{
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(name),
IdentifierName("Add")))
.AddArgumentListArguments(Argument(
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item))))));
prologueStatements++;
}
}
DeclareMapping(0, "__typeNames", hlslSourceInfo.DefinedTypes);
DeclareMapping(1, "__constantNames", hlslSourceInfo.DefinedConstants);
DeclareMapping(2, "__methodNames", hlslSourceInfo.MethodSignatures);
// Go through all existing delegate fields, if any
foreach (string fieldName in hlslSourceInfo.Delegates)
{
// global::ComputeSharp.__Internals.ShaderMethodSourceAttribute __<DELEGATE_NAME>Attribute = global::ComputeSharp.__Internals.ShaderMethodSourceAttribute.GetForDelegate(<DELEGATE_NAME>, "<DELEGATE_NAME>");
statements.Add(
LocalDeclarationStatement(VariableDeclaration(IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"))
.AddVariables(
VariableDeclarator(Identifier($"__{fieldName}Attribute"))
.WithInitializer(
EqualsValueClause(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName($"global::ComputeSharp.__Internals.{nameof(ShaderMethodSourceAttribute)}"),
IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate))))
.AddArgumentListArguments(
Argument(IdentifierName(fieldName)),
Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName)))))))));
capturedDelegates++;
prologueStatements++;
}
}
// Header and thread ids
AppendLine(hlslSourceInfo.HeaderAndThreadsX);
AppendParsedStatement("builder.Append(threadsX);");
@@ -204,68 +136,15 @@ partial class IShaderGenerator
// Define declarations
AppendLine(hlslSourceInfo.Defines);
// Defines from captured delegates
foreach (string fieldName in hlslSourceInfo.Delegates)
{
AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);");
}
// Static fields and declared types
AppendLine(hlslSourceInfo.StaticFieldsAndDeclaredTypes);
// Declared types from captured delegates
foreach (string fieldName in hlslSourceInfo.Delegates)
{
AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);");
}
// Captured variables
AppendLine(hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations);
// Forward declarations from captured delegates
foreach (string fieldName in hlslSourceInfo.Delegates)
{
AppendParsedStatement($"__{fieldName}Attribute.AppendForwardDeclarations(ref builder, __methodNames);");
}
// Remove all forward declarations from methods that are embedded into the shader.
// This is necessary to avoid duplicate definitions from methods from delegates.
if (capturedDelegates > 0)
{
// <NAME>.Add("<ITEM>");
foreach (string forwardDeclaration in hlslSourceInfo.MethodSignatures)
{
FlushText();
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("__methodNames"),
IdentifierName("Remove")))
.AddArgumentListArguments(Argument(
LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration))))));
}
}
// Captured methods
AppendLine(hlslSourceInfo.CapturedMethods);
// Captured methods from captured delegates
foreach (string fieldName in hlslSourceInfo.Delegates)
{
AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);");
}
// Captured delegate methods
foreach (string fieldName in hlslSourceInfo.Delegates)
{
AppendLF();
AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");");
AppendLF();
}
// Entry point
AppendLine(hlslSourceInfo.EntryPoint);
+1 -6
ファイルの表示
@@ -62,7 +62,6 @@ partial class IShaderGenerator
bool isComputeShader = pixelShaderSymbol is null;
string? implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!);
(ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields, ImmutableArray<(string Name, string HlslType)> valueFields) = GetInstanceFields(diagnostics, structDeclarationSymbol, discoveredTypes, isComputeShader);
ImmutableArray<string> delegateInstanceFields = GetDispatchId.GetInfo(structDeclarationSymbol);
ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers = GetSharedBuffers(diagnostics, structDeclarationSymbol, discoveredTypes);
(string entryPoint, ImmutableArray<(string Signature, string Definition)> processedMethods, bool isSamplerUsed) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, instanceMethods, constantDefinitions, isComputeShader);
(string, string)? implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?);
@@ -78,7 +77,6 @@ partial class IShaderGenerator
declaredTypes,
resourceFields,
valueFields,
delegateInstanceFields,
staticFields,
sharedBuffers,
processedMethods,
@@ -544,7 +542,6 @@ partial class IShaderGenerator
/// <param name="declaredTypes">The sequence of declared types used by the shader.</param>
/// <param name="resourceFields">The sequence of resource instance fields for the current shader.</param>
/// <param name="valueFields">The sequence of value instance fields for the current shader.</param>
/// <param name="delegateInstanceFields">The sequence of delegate fields for the current shader.</param>
/// <param name="staticFields">The sequence of static fields referenced by the shader.</param>
/// <param name="sharedBuffers">The sequence of shared buffers declared by the shader.</param>
/// <param name="processedMethods">The sequence of processed methods used by the shader.</param>
@@ -558,7 +555,6 @@ partial class IShaderGenerator
ImmutableArray<(string Name, string Definition)> declaredTypes,
ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields,
ImmutableArray<(string Name, string HlslType)> valueFields,
ImmutableArray<string> delegateInstanceFields,
ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields,
ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers,
ImmutableArray<(string Signature, string Definition)> processedMethods,
@@ -768,8 +764,7 @@ partial class IShaderGenerator
isSamplerUsed,
declaredTypes.Select(static t => t.Name).ToImmutableArray(),
definedConstants.Select(static c => c.Name).ToImmutableArray(),
processedMethods.Select(static m => m.Signature).ToImmutableArray(),
delegateInstanceFields);
processedMethods.Select(static m => m.Signature).ToImmutableArray());
}
/// <summary>
@@ -1,97 +0,0 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.__Internals;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
partial class IShaderGenerator
{
/// <inheritdoc/>
partial class GetDispatchId
{
/// <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>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(ImmutableArray<string> delegateFieldNames)
{
// This code produces a method declaration as follows:
//
// readonly int global::ComputeSharp.__Internals.IShader.GetDispatchId()
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.IntKeyword)),
Identifier("GetDispatchId"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.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>
/// <returns>The <see cref="BlockSyntax"/> instance to hash the input shader.</returns>
private static BlockSyntax GetShaderHashCodeBody(ImmutableArray<string> delegateFieldNames)
{
if (delegateFieldNames.Length == 0)
{
// return 0;
return
Block(ReturnStatement(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))));
}
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))))))
};
foreach (string fieldName in delegateFieldNames)
{
// hashCode.Add(delegateField.Method);
blockStatements.Add(ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("hashCode"),
IdentifierName("Add")))
.AddArgumentListArguments(Argument(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(fieldName),
IdentifierName("Method"))))));
}
// return hashCode.ToHashCode();
blockStatements.Add(ReturnStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("hashCode"),
IdentifierName("ToHashCode")))));
return Block(blockStatements);
}
}
}
-31
ファイルの表示
@@ -1,31 +0,0 @@
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
partial class IShaderGenerator
{
/// <summary>
/// A helper with all logic to generate the <c>GetDispatchId</c> method.
/// </summary>
private static partial class GetDispatchId
{
/// <summary>
/// Extracts the names of all instance fields of a <see cref="System.Delegate"/> type.
/// </summary>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <returns>The names of all <see cref="System.Delegate"/> instance fields within <paramref name="structDeclarationSymbol"/>.</returns>
public static ImmutableArray<string> GetInfo(INamedTypeSymbol structDeclarationSymbol)
{
return
structDeclarationSymbol
.GetMembers()
.OfType<IFieldSymbol>()
.Where(static member => member is { Type: INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false }, IsImplicitlyDeclared: false })
.Select(static member => member.Name)
.ToImmutableArray();
}
}
}
-10
ファイルの表示
@@ -36,13 +36,11 @@ partial class IShaderGenerator
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="isDynamicShader">Indicates whether or not the shader is dynamic (ie. captures delegates).</param>
/// <param name="supportsDynamicShaders">Indicates whether or not dynamic shaders are supported.</param>
/// <returns>The thread ids for the precompiled shader, if available.</returns>
public static ThreadIdsInfo GetInfo(
ImmutableArrayBuilder<DiagnosticInfo> diagnostics,
INamedTypeSymbol structDeclarationSymbol,
bool isDynamicShader,
bool supportsDynamicShaders)
{
// Try to get the attribute that controls shader precompilation (has to be present when ComputeSharp.Dynamic is not referenced)
@@ -107,14 +105,6 @@ partial class IShaderGenerator
threadsZ = explicitThreadsZ;
}
// If the current shader is dynamic, emit a diagnostic error
if (isDynamicShader)
{
diagnostics.Add(EmbeddedBytecodeWithDynamicShader, structDeclarationSymbol, structDeclarationSymbol);
return new(true, 0, 0, 0);
}
// Ensure the bytecode generation is disabled if any errors are present. This step is done last to ensure that
// all available diagnostics are still emitted correctly before reaching this point, instead of being disabled.
if (diagnostics.Count > 0)
-21
ファイルの表示
@@ -56,11 +56,6 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
using ImmutableArrayBuilder<DiagnosticInfo> diagnostics = new();
// GetDispatchId() info
ImmutableArray<string> dispatchIdInfo = GetDispatchId.GetInfo(typeSymbol);
token.ThrowIfCancellationRequested();
// LoadDispatchData() info
ImmutableArray<FieldInfo> fieldInfos = LoadDispatchData.GetInfo(
diagnostics,
@@ -93,14 +88,12 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
ThreadIdsInfo threadIds = LoadBytecode.GetInfo(
diagnostics,
typeSymbol,
!hlslSourceInfo.Delegates.IsEmpty,
IsDynamicCompilationSupported(context.SemanticModel.Compilation));
token.ThrowIfCancellationRequested();
return new ShaderInfo(
Hierarchy: HierarchyInfo.From(typeSymbol),
DispatchId: new DispatchIdInfo(dispatchIdInfo),
DispatchData: new DispatchDataInfo(
shaderType,
fieldInfos,
@@ -118,20 +111,6 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator
shaderInfoWithErrors
.Select(static (item, _) => item.Diagnostcs));
// 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(dispatchIdInfo, static (context, item) =>
{
MethodDeclarationSyntax getDispatchIdMethod = GetDispatchId.GetSyntax(item.DispatchId.Delegates);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getDispatchIdMethod, addSkipLocalsInitAttribute: false);
context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(GetDispatchId)}.g.cs", compilationUnit.GetText(Encoding.UTF8));
});
// Get the LoadDispatchData() info (hierarchy and dispatch data info)
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo DispatchData)> dispatchDataInfo =
shaderInfoWithErrors
-9
ファイルの表示
@@ -1,9 +0,0 @@
using ComputeSharp.SourceGeneration.Helpers;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model representing gathered info on a shader dispatch id.
/// </summary>
/// <param name="Delegates">The list of delegate field names for the shader.</param>
internal sealed record DispatchIdInfo(EquatableArray<string> Delegates);
+1 -3
ファイルの表示
@@ -18,7 +18,6 @@ namespace ComputeSharp.SourceGenerators.Models;
/// <param name="DefinedTypes">The names of declared types.</param>
/// <param name="DefinedConstants">The names of defined constants.</param>
/// <param name="MethodSignatures">The signatures for captured methods.</param>
/// <param name="Delegates">The list of delegate fields.</param>
internal sealed record HlslShaderSourceInfo(
string HeaderAndThreadsX,
string ThreadsY,
@@ -32,5 +31,4 @@ internal sealed record HlslShaderSourceInfo(
bool IsSamplerUsed,
EquatableArray<string> DefinedTypes,
EquatableArray<string> DefinedConstants,
EquatableArray<string> MethodSignatures,
EquatableArray<string> Delegates);
EquatableArray<string> MethodSignatures);
-2
ファイルの表示
@@ -7,7 +7,6 @@ namespace ComputeSharp.SourceGenerators.Models;
/// 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>
@@ -15,7 +14,6 @@ namespace ComputeSharp.SourceGenerators.Models;
/// <param name="Diagnostcs">The discovered diagnostics, if any.</param>
internal sealed record ShaderInfo(
HierarchyInfo Hierarchy,
DispatchIdInfo DispatchId,
DispatchDataInfo DispatchData,
DispatchMetadataInfo DispatchMetadata,
HlslShaderSourceInfo HlslShaderSource,