Merge pull request #172 from Sergio0694/feature/incremental-generator

Switch source generators to incremental generators
このコミットが含まれているのは:
Sergio Pedri authored and GitHub committed 2021-12-08 18:43:25 +01:00
コミット e14c91f429
48ファイル変更
+4449 -2245

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

+5 -8
ファイルの表示
@@ -43,16 +43,13 @@ CMPS0033 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentatio
CMPS0034 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0035 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0036 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0037 | ComputeSharp.SourceGenerators.AutoConstructorGenerator | Warning | AutoConstructorGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0040 | ComputeSharp.SourceGenerators.IShaderGenerator | Warning | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0041 | ComputeSharp.SourceGenerators.ShaderMethodSourceGenerator | Warning | ShaderMethodSourceGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0037 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0038 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0039 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0040 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0041 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0042 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0043 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0044 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0045 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0046 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0047 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0048 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0049 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0050 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
CMPS0051 | ComputeSharp.IComputeShader | Error | IShaderGenerator, [Documentation](https://github.com/Sergio0694/ComputeSharp)
-54
ファイルの表示
@@ -1,54 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
public sealed partial class AutoConstructorGenerator
{
/// <summary>
/// An <see cref="ISyntaxContextReceiver"/> that selects candidate nodes to process.
/// </summary>
private sealed class SyntaxReceiver : ISyntaxContextReceiver
{
/// <summary>
/// The list of info gathered during exploration.
/// </summary>
private readonly List<Item> gatheredInfo = new();
/// <summary>
/// Gets the collection of gathered info to process.
/// </summary>
public IReadOnlyCollection<Item> GatheredInfo => this.gatheredInfo;
/// <inheritdoc/>
public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
{
if (context.Node is StructDeclarationSyntax { AttributeLists: { Count: > 0 } } structDeclaration &&
context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol &&
context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(AutoConstructorAttribute).FullName) is INamedTypeSymbol attributeSymbol &&
structSymbol.GetAttributes().FirstOrDefault(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, attributeSymbol)) is AttributeData attributeData &&
attributeData.ApplicationSyntaxReference is SyntaxReference syntaxReference &&
syntaxReference.GetSyntax() is AttributeSyntax attributeSyntax)
{
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol, attributeSyntax, attributeData));
}
}
/// <summary>
/// A model for a group of item representing a discovered type to process.
/// </summary>
/// <param name="StructDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the target struct declaration.</param>
/// <param name="StructSymbol">The <see cref="INamedTypeSymbol"/> instance for <paramref name="StructDeclaration"/>.</param>
/// <param name="AttributeSyntax">The <see cref="AttributeSyntax"/> instance for the target attribute over <paramref name="StructDeclaration"/>.</param>
/// <param name="AttributeData">The <see cref="AttributeData"/> instance for <paramref name="AttributeSyntax"/>.</param>
public sealed record Item(
StructDeclarationSyntax StructDeclaration,
INamedTypeSymbol StructSymbol,
AttributeSyntax AttributeSyntax,
AttributeData AttributeData);
}
}
+120 -80
ファイルの表示
@@ -1,111 +1,151 @@
using System.Collections.Immutable;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle;
namespace ComputeSharp.SourceGenerators;
/// <summary>
/// A source generator creating constructors for types annotated with <see cref="AutoConstructorAttribute"/>.
/// </summary>
[Generator]
public sealed partial class AutoConstructorGenerator : ISourceGenerator
[Generator(LanguageNames.CSharp)]
public sealed partial class AutoConstructorGenerator : IIncrementalGenerator
{
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
public void Initialize(IncrementalGeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver());
}
// Get all declared struct symbols with the [AutoConstructor] attribute
IncrementalValuesProvider<INamedTypeSymbol> structDeclarations =
context.SyntaxProvider
.CreateSyntaxProvider(
static (node, token) => node is StructDeclarationSyntax structDeclaration,
static (context, token) => (INamedTypeSymbol?)context.SemanticModel.GetDeclaredSymbol(context.Node, token))
.Where(static symbol => symbol is not null &&
symbol.GetAttributes().Any(static a => a.AttributeClass?.ToDisplayString() == typeof(AutoConstructorAttribute).FullName))!;
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
{
// Get the syntax receiver with the candidate nodes
if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver)
{
return;
}
// Get the type hierarchy and fields info
IncrementalValuesProvider<(HierarchyInfo Left, ImmutableArray<ParameterInfo> Right)> constructorInfo =
structDeclarations
.Select(static (item, token) => (Hierarchy: HierarchyInfo.From(item), Parameters: Ctor.GetData(item)))
.Where(static item => !item.Parameters.IsEmpty)
.WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer<ParameterInfo>.Default.ForImmutableArray());
foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo)
// Generate the constructors
context.RegisterSourceOutput(constructorInfo, static (context, item) =>
{
try
{
OnExecute(context, item.StructDeclaration, item.StructSymbol);
}
catch
{
context.ReportDiagnostic(AutoConstructorGeneratorError, item.AttributeSyntax, item.StructSymbol);
}
}
CompilationUnitSyntax compilationUnit = Ctor.GetSyntax(item.Left, item.Right);
context.AddSource($"{item.Left.FilenameHint}.Ctor", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8));
});
}
/// <summary>
/// Processes a given target type.
/// A helper with all logic to generate the constructor declarations.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> node to process.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol)
private static class Ctor
{
// Extract the info on the type to process
var namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces));
var structName = structDeclaration.Identifier.Text;
var structModifiers = structDeclaration.Modifiers;
var fields = (
from fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>()
where !fieldSymbol.IsConst && !fieldSymbol.IsStatic && !fieldSymbol.IsFixedSizeBuffer
let typeName = fieldSymbol.Type!.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)
let fieldFullType = ParseTypeName(typeName)
select (Type: fieldFullType, Identifier: Identifier(fieldSymbol.Name))).ToImmutableArray();
// Create the constructor declaration for the type. This will
// produce a constructor with simple initialization of all variables:
//
// public MyType(Foo a, Bar b, Baz c, ...)
// {
// this.a = a;
// this.b = b;
// this.c = c;
// ...
// }
var structDeclarationSyntax =
StructDeclaration(structName).WithModifiers(structModifiers).AddMembers(
ConstructorDeclaration(structName)
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(fields.Select(field => Parameter(field.Identifier).WithType(field.Type)).ToArray())
.AddBodyStatements(fields.Select(field => ParseStatement($"this.{field.Identifier} = {field.Identifier};")).ToArray()));
TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
// Add all parent types in ascending order, if any
foreach (var parentType in structDeclaration.Ancestors().OfType<TypeDeclarationSyntax>())
/// <summary>
/// Gets the sequence of <see cref="ParameterInfo"/> items for all fields in the input type.
/// </summary>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> being inspected.</param>
/// <returns>The sequence of <see cref="ParameterInfo"/> items for all fields in <paramref name="structDeclarationSymbol"/>.</returns>
public static ImmutableArray<ParameterInfo> GetData(INamedTypeSymbol structDeclarationSymbol)
{
typeDeclarationSyntax = parentType
.WithMembers(SingletonList<MemberDeclarationSyntax>(typeDeclarationSyntax))
.WithConstraintClauses(List<TypeParameterConstraintClauseSyntax>())
.WithBaseList(null)
.WithAttributeLists(List<AttributeListSyntax>())
.WithoutTrivia();
return (
from fieldSymbol in structDeclarationSymbol.GetMembers().OfType<IFieldSymbol>()
where fieldSymbol is { IsConst: false, IsStatic: false, IsFixedSizeBuffer: false }
let typeName = fieldSymbol.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)
select new ParameterInfo(typeName, fieldSymbol.Name)).ToImmutableArray();
}
// Create the compilation unit with the namespace and target member.
// From this, we can finally generate the source code to output.
var source =
CompilationUnit().AddMembers(
FileScopedNamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax)
.WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList())))
.NormalizeWhitespace(eol: "\n")
.ToFullString();
/// <summary>
/// Gets the <see cref="CompilationUnitSyntax"/> instance for a given type and sequence of parameters.
/// </summary>
/// <param name="hierarchyInfo">The type hierarchy info.</param>
/// <param name="parameters">The sequence of parameters to initialize.</param>
/// <returns>A <see cref="CompilationUnitSyntax"/> instance for a specified type.</returns>
public static CompilationUnitSyntax GetSyntax(HierarchyInfo hierarchyInfo, ImmutableArray<ParameterInfo> parameters)
{
// Create the constructor declaration for the type. This will
// produce a constructor with simple initialization of all variables:
//
// public MyType(Foo a, Bar b, Baz c, ...)
// {
// this.a = a;
// this.b = b;
// this.c = c;
// ...
// }
ConstructorDeclarationSyntax constructorDeclaration =
ConstructorDeclaration(hierarchyInfo.Names[0])
.AddModifiers(Token(SyntaxKind.PublicKeyword))
.AddParameterListParameters(parameters.Select(field => Parameter(Identifier(field.Name)).WithType(IdentifierName(field.Type))).ToArray())
.AddBodyStatements(parameters.Select(field => ParseStatement($"this.{field.Name} = {field.Name};")).ToArray());
// Add the partial type
context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
// Add the unsafe modifier, if needed
if (parameters.Any(static param => param.Type.Contains("*")))
{
constructorDeclaration = constructorDeclaration.AddModifiers(Token(SyntaxKind.UnsafeKeyword));
}
// Constructor attributes
AttributeListSyntax[] attributes =
{
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(AutoConstructorGenerator).FullName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(AutoConstructorGenerator).Assembly.GetName().Version.ToString())))))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage"))))
};
// Create the partial shader type declaration with the given method implementation.
// This code produces a struct declaration as follows:
//
// partial struct <SHADER_TYPE>
// {
// <METHOD>
// }
StructDeclarationSyntax structDeclarationSyntax =
StructDeclaration(hierarchyInfo.Names[0])
.AddModifiers(Token(SyntaxKind.PartialKeyword))
.AddMembers(constructorDeclaration.AddAttributeLists(attributes));
TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
// Add all parent types in ascending order, if any
foreach (string parentType in hierarchyInfo.Names.AsSpan().Slice(1))
{
typeDeclarationSyntax =
ClassDeclaration(parentType)
.AddModifiers(Token(SyntaxKind.PartialKeyword))
.AddMembers(typeDeclarationSyntax);
}
// Create the compilation unit with disabled warnings, target namespace and generated type.
// This will produce code as follows:
//
// #pragma warning disable
//
// namespace <NAMESPACE>;
//
// <TYPE_HIERARCHY>
return
CompilationUnit().AddMembers(
FileScopedNamespaceDeclaration(IdentifierName(hierarchyInfo.Namespace))
.AddMembers(typeDeclarationSyntax)
.WithNamespaceKeyword(Token(TriviaList(
Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))),
SyntaxKind.NamespaceKeyword,
TriviaList())))
.NormalizeWhitespace(eol: "\n");
}
}
}
+10 -58
ファイルの表示
@@ -496,59 +496,11 @@ internal static class DiagnosticDescriptors
description: "String literal expressions cannot be used in a compute shader.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an internal error in <see cref="AutoConstructorGenerator"/>.
/// <para>
/// Format: <c>"The generator AutoConstructorGenerator failed to execute on type {0}, and its constructor might not be available"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor AutoConstructorGeneratorError = new(
id: "CMPS0037",
title: $"Internal error for {nameof(AutoConstructorGenerator)}",
messageFormat: $"The generator {nameof(AutoConstructorGenerator)} failed to execute on type {{0}}, and its constructor might not be available",
category: typeof(AutoConstructorGenerator).FullName,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: $"The {nameof(AutoConstructorGenerator)} generator encountered an error while processing a type, and its constructor might not be available. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an internal error in <see cref="IShaderGenerator"/>.
/// <para>
/// Format: <c>"The generator IShaderGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor IShaderGeneratorError = new(
id: "CMPS0040",
title: $"Internal error for {nameof(IShaderGenerator)}",
messageFormat: $"The generator {nameof(IShaderGenerator)} failed to execute on type {{0}}, and trying to use that shader might result in a runtime crash",
category: typeof(IShaderGenerator).FullName,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: $"The {nameof(IShaderGenerator)} generator encountered an error while processing a type, and trying to use that shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an internal error in <see cref="ShaderMethodSourceGenerator"/>.
/// <para>
/// Format: <c>"The generator ShaderMethodSourceGenerator failed to execute on method {0}, and using it in a shader might result in a runtime crash"</c>.
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor ShaderMethodSourceGeneratorError = new(
id: "CMPS0041",
title: $"Internal error for {nameof(ShaderMethodSourceGenerator)}",
messageFormat: $"The generator {nameof(ShaderMethodSourceGenerator)} failed to execute on method {{0}}, and using it in a shader might result in a runtime crash",
category: typeof(ShaderMethodSourceGenerator).FullName,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: $"The {nameof(ShaderMethodSourceGenerator)} generator encountered an error while processing a method, and using it in a shader might result in a runtime crash. Please report this issue at https://github.com/Sergio0694/ComputeSharp/issues.",
helpLinkUri: "https://github.com/Sergio0694/ComputeSharp");
/// <summary>
/// Gets a <see cref="DiagnosticDescriptor"/> for an incorrect matrix swizzling property argument.
/// </summary>
public static readonly DiagnosticDescriptor NonConstantMatrixSwizzledIndex = new(
id: "CMPS0042",
id: "CMPS0037",
title: "Non constant matrix swizzled property argument",
messageFormat: "The arguments in a swizzled indexer for a matrix type must be compile-time constants",
category: typeof(ShaderMethodSourceGenerator).FullName,
@@ -564,7 +516,7 @@ internal static class DiagnosticDescriptors
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidShaderStaticFieldType = new(
id: "CMPS0043",
id: "CMPS0038",
title: "Invalid shader static field type",
messageFormat: "The compute shader of type {0} contains a static field \"{1}\" of an invalid type {2} (only primitive, vector and matrix types are supported)",
category: typeof(IComputeShader).FullName,
@@ -577,7 +529,7 @@ internal static class DiagnosticDescriptors
/// Gets a <see cref="DiagnosticDescriptor"/> for an invalid <see cref="DispatchSize"/> usage.
/// </summary>
public static readonly DiagnosticDescriptor InvalidDispatchSizeUsage = new(
id: "CMPS0044",
id: "CMPS0039",
title: "Invalid DispatchSize usage",
messageFormat: "The DispatchSize type can only be used within the main body of a compute shader",
category: typeof(IComputeShader).FullName,
@@ -590,7 +542,7 @@ internal static class DiagnosticDescriptors
/// Gets a <see cref="DiagnosticDescriptor"/> for a property declaration.
/// </summary>
public static readonly DiagnosticDescriptor PropertyDeclaration = new(
id: "CMPS0045",
id: "CMPS0040",
title: "Property declaration",
messageFormat: "Property declarations cannot be used in a compute shader",
category: typeof(IComputeShader).FullName,
@@ -606,7 +558,7 @@ internal static class DiagnosticDescriptors
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor ShaderDispatchDataSizeExceeded = new(
id: "CMPS0046",
id: "CMPS0041",
title: "Shader dispatch data size exceeded",
messageFormat: "The compute shader of type {0} has exceeded the maximum allowed size for captured values and resources",
category: typeof(IComputeShader).FullName,
@@ -622,7 +574,7 @@ internal static class DiagnosticDescriptors
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor MultipleShaderTypesImplemented = new(
id: "CMPS0047",
id: "CMPS0042",
title: "Multiple shader implementations for type declaration",
messageFormat: $"The shader of type {{0}} cannot implement more than one shader interface",
category: typeof(IShaderGenerator).FullName,
@@ -638,7 +590,7 @@ internal static class DiagnosticDescriptors
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor EmbeddedBytecodeWithDynamicShader = new(
id: "CMPS0048",
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: typeof(IShaderGenerator).FullName,
@@ -654,7 +606,7 @@ internal static class DiagnosticDescriptors
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor InvalidEmbeddedBytecodeThreadIds = new(
id: "CMPS0049",
id: "CMPS0044",
title: "Invalid thread ids for shader with embedded bytecode",
messageFormat: $"The shader of type {{0}} is annotated with invalid thread ids values ({{1}}, {{2}}, {{3}})",
category: typeof(IShaderGenerator).FullName,
@@ -670,7 +622,7 @@ internal static class DiagnosticDescriptors
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor EmbeddedBytecodeFailedWithWin32Exception = new(
id: "CMPS0050",
id: "CMPS0045",
title: "Embedded bytecode compilation failed due to Win32 exception",
messageFormat: $"The shader of type {{0}} failed to compile due to a Win32 exception (HRESULT: {{1:X8}}, Message: \"{{2}}\")",
category: typeof(IShaderGenerator).FullName,
@@ -686,7 +638,7 @@ internal static class DiagnosticDescriptors
/// </para>
/// </summary>
public static readonly DiagnosticDescriptor EmbeddedBytecodeFailedWithHlslCompilationException = new(
id: "CMPS0051",
id: "CMPS0046",
title: "Embedded bytecode compilation failed due to an HLSL compiler error",
messageFormat: $"The shader of type {{0}} failed to compile due to an HLSL compiler error (Message: \"{{1}}\")",
category: typeof(IShaderGenerator).FullName,
+50 -1
ファイルの表示
@@ -1,4 +1,5 @@
using System.Linq;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.SourceGenerators.Diagnostics;
@@ -39,4 +40,52 @@ internal static class DiagnosticsExtensions
{
context.ReportDiagnostic(Diagnostic.Create(descriptor, node.GetLocation(), args));
}
/// <summary>
/// Adds a new diagnostics to the target builder.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="descriptor">The input <see cref="DiagnosticDescriptor"/> for the diagnostics to create.</param>
/// <param name="symbol">The source <see cref="ISymbol"/> to attach the diagnostics to.</param>
/// <param name="args">The optional arguments for the formatted message to include.</param>
public static void Add(
this ImmutableArray<Diagnostic>.Builder diagnostics,
DiagnosticDescriptor descriptor,
ISymbol symbol,
params object[] args)
{
diagnostics.Add(Diagnostic.Create(descriptor, symbol.Locations.FirstOrDefault(), args));
}
/// <summary>
/// Adds a new diagnostics to the target builder.
/// </summary>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="descriptor">The input <see cref="DiagnosticDescriptor"/> for the diagnostics to create.</param>
/// <param name="node">The source <see cref="SyntaxNode"/> to attach the diagnostics to.</param>
/// <param name="args">The optional arguments for the formatted message to include.</param>
public static void Add(
this ImmutableArray<Diagnostic>.Builder diagnostics,
DiagnosticDescriptor descriptor,
SyntaxNode node,
params object[] args)
{
diagnostics.Add(Diagnostic.Create(descriptor, node.GetLocation(), args));
}
/// <summary>
/// Registers an output node into an <see cref="IncrementalGeneratorInitializationContext"/> to output diagnostics.
/// </summary>
/// <param name="context">The input <see cref="IncrementalGeneratorInitializationContext"/> instance.</param>
/// <param name="diagnostics">The input <see cref="IncrementalValuesProvider{TValues}"/> sequence of diagnostics.</param>
public static void ReportDiagnostics(this IncrementalGeneratorInitializationContext context, IncrementalValuesProvider<ImmutableArray<Diagnostic>> diagnostics)
{
context.RegisterSourceOutput(diagnostics, static (context, diagnostics) =>
{
foreach (Diagnostic diagnostic in diagnostics)
{
context.ReportDiagnostic(diagnostic);
}
});
}
}
+40
ファイルの表示
@@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace ComputeSharp.SourceGenerators.Extensions;
/// <summary>
/// Extension methods for <see cref="HashCode"/>.
/// </summary>
internal static class HashCodeExtensions
{
/// <summary>
/// Adds all items from a given <see cref="ImmutableArray{T}"/> instance to an hashcode.
/// </summary>
/// <typeparam name="T">The type of items to hash.</typeparam>
/// <param name="hashCode">The target <see cref="HashCode"/> instance.</param>
/// <param name="items">The input items to hash.</param>
public static void AddRange<T>(this ref HashCode hashCode, ImmutableArray<T> items)
{
foreach (T item in items)
{
hashCode.Add(item);
}
}
/// <summary>
/// Adds all items from a given <see cref="ImmutableArray{T}"/> instance to an hashcode.
/// </summary>
/// <typeparam name="T">The type of items to hash.</typeparam>
/// <param name="hashCode">The target <see cref="HashCode"/> instance.</param>
/// <param name="comparer">A comparer to get hashcodes for <typeparamref name="T"/> items.</param>
/// <param name="items">The input items to hash.</param>
public static void AddRange<T>(this ref HashCode hashCode, ImmutableArray<T> items, IEqualityComparer<T> comparer)
{
foreach (T item in items)
{
hashCode.Add(item, comparer);
}
}
}
+59
ファイルの表示
@@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace ComputeSharp.SourceGenerators.Extensions;
/// <summary>
/// Extension methods for <see cref="IEqualityComparer{T}"/>.
/// </summary>
internal static class IEqualityComparerExtensions
{
/// <summary>
/// Gets an <see cref="IEqualityComparer{T}"/> for an <see cref="ImmutableArray{T}"/> sequence.
/// </summary>
/// <typeparam name="T">The type of items to compare.</typeparam>
/// <param name="comparer">The compare for individual <typeparamref name="T"/> items.</param>
public static IEqualityComparer<ImmutableArray<T>> ForImmutableArray<T>(this IEqualityComparer<T> comparer)
{
return new Comparer<T>(comparer);
}
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for an <see cref="ImmutableArray{T}"/> value.
/// </summary>
public sealed class Comparer<T> : IEqualityComparer<ImmutableArray<T>>
{
/// <summary>
/// The <typeparamref name="T"/> comparer.
/// </summary>
private readonly IEqualityComparer<T> comparer;
/// <summary>
/// Creates a new <see cref="Comparer{T}"/> instance with the specified parameters.
/// </summary>
/// <param name="comparer">The <typeparamref name="T"/> comparer.</param>
public Comparer(IEqualityComparer<T> comparer)
{
this.comparer = comparer;
}
/// <inheritdoc/>
public bool Equals(ImmutableArray<T> x, ImmutableArray<T> y)
{
return
x == y ||
x.SequenceEqual(y, this.comparer);
}
/// <inheritdoc/>
public int GetHashCode(ImmutableArray<T> obj)
{
HashCode hashCode = default;
hashCode.AddRange(obj, this.comparer);
return hashCode.ToHashCode();
}
}
}
-11
ファイルの表示
@@ -116,17 +116,6 @@ internal static class ISymbolExtensions
return symbol.GetFullMetadataName().Replace('`', '-').Replace('+', '.');
}
/// <summary>
/// Gets a valid filename for a target symbol and generator type.
/// </summary>
/// <param name="symbol">The symbol being processed.</param>
/// <returns>A filename in the form "&lt;SYMBOL_FULLNAME&gt;"</returns>
[Pure]
public static string GetGeneratedFileName(this IMethodSymbol symbol)
{
return symbol.GetFullMetadataName(true).Replace('`', '-').Replace('+', '.');
}
/// <summary>
/// Tracks an <see cref="ITypeSymbol"/> instance and returns an HLSL compatible <see cref="TypeSyntax"/> object.
/// </summary>
+50
ファイルの表示
@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace ComputeSharp.SourceGenerators.Extensions;
/// <summary>
/// Extension methods for <see cref="ImmutableArray{T}"/>.
/// </summary>
internal static class ImmutableArrayExtensions
{
/// <summary>
/// Compares two sequences for equality.
/// </summary>
/// <typeparam name="T">The items to compare.</typeparam>
/// <param name="left">The left sequence of items.</param>
/// <param name="right">The right sequence of items.</param>
/// <returns>Whether or not <paramref name="left"/> equals <paramref name="right"/>.</returns>
public static bool SequenceEqual<T>(this ImmutableArray<T> left, ImmutableArray<T> right)
where T : IEquatable<T>
{
return left.AsSpan().SequenceEqual(right.AsSpan());
}
/// <summary>
/// Compares two sequences for equality.
/// </summary>
/// <typeparam name="T">The items to compare.</typeparam>
/// <param name="left">The left sequence of items.</param>
/// <param name="right">The right sequence of items.</param>
/// <param name="comparer">The <see cref="IEqualityComparer{T}"/> instance used to compare <typeparamref name="T"/> items.</param>
/// <returns>Whether or not <paramref name="left"/> equals <paramref name="right"/>.</returns>
public static bool SequenceEqual<T>(this ImmutableArray<T> left, ImmutableArray<T> right, IEqualityComparer<T> comparer)
{
if (left.Length != right.Length)
{
return false;
}
for (int i = 0; i < left.Length; i++)
{
if (!comparer.Equals(left[i], right[i]))
{
return false;
}
}
return true;
}
}
+143
ファイルの表示
@@ -0,0 +1,143 @@
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.SourceGenerators.Extensions;
/// <summary>
/// Extension methods for <see cref="IncrementalValuesProvider{TValues}"/>.
/// </summary>
internal static class IncrementalValuesProviderExtensions
{
/// <summary>
/// Creates a new <see cref="IncrementalValuesProvider{TValues}"/> instance with a gven pair of comparers.
/// </summary>
/// <typeparam name="TLeft">The type of left items in each tuple.</typeparam>
/// <typeparam name="TRight">The type of right items in each tuple.</typeparam>
/// <param name="source">The input <see cref="IncrementalValuesProvider{TValues}"/> instance.</param>
/// <param name="comparerLeft">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="TLeft"/> items.</param>
/// <param name="comparerRight">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="TRight"/> items.</param>
/// <returns>An <see cref="IncrementalValuesProvider{TValues}"/> with the specified comparers applied to each item.</returns>
public static IncrementalValuesProvider<(TLeft Left, TRight Right)> WithComparers<TLeft, TRight>(
this IncrementalValuesProvider<(TLeft Left, TRight Right)> source,
IEqualityComparer<TLeft> comparerLeft,
IEqualityComparer<TRight> comparerRight)
{
return source.WithComparer(new Comparer<TLeft, TRight>(comparerLeft, comparerRight));
}
/// <summary>
/// Creates a new <see cref="IncrementalValuesProvider{TValues}"/> instance with a gven pair of comparers.
/// </summary>
/// <typeparam name="T1">The type of first items in each tuple.</typeparam>
/// <typeparam name="T2">The type of second items in each tuple.</typeparam>
/// <typeparam name="T3">The type of third items in each tuple.</typeparam>
/// <param name="source">The input <see cref="IncrementalValuesProvider{TValues}"/> instance.</param>
/// <param name="comparer1">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T1"/> items.</param>
/// <param name="comparer2">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T2"/> items.</param>
/// <param name="comparer3">An <see cref="IEqualityComparer{T}"/> instance for <typeparamref name="T3"/> items.</param>
/// <returns>An <see cref="IncrementalValuesProvider{TValues}"/> with the specified comparers applied to each item.</returns>
public static IncrementalValuesProvider<(T1, T2, T3)> WithComparers<T1, T2, T3>(
this IncrementalValuesProvider<(T1, T2, T3)> source,
IEqualityComparer<T1> comparer1,
IEqualityComparer<T2> comparer2,
IEqualityComparer<T3> comparer3)
{
return source.WithComparer(new Comparer<T1, T2, T3>(comparer1, comparer2, comparer3));
}
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for a value tuple.
/// </summary>
public sealed class Comparer<TLeft, TRight> : IEqualityComparer<(TLeft Left, TRight Right)>
{
/// <summary>
/// The <typeparamref name="TLeft"/> comparer.
/// </summary>
private readonly IEqualityComparer<TLeft> comparerLeft;
/// <summary>
/// The <typeparamref name="TRight"/> comparer.
/// </summary>
private readonly IEqualityComparer<TRight> comparerRight;
/// <summary>
/// Creates a new <see cref="Comparer{TLeft, TRight}"/> instance with the specified parameters.
/// </summary>
/// <param name="comparerLeft">The <typeparamref name="TLeft"/> comparer.</param>
/// <param name="comparerRight">The <typeparamref name="TRight"/> comparer.</param>
public Comparer(IEqualityComparer<TLeft> comparerLeft, IEqualityComparer<TRight> comparerRight)
{
this.comparerLeft = comparerLeft;
this.comparerRight = comparerRight;
}
/// <inheritdoc/>
public bool Equals((TLeft Left, TRight Right) x, (TLeft Left, TRight Right) y)
{
return
this.comparerLeft.Equals(x.Left, y.Left) &&
this.comparerRight.Equals(x.Right, y.Right);
}
/// <inheritdoc/>
public int GetHashCode((TLeft Left, TRight Right) obj)
{
return HashCode.Combine(
this.comparerLeft.GetHashCode(obj.Left),
this.comparerRight.GetHashCode(obj.Right));
}
}
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for a value tuple.
/// </summary>
public sealed class Comparer<T1, T2, T3> : IEqualityComparer<(T1, T2, T3)>
{
/// <summary>
/// The <typeparamref name="T1"/> comparer.
/// </summary>
private readonly IEqualityComparer<T1> comparer1;
/// <summary>
/// The <typeparamref name="T2"/> comparer.
/// </summary>
private readonly IEqualityComparer<T2> comparer2;
/// <summary>
/// The <typeparamref name="T3"/> comparer.
/// </summary>
private readonly IEqualityComparer<T3> comparer3;
/// <summary>
/// Creates a new <see cref="Comparer{T1, T2, T3}"/> instance with the specified parameters.
/// </summary>
/// <param name="comparer1">The <typeparamref name="T1"/> comparer.</param>
/// <param name="comparer2">The <typeparamref name="T2"/> comparer.</param>
/// <param name="comparer3">The <typeparamref name="T3"/> comparer.</param>
public Comparer(IEqualityComparer<T1> comparer1, IEqualityComparer<T2> comparer2, IEqualityComparer<T3> comparer3)
{
this.comparer1 = comparer1;
this.comparer2 = comparer2;
this.comparer3 = comparer3;
}
/// <inheritdoc/>
public bool Equals((T1, T2, T3) x, (T1, T2, T3) y)
{
return
this.comparer1.Equals(x.Item1, y.Item1) &&
this.comparer2.Equals(x.Item2, y.Item2) &&
this.comparer3.Equals(x.Item3, y.Item3);
}
/// <inheritdoc/>
public int GetHashCode((T1, T2, T3) obj)
{
return HashCode.Combine(
this.comparer1.GetHashCode(obj.Item1),
this.comparer2.GetHashCode(obj.Item2),
this.comparer3.GetHashCode(obj.Item3));
}
}
}
+4 -9
ファイルの表示
@@ -9,13 +9,13 @@ namespace ComputeSharp.SourceGenerators;
/// <summary>
/// A source generator to create global using directives for the HLSL primitive types.
/// </summary>
[Generator]
public sealed class GlobalUsingDirectivesGenerator : ISourceGenerator
[Generator(LanguageNames.CSharp)]
public sealed class GlobalUsingDirectivesGenerator : IIncrementalGenerator
{
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
public void Initialize(IncrementalGeneratorInitializationContext context)
{
context.RegisterForPostInitialization(static context =>
context.RegisterPostInitializationOutput(static context =>
{
const string filename = "ComputeSharp.SourceGenerators.EmbeddedResources.GlobalUsingDirectives.cs";
@@ -27,9 +27,4 @@ public sealed class GlobalUsingDirectivesGenerator : ISourceGenerator
context.AddSource("GlobalUsingDirectives.cs", SourceText.From(globalUsingDirectives, Encoding.UTF8));
});
}
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
{
}
}
+456 -10
ファイルの表示
@@ -1,10 +1,181 @@
namespace System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
#pragma warning disable CS0809
namespace System;
/// <summary>
/// A polyfill type that mirrors some methods from <see cref="HashCode"/> on .NET 6.
/// </summary>
internal struct HashCode
{
private const uint Prime1 = 2654435761U;
private const uint Prime2 = 2246822519U;
private const uint Prime3 = 3266489917U;
private const uint Prime4 = 668265263U;
private const uint Prime5 = 374761393U;
private static readonly uint seed = GenerateGlobalSeed();
private uint v1, v2, v3, v4;
private uint queue1, queue2, queue3;
private uint length;
/// <summary>
/// Initializes the default seed.
/// </summary>
/// <returns>A random seed.</returns>
private static unsafe uint GenerateGlobalSeed()
{
byte[] bytes = new byte[4];
RandomNumberGenerator.Create().GetBytes(bytes);
return BitConverter.ToUInt32(bytes, 0);
}
/// <summary>
/// Combines a value into a hash code.
/// </summary>
/// <typeparam name="T1">The type of the value to combine into the hash code.</typeparam>
/// <param name="value">The value to combine into the hash code.</param>
/// <returns>The hash code that represents the value.</returns>
public static int Combine<T1>(T1 value)
{
uint hc1 = (uint)(value?.GetHashCode() ?? 0);
uint hash = MixEmptyState();
hash += 4;
hash = QueueRound(hash, hc1);
hash = MixFinal(hash);
return (int)hash;
}
/// <summary>
/// Combines two values into a hash code.
/// </summary>
/// <typeparam name="T1">The type of the first value to combine into the hash code.</typeparam>
/// <typeparam name="T2">The type of the second value to combine into the hash code.</typeparam>
/// <param name="value1">The first value to combine into the hash code.</param>
/// <param name="value2">The second value to combine into the hash code.</param>
/// <returns>The hash code that represents the values.</returns>
public static int Combine<T1, T2>(T1 value1, T2 value2)
{
uint hc1 = (uint)(value1?.GetHashCode() ?? 0);
uint hc2 = (uint)(value2?.GetHashCode() ?? 0);
uint hash = MixEmptyState();
hash += 8;
hash = QueueRound(hash, hc1);
hash = QueueRound(hash, hc2);
hash = MixFinal(hash);
return (int)hash;
}
/// <summary>
/// Combines three values into a hash code.
/// </summary>
/// <typeparam name="T1">The type of the first value to combine into the hash code.</typeparam>
/// <typeparam name="T2">The type of the second value to combine into the hash code.</typeparam>
/// <typeparam name="T3">The type of the third value to combine into the hash code.</typeparam>
/// <param name="value1">The first value to combine into the hash code.</param>
/// <param name="value2">The second value to combine into the hash code.</param>
/// <param name="value3">The third value to combine into the hash code.</param>
/// <returns>The hash code that represents the values.</returns>
public static int Combine<T1, T2, T3>(T1 value1, T2 value2, T3 value3)
{
uint hc1 = (uint)(value1?.GetHashCode() ?? 0);
uint hc2 = (uint)(value2?.GetHashCode() ?? 0);
uint hc3 = (uint)(value3?.GetHashCode() ?? 0);
uint hash = MixEmptyState();
hash += 12;
hash = QueueRound(hash, hc1);
hash = QueueRound(hash, hc2);
hash = QueueRound(hash, hc3);
hash = MixFinal(hash);
return (int)hash;
}
/// <summary>
/// Combines four values into a hash code.
/// </summary>
/// <typeparam name="T1">The type of the first value to combine into the hash code.</typeparam>
/// <typeparam name="T2">The type of the second value to combine into the hash code.</typeparam>
/// <typeparam name="T3">The type of the third value to combine into the hash code.</typeparam>
/// <typeparam name="T4">The type of the fourth value to combine into the hash code.</typeparam>
/// <param name="value1">The first value to combine into the hash code.</param>
/// <param name="value2">The second value to combine into the hash code.</param>
/// <param name="value3">The third value to combine into the hash code.</param>
/// <param name="value4">The fourth value to combine into the hash code.</param>
/// <returns>The hash code that represents the values.</returns>
public static int Combine<T1, T2, T3, T4>(T1 value1, T2 value2, T3 value3, T4 value4)
{
uint hc1 = (uint)(value1?.GetHashCode() ?? 0);
uint hc2 = (uint)(value2?.GetHashCode() ?? 0);
uint hc3 = (uint)(value3?.GetHashCode() ?? 0);
uint hc4 = (uint)(value4?.GetHashCode() ?? 0);
Initialize(out uint v1, out uint v2, out uint v3, out uint v4);
v1 = Round(v1, hc1);
v2 = Round(v2, hc2);
v3 = Round(v3, hc3);
v4 = Round(v4, hc4);
uint hash = MixState(v1, v2, v3, v4);
hash += 16;
hash = MixFinal(hash);
return (int)hash;
}
/// <summary>
/// Combines five values into a hash code.
/// </summary>
/// <typeparam name="T1">The type of the first value to combine into the hash code.</typeparam>
/// <typeparam name="T2">The type of the second value to combine into the hash code.</typeparam>
/// <typeparam name="T3">The type of the third value to combine into the hash code.</typeparam>
/// <typeparam name="T4">The type of the fourth value to combine into the hash code.</typeparam>
/// <typeparam name="T5">The type of the fifth value to combine into the hash code.</typeparam>
/// <param name="value1">The first value to combine into the hash code.</param>
/// <param name="value2">The second value to combine into the hash code.</param>
/// <param name="value3">The third value to combine into the hash code.</param>
/// <param name="value4">The fourth value to combine into the hash code.</param>
/// <param name="value5">The fifth value to combine into the hash code.</param>
/// <returns>The hash code that represents the values.</returns>
public static int Combine<T1, T2, T3, T4, T5>(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5)
{
uint hc1 = (uint)(value1?.GetHashCode() ?? 0);
uint hc2 = (uint)(value2?.GetHashCode() ?? 0);
uint hc3 = (uint)(value3?.GetHashCode() ?? 0);
uint hc4 = (uint)(value4?.GetHashCode() ?? 0);
uint hc5 = (uint)(value5?.GetHashCode() ?? 0);
Initialize(out uint v1, out uint v2, out uint v3, out uint v4);
v1 = Round(v1, hc1);
v2 = Round(v2, hc2);
v3 = Round(v3, hc3);
v4 = Round(v4, hc4);
uint hash = MixState(v1, v2, v3, v4);
hash += 20;
hash = QueueRound(hash, hc5);
hash = MixFinal(hash);
return (int)hash;
}
/// <summary>
/// Combines six values into a hash code.
/// </summary>
@@ -20,28 +191,303 @@ internal struct HashCode
/// <param name="value4">The fourth value to combine into the hash code.</param>
/// <param name="value5">The fifth value to combine into the hash code.</param>
/// <param name="value6">The sixth value to combine into the hash code.</param>
/// <returns>The hash code that represents the six values.</returns>
/// <returns>The hash code that represents the values.</returns>
public static int Combine<T1, T2, T3, T4, T5, T6>(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6)
{
throw new NotSupportedException();
uint hc1 = (uint)(value1?.GetHashCode() ?? 0);
uint hc2 = (uint)(value2?.GetHashCode() ?? 0);
uint hc3 = (uint)(value3?.GetHashCode() ?? 0);
uint hc4 = (uint)(value4?.GetHashCode() ?? 0);
uint hc5 = (uint)(value5?.GetHashCode() ?? 0);
uint hc6 = (uint)(value6?.GetHashCode() ?? 0);
Initialize(out uint v1, out uint v2, out uint v3, out uint v4);
v1 = Round(v1, hc1);
v2 = Round(v2, hc2);
v3 = Round(v3, hc3);
v4 = Round(v4, hc4);
uint hash = MixState(v1, v2, v3, v4);
hash += 24;
hash = QueueRound(hash, hc5);
hash = QueueRound(hash, hc6);
hash = MixFinal(hash);
return (int)hash;
}
/// <summary>
/// Adds a single value to the hash code.
/// Combines seven values into a hash code.
/// </summary>
/// <typeparam name="T">The type of the value to add to the hash code.</typeparam>
/// <param name="value">The value to add to the hash code.</param>
/// <typeparam name="T1">The type of the first value to combine into the hash code.</typeparam>
/// <typeparam name="T2">The type of the second value to combine into the hash code.</typeparam>
/// <typeparam name="T3">The type of the third value to combine into the hash code.</typeparam>
/// <typeparam name="T4">The type of the fourth value to combine into the hash code.</typeparam>
/// <typeparam name="T5">The type of the fifth value to combine into the hash code.</typeparam>
/// <typeparam name="T6">The type of the sixth value to combine into the hash code.</typeparam>
/// <typeparam name="T7">The type of the seventh value to combine into the hash code.</typeparam>
/// <param name="value1">The first value to combine into the hash code.</param>
/// <param name="value2">The second value to combine into the hash code.</param>
/// <param name="value3">The third value to combine into the hash code.</param>
/// <param name="value4">The fourth value to combine into the hash code.</param>
/// <param name="value5">The fifth value to combine into the hash code.</param>
/// <param name="value6">The sixth value to combine into the hash code.</param>
/// <param name="value7">The seventh value to combine into the hash code.</param>
/// <returns>The hash code that represents the values.</returns>
public static int Combine<T1, T2, T3, T4, T5, T6, T7>(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7)
{
uint hc1 = (uint)(value1?.GetHashCode() ?? 0);
uint hc2 = (uint)(value2?.GetHashCode() ?? 0);
uint hc3 = (uint)(value3?.GetHashCode() ?? 0);
uint hc4 = (uint)(value4?.GetHashCode() ?? 0);
uint hc5 = (uint)(value5?.GetHashCode() ?? 0);
uint hc6 = (uint)(value6?.GetHashCode() ?? 0);
uint hc7 = (uint)(value7?.GetHashCode() ?? 0);
Initialize(out uint v1, out uint v2, out uint v3, out uint v4);
v1 = Round(v1, hc1);
v2 = Round(v2, hc2);
v3 = Round(v3, hc3);
v4 = Round(v4, hc4);
uint hash = MixState(v1, v2, v3, v4);
hash += 28;
hash = QueueRound(hash, hc5);
hash = QueueRound(hash, hc6);
hash = QueueRound(hash, hc7);
hash = MixFinal(hash);
return (int)hash;
}
/// <summary>
/// Combines eight values into a hash code.
/// </summary>
/// <typeparam name="T1">The type of the first value to combine into the hash code.</typeparam>
/// <typeparam name="T2">The type of the second value to combine into the hash code.</typeparam>
/// <typeparam name="T3">The type of the third value to combine into the hash code.</typeparam>
/// <typeparam name="T4">The type of the fourth value to combine into the hash code.</typeparam>
/// <typeparam name="T5">The type of the fifth value to combine into the hash code.</typeparam>
/// <typeparam name="T6">The type of the sixth value to combine into the hash code.</typeparam>
/// <typeparam name="T7">The type of the seventh value to combine into the hash code.</typeparam>
/// <typeparam name="T8">The type of the eigth value to combine into the hash code.</typeparam>
/// <param name="value1">The first value to combine into the hash code.</param>
/// <param name="value2">The second value to combine into the hash code.</param>
/// <param name="value3">The third value to combine into the hash code.</param>
/// <param name="value4">The fourth value to combine into the hash code.</param>
/// <param name="value5">The fifth value to combine into the hash code.</param>
/// <param name="value6">The sixth value to combine into the hash code.</param>
/// <param name="value7">The seventh value to combine into the hash code.</param>
/// <param name="value8">The eigth value to combine into the hash code.</param>
/// <returns>The hash code that represents the values.</returns>
public static int Combine<T1, T2, T3, T4, T5, T6, T7, T8>(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7, T8 value8)
{
uint hc1 = (uint)(value1?.GetHashCode() ?? 0);
uint hc2 = (uint)(value2?.GetHashCode() ?? 0);
uint hc3 = (uint)(value3?.GetHashCode() ?? 0);
uint hc4 = (uint)(value4?.GetHashCode() ?? 0);
uint hc5 = (uint)(value5?.GetHashCode() ?? 0);
uint hc6 = (uint)(value6?.GetHashCode() ?? 0);
uint hc7 = (uint)(value7?.GetHashCode() ?? 0);
uint hc8 = (uint)(value8?.GetHashCode() ?? 0);
Initialize(out uint v1, out uint v2, out uint v3, out uint v4);
v1 = Round(v1, hc1);
v2 = Round(v2, hc2);
v3 = Round(v3, hc3);
v4 = Round(v4, hc4);
v1 = Round(v1, hc5);
v2 = Round(v2, hc6);
v3 = Round(v3, hc7);
v4 = Round(v4, hc8);
uint hash = MixState(v1, v2, v3, v4);
hash += 32;
hash = MixFinal(hash);
return (int)hash;
}
/// <summary>
/// Adds a single value to the current hash.
/// </summary>
/// <typeparam name="T">The type of the value to add into the hash code.</typeparam>
/// <param name="value">The value to add into the hash code.</param>
public void Add<T>(T value)
{
throw new NotSupportedException();
Add(value?.GetHashCode() ?? 0);
}
/// <summary>
/// Calculates the final hash code after consecutive <see cref="Add{T}(T)"/> invocations.
/// Adds a single value to the current hash.
/// </summary>
/// <returns>The calculated hash code.</returns>
/// <typeparam name="T">The type of the value to add into the hash code.</typeparam>
/// <param name="value">The value to add into the hash code.</param>
/// <param name="comparer">The <see cref="IEqualityComparer{T}"/> instance to use.</param>
public void Add<T>(T value, IEqualityComparer<T>? comparer)
{
Add(value is null ? 0 : (comparer?.GetHashCode(value) ?? value.GetHashCode()));
}
/// <summary>
/// Adds a span of bytes to the hash code.
/// </summary>
/// <param name="value">The span.</param>
public void AddBytes(ReadOnlySpan<byte> value)
{
ref byte pos = ref MemoryMarshal.GetReference(value);
ref byte end = ref Unsafe.Add(ref pos, value.Length);
while ((nint)Unsafe.ByteOffset(ref pos, ref end) >= sizeof(int))
{
Add(Unsafe.ReadUnaligned<int>(ref pos));
pos = ref Unsafe.Add(ref pos, sizeof(int));
}
while (Unsafe.IsAddressLessThan(ref pos, ref end))
{
Add((int)pos);
pos = ref Unsafe.Add(ref pos, 1);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void Initialize(out uint v1, out uint v2, out uint v3, out uint v4)
{
v1 = seed + Prime1 + Prime2;
v2 = seed + Prime2;
v3 = seed;
v4 = seed - Prime1;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static uint Round(uint hash, uint input)
{
return RotateLeft(hash + input * Prime2, 13) * Prime1;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static uint QueueRound(uint hash, uint queuedValue)
{
return RotateLeft(hash + queuedValue * Prime3, 17) * Prime4;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static uint MixState(uint v1, uint v2, uint v3, uint v4)
{
return RotateLeft(v1, 1) + RotateLeft(v2, 7) + RotateLeft(v3, 12) + RotateLeft(v4, 18);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static uint MixEmptyState()
{
return seed + Prime5;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static uint MixFinal(uint hash)
{
hash ^= hash >> 15;
hash *= Prime2;
hash ^= hash >> 13;
hash *= Prime3;
hash ^= hash >> 16;
return hash;
}
private void Add(int value)
{
uint val = (uint)value;
uint previousLength = length++;
uint position = previousLength % 4;
if (position == 0)
{
queue1 = val;
}
else if (position == 1)
{
queue2 = val;
}
else if (position == 2)
{
queue3 = val;
}
else
{
if (previousLength == 3)
{
Initialize(out v1, out v2, out v3, out v4);
}
v1 = Round(v1, queue1);
v2 = Round(v2, queue2);
v3 = Round(v3, queue3);
v4 = Round(v4, val);
}
}
/// <summary>
/// Gets the resulting hashcode from the current instance.
/// </summary>
/// <returns>The resulting hashcode from the current instance.</returns>
public int ToHashCode()
{
throw new NotSupportedException();
uint length = this.length;
uint position = length % 4;
uint hash = length < 4 ? MixEmptyState() : MixState(v1, v2, v3, v4);
hash += length * 4;
if (position > 0)
{
hash = QueueRound(hash, queue1);
if (position > 1)
{
hash = QueueRound(hash, queue2);
if (position > 2)
{
hash = QueueRound(hash, queue3);
}
}
}
hash = MixFinal(hash);
return (int)hash;
}
/// <inheritdoc/>
[Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes. Use ToHashCode to retrieve the computed hash code.", error: true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => throw new NotSupportedException();
/// <inheritdoc/>
[Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes.", error: true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj) => throw new NotSupportedException();
/// <summary>
/// Rotates the specified value left by the specified number of bits.
/// Similar in behavior to the x86 instruction ROL.
/// </summary>
/// <param name="value">The value to rotate.</param>
/// <param name="offset">The number of bits to rotate by.
/// Any value outside the range [0..31] is treated as congruent mod 32.</param>
/// <returns>The rotated value.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static uint RotateLeft(uint value, int offset)
{
return (value << offset) | (value >> (32 - offset));
}
}
@@ -0,0 +1,258 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Text;
using ComputeSharp.__Internals;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618, RS1024
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
public sealed partial class IShaderGenerator
{
/// <inheritdoc/>
internal static partial class BuildHlslString
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.
/// </summary>
/// <param name="hlslSourceInfo">The input <see cref="HlslShaderSourceInfo"/> instance to use.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(HlslShaderSourceInfo hlslSourceInfo)
{
ImmutableArray<StatementSyntax> bodyStatements = GenerateRenderMethodBody(hlslSourceInfo);
// This code produces a method declaration as follows:
//
// readonly void global::ComputeSharp.__Internals.IShader.BuildHlslString(ref global::ComputeSharp.__Internals.ArrayPoolStringBuilder builder, int threadsX, int threadsY, int threadsZ)
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.VoidKeyword)),
Identifier("BuildHlslString"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddParameterListParameters(
Parameter(Identifier("builder")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder")),
Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))))
.WithBody(Block(bodyStatements));
}
/// <summary>
/// Produces the series of statements to build the current HLSL source.
/// </summary>
/// <param name="hlslSourceInfo">The input <see cref="HlslShaderSourceInfo"/> instance to use.</param>
/// <returns>The series of statements to build the HLSL source to compile to execute the current shader.</returns>
private static ImmutableArray<StatementSyntax> GenerateRenderMethodBody(HlslShaderSourceInfo hlslSourceInfo)
{
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
StringBuilder textBuilder = new();
int capturedDelegates = 0;
int prologueStatements = 0;
int sizeHint = 64;
void AppendLF()
{
textBuilder.Append('\n');
}
void AppendLine(string text)
{
textBuilder.Append(text);
}
void AppendParsedStatement(string text)
{
FlushText();
statements.Add(ParseStatement(text));
}
void FlushText()
{
if (textBuilder.Length > 0)
{
string text = textBuilder.ToString();
textBuilder.Append(text);
sizeHint += textBuilder.Length;
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append")))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(text))))));
textBuilder.Clear();
}
}
// 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 (var 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);");
AppendLine(hlslSourceInfo.ThreadsY);
AppendParsedStatement("builder.Append(threadsY);");
AppendLine(hlslSourceInfo.ThreadsZ);
AppendParsedStatement("builder.Append(threadsZ);");
// 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);
FlushText();
// builder = global::ComputeSharp.__Internals.ArrayPoolStringBuilder.Create(<SIZE_HINT>);
statements.Insert(
prologueStatements,
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName("builder"),
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("global::ComputeSharp.__Internals.ArrayPoolStringBuilder"),
IdentifierName("Create")))
.AddArgumentListArguments(
Argument(LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(sizeHint)))))));
return statements.ToImmutable();
}
}
}
ファイル差分が大きすぎるため表示されません。 差分を読み込み
@@ -0,0 +1,98 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
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/>
public sealed partial class IShaderGenerator
{
/// <inheritdoc/>
private static 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>
[Pure]
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;
blockStatements.Add(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);
}
}
}
+16 -84
ファイルの表示
@@ -1,101 +1,33 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
using ComputeSharp.__Internals;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
public sealed partial class IShaderGenerator
{
/// <inheritdoc/>
private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol, out bool isDynamicShader)
{
// 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(structDeclarationSymbol, out isDynamicShader));
}
/// <summary>
/// Gets a <see cref="BlockSyntax"/> instance with the logic to compute the hashcode of a given shader type.
/// A helper with all logic to generate the <c>GetDispatchId</c> method.
/// </summary>
/// <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>
/// <returns>The <see cref="BlockSyntax"/> instance to hash the input shader.</returns>
[Pure]
private static BlockSyntax GetShaderHashCodeBody(INamedTypeSymbol structDeclarationSymbol, out bool isDynamicShader)
private static partial class GetDispatchId
{
var delegateFields = structDeclarationSymbol
.GetMembers()
.OfType<IFieldSymbol>()
.Where(static m => m.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false })
.ToImmutableArray();
isDynamicShader = delegateFields.Length > 0;
if (delegateFields.Length == 0)
/// <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>
[Pure]
public static ImmutableArray<string> GetInfo(INamedTypeSymbol structDeclarationSymbol)
{
// return 0;
return
Block(ReturnStatement(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))));
structDeclarationSymbol
.GetMembers()
.OfType<IFieldSymbol>()
.Where(static member => member.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false })
.Select(static member => member.Name)
.ToImmutableArray();
}
List<StatementSyntax> blockStatements = new(4);
// global::System.HashCode hashCode = default;
blockStatements.Add(LocalDeclarationStatement(
VariableDeclaration(IdentifierName("global::System.HashCode"))
.AddVariables(
VariableDeclarator(Identifier("hashCode"))
.WithInitializer(EqualsValueClause(
LiteralExpression(
SyntaxKind.DefaultLiteralExpression,
Token(SyntaxKind.DefaultKeyword)))))));
foreach (IFieldSymbol fieldSymbol in delegateFields)
{
// hashCode.Add(delegateField.Method);
blockStatements.Add(ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("hashCode"),
IdentifierName("Add")))
.AddArgumentListArguments(Argument(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(fieldSymbol.Name),
IdentifierName("Method"))))));
}
// return hashCode.ToHashCode();
blockStatements.Add(ReturnStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("hashCode"),
IdentifierName("ToHashCode")))));
return Block(blockStatements);
}
}
@@ -0,0 +1,249 @@
using System;
using System.Collections.Immutable;
using ComputeSharp.__Internals;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
public sealed partial class IShaderGenerator
{
/// <inheritdoc/>
private static partial class LoadDispatchData
{
/// <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="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,
ImmutableArray<FieldInfo> fieldInfos,
int resourceCount,
int root32BitConstantsCount)
{
// This code produces a method declaration as follows:
//
// readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData<TDataLoader>(ref TDataLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z)
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.VoidKeyword)),
Identifier("LoadDispatchData"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader")))
.AddParameterListParameters(
Parameter(Identifier("loader"))
.AddModifiers(Token(SyntaxKind.RefKeyword))
.WithType(IdentifierName("TDataLoader")),
Parameter(Identifier("device")).WithType(IdentifierName("global::ComputeSharp.GraphicsDevice")),
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)));
}
/// <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="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,
ImmutableArray<FieldInfo> fieldInfos,
int resourceCount,
int root32BitConstantsCount)
{
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
bool isComputeShader = shaderInterfaceType == typeof(IComputeShader);
// Append the statements for the dispatch ranges:
//
// span0[0] = (uint)x;
// span0[1] = (uint)y;
// span0[2] = (uint)z;
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x")))));
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("y")))));
// If the shader is a compute shader, also track the bounds on the Z axis
if (isComputeShader)
{
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z")))));
}
// Generate loading statements for each captured field
foreach (FieldInfo fieldInfo in fieldInfos)
{
switch (fieldInfo)
{
case FieldInfo.Resource resource:
// Validate the resource and get a handle for it. This will generate:
//
// global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, <OFFSET>) =
// global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(<FIELD_NAME>, device);
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resource.Offset})"),
ParseExpression($"global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({resource.FieldName}, device)"))));
break;
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")))));
if (resourceCount > 0)
{
// global::System.Span<ulong> span1 = stackalloc ulong[<RESOURCES>];
statements.Insert(1,
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("global::System.Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword))))
.AddVariables(
VariableDeclarator(Identifier("span1"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceCount)))))))))));
// ref ulong r1 = ref span1[0];
statements.Insert(3,
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r1"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span1"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))))))))));
// loader.LoadCapturedResources(span1);
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("loader"),
IdentifierName("LoadCapturedResources")))
.AddArgumentListArguments(Argument(IdentifierName("span1")))));
}
return statements.ToImmutable();
}
}
}
+162 -304
ファイルの表示
@@ -1,335 +1,193 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using ComputeSharp.__Internals;
using System.Runtime.CompilerServices;
using ComputeSharp.Core.Helpers;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.Mappings;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
public sealed partial class IShaderGenerator
{
/// <inheritdoc/>
private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod(
GeneratorExecutionContext context,
INamedTypeSymbol structDeclarationSymbol,
out IReadOnlyCollection<string> discoveredResources,
out int root32BitConstantsCount)
{
// This code produces a method declaration as follows:
//
// readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData<TDataLoader>(ref TDataLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z)
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.VoidKeyword)),
Identifier("LoadDispatchData"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddTypeParameterListParameters(TypeParameter(Identifier("TDataLoader")))
.AddParameterListParameters(
Parameter(Identifier("loader"))
.AddModifiers(Token(SyntaxKind.RefKeyword))
.WithType(IdentifierName("TDataLoader")),
Parameter(Identifier("device")).WithType(IdentifierName("global::ComputeSharp.GraphicsDevice")),
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(context, structDeclarationSymbol, out discoveredResources, out root32BitConstantsCount)));
}
/// <summary>
/// Gets a sequence of statements to load the dispatch data for a given shader.
/// A helper with all logic to generate the <c>LoadDispatchData</c> method.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="discoveredResources">The collection of discovered resources in the current shader type.</param>
/// <param name="root32BitConstantsCount">The total number of 32 bit root constants being loaded for the current shader type.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
private static IEnumerable<StatementSyntax> GetDispatchDataLoadingStatements(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, out IReadOnlyCollection<string> discoveredResources, out int root32BitConstantsCount)
private static partial class LoadDispatchData
{
List<StatementSyntax> statements = new();
List<string> resources = new();
discoveredResources = resources;
var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) });
var isComputeShader = pixelShaderSymbol is null;
int resourceOffset = 0;
int rawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2);
// Append the statements for the dispatch ranges:
//
// span0[0] = (uint)x;
// span0[1] = (uint)y;
// span0[2] = (uint)z;
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x")))));
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("y")))));
if (isComputeShader)
/// <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="shaderInterfaceType">The type of shader interface urrently 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,
out int resourceCount,
out int root32BitConstantCount,
out ImmutableArray<Diagnostic> diagnostics)
{
statements.Add(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))),
CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z")))));
// Helper method that uses boxes instead of ref-s (illegal in enumerators)
static IEnumerable<FieldInfo> GetCapturedFieldInfos(
ITypeSymbol currentTypeSymbol,
ImmutableArray<string> fieldPath,
StrongBox<int> resourceOffset,
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" or "device" or "x" or "y" or "z")
{
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.IsTypedResourceType(typeName))
{
yield return new FieldInfo.Resource(fieldName, typeName, resourceOffset.Value++);
}
else 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), resourceOffset, rawDataOffset))
{
yield return fieldInfo;
}
}
}
}
ImmutableArray<Diagnostic>.Builder builder = ImmutableArray.CreateBuilder<Diagnostic>();
// 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);
int initialRawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2);
StrongBox<int> resourceOffsetAsBox = new();
StrongBox<int> rawDataOffsetAsBox = new(initialRawDataOffset);
// Traverse all shader fields and gather info, and update the tracking offsets
ImmutableArray<FieldInfo> fieldInfos = GetCapturedFieldInfos(
structDeclarationSymbol,
ImmutableArray<string>.Empty,
resourceOffsetAsBox,
rawDataOffsetAsBox).ToImmutableArray();
resourceCount = resourceOffsetAsBox.Value;
// 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 + resourceCount;
if (rootSignatureDwordSize > 64)
{
builder.Add(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol);
}
diagnostics = builder.ToImmutable();
return fieldInfos;
}
// Append the statements to load all fields (both resources and other captured values)
AppendFields(structDeclarationSymbol, Array.Empty<string>(), ref resourceOffset, ref rawDataOffset, resources, statements);
// 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.
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, sizeof(int));
root32BitConstantsCount = rawDataOffset / 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 = root32BitConstantsCount + resourceOffset;
if (rootSignatureDwordSize > 64)
/// <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)
{
context.ReportDiagnostic(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol);
}
// 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);
// 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")))));
if (resourceOffset > 0)
{
// global::System.Span<ulong> span1 = stackalloc ulong[<RESOURCES>];
statements.Insert(1,
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("global::System.Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword))))
.AddVariables(
VariableDeclarator(Identifier("span1"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceOffset)))))))))));
// ref ulong r1 = ref span1[0];
statements.Insert(3,
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r1"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span1"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))))))))));
// loader.LoadCapturedResources(span1);
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName("loader"),
IdentifierName("LoadCapturedResources")))
.AddArgumentListArguments(Argument(IdentifierName("span1")))));
}
return statements;
}
/// <summary>
/// Explores a given type hierarchy and generates statements to load fields.
/// </summary>
/// <param name="currentTypeSymbol">The current type being explored.</param>
/// <param name="fieldPath">The current path of the field with respect to the shader instance.</param>
/// <param name="resourceOffset">The current offset in the root table of loaded resources.</param>
/// <param name="rawDataOffset">The current offset within the loaded data buffer.</param>
/// <param name="resources">The target list of resources in the current shader type.</param>
/// <param name="statements">The target list of statements being generated.</param>
private static void AppendFields(ITypeSymbol currentTypeSymbol, IReadOnlyCollection<string> fieldPath, ref int resourceOffset, ref int rawDataOffset, ICollection<string> resources, ICollection<StatementSyntax> statements)
{
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" or "device" or "x" or "y" or "z")
// 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))
{
fieldName = $"this.{fieldName}";
}
ImmutableArray<int>.Builder builder = ImmutableArray.CreateBuilder<int>(rows);
// The first item in each nested struct needs to be aligned to 16 bytes
if (isFirstField && fieldPath.Count > 0)
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
{
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
// 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);
isFirstField = false;
rawDataOffset = startingRawDataOffset + fieldSize;
return new FieldInfo.Primitive(fieldPath, typeName, startingRawDataOffset);
}
if (HlslKnownTypes.IsTypedResourceType(typeName))
{
resources.Add(typeName);
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++})"),
ParseExpression($"global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({fieldName}, device)"))));
}
else if (HlslKnownTypes.IsKnownHlslType(typeName))
{
AppendHlslKnownTypeField(fieldPath.Concat(new[] { fieldName }), typeName, ref rawDataOffset, statements);
}
else if (fieldSymbol.Type.IsUnmanagedType)
{
// Custom struct type defined by the user
AppendFields(fieldSymbol.Type, fieldPath.Concat(new[] { fieldName }).ToArray(), ref resourceOffset, ref rawDataOffset, resources, statements);
}
}
}
/// <summary>
/// Generates a loading statement for a known HLSL primitive type field (scalar, vector or 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>
/// <param name="statements">The target list of statements being generated.</param>
private static void AppendHlslKnownTypeField(IEnumerable<string> fieldPath, string typeName, ref int rawDataOffset, ICollection<StatementSyntax> statements)
{
// 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))
{
string rowTypeName = $"global::ComputeSharp.{elementName}{columns}";
string rowLocalName = $"__{string.Join("_", fieldPath)}__row0";
statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As<global::{typeName}, {rowTypeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", 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 < rows; j++)
{
rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16);
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){rawDataOffset}))"),
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})"))));
rawDataOffset += fieldPack * columns;
}
}
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.
rawDataOffset = AlignmentHelper.AlignToBoundary(
AlignmentHelper.Pad(rawDataOffset, fieldPack),
fieldSize,
16);
statements.Add(ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As<uint, global::{typeName}>(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"),
ParseExpression($"{string.Join(".", fieldPath)}"))));
rawDataOffset += fieldSize;
}
}
}
@@ -0,0 +1,136 @@
using System;
using System.Collections.Immutable;
using ComputeSharp.__Internals;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
public sealed partial class IShaderGenerator
{
/// <inheritdoc/>
private static partial class LoadDispatchMetadata
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.
/// </summary>
/// <param name="metadataInfo">The dispatch metadata for the current shader..</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(DispatchMetadataInfo metadataInfo)
{
// This code produces a method declaration as follows:
//
// readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata<TMetadataLoader>(ref TMetadataLoader loader, out global::System.IntPtr result)
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.VoidKeyword)),
Identifier("LoadDispatchMetadata"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddTypeParameterListParameters(TypeParameter(Identifier("TMetadataLoader")))
.AddParameterListParameters(
Parameter(Identifier("loader"))
.AddModifiers(Token(SyntaxKind.RefKeyword))
.WithType(IdentifierName("TMetadataLoader")),
Parameter(Identifier("result"))
.AddModifiers(Token(SyntaxKind.OutKeyword))
.WithType(IdentifierName($"global::System.{typeof(IntPtr).Name}")))
.WithBody(Block(GetDispatchMetadataLoadingStatements(metadataInfo)));
}
/// <summary>
/// Gets a sequence of statements to load the dispatch metadata for a given shader type.
/// </summary>
/// <param name="metadataInfo">The dispatch metadata for the current shader..</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
private static ImmutableArray<StatementSyntax> GetDispatchMetadataLoadingStatements(DispatchMetadataInfo metadataInfo)
{
ImmutableArray<StatementSyntax>.Builder statements = ImmutableArray.CreateBuilder<StatementSyntax>();
// global::System.Span<byte> span0 = stackalloc byte[5];
statements.Add(
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("global::System.Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.AddVariables(
VariableDeclarator(Identifier("span0"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5)))))))))));
// Compute the total number of resources
int totalResourcesCount = metadataInfo.ResourceDescriptors.Length;
// Span<global::ComputeSharp.__Internals.ResourceDescriptor> span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[<ADJUSTED_COUNT>];
statements.Add(
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("global::System.Span"))
.AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")))
.AddVariables(
VariableDeclarator(Identifier("span1"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount)))))))))));
// ref byte r0 = ref span0[0];
statements.Add(
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r0"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))))))))));
// ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0];
statements.Add(
LocalDeclarationStatement(
VariableDeclaration(RefType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")))
.AddVariables(
VariableDeclarator(Identifier("r1"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span1"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0))))))))));
// Serialized shader metadata
statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned<int>(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {metadataInfo.Root32BitConstantCount});"));
statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned<bool>(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {metadataInfo.IsSamplerUsed.ToString().ToLowerInvariant()});"));
// Populate the sequence of resource descriptors
foreach (ResourceDescriptor descriptor in metadataInfo.ResourceDescriptors)
{
statements.Add(ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create({descriptor.TypeId}, {descriptor.RegisterOffset}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {descriptor.Offset}));"));
}
// Invoke the value delegate to create the opaque root signature handle
statements.Add(ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);"));
return statements.ToImmutable();
}
}
}
+47 -139
ファイルの表示
@@ -1,156 +1,64 @@
using System;
using System.Collections.Generic;
using ComputeSharp.__Internals;
using System.Collections.Immutable;
using ComputeSharp.SourceGenerators.Mappings;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
using ComputeSharp.SourceGenerators.Models;
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
public sealed partial class IShaderGenerator
{
/// <inheritdoc/>
private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod(
string? implicitTextureType,
IReadOnlyCollection<string> discoveredResources,
int root32BitConstantsCount,
bool isSamplerUsed)
{
// This code produces a method declaration as follows:
//
// readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata<TMetadataLoader>(ref TMetadataLoader loader, out global::System.IntPtr result)
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.VoidKeyword)),
Identifier("LoadDispatchMetadata"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddTypeParameterListParameters(TypeParameter(Identifier("TMetadataLoader")))
.AddParameterListParameters(
Parameter(Identifier("loader"))
.AddModifiers(Token(SyntaxKind.RefKeyword))
.WithType(IdentifierName("TMetadataLoader")),
Parameter(Identifier("result"))
.AddModifiers(Token(SyntaxKind.OutKeyword))
.WithType(IdentifierName($"global::System.{typeof(IntPtr).Name}")))
.WithBody(Block(GetDispatchMetadataLoadingStatements(implicitTextureType, discoveredResources, root32BitConstantsCount, isSamplerUsed)));
}
/// <summary>
/// Gets a sequence of statements to load the dispatch metadata for a given shader type.
/// A helper with all logic to generate the <c>LoadDispatchMetadata</c> method.
/// </summary>
/// <param name="implicitTextureType">The implicit texture type, if available (if the shader is a pixel shader).</param>
/// <param name="discoveredResources">The collection of resources used by the shader.</param>
/// <param name="root32BitConstantsCount">The total number of 32 bit root constants being loaded for the shader.</param>
/// <param name="isSamplerUsed">Whether or not the shader requires a static sampler to be available.</param>
/// <returns>The sequence of <see cref="StatementSyntax"/> instances to load shader dispatch data.</returns>
private static IEnumerable<StatementSyntax> GetDispatchMetadataLoadingStatements(
string? implicitTextureType,
IReadOnlyCollection<string> discoveredResources,
int root32BitConstantsCount,
bool isSamplerUsed)
private static partial class LoadDispatchMetadata
{
// global::System.Span<byte> span0 = stackalloc byte[5];
yield return
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("global::System.Span"))
.AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.AddVariables(
VariableDeclarator(Identifier("span0"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5))))))))));
// Compute the total number of resources (discovered ones and the implicit target texture, if present)
int totalResourcesCount = discoveredResources.Count + (implicitTextureType is not null ? 1 : 0);
// Span<global::ComputeSharp.__Internals.ResourceDescriptor> span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[<ADJUSTED_COUNT>];
yield return
LocalDeclarationStatement(
VariableDeclaration(
GenericName(Identifier("global::System.Span"))
.AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")))
.AddVariables(
VariableDeclarator(Identifier("span1"))
.WithInitializer(EqualsValueClause(
StackAllocArrayCreationExpression(
ArrayType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))
.AddRankSpecifiers(
ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount))))))))));
// ref byte r0 = ref span0[0];
yield return
LocalDeclarationStatement(
VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword))))
.AddVariables(
VariableDeclarator(Identifier("r0"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span0"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0)))))))));
// ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0];
yield return
LocalDeclarationStatement(
VariableDeclaration(RefType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")))
.AddVariables(
VariableDeclarator(Identifier("r1"))
.WithInitializer(EqualsValueClause(
RefExpression(
ElementAccessExpression(IdentifierName("span1"))
.AddArgumentListArguments(Argument(
LiteralExpression(
SyntaxKind.NumericLiteralExpression,
Literal(0)))))))));
// Serialized shader metadata
yield return ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned<int>(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {root32BitConstantsCount});");
yield return ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned<bool>(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {isSamplerUsed.ToString().ToLowerInvariant()});");
int constantBufferOffset = 1;
int readOnlyResourceOffset = 0;
int readWriteResourceOffset = 0;
int resourceOffset = 0;
// Add the implicit texture descriptor, if needed
if (implicitTextureType is not null)
/// <summary>
/// Gets the data related to the shader metadata for a given shader type.
/// </summary>
/// <param name="root32BitConstantCount">The total number of needed 32 bit constants in the shader root signature.</param>
/// <param name="isImplicitTextureUsed">Indicates whether the current shader uses an implicit texture.</param>
/// <param name="isSamplerUsed">Whether the static sampler is used by the shader.</param>
/// <param name="capturedFields">The sequence of captured fields for the shader.</param>
/// <returns>The metadata info for the shader.</returns>
public static DispatchMetadataInfo GetInfo(
int root32BitConstantCount,
bool isImplicitTextureUsed,
bool isSamplerUsed,
ImmutableArray<FieldInfo> capturedFields)
{
yield return ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create(1, {readWriteResourceOffset++}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++}));");
}
ImmutableArray<ResourceDescriptor>.Builder descriptors = ImmutableArray.CreateBuilder<ResourceDescriptor>();
int constantBufferOffset = 1;
int readOnlyResourceOffset = 0;
int readWriteResourceOffset = 0;
int resourceOffset = 0;
// Populate the sequence of resource descriptors
foreach (var resource in discoveredResources)
{
if (HlslKnownTypes.IsConstantBufferType(resource))
// Add the implicit texture descriptor, if needed
if (isImplicitTextureUsed)
{
yield return ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create(2, {constantBufferOffset++}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++}));");
}
else if (HlslKnownTypes.IsReadOnlyTypedResourceType(resource))
{
yield return ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create(0, {readOnlyResourceOffset++}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++}));");
descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++, resourceOffset++));
}
else
{
yield return ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create(1, {readWriteResourceOffset++}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++}));");
}
}
// Invoke the value delegate to create the opaque root signature handle
yield return ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);");
// Populate the sequence of resource descriptors
foreach (FieldInfo.Resource resource in capturedFields.OfType<FieldInfo.Resource>())
{
if (HlslKnownTypes.IsConstantBufferType(resource.TypeName))
{
descriptors.Add(new ResourceDescriptor(2, constantBufferOffset++, resourceOffset++));
}
else if (HlslKnownTypes.IsReadOnlyTypedResourceType(resource.TypeName))
{
descriptors.Add(new ResourceDescriptor(0, readOnlyResourceOffset++, resourceOffset++));
}
else
{
descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++, resourceOffset++));
}
}
return new(
root32BitConstantCount,
isSamplerUsed,
descriptors.ToImmutable());
}
}
}
@@ -0,0 +1,191 @@
using System;
using System.Diagnostics.Contracts;
using ComputeSharp.__Internals;
using ComputeSharp.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.SourceGenerators;
/// <inheritdoc/>
public sealed partial class IShaderGenerator
{
/// <inheritdoc/>
private static partial class TryGetBytecode
{
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>TryGetBytecode</c> method.
/// </summary>
/// <param name="bytecodeInfo">The input <see cref="EmbeddedBytecodeInfo"/> instance.</param>
/// <param name="fixup">An opaque <see cref="Func{TResult}"/> instance to transform the final tree into text.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.</returns>
public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeInfo bytecodeInfo, out Func<SyntaxNode, string> fixup)
{
BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, out string? bytecodeLiterals);
if (bytecodeLiterals is not null)
{
fixup = tree => tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals);
}
else
{
fixup = static tree => tree.ToFullString();
}
// This code produces a method declaration as follows:
//
// readonly int global::ComputeSharp.__Internals.IShader.TryGetBytecode(int threadsX, int threadsY, int threadsZ, out ReadOnlySpan<byte> bytecode)
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.BoolKeyword)),
Identifier("TryGetBytecode"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddParameterListParameters(
Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("bytecode")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::System.ReadOnlySpan<byte>")))
.WithBody(block);
}
/// <summary>
/// Gets a <see cref="BlockSyntax"/> instance with the logic to try to get a compiled shader bytecode.
/// </summary>
/// <param name="bytecodeInfo">The input <see cref="EmbeddedBytecodeInfo"/> instance.</param>
/// <param name="bytecodeLiterals">The resulting bytecode literals to insert into the final source code.</param>
/// <returns>The <see cref="BlockSyntax"/> instance trying to retrieve the precompiled shader.</returns>
[Pure]
private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, out string? bytecodeLiterals)
{
if (bytecodeInfo.Bytecode.IsEmpty)
{
bytecodeLiterals = null;
// This code produces a method declaration as follows:
//
// bytecode = default;
//
// return false;
return
Block(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName("bytecode"),
LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))),
ReturnStatement(
LiteralExpression(
SyntaxKind.FalseLiteralExpression)));
}
bytecodeLiterals = BuildShaderBytecodeExpressionString(bytecodeInfo.Bytecode.AsSpan());
// This code produces a method declaration as follows:
//
// if (threadsX == <X> && threadsY == <Y> && threadsZ == <Z>)
// {
// bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE };
//
// return true;
// }
//
// bytecode = default;
//
// return false;
//
// Note that the __EMBEDDED_SHADER_BYTECODE identifier will be replaced after the string
// is created by the generator. This greatly speeds up the code generation, as it avoids
// having to create/parse tens of thousands of literal expression nodes for every shader.
return
Block(
IfStatement(
BinaryExpression(
SyntaxKind.LogicalAndExpression,
BinaryExpression(
SyntaxKind.LogicalAndExpression,
BinaryExpression(
SyntaxKind.EqualsExpression,
IdentifierName("threadsX"),
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.X))),
BinaryExpression(
SyntaxKind.EqualsExpression,
IdentifierName("threadsY"),
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Y)))),
BinaryExpression(
SyntaxKind.EqualsExpression,
IdentifierName("threadsZ"),
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Z)))),
Block(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName("bytecode"),
ArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(
InitializerExpression(
SyntaxKind.ArrayInitializerExpression,
SingletonSeparatedList<ExpressionSyntax>(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))),
ReturnStatement(LiteralExpression(SyntaxKind.TrueLiteralExpression)))),
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName("bytecode"),
LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))),
ReturnStatement(LiteralExpression(SyntaxKind.FalseLiteralExpression)));
}
/// <summary>
/// A mapping of precomputed literals for all <see cref="byte"/> values.
/// </summary>
private static readonly string[] formattedBytes =
{
"0x00", "0x01", "0x02", "0x03", "0x04", "0x05", "0x06", "0x07", "0x08", "0x09", "0x0A", "0x0B", "0x0C", "0x0D", "0x0E", "0x0F",
"0x10", "0x11", "0x12", "0x13", "0x14", "0x15", "0x16", "0x17", "0x18", "0x19", "0x1A", "0x1B", "0x1C", "0x1D", "0x1E", "0x1F",
"0x20", "0x21", "0x22", "0x23", "0x24", "0x25", "0x26", "0x27", "0x28", "0x29", "0x2A", "0x2B", "0x2C", "0x2D", "0x2E", "0x2F",
"0x30", "0x31", "0x32", "0x33", "0x34", "0x35", "0x36", "0x37", "0x38", "0x39", "0x3A", "0x3B", "0x3C", "0x3D", "0x3E", "0x3F",
"0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4A", "0x4B", "0x4C", "0x4D", "0x4E", "0x4F",
"0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5A", "0x5B", "0x5C", "0x5D", "0x5E", "0x5F",
"0x60", "0x61", "0x62", "0x63", "0x64", "0x65", "0x66", "0x67", "0x68", "0x69", "0x6A", "0x6B", "0x6C", "0x6D", "0x6E", "0x6F",
"0x70", "0x71", "0x72", "0x73", "0x74", "0x75", "0x76", "0x77", "0x78", "0x79", "0x7A", "0x7B", "0x7C", "0x7D", "0x7E", "0x7F",
"0x80", "0x81", "0x82", "0x83", "0x84", "0x85", "0x86", "0x87", "0x88", "0x89", "0x8A", "0x8B", "0x8C", "0x8D", "0x8E", "0x8F",
"0x90", "0x91", "0x92", "0x93", "0x94", "0x95", "0x96", "0x97", "0x98", "0x99", "0x9A", "0x9B", "0x9C", "0x9D", "0x9E", "0x9F",
"0xA0", "0xA1", "0xA2", "0xA3", "0xA4", "0xA5", "0xA6", "0xA7", "0xA8", "0xA9", "0xAA", "0xAB", "0xAC", "0xAD", "0xAE", "0xAF",
"0xB0", "0xB1", "0xB2", "0xB3", "0xB4", "0xB5", "0xB6", "0xB7", "0xB8", "0xB9", "0xBA", "0xBB", "0xBC", "0xBD", "0xBE", "0xBF",
"0xC0", "0xC1", "0xC2", "0xC3", "0xC4", "0xC5", "0xC6", "0xC7", "0xC8", "0xC9", "0xCA", "0xCB", "0xCC", "0xCD", "0xCE", "0xCF",
"0xD0", "0xD1", "0xD2", "0xD3", "0xD4", "0xD5", "0xD6", "0xD7", "0xD8", "0xD9", "0xDA", "0xDB", "0xDC", "0xDD", "0xDE", "0xDF",
"0xE0", "0xE1", "0xE2", "0xE3", "0xE4", "0xE5", "0xE6", "0xE7", "0xE8", "0xE9", "0xEA", "0xEB", "0xEC", "0xED", "0xEE", "0xEF",
"0xF0", "0xF1", "0xF2", "0xF3", "0xF4", "0xF5", "0xF6", "0xF7", "0xF8", "0xF9", "0xFA", "0xFB", "0xFC", "0xFD", "0xFE", "0xFF"
};
/// <summary>
/// Creates a formatted expression to initialize a <see cref="ReadOnlySpan{T}"/> with a given shader data.
/// </summary>
/// <param name="bytecode">The input shader bytecode to serialize.</param>
/// <returns>A formatted <see cref="string"/> with the serialized data.</returns>
private static string BuildShaderBytecodeExpressionString(ReadOnlySpan<byte> bytecode)
{
//The estimation is 4 characters per byte (up to "255" in hex), plus ", " to separate sequential values
using ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create(bytecode.Length * 6);
builder.Append(formattedBytes[bytecode[0]]);
foreach (byte b in bytecode.Slice(1))
{
builder.Append(", ");
builder.Append(formattedBytes[b]);
}
return builder.WrittenSpan.ToString();
}
}
}
+163 -271
ファイルの表示
@@ -1,23 +1,21 @@
using System;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using ComputeSharp.__Internals;
using ComputeSharp.Exceptions;
using ComputeSharp.Shaders.Translation;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
@@ -25,298 +23,192 @@ namespace ComputeSharp.SourceGenerators;
public sealed partial class IShaderGenerator
{
/// <summary>
/// Indicates whether the required <c>dxcompiler.dll</c> and <c>dxil.dll</c> libraries have been loaded.
/// A helper with all logic to generate the <c>TryGetBytecode</c> method.
/// </summary>
private static bool areDxcLibrariesLoaded;
/// <inheritdoc/>
private static partial MethodDeclarationSyntax CreateTryGetBytecodeMethod(
GeneratorExecutionContext context,
INamedTypeSymbol structDeclarationSymbol,
bool isDynamicShader,
string hlslSource,
out string? bytecodeLiterals)
private static partial class TryGetBytecode
{
// This code produces a method declaration as follows:
//
// readonly int global::ComputeSharp.__Internals.IShader.TryGetBytecode(int threadsX, int threadsY, int threadsZ, out ReadOnlySpan<byte> bytecode)
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.BoolKeyword)),
Identifier("TryGetBytecode"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddParameterListParameters(
Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("bytecode")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::System.ReadOnlySpan<byte>")))
.WithBody(GetShaderBytecodeBody(context, structDeclarationSymbol, isDynamicShader, hlslSource, out bytecodeLiterals));
}
/// <summary>
/// Gets a <see cref="BlockSyntax"/> instance with the logic to try to get a compiled shader bytecode.
/// </summary>
/// <param name="context">The current generator context in use.</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="hlslSource">The generated HLSL source code (ignoring captured delegates, if present).</param>
/// <param name="bytecodeLiterals">The resulting bytecode literals to insert into the final source code.</param>
/// <returns>The <see cref="BlockSyntax"/> instance to hash the input shader.</returns>
[Pure]
private static unsafe BlockSyntax GetShaderBytecodeBody(
GeneratorExecutionContext context,
INamedTypeSymbol structDeclarationSymbol,
bool isDynamicShader,
string hlslSource,
out string? bytecodeLiterals)
{
AttributeData? attribute = structDeclarationSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(EmbeddedBytecodeAttribute) });
// No embedded shader was requested
if (attribute is null)
/// <summary>
/// Gets the thread ids values for a given shader type, if available.
/// </summary>
/// <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="diagnostics">The resulting diagnostics from the processing operation.</param>
/// <returns>The thread ids for the precompiled shader, if available.</returns>
public static ThreadIdsInfo GetInfo(
INamedTypeSymbol structDeclarationSymbol,
bool isDynamicShader,
out ImmutableArray<Diagnostic> diagnostics)
{
goto Failure;
AttributeData? attribute = structDeclarationSymbol
.GetAttributes()
.FirstOrDefault(static a => a.AttributeClass?.ToDisplayString() == typeof(EmbeddedBytecodeAttribute).FullName);
if (attribute is null)
{
diagnostics = ImmutableArray<Diagnostic>.Empty;
return new(true, 0, 0, 0);
}
ImmutableArray<Diagnostic>.Builder builder = ImmutableArray.CreateBuilder<Diagnostic>();
// Validate the thread number arguments
if (attribute.ConstructorArguments.Length != 3 ||
attribute.ConstructorArguments[0].Value is not int threadsX ||
attribute.ConstructorArguments[1].Value is not int threadsY ||
attribute.ConstructorArguments[2].Value is not int threadsZ ||
threadsX is < 1 or > 1024 ||
threadsY is < 1 or > 1024 ||
threadsZ is < 1 or > 64)
{
builder.Add(InvalidEmbeddedBytecodeThreadIds, structDeclarationSymbol, structDeclarationSymbol);
diagnostics = builder.ToImmutable();
return new(true, 0, 0, 0);
}
// If the current shader is dynamic, emit a diagnostic error
if (isDynamicShader)
{
builder.Add(EmbeddedBytecodeWithDynamicShader, structDeclarationSymbol, structDeclarationSymbol);
diagnostics = builder.ToImmutable();
return new(true, 0, 0, 0);
}
diagnostics = builder.ToImmutable();
return new(false, threadsX, threadsY, threadsZ);
}
// If the current shader is dynamic, emit a diagnostic error
if (isDynamicShader)
/// <summary>
/// Indicates whether the required <c>dxcompiler.dll</c> and <c>dxil.dll</c> libraries have been loaded.
/// </summary>
private static volatile bool areDxcLibrariesLoaded;
/// <summary>
/// Gets a <see cref="BlockSyntax"/> instance with the logic to try to get a compiled shader bytecode.
/// </summary>
/// <param name="threadIds">The input <see cref="ThreadIdsInfo"/> instance to process.</param>
/// <param name="hlslSource">The generated HLSL source code (ignoring captured delegates, if present).</param>
/// <param name="diagnostic">The resulting diagnostic from the processing operation, if any.</param>
/// <returns>The <see cref="ImmutableArray{T}"/> instance with the compiled shader bytecode.</returns>
[Pure]
public static unsafe ImmutableArray<byte> GetBytecode(
ThreadIdsInfo threadIds,
string hlslSource,
out DiagnosticInfo? diagnostic)
{
context.ReportDiagnostic(EmbeddedBytecodeWithDynamicShader, structDeclarationSymbol, structDeclarationSymbol);
ImmutableArray<byte> bytecode = ImmutableArray<byte>.Empty;
goto Failure;
}
// No embedded shader was requested
if (threadIds.IsDefault)
{
diagnostic = null;
// Validate the thread number arguments
if (attribute.ConstructorArguments[0].Value is not int threadsX ||
attribute.ConstructorArguments[1].Value is not int threadsY ||
attribute.ConstructorArguments[2].Value is not int threadsZ ||
threadsX is < 1 or > 1024 ||
threadsY is < 1 or > 1024 ||
threadsZ is < 1 or > 64)
{
context.ReportDiagnostic(InvalidEmbeddedBytecodeThreadIds, structDeclarationSymbol, structDeclarationSymbol);
goto Failure;
}
try
{
// Try to load dxcompiler.dll and dxil.dll
LoadNativeDxcLibraries();
// Replace the actual thread num values
hlslSource = hlslSource.Replace("<THREADSX>", threadsX.ToString()).Replace("<THREADSY>", threadsY.ToString()).Replace("<THREADSZ>", threadsZ.ToString());
// Compile the shader bytecode
using ComPtr<IDxcBlob> dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(hlslSource.AsSpan());
byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer();
int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize());
// Build and set the text with the literal expressions
bytecodeLiterals = BuildShaderBytecodeExpressionString(new ReadOnlySpan<byte>(buffer, length));
// This code produces a method declaration as follows:
//
// if (threadsX == <X> && threadsY == <Y> && threadsZ == <Z>)
// {
// bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE };
//
// return true;
// }
//
// bytecode = default;
//
// return false;
//
// Note that the __EMBEDDED_SHADER_BYTECODE identifier will be replaced after the string
// is created by the generator. This greatly speeds up the code generation, as it avoids
// having to create/parse tens of thousands of literal expression nodes for every shader.
return
Block(
IfStatement(
BinaryExpression(
SyntaxKind.LogicalAndExpression,
BinaryExpression(
SyntaxKind.LogicalAndExpression,
BinaryExpression(
SyntaxKind.EqualsExpression,
IdentifierName("threadsX"),
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(threadsX))),
BinaryExpression(
SyntaxKind.EqualsExpression,
IdentifierName("threadsY"),
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(threadsY)))),
BinaryExpression(
SyntaxKind.EqualsExpression,
IdentifierName("threadsZ"),
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(threadsZ)))),
Block(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName("bytecode"),
ArrayCreationExpression(
ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword)))
.AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList<ExpressionSyntax>(OmittedArraySizeExpression()))))
.WithInitializer(
InitializerExpression(
SyntaxKind.ArrayInitializerExpression,
SingletonSeparatedList<ExpressionSyntax>(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))),
ReturnStatement(LiteralExpression(SyntaxKind.TrueLiteralExpression)))),
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName("bytecode"),
LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))),
ReturnStatement(LiteralExpression(SyntaxKind.FalseLiteralExpression)));
}
catch (Win32Exception e)
{
context.ReportDiagnostic(
EmbeddedBytecodeFailedWithWin32Exception,
structDeclarationSymbol,
structDeclarationSymbol,
e.HResult,
e.Message);
}
catch (HlslCompilationException e)
{
context.ReportDiagnostic(
EmbeddedBytecodeFailedWithHlslCompilationException,
structDeclarationSymbol,
structDeclarationSymbol,
e.Message);
}
Failure:
bytecodeLiterals = null;
// This code produces a method declaration as follows:
//
// bytecode = default;
//
// return false;
return
Block(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName("bytecode"),
LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))),
ReturnStatement(
LiteralExpression(
SyntaxKind.FalseLiteralExpression)));
}
/// <summary>
/// Extracts and loads the <c>dxcompiler.dll</c> and <c>dxil.dll</c> libraries.
/// </summary>
/// <exception cref="NotSupportedException">Thrown if the CPU architecture is not supported.</exception>
/// <exception cref="Win32Exception">Thrown if a library fails to load.</exception>
private static void LoadNativeDxcLibraries()
{
// Extracts a specified native library for a given runtime identifier
static string ExtractLibrary(string rid, string name)
{
string sourceFilename = $"ComputeSharp.SourceGenerators.ComputeSharp.Libraries.{rid}.{name}.dll";
string targetFilename = Path.Combine(Path.GetTempPath(), "ComputeSharp.SourceGenerators", Path.GetRandomFileName(), rid, $"{name}.dll");
Directory.CreateDirectory(Path.GetDirectoryName(targetFilename));
using Stream sourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(sourceFilename);
goto End;
}
try
{
using Stream destinationStream = File.Open(targetFilename, FileMode.CreateNew, FileAccess.Write);
// Try to load dxcompiler.dll and dxil.dll
LoadNativeDxcLibraries();
sourceStream.CopyTo(destinationStream);
// Replace the actual thread num values
hlslSource = hlslSource
.Replace("<THREADSX>", threadIds.X.ToString())
.Replace("<THREADSY>", threadIds.Y.ToString())
.Replace("<THREADSZ>", threadIds.Z.ToString());
// Compile the shader bytecode
using ComPtr<IDxcBlob> dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(hlslSource.AsSpan());
byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer();
int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize());
byte[] array = new ReadOnlySpan<byte>(buffer, length).ToArray();
bytecode = Unsafe.As<byte[], ImmutableArray<byte>>(ref array);
diagnostic = null;
}
catch (IOException)
catch (Win32Exception e)
{
diagnostic = new DiagnosticInfo(EmbeddedBytecodeFailedWithWin32Exception, e.HResult, e.Message);
}
catch (HlslCompilationException e)
{
diagnostic = new DiagnosticInfo(EmbeddedBytecodeFailedWithHlslCompilationException, e.Message);
}
return targetFilename;
End:
return bytecode;
}
// Loads a target native library
static unsafe void LoadLibrary(string filename)
/// <summary>
/// Extracts and loads the <c>dxcompiler.dll</c> and <c>dxil.dll</c> libraries.
/// </summary>
/// <exception cref="NotSupportedException">Thrown if the CPU architecture is not supported.</exception>
/// <exception cref="Win32Exception">Thrown if a library fails to load.</exception>
private static void LoadNativeDxcLibraries()
{
[DllImport("kernel32", ExactSpelling = true, SetLastError = true)]
static extern void* LoadLibraryW(ushort* lpLibFileName);
fixed (char* p = filename)
// Extracts a specified native library for a given runtime identifier
static string ExtractLibrary(string folder, string rid, string name)
{
if (LoadLibraryW((ushort*)p) is null)
{
int hresult = Marshal.GetLastWin32Error();
string sourceFilename = $"ComputeSharp.SourceGenerators.ComputeSharp.Libraries.{rid}.{name}.dll";
string targetFilename = Path.Combine(folder, rid, $"{name}.dll");
throw new Win32Exception(hresult, $"Failed to load {Path.GetFileName(filename)}.");
Directory.CreateDirectory(Path.GetDirectoryName(targetFilename));
using Stream sourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(sourceFilename);
try
{
using Stream destinationStream = File.Open(targetFilename, FileMode.CreateNew, FileAccess.Write);
sourceStream.CopyTo(destinationStream);
}
catch (IOException)
{
}
return targetFilename;
}
// Loads a target native library
static unsafe void LoadLibrary(string filename)
{
[DllImport("kernel32", ExactSpelling = true, SetLastError = true)]
static extern void* LoadLibraryW(ushort* lpLibFileName);
fixed (char* p = filename)
{
if (LoadLibraryW((ushort*)p) is null)
{
int hresult = Marshal.GetLastWin32Error();
throw new Win32Exception(hresult, $"Failed to load {Path.GetFileName(filename)}.");
}
}
}
}
if (!areDxcLibrariesLoaded)
{
string rid = RuntimeInformation.ProcessArchitecture switch
if (!areDxcLibrariesLoaded)
{
Architecture.X64 => "x64",
Architecture.Arm64 => "arm64",
_ => throw new NotSupportedException("Invalid process architecture")
};
string rid = RuntimeInformation.ProcessArchitecture switch
{
Architecture.X64 => "x64",
Architecture.Arm64 => "arm64",
_ => throw new NotSupportedException("Invalid process architecture")
};
LoadLibrary(ExtractLibrary(rid, "dxil"));
LoadLibrary(ExtractLibrary(rid, "dxcompiler"));
string folder = Path.Combine(Path.GetTempPath(), "ComputeSharp.SourceGenerators", Path.GetRandomFileName());
LoadLibrary(ExtractLibrary(folder, rid, "dxil"));
LoadLibrary(ExtractLibrary(folder, rid, "dxcompiler"));
areDxcLibrariesLoaded = true;
}
}
areDxcLibrariesLoaded = true;
}
/// <summary>
/// A mapping of precomputed literals for all <see cref="byte"/> values.
/// </summary>
private static readonly string[] formattedBytes =
{
"0x00", "0x01", "0x02", "0x03", "0x04", "0x05", "0x06", "0x07", "0x08", "0x09", "0x0A", "0x0B", "0x0C", "0x0D", "0x0E", "0x0F",
"0x10", "0x11", "0x12", "0x13", "0x14", "0x15", "0x16", "0x17", "0x18", "0x19", "0x1A", "0x1B", "0x1C", "0x1D", "0x1E", "0x1F",
"0x20", "0x21", "0x22", "0x23", "0x24", "0x25", "0x26", "0x27", "0x28", "0x29", "0x2A", "0x2B", "0x2C", "0x2D", "0x2E", "0x2F",
"0x30", "0x31", "0x32", "0x33", "0x34", "0x35", "0x36", "0x37", "0x38", "0x39", "0x3A", "0x3B", "0x3C", "0x3D", "0x3E", "0x3F",
"0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4A", "0x4B", "0x4C", "0x4D", "0x4E", "0x4F",
"0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5A", "0x5B", "0x5C", "0x5D", "0x5E", "0x5F",
"0x60", "0x61", "0x62", "0x63", "0x64", "0x65", "0x66", "0x67", "0x68", "0x69", "0x6A", "0x6B", "0x6C", "0x6D", "0x6E", "0x6F",
"0x70", "0x71", "0x72", "0x73", "0x74", "0x75", "0x76", "0x77", "0x78", "0x79", "0x7A", "0x7B", "0x7C", "0x7D", "0x7E", "0x7F",
"0x80", "0x81", "0x82", "0x83", "0x84", "0x85", "0x86", "0x87", "0x88", "0x89", "0x8A", "0x8B", "0x8C", "0x8D", "0x8E", "0x8F",
"0x90", "0x91", "0x92", "0x93", "0x94", "0x95", "0x96", "0x97", "0x98", "0x99", "0x9A", "0x9B", "0x9C", "0x9D", "0x9E", "0x9F",
"0xA0", "0xA1", "0xA2", "0xA3", "0xA4", "0xA5", "0xA6", "0xA7", "0xA8", "0xA9", "0xAA", "0xAB", "0xAC", "0xAD", "0xAE", "0xAF",
"0xB0", "0xB1", "0xB2", "0xB3", "0xB4", "0xB5", "0xB6", "0xB7", "0xB8", "0xB9", "0xBA", "0xBB", "0xBC", "0xBD", "0xBE", "0xBF",
"0xC0", "0xC1", "0xC2", "0xC3", "0xC4", "0xC5", "0xC6", "0xC7", "0xC8", "0xC9", "0xCA", "0xCB", "0xCC", "0xCD", "0xCE", "0xCF",
"0xD0", "0xD1", "0xD2", "0xD3", "0xD4", "0xD5", "0xD6", "0xD7", "0xD8", "0xD9", "0xDA", "0xDB", "0xDC", "0xDD", "0xDE", "0xDF",
"0xE0", "0xE1", "0xE2", "0xE3", "0xE4", "0xE5", "0xE6", "0xE7", "0xE8", "0xE9", "0xEA", "0xEB", "0xEC", "0xED", "0xEE", "0xEF",
"0xF0", "0xF1", "0xF2", "0xF3", "0xF4", "0xF5", "0xF6", "0xF7", "0xF8", "0xF9", "0xFA", "0xFB", "0xFC", "0xFD", "0xFE", "0xFF"
};
/// <summary>
/// Creates a formatted expression to initialize a <see cref="ReadOnlySpan{T}"/> with a given shader data.
/// </summary>
/// <param name="bytecode">The input shader bytecode to serialize.</param>
/// <returns>A formatted <see cref="string"/> with the serialized data.</returns>
private static string BuildShaderBytecodeExpressionString(ReadOnlySpan<byte> bytecode)
{
//The estimation is 4 characters per byte (up to "255" in hex), plus ", " to separate sequential values
using ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create(bytecode.Length * 6);
builder.Append(formattedBytes[bytecode[0]]);
foreach (byte b in bytecode.Slice(1))
{
builder.Append(", ");
builder.Append(formattedBytes[b]);
}
return builder.WrittenSpan.ToString();
}
}
+126
ファイルの表示
@@ -0,0 +1,126 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
public sealed partial class IShaderGenerator
{
/// <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="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>
[Pure]
private static Type? GetShaderType(
INamedTypeSymbol typeSymbol,
INamedTypeSymbol iComputeShaderSymbol,
INamedTypeSymbol iPixelShaderSymbol)
{
foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.Interfaces)
{
if (interfaceSymbol.Name == nameof(IComputeShader) &&
SymbolEqualityComparer.Default.Equals(interfaceSymbol, iComputeShaderSymbol))
{
return typeof(IComputeShader);
}
if (interfaceSymbol.IsGenericType &&
interfaceSymbol.Name == nameof(IPixelShader<byte>) &&
SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, iPixelShaderSymbol))
{
return typeof(IPixelShader<>);
}
}
return null;
}
/// <summary>
/// Creates a <see cref="CompilationUnitSyntax"/> instance wrapping the given method.
/// </summary>
/// <param name="hierarchyInfo">The <see cref="HierarchyInfo"/> instance for the current type.</param>
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> item to insert.</param>
/// <param name="canUseSkipLocalsInit">Whether <c>[SkipLocalsInit]</c> can be used.</param>
/// <returns>A <see cref="CompilationUnitSyntax"/> object wrapping <paramref name="methodDeclaration"/>.</returns>
[Pure]
private static CompilationUnitSyntax GetCompilationUnitFromMethod(
HierarchyInfo hierarchyInfo,
MethodDeclarationSyntax methodDeclaration,
bool canUseSkipLocalsInit)
{
// Method attributes
List<AttributeListSyntax> attributes = new()
{
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).FullName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).Assembly.GetName().Version.ToString())))))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("global::System.ComponentModel.EditorBrowsable")).AddArgumentListArguments(
AttributeArgument(ParseExpression("global::System.ComponentModel.EditorBrowsableState.Never"))))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("global::System.Obsolete")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("This method is not intended to be used directly by user code"))))))
};
// Add [SkipLocalsInit] if the target project allows it
if (canUseSkipLocalsInit)
{
attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit")))));
}
// Create the partial shader type declaration with the given method implementation.
// This code produces a struct declaration as follows:
//
// partial struct <SHADER_TYPE>
// {
// <METHOD>
// }
StructDeclarationSyntax structDeclarationSyntax =
StructDeclaration(hierarchyInfo.Names[0])
.AddModifiers(Token(SyntaxKind.PartialKeyword))
.AddMembers(methodDeclaration.AddAttributeLists(attributes.ToArray()));
TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
// Add all parent types in ascending order, if any
foreach (string parentType in hierarchyInfo.Names.AsSpan().Slice(1))
{
typeDeclarationSyntax =
ClassDeclaration(parentType)
.AddModifiers(Token(SyntaxKind.PartialKeyword))
.AddMembers(typeDeclarationSyntax);
}
// Create the compilation unit with disabled warnings, target namespace and generated type.
// This will produce code as follows:
//
// #pragma warning disable
//
// namespace <NAMESPACE>;
//
// <TYPE_HIERARCHY>
return
CompilationUnit().AddMembers(
FileScopedNamespaceDeclaration(IdentifierName(hierarchyInfo.Namespace))
.AddMembers(typeDeclarationSyntax)
.WithNamespaceKeyword(Token(TriviaList(
Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))),
SyntaxKind.NamespaceKeyword,
TriviaList())))
.NormalizeWhitespace(eol: "\n");
}
}
-47
ファイルの表示
@@ -1,47 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
public sealed partial class IShaderGenerator
{
/// <summary>
/// An <see cref="ISyntaxContextReceiver"/> that selects candidate nodes to process.
/// </summary>
private sealed class SyntaxReceiver : ISyntaxContextReceiver
{
/// <summary>
/// The list of info gathered during exploration.
/// </summary>
private readonly List<Item> gatheredInfo = new();
/// <summary>
/// Gets the collection of gathered info to process.
/// </summary>
public IReadOnlyCollection<Item> GatheredInfo => this.gatheredInfo;
/// <inheritdoc/>
public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
{
if (context.Node is StructDeclarationSyntax structDeclaration &&
context.SemanticModel.GetDeclaredSymbol(structDeclaration) is INamedTypeSymbol structSymbol &&
structSymbol.Interfaces.Any(static interfaceSymbol =>
interfaceSymbol.Name == nameof(IComputeShader) ||
interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader<byte>) }))
{
this.gatheredInfo.Add(new Item(structDeclaration, structSymbol));
}
}
/// <summary>
/// A model for a group of item representing a discovered type to process.
/// </summary>
/// <param name="StructDeclaration">The <see cref="StructDeclarationSyntax"/> instance for the target struct declaration.</param>
/// <param name="StructSymbol">The <see cref="INamedTypeSymbol"/> instance for <paramref name="StructDeclaration"/>.</param>
public sealed record Item(StructDeclarationSyntax StructDeclaration, INamedTypeSymbol StructSymbol);
}
}
+212 -199
ファイルの表示
@@ -1,15 +1,15 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle;
namespace ComputeSharp.SourceGenerators;
@@ -17,208 +17,221 @@ namespace ComputeSharp.SourceGenerators;
/// A source generator creating data loaders for <see cref="IComputeShader"/> and <see cref="IPixelShader{TPixel}"/> types.
/// </summary>
[Generator]
public sealed partial class IShaderGenerator : ISourceGenerator
public sealed partial class IShaderGenerator : IIncrementalGenerator
{
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
public void Initialize(IncrementalGeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver());
}
// 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);
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
{
// Get the syntax receiver with the candidate nodes
if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver)
{
return;
}
// 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 })!;
foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo)
// 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)!));
// 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 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))))
.WithComparers(HierarchyInfo.Comparer.Default, DispatchIdInfo.Comparer.Default);
// Generate the GetDispatchId() methods
context.RegisterSourceOutput(hierarchyAndDispatchIdInfo, static (context, item) =>
{
try
MethodDeclarationSyntax getDispatchIdMethod = GetDispatchId.GetSyntax(item.Info.Delegates);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, getDispatchIdMethod, false);
context.AddSource($"{item.Hierarchy.FilenameHint}.GetDispatchId", SourceText.From(compilationUnit.ToFullString(), 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(context.CompilationProvider)
.Select(static (item, token) =>
{
OnExecute(context, item.StructDeclaration, item.StructSymbol);
}
catch
// LoadDispatchData() info
ImmutableArray<FieldInfo> fieldInfos = LoadDispatchData.GetInfo(
item.Left.Symbol,
item.Left.Type,
out int resourceCount,
out int root32BitConstantCount,
out ImmutableArray<Diagnostic> dispatchDataDiagnostics);
DispatchDataInfo dispatchDataInfo = new(
item.Left.Hierarchy,
item.Left.Type,
fieldInfos,
resourceCount,
root32BitConstantCount);
// BuildHlslString() info
HlslShaderSourceInfo hlslSourceInfo = BuildHlslString.GetInfo(
item.Right,
item.Left.Syntax,
item.Left.Symbol,
out ImmutableArray<Diagnostic> hlslSourceDiagnostics);
// TryGetBytecode() info
ThreadIdsInfo threadIds = TryGetBytecode.GetInfo(
item.Left.Symbol,
!hlslSourceInfo.Delegates.IsEmpty,
out ImmutableArray<Diagnostic> threadIdsDiagnostics);
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 =
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.Type,
item.Left.FieldInfos,
item.Left.ResourceCount,
item.Left.Root32BitConstantCount);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, loadDispatchDataMethod, item.Right);
context.AddSource($"{item.Left.Hierarchy.FilenameHint}.LoadDispatchData", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8));
});
// Get the filtered sequence to enable caching
IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo SourceInfo)> hlslSourceInfo =
shaderInfo
.Select(static (item, token) => (item.Dispatch.Hierarchy, item.Hlsl))
.WithComparers(HierarchyInfo.Comparer.Default, HlslShaderSourceInfo.Comparer.Default);
// Generate the BuildHlslString() methods
context.RegisterSourceOutput(hlslSourceInfo.Combine(canUseSkipLocalsInit), static (context, item) =>
{
MethodDeclarationSyntax buildHlslStringMethod = BuildHlslString.GetSyntax(item.Left.SourceInfo);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, item.Right);
context.AddSource($"{item.Left.Hierarchy.FilenameHint}.BuildHlslString", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8));
});
// Get the dispatch metadata info
IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchMetadataInfo MetadataInfo)> dispatchMetadataInfo =
shaderInfo
.Select(static (item, token) => (
item.Dispatch.Hierarchy,
LoadDispatchMetadata.GetInfo(
item.Dispatch.Root32BitConstantCount,
item.Hlsl.ImplicitTextureType is not null,
item.Hlsl.IsSamplerUsed,
item.Dispatch.FieldInfos)))
.WithComparers(HierarchyInfo.Comparer.Default, DispatchMetadataInfo.Comparer.Default);
// Generate the LoadDispatchMetadata() methods
context.RegisterSourceOutput(dispatchMetadataInfo.Combine(canUseSkipLocalsInit), static (context, item) =>
{
MethodDeclarationSyntax buildHlslStringMethod = LoadDispatchMetadata.GetSyntax(item.Left.MetadataInfo);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Left.Hierarchy, buildHlslStringMethod, item.Right);
context.AddSource($"{item.Left.Hierarchy.FilenameHint}.LoadDispatchMetadata", SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8));
});
// Transform the raw HLSL source to compile
IncrementalValuesProvider<(HierarchyInfo Hierarchy, string Hlsl, ThreadIdsInfo ThreadIds)> shaderBytecodeInfo =
shaderInfo
.Select(static (item, token) => (item.Dispatch.Hierarchy, BuildHlslString.GetNonDynamicHlslSource(item.Hlsl), item.ThreadIds))
.WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer<string>.Default, ThreadIdsInfo.Comparer.Default);
// Compile the requested shader bytecodes
IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo, DiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors =
shaderBytecodeInfo
.Select(static (item, token) =>
{
context.ReportDiagnostic(IShaderGeneratorError, item.StructDeclaration, item.StructSymbol);
}
}
ImmutableArray<byte> bytecode = TryGetBytecode.GetBytecode(item.ThreadIds, item.Hlsl, out DiagnosticInfo? diagnostic);
EmbeddedBytecodeInfo bytecodeInfo = new(
item.ThreadIds.X,
item.ThreadIds.Y,
item.ThreadIds.Z,
bytecode);
return (item.Hierarchy, bytecodeInfo, diagnostic);
});
// Gather the diagnostics
IncrementalValuesProvider<ImmutableArray<Diagnostic>> embeddedBytecodeDiagnostics =
embeddedBytecodeWithErrors
.Select(static (item, token) => (item.Hierarchy.MetadataName, item.Diagnostic))
.Where(static item => item.Diagnostic is not null)
.Combine(context.CompilationProvider)
.Select(static (item, token) =>
{
INamedTypeSymbol? typeSymbol = item.Right.GetTypeByMetadataName(item.Left.MetadataName)!;
Diagnostic diagnostic = Diagnostic.Create(
item.Left.Diagnostic!.Descriptor,
typeSymbol.Locations.FirstOrDefault(),
new object[] { typeSymbol }.Concat(item.Left.Diagnostic.Args).ToArray());
return ImmutableArray.Create(diagnostic);
});
// Output the diagnostics
context.ReportDiagnostics(embeddedBytecodeDiagnostics);
// Get the filtered sequence to enable caching
IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo)> embeddedBytecode =
embeddedBytecodeWithErrors
.Select(static (item, token) => (item.Hierarchy, item.BytecodeInfo))
.WithComparers(HierarchyInfo.Comparer.Default, EmbeddedBytecodeInfo.Comparer.Default);
// Generate the TryGetBytecode() methods
context.RegisterSourceOutput(embeddedBytecode, static (context, item) =>
{
MethodDeclarationSyntax tryGetBytecodeMethod = TryGetBytecode.GetSyntax(item.BytecodeInfo, out Func<SyntaxNode, string> fixup);
CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, tryGetBytecodeMethod, false);
string text = fixup(compilationUnit);
context.AddSource($"{item.Hierarchy.FilenameHint}.TryGetBytecode", SourceText.From(text, Encoding.UTF8));
});
}
/// <summary>
/// Processes a given target type.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> node to process.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol)
{
// Create the required interface methods for the current shader type
MethodDeclarationSyntax getDispatchIdMethod = CreateGetDispatchIdMethod(structDeclarationSymbol, out bool isDynamicShader);
MethodDeclarationSyntax loadDispatchDataMethod = CreateLoadDispatchDataMethod(context, structDeclarationSymbol, out var discoveredResources, out int root32BitConstants);
MethodDeclarationSyntax buildHlslStringMethod = CreateBuildHlslStringMethod(context, structDeclaration, structDeclarationSymbol, out string? implicitTextureType, out bool isSamplerUsed, out string hlslSource);
MethodDeclarationSyntax loadDispatchMetadataMethod = CreateLoadDispatchMetadataMethod(implicitTextureType, discoveredResources, root32BitConstants, isSamplerUsed);
MethodDeclarationSyntax tryGetBytecodeMethod = CreateTryGetBytecodeMethod(context, structDeclarationSymbol, isDynamicShader, hlslSource, out string? bytecodeLiterals);
// Reorder the method declarations to respect the order in the interface definition
MethodDeclarationSyntax[] methods =
{
getDispatchIdMethod,
loadDispatchDataMethod,
loadDispatchMetadataMethod,
buildHlslStringMethod,
tryGetBytecodeMethod
};
// Method attributes
List<AttributeListSyntax> attributes = new()
{
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).FullName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).Assembly.GetName().Version.ToString())))))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))),
AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("global::System.ComponentModel.EditorBrowsable")).AddArgumentListArguments(
AttributeArgument(ParseExpression("global::System.ComponentModel.EditorBrowsableState.Never"))))),
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName("global::System.Obsolete")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(
SyntaxKind.StringLiteralExpression,
Literal("This method is not intended to be used directly by user code"))))))
};
// Add [SkipLocalsInit] if the target project allows it and can access it
if (context.Compilation.Options is CSharpCompilationOptions { AllowUnsafe: true } &&
context.Compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.SkipLocalsInit") is not null)
{
attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit")))));
}
string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces));
string structName = structDeclaration.Identifier.Text;
SyntaxTokenList structModifiers = structDeclaration.Modifiers;
// Create the partial shader type declaration with the hashcode interface method implementation.
// This code produces a struct declaration as follows:
//
// public <MODIFIERS> struct ShaderType
// {
// <METHODS_LIST>
// }
var structDeclarationSyntax =
StructDeclaration(structName)
.WithModifiers(structModifiers)
.AddMembers(methods.Select(m => m.AddAttributeLists(attributes.ToArray())).ToArray());
TypeDeclarationSyntax typeDeclarationSyntax = structDeclarationSyntax;
// Add all parent types in ascending order, if any
foreach (var parentType in structDeclaration.Ancestors().OfType<TypeDeclarationSyntax>())
{
typeDeclarationSyntax = parentType
.WithMembers(SingletonList<MemberDeclarationSyntax>(typeDeclarationSyntax))
.WithConstraintClauses(List<TypeParameterConstraintClauseSyntax>())
.WithBaseList(null)
.WithAttributeLists(List<AttributeListSyntax>())
.WithoutTrivia();
}
// Create a static method to create the combined hashcode for a given shader type.
// This code takes a block syntax and produces a compilation unit as follows:
//
// #pragma warning disable
//
// namespace <SHADER_NAMESPACE>;
//
// <SHADER_DECLARATION>
var source =
CompilationUnit().AddMembers(
FileScopedNamespaceDeclaration(IdentifierName(namespaceName)).AddMembers(typeDeclarationSyntax)
.WithNamespaceKeyword(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.NamespaceKeyword, TriviaList())))
.NormalizeWhitespace(eol: "\n")
.ToFullString();
// Insert the bytecode literals, if needed
if (bytecodeLiterals is not null)
{
source = source.Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals);
}
// Add the method source attribute
context.AddSource(structDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
}
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.
/// </summary>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for the input struct declaration.</param>
/// <param name="isDynamicShader">Indicates whether or not the shader is dynamic (ie. captures delegates).</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.</returns>
private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol, out bool isDynamicShader);
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for the input struct declaration.</param>
/// <param name="discoveredResources">The collection of discovered resources in the current shader type.</param>
/// <param name="root32BitConstantsCount">The total number of 32 bit root constants being loaded for the current shader type.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.</returns>
private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod(
GeneratorExecutionContext context,
INamedTypeSymbol structDeclarationSymbol,
out IReadOnlyCollection<string> discoveredResources,
out int root32BitConstantsCount);
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> node to process.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
/// <param name="implicitTextureType">The implicit texture type, if available (if the shader is a pixel shader).</param>
/// <param name="isSamplerUsed">Whether or not the current shader type requires a static sampler to be available.</param>
/// <param name="hlslSource">The generated HLSL source code (ignoring captured delegates, if present).</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.</returns>
private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod(
GeneratorExecutionContext context,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
out string? implicitTextureType,
out bool isSamplerUsed,
out string hlslSource);
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.
/// </summary>
/// <param name="implicitTextureType">The implicit texture type, if available (if the shader is a pixel shader).</param>
/// <param name="discoveredResources">The collection of resources used by the shader.</param>
/// <param name="root32BitConstantsCount">The total number of 32 bit root constants being loaded for the shader.</param>
/// <param name="isSamplerUsed">Whether or not the shader requires a static sampler to be available.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.</returns>
private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod(
string? implicitTextureType,
IReadOnlyCollection<string> discoveredResources,
int root32BitConstantsCount,
bool isSamplerUsed);
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>TryGetBytecode</c> method.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for the shader type.</param>
/// <param name="isDynamicShader">Indicates whether or not the shader is dynamic (ie. captures delegates).</param>
/// <param name="hlslSource">The generated HLSL source code (ignoring captured delegates, if present).</param>
/// <param name="bytecodeLiterals">The resulting bytecode literals to insert into the final source code.</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.</returns>
private static partial MethodDeclarationSyntax CreateTryGetBytecodeMethod(
GeneratorExecutionContext context,
INamedTypeSymbol structDeclarationSymbol,
bool isDynamicShader,
string hlslSource,
out string? bytecodeLiterals);
}
+20
ファイルの表示
@@ -149,6 +149,26 @@ internal static class HlslKnownTypes
};
}
/// <summary>
/// Checks whether or not a given type name matches a writeable typed resource type.
/// </summary>
/// <param name="typeName">The input type name to check.</param>
/// <returns>Whether or not <paramref name="typeName"/> represents a writeable typed resource type.</returns>
public static bool IsReadWriteTypedResourceType(string typeName)
{
return typeName switch
{
"ComputeSharp.ReadWriteBuffer`1" or
"ComputeSharp.ReadWriteTexture2D`1" or
"ComputeSharp.ReadWriteTexture2D`2" or
"ComputeSharp.ReadWriteTexture3D`1" or
"ComputeSharp.ReadWriteTexture3D`2" or
"ComputeSharp.IReadWriteTexture2D`1" or
"ComputeSharp.IReadWriteTexture3D`1" => true,
_ => false,
};
}
/// <summary>
/// Checks whether or not a given type name matches a typed resource type.
/// </summary>
+64
ファイルの表示
@@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using ComputeSharp.SourceGenerators.Extensions;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model for a serializeable diagnostic provider.
/// </summary>
/// <param name="Descriptor">The wrapped <see cref="DiagnosticDescriptor"/> instance.</param>
/// <param name="Args">The diagnostic args.</param>
internal sealed record DiagnosticInfo(DiagnosticDescriptor Descriptor, params object[] Args)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="DiagnosticInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<DiagnosticInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(DiagnosticInfo? x, DiagnosticInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return
x.Descriptor.Equals(y.Descriptor) &&
x.Args.SequenceEqual(y.Args);
}
/// <inheritdoc/>
public int GetHashCode(DiagnosticInfo obj)
{
HashCode hashCode = default;
hashCode.Add(obj.Descriptor);
foreach (object arg in obj.Args)
{
hashCode.Add(arg);
}
return hashCode.ToHashCode();
}
}
}
+73
ファイルの表示
@@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.SourceGenerators.Extensions;
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,
ImmutableArray<FieldInfo> FieldInfos,
int ResourceCount,
int Root32BitConstantCount)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="DispatchDataInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<DispatchDataInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(DispatchDataInfo? x, DispatchDataInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
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;
}
/// <inheritdoc/>
public int GetHashCode(DispatchDataInfo obj)
{
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();
}
}
}
+55
ファイルの表示
@@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.SourceGenerators.Extensions;
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(ImmutableArray<string> Delegates)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="DispatchIdInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<DispatchIdInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(DispatchIdInfo? x, DispatchIdInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return x.Delegates.SequenceEqual(y.Delegates);
}
/// <inheritdoc/>
public int GetHashCode(DispatchIdInfo obj)
{
HashCode hashCode = default;
hashCode.AddRange(obj.Delegates);
return hashCode.ToHashCode();
}
}
}
+65
ファイルの表示
@@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.SourceGenerators.Extensions;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model containing info on shader dispatch metadata.
/// </summary>
/// <param name="Root32BitConstantCount">The size of the shader root signature, in 32 bit constants.</param>
/// <param name="IsSamplerUsed">Whether or not the static sampler is used.</param>
/// <param name="ResourceDescriptors">The sequence of resource descriptors for the shader.</param>
internal sealed record DispatchMetadataInfo(
int Root32BitConstantCount,
bool IsSamplerUsed,
ImmutableArray<ResourceDescriptor> ResourceDescriptors)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="DispatchMetadataInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<DispatchMetadataInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(DispatchMetadataInfo? x, DispatchMetadataInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return
x.Root32BitConstantCount == y.Root32BitConstantCount &&
x.IsSamplerUsed == y.IsSamplerUsed &&
x.ResourceDescriptors.SequenceEqual(y.ResourceDescriptors, ResourceDescriptor.Comparer.Default);
}
/// <inheritdoc/>
public int GetHashCode(DispatchMetadataInfo obj)
{
HashCode hashCode = default;
hashCode.Add(obj.Root32BitConstantCount);
hashCode.Add(obj.IsSamplerUsed);
hashCode.AddRange(obj.ResourceDescriptors, ResourceDescriptor.Comparer.Default);
return hashCode.ToHashCode();
}
}
}
+65
ファイルの表示
@@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.SourceGenerators.Extensions;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model representing a compiled shader bytecode, or none.
/// </summary>
/// <param name="X">The thread ids value for the X axis.</param>
/// <param name="Y">The thread ids value for the Y axis.</param>
/// <param name="Z">The thread ids value for the Z axis.</param>
/// <param name="Bytecode">The compiled shader bytecode, if available.</param>
internal sealed record EmbeddedBytecodeInfo(int X, int Y, int Z, ImmutableArray<byte> Bytecode)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="EmbeddedBytecodeInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<EmbeddedBytecodeInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(EmbeddedBytecodeInfo? x, EmbeddedBytecodeInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return
x.X == y.X &&
x.Y == y.Y &&
x.Z == y.Z &&
x.Bytecode.SequenceEqual(y.Bytecode);
}
/// <inheritdoc/>
public int GetHashCode(EmbeddedBytecodeInfo obj)
{
HashCode hashCode = default;
hashCode.Add(obj.X);
hashCode.Add(obj.Y);
hashCode.Add(obj.Z);
hashCode.AddBytes(obj.Bytecode.AsSpan());
return hashCode.ToHashCode();
}
}
}
+137
ファイルの表示
@@ -0,0 +1,137 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.SourceGenerators.Extensions;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A base type for a model describing a given captured field in a shader.
/// </summary>
internal abstract record FieldInfo
{
/// <summary>
/// A captured resource (either a buffer or a texture).
/// </summary>
/// <param name="FieldName">The name of the resource field.</param>
/// <param name="TypeName">The full metadata name for the resource type.</param>
/// <param name="Offset">The offset for the resource within the root signature.</param>
public sealed record Resource(string FieldName, string TypeName, int Offset) : FieldInfo;
/// <summary>
/// A captured primitive value (either a scalar, a vector, or a linear matrix).
/// </summary>
/// <param name="FieldPath">The path of the field with respect to the shader instance.</param>
/// <param name="TypeName">The full metadata name for the primitive type.</param>
/// <param name="Offset">The byte offset of the value within the root signature.</param>
public sealed record Primitive(ImmutableArray<string> FieldPath, string TypeName, int Offset) : FieldInfo;
/// <summary>
/// A captured non linear matrix value.
/// </summary>
/// <param name="FieldPath">The path of the field with respect to the shader instance.</param>
/// <param name="TypeName">The full metadata name for the matrix type.</param>
/// <param name="ElementName">The name of each element in the matrix type.</param>
/// <param name="Rows">The number of rows in the matrix.</param>
/// <param name="Columns">The number of columns in the matrix.</param>
/// <param name="Offsets">The sequence of byte offsets for each row within the root signature.</param>
public sealed record NonLinearMatrix(
ImmutableArray<string> FieldPath,
string TypeName,
string ElementName,
int Rows,
int Columns,
ImmutableArray<int> Offsets) : FieldInfo;
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="FieldInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<FieldInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(FieldInfo? x, FieldInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
if (x is Resource resourceX && y is Resource resourceY)
{
return
resourceX.FieldName == resourceY.FieldName &&
resourceX.TypeName == resourceY.TypeName &&
resourceX.Offset == resourceY.Offset;
}
else if (x is Primitive primitiveX && y is Primitive primitiveY)
{
return
primitiveX.FieldPath.SequenceEqual(primitiveY.FieldPath) &&
primitiveX.TypeName == primitiveY.TypeName &&
primitiveX.Offset == primitiveY.Offset;
}
else if (x is NonLinearMatrix matrixX && y is NonLinearMatrix matrixY)
{
return
matrixX.FieldPath.SequenceEqual(matrixY.FieldPath) &&
matrixX.TypeName == matrixY.TypeName &&
matrixX.ElementName == matrixY.ElementName &&
matrixX.Rows == matrixY.Rows &&
matrixY.Columns == matrixY.Columns &&
matrixX.Offsets.SequenceEqual(matrixY.Offsets);
}
return false;
}
/// <inheritdoc/>
public int GetHashCode(FieldInfo obj)
{
switch (obj)
{
case Resource resource:
return HashCode.Combine(resource.FieldName, resource.TypeName, resource.Offset);
case Primitive primitive:
{
HashCode hashCode = default;
hashCode.AddRange(primitive.FieldPath);
hashCode.Add(primitive.TypeName);
hashCode.Add(primitive.Offset);
return hashCode.ToHashCode();
}
case NonLinearMatrix matrix:
{
HashCode hashCode = default;
hashCode.AddRange(matrix.FieldPath);
hashCode.Add(matrix.TypeName);
hashCode.Add(matrix.ElementName);
hashCode.Add(matrix.Rows);
hashCode.Add(matrix.Columns);
hashCode.AddRange(matrix.Offsets);
return hashCode.ToHashCode();
}
default:
return 0;
}
}
}
}
+85
ファイルの表示
@@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using ComputeSharp.SourceGenerators.Extensions;
using Microsoft.CodeAnalysis;
using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model describing the hierarchy info for a specific type.
/// </summary>
/// <param name="FilenameHint">The filename hint for the current type.</param>
/// <param name="MetadataName">The metadata name for the current type.</param>
/// <param name="Namespace">Gets the namespace for the current type.</param>
/// <param name="Names">Gets the sequence of type definitions containing the current type.</param>
internal sealed record HierarchyInfo(string FilenameHint, string MetadataName, string Namespace, ImmutableArray<string> Names)
{
/// <summary>
/// Creates a new <see cref="HierarchyInfo"/> instance from a given <see cref="INamedTypeSymbol"/>.
/// </summary>
/// <param name="typeSymbol">The input <see cref="INamedTypeSymbol"/> instance to gather info for.</param>
/// <returns>A <see cref="HierarchyInfo"/> instance describing <paramref name="typeSymbol"/>.</returns>
[Pure]
public static HierarchyInfo From(INamedTypeSymbol typeSymbol)
{
ImmutableArray<string>.Builder names = ImmutableArray.CreateBuilder<string>();
for (INamedTypeSymbol? parent = typeSymbol;
parent is not null;
parent = parent.ContainingType)
{
names.Add(parent.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat));
}
return new(
typeSymbol.GetGeneratedFileName(),
typeSymbol.MetadataName,
typeSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)),
names.ToImmutable());
}
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="HierarchyInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<HierarchyInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(HierarchyInfo? x, HierarchyInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return
x.FilenameHint == y.FilenameHint &&
x.MetadataName == y.MetadataName &&
x.Namespace == y.Namespace &&
x.Names.SequenceEqual(y.Names);
}
/// <inheritdoc/>
public int GetHashCode(HierarchyInfo obj)
{
return HashCode.Combine(obj.Namespace, obj.MetadataName, obj.Names, obj.Names[0]);
}
}
}
+73
ファイルの表示
@@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.SourceGenerators.Extensions;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model for extracted info on a processed HLSL method.
/// </summary>
/// <param name="MetadataName">The metadata name for the method.</param>
/// <param name="EntryPoint">The meethod entry point.</param>
/// <param name="DefinedTypes">The discovered declared types.</param>
/// <param name="DefinedConstants">The discovered defined constants.</param>
/// <param name="DependentMethods">The dependent captured methods.</param>
internal sealed record HlslMethodSourceInfo(
string MetadataName,
string EntryPoint,
ImmutableArray<(string Name, string Definition)> DefinedTypes,
ImmutableArray<(string Name, string Value)> DefinedConstants,
ImmutableArray<(string Signature, string Definition)> DependentMethods)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="HlslMethodSourceInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<HlslMethodSourceInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(HlslMethodSourceInfo? x, HlslMethodSourceInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return
x.MetadataName == y.MetadataName &&
x.EntryPoint == y.EntryPoint &&
x.DefinedTypes.SequenceEqual(y.DefinedTypes) &&
x.DefinedConstants.SequenceEqual(y.DefinedConstants) &&
x.DependentMethods.SequenceEqual(y.DependentMethods);
}
/// <inheritdoc/>
public int GetHashCode(HlslMethodSourceInfo obj)
{
HashCode hashCode = default;
hashCode.Add(obj.MetadataName);
hashCode.Add(obj.EntryPoint);
hashCode.AddRange(obj.DefinedTypes);
hashCode.AddRange(obj.DefinedConstants);
hashCode.AddRange(obj.DependentMethods);
return hashCode.ToHashCode();
}
}
}
+109
ファイルの表示
@@ -0,0 +1,109 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using ComputeSharp.SourceGenerators.Extensions;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model for extracted info on a processed HLSL shader.
/// </summary>
/// <param name="HeaderAndThreadsX">The shader generated header and <c>threadsX</c> count declaration.</param>
/// <param name="ThreadsY">The <c>threadsY</c> count declaration.</param>
/// <param name="ThreadsZ">The <c>threadsZ</c> count declaration.</param>
/// <param name="Defines">The define statements, if any.</param>
/// <param name="StaticFieldsAndDeclaredTypes">The static fields and declared types, if any.</param>
/// <param name="CapturedFieldsAndResourcesAndForwardDeclarations">The captured fields, and method forward declarations.</param>
/// <param name="CapturedMethods">The captured method implementations.</param>
/// <param name="EntryPoint">The shader entry point.</param>
/// <param name="ImplicitTextureType">The type of the implicit texture type, if any.</param>
/// <param name="IsSamplerUsed">Whether or not the static sampler is used.</param>
/// <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,
string ThreadsZ,
string Defines,
string StaticFieldsAndDeclaredTypes,
string CapturedFieldsAndResourcesAndForwardDeclarations,
string CapturedMethods,
string EntryPoint,
string? ImplicitTextureType,
bool IsSamplerUsed,
ImmutableArray<string> DefinedTypes,
ImmutableArray<string> DefinedConstants,
ImmutableArray<string> MethodSignatures,
ImmutableArray<string> Delegates)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="HlslShaderSourceInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<HlslShaderSourceInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(HlslShaderSourceInfo? x, HlslShaderSourceInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return
x.HeaderAndThreadsX == y.HeaderAndThreadsX &&
x.ThreadsY == y.ThreadsY &&
x.ThreadsZ == y.ThreadsZ &&
x.Defines == y.Defines &&
x.StaticFieldsAndDeclaredTypes == y.StaticFieldsAndDeclaredTypes &&
x.CapturedFieldsAndResourcesAndForwardDeclarations == y.CapturedFieldsAndResourcesAndForwardDeclarations &&
x.CapturedMethods == y.CapturedMethods &&
x.EntryPoint == y.EntryPoint &&
x.ImplicitTextureType == y.ImplicitTextureType &&
x.IsSamplerUsed == y.IsSamplerUsed &&
x.DefinedTypes.SequenceEqual(y.DefinedTypes) &&
x.DefinedConstants.SequenceEqual(y.DefinedTypes) &&
x.MethodSignatures.SequenceEqual(y.MethodSignatures) &&
x.Delegates.SequenceEqual(y.Delegates);
}
/// <inheritdoc/>
public int GetHashCode(HlslShaderSourceInfo obj)
{
HashCode hashCode = default;
hashCode.Add(obj.HeaderAndThreadsX);
hashCode.Add(obj.ThreadsY);
hashCode.Add(obj.ThreadsZ);
hashCode.Add(obj.Defines);
hashCode.Add(obj.StaticFieldsAndDeclaredTypes);
hashCode.Add(obj.CapturedFieldsAndResourcesAndForwardDeclarations);
hashCode.Add(obj.CapturedMethods);
hashCode.Add(obj.EntryPoint);
hashCode.Add(obj.ImplicitTextureType);
hashCode.Add(obj.IsSamplerUsed);
hashCode.AddRange(obj.DefinedTypes);
hashCode.AddRange(obj.DefinedConstants);
hashCode.AddRange(obj.MethodSignatures);
hashCode.AddRange(obj.Delegates);
return hashCode.ToHashCode();
}
}
}
+8
ファイルの表示
@@ -0,0 +1,8 @@
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model describing info on a constructor parameter.
/// </summary>
/// <param name="Type">The fully qualified type name.</param>
/// <param name="Name">The parameter name.</param>
internal sealed record ParameterInfo(string Type, string Name);
+54
ファイルの表示
@@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A resource descriptor for a captured resource in a shader.
/// </summary>
/// <param name="TypeId">The type id for the resource.</param>
/// <param name="RegisterOffset">The offset of the resource in its containing register.</param>
/// <param name="Offset">The offset of the resource descriptor in the shader root signature.</param>
internal sealed record ResourceDescriptor(int TypeId, int RegisterOffset, int Offset)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="ResourceDescriptor"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<ResourceDescriptor>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(ResourceDescriptor? x, ResourceDescriptor? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return
x.TypeId == y.TypeId &&
x.RegisterOffset == y.RegisterOffset &&
x.Offset == y.Offset;
}
/// <inheritdoc/>
public int GetHashCode(ResourceDescriptor obj)
{
return HashCode.Combine(obj.TypeId, obj.RegisterOffset, obj.Offset);
}
}
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model representing a value and an associated set of diagnostic errors.
/// </summary>
/// <typeparam name="TValue">The type of the wrapped value.</typeparam>
/// <param name="Value">The wrapped value for the current result.</param>
/// <param name="Errors">The associated diagnostic errors, if any.</param>
internal sealed record Result<TValue>(TValue Value, ImmutableArray<Diagnostic> Errors);
+56
ファイルの表示
@@ -0,0 +1,56 @@
using System;
using System.Collections.Generic;
namespace ComputeSharp.SourceGenerators.Models;
/// <summary>
/// A model representing gathered info on a embedded thread ids.
/// </summary>
/// <param name="IsDefault">Whether the values are diascarded.</param>
/// <param name="X">The thread ids value for the X axis.</param>
/// <param name="Y">The thread ids value for the Y axis.</param>
/// <param name="Z">The thread ids value for the Z axis.</param>
internal sealed record ThreadIdsInfo(bool IsDefault, int X, int Y, int Z)
{
/// <summary>
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="ThreadIdsInfo"/>.
/// </summary>
public sealed class Comparer : IEqualityComparer<ThreadIdsInfo>
{
/// <summary>
/// The singleton <see cref="Comparer"/> instance.
/// </summary>
public static Comparer Default { get; } = new();
/// <inheritdoc/>
public bool Equals(ThreadIdsInfo? x, ThreadIdsInfo? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return
x.IsDefault == y.IsDefault &&
x.X == y.X &&
x.Y == y.Y &&
x.Z == y.Y;
}
/// <inheritdoc/>
public int GetHashCode(ThreadIdsInfo obj)
{
return HashCode.Combine(obj.IsDefault, obj.X, obj.Y, obj.Z);
}
}
}
-46
ファイルの表示
@@ -1,46 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
public sealed partial class ShaderMethodSourceGenerator
{
/// <summary>
/// An <see cref="ISyntaxContextReceiver"/> that selects candidate nodes to process.
/// </summary>
private sealed class SyntaxReceiver : ISyntaxContextReceiver
{
/// <summary>
/// The list of info gathered during exploration.
/// </summary>
private readonly List<Item> gatheredInfo = new();
/// <summary>
/// Gets the collection of gathered info to process.
/// </summary>
public IReadOnlyCollection<Item> GatheredInfo => this.gatheredInfo;
/// <inheritdoc/>
public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
{
if (context.Node is MethodDeclarationSyntax { AttributeLists: { Count: > 0 } } methodDeclaration &&
context.SemanticModel.GetDeclaredSymbol(methodDeclaration) is IMethodSymbol methodSymbol &&
context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(ShaderMethodAttribute).FullName) is INamedTypeSymbol attributeSymbol &&
methodSymbol.GetAttributes().Any(a => SymbolEqualityComparer.Default.Equals(a.AttributeClass, attributeSymbol)))
{
this.gatheredInfo.Add(new Item(methodDeclaration, methodSymbol));
}
}
/// <summary>
/// A model for a group of item representing a discovered method to process.
/// </summary>
/// <param name="MethodDeclaration">The <see cref="MethodDeclarationSyntax"/> instance for the target method declaration.</param>
/// <param name="MethodSymbol">The <see cref="IMethodSymbol"/> instance for <paramref name="MethodDeclaration"/>.</param>
public sealed record Item(MethodDeclarationSyntax MethodDeclaration, IMethodSymbol MethodSymbol);
}
}
+145 -103
ファイルの表示
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
@@ -6,12 +7,12 @@ using ComputeSharp.__Internals;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.Helpers;
using ComputeSharp.SourceGenerators.Models;
using ComputeSharp.SourceGenerators.SyntaxRewriters;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static ComputeSharp.SourceGenerators.Helpers.SyntaxFactoryHelper;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
@@ -22,123 +23,164 @@ namespace ComputeSharp.SourceGenerators;
/// <summary>
/// A source generator for processing static methods referenced from compute shaders.
/// </summary>
[Generator]
public sealed partial class ShaderMethodSourceGenerator : ISourceGenerator
[Generator(LanguageNames.CSharp)]
public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator
{
/// <inheritdoc/>
public void Initialize(GeneratorInitializationContext context)
public void Initialize(IncrementalGeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver());
}
// Get all declared methods with the [ShaderMethod] attribute
IncrementalValuesProvider<(MethodDeclarationSyntax Syntax, IMethodSymbol Symbol)> structDeclarations =
context.SyntaxProvider
.CreateSyntaxProvider(
static (node, token) => node is MethodDeclarationSyntax { AttributeLists.Count: > 0 } methodDeclaration,
static (context, token) => (
Syntax: (MethodDeclarationSyntax)context.Node,
Symbol: (IMethodSymbol?)context.SemanticModel.GetDeclaredSymbol(context.Node, token)))
.Where(static item => item.Symbol is not null &&
item.Symbol.GetAttributes().Any(static a => a.AttributeClass?.ToDisplayString() == typeof(ShaderMethodAttribute).FullName))!;
/// <inheritdoc/>
public void Execute(GeneratorExecutionContext context)
{
// Get the syntax receiver with the candidate nodes
if (context.SyntaxContextReceiver is not SyntaxReceiver syntaxReceiver)
{
return;
}
foreach (SyntaxReceiver.Item item in syntaxReceiver.GatheredInfo)
{
SemanticModelProvider semanticModel = new(context.Compilation);
try
// Get the source info for each method
IncrementalValuesProvider<Result<HlslMethodSourceInfo>> methodSourceInfoWithErrors =
structDeclarations
.Combine(context.CompilationProvider)
.Select(static (item, token) =>
{
OnExecute(context, item.MethodDeclaration, semanticModel, item.MethodSymbol);
}
catch
{
context.ReportDiagnostic(ShaderMethodSourceGeneratorError, item.MethodDeclaration, item.MethodSymbol);
}
}
HlslMethodSourceInfo sourceInfo = Execute.GetData(
item.Right,
item.Left.Syntax,
item.Left.Symbol,
out ImmutableArray<Diagnostic> diagnostics);
return new Result<HlslMethodSourceInfo>(sourceInfo, diagnostics);
});
// Output the diagnostics
context.ReportDiagnostics(methodSourceInfoWithErrors.Select(static (item, token) => item.Errors));
// Get the filtered sequence to enable caching
IncrementalValuesProvider<HlslMethodSourceInfo> methodSourceInfo =
methodSourceInfoWithErrors
.Select(static (item, token) => item.Value)
.WithComparer(HlslMethodSourceInfo.Comparer.Default);
// Generate the [ShaderMethodSource] attributes
context.RegisterSourceOutput(methodSourceInfo, static (context, item) =>
{
CompilationUnitSyntax compilationUnit = Execute.GetSyntax(item);
string filename = item.MetadataName.Replace('`', '-').Replace('+', '.');
context.AddSource(filename, SourceText.From(compilationUnit.ToFullString(), Encoding.UTF8));
});
}
/// <summary>
/// Processes a given target method.
/// A helper with all logic to generate the attribute declarations.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> node to process.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> with metadata on the types being processed.</param>
/// <param name="methodDeclarationSymbol">The <see cref="IMethodSymbol"/> for <paramref name="methodDeclaration"/>.</param>
private static void OnExecute(GeneratorExecutionContext context, MethodDeclarationSyntax methodDeclaration, SemanticModelProvider semanticModel, IMethodSymbol methodDeclarationSymbol)
private static class Execute
{
// We need to sets to track all discovered custom types and static methods
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
// Explore the syntax tree and extract the processed info
var (invokeMethod, processedMethods) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, constantDefinitions);
var processedTypes = IShaderGenerator.GetProcessedTypes(discoveredTypes).ToArray();
var processedConstants = IShaderGenerator.GetProcessedConstants(constantDefinitions);
// Create the compilation unit with the source attribute
var source =
CompilationUnit().AddAttributeLists(
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName($"global::{typeof(ShaderMethodSourceAttribute).FullName}")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))),
AttributeArgument(NestedArrayExpression(processedTypes)),
AttributeArgument(NestedArrayExpression(processedMethods)),
AttributeArgument(NestedArrayExpression(processedConstants)))))
.WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
.NormalizeWhitespace(eol: "\n")
.ToFullString();
// Add the method source attribute
context.AddSource(methodDeclarationSymbol.GetGeneratedFileName(), SourceText.From(source, Encoding.UTF8));
}
/// <summary>
/// Gets a sequence of processed methods from a target method declaration.
/// </summary>
/// <param name="context">The current generator context in use.</param>
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> instance for the current method.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the method to process.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <returns>A sequence of processed methods in <paramref name="methodDeclaration"/> (main method and all captured methods).</returns>
[Pure]
private static (string TargetMethod, IEnumerable<(string Signature, string Definition)> ProcessedMethods) GetProcessedMethods(
GeneratorExecutionContext context,
MethodDeclarationSyntax methodDeclaration,
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions)
{
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, context);
// Rewrite the method syntax tree
var targetMethod = shaderSourceRewriter
.Visit(methodDeclaration)!
.WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier))
.WithoutTrivia()
.NormalizeWhitespace(eol: "\n")
.ToFullString();
List<(string, string)> processedMethods = new(shaderSourceRewriter.LocalFunctions.Count);
// Emit the extracted local functions
foreach (var localFunction in shaderSourceRewriter.LocalFunctions)
/// <summary>
/// Processes a given target method.
/// </summary>
/// <param name="compilation">The input <see cref="Compilation"/> object currently in use.</param>
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> node to process.</param>
/// <param name="methodSymbol">The <see cref="IMethodSymbol"/> instance for the current method.</param>
/// <param name="diagnostics">The resulting diagnostics from the processing operation.</param>
public static HlslMethodSourceInfo GetData(
Compilation compilation,
MethodDeclarationSyntax methodDeclaration,
IMethodSymbol methodSymbol,
out ImmutableArray<Diagnostic> diagnostics)
{
processedMethods.Add((
localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()));
// We need to sets to track all discovered custom types and static methods
HashSet<INamedTypeSymbol> discoveredTypes = new(SymbolEqualityComparer.Default);
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
// Explore the syntax tree and extract the processed info
var semanticModel = new SemanticModelProvider(compilation);
var (entryPoint, dependentMethods) = GetProcessedMethods(methodDeclaration, semanticModel, discoveredTypes, constantDefinitions, out diagnostics);
var definedTypes = IShaderGenerator.BuildHlslString.GetDeclaredTypes(discoveredTypes);
var definedConstants = IShaderGenerator.BuildHlslString.GetDefinedConstants(constantDefinitions);
return new(
methodSymbol.GetFullMetadataName(includeParameters: true),
entryPoint,
definedTypes,
definedConstants,
dependentMethods);
}
// Emit the discovered static methods
foreach (var staticMethod in staticMethods.Values)
/// <summary>
/// Gets a sequence of processed methods from a target method declaration.
/// </summary>
/// <param name="methodDeclaration">The <see cref="MethodDeclarationSyntax"/> instance for the current method.</param>
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the method to process.</param>
/// <param name="discoveredTypes">The collection of currently discovered types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="diagnostics">The resulting diagnostics from the processing operation.</param>
/// <returns>A sequence of processed methods in <paramref name="methodDeclaration"/> (main method and all captured methods).</returns>
[Pure]
private static (string TargetMethod, ImmutableArray<(string Signature, string Definition)> DependentMethods) GetProcessedMethods(
MethodDeclarationSyntax methodDeclaration,
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
out ImmutableArray<Diagnostic> diagnostics)
{
processedMethods.Add((
staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
Dictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods = new(SymbolEqualityComparer.Default);
ImmutableArray<Diagnostic>.Builder builder = ImmutableArray.CreateBuilder<Diagnostic>();
ShaderSourceRewriter shaderSourceRewriter = new(semanticModel, discoveredTypes, staticMethods, constantDefinitions, builder);
diagnostics = builder.ToImmutable();
// Rewrite the method syntax tree
var targetMethod = shaderSourceRewriter
.Visit(methodDeclaration)!
.WithIdentifier(Identifier(ShaderMethodSourceAttribute.InvokeMethodIdentifier))
.WithoutTrivia()
.NormalizeWhitespace(eol: "\n")
.ToFullString();
ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>(shaderSourceRewriter.LocalFunctions.Count);
// Emit the extracted local functions
foreach (var localFunction in shaderSourceRewriter.LocalFunctions)
{
methods.Add((
localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString()));
}
// Emit the discovered static methods
foreach (var staticMethod in staticMethods.Values)
{
methods.Add((
staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(),
staticMethod.NormalizeWhitespace(eol: "\n").ToFullString()));
}
return (targetMethod, methods.ToImmutable());
}
return (targetMethod, processedMethods);
/// <summary>
/// Creates a <see cref="CompilationUnitSyntax"/> instance with the processed attribute.
/// </summary>
/// <param name="methodSourceInfo">The input <see cref="HlslMethodSourceInfo"/> instance to use.</param>
public static CompilationUnitSyntax GetSyntax(HlslMethodSourceInfo methodSourceInfo)
{
return
CompilationUnit().AddAttributeLists(
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName($"global::{typeof(ShaderMethodSourceAttribute).FullName}")).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodSourceInfo.MetadataName))),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodSourceInfo.EntryPoint))),
AttributeArgument(NestedArrayExpression(methodSourceInfo.DefinedTypes)),
AttributeArgument(NestedArrayExpression(methodSourceInfo.DependentMethods)),
AttributeArgument(NestedArrayExpression(methodSourceInfo.DefinedConstants)))))
.WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
.NormalizeWhitespace(eol: "\n");
}
}
}
+24 -24
ファイルの表示
@@ -14,7 +14,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
{
var updatedNode = (AnonymousObjectCreationExpressionSyntax)base.VisitAnonymousObjectCreationExpression(node)!;
Context.ReportDiagnostic(AnonymousObjectCreationExpression, node);
Diagnostics.Add(AnonymousObjectCreationExpression, node);
return updatedNode;
}
@@ -22,7 +22,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitAwaitExpression(AwaitExpressionSyntax node)
{
Context.ReportDiagnostic(AwaitExpression, node);
Diagnostics.Add(AwaitExpression, node);
return base.VisitAwaitExpression(node);
}
@@ -30,7 +30,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitCheckedExpression(CheckedExpressionSyntax node)
{
Context.ReportDiagnostic(CheckedExpression, node);
Diagnostics.Add(CheckedExpression, node);
return base.VisitCheckedExpression(node);
}
@@ -38,7 +38,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitCheckedStatement(CheckedStatementSyntax node)
{
Context.ReportDiagnostic(CheckedStatement, node);
Diagnostics.Add(CheckedStatement, node);
return base.VisitCheckedStatement(node);
}
@@ -46,7 +46,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitFixedStatement(FixedStatementSyntax node)
{
Context.ReportDiagnostic(FixedStatement, node);
Diagnostics.Add(FixedStatement, node);
return base.VisitFixedStatement(node);
}
@@ -54,7 +54,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitForEachStatement(ForEachStatementSyntax node)
{
Context.ReportDiagnostic(ForEachStatement, node);
Diagnostics.Add(ForEachStatement, node);
return base.VisitForEachStatement(node);
}
@@ -62,7 +62,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitForEachVariableStatement(ForEachVariableStatementSyntax node)
{
Context.ReportDiagnostic(ForEachStatement, node);
Diagnostics.Add(ForEachStatement, node);
return base.VisitForEachVariableStatement(node);
}
@@ -70,7 +70,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitLockStatement(LockStatementSyntax node)
{
Context.ReportDiagnostic(LockStatement, node);
Diagnostics.Add(LockStatement, node);
return base.VisitLockStatement(node);
}
@@ -78,7 +78,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitQueryExpression(QueryExpressionSyntax node)
{
Context.ReportDiagnostic(QueryExpression, node);
Diagnostics.Add(QueryExpression, node);
return base.VisitQueryExpression(node);
}
@@ -86,7 +86,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitRangeExpression(RangeExpressionSyntax node)
{
Context.ReportDiagnostic(RangeExpression, node);
Diagnostics.Add(RangeExpression, node);
return base.VisitRangeExpression(node);
}
@@ -94,7 +94,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitRecursivePattern(RecursivePatternSyntax node)
{
Context.ReportDiagnostic(RecursivePattern, node);
Diagnostics.Add(RecursivePattern, node);
return base.VisitRecursivePattern(node);
}
@@ -102,7 +102,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitRefType(RefTypeSyntax node)
{
Context.ReportDiagnostic(RefType, node);
Diagnostics.Add(RefType, node);
return base.VisitRefType(node);
}
@@ -110,7 +110,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitRelationalPattern(RelationalPatternSyntax node)
{
Context.ReportDiagnostic(RelationalPattern, node);
Diagnostics.Add(RelationalPattern, node);
return base.VisitRelationalPattern(node);
}
@@ -118,7 +118,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitSizeOfExpression(SizeOfExpressionSyntax node)
{
Context.ReportDiagnostic(SizeOfExpression, node);
Diagnostics.Add(SizeOfExpression, node);
return base.VisitSizeOfExpression(node);
}
@@ -126,7 +126,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node)
{
Context.ReportDiagnostic(StackAllocArrayCreationExpression, node);
Diagnostics.Add(StackAllocArrayCreationExpression, node);
return base.VisitStackAllocArrayCreationExpression(node);
}
@@ -134,7 +134,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitThrowExpression(ThrowExpressionSyntax node)
{
Context.ReportDiagnostic(ThrowExpressionOrStatement, node);
Diagnostics.Add(ThrowExpressionOrStatement, node);
return base.VisitThrowExpression(node);
}
@@ -142,7 +142,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitThrowStatement(ThrowStatementSyntax node)
{
Context.ReportDiagnostic(ThrowExpressionOrStatement, node);
Diagnostics.Add(ThrowExpressionOrStatement, node);
return base.VisitThrowStatement(node);
}
@@ -150,7 +150,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitTryStatement(TryStatementSyntax node)
{
Context.ReportDiagnostic(TryStatement, node);
Diagnostics.Add(TryStatement, node);
return base.VisitTryStatement(node);
}
@@ -158,7 +158,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitTupleType(TupleTypeSyntax node)
{
Context.ReportDiagnostic(TupleType, node);
Diagnostics.Add(TupleType, node);
return base.VisitTupleType(node);
}
@@ -166,7 +166,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitUsingStatement(UsingStatementSyntax node)
{
Context.ReportDiagnostic(UsingStatementOrDeclaration, node);
Diagnostics.Add(UsingStatementOrDeclaration, node);
return base.VisitUsingStatement(node);
}
@@ -174,7 +174,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitYieldStatement(YieldStatementSyntax node)
{
Context.ReportDiagnostic(YieldStatement, node);
Diagnostics.Add(YieldStatement, node);
return base.VisitYieldStatement(node);
}
@@ -182,7 +182,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitFunctionPointerType(FunctionPointerTypeSyntax node)
{
Context.ReportDiagnostic(FunctionPointer, node);
Diagnostics.Add(FunctionPointer, node);
return base.VisitFunctionPointerType(node);
}
@@ -190,7 +190,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitPointerType(PointerTypeSyntax node)
{
Context.ReportDiagnostic(PointerType, node);
Diagnostics.Add(PointerType, node);
return base.VisitPointerType(node);
}
@@ -198,7 +198,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <inheritdoc/>
public override SyntaxNode? VisitUnsafeStatement(UnsafeStatementSyntax node)
{
Context.ReportDiagnostic(UnsafeStatement, node);
Diagnostics.Add(UnsafeStatement, node);
return base.VisitUnsafeStatement(node);
}
+11 -10
ファイルの表示
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using ComputeSharp.SourceGenerators.Diagnostics;
@@ -37,9 +38,9 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
protected readonly IDictionary<IFieldSymbol, string> ConstantDefinitions;
/// <summary>
/// The current generator context in use.
/// The collection of produced <see cref="Diagnostic"/> instances.
/// </summary>
protected readonly GeneratorExecutionContext Context;
protected readonly ImmutableArray<Diagnostic>.Builder Diagnostics;
/// <summary>
/// Creates a new <see cref="HlslSourceRewriter"/> instance with the specified parameters.
@@ -47,17 +48,17 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
/// <param name="semanticModel">The <see cref="Microsoft.CodeAnalysis.SemanticModel"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="context">The current generator context in use.</param>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
protected HlslSourceRewriter(
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
GeneratorExecutionContext context)
ImmutableArray<Diagnostic>.Builder diagnostics)
{
SemanticModel = semanticModel;
DiscoveredTypes = discoveredTypes;
ConstantDefinitions = constantDefinitions;
Context = context;
Diagnostics = diagnostics;
}
/// <summary>
@@ -80,7 +81,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
if (SemanticModel.For(node).GetTypeInfo(node.Type).Type is ITypeSymbol { IsUnmanagedType: false } type)
{
Context.ReportDiagnostic(InvalidObjectDeclaration, node, type);
Diagnostics.Add(InvalidObjectDeclaration, node, type);
}
// If var is used, replace it with the explicit type
@@ -99,7 +100,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type)
{
Context.ReportDiagnostic(InvalidObjectCreationExpression, node, type);
Diagnostics.Add(InvalidObjectCreationExpression, node, type);
}
updatedNode = updatedNode.ReplaceAndTrackType(updatedNode.Type, node, SemanticModel.For(node), DiscoveredTypes);
@@ -135,7 +136,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
if (SemanticModel.For(node).GetTypeInfo(node).Type is ITypeSymbol { IsUnmanagedType: false } type)
{
Context.ReportDiagnostic(InvalidObjectCreationExpression, node, type);
Diagnostics.Add(InvalidObjectCreationExpression, node, type);
}
TypeSyntax explicitType = IdentifierName("").ReplaceAndTrackType(node, SemanticModel.For(node), DiscoveredTypes);
@@ -214,7 +215,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
}
else if (updatedNode.IsKind(SyntaxKind.StringLiteralExpression))
{
Context.ReportDiagnostic(StringLiteralExpression, node);
Diagnostics.Add(StringLiteralExpression, node);
}
return updatedNode;
@@ -276,7 +277,7 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter
if (SemanticModel.For(node).GetOperation(argument.Expression) is not IFieldReferenceOperation fieldReference ||
!HlslKnownMembers.IsKnownMatrixIndex(fieldReference.Field.GetFullMetadataName()))
{
Context.ReportDiagnostic(NonConstantMatrixSwizzledIndex, argument);
Diagnostics.Add(NonConstantMatrixSwizzledIndex, argument);
isValid = false;
}
+14 -13
ファイルの表示
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using ComputeSharp.SourceGenerators.Diagnostics;
@@ -63,7 +64,7 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="context">The current generator context in use.</param>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
/// <param name="isEntryPoint">Whether or not the current instance is processing a shader entry point.</param>
public ShaderSourceRewriter(
INamedTypeSymbol shaderType,
@@ -71,9 +72,9 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IFieldSymbol, string> constantDefinitions,
GeneratorExecutionContext context,
ImmutableArray<Diagnostic>.Builder diagnostics,
bool isEntryPoint)
: base(semanticModel, discoveredTypes, constantDefinitions, context)
: base(semanticModel, discoveredTypes, constantDefinitions, diagnostics)
{
this.shaderType = shaderType;
this.staticMethods = staticMethods;
@@ -89,14 +90,14 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="staticMethods">The set of discovered and processed static methods.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="context">The current generator context in use.</param>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
public ShaderSourceRewriter(
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IMethodSymbol, MethodDeclarationSyntax> staticMethods,
IDictionary<IFieldSymbol, string> constantDefinitions,
GeneratorExecutionContext context)
: base(semanticModel, discoveredTypes, constantDefinitions, context)
ImmutableArray<Diagnostic>.Builder diagnostics)
: base(semanticModel, discoveredTypes, constantDefinitions, diagnostics)
{
this.staticMethods = staticMethods;
this.implicitVariables = new();
@@ -134,12 +135,12 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter
if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
{
Context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node);
Diagnostics.Add(AsyncModifierOnMethodOrFunction, node);
}
if (node!.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
{
Context.ReportDiagnostic(UnsafeModifierOnMethodOrFunction, node);
Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node);
}
if (updatedNode is not null)
@@ -183,7 +184,7 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter
if (SemanticModel.For(node).GetOperation(node) is IOperation { Kind: OperationKind.UsingDeclaration })
{
Context.ReportDiagnostic(UsingStatementOrDeclaration, node);
Diagnostics.Add(UsingStatementOrDeclaration, node);
}
return updatedNode.ReplaceAndTrackType(updatedNode.Declaration.Type, node.Declaration.Type, SemanticModel.For(node), DiscoveredTypes);
@@ -227,12 +228,12 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter
if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
{
Context.ReportDiagnostic(AsyncModifierOnMethodOrFunction, node);
Diagnostics.Add(AsyncModifierOnMethodOrFunction, node);
}
if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.UnsafeKeyword)))
{
Context.ReportDiagnostic(UnsafeModifierOnMethodOrFunction, node);
Diagnostics.Add(UnsafeModifierOnMethodOrFunction, node);
}
this.localFunctionDepth--;
@@ -295,7 +296,7 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter
if (descriptor is not null)
{
Context.ReportDiagnostic(descriptor, node);
Diagnostics.Add(descriptor, node);
}
}
}
@@ -403,7 +404,7 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter
if (!this.staticMethods.ContainsKey(method))
{
ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Context);
ShaderSourceRewriter shaderSourceRewriter = new(SemanticModel, DiscoveredTypes, this.staticMethods, ConstantDefinitions, Diagnostics);
MethodDeclarationSyntax methodNode = (MethodDeclarationSyntax)method.DeclaringSyntaxReferences[0].GetSyntax();
MethodDeclarationSyntax processedMethod = shaderSourceRewriter.Visit(methodNode)!.NormalizeWhitespace(eol: "\n").WithoutTrivia();
+5 -4
ファイルの表示
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
@@ -25,13 +26,13 @@ internal sealed class StaticFieldRewriter : HlslSourceRewriter
/// <param name="semanticModel">The <see cref="SemanticModelProvider"/> instance for the target syntax tree.</param>
/// <param name="discoveredTypes">The set of discovered custom types.</param>
/// <param name="constantDefinitions">The collection of discovered constant definitions.</param>
/// <param name="context">The current generator context in use.</param>
/// <param name="diagnostics">The collection of produced <see cref="Diagnostic"/> instances.</param>
public StaticFieldRewriter(
SemanticModelProvider semanticModel,
ICollection<INamedTypeSymbol> discoveredTypes,
IDictionary<IFieldSymbol, string> constantDefinitions,
GeneratorExecutionContext context)
: base(semanticModel, discoveredTypes, constantDefinitions, context)
ImmutableArray<Diagnostic>.Builder diagnostics)
: base(semanticModel, discoveredTypes, constantDefinitions, diagnostics)
{
}
@@ -86,7 +87,7 @@ internal sealed class StaticFieldRewriter : HlslSourceRewriter
if (descriptor is not null)
{
Context.ReportDiagnostic(descriptor, node);
Diagnostics.Add(descriptor, node);
}
}
+18 -15
ファイルの表示
@@ -27,7 +27,7 @@ public class AutoConstructorGeneratorTests
namespace MyFancyApp.Sample
{
public partial interface IFoo<T> : IFluff
public partial class IFoo<T> : IFluff
where T : notnull, new()
{
public partial class Foo
@@ -44,25 +44,28 @@ public class AutoConstructorGeneratorTests
}
}";
string expected = @"
string expected = $@"
#pragma warning disable
namespace MyFancyApp.Sample;
public partial interface IFoo<T>
{
public partial class Foo
{
public readonly partial struct Test
{
partial class IFoo<T>
{{
partial class Foo
{{
partial struct Test
{{
[global::System.CodeDom.Compiler.GeneratedCode(""ComputeSharp.SourceGenerators.AutoConstructorGenerator"", ""{typeof(AutoConstructorGenerator).Assembly.GetName().Version}"")]
[global::System.Diagnostics.DebuggerNonUserCode]
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public Test(float a, global::System.Numerics.Vector2 b, global::ComputeSharp.ReadWriteBuffer<global::System.Numerics.Vector4> c, global::ComputeSharp.ReadWriteBuffer<int> d)
{
{{
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
}
}
}";
}}
}}
}}
}}";
VerifyGeneratedMethodLines<AutoConstructorGenerator>(source, 0, expected);
}
@@ -75,7 +78,7 @@ public class AutoConstructorGeneratorTests
/// <param name="index">The target index to check in the resulting output.</param>
/// <param name="expectedBody">The expected body to compare with the generated code.</param>
private static void VerifyGeneratedMethodLines<TGenerator>(string source, int index, string expectedBody)
where TGenerator : class, ISourceGenerator, new()
where TGenerator : class, IIncrementalGenerator, new()
{
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source);
@@ -87,7 +90,7 @@ public class AutoConstructorGeneratorTests
CSharpCompilation compilation = CSharpCompilation.Create("original", new SyntaxTree[] { syntaxTree }, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
ISourceGenerator generator = new TGenerator();
IIncrementalGenerator generator = new TGenerator();
CSharpGeneratorDriver driver = CSharpGeneratorDriver.Create(generator);
+19 -16
ファイルの表示
@@ -167,7 +167,7 @@ public class DiagnosticsTests
[DataRow(nameof(GroupIds), "CMPS0007")]
[DataRow(nameof(GroupSize), "CMPS0008")]
[DataRow(nameof(GridIds), "CMPS0009")]
[DataRow(nameof(DispatchSize), "CMPS0044")]
[DataRow(nameof(DispatchSize), "CMPS0039")]
public void InvalidDispatchInfoUsage_LocalFunction(string typeName, string diagnosticsId)
{
string source = $@"
@@ -202,7 +202,7 @@ public class DiagnosticsTests
[DataRow(nameof(GroupIds), "CMPS0007")]
[DataRow(nameof(GroupSize), "CMPS0008")]
[DataRow(nameof(GridIds), "CMPS0009")]
[DataRow(nameof(DispatchSize), "CMPS0044")]
[DataRow(nameof(DispatchSize), "CMPS0039")]
public void InvalidDispatchInfoUsage_StaticMethod(string typeName, string diagnosticsId)
{
string source = $@"
@@ -1194,7 +1194,7 @@ public class DiagnosticsTests
}
}";
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0042");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0037");
}
[TestMethod]
@@ -1222,7 +1222,7 @@ public class DiagnosticsTests
}
}";
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0043");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0038");
}
[TestMethod]
@@ -1250,7 +1250,7 @@ public class DiagnosticsTests
}
}";
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0045");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0040");
}
[TestMethod]
@@ -1281,7 +1281,7 @@ public class DiagnosticsTests
}
}";
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0045");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0040");
}
[TestMethod]
@@ -1309,7 +1309,7 @@ public class DiagnosticsTests
}
}";
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0045");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0040");
}
[TestMethod]
@@ -1337,7 +1337,7 @@ public class DiagnosticsTests
}
}";
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0045");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0040");
}
[TestMethod]
@@ -1371,7 +1371,7 @@ public class DiagnosticsTests
}
}";
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0046");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0041");
}
[TestMethod]
@@ -1396,7 +1396,7 @@ public class DiagnosticsTests
}
}";
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0047");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0042");
}
[TestMethod]
@@ -1410,12 +1410,15 @@ public class DiagnosticsTests
{
public interface IComputeShader { }
public class ReadWriteBuffer<T> { }
public class EmbeddedBytecodeAttribute : Attribute { }
public class EmbeddedBytecodeAttribute : Attribute
{
public EmbeddedBytecodeAttribute(int threadsX, int threadsY, int threadsZ) { }
}
}
namespace MyFancyApp.Sample
{
[EmbeddedBytecode]
[EmbeddedBytecode(8, 8, 1)]
public struct MyShader : IComputeShader
{
public ReadWriteBuffer<float> buffer;
@@ -1427,7 +1430,7 @@ public class DiagnosticsTests
}
}";
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0048");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0043");
}
[TestMethod]
@@ -1466,7 +1469,7 @@ public class DiagnosticsTests
}}
}}";
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0049");
VerifyGeneratedDiagnostics<IShaderGenerator>(source, "CMPS0044");
}
/// <summary>
@@ -1476,7 +1479,7 @@ public class DiagnosticsTests
/// <param name="source">The input source to process.</param>
/// <param name="diagnosticsIds">The expected diagnostics ids to be generated.</param>
private static void VerifyGeneratedDiagnostics<TGenerator>(string source, params string[] diagnosticsIds)
where TGenerator : class, ISourceGenerator, new()
where TGenerator : class, IIncrementalGenerator, new()
{
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source);
@@ -1488,7 +1491,7 @@ public class DiagnosticsTests
CSharpCompilation compilation = CSharpCompilation.Create("original", new SyntaxTree[] { syntaxTree }, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
ISourceGenerator generator = new TGenerator();
IIncrementalGenerator generator = new TGenerator();
CSharpGeneratorDriver driver = CSharpGeneratorDriver.Create(generator);
+88
ファイルの表示
@@ -4,6 +4,8 @@ using ComputeSharp.Tests.Attributes;
using ComputeSharp.Tests.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
#pragma warning disable CS0649, CS8618
namespace ComputeSharp.Tests;
[TestClass]
@@ -298,4 +300,90 @@ public partial class DispatchTests
1);
}
}
[CombinatorialTestMethod]
[AllDevices]
public void Verify_GroupShared_WithFixedSize(Device device)
{
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(128);
device.Get().For(256, new FixedGroupSharedPixelShader(buffer));
int[] result = buffer.ToArray();
for (int i = 0; i < 128; i++)
{
Assert.AreEqual(result[i], i);
}
}
[AutoConstructor]
internal readonly partial struct FixedGroupSharedPixelShader : IComputeShader
{
private readonly ReadWriteBuffer<int> buffer;
[GroupShared(128)]
private static readonly int[] cache;
public void Execute()
{
int index = ThreadIds.X / 2;
bool isWritingToGroupShared = ThreadIds.X % 2 == 0;
if (isWritingToGroupShared)
{
cache[index] = index;
}
Hlsl.GroupMemoryBarrier();
if (!isWritingToGroupShared)
{
buffer[index] = cache[index];
}
}
}
[CombinatorialTestMethod]
[AllDevices]
public void Verify_GroupShared_WithDynamicSize(Device device)
{
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(32);
device.Get().For(64, 1, 1, 32, 1, 1, new DynamicGroupSharedPixelShader(buffer));
int[] result = buffer.ToArray();
for (int i = 0; i < 32; i++)
{
Assert.AreEqual(result[i], i);
}
}
[AutoConstructor]
internal readonly partial struct DynamicGroupSharedPixelShader : IComputeShader
{
private readonly ReadWriteBuffer<int> buffer;
[GroupShared]
private static readonly int[] cache;
public void Execute()
{
int index = ThreadIds.X / 2;
bool isWritingToGroupShared = ThreadIds.X % 2 == 0;
if (isWritingToGroupShared)
{
cache[index] = index;
}
Hlsl.GroupMemoryBarrier();
if (!isWritingToGroupShared)
{
buffer[index] = cache[index];
}
}
}
}