diff --git a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md index 9507ad4e..74fadd53 100644 --- a/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md +++ b/src/ComputeSharp.SourceGenerators/AnalyzerReleases.Shipped.md @@ -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) diff --git a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.SyntaxReceiver.cs deleted file mode 100644 index 478303bb..00000000 --- a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.SyntaxReceiver.cs +++ /dev/null @@ -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; - -/// -public sealed partial class AutoConstructorGenerator -{ - /// - /// An that selects candidate nodes to process. - /// - private sealed class SyntaxReceiver : ISyntaxContextReceiver - { - /// - /// The list of info gathered during exploration. - /// - private readonly List gatheredInfo = new(); - - /// - /// Gets the collection of gathered info to process. - /// - public IReadOnlyCollection GatheredInfo => this.gatheredInfo; - - /// - 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)); - } - } - - /// - /// A model for a group of item representing a discovered type to process. - /// - /// The instance for the target struct declaration. - /// The instance for . - /// The instance for the target attribute over . - /// The instance for . - public sealed record Item( - StructDeclarationSyntax StructDeclaration, - INamedTypeSymbol StructSymbol, - AttributeSyntax AttributeSyntax, - AttributeData AttributeData); - } -} diff --git a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs index 1aac7f97..f04c3e04 100644 --- a/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/AutoConstructorGenerator.cs @@ -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; /// /// A source generator creating constructors for types annotated with . /// -[Generator] -public sealed partial class AutoConstructorGenerator : ISourceGenerator +[Generator(LanguageNames.CSharp)] +public sealed partial class AutoConstructorGenerator : IIncrementalGenerator { /// - 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 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))!; - /// - 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 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.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)); + }); } /// - /// Processes a given target type. + /// A helper with all logic to generate the constructor declarations. /// - /// The input instance to use. - /// The node to process. - /// The for . - 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() - 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()) + /// + /// Gets the sequence of items for all fields in the input type. + /// + /// The being inspected. + /// The sequence of items for all fields in . + public static ImmutableArray GetData(INamedTypeSymbol structDeclarationSymbol) { - typeDeclarationSyntax = parentType - .WithMembers(SingletonList(typeDeclarationSyntax)) - .WithConstraintClauses(List()) - .WithBaseList(null) - .WithAttributeLists(List()) - .WithoutTrivia(); + return ( + from fieldSymbol in structDeclarationSymbol.GetMembers().OfType() + 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(); + /// + /// Gets the instance for a given type and sequence of parameters. + /// + /// The type hierarchy info. + /// The sequence of parameters to initialize. + /// A instance for a specified type. + public static CompilationUnitSyntax GetSyntax(HierarchyInfo hierarchyInfo, ImmutableArray 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 + // { + // + // } + 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 ; + // + // + return + CompilationUnit().AddMembers( + FileScopedNamespaceDeclaration(IdentifierName(hierarchyInfo.Namespace)) + .AddMembers(typeDeclarationSyntax) + .WithNamespaceKeyword(Token(TriviaList( + Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), + SyntaxKind.NamespaceKeyword, + TriviaList()))) + .NormalizeWhitespace(eol: "\n"); + } } } diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 1e5cf347..7f11ded0 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -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"); - /// - /// Gets a for an internal error in . - /// - /// Format: "The generator AutoConstructorGenerator failed to execute on type {0}, and its constructor might not be available". - /// - /// - 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"); - - /// - /// Gets a for an internal error in . - /// - /// Format: "The generator IShaderGenerator failed to execute on type {0}, and trying to use that shader might result in a runtime crash". - /// - /// - 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"); - - /// - /// Gets a for an internal error in . - /// - /// Format: "The generator ShaderMethodSourceGenerator failed to execute on method {0}, and using it in a shader might result in a runtime crash". - /// - /// - 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"); - /// /// Gets a for an incorrect matrix swizzling property argument. /// 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 /// /// 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 for an invalid usage. /// 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 for a property declaration. /// 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 /// /// 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 /// /// 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 /// /// 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 /// /// 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 /// /// 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 /// /// 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, diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs index a5894cd6..8584bee1 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticsExtensions.cs @@ -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)); } + + /// + /// Adds a new diagnostics to the target builder. + /// + /// The collection of produced instances. + /// The input for the diagnostics to create. + /// The source to attach the diagnostics to. + /// The optional arguments for the formatted message to include. + public static void Add( + this ImmutableArray.Builder diagnostics, + DiagnosticDescriptor descriptor, + ISymbol symbol, + params object[] args) + { + diagnostics.Add(Diagnostic.Create(descriptor, symbol.Locations.FirstOrDefault(), args)); + } + + /// + /// Adds a new diagnostics to the target builder. + /// + /// The collection of produced instances. + /// The input for the diagnostics to create. + /// The source to attach the diagnostics to. + /// The optional arguments for the formatted message to include. + public static void Add( + this ImmutableArray.Builder diagnostics, + DiagnosticDescriptor descriptor, + SyntaxNode node, + params object[] args) + { + diagnostics.Add(Diagnostic.Create(descriptor, node.GetLocation(), args)); + } + + /// + /// Registers an output node into an to output diagnostics. + /// + /// The input instance. + /// The input sequence of diagnostics. + public static void ReportDiagnostics(this IncrementalGeneratorInitializationContext context, IncrementalValuesProvider> diagnostics) + { + context.RegisterSourceOutput(diagnostics, static (context, diagnostics) => + { + foreach (Diagnostic diagnostic in diagnostics) + { + context.ReportDiagnostic(diagnostic); + } + }); + } } diff --git a/src/ComputeSharp.SourceGenerators/Extensions/HashCodeExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/HashCodeExtensions.cs new file mode 100644 index 00000000..7d486566 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Extensions/HashCodeExtensions.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace ComputeSharp.SourceGenerators.Extensions; + +/// +/// Extension methods for . +/// +internal static class HashCodeExtensions +{ + /// + /// Adds all items from a given instance to an hashcode. + /// + /// The type of items to hash. + /// The target instance. + /// The input items to hash. + public static void AddRange(this ref HashCode hashCode, ImmutableArray items) + { + foreach (T item in items) + { + hashCode.Add(item); + } + } + + /// + /// Adds all items from a given instance to an hashcode. + /// + /// The type of items to hash. + /// The target instance. + /// A comparer to get hashcodes for items. + /// The input items to hash. + public static void AddRange(this ref HashCode hashCode, ImmutableArray items, IEqualityComparer comparer) + { + foreach (T item in items) + { + hashCode.Add(item, comparer); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/Extensions/IEqualityComparerExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/IEqualityComparerExtensions.cs new file mode 100644 index 00000000..306d8c11 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Extensions/IEqualityComparerExtensions.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace ComputeSharp.SourceGenerators.Extensions; + +/// +/// Extension methods for . +/// +internal static class IEqualityComparerExtensions +{ + /// + /// Gets an for an sequence. + /// + /// The type of items to compare. + /// The compare for individual items. + public static IEqualityComparer> ForImmutableArray(this IEqualityComparer comparer) + { + return new Comparer(comparer); + } + + /// + /// An implementation for an value. + /// + public sealed class Comparer : IEqualityComparer> + { + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The comparer. + public Comparer(IEqualityComparer comparer) + { + this.comparer = comparer; + } + + /// + public bool Equals(ImmutableArray x, ImmutableArray y) + { + return + x == y || + x.SequenceEqual(y, this.comparer); + } + + /// + public int GetHashCode(ImmutableArray obj) + { + HashCode hashCode = default; + + hashCode.AddRange(obj, this.comparer); + + return hashCode.ToHashCode(); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs index aade5e79..dac1c8f9 100644 --- a/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs +++ b/src/ComputeSharp.SourceGenerators/Extensions/ISymbolExtensions.cs @@ -116,17 +116,6 @@ internal static class ISymbolExtensions return symbol.GetFullMetadataName().Replace('`', '-').Replace('+', '.'); } - /// - /// Gets a valid filename for a target symbol and generator type. - /// - /// The symbol being processed. - /// A filename in the form "<SYMBOL_FULLNAME>" - [Pure] - public static string GetGeneratedFileName(this IMethodSymbol symbol) - { - return symbol.GetFullMetadataName(true).Replace('`', '-').Replace('+', '.'); - } - /// /// Tracks an instance and returns an HLSL compatible object. /// diff --git a/src/ComputeSharp.SourceGenerators/Extensions/ImmutableArrayExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/ImmutableArrayExtensions.cs new file mode 100644 index 00000000..e4100441 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Extensions/ImmutableArrayExtensions.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; + +namespace ComputeSharp.SourceGenerators.Extensions; + +/// +/// Extension methods for . +/// +internal static class ImmutableArrayExtensions +{ + /// + /// Compares two sequences for equality. + /// + /// The items to compare. + /// The left sequence of items. + /// The right sequence of items. + /// Whether or not equals . + public static bool SequenceEqual(this ImmutableArray left, ImmutableArray right) + where T : IEquatable + { + return left.AsSpan().SequenceEqual(right.AsSpan()); + } + + /// + /// Compares two sequences for equality. + /// + /// The items to compare. + /// The left sequence of items. + /// The right sequence of items. + /// The instance used to compare items. + /// Whether or not equals . + public static bool SequenceEqual(this ImmutableArray left, ImmutableArray right, IEqualityComparer 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; + } +} diff --git a/src/ComputeSharp.SourceGenerators/Extensions/IncrementalValuesProviderExtensions.cs b/src/ComputeSharp.SourceGenerators/Extensions/IncrementalValuesProviderExtensions.cs new file mode 100644 index 00000000..bdcd5290 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Extensions/IncrementalValuesProviderExtensions.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.SourceGenerators.Extensions; + +/// +/// Extension methods for . +/// +internal static class IncrementalValuesProviderExtensions +{ + /// + /// Creates a new instance with a gven pair of comparers. + /// + /// The type of left items in each tuple. + /// The type of right items in each tuple. + /// The input instance. + /// An instance for items. + /// An instance for items. + /// An with the specified comparers applied to each item. + public static IncrementalValuesProvider<(TLeft Left, TRight Right)> WithComparers( + this IncrementalValuesProvider<(TLeft Left, TRight Right)> source, + IEqualityComparer comparerLeft, + IEqualityComparer comparerRight) + { + return source.WithComparer(new Comparer(comparerLeft, comparerRight)); + } + + /// + /// Creates a new instance with a gven pair of comparers. + /// + /// The type of first items in each tuple. + /// The type of second items in each tuple. + /// The type of third items in each tuple. + /// The input instance. + /// An instance for items. + /// An instance for items. + /// An instance for items. + /// An with the specified comparers applied to each item. + public static IncrementalValuesProvider<(T1, T2, T3)> WithComparers( + this IncrementalValuesProvider<(T1, T2, T3)> source, + IEqualityComparer comparer1, + IEqualityComparer comparer2, + IEqualityComparer comparer3) + { + return source.WithComparer(new Comparer(comparer1, comparer2, comparer3)); + } + + /// + /// An implementation for a value tuple. + /// + public sealed class Comparer : IEqualityComparer<(TLeft Left, TRight Right)> + { + /// + /// The comparer. + /// + private readonly IEqualityComparer comparerLeft; + + /// + /// The comparer. + /// + private readonly IEqualityComparer comparerRight; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The comparer. + /// The comparer. + public Comparer(IEqualityComparer comparerLeft, IEqualityComparer comparerRight) + { + this.comparerLeft = comparerLeft; + this.comparerRight = comparerRight; + } + + /// + 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); + } + + /// + public int GetHashCode((TLeft Left, TRight Right) obj) + { + return HashCode.Combine( + this.comparerLeft.GetHashCode(obj.Left), + this.comparerRight.GetHashCode(obj.Right)); + } + } + + /// + /// An implementation for a value tuple. + /// + public sealed class Comparer : IEqualityComparer<(T1, T2, T3)> + { + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer1; + + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer2; + + /// + /// The comparer. + /// + private readonly IEqualityComparer comparer3; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The comparer. + /// The comparer. + /// The comparer. + public Comparer(IEqualityComparer comparer1, IEqualityComparer comparer2, IEqualityComparer comparer3) + { + this.comparer1 = comparer1; + this.comparer2 = comparer2; + this.comparer3 = comparer3; + } + + /// + 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); + } + + /// + 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)); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/GlobalUsingDirectivesGenerator.cs b/src/ComputeSharp.SourceGenerators/GlobalUsingDirectivesGenerator.cs index 020d0056..53d86891 100644 --- a/src/ComputeSharp.SourceGenerators/GlobalUsingDirectivesGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/GlobalUsingDirectivesGenerator.cs @@ -9,13 +9,13 @@ namespace ComputeSharp.SourceGenerators; /// /// A source generator to create global using directives for the HLSL primitive types. /// -[Generator] -public sealed class GlobalUsingDirectivesGenerator : ISourceGenerator +[Generator(LanguageNames.CSharp)] +public sealed class GlobalUsingDirectivesGenerator : IIncrementalGenerator { /// - 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)); }); } - - /// - public void Execute(GeneratorExecutionContext context) - { - } } diff --git a/src/ComputeSharp.SourceGenerators/Helpers/HashCode.cs b/src/ComputeSharp.SourceGenerators/Helpers/HashCode.cs index 1861ee67..94ea71f0 100644 --- a/src/ComputeSharp.SourceGenerators/Helpers/HashCode.cs +++ b/src/ComputeSharp.SourceGenerators/Helpers/HashCode.cs @@ -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; /// /// A polyfill type that mirrors some methods from on .NET 6. /// 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; + + /// + /// Initializes the default seed. + /// + /// A random seed. + private static unsafe uint GenerateGlobalSeed() + { + byte[] bytes = new byte[4]; + + RandomNumberGenerator.Create().GetBytes(bytes); + + return BitConverter.ToUInt32(bytes, 0); + } + + /// + /// Combines a value into a hash code. + /// + /// The type of the value to combine into the hash code. + /// The value to combine into the hash code. + /// The hash code that represents the value. + public static int Combine(T1 value) + { + uint hc1 = (uint)(value?.GetHashCode() ?? 0); + uint hash = MixEmptyState(); + + hash += 4; + hash = QueueRound(hash, hc1); + hash = MixFinal(hash); + + return (int)hash; + } + + /// + /// Combines two values into a hash code. + /// + /// The type of the first value to combine into the hash code. + /// The type of the second value to combine into the hash code. + /// The first value to combine into the hash code. + /// The second value to combine into the hash code. + /// The hash code that represents the values. + public static int Combine(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; + } + + /// + /// Combines three values into a hash code. + /// + /// The type of the first value to combine into the hash code. + /// The type of the second value to combine into the hash code. + /// The type of the third value to combine into the hash code. + /// The first value to combine into the hash code. + /// The second value to combine into the hash code. + /// The third value to combine into the hash code. + /// The hash code that represents the values. + public static int Combine(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; + } + + /// + /// Combines four values into a hash code. + /// + /// The type of the first value to combine into the hash code. + /// The type of the second value to combine into the hash code. + /// The type of the third value to combine into the hash code. + /// The type of the fourth value to combine into the hash code. + /// The first value to combine into the hash code. + /// The second value to combine into the hash code. + /// The third value to combine into the hash code. + /// The fourth value to combine into the hash code. + /// The hash code that represents the values. + public static int Combine(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; + } + + /// + /// Combines five values into a hash code. + /// + /// The type of the first value to combine into the hash code. + /// The type of the second value to combine into the hash code. + /// The type of the third value to combine into the hash code. + /// The type of the fourth value to combine into the hash code. + /// The type of the fifth value to combine into the hash code. + /// The first value to combine into the hash code. + /// The second value to combine into the hash code. + /// The third value to combine into the hash code. + /// The fourth value to combine into the hash code. + /// The fifth value to combine into the hash code. + /// The hash code that represents the values. + public static int Combine(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; + } + /// /// Combines six values into a hash code. /// @@ -20,28 +191,303 @@ internal struct HashCode /// The fourth value to combine into the hash code. /// The fifth value to combine into the hash code. /// The sixth value to combine into the hash code. - /// The hash code that represents the six values. + /// The hash code that represents the values. public static int Combine(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; } /// - /// Adds a single value to the hash code. + /// Combines seven values into a hash code. /// - /// The type of the value to add to the hash code. - /// The value to add to the hash code. + /// The type of the first value to combine into the hash code. + /// The type of the second value to combine into the hash code. + /// The type of the third value to combine into the hash code. + /// The type of the fourth value to combine into the hash code. + /// The type of the fifth value to combine into the hash code. + /// The type of the sixth value to combine into the hash code. + /// The type of the seventh value to combine into the hash code. + /// The first value to combine into the hash code. + /// The second value to combine into the hash code. + /// The third value to combine into the hash code. + /// The fourth value to combine into the hash code. + /// The fifth value to combine into the hash code. + /// The sixth value to combine into the hash code. + /// The seventh value to combine into the hash code. + /// The hash code that represents the values. + public static int Combine(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; + } + + /// + /// Combines eight values into a hash code. + /// + /// The type of the first value to combine into the hash code. + /// The type of the second value to combine into the hash code. + /// The type of the third value to combine into the hash code. + /// The type of the fourth value to combine into the hash code. + /// The type of the fifth value to combine into the hash code. + /// The type of the sixth value to combine into the hash code. + /// The type of the seventh value to combine into the hash code. + /// The type of the eigth value to combine into the hash code. + /// The first value to combine into the hash code. + /// The second value to combine into the hash code. + /// The third value to combine into the hash code. + /// The fourth value to combine into the hash code. + /// The fifth value to combine into the hash code. + /// The sixth value to combine into the hash code. + /// The seventh value to combine into the hash code. + /// The eigth value to combine into the hash code. + /// The hash code that represents the values. + public static int Combine(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; + } + + /// + /// Adds a single value to the current hash. + /// + /// The type of the value to add into the hash code. + /// The value to add into the hash code. public void Add(T value) { - throw new NotSupportedException(); + Add(value?.GetHashCode() ?? 0); } /// - /// Calculates the final hash code after consecutive invocations. + /// Adds a single value to the current hash. /// - /// The calculated hash code. + /// The type of the value to add into the hash code. + /// The value to add into the hash code. + /// The instance to use. + public void Add(T value, IEqualityComparer? comparer) + { + Add(value is null ? 0 : (comparer?.GetHashCode(value) ?? value.GetHashCode())); + } + + /// + /// Adds a span of bytes to the hash code. + /// + /// The span. + public void AddBytes(ReadOnlySpan 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(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); + } + } + + /// + /// Gets the resulting hashcode from the current instance. + /// + /// The resulting hashcode from the current instance. 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; + } + + /// + [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(); + + /// + [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(); + + /// + /// Rotates the specified value left by the specified number of bits. + /// Similar in behavior to the x86 instruction ROL. + /// + /// The value to rotate. + /// The number of bits to rotate by. + /// Any value outside the range [0..31] is treated as congruent mod 32. + /// The rotated value. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static uint RotateLeft(uint value, int offset) + { + return (value << offset) | (value >> (32 - offset)); } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs new file mode 100644 index 00000000..5b4e860a --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.Syntax.cs @@ -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; + +/// +public sealed partial class IShaderGenerator +{ + /// + internal static partial class BuildHlslString + { + /// + /// Creates a instance for the BuildHlslString method. + /// + /// The input instance to use. + /// The resulting instance for the BuildHlslString method. + public static MethodDeclarationSyntax GetSyntax(HlslShaderSourceInfo hlslSourceInfo) + { + ImmutableArray 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) + // { + // + // } + 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)); + } + + /// + /// Produces the series of statements to build the current HLSL source. + /// + /// The input instance to use. + /// The series of statements to build the HLSL source to compile to execute the current shader. + private static ImmutableArray GenerateRenderMethodBody(HlslShaderSourceInfo hlslSourceInfo) + { + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + 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 items) + { + // global::System.Collections.Generic.HashSet = 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++; + + // .Add(""); + 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 __Attribute = global::ComputeSharp.__Internals.ShaderMethodSourceAttribute.GetForDelegate(, ""); + 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) + { + // .Add(""); + 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(); + 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(); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs index 94d6bf45..d329491e 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslStringMethod.cs @@ -1,20 +1,20 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; using System.Text; -using ComputeSharp.__Internals; using ComputeSharp.SourceGenerators.Diagnostics; using ComputeSharp.SourceGenerators.Extensions; using ComputeSharp.SourceGenerators.Helpers; using ComputeSharp.SourceGenerators.Mappings; +using ComputeSharp.SourceGenerators.Models; using ComputeSharp.SourceGenerators.SyntaxRewriters; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; -using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle; #pragma warning disable CS0618, RS1024 @@ -23,812 +23,727 @@ namespace ComputeSharp.SourceGenerators; /// public sealed partial class IShaderGenerator { - /// - private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod( - GeneratorExecutionContext context, - StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - out string? implicitTextureType, - out bool isSamplerUsed, - out string hlslSource) - { - // Properties are not supported - DetectAndReportPropertyDeclarations(context, structDeclarationSymbol); - - // We need to sets to track all discovered custom types and static methods - HashSet discoveredTypes = new(SymbolEqualityComparer.Default); - Dictionary staticMethods = new(SymbolEqualityComparer.Default); - Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); - - // A given type can only represent a single shader type - if (structDeclarationSymbol.AllInterfaces.Count(static interfaceSymbol => interfaceSymbol is { Name: nameof(IComputeShader) } or { IsGenericType: true, Name: nameof(IPixelShader) }) > 1) - { - context.ReportDiagnostic(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol); - } - - // Explore the syntax tree and extract the processed info - var semanticModel = new SemanticModelProvider(context.Compilation); - var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); - var isComputeShader = pixelShaderSymbol is null; - var pixelShaderTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); - var processedMembers = GetProcessedFields(context, structDeclarationSymbol, discoveredTypes, isComputeShader).ToArray(); - var sharedBuffers = GetGroupSharedMembers(context, structDeclarationSymbol, discoveredTypes).ToArray(); - var (entryPoint, processedMethods, accessesStaticSampler) = GetProcessedMethods(context, structDeclaration, structDeclarationSymbol, semanticModel, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); - var implicitSamplerField = accessesStaticSampler ? ("SamplerState", "__sampler") : default((string, string)?); - var processedTypes = GetProcessedTypes(discoveredTypes).ToArray(); - var processedConstants = GetProcessedConstants(constantDefinitions); - var staticFields = GetStaticFields(context, semanticModel, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); - string namespaceName = structDeclarationSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)); - string structName = structDeclaration.Identifier.Text; - SyntaxTokenList structModifiers = structDeclaration.Modifiers; - IEnumerable bodyStatements = GenerateRenderMethodBody( - processedConstants, - staticFields, - processedTypes, - isComputeShader, - processedMembers, - pixelShaderTextureType, - accessesStaticSampler, - sharedBuffers, - processedMethods, - entryPoint, - out hlslSource); - - implicitTextureType = pixelShaderTextureType; - isSamplerUsed = accessesStaticSampler; - - // 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) - // { - // - // } - 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)); - } - /// - /// Gets a sequence of captured fields and their mapped names. + /// A helper with all logic to generate the BuildHlslString method. /// - /// The current generator context in use. - /// The input instance to process. - /// The collection of currently discovered types. - /// Indicates whether or not represents a compute shader. - /// A sequence of captured fields in . - [Pure] - private static IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> GetProcessedFields( - GeneratorExecutionContext context, - INamedTypeSymbol structDeclarationSymbol, - ICollection types, - bool isComputeShader) + internal static partial class BuildHlslString { - bool hlslResourceFound = false; - - foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + /// + /// Gathers all necessary information on a transpiled HLSL source for a given shader type. + /// + /// The input object currently in use. + /// The node to process. + /// The for . + /// The resulting diagnostics from the processing operation. + /// The resulting info on the processed shader. + public static HlslShaderSourceInfo GetInfo( + Compilation compilation, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + out ImmutableArray diagnostics) { - if (fieldSymbol.IsStatic) continue; + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + // Properties are not supported + DetectAndReportPropertyDeclarations(builder, structDeclarationSymbol); - // Group shared fields must be static - if (attribute is not null) + // We need to sets to track all discovered custom types and static methods + HashSet discoveredTypes = new(SymbolEqualityComparer.Default); + Dictionary staticMethods = new(SymbolEqualityComparer.Default); + Dictionary constantDefinitions = new(SymbolEqualityComparer.Default); + + // A given type can only represent a single shader type + if (structDeclarationSymbol.AllInterfaces.Count(static interfaceSymbol => interfaceSymbol is { Name: nameof(IComputeShader) } or { IsGenericType: true, Name: nameof(IPixelShader) }) > 1) { - context.ReportDiagnostic(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name); + builder.Add(MultipleShaderTypesImplemented, structDeclarationSymbol, structDeclarationSymbol); } - // Captured fields must be named type symbols - if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol) - { - context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + // Explore the syntax tree and extract the processed info + var semanticModelProvider = new SemanticModelProvider(compilation); + var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); + var isComputeShader = pixelShaderSymbol is null; + var implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); + var (resourceFields, valueFields) = GetInstanceFields(builder, structDeclarationSymbol, discoveredTypes, isComputeShader); + var delegateInstanceFields = GetDispatchId.GetInfo(structDeclarationSymbol); + var sharedBuffers = GetSharedBuffers(builder, structDeclarationSymbol, discoveredTypes); + var (entryPoint, processedMethods, isSamplerUsed) = GetProcessedMethods(builder, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, constantDefinitions, isComputeShader); + var implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?); + var declaredTypes = GetDeclaredTypes(discoveredTypes); + var definedConstants = GetDefinedConstants(constantDefinitions); + var staticFields = GetStaticFields(builder, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); - continue; - } + diagnostics = builder.ToImmutable(); - string metadataName = typeSymbol.GetFullMetadataName(); - - // Allowed fields must be either resources, unmanaged values or delegates - if (HlslKnownTypes.IsTypedResourceType(metadataName)) - { - hlslResourceFound = true; - - // Track the type of items in the current buffer - if (HlslKnownTypes.IsStructuredBufferType(metadataName)) - { - types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]); - } - } - else if (!typeSymbol.IsUnmanagedType && - typeSymbol.TypeKind != TypeKind.Delegate) - { - // Shaders can only capture valid HLSL resource types or unmanaged types - context.ReportDiagnostic(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol); - - continue; - } - else if (typeSymbol.IsUnmanagedType && - !HlslKnownTypes.IsKnownHlslType(metadataName)) - { - // Track the type if it's a custom struct - types.Add(typeSymbol); - } - - string typeName = HlslKnownTypes.GetMappedName(typeSymbol); - - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - - // Yield back the current mapping for the name (if the name used a reserved keyword) - yield return (fieldSymbol, mapping ?? fieldSymbol.Name, typeName); + // Get the HLSL source data with the intermediate info + return GetHlslSourceInfo( + definedConstants, + declaredTypes, + resourceFields, + valueFields, + delegateInstanceFields, + staticFields, + sharedBuffers, + processedMethods, + isComputeShader, + implicitTextureType, + isSamplerUsed, + entryPoint); } - // If the shader is a compute one (so no implicit output texture), it has to contain at least one resource - if (!hlslResourceFound && isComputeShader) + /// + /// Gets a sequence of captured fields and their mapped names. + /// + /// The collection of produced instances. + /// The input instance to process. + /// The collection of currently discovered types. + /// Indicates whether or not represents a compute shader. + /// A sequence of captured fields in . + [Pure] + private static ( + ImmutableArray<(string MetadataName, string Name, string HlslType)>, + ImmutableArray<(string Name, string HlslType)>) + GetInstanceFields( + ImmutableArray.Builder diagnostics, + INamedTypeSymbol structDeclarationSymbol, + ICollection types, + bool isComputeShader) { - context.ReportDiagnostic(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol); - } - } + ImmutableArray<(string, string, string)>.Builder resources = ImmutableArray.CreateBuilder<(string, string, string)>(); + ImmutableArray<(string, string)>.Builder values = ImmutableArray.CreateBuilder<(string, string)>(); + bool hlslResourceFound = false; - /// - /// Gets a sequence of shader static fields and their mapped names. - /// - /// The current generator context in use. - /// The instance for the type to process. - /// The instance for the current type. - /// The type symbol for the shader type. - /// The collection of currently discovered types. - /// The collection of discovered constant definitions. - /// A sequence of static constant fields in . - [Pure] - private static IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( - GeneratorExecutionContext context, - SemanticModelProvider semanticModel, - StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - ICollection discoveredTypes, - IDictionary constantDefinitions) - { - foreach (var fieldDeclaration in structDeclaration.Members.OfType()) - { - foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) { - IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!; - - if (!fieldSymbol.IsStatic || fieldSymbol.IsConst) + if (fieldSymbol.IsStatic) { continue; } - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass?.ToDisplayString() == typeof(GroupSharedAttribute).FullName); - if (attribute is not null) continue; - - // Constant properties must be of a primitive, vector or matrix type - if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol || - !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName())) + // Group shared fields must be static + if (attribute is not null) { - context.ReportDiagnostic(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + diagnostics.Add(InvalidGroupSharedFieldDeclaration, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name); + } + + // Captured fields must be named type symbols + if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol) + { + diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); continue; } + string metadataName = typeSymbol.GetFullMetadataName(); + string typeName = HlslKnownTypes.GetMappedName(typeSymbol); + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - string typeDeclaration = fieldSymbol.IsReadOnly switch + // Allowed fields must be either resources, unmanaged values or delegates + if (HlslKnownTypes.IsTypedResourceType(metadataName)) { - true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}", - false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}" - }; + hlslResourceFound = true; - StaticFieldRewriter staticFieldRewriter = new( + // Track the type of items in the current buffer + if (HlslKnownTypes.IsStructuredBufferType(metadataName)) + { + types.Add((INamedTypeSymbol)typeSymbol.TypeArguments[0]); + } + + // Add the current mapping for the name (if the name used a reserved keyword) + resources.Add((metadataName, mapping ?? fieldSymbol.Name, typeName)); + } + else if (!typeSymbol.IsUnmanagedType && + typeSymbol.TypeKind != TypeKind.Delegate) + { + // Shaders can only capture valid HLSL resource types or unmanaged types + diagnostics.Add(InvalidShaderField, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, typeSymbol); + + continue; + } + else if (typeSymbol.IsUnmanagedType) + { + // Track the type if it's a custom struct + if (!HlslKnownTypes.IsKnownHlslType(metadataName)) + { + types.Add(typeSymbol); + } + + values.Add((mapping ?? fieldSymbol.Name, typeName)); + } + } + + // If the shader is a compute one (so no implicit output texture), it has to contain at least one resource + if (!hlslResourceFound && isComputeShader) + { + diagnostics.Add(MissingShaderResources, structDeclarationSymbol, structDeclarationSymbol); + } + + return (resources.ToImmutable(), values.ToImmutable()); + } + + /// + /// Gets a sequence of shader static fields and their mapped names. + /// + /// The collection of produced instances. + /// The instance for the type to process. + /// The instance for the current type. + /// The type symbol for the shader type. + /// The collection of currently discovered types. + /// The collection of discovered constant definitions. + /// A sequence of static constant fields in . + [Pure] + private static ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> GetStaticFields( + ImmutableArray.Builder diagnostics, + SemanticModelProvider semanticModel, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + ICollection discoveredTypes, + IDictionary constantDefinitions) + { + ImmutableArray<(string, string, string?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, string?)>(); + + foreach (var fieldDeclaration in structDeclaration.Members.OfType()) + { + foreach (var variableDeclarator in fieldDeclaration.Declaration.Variables) + { + IFieldSymbol fieldSymbol = (IFieldSymbol)semanticModel.For(variableDeclarator).GetDeclaredSymbol(variableDeclarator)!; + + if (!fieldSymbol.IsStatic || fieldSymbol.IsConst) + { + continue; + } + + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass?.ToDisplayString() == typeof(GroupSharedAttribute).FullName); + + if (attribute is not null) + { + continue; + } + + // Constant properties must be of a primitive, vector or matrix type + if (fieldSymbol.Type is not INamedTypeSymbol typeSymbol || + !HlslKnownTypes.IsKnownHlslType(typeSymbol.GetFullMetadataName())) + { + diagnostics.Add(InvalidShaderStaticFieldType, variableDeclarator, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + string typeDeclaration = fieldSymbol.IsReadOnly switch + { + true => $"static const {HlslKnownTypes.GetMappedName(typeSymbol)}", + false => $"static {HlslKnownTypes.GetMappedName(typeSymbol)}" + }; + + StaticFieldRewriter staticFieldRewriter = new( + semanticModel, + discoveredTypes, + constantDefinitions, + diagnostics); + + string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace(eol: "\n").ToFullString(); + + builder.Add((mapping ?? fieldSymbol.Name, typeDeclaration, assignment)); + } + } + + return builder.ToImmutable(); + } + + /// + /// Gets a sequence of captured members and their mapped names. + /// + /// The collection of produced instances. + /// The input instance to process. + /// The collection of currently discovered types. + /// A sequence of captured members in . + [Pure] + private static ImmutableArray<(string Name, string Type, int? Count)> GetSharedBuffers( + ImmutableArray.Builder diagnostics, + INamedTypeSymbol structDeclarationSymbol, + ICollection types) + { + ImmutableArray<(string, string, int?)>.Builder builder = ImmutableArray.CreateBuilder<(string, string, int?)>(); + + foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) + { + if (!fieldSymbol.IsStatic) + { + continue; + } + + AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass?.ToDisplayString() == typeof(GroupSharedAttribute).FullName); + + if (attribute is null) + { + continue; + } + + if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol) + { + diagnostics.Add(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + if (!typeSymbol.ElementType.IsUnmanagedType) + { + diagnostics.Add(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); + + continue; + } + + int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value; + + string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol); + + _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); + + builder.Add((mapping ?? fieldSymbol.Name, typeName, bufferSize)); + + types.Add((INamedTypeSymbol)typeSymbol.ElementType); + } + + return builder.ToImmutable(); + } + + /// + /// Gets a sequence of processed methods declared within a given type. + /// + /// The collection of produced instances. + /// The type symbol for the shader type. + /// The instance for the current type. + /// The instance for the type to process. + /// The collection of currently discovered types. + /// The set of discovered and processed static methods. + /// The collection of discovered constant definitions. + /// Indicates whether or not represents a compute shader. + /// A sequence of processed methods in , and the entry point. + [Pure] + private static (string EntryPoint, ImmutableArray<(string Signature, string Definition)> Methods, bool IsSamplerUser) GetProcessedMethods( + ImmutableArray.Builder diagnostics, + StructDeclarationSyntax structDeclaration, + INamedTypeSymbol structDeclarationSymbol, + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary staticMethods, + IDictionary constantDefinitions, + bool isComputeShader) + { + // Find all declared methods in the type + ImmutableArray methodDeclarations = ( + from syntaxNode in structDeclaration.DescendantNodes() + where syntaxNode.IsKind(SyntaxKind.MethodDeclaration) + select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); + + string? entryPoint = null; + ImmutableArray<(string, string)>.Builder methods = ImmutableArray.CreateBuilder<(string, string)>(); + bool isSamplerUsed = false; + + foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) + { + IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!; + bool isShaderEntryPoint = + (isComputeShader && + methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) && + methodDeclarationSymbol.ReturnsVoid && + methodDeclarationSymbol.TypeParameters.Length == 0 && + methodDeclarationSymbol.Parameters.Length == 0) || + (!isComputeShader && + methodDeclarationSymbol.Name == nameof(IPixelShader.Execute) && + methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type + methodDeclarationSymbol.TypeParameters.Length == 0 && + methodDeclarationSymbol.Parameters.Length == 0); + + // Create the source rewriter for the current method + ShaderSourceRewriter shaderSourceRewriter = new( + structDeclarationSymbol, semanticModel, discoveredTypes, + staticMethods, constantDefinitions, - context); + diagnostics, + isShaderEntryPoint); - string? assignment = staticFieldRewriter.Visit(variableDeclarator)?.NormalizeWhitespace(eol: "\n").ToFullString(); + // Rewrite the method syntax tree + MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); - yield return (mapping ?? fieldSymbol.Name, typeDeclaration, assignment); - } - } - } + // Track the implicit sampler, if used + isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed; - /// - /// Gets a sequence of captured members and their mapped names. - /// - /// The current generator context in use. - /// The input instance to process. - /// The collection of currently discovered types. - /// A sequence of captured members in . - [Pure] - private static IEnumerable<(string Name, string Type, int? Count)> GetGroupSharedMembers( - GeneratorExecutionContext context, - INamedTypeSymbol structDeclarationSymbol, - ICollection types) - { - foreach (var fieldSymbol in structDeclarationSymbol.GetMembers().OfType()) - { - if (!fieldSymbol.IsStatic) continue; - - AttributeData? attribute = fieldSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(GroupSharedAttribute) }); - - if (attribute is null) continue; - - if (fieldSymbol.Type is not IArrayTypeSymbol typeSymbol) - { - context.ReportDiagnostic(InvalidGroupSharedFieldType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - if (!typeSymbol.ElementType.IsUnmanagedType) - { - context.ReportDiagnostic(InvalidGroupSharedFieldElementType, fieldSymbol, structDeclarationSymbol, fieldSymbol.Name, fieldSymbol.Type); - - continue; - } - - int? bufferSize = (int?)attribute.ConstructorArguments.FirstOrDefault().Value; - - string typeName = HlslKnownTypes.GetMappedElementName(typeSymbol); - - _ = HlslKnownKeywords.TryGetMappedName(fieldSymbol.Name, out string? mapping); - - yield return (mapping ?? fieldSymbol.Name, typeName, bufferSize); - - types.Add((INamedTypeSymbol)typeSymbol.ElementType); - } - } - - /// - /// Gets a sequence of processed methods declared within a given type. - /// - /// The current generator context in use. - /// The type symbol for the shader type. - /// The instance for the current type. - /// The instance for the type to process. - /// The collection of currently discovered types. - /// The set of discovered and processed static methods. - /// The collection of discovered constant definitions. - /// Indicates whether or not represents a compute shader. - /// A sequence of processed methods in , and the entry point. - [Pure] - private static (string EntryPoint, IEnumerable<(string Signature, string Definition)> ProcessedMethods, bool IsSamplerUser) GetProcessedMethods( - GeneratorExecutionContext context, - StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary staticMethods, - IDictionary constantDefinitions, - bool isComputeShader) - { - // Find all declared methods in the type - ImmutableArray methodDeclarations = ( - from syntaxNode in structDeclaration.DescendantNodes() - where syntaxNode.IsKind(SyntaxKind.MethodDeclaration) - select (MethodDeclarationSyntax)syntaxNode).ToImmutableArray(); - - string? entryPoint = null; - List<(string, string)> processedMethods = new(); - bool isSamplerUsed = false; - - foreach (MethodDeclarationSyntax methodDeclaration in methodDeclarations) - { - IMethodSymbol methodDeclarationSymbol = semanticModel.For(methodDeclaration).GetDeclaredSymbol(methodDeclaration)!; - bool isShaderEntryPoint = - (isComputeShader && - methodDeclarationSymbol.Name == nameof(IComputeShader.Execute) && - methodDeclarationSymbol.ReturnsVoid && - methodDeclarationSymbol.TypeParameters.Length == 0 && - methodDeclarationSymbol.Parameters.Length == 0) || - (!isComputeShader && - methodDeclarationSymbol.Name == nameof(IPixelShader.Execute) && - methodDeclarationSymbol.ReturnType is not null && // TODO: match for pixel type - methodDeclarationSymbol.TypeParameters.Length == 0 && - methodDeclarationSymbol.Parameters.Length == 0); - - // Create the source rewriter for the current method - ShaderSourceRewriter shaderSourceRewriter = new( - structDeclarationSymbol, - semanticModel, - discoveredTypes, - staticMethods, - constantDefinitions, - context, - isShaderEntryPoint); - - // Rewrite the method syntax tree - MethodDeclarationSyntax? processedMethod = shaderSourceRewriter.Visit(methodDeclaration)!.WithoutTrivia(); - - // Track the implicit sampler, if used - isSamplerUsed = isSamplerUsed || shaderSourceRewriter.IsSamplerUsed; - - // Emit the extracted local functions first - foreach (var localFunction in shaderSourceRewriter.LocalFunctions) - { - processedMethods.Add(( - localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), - localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString())); - } - - // If the method is the shader entry point, do additional processing - if (isShaderEntryPoint) - { - processedMethod = isComputeShader switch + // Emit the extracted local functions first + foreach (var localFunction in shaderSourceRewriter.LocalFunctions) { - true => new ExecuteMethodRewriter.Compute(shaderSourceRewriter).Visit(processedMethod)!, - false => new ExecuteMethodRewriter.Pixel(shaderSourceRewriter).Visit(processedMethod)! - }; - - entryPoint = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString(); - } - else - { - processedMethods.Add(( - processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), - processedMethod.NormalizeWhitespace(eol: "\n").ToFullString())); - } - } - - // Process static methods as well - foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values) - { - processedMethods.Add(( - staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), - staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); - } - - return (entryPoint!, processedMethods, isSamplerUsed); - } - - /// - /// Gets a sequence of discovered constants. - /// - /// The collection of discovered constant definitions. - /// A sequence of discovered constants to declare in the shader. - [Pure] - internal static IEnumerable<(string Name, string Value)> GetProcessedConstants(IReadOnlyDictionary constantDefinitions) - { - foreach (var constant in constantDefinitions) - { - var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); - var constantName = $"__{ownerTypeName}__{constant.Key.Name}"; - - yield return (constantName, constant.Value); - } - } - - /// - /// Gets the sequence of processed discovered custom types. - /// - /// The sequence of discovered custom types. - /// A sequence of custom type definitions to add to the shader source. - internal static IEnumerable<(string Name, string Definition)> GetProcessedTypes(IEnumerable types) - { - foreach (var type in HlslKnownTypes.GetCustomTypes(types)) - { - var structType = type.GetFullMetadataName().ToHlslIdentifierName(); - var structDeclaration = StructDeclaration(structType); - - // Declare the fields of the current type - foreach (var field in type.GetMembers().OfType()) - { - if (field.IsStatic) continue; - - INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type; - - // Convert the name to the fully qualified HLSL version - if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped)) - { - mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName(); + methods.Add(( + localFunction.Value.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + localFunction.Value.NormalizeWhitespace(eol: "\n").ToFullString())); } - structDeclaration = structDeclaration.AddMembers( - FieldDeclaration(VariableDeclaration( - IdentifierName(mapped!)).AddVariables( - VariableDeclarator(Identifier(field.Name))))); - } - - // Insert the trailing ; right after the closing bracket (after normalization) - yield return - (structType, - structDeclaration - .NormalizeWhitespace(eol: "\n") - .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) - .ToFullString()); - } - } - - /// - /// Finds and reports all declared properties in a shader. - /// - /// The current generator context in use. - /// The input instance to process. - private static void DetectAndReportPropertyDeclarations(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol) - { - foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType()) - { - context.ReportDiagnostic(DiagnosticDescriptors.PropertyDeclaration, propertySymbol); - } - } - - /// - /// Produces the series of statements to build the current HLSL source. - /// - /// The sequence of defined constants for the shader. - /// The sequence of static fields referenced by the shader. - /// The sequence of declared types used by the shader. - /// Whether or not the current shader is a compute shader (or a pixel shader). - /// The sequence of instance fields for the current shader. - /// The type of the implicit target texture, if present. - /// Whether the static sampler is used by the shader. - /// The sequence of shared buffers declared by the shader. - /// The sequence of processed methods used by the shader. - /// The body of the entry point of the shader. - /// The generated HLSL source code (ignoring captured delegates, if present). - /// The series of statements to build the HLSL source to compile to execute the current shader. - private static IEnumerable GenerateRenderMethodBody( - IEnumerable<(string Name, string Value)> definedConstants, - IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> staticFields, - IEnumerable<(string Name, string Definition)> declaredTypes, - bool isComputeShader, - IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> instanceFields, - string? implicitTextureType, - bool isSamplerUsed, - IEnumerable<(string Name, string Type, int? Count)> sharedBuffers, - IEnumerable<(string Signature, string Definition)> processedMethods, - string executeMethod, - out string hlslSource) - { - List statements = new(); - StringBuilder chunkedTextBuilder = new(); - StringBuilder aggregateTextBuilder = new(); - int capturedDelegates = 0; - int prologueStatements = 0; - int sizeHint = 64; - - void AppendLF() - { - chunkedTextBuilder.Append('\n'); - } - - void AppendLine(string text) - { - chunkedTextBuilder.Append(text); - } - - void AppendLineAndLF(string text) - { - chunkedTextBuilder.Append(text); - chunkedTextBuilder.Append('\n'); - } - - void AppendCharacterAndLF(char c) - { - chunkedTextBuilder.Append(c); - chunkedTextBuilder.Append('\n'); - } - - void AppendThreadNumIdentifier(string name) - { - aggregateTextBuilder.Append(name); - } - - void AppendParsedStatement(string text) - { - FlushText(); - - statements.Add(ParseStatement(text)); - } - - void FlushText() - { - if (chunkedTextBuilder.Length > 0) - { - string chunkedText = chunkedTextBuilder.ToString(); - - aggregateTextBuilder.Append(chunkedText); - - sizeHint += chunkedTextBuilder.Length; - - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append"))) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(chunkedText)))))); - - chunkedTextBuilder.Clear(); - } - } - - // Declare the hashsets to track imported members and types from delegates, if needed - if (instanceFields.Any(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) - { - void DeclareMapping(int index, string name, IEnumerable items) - { - // global::System.Collections.Generic.HashSet = 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++; - - // .Add(""); - foreach (var item in items) + // If the method is the shader entry point, do additional processing + if (isShaderEntryPoint) { - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName(name), - IdentifierName("Add"))) - .AddArgumentListArguments(Argument( - LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(item)))))); + processedMethod = isComputeShader switch + { + true => new ExecuteMethodRewriter.Compute(shaderSourceRewriter).Visit(processedMethod)!, + false => new ExecuteMethodRewriter.Pixel(shaderSourceRewriter).Visit(processedMethod)! + }; - prologueStatements++; - } - } - - DeclareMapping(0, "__typeNames", declaredTypes.Select(static t => t.Name)); - DeclareMapping(1, "__constantNames", definedConstants.Select(static t => t.Name)); - DeclareMapping(2, "__methodNames", processedMethods.Select(static t => t.Signature)); - - // Go through all existing delegate fields, if any - foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) - { - // global::ComputeSharp.__Internals.ShaderMethodSourceAttribute __Attribute = global::ComputeSharp.__Internals.ShaderMethodSourceAttribute.GetForDelegate(, ""); - 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 - AppendLineAndLF("// ================================================"); - AppendLineAndLF("// AUTO GENERATED"); - AppendLineAndLF("// ================================================"); - AppendLineAndLF("// This shader was created by ComputeSharp."); - AppendLineAndLF("// See: https://github.com/Sergio0694/ComputeSharp."); - - // Group size constants - AppendLF(); - AppendLine("#define __GroupSize__get_X "); - AppendParsedStatement("builder.Append(threadsX);"); - AppendThreadNumIdentifier(""); - AppendLF(); - AppendLine("#define __GroupSize__get_Y "); - AppendParsedStatement("builder.Append(threadsY);"); - AppendThreadNumIdentifier(""); - AppendLF(); - AppendLine("#define __GroupSize__get_Z "); - AppendParsedStatement("builder.Append(threadsZ);"); - AppendThreadNumIdentifier(""); - AppendLF(); - - // Define declarations - foreach (var (name, value) in definedConstants) - { - AppendLineAndLF($"#define {name} {value}"); - } - - // Defines from captured delegates - foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) - { - AppendParsedStatement($"__{fieldName}Attribute.AppendConstants(ref builder, __constantNames);"); - } - - // Static fields - if (staticFields.Any()) - { - AppendLF(); - - foreach (var field in staticFields) - { - if (field.Assignment is string assignment) - { - AppendLineAndLF($"{field.TypeDeclaration} {field.Name} = {assignment};"); + entryPoint = processedMethod.NormalizeWhitespace(eol: "\n").ToFullString(); } else { - AppendLineAndLF($"{field.TypeDeclaration} {field.Name};"); + methods.Add(( + processedMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + processedMethod.NormalizeWhitespace(eol: "\n").ToFullString())); } } - } - // Declared types - foreach (var (_, typeDefinition) in declaredTypes) - { - AppendLF(); - AppendLineAndLF(typeDefinition); - } - - // Declared types from captured delegates - foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) - { - AppendParsedStatement($"__{fieldName}Attribute.AppendTypes(ref builder, __typeNames);"); - } - - // Captured variables - AppendLF(); - AppendLineAndLF("cbuffer _ : register(b0)"); - AppendCharacterAndLF('{'); - AppendLineAndLF(" uint __x;"); - AppendLineAndLF(" uint __y;"); - - if (isComputeShader) - { - AppendLineAndLF(" uint __z;"); - } - - // User-defined values - foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields.Where(static t => t.Symbol.Type.IsUnmanagedType)) - { - AppendLineAndLF($" {fieldType} {fieldName};"); - } - - AppendCharacterAndLF('}'); - - int constantBuffersCount = 1; - int readOnlyBuffersCount = 0; - int readWriteBuffersCount = 0; - - // Optional implicit texture field - if (!isComputeShader) - { - AppendLF(); - AppendLineAndLF($"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});"); - } - - // Optional sampler field - if (isSamplerUsed) - { - AppendLF(); - AppendLineAndLF("SamplerState __sampler : register(s);"); - } - - // Resources - foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields) - { - string metadataName = fieldSymbol.Type.GetFullMetadataName(); - - if (HlslKnownTypes.IsConstantBufferType(metadataName)) + // Process static methods as well + foreach (MethodDeclarationSyntax staticMethod in staticMethods.Values) { - AppendLF(); - AppendLineAndLF($"cbuffer _{fieldName} : register(b{constantBuffersCount++})"); - AppendCharacterAndLF('{'); - AppendLineAndLF($" {fieldType} {fieldName}[2];"); - AppendCharacterAndLF('}'); + methods.Add(( + staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), + staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); } - else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName)) + + return (entryPoint!, methods.ToImmutable(), isSamplerUsed); + } + + /// + /// Gets a sequence of discovered constants. + /// + /// The collection of discovered constant definitions. + /// A sequence of discovered constants to declare in the shader. + [Pure] + internal static ImmutableArray<(string Name, string Value)> GetDefinedConstants(IReadOnlyDictionary constantDefinitions) + { + ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(constantDefinitions.Count); + + foreach (var constant in constantDefinitions) { - AppendLF(); - AppendLineAndLF($"{fieldType} {fieldName} : register(t{readOnlyBuffersCount++});"); + var ownerTypeName = ((INamedTypeSymbol)constant.Key.ContainingSymbol).ToDisplayString().ToHlslIdentifierName(); + var constantName = $"__{ownerTypeName}__{constant.Key.Name}"; + + builder.Add((constantName, constant.Value)); } - else if (HlslKnownTypes.IsTypedResourceType(metadataName)) + + return builder.MoveToImmutable(); + } + + /// + /// Gets the sequence of processed discovered custom types. + /// + /// The sequence of discovered custom types. + /// A sequence of custom type definitions to add to the shader source. + internal static ImmutableArray<(string Name, string Definition)> GetDeclaredTypes(IEnumerable types) + { + ImmutableArray<(string, string)>.Builder builder = ImmutableArray.CreateBuilder<(string, string)>(); + + foreach (var type in HlslKnownTypes.GetCustomTypes(types)) { - AppendLF(); - AppendLineAndLF($"{fieldType} {fieldName} : register(u{readWriteBuffersCount++});"); + var structType = type.GetFullMetadataName().ToHlslIdentifierName(); + var structDeclaration = StructDeclaration(structType); + + // Declare the fields of the current type + foreach (var field in type.GetMembers().OfType()) + { + if (field.IsStatic) continue; + + INamedTypeSymbol fieldType = (INamedTypeSymbol)field.Type; + + // Convert the name to the fully qualified HLSL version + if (!HlslKnownTypes.TryGetMappedName(fieldType.GetFullMetadataName(), out string? mapped)) + { + mapped = fieldType.GetFullMetadataName().ToHlslIdentifierName(); + } + + structDeclaration = structDeclaration.AddMembers( + FieldDeclaration(VariableDeclaration( + IdentifierName(mapped!)).AddVariables( + VariableDeclarator(Identifier(field.Name))))); + } + + // Insert the trailing ; right after the closing bracket (after normalization) + builder.Add(( + structType, + structDeclaration + .NormalizeWhitespace(eol: "\n") + .WithSemicolonToken(Token(SyntaxKind.SemicolonToken)) + .ToFullString())); + } + + return builder.ToImmutable(); + } + + /// + /// Finds and reports all declared properties in a shader. + /// + /// The collection of produced instances. + /// The input instance to process. + private static void DetectAndReportPropertyDeclarations(ImmutableArray.Builder diagnostics, INamedTypeSymbol structDeclarationSymbol) + { + foreach (var propertySymbol in structDeclarationSymbol.GetMembers().OfType()) + { + diagnostics.Add(DiagnosticDescriptors.PropertyDeclaration, propertySymbol); } } - // Shared buffers - foreach (var (bufferName, bufferType, bufferCount) in sharedBuffers) + /// + /// Produces the series of statements to build the current HLSL source. + /// + /// The sequence of defined constants for the shader. + /// The sequence of declared types used by the shader. + /// The sequence of resource instance fields for the current shader. + /// The sequence of value instance fields for the current shader. + /// The sequence of delegate fields for the current shader. + /// The sequence of static fields referenced by the shader. + /// The sequence of shared buffers declared by the shader. + /// The sequence of processed methods used by the shader. + /// Whether or not the current shader type is a compute shader. + /// The type of the implicit target texture, if present. + /// Whether the static sampler is used by the shader. + /// The body of the entry point of the shader. + /// The series of statements to build the HLSL source to compile to execute the current shader. + private static HlslShaderSourceInfo GetHlslSourceInfo( + ImmutableArray<(string Name, string Value)> definedConstants, + ImmutableArray<(string Name, string Definition)> declaredTypes, + ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields, + ImmutableArray<(string Name, string HlslType)> valueFields, + ImmutableArray delegateInstanceFields, + ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields, + ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers, + ImmutableArray<(string Signature, string Definition)> processedMethods, + bool isComputeShader, + string? implicitTextureType, + bool isSamplerUsed, + + string executeMethod) { - object count = (object?)bufferCount ?? "threadsX * threadsY * threadsZ"; + StringBuilder hlslBuilder = new(); + + void AppendLF() + { + hlslBuilder.Append('\n'); + } + + void AppendLine(string text) + { + hlslBuilder.Append(text); + } + + void AppendLineAndLF(string text) + { + hlslBuilder.Append(text); + hlslBuilder.Append('\n'); + } + + void AppendCharacterAndLF(char c) + { + hlslBuilder.Append(c); + hlslBuilder.Append('\n'); + } + + string FlushText() + { + string text = hlslBuilder.ToString(); + + hlslBuilder.Clear(); + + return text; + } + + // Header + AppendLineAndLF("// ================================================"); + AppendLineAndLF("// AUTO GENERATED"); + AppendLineAndLF("// ================================================"); + AppendLineAndLF("// This shader was created by ComputeSharp."); + AppendLineAndLF("// See: https://github.com/Sergio0694/ComputeSharp."); + + // Group size constants + AppendLF(); + AppendLine("#define __GroupSize__get_X "); + + string headerAndThreadsX = FlushText(); AppendLF(); - AppendLineAndLF($"groupshared {bufferType} {bufferName} [{count}];"); - } + AppendLine("#define __GroupSize__get_Y "); + + string threadsY = FlushText(); - // Forward declarations - foreach (var (forwardDeclaration, _) in processedMethods) - { AppendLF(); - AppendLineAndLF(forwardDeclaration); - } + AppendLine("#define __GroupSize__get_Z "); - // Forward declarations from captured delegates - foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) - { - AppendParsedStatement($"__{fieldName}Attribute.AppendForwardDeclarations(ref builder, __methodNames);"); - } + string threadsZ = FlushText(); - // 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) - { - // .Add(""); + AppendLF(); + + // Define declarations + foreach (var (name, value) in definedConstants) + { + AppendLineAndLF($"#define {name} {value}"); + } + + string defines = FlushText(); + + // Static fields + if (staticFields.Any()) + { + AppendLF(); + + foreach (var field in staticFields) + { + if (field.Assignment is string assignment) + { + AppendLineAndLF($"{field.TypeDeclaration} {field.Name} = {assignment};"); + } + else + { + AppendLineAndLF($"{field.TypeDeclaration} {field.Name};"); + } + } + } + + // Declared types + foreach (var (_, typeDefinition) in declaredTypes) + { + AppendLF(); + AppendLineAndLF(typeDefinition); + } + + string staticFieldsAndDeclaredTypes = FlushText(); + + // Captured variables + AppendLF(); + AppendLineAndLF("cbuffer _ : register(b0)"); + AppendCharacterAndLF('{'); + AppendLineAndLF(" uint __x;"); + AppendLineAndLF(" uint __y;"); + + if (isComputeShader) + { + AppendLineAndLF(" uint __z;"); + } + + // User-defined values + foreach (var (fieldName, fieldType) in valueFields) + { + AppendLineAndLF($" {fieldType} {fieldName};"); + } + + AppendCharacterAndLF('}'); + + int constantBuffersCount = 1; + int readOnlyBuffersCount = 0; + int readWriteBuffersCount = 0; + + // Optional implicit texture field + if (!isComputeShader) + { + AppendLF(); + AppendLineAndLF($"{implicitTextureType} __outputTexture : register(u{readWriteBuffersCount++});"); + } + + // Optional sampler field + if (isSamplerUsed) + { + AppendLF(); + AppendLineAndLF("SamplerState __sampler : register(s);"); + } + + // Resources + foreach (var (metadataName, fieldName, fieldType) in resourceFields) + { + if (HlslKnownTypes.IsConstantBufferType(metadataName)) + { + AppendLF(); + AppendLineAndLF($"cbuffer _{fieldName} : register(b{constantBuffersCount++})"); + AppendCharacterAndLF('{'); + AppendLineAndLF($" {fieldType} {fieldName}[2];"); + AppendCharacterAndLF('}'); + } + else if (HlslKnownTypes.IsReadOnlyTypedResourceType(metadataName)) + { + AppendLF(); + AppendLineAndLF($"{fieldType} {fieldName} : register(t{readOnlyBuffersCount++});"); + } + else if (HlslKnownTypes.IsReadWriteTypedResourceType(metadataName)) + { + AppendLF(); + AppendLineAndLF($"{fieldType} {fieldName} : register(u{readWriteBuffersCount++});"); + } + } + + // Shared buffers + foreach (var (bufferName, bufferType, bufferCount) in sharedBuffers) + { + object count = (object?)bufferCount ?? "__GroupSize__get_X * __GroupSize__get_Y * __GroupSize__get_Z"; + + AppendLF(); + AppendLineAndLF($"groupshared {bufferType} {bufferName} [{count}];"); + } + + // Forward declarations foreach (var (forwardDeclaration, _) in processedMethods) { - FlushText(); - - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("__methodNames"), - IdentifierName("Remove"))) - .AddArgumentListArguments(Argument( - LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(forwardDeclaration)))))); + AppendLF(); + AppendLineAndLF(forwardDeclaration); } - } - // Captured methods - foreach (var (_, method) in processedMethods) - { + string capturedFieldsAndResourcesAndForwardDeclarations = FlushText(); + + // Captured methods + foreach (var (_, method) in processedMethods) + { + AppendLF(); + AppendLineAndLF(method); + } + + string capturedMethods = FlushText(); + + // Entry point AppendLF(); - AppendLineAndLF(method); + AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]"); + AppendLineAndLF(executeMethod); + + string entryPoint = FlushText(); + + return new( + headerAndThreadsX, + threadsY, + threadsZ, + defines, + staticFieldsAndDeclaredTypes, + capturedFieldsAndResourcesAndForwardDeclarations, + capturedMethods, + entryPoint, + implicitTextureType, + isSamplerUsed, + declaredTypes.Select(static t => t.Name).ToImmutableArray(), + definedConstants.Select(static c => c.Name).ToImmutableArray(), + processedMethods.Select(static m => m.Signature).ToImmutableArray(), + delegateInstanceFields); } - // Captured methods from captured delegates - foreach (var (_, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) + /// + /// Produces the non dynamic HLSL source (concatenating all generated HLSL source chunks). + /// + /// The input instance to use. + /// The non dynamic HLSL source code. + public static string GetNonDynamicHlslSource(HlslShaderSourceInfo hlslSourceInfo) { - AppendParsedStatement($"__{fieldName}Attribute.AppendMethods(ref builder, __methodNames);"); + return + hlslSourceInfo.HeaderAndThreadsX + "" + + hlslSourceInfo.ThreadsY + "" + + hlslSourceInfo.ThreadsZ + "" + + hlslSourceInfo.Defines + + hlslSourceInfo.StaticFieldsAndDeclaredTypes + + hlslSourceInfo.CapturedFieldsAndResourcesAndForwardDeclarations + + hlslSourceInfo.CapturedMethods + + hlslSourceInfo.EntryPoint; } - - // Captured delegate methods - foreach (var (fieldSymbol, fieldName, _) in instanceFields.Where(static t => t.Symbol.Type.TypeKind == TypeKind.Delegate)) - { - AppendLF(); - AppendParsedStatement($"__{fieldName}Attribute.AppendMappedInvokeMethod(ref builder, \"{fieldName}\");"); - AppendLF(); - } - - // Entry point - AppendLF(); - AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]"); - AppendLineAndLF(executeMethod); - - FlushText(); - - // builder = global::ComputeSharp.__Internals.ArrayPoolStringBuilder.Create(); - 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))))))); - - hlslSource = aggregateTextBuilder.ToString(); - - return statements; } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs new file mode 100644 index 00000000..273bf081 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.Syntax.cs @@ -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; + +/// +public sealed partial class IShaderGenerator +{ + /// + private static partial class GetDispatchId + { + /// + /// Creates a instance for the GetDispatchId method. + /// + ///The names of all instance fields within the current shader type. + /// The resulting instance for the GetDispatchId method. + public static MethodDeclarationSyntax GetSyntax(ImmutableArray delegateFieldNames) + { + // This code produces a method declaration as follows: + // + // readonly int global::ComputeSharp.__Internals.IShader.GetDispatchId() + // { + // + // } + return + MethodDeclaration( + PredefinedType(Token(SyntaxKind.IntKeyword)), + Identifier("GetDispatchId")) + .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) + .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) + .WithBody(GetShaderHashCodeBody(delegateFieldNames)); + } + + /// + /// Gets a instance with the logic to compute the hashcode of a given shader type. + /// + /// The names of all instance fields within the current shader type. + /// The instance to hash the input shader. + [Pure] + private static BlockSyntax GetShaderHashCodeBody(ImmutableArray delegateFieldNames) + { + if (delegateFieldNames.Length == 0) + { + // return 0; + return + Block(ReturnStatement( + LiteralExpression( + SyntaxKind.NumericLiteralExpression, + Literal(0)))); + } + + List 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); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs index 1e8a3eae..65b64877 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateGetDispatchIdMethod.cs @@ -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; /// public sealed partial class IShaderGenerator { - /// - 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() - // { - // - // } - 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)); - } - /// - /// Gets a instance with the logic to compute the hashcode of a given shader type. + /// A helper with all logic to generate the GetDispatchId method. /// - /// The input instance to process. - /// Indicates whether or not the shader is dynamic (ie. captures delegates). - /// The instance to hash the input shader. - [Pure] - private static BlockSyntax GetShaderHashCodeBody(INamedTypeSymbol structDeclarationSymbol, out bool isDynamicShader) + private static partial class GetDispatchId { - var delegateFields = structDeclarationSymbol - .GetMembers() - .OfType() - .Where(static m => m.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false }) - .ToImmutableArray(); - - isDynamicShader = delegateFields.Length > 0; - - if (delegateFields.Length == 0) + /// + /// Extracts the names of all instance fields of a type. + /// + /// The input instance to process. + /// The names of all instance fields within . + [Pure] + public static ImmutableArray GetInfo(INamedTypeSymbol structDeclarationSymbol) { - // return 0; return - Block(ReturnStatement( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))); + structDeclarationSymbol + .GetMembers() + .OfType() + .Where(static member => member.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false }) + .Select(static member => member.Name) + .ToImmutableArray(); } - - List 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); } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs new file mode 100644 index 00000000..e834356d --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -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; + +/// +public sealed partial class IShaderGenerator +{ + /// + private static partial class LoadDispatchData + { + /// + /// Creates a instance for the LoadDispatchDataMethod method. + /// + /// The type of shader interface urrently being processed. + /// The array of values for all captured fields. + /// The total number of captured resources in the shader. + /// The total number of needed 32 bit constants in the shader root signature. + /// The resulting instance for the LoadDispatchDataMethod method. + public static MethodDeclarationSyntax GetSyntax( + Type shaderInterfaceType, + ImmutableArray fieldInfos, + int resourceCount, + int root32BitConstantsCount) + { + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData(ref TDataLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z) + // { + // + // } + 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))); + } + + /// + /// Gets a sequence of statements to load the dispatch data for a given shader. + /// + /// The type of shader interface urrently being processed. + /// The array of values for all captured fields. + /// The total number of captured resources in the shader. + /// The total number of needed 32 bit constants in the shader root signature. + /// The sequence of instances to load shader dispatch data. + private static ImmutableArray GetDispatchDataLoadingStatements( + Type shaderInterfaceType, + ImmutableArray fieldInfos, + int resourceCount, + int root32BitConstantsCount) + { + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + 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, ) = + // global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(, 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>( + // ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint))) = + statements.Add(ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(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 = ref global::System.Runtime.CompilerServices.Unsafe.As, >( + // ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in )); + statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(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(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m)); + // global::System.Runtime.CompilerServices.Unsafe.As(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(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(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 span0 = stackalloc uint[]; + 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( + 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 span1 = stackalloc ulong[]; + 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( + 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(); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs index a6288e93..813722bf 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs @@ -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; /// public sealed partial class IShaderGenerator { - /// - private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod( - GeneratorExecutionContext context, - INamedTypeSymbol structDeclarationSymbol, - out IReadOnlyCollection discoveredResources, - out int root32BitConstantsCount) - { - // This code produces a method declaration as follows: - // - // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData(ref TDataLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z) - // { - // - // } - 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))); - } - /// - /// Gets a sequence of statements to load the dispatch data for a given shader. + /// A helper with all logic to generate the LoadDispatchData method. /// - /// The current generator context in use. - /// The input instance to process. - /// The collection of discovered resources in the current shader type. - /// The total number of 32 bit root constants being loaded for the current shader type. - /// The sequence of instances to load shader dispatch data. - private static IEnumerable GetDispatchDataLoadingStatements(GeneratorExecutionContext context, INamedTypeSymbol structDeclarationSymbol, out IReadOnlyCollection discoveredResources, out int root32BitConstantsCount) + private static partial class LoadDispatchData { - List statements = new(); - List resources = new(); - - discoveredResources = resources; - - var pixelShaderSymbol = structDeclarationSymbol.AllInterfaces.FirstOrDefault(static interfaceSymbol => interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }); - 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) + /// + /// Explores a given type hierarchy and generates statements to load fields. + /// + /// The current shader type being explored. + /// The type of shader interface urrently being processed. + /// The total number of captured resources in the shader. + /// The total number of needed 32 bit constants in the shader root signature. + /// The resulting diagnostics from the processing operation. + /// The sequence of instances for all captured resources and values. + public static ImmutableArray GetInfo( + ITypeSymbol structDeclarationSymbol, + Type shaderInterfaceType, + out int resourceCount, + out int root32BitConstantCount, + out ImmutableArray 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 GetCapturedFieldInfos( + ITypeSymbol currentTypeSymbol, + ImmutableArray fieldPath, + StrongBox resourceOffset, + StrongBox rawDataOffset) + { + bool isFirstField = true; + + foreach ( + IFieldSymbol fieldSymbol in + from fieldSymbol in currentTypeSymbol.GetMembers().OfType() + 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.Builder builder = ImmutableArray.CreateBuilder(); + + // 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 resourceOffsetAsBox = new(); + StrongBox rawDataOffsetAsBox = new(initialRawDataOffset); + + // Traverse all shader fields and gather info, and update the tracking offsets + ImmutableArray fieldInfos = GetCapturedFieldInfos( + structDeclarationSymbol, + ImmutableArray.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(), 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) + /// + /// Gets info on a given captured HLSL primitive type (either a scalar, a vector or a matrix). + /// + /// The current path of the field with respect to the shader instance. + /// The type name currently being read. + /// The current offset within the loaded data buffer. + private static FieldInfo GetHlslKnownTypeFieldInfo( + ImmutableArray 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 span0 = stackalloc uint[]; - 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( - 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 span1 = stackalloc ulong[]; - 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( - 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; - } - - /// - /// Explores a given type hierarchy and generates statements to load fields. - /// - /// The current type being explored. - /// The current path of the field with respect to the shader instance. - /// The current offset in the root table of loaded resources. - /// The current offset within the loaded data buffer. - /// The target list of resources in the current shader type. - /// The target list of statements being generated. - private static void AppendFields(ITypeSymbol currentTypeSymbol, IReadOnlyCollection fieldPath, ref int resourceOffset, ref int rawDataOffset, ICollection resources, ICollection statements) - { - bool isFirstField = true; - - foreach ( - IFieldSymbol fieldSymbol in - from fieldSymbol in currentTypeSymbol.GetMembers().OfType() - 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.Builder builder = ImmutableArray.CreateBuilder(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); - } - } - } - - /// - /// Generates a loading statement for a known HLSL primitive type field (scalar, vector or matrix). - /// - /// The current path of the field with respect to the shader instance. - /// The type name currently being read. - /// The current offset within the loaded data buffer. - /// The target list of statements being generated. - private static void AppendHlslKnownTypeField(IEnumerable fieldPath, string typeName, ref int rawDataOffset, ICollection 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(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(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m)); - // global::System.Runtime.CompilerServices.Unsafe.As(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(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(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(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){rawDataOffset}))"), - ParseExpression($"{string.Join(".", fieldPath)}")))); - - rawDataOffset += fieldSize; } } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs new file mode 100644 index 00000000..a886d33e --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs @@ -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; + +/// +public sealed partial class IShaderGenerator +{ + /// + private static partial class LoadDispatchMetadata + { + /// + /// Creates a instance for the LoadDispatchMetadata method. + /// + /// The dispatch metadata for the current shader.. + /// The resulting instance for the LoadDispatchMetadata method. + public static MethodDeclarationSyntax GetSyntax(DispatchMetadataInfo metadataInfo) + { + // This code produces a method declaration as follows: + // + // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata(ref TMetadataLoader loader, out global::System.IntPtr result) + // { + // + // } + 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))); + } + + /// + /// Gets a sequence of statements to load the dispatch metadata for a given shader type. + /// + /// The dispatch metadata for the current shader.. + /// The sequence of instances to load shader dispatch data. + private static ImmutableArray GetDispatchMetadataLoadingStatements(DispatchMetadataInfo metadataInfo) + { + ImmutableArray.Builder statements = ImmutableArray.CreateBuilder(); + + // global::System.Span 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( + LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5))))))))))); + + // Compute the total number of resources + int totalResourcesCount = metadataInfo.ResourceDescriptors.Length; + + // Span span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[]; + 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( + 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(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {metadataInfo.Root32BitConstantCount});")); + statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(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(); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs index 391416d0..5132b5d0 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs @@ -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; /// public sealed partial class IShaderGenerator { - /// - private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod( - string? implicitTextureType, - IReadOnlyCollection discoveredResources, - int root32BitConstantsCount, - bool isSamplerUsed) - { - // This code produces a method declaration as follows: - // - // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata(ref TMetadataLoader loader, out global::System.IntPtr result) - // { - // - // } - 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))); - } - /// - /// Gets a sequence of statements to load the dispatch metadata for a given shader type. + /// A helper with all logic to generate the LoadDispatchMetadata method. /// - /// The implicit texture type, if available (if the shader is a pixel shader). - /// The collection of resources used by the shader. - /// The total number of 32 bit root constants being loaded for the shader. - /// Whether or not the shader requires a static sampler to be available. - /// The sequence of instances to load shader dispatch data. - private static IEnumerable GetDispatchMetadataLoadingStatements( - string? implicitTextureType, - IReadOnlyCollection discoveredResources, - int root32BitConstantsCount, - bool isSamplerUsed) + private static partial class LoadDispatchMetadata { - // global::System.Span 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( - 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 span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[]; - 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( - 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(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {root32BitConstantsCount});"); - yield return ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(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) + /// + /// Gets the data related to the shader metadata for a given shader type. + /// + /// The total number of needed 32 bit constants in the shader root signature. + /// Indicates whether the current shader uses an implicit texture. + /// Whether the static sampler is used by the shader. + /// The sequence of captured fields for the shader. + /// The metadata info for the shader. + public static DispatchMetadataInfo GetInfo( + int root32BitConstantCount, + bool isImplicitTextureUsed, + bool isSamplerUsed, + ImmutableArray capturedFields) { - yield return ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create(1, {readWriteResourceOffset++}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resourceOffset++}));"); - } + ImmutableArray.Builder descriptors = ImmutableArray.CreateBuilder(); + 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()) + { + 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()); + } } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.Syntax.cs new file mode 100644 index 00000000..ce084c18 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.Syntax.cs @@ -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; + +/// +public sealed partial class IShaderGenerator +{ + /// + private static partial class TryGetBytecode + { + /// + /// Creates a instance for the TryGetBytecode method. + /// + /// The input instance. + /// An opaque instance to transform the final tree into text. + /// The resulting instance for the BuildHlslString method. + public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeInfo bytecodeInfo, out Func 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 bytecode) + // { + // + // } + 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"))) + .WithBody(block); + } + + /// + /// Gets a instance with the logic to try to get a compiled shader bytecode. + /// + /// The input instance. + /// The resulting bytecode literals to insert into the final source code. + /// The instance trying to retrieve the precompiled shader. + [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 == && threadsY == && threadsZ == ) + // { + // 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(OmittedArraySizeExpression())))) + .WithInitializer( + InitializerExpression( + SyntaxKind.ArrayInitializerExpression, + SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))), + ReturnStatement(LiteralExpression(SyntaxKind.TrueLiteralExpression)))), + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("bytecode"), + LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))), + ReturnStatement(LiteralExpression(SyntaxKind.FalseLiteralExpression))); + } + + /// + /// A mapping of precomputed literals for all values. + /// + 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" + }; + + /// + /// Creates a formatted expression to initialize a with a given shader data. + /// + /// The input shader bytecode to serialize. + /// A formatted with the serialized data. + private static string BuildShaderBytecodeExpressionString(ReadOnlySpan 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(); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs index 78e78d53..47fc3948 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateTryGetBytecodeMethod.cs @@ -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 { /// - /// Indicates whether the required dxcompiler.dll and dxil.dll libraries have been loaded. + /// A helper with all logic to generate the TryGetBytecode method. /// - private static bool areDxcLibrariesLoaded; - - /// - 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 bytecode) - // { - // - // } - 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"))) - .WithBody(GetShaderBytecodeBody(context, structDeclarationSymbol, isDynamicShader, hlslSource, out bytecodeLiterals)); - } - - /// - /// Gets a instance with the logic to try to get a compiled shader bytecode. - /// - /// The current generator context in use. - /// The input instance to process. - /// Indicates whether or not the shader is dynamic (ie. captures delegates). - /// The generated HLSL source code (ignoring captured delegates, if present). - /// The resulting bytecode literals to insert into the final source code. - /// The instance to hash the input shader. - [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) + /// + /// Gets the thread ids values for a given shader type, if available. + /// + /// The input instance to process. + /// Indicates whether or not the shader is dynamic (ie. captures delegates). + /// The resulting diagnostics from the processing operation. + /// The thread ids for the precompiled shader, if available. + public static ThreadIdsInfo GetInfo( + INamedTypeSymbol structDeclarationSymbol, + bool isDynamicShader, + out ImmutableArray diagnostics) { - goto Failure; + AttributeData? attribute = structDeclarationSymbol + .GetAttributes() + .FirstOrDefault(static a => a.AttributeClass?.ToDisplayString() == typeof(EmbeddedBytecodeAttribute).FullName); + + if (attribute is null) + { + diagnostics = ImmutableArray.Empty; + + return new(true, 0, 0, 0); + } + + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + + // 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) + /// + /// Indicates whether the required dxcompiler.dll and dxil.dll libraries have been loaded. + /// + private static volatile bool areDxcLibrariesLoaded; + + /// + /// Gets a instance with the logic to try to get a compiled shader bytecode. + /// + /// The input instance to process. + /// The generated HLSL source code (ignoring captured delegates, if present). + /// The resulting diagnostic from the processing operation, if any. + /// The instance with the compiled shader bytecode. + [Pure] + public static unsafe ImmutableArray GetBytecode( + ThreadIdsInfo threadIds, + string hlslSource, + out DiagnosticInfo? diagnostic) { - context.ReportDiagnostic(EmbeddedBytecodeWithDynamicShader, structDeclarationSymbol, structDeclarationSymbol); + ImmutableArray bytecode = ImmutableArray.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.ToString()).Replace("", threadsY.ToString()).Replace("", threadsZ.ToString()); - - // Compile the shader bytecode - using ComPtr 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(buffer, length)); - - // This code produces a method declaration as follows: - // - // if (threadsX == && threadsY == && threadsZ == ) - // { - // 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(OmittedArraySizeExpression())))) - .WithInitializer( - InitializerExpression( - SyntaxKind.ArrayInitializerExpression, - SingletonSeparatedList(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))); - } - - /// - /// Extracts and loads the dxcompiler.dll and dxil.dll libraries. - /// - /// Thrown if the CPU architecture is not supported. - /// Thrown if a library fails to load. - 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("", threadIds.X.ToString()) + .Replace("", threadIds.Y.ToString()) + .Replace("", threadIds.Z.ToString()); + + // Compile the shader bytecode + using ComPtr dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(hlslSource.AsSpan()); + + byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer(); + int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize()); + + byte[] array = new ReadOnlySpan(buffer, length).ToArray(); + + bytecode = Unsafe.As>(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) + /// + /// Extracts and loads the dxcompiler.dll and dxil.dll libraries. + /// + /// Thrown if the CPU architecture is not supported. + /// Thrown if a library fails to load. + 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; - } - - /// - /// A mapping of precomputed literals for all values. - /// - 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" - }; - - /// - /// Creates a formatted expression to initialize a with a given shader data. - /// - /// The input shader bytecode to serialize. - /// A formatted with the serialized data. - private static string BuildShaderBytecodeExpressionString(ReadOnlySpan 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(); } } diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs new file mode 100644 index 00000000..fe59ff8e --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs @@ -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; + +/// +public sealed partial class IShaderGenerator +{ + /// + /// Gets the shader type for a given shader, if any. + /// + /// The input instance to check. + /// The instance for . + /// The instance for . + /// Either or , or . + [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) && + SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, iPixelShaderSymbol)) + { + return typeof(IPixelShader<>); + } + } + + return null; + } + + /// + /// Creates a instance wrapping the given method. + /// + /// The instance for the current type. + /// The item to insert. + /// Whether [SkipLocalsInit] can be used. + /// A object wrapping . + [Pure] + private static CompilationUnitSyntax GetCompilationUnitFromMethod( + HierarchyInfo hierarchyInfo, + MethodDeclarationSyntax methodDeclaration, + bool canUseSkipLocalsInit) + { + // Method attributes + List 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 + // { + // + // } + 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 ; + // + // + return + CompilationUnit().AddMembers( + FileScopedNamespaceDeclaration(IdentifierName(hierarchyInfo.Namespace)) + .AddMembers(typeDeclarationSyntax) + .WithNamespaceKeyword(Token(TriviaList( + Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), + SyntaxKind.NamespaceKeyword, + TriviaList()))) + .NormalizeWhitespace(eol: "\n"); + } +} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.SyntaxReceiver.cs deleted file mode 100644 index 1fe3c634..00000000 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.SyntaxReceiver.cs +++ /dev/null @@ -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; - -/// -public sealed partial class IShaderGenerator -{ - /// - /// An that selects candidate nodes to process. - /// - private sealed class SyntaxReceiver : ISyntaxContextReceiver - { - /// - /// The list of info gathered during exploration. - /// - private readonly List gatheredInfo = new(); - - /// - /// Gets the collection of gathered info to process. - /// - public IReadOnlyCollection GatheredInfo => this.gatheredInfo; - - /// - 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) })) - { - this.gatheredInfo.Add(new Item(structDeclaration, structSymbol)); - } - } - - /// - /// A model for a group of item representing a discovered type to process. - /// - /// The instance for the target struct declaration. - /// The instance for . - public sealed record Item(StructDeclarationSyntax StructDeclaration, INamedTypeSymbol StructSymbol); - } -} diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index cf231bf6..aabfe271 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -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 and types. /// [Generator] -public sealed partial class IShaderGenerator : ISourceGenerator +public sealed partial class IShaderGenerator : IIncrementalGenerator { /// - public void Initialize(GeneratorInitializationContext context) + public void Initialize(IncrementalGeneratorInitializationContext context) { - context.RegisterForSyntaxNotifications(static () => new SyntaxReceiver()); - } + // Check whether [SkipLocalsInit] can be used + IncrementalValueProvider canUseSkipLocalsInit = + context.CompilationProvider + .Select(static (compilation, token) => + compilation.Options is CSharpCompilationOptions { AllowUnsafe: true } && + compilation.GetTypeByMetadataName("System.Runtime.CompilerServices.SkipLocalsInitAttribute") is not null); - /// - 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 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 Dispatch, Result Hlsl, Result ThreadIds)> shaderInfoWithErrors = + shaderDeclarations + .Combine(context.CompilationProvider) + .Select(static (item, token) => { - OnExecute(context, item.StructDeclaration, item.StructSymbol); - } - catch + // LoadDispatchData() info + ImmutableArray fieldInfos = LoadDispatchData.GetInfo( + item.Left.Symbol, + item.Left.Type, + out int resourceCount, + out int root32BitConstantCount, + out ImmutableArray 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 hlslSourceDiagnostics); + + // TryGetBytecode() info + ThreadIdsInfo threadIds = TryGetBytecode.GetInfo( + item.Left.Symbol, + !hlslSourceInfo.Delegates.IsEmpty, + out ImmutableArray threadIdsDiagnostics); + + return ( + new Result(dispatchDataInfo, dispatchDataDiagnostics), + new Result(hlslSourceInfo, hlslSourceDiagnostics), + new Result(threadIds, threadIdsDiagnostics)); + }); + + // Output the diagnostics + context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.Dispatch.Errors)); + context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.Hlsl.Errors)); + context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, token) => item.ThreadIds.Errors)); + + // Filter all items to enable caching at a coarse level, and remove diagnostics + IncrementalValuesProvider<(DispatchDataInfo Dispatch, HlslShaderSourceInfo Hlsl, ThreadIdsInfo ThreadIds)> shaderInfo = + 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 = + 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.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 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> 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 fixup); + CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, tryGetBytecodeMethod, false); + string text = fixup(compilationUnit); + + context.AddSource($"{item.Hierarchy.FilenameHint}.TryGetBytecode", SourceText.From(text, Encoding.UTF8)); + }); } - - /// - /// Processes a given target type. - /// - /// The input instance to use. - /// The node to process. - /// The for . - 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 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 struct ShaderType - // { - // - // } - 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 = parentType - .WithMembers(SingletonList(typeDeclarationSyntax)) - .WithConstraintClauses(List()) - .WithBaseList(null) - .WithAttributeLists(List()) - .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 ; - // - // - 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)); - } - - /// - /// Creates a instance for the GetDispatchId method. - /// - /// The for the input struct declaration. - /// Indicates whether or not the shader is dynamic (ie. captures delegates). - /// The resulting instance for the GetDispatchId method. - private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol, out bool isDynamicShader); - - /// - /// Creates a instance for the LoadDispatchDataMethod method. - /// - /// The input instance to use. - /// The for the input struct declaration. - /// The collection of discovered resources in the current shader type. - /// The total number of 32 bit root constants being loaded for the current shader type. - /// The resulting instance for the LoadDispatchDataMethod method. - private static partial MethodDeclarationSyntax CreateLoadDispatchDataMethod( - GeneratorExecutionContext context, - INamedTypeSymbol structDeclarationSymbol, - out IReadOnlyCollection discoveredResources, - out int root32BitConstantsCount); - - /// - /// Creates a instance for the BuildHlslString method. - /// - /// The input instance to use. - /// The node to process. - /// The for . - /// The implicit texture type, if available (if the shader is a pixel shader). - /// Whether or not the current shader type requires a static sampler to be available. - /// The generated HLSL source code (ignoring captured delegates, if present). - /// The resulting instance for the BuildHlslString method. - private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod( - GeneratorExecutionContext context, - StructDeclarationSyntax structDeclaration, - INamedTypeSymbol structDeclarationSymbol, - out string? implicitTextureType, - out bool isSamplerUsed, - out string hlslSource); - - /// - /// Creates a instance for the LoadDispatchMetadata method. - /// - /// The implicit texture type, if available (if the shader is a pixel shader). - /// The collection of resources used by the shader. - /// The total number of 32 bit root constants being loaded for the shader. - /// Whether or not the shader requires a static sampler to be available. - /// The resulting instance for the LoadDispatchMetadata method. - private static partial MethodDeclarationSyntax CreateLoadDispatchMetadataMethod( - string? implicitTextureType, - IReadOnlyCollection discoveredResources, - int root32BitConstantsCount, - bool isSamplerUsed); - - /// - /// Creates a instance for the TryGetBytecode method. - /// - /// The input instance to use. - /// The for the shader type. - /// Indicates whether or not the shader is dynamic (ie. captures delegates). - /// The generated HLSL source code (ignoring captured delegates, if present). - /// The resulting bytecode literals to insert into the final source code. - /// The resulting instance for the BuildHlslString method. - private static partial MethodDeclarationSyntax CreateTryGetBytecodeMethod( - GeneratorExecutionContext context, - INamedTypeSymbol structDeclarationSymbol, - bool isDynamicShader, - string hlslSource, - out string? bytecodeLiterals); } diff --git a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs index 25b7ae9d..2b92ca6e 100644 --- a/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.SourceGenerators/Mappings/HlslKnownTypes.cs @@ -149,6 +149,26 @@ internal static class HlslKnownTypes }; } + /// + /// Checks whether or not a given type name matches a writeable typed resource type. + /// + /// The input type name to check. + /// Whether or not represents a writeable typed resource type. + 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, + }; + } + /// /// Checks whether or not a given type name matches a typed resource type. /// diff --git a/src/ComputeSharp.SourceGenerators/Models/DiagnosticInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DiagnosticInfo.cs new file mode 100644 index 00000000..e3711b93 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/DiagnosticInfo.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using ComputeSharp.SourceGenerators.Extensions; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model for a serializeable diagnostic provider. +/// +/// The wrapped instance. +/// The diagnostic args. +internal sealed record DiagnosticInfo(DiagnosticDescriptor Descriptor, params object[] Args) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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); + } + + /// + public int GetHashCode(DiagnosticInfo obj) + { + HashCode hashCode = default; + + hashCode.Add(obj.Descriptor); + + foreach (object arg in obj.Args) + { + hashCode.Add(arg); + } + + return hashCode.ToHashCode(); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs new file mode 100644 index 00000000..b1462dad --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGenerators.Extensions; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model representing gathered info on a shader dispatch data. +/// +/// The hierarchy data for the shader. +/// The shader interface type. +/// The description on shader instance fields. +/// The total number of captured resources. +/// The size of the shader root signature, in 32 bit constants. +internal sealed record DispatchDataInfo( + HierarchyInfo Hierarchy, + Type Type, + ImmutableArray FieldInfos, + int ResourceCount, + int Root32BitConstantCount) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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; + } + + /// + 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(); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs new file mode 100644 index 00000000..373eb800 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/DispatchIdInfo.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGenerators.Extensions; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model representing gathered info on a shader dispatch id. +/// +/// The list of delegate field names for the shader. +internal sealed record DispatchIdInfo(ImmutableArray Delegates) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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); + } + + /// + public int GetHashCode(DispatchIdInfo obj) + { + HashCode hashCode = default; + + hashCode.AddRange(obj.Delegates); + + return hashCode.ToHashCode(); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/Models/DispatchMetadataInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DispatchMetadataInfo.cs new file mode 100644 index 00000000..cbf3bc4f --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/DispatchMetadataInfo.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGenerators.Extensions; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model containing info on shader dispatch metadata. +/// +/// The size of the shader root signature, in 32 bit constants. +/// Whether or not the static sampler is used. +/// The sequence of resource descriptors for the shader. +internal sealed record DispatchMetadataInfo( + int Root32BitConstantCount, + bool IsSamplerUsed, + ImmutableArray ResourceDescriptors) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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); + } + + /// + 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(); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Models/EmbeddedBytecodeInfo.cs b/src/ComputeSharp.SourceGenerators/Models/EmbeddedBytecodeInfo.cs new file mode 100644 index 00000000..df208415 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/EmbeddedBytecodeInfo.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGenerators.Extensions; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model representing a compiled shader bytecode, or none. +/// +/// The thread ids value for the X axis. +/// The thread ids value for the Y axis. +/// The thread ids value for the Z axis. +/// The compiled shader bytecode, if available. +internal sealed record EmbeddedBytecodeInfo(int X, int Y, int Z, ImmutableArray Bytecode) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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); + } + + /// + 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(); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs b/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs new file mode 100644 index 00000000..25f7a5d7 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/FieldInfo.cs @@ -0,0 +1,137 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGenerators.Extensions; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A base type for a model describing a given captured field in a shader. +/// +internal abstract record FieldInfo +{ + /// + /// A captured resource (either a buffer or a texture). + /// + /// The name of the resource field. + /// The full metadata name for the resource type. + /// The offset for the resource within the root signature. + public sealed record Resource(string FieldName, string TypeName, int Offset) : FieldInfo; + + /// + /// A captured primitive value (either a scalar, a vector, or a linear matrix). + /// + /// The path of the field with respect to the shader instance. + /// The full metadata name for the primitive type. + /// The byte offset of the value within the root signature. + public sealed record Primitive(ImmutableArray FieldPath, string TypeName, int Offset) : FieldInfo; + + /// + /// A captured non linear matrix value. + /// + /// The path of the field with respect to the shader instance. + /// The full metadata name for the matrix type. + /// The name of each element in the matrix type. + /// The number of rows in the matrix. + /// The number of columns in the matrix. + /// The sequence of byte offsets for each row within the root signature. + public sealed record NonLinearMatrix( + ImmutableArray FieldPath, + string TypeName, + string ElementName, + int Rows, + int Columns, + ImmutableArray Offsets) : FieldInfo; + + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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; + } + + /// + 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; + } + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs new file mode 100644 index 00000000..10039dac --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/HierarchyInfo.cs @@ -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; + +/// +/// A model describing the hierarchy info for a specific type. +/// +/// The filename hint for the current type. +/// The metadata name for the current type. +/// Gets the namespace for the current type. +/// Gets the sequence of type definitions containing the current type. +internal sealed record HierarchyInfo(string FilenameHint, string MetadataName, string Namespace, ImmutableArray Names) +{ + /// + /// Creates a new instance from a given . + /// + /// The input instance to gather info for. + /// A instance describing . + [Pure] + public static HierarchyInfo From(INamedTypeSymbol typeSymbol) + { + ImmutableArray.Builder names = ImmutableArray.CreateBuilder(); + + 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()); + } + + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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); + } + + /// + public int GetHashCode(HierarchyInfo obj) + { + return HashCode.Combine(obj.Namespace, obj.MetadataName, obj.Names, obj.Names[0]); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs new file mode 100644 index 00000000..40788938 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/HlslMethodSourceInfo.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGenerators.Extensions; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model for extracted info on a processed HLSL method. +/// +/// The metadata name for the method. +/// The meethod entry point. +/// The discovered declared types. +/// The discovered defined constants. +/// The dependent captured methods. +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) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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); + } + + /// + 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(); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs new file mode 100644 index 00000000..82067efa --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using ComputeSharp.SourceGenerators.Extensions; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model for extracted info on a processed HLSL shader. +/// +/// The shader generated header and threadsX count declaration. +/// The threadsY count declaration. +/// The threadsZ count declaration. +/// The define statements, if any. +/// The static fields and declared types, if any. +/// The captured fields, and method forward declarations. +/// The captured method implementations. +/// The shader entry point. +/// The type of the implicit texture type, if any. +/// Whether or not the static sampler is used. +/// The names of declared types. +/// The names of defined constants. +/// The signatures for captured methods. +/// The list of delegate fields. +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 DefinedTypes, + ImmutableArray DefinedConstants, + ImmutableArray MethodSignatures, + ImmutableArray Delegates) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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); + } + + /// + 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(); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/Models/ParameterInfo.cs b/src/ComputeSharp.SourceGenerators/Models/ParameterInfo.cs new file mode 100644 index 00000000..137df444 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/ParameterInfo.cs @@ -0,0 +1,8 @@ +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model describing info on a constructor parameter. +/// +/// The fully qualified type name. +/// The parameter name. +internal sealed record ParameterInfo(string Type, string Name); diff --git a/src/ComputeSharp.SourceGenerators/Models/ResourceDescriptor.cs b/src/ComputeSharp.SourceGenerators/Models/ResourceDescriptor.cs new file mode 100644 index 00000000..bb5070c4 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/ResourceDescriptor.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A resource descriptor for a captured resource in a shader. +/// +/// The type id for the resource. +/// The offset of the resource in its containing register. +/// The offset of the resource descriptor in the shader root signature. +internal sealed record ResourceDescriptor(int TypeId, int RegisterOffset, int Offset) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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; + } + + /// + public int GetHashCode(ResourceDescriptor obj) + { + return HashCode.Combine(obj.TypeId, obj.RegisterOffset, obj.Offset); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/Models/Result{T}.cs b/src/ComputeSharp.SourceGenerators/Models/Result{T}.cs new file mode 100644 index 00000000..4bee6af9 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/Result{T}.cs @@ -0,0 +1,12 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model representing a value and an associated set of diagnostic errors. +/// +/// The type of the wrapped value. +/// The wrapped value for the current result. +/// The associated diagnostic errors, if any. +internal sealed record Result(TValue Value, ImmutableArray Errors); diff --git a/src/ComputeSharp.SourceGenerators/Models/ThreadIdsInfo.cs b/src/ComputeSharp.SourceGenerators/Models/ThreadIdsInfo.cs new file mode 100644 index 00000000..dfcd72b8 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/ThreadIdsInfo.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model representing gathered info on a embedded thread ids. +/// +/// Whether the values are diascarded. +/// The thread ids value for the X axis. +/// The thread ids value for the Y axis. +/// The thread ids value for the Z axis. +internal sealed record ThreadIdsInfo(bool IsDefault, int X, int Y, int Z) +{ + /// + /// An implementation for . + /// + public sealed class Comparer : IEqualityComparer + { + /// + /// The singleton instance. + /// + public static Comparer Default { get; } = new(); + + /// + 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; + } + + /// + public int GetHashCode(ThreadIdsInfo obj) + { + return HashCode.Combine(obj.IsDefault, obj.X, obj.Y, obj.Z); + } + } +} diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.SyntaxReceiver.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.SyntaxReceiver.cs deleted file mode 100644 index 8349eb3f..00000000 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.SyntaxReceiver.cs +++ /dev/null @@ -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; - -/// -public sealed partial class ShaderMethodSourceGenerator -{ - /// - /// An that selects candidate nodes to process. - /// - private sealed class SyntaxReceiver : ISyntaxContextReceiver - { - /// - /// The list of info gathered during exploration. - /// - private readonly List gatheredInfo = new(); - - /// - /// Gets the collection of gathered info to process. - /// - public IReadOnlyCollection GatheredInfo => this.gatheredInfo; - - /// - 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)); - } - } - - /// - /// A model for a group of item representing a discovered method to process. - /// - /// The instance for the target method declaration. - /// The instance for . - public sealed record Item(MethodDeclarationSyntax MethodDeclaration, IMethodSymbol MethodSymbol); - } -} diff --git a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs index cfabb6a4..ad462f9a 100644 --- a/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ShaderMethodSourceGenerator.cs @@ -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; /// /// A source generator for processing static methods referenced from compute shaders. /// -[Generator] -public sealed partial class ShaderMethodSourceGenerator : ISourceGenerator +[Generator(LanguageNames.CSharp)] +public sealed partial class ShaderMethodSourceGenerator : IIncrementalGenerator { /// - 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))!; - /// - 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> 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 diagnostics); + + return new Result(sourceInfo, diagnostics); + }); + + // Output the diagnostics + context.ReportDiagnostics(methodSourceInfoWithErrors.Select(static (item, token) => item.Errors)); + + // Get the filtered sequence to enable caching + IncrementalValuesProvider 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)); + }); } /// - /// Processes a given target method. + /// A helper with all logic to generate the attribute declarations. /// - /// The input instance to use. - /// The node to process. - /// The with metadata on the types being processed. - /// The for . - 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 discoveredTypes = new(SymbolEqualityComparer.Default); - Dictionary 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)); - } - - /// - /// Gets a sequence of processed methods from a target method declaration. - /// - /// The current generator context in use. - /// The instance for the current method. - /// The instance for the method to process. - /// The collection of currently discovered types. - /// The collection of discovered constant definitions. - /// A sequence of processed methods in (main method and all captured methods). - [Pure] - private static (string TargetMethod, IEnumerable<(string Signature, string Definition)> ProcessedMethods) GetProcessedMethods( - GeneratorExecutionContext context, - MethodDeclarationSyntax methodDeclaration, - SemanticModelProvider semanticModel, - ICollection discoveredTypes, - IDictionary constantDefinitions) - { - Dictionary 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) + /// + /// Processes a given target method. + /// + /// The input object currently in use. + /// The node to process. + /// The instance for the current method. + /// The resulting diagnostics from the processing operation. + public static HlslMethodSourceInfo GetData( + Compilation compilation, + MethodDeclarationSyntax methodDeclaration, + IMethodSymbol methodSymbol, + out ImmutableArray 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 discoveredTypes = new(SymbolEqualityComparer.Default); + Dictionary 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) + /// + /// Gets a sequence of processed methods from a target method declaration. + /// + /// The instance for the current method. + /// The instance for the method to process. + /// The collection of currently discovered types. + /// The collection of discovered constant definitions. + /// The resulting diagnostics from the processing operation. + /// A sequence of processed methods in (main method and all captured methods). + [Pure] + private static (string TargetMethod, ImmutableArray<(string Signature, string Definition)> DependentMethods) GetProcessedMethods( + MethodDeclarationSyntax methodDeclaration, + SemanticModelProvider semanticModel, + ICollection discoveredTypes, + IDictionary constantDefinitions, + out ImmutableArray diagnostics) { - processedMethods.Add(( - staticMethod.AsDefinition().NormalizeWhitespace(eol: "\n").ToFullString(), - staticMethod.NormalizeWhitespace(eol: "\n").ToFullString())); + Dictionary staticMethods = new(SymbolEqualityComparer.Default); + ImmutableArray.Builder builder = ImmutableArray.CreateBuilder(); + + 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); + /// + /// Creates a instance with the processed attribute. + /// + /// The input instance to use. + 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"); + } } } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs index ea074239..ca805ce7 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.Diagnostics.cs @@ -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 /// 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 /// 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 /// 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 /// 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 /// 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 /// 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 /// 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 /// 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 /// 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 /// 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 /// 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 /// 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 /// 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 /// 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 /// 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 /// 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 /// 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 /// 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 /// 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 /// 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 /// 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 /// 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 /// public override SyntaxNode? VisitUnsafeStatement(UnsafeStatementSyntax node) { - Context.ReportDiagnostic(UnsafeStatement, node); + Diagnostics.Add(UnsafeStatement, node); return base.VisitUnsafeStatement(node); } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs index 607f53b9..59ab4edf 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/HlslSourceRewriter.cs @@ -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 ConstantDefinitions; /// - /// The current generator context in use. + /// The collection of produced instances. /// - protected readonly GeneratorExecutionContext Context; + protected readonly ImmutableArray.Builder Diagnostics; /// /// Creates a new instance with the specified parameters. @@ -47,17 +48,17 @@ internal abstract partial class HlslSourceRewriter : CSharpSyntaxRewriter /// The instance for the target syntax tree. /// The set of discovered custom types. /// The collection of discovered constant definitions. - /// The current generator context in use. + /// The collection of produced instances. protected HlslSourceRewriter( SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary constantDefinitions, - GeneratorExecutionContext context) + ImmutableArray.Builder diagnostics) { SemanticModel = semanticModel; DiscoveredTypes = discoveredTypes; ConstantDefinitions = constantDefinitions; - Context = context; + Diagnostics = diagnostics; } /// @@ -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; } diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs index 0b45396c..0cf712f9 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/ShaderSourceRewriter.cs @@ -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 /// The set of discovered custom types. /// The set of discovered and processed static methods. /// The collection of discovered constant definitions. - /// The current generator context in use. + /// The collection of produced instances. /// Whether or not the current instance is processing a shader entry point. public ShaderSourceRewriter( INamedTypeSymbol shaderType, @@ -71,9 +72,9 @@ internal sealed class ShaderSourceRewriter : HlslSourceRewriter ICollection discoveredTypes, IDictionary staticMethods, IDictionary constantDefinitions, - GeneratorExecutionContext context, + ImmutableArray.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 /// The set of discovered custom types. /// The set of discovered and processed static methods. /// The collection of discovered constant definitions. - /// The current generator context in use. + /// The collection of produced instances. public ShaderSourceRewriter( SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary staticMethods, IDictionary constantDefinitions, - GeneratorExecutionContext context) - : base(semanticModel, discoveredTypes, constantDefinitions, context) + ImmutableArray.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(); diff --git a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs index f80d5e49..b724fc9d 100644 --- a/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs +++ b/src/ComputeSharp.SourceGenerators/SyntaxRewriters/StaticFieldRewriter.cs @@ -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 /// The instance for the target syntax tree. /// The set of discovered custom types. /// The collection of discovered constant definitions. - /// The current generator context in use. + /// The collection of produced instances. public StaticFieldRewriter( SemanticModelProvider semanticModel, ICollection discoveredTypes, IDictionary constantDefinitions, - GeneratorExecutionContext context) - : base(semanticModel, discoveredTypes, constantDefinitions, context) + ImmutableArray.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); } } diff --git a/tests/ComputeSharp.Tests.SourceGenerators/AutoConstructorGeneratorTests.cs b/tests/ComputeSharp.Tests.SourceGenerators/AutoConstructorGeneratorTests.cs index ca2cc0af..db4eb6c6 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/AutoConstructorGeneratorTests.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/AutoConstructorGeneratorTests.cs @@ -27,7 +27,7 @@ public class AutoConstructorGeneratorTests namespace MyFancyApp.Sample { - public partial interface IFoo : IFluff + public partial class IFoo : 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 - { - public partial class Foo - { - public readonly partial struct Test - { + partial class IFoo + {{ + 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 c, global::ComputeSharp.ReadWriteBuffer d) - { + {{ this.a = a; this.b = b; this.c = c; this.d = d; - } - } - } - }"; + }} + }} + }} + }}"; VerifyGeneratedMethodLines(source, 0, expected); } @@ -75,7 +78,7 @@ public class AutoConstructorGeneratorTests /// The target index to check in the resulting output. /// The expected body to compare with the generated code. private static void VerifyGeneratedMethodLines(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); diff --git a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs index 0092a1ae..4cb19f28 100644 --- a/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs +++ b/tests/ComputeSharp.Tests.SourceGenerators/DiagnosticsTests.cs @@ -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(source, "CMPS0042"); + VerifyGeneratedDiagnostics(source, "CMPS0037"); } [TestMethod] @@ -1222,7 +1222,7 @@ public class DiagnosticsTests } }"; - VerifyGeneratedDiagnostics(source, "CMPS0043"); + VerifyGeneratedDiagnostics(source, "CMPS0038"); } [TestMethod] @@ -1250,7 +1250,7 @@ public class DiagnosticsTests } }"; - VerifyGeneratedDiagnostics(source, "CMPS0045"); + VerifyGeneratedDiagnostics(source, "CMPS0040"); } [TestMethod] @@ -1281,7 +1281,7 @@ public class DiagnosticsTests } }"; - VerifyGeneratedDiagnostics(source, "CMPS0045"); + VerifyGeneratedDiagnostics(source, "CMPS0040"); } [TestMethod] @@ -1309,7 +1309,7 @@ public class DiagnosticsTests } }"; - VerifyGeneratedDiagnostics(source, "CMPS0045"); + VerifyGeneratedDiagnostics(source, "CMPS0040"); } [TestMethod] @@ -1337,7 +1337,7 @@ public class DiagnosticsTests } }"; - VerifyGeneratedDiagnostics(source, "CMPS0045"); + VerifyGeneratedDiagnostics(source, "CMPS0040"); } [TestMethod] @@ -1371,7 +1371,7 @@ public class DiagnosticsTests } }"; - VerifyGeneratedDiagnostics(source, "CMPS0046"); + VerifyGeneratedDiagnostics(source, "CMPS0041"); } [TestMethod] @@ -1396,7 +1396,7 @@ public class DiagnosticsTests } }"; - VerifyGeneratedDiagnostics(source, "CMPS0047"); + VerifyGeneratedDiagnostics(source, "CMPS0042"); } [TestMethod] @@ -1410,12 +1410,15 @@ public class DiagnosticsTests { public interface IComputeShader { } public class ReadWriteBuffer { } - 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 buffer; @@ -1427,7 +1430,7 @@ public class DiagnosticsTests } }"; - VerifyGeneratedDiagnostics(source, "CMPS0048"); + VerifyGeneratedDiagnostics(source, "CMPS0043"); } [TestMethod] @@ -1466,7 +1469,7 @@ public class DiagnosticsTests }} }}"; - VerifyGeneratedDiagnostics(source, "CMPS0049"); + VerifyGeneratedDiagnostics(source, "CMPS0044"); } /// @@ -1476,7 +1479,7 @@ public class DiagnosticsTests /// The input source to process. /// The expected diagnostics ids to be generated. private static void VerifyGeneratedDiagnostics(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); diff --git a/tests/ComputeSharp.Tests/DispatchTests.cs b/tests/ComputeSharp.Tests/DispatchTests.cs index df57f287..b4078328 100644 --- a/tests/ComputeSharp.Tests/DispatchTests.cs +++ b/tests/ComputeSharp.Tests/DispatchTests.cs @@ -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 buffer = device.Get().AllocateReadWriteBuffer(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 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 buffer = device.Get().AllocateReadWriteBuffer(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 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]; + } + } + } }