From 9815b8532c8ffbabf094c3e10cc3c3bb0e9a0ab1 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 21 Oct 2023 16:15:50 +0200 Subject: [PATCH 1/6] Generate GraphicsResourcesLoader type to load resources --- ...DescriptorGenerator.HlslBytecode.Syntax.cs | 4 +- ...iptorGenerator.InputDescriptions.Syntax.cs | 4 +- ...erDescriptorGenerator.InputTypes.Syntax.cs | 4 +- .../D2DPixelShaderDescriptorGenerator.cs | 6 +- ...onstantBufferSyntaxProcessor.Generation.cs | 2 +- ...DescriptorGenerator.HlslBytecode.Syntax.cs | 4 +- ...puteShaderDescriptorGenerator.Resources.cs | 105 +++++++++++++++++- .../ComputeShaderDescriptorGenerator.cs | 3 +- .../Models/ResourceInfo.cs | 3 +- 9 files changed, 116 insertions(+), 19 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.Syntax.cs index 836ddd60..4cda30e7 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.Syntax.cs @@ -69,12 +69,12 @@ partial class D2DPixelShaderDescriptorGenerator } /// - /// Registers a callback to generate an additional type, if needed. + /// Registers a callback to generate additional types, if needed. /// /// The input instance with gathered shader info. /// The registered callbacks to generate additional types. /// The using directives needed by the generated code. - public static void RegisterAdditionalTypeSyntax( + public static void RegisterAdditionalTypesSyntax( D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks, ImmutableHashSetBuilder usingDirectives) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputDescriptions.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputDescriptions.Syntax.cs index ca098146..6b581f35 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputDescriptions.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputDescriptions.Syntax.cs @@ -36,12 +36,12 @@ partial class D2DPixelShaderDescriptorGenerator } /// - /// Registers a callback to generate an additional type, if needed. + /// Registers a callback to generate additional types, if needed. /// /// The input instance with gathered shader info. /// The registered callbacks to generate additional types. /// The using directives needed by the generated code. - public static void RegisterAdditionalTypeSyntax( + public static void RegisterAdditionalTypesSyntax( D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks, ImmutableHashSetBuilder usingDirectives) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputTypes.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputTypes.Syntax.cs index 5ed34b34..07944b28 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputTypes.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.InputTypes.Syntax.cs @@ -34,12 +34,12 @@ partial class D2DPixelShaderDescriptorGenerator } /// - /// Registers a callback to generate an additional type, if needed. + /// Registers a callback to generate additional types, if needed. /// /// The input instance with gathered shader info. /// The registered callbacks to generate additional types. /// The using directives needed by the generated code. - public static void RegisterAdditionalTypeSyntax( + public static void RegisterAdditionalTypesSyntax( D2D1ShaderInfo info, ImmutableArrayBuilder> callbacks, ImmutableHashSetBuilder usingDirectives) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs index 5322c88c..8eddfaaa 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs @@ -236,9 +236,9 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene using ImmutableHashSetBuilder usingDirectives = new(); ConstantBufferSyntaxProcessor.RegisterAdditionalTypesSyntax(GeneratorName, BindingDirection.TwoWay, item, additionalTypes, usingDirectives); - InputDescriptions.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives); - InputTypes.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives); - HlslBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives); + InputDescriptions.RegisterAdditionalTypesSyntax(item, additionalTypes, usingDirectives); + InputTypes.RegisterAdditionalTypesSyntax(item, additionalTypes, usingDirectives); + HlslBytecode.RegisterAdditionalTypesSyntax(item, additionalTypes, usingDirectives); using IndentedTextWriter writer = new(); diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/ConstantBufferSyntaxProcessor.Generation.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/ConstantBufferSyntaxProcessor.Generation.cs index f251d0c9..707826ca 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/ConstantBufferSyntaxProcessor.Generation.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/ConstantBufferSyntaxProcessor.Generation.cs @@ -119,7 +119,7 @@ partial class ConstantBufferSyntaxProcessor string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName(); writer.WriteLine($"""/// """); - writer.WriteLine($"""/// A type containing marshalling logic for shaders of type ."""); + writer.WriteLine($"""/// A type containing marshalling logic for the constant buffer in shaders of type ."""); writer.WriteLine($"""/// """); writer.WriteGeneratedAttributes(ConstantBufferSyntaxProcessor.generatorName!, useFullyQualifiedTypeNames: false); writer.WriteLine($"""file static class ConstantBufferMarshaller"""); diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.Syntax.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.Syntax.cs index a081e890..03a39a11 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.Syntax.cs @@ -34,12 +34,12 @@ partial class ComputeShaderDescriptorGenerator } /// - /// Registers a callback to generate an additional type, if needed. + /// Registers a callback to generate additional types, if needed. /// /// The input instance with gathered shader info. /// The registered callbacks to generate additional types. /// The using directives needed by the generated code. - public static void RegisterAdditionalTypeSyntax( + public static void RegisterAdditionalTypesSyntax( ShaderInfo info, ImmutableArrayBuilder> callbacks, ImmutableHashSetBuilder usingDirectives) diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs index 065b7544..e475aa08 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs @@ -4,6 +4,7 @@ using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGeneration.Models; +using ComputeSharp.SourceGeneration.SyntaxProcessors; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; @@ -49,13 +50,18 @@ partial class ComputeShaderDescriptorGenerator continue; } - string fieldName = fieldSymbol.Name; + // Try to get the name to use for the field and the accessor + if (!ConstantBufferSyntaxProcessor.TryGetFieldAccessorName(fieldSymbol, out string? fieldName, out string? unspeakableName)) + { + continue; + } + string typeName = fieldSymbol.Type.GetFullyQualifiedMetadataName(); // Check if the field is a resource (note: resources can only be top level fields) if (HlslKnownTypes.IsTypedResourceType(typeName)) { - resourceBuilder.Add(new ResourceInfo(fieldName, typeName)); + resourceBuilder.Add(new ResourceInfo(fieldName, unspeakableName, typeName)); } } @@ -90,12 +96,101 @@ partial class ComputeShaderDescriptorGenerator using (writer.WriteBlock()) { - // Generate loading statements for each captured resource - for (int i = 0; i < info.Resources.Length; i++) + // Nothing to do if there are no resources + if (info.Resources.IsEmpty) { - writer.WriteLine($"loader.LoadGraphicsResource(shader.{info.Resources[i].FieldName}, {i});"); + return; + } + + // Delegate to the generated loader type + writer.WriteLine("global::ComputeSharp.Generated.GraphicsResourcesLoader.LoadGraphicsResources(in shader, ref loader);"); + } + } + + /// + /// Registers a callback to generate additional types, if needed. + /// + /// The input instance with gathered shader info. + /// The registered callbacks to generate additional types. + /// The using directives needed by the generated code. + public static void RegisterAdditionalTypesSyntax( + ShaderInfo info, + ImmutableArrayBuilder> callbacks, + ImmutableHashSetBuilder usingDirectives) + { + // If there are no resources, there's no need for any additional types + if (info.Resources.IsEmpty) + { + return; + } + + _ = usingDirectives.Add("global::System.CodeDom.Compiler"); + _ = usingDirectives.Add("global::System.Diagnostics"); + _ = usingDirectives.Add("global::System.Diagnostics.CodeAnalysis"); + _ = usingDirectives.Add("global::System.Runtime.CompilerServices"); + _ = usingDirectives.Add("global::ComputeSharp.Descriptors"); + + // Declare the GraphicsResourcesLoader type + static void Callback(ShaderInfo info, IndentedTextWriter writer) + { + string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName(); + + writer.WriteLine($"""/// """); + writer.WriteLine($"""/// A type containing loading logic for graphics resources in shaders of type ."""); + writer.WriteLine($"""/// """); + writer.WriteGeneratedAttributes(GeneratorName, useFullyQualifiedTypeNames: false); + writer.WriteLine($"""file static class GraphicsResourcesLoader"""); + + using (writer.WriteBlock()) + { + // Define the FromManaged method (managed shader type to native constant buffer) + writer.WriteLine($$"""/// """); + writer.WriteLine($"""[MethodImpl(MethodImplOptions.AggressiveInlining)]"""); + writer.WriteLine($"""[SkipLocalsInit]"""); + writer.WriteLine($"public static void LoadGraphicsResources(in {fullyQualifiedTypeName} shader, ref TLoader loader)"); + writer.WriteLine(" where TLoader : struct, IGraphicsResourceLoader"); + + using (writer.WriteBlock()) + { + // Generate loading statements for each captured resource. + // Each loading statement will invoke the generated accessor. + for (int i = 0; i < info.Resources.Length; i++) + { + writer.WriteLine($"loader.LoadGraphicsResource(shader.{info.Resources[i].FieldName}(), {i});"); + } + } + + // Define all field accessors (always used, just like for constant buffer fields, see remarks there) + foreach (ResourceInfo resourceInfo in info.Resources) + { + writer.WriteLine(); + + // Generate the correct field accessor depending on whether the field can be referenced directly + if (resourceInfo.UnspeakableName is null) + { + writer.WriteLine($""" + /// + /// The input value. + /// A reference to . + [UnsafeAccessor(UnsafeAccessorKind.Field)] + private static extern ref readonly IGraphicsResource {resourceInfo.FieldName}(this ref readonly {fullyQualifiedTypeName} value); + """, isMultiline: true); + } + else + { + writer.WriteLine($""" + /// Gets a reference to the unspeakable field "{resourceInfo.FieldName}" of type . + /// The input value. + /// A reference to the unspeakable field "{resourceInfo.FieldName}". + [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "{resourceInfo.UnspeakableName}")] + private static extern ref readonly IGraphicsResource {resourceInfo.FieldName}(this ref readonly {fullyQualifiedTypeName} value); + """, isMultiline: true); + } + } } } + + callbacks.Add(Callback); } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs index 37da4b50..0483a1dc 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs @@ -174,8 +174,9 @@ public sealed partial class ComputeShaderDescriptorGenerator : IIncrementalGener using ImmutableHashSetBuilder usingDirectives = new(); ConstantBufferSyntaxProcessor.RegisterAdditionalTypesSyntax(GeneratorName, BindingDirection.OneWay, item, additionalTypes, usingDirectives); + Resources.RegisterAdditionalTypesSyntax(item, additionalTypes, usingDirectives); ResourceDescriptorRanges.RegisterAdditionalDataMemberSyntax(item, additionalTypes, usingDirectives); - HlslBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives); + HlslBytecode.RegisterAdditionalTypesSyntax(item, additionalTypes, usingDirectives); using IndentedTextWriter writer = new(); diff --git a/src/ComputeSharp.SourceGenerators/Models/ResourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/ResourceInfo.cs index dab66a81..2e738721 100644 --- a/src/ComputeSharp.SourceGenerators/Models/ResourceInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/ResourceInfo.cs @@ -4,5 +4,6 @@ namespace ComputeSharp.SourceGenerators.Models; /// A model describing a captured resource (either a buffer or a texture). /// /// The name of the resource field. +/// The unspeakable name of the field, if present. /// The full metadata name for the resource type. -public sealed record ResourceInfo(string FieldName, string TypeName); \ No newline at end of file +public sealed record ResourceInfo(string FieldName, string? UnspeakableName, string TypeName); \ No newline at end of file From e254cc19f3926d225bb5b7112db3e927f43d4436 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 21 Oct 2023 16:23:53 +0200 Subject: [PATCH 2/6] Remove unnecessary parameter --- ...ComputeShaderDescriptorGenerator.ResourceDescriptorRanges.cs | 2 -- .../ComputeShaderDescriptorGenerator.cs | 1 - 2 files changed, 3 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.ResourceDescriptorRanges.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.ResourceDescriptorRanges.cs index ab12214b..bfe91e80 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.ResourceDescriptorRanges.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.ResourceDescriptorRanges.cs @@ -17,12 +17,10 @@ partial class ComputeShaderDescriptorGenerator /// Gets the data related to the shader metadata for a given shader type. /// /// Indicates whether the current shader uses an implicit texture. - /// Whether the static sampler is used by the shader. /// The sequence of captured resources for the shader. /// The metadata info for the shader. public static ImmutableArray GetInfo( bool isImplicitTextureUsed, - bool isSamplerUsed, ImmutableArray resources) { using ImmutableArrayBuilder descriptors = new(); diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs index 0483a1dc..c75a2732 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs @@ -108,7 +108,6 @@ public sealed partial class ComputeShaderDescriptorGenerator : IIncrementalGener // Resource descriptor ranges info ImmutableArray resourceDescriptors = ResourceDescriptorRanges.GetInfo( isImplicitTextureUsed, - isSamplerUsed, resourceInfo); token.ThrowIfCancellationRequested(); From 1760c8d3ff9ed46e0ff0f642225a766b758d059e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 21 Oct 2023 16:25:08 +0200 Subject: [PATCH 3/6] Split Resources syntax generation code into partial file --- ...derDescriptorGenerator.Resources.Syntax.cs | 125 ++++++++++++++++++ ...puteShaderDescriptorGenerator.Resources.cs | 114 +--------------- 2 files changed, 126 insertions(+), 113 deletions(-) create mode 100644 src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.Syntax.cs diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.Syntax.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.Syntax.cs new file mode 100644 index 00000000..ab9df011 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.Syntax.cs @@ -0,0 +1,125 @@ +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGenerators.Models; + +namespace ComputeSharp.SourceGenerators; + +/// +partial class ComputeShaderDescriptorGenerator +{ + /// + partial class Resources + { + /// + /// Writes the LoadGraphicsResources method. + /// + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(ShaderInfo info, IndentedTextWriter writer) + { + string typeName = info.Hierarchy.Hierarchy[0].QualifiedName; + + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(GeneratorName); + writer.WriteLine($"static void global::ComputeSharp.Descriptors.IComputeShaderDescriptor<{typeName}>.LoadGraphicsResources(in {typeName} shader, ref TLoader loader)"); + + using (writer.WriteBlock()) + { + // Nothing to do if there are no resources + if (info.Resources.IsEmpty) + { + return; + } + + // Delegate to the generated loader type + writer.WriteLine("global::ComputeSharp.Generated.GraphicsResourcesLoader.LoadGraphicsResources(in shader, ref loader);"); + } + } + + /// + /// Registers a callback to generate additional types, if needed. + /// + /// The input instance with gathered shader info. + /// The registered callbacks to generate additional types. + /// The using directives needed by the generated code. + public static void RegisterAdditionalTypesSyntax( + ShaderInfo info, + ImmutableArrayBuilder> callbacks, + ImmutableHashSetBuilder usingDirectives) + { + // If there are no resources, there's no need for any additional types + if (info.Resources.IsEmpty) + { + return; + } + + _ = usingDirectives.Add("global::System.CodeDom.Compiler"); + _ = usingDirectives.Add("global::System.Diagnostics"); + _ = usingDirectives.Add("global::System.Diagnostics.CodeAnalysis"); + _ = usingDirectives.Add("global::System.Runtime.CompilerServices"); + _ = usingDirectives.Add("global::ComputeSharp.Descriptors"); + + // Declare the GraphicsResourcesLoader type + static void Callback(ShaderInfo info, IndentedTextWriter writer) + { + string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName(); + + writer.WriteLine($"""/// """); + writer.WriteLine($"""/// A type containing loading logic for graphics resources in shaders of type ."""); + writer.WriteLine($"""/// """); + writer.WriteGeneratedAttributes(GeneratorName, useFullyQualifiedTypeNames: false); + writer.WriteLine($"""file static class GraphicsResourcesLoader"""); + + using (writer.WriteBlock()) + { + // Define the FromManaged method (managed shader type to native constant buffer) + writer.WriteLine($$"""/// """); + writer.WriteLine($"""[MethodImpl(MethodImplOptions.AggressiveInlining)]"""); + writer.WriteLine($"""[SkipLocalsInit]"""); + writer.WriteLine($"public static void LoadGraphicsResources(in {fullyQualifiedTypeName} shader, ref TLoader loader)"); + writer.WriteLine(" where TLoader : struct, IGraphicsResourceLoader"); + + using (writer.WriteBlock()) + { + // Generate loading statements for each captured resource. + // Each loading statement will invoke the generated accessor. + for (int i = 0; i < info.Resources.Length; i++) + { + writer.WriteLine($"loader.LoadGraphicsResource(shader.{info.Resources[i].FieldName}(), {i});"); + } + } + + // Define all field accessors (always used, just like for constant buffer fields, see remarks there) + foreach (ResourceInfo resourceInfo in info.Resources) + { + writer.WriteLine(); + + // Generate the correct field accessor depending on whether the field can be referenced directly + if (resourceInfo.UnspeakableName is null) + { + writer.WriteLine($""" + /// + /// The input value. + /// A reference to . + [UnsafeAccessor(UnsafeAccessorKind.Field)] + private static extern ref readonly IGraphicsResource {resourceInfo.FieldName}(this ref readonly {fullyQualifiedTypeName} value); + """, isMultiline: true); + } + else + { + writer.WriteLine($""" + /// Gets a reference to the unspeakable field "{resourceInfo.FieldName}" of type . + /// The input value. + /// A reference to the unspeakable field "{resourceInfo.FieldName}". + [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "{resourceInfo.UnspeakableName}")] + private static extern ref readonly IGraphicsResource {resourceInfo.FieldName}(this ref readonly {fullyQualifiedTypeName} value); + """, isMultiline: true); + } + } + } + } + + callbacks.Add(Callback); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs index e475aa08..1e7b84e3 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs @@ -17,7 +17,7 @@ partial class ComputeShaderDescriptorGenerator /// /// A helper with all logic to generate the resources loading code. /// - private static class Resources + private static partial class Resources { /// /// Explores a given type hierarchy and generates statements to load fields. @@ -80,117 +80,5 @@ partial class ComputeShaderDescriptorGenerator diagnostics.Add(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol); } } - - /// - /// Writes the LoadGraphicsResources method. - /// - /// The input instance with gathered shader info. - /// The instance to write into. - public static void WriteSyntax(ShaderInfo info, IndentedTextWriter writer) - { - string typeName = info.Hierarchy.Hierarchy[0].QualifiedName; - - writer.WriteLine("/// "); - writer.WriteGeneratedAttributes(GeneratorName); - writer.WriteLine($"static void global::ComputeSharp.Descriptors.IComputeShaderDescriptor<{typeName}>.LoadGraphicsResources(in {typeName} shader, ref TLoader loader)"); - - using (writer.WriteBlock()) - { - // Nothing to do if there are no resources - if (info.Resources.IsEmpty) - { - return; - } - - // Delegate to the generated loader type - writer.WriteLine("global::ComputeSharp.Generated.GraphicsResourcesLoader.LoadGraphicsResources(in shader, ref loader);"); - } - } - - /// - /// Registers a callback to generate additional types, if needed. - /// - /// The input instance with gathered shader info. - /// The registered callbacks to generate additional types. - /// The using directives needed by the generated code. - public static void RegisterAdditionalTypesSyntax( - ShaderInfo info, - ImmutableArrayBuilder> callbacks, - ImmutableHashSetBuilder usingDirectives) - { - // If there are no resources, there's no need for any additional types - if (info.Resources.IsEmpty) - { - return; - } - - _ = usingDirectives.Add("global::System.CodeDom.Compiler"); - _ = usingDirectives.Add("global::System.Diagnostics"); - _ = usingDirectives.Add("global::System.Diagnostics.CodeAnalysis"); - _ = usingDirectives.Add("global::System.Runtime.CompilerServices"); - _ = usingDirectives.Add("global::ComputeSharp.Descriptors"); - - // Declare the GraphicsResourcesLoader type - static void Callback(ShaderInfo info, IndentedTextWriter writer) - { - string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName(); - - writer.WriteLine($"""/// """); - writer.WriteLine($"""/// A type containing loading logic for graphics resources in shaders of type ."""); - writer.WriteLine($"""/// """); - writer.WriteGeneratedAttributes(GeneratorName, useFullyQualifiedTypeNames: false); - writer.WriteLine($"""file static class GraphicsResourcesLoader"""); - - using (writer.WriteBlock()) - { - // Define the FromManaged method (managed shader type to native constant buffer) - writer.WriteLine($$"""/// """); - writer.WriteLine($"""[MethodImpl(MethodImplOptions.AggressiveInlining)]"""); - writer.WriteLine($"""[SkipLocalsInit]"""); - writer.WriteLine($"public static void LoadGraphicsResources(in {fullyQualifiedTypeName} shader, ref TLoader loader)"); - writer.WriteLine(" where TLoader : struct, IGraphicsResourceLoader"); - - using (writer.WriteBlock()) - { - // Generate loading statements for each captured resource. - // Each loading statement will invoke the generated accessor. - for (int i = 0; i < info.Resources.Length; i++) - { - writer.WriteLine($"loader.LoadGraphicsResource(shader.{info.Resources[i].FieldName}(), {i});"); - } - } - - // Define all field accessors (always used, just like for constant buffer fields, see remarks there) - foreach (ResourceInfo resourceInfo in info.Resources) - { - writer.WriteLine(); - - // Generate the correct field accessor depending on whether the field can be referenced directly - if (resourceInfo.UnspeakableName is null) - { - writer.WriteLine($""" - /// - /// The input value. - /// A reference to . - [UnsafeAccessor(UnsafeAccessorKind.Field)] - private static extern ref readonly IGraphicsResource {resourceInfo.FieldName}(this ref readonly {fullyQualifiedTypeName} value); - """, isMultiline: true); - } - else - { - writer.WriteLine($""" - /// Gets a reference to the unspeakable field "{resourceInfo.FieldName}" of type . - /// The input value. - /// A reference to the unspeakable field "{resourceInfo.FieldName}". - [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "{resourceInfo.UnspeakableName}")] - private static extern ref readonly IGraphicsResource {resourceInfo.FieldName}(this ref readonly {fullyQualifiedTypeName} value); - """, isMultiline: true); - } - } - } - } - - callbacks.Add(Callback); - } } } \ No newline at end of file From 5811ba60cf84bf6ca330398d4b9301ddaaff321a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 21 Oct 2023 16:34:17 +0200 Subject: [PATCH 4/6] Restructure resources info logic, drop unnecessary TypeName field --- ...iptorGenerator.ResourceDescriptorRanges.cs | 58 ------------------- ...puteShaderDescriptorGenerator.Resources.cs | 36 +++++++++++- .../ComputeShaderDescriptorGenerator.cs | 21 +++---- .../Models/ResourceInfo.cs | 3 +- 4 files changed, 42 insertions(+), 76 deletions(-) delete mode 100644 src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.ResourceDescriptorRanges.cs diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.ResourceDescriptorRanges.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.ResourceDescriptorRanges.cs deleted file mode 100644 index bfe91e80..00000000 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.ResourceDescriptorRanges.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System.Collections.Immutable; -using ComputeSharp.SourceGeneration.Helpers; -using ComputeSharp.SourceGeneration.Mappings; -using ComputeSharp.SourceGenerators.Models; - -namespace ComputeSharp.SourceGenerators; - -/// -partial class ComputeShaderDescriptorGenerator -{ - /// - /// A helper with all logic to generate the ResourceDescriptorRanges property. - /// - private static partial class ResourceDescriptorRanges - { - /// - /// Gets the data related to the shader metadata for a given shader type. - /// - /// Indicates whether the current shader uses an implicit texture. - /// The sequence of captured resources for the shader. - /// The metadata info for the shader. - public static ImmutableArray GetInfo( - bool isImplicitTextureUsed, - ImmutableArray resources) - { - using ImmutableArrayBuilder descriptors = new(); - - int constantBufferOffset = 1; - int readOnlyResourceOffset = 0; - int readWriteResourceOffset = 0; - - // Add the implicit texture descriptor, if needed - if (isImplicitTextureUsed) - { - descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++)); - } - - // Populate the sequence of resource descriptors - foreach (ResourceInfo resource in resources) - { - if (HlslKnownTypes.IsConstantBufferType(resource.TypeName)) - { - descriptors.Add(new ResourceDescriptor(2, constantBufferOffset++)); - } - else if (HlslKnownTypes.IsReadOnlyTypedResourceType(resource.TypeName)) - { - descriptors.Add(new ResourceDescriptor(0, readOnlyResourceOffset++)); - } - else - { - descriptors.Add(new ResourceDescriptor(1, readWriteResourceOffset++)); - } - } - - return descriptors.ToImmutable(); - } - } -} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs index 1e7b84e3..a7b7b288 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs @@ -20,21 +20,36 @@ partial class ComputeShaderDescriptorGenerator private static partial class Resources { /// - /// Explores a given type hierarchy and generates statements to load fields. + /// Gathers info on all resources captured by a given shader type. /// /// The collection of produced instances. /// The input object currently in use. /// The current shader type being explored. + /// Indicates whether the current shader uses an implicit texture. /// The size of the shader constant buffer. /// The sequence of instances for all captured resources. + /// The sequence of instances for all captured resources. public static void GetInfo( ImmutableArrayBuilder diagnostics, Compilation compilation, ITypeSymbol structDeclarationSymbol, + bool isImplicitTextureUsed, int constantBufferSizeInBytes, - out ImmutableArray resources) + out ImmutableArray resources, + out ImmutableArray resourceDescriptors) { using ImmutableArrayBuilder resourceBuilder = new(); + using ImmutableArrayBuilder resourceDescriptorBuilder = new(); + + int constantBufferOffset = 1; + int readOnlyResourceOffset = 0; + int readWriteResourceOffset = 0; + + // Add the implicit texture descriptor, if needed + if (isImplicitTextureUsed) + { + resourceDescriptorBuilder.Add(new ResourceDescriptor(1, readWriteResourceOffset++)); + } foreach (ISymbol memberSymbol in structDeclarationSymbol.GetMembers()) { @@ -61,11 +76,26 @@ partial class ComputeShaderDescriptorGenerator // Check if the field is a resource (note: resources can only be top level fields) if (HlslKnownTypes.IsTypedResourceType(typeName)) { - resourceBuilder.Add(new ResourceInfo(fieldName, unspeakableName, typeName)); + resourceBuilder.Add(new ResourceInfo(fieldName, unspeakableName)); + + // Populate the resource descriptors as well + if (HlslKnownTypes.IsConstantBufferType(typeName)) + { + resourceDescriptorBuilder.Add(new ResourceDescriptor(2, constantBufferOffset++)); + } + else if (HlslKnownTypes.IsReadOnlyTypedResourceType(typeName)) + { + resourceDescriptorBuilder.Add(new ResourceDescriptor(0, readOnlyResourceOffset++)); + } + else + { + resourceDescriptorBuilder.Add(new ResourceDescriptor(1, readWriteResourceOffset++)); + } } } resources = resourceBuilder.ToImmutable(); + resourceDescriptors = resourceDescriptorBuilder.ToImmutable(); // A shader root signature has a maximum size of 64 DWORDs, so 256 bytes. // Loaded values in the root signature have the following costs: diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs index c75a2732..92abac1d 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs @@ -69,16 +69,6 @@ public sealed partial class ComputeShaderDescriptorGenerator : IIncrementalGener token.ThrowIfCancellationRequested(); - // Get the resources info - Resources.GetInfo( - diagnostics, - context.SemanticModel.Compilation, - typeSymbol, - constantBufferSizeInBytes, - out ImmutableArray resourceInfo); - - token.ThrowIfCancellationRequested(); - // Thread group size info NumThreads.GetInfo( diagnostics, @@ -105,10 +95,15 @@ public sealed partial class ComputeShaderDescriptorGenerator : IIncrementalGener token.ThrowIfCancellationRequested(); - // Resource descriptor ranges info - ImmutableArray resourceDescriptors = ResourceDescriptorRanges.GetInfo( + // Get the resources info + Resources.GetInfo( + diagnostics, + context.SemanticModel.Compilation, + typeSymbol, isImplicitTextureUsed, - resourceInfo); + constantBufferSizeInBytes, + out ImmutableArray resourceInfo, + out ImmutableArray resourceDescriptors); token.ThrowIfCancellationRequested(); diff --git a/src/ComputeSharp.SourceGenerators/Models/ResourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/ResourceInfo.cs index 2e738721..87c5ca6a 100644 --- a/src/ComputeSharp.SourceGenerators/Models/ResourceInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/ResourceInfo.cs @@ -5,5 +5,4 @@ namespace ComputeSharp.SourceGenerators.Models; /// /// The name of the resource field. /// The unspeakable name of the field, if present. -/// The full metadata name for the resource type. -public sealed record ResourceInfo(string FieldName, string? UnspeakableName, string TypeName); \ No newline at end of file +public sealed record ResourceInfo(string FieldName, string? UnspeakableName); \ No newline at end of file From cf8969a77e3ce3498c819ec5f8f9ec3c6457c5b6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sat, 21 Oct 2023 18:40:27 +0200 Subject: [PATCH 5/6] Fix generated field accessors for resource fields --- ...derDescriptorGenerator.Resources.Syntax.cs | 5 +-- ...puteShaderDescriptorGenerator.Resources.cs | 40 +++++++++++++++++-- .../Models/ResourceInfo.cs | 3 +- .../Imaging/Interfaces/IPixel{T,TPixel}.cs | 1 + 4 files changed, 41 insertions(+), 8 deletions(-) diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.Syntax.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.Syntax.cs index ab9df011..48fc7f79 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.Syntax.cs @@ -75,7 +75,6 @@ partial class ComputeShaderDescriptorGenerator // Define the FromManaged method (managed shader type to native constant buffer) writer.WriteLine($$"""/// """); writer.WriteLine($"""[MethodImpl(MethodImplOptions.AggressiveInlining)]"""); - writer.WriteLine($"""[SkipLocalsInit]"""); writer.WriteLine($"public static void LoadGraphicsResources(in {fullyQualifiedTypeName} shader, ref TLoader loader)"); writer.WriteLine(" where TLoader : struct, IGraphicsResourceLoader"); @@ -102,7 +101,7 @@ partial class ComputeShaderDescriptorGenerator /// The input value. /// A reference to . [UnsafeAccessor(UnsafeAccessorKind.Field)] - private static extern ref readonly IGraphicsResource {resourceInfo.FieldName}(this ref readonly {fullyQualifiedTypeName} value); + private static extern ref readonly {resourceInfo.FieldType} {resourceInfo.FieldName}(this ref readonly {fullyQualifiedTypeName} value); """, isMultiline: true); } else @@ -112,7 +111,7 @@ partial class ComputeShaderDescriptorGenerator /// The input value. /// A reference to the unspeakable field "{resourceInfo.FieldName}". [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "{resourceInfo.UnspeakableName}")] - private static extern ref readonly IGraphicsResource {resourceInfo.FieldName}(this ref readonly {fullyQualifiedTypeName} value); + private static extern ref readonly {resourceInfo.FieldType} {resourceInfo.FieldName}(this ref readonly {fullyQualifiedTypeName} value); """, isMultiline: true); } } diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs index a7b7b288..e3b40133 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs @@ -54,13 +54,13 @@ partial class ComputeShaderDescriptorGenerator foreach (ISymbol memberSymbol in structDeclarationSymbol.GetMembers()) { // Only process instance fields - if (memberSymbol is not IFieldSymbol { Type: INamedTypeSymbol { IsStatic: false }, IsConst: false, IsStatic: false, IsFixedSizeBuffer: false, IsImplicitlyDeclared: false } fieldSymbol) + if (memberSymbol is not IFieldSymbol { Type: INamedTypeSymbol { IsStatic: false } typeSymbol, IsConst: false, IsStatic: false, IsFixedSizeBuffer: false } fieldSymbol) { continue; } // Skip fields of not accessible types (the analyzer will handle this just like other fields) - if (!fieldSymbol.Type.IsAccessibleFromCompilationAssembly(compilation)) + if (!typeSymbol.IsAccessibleFromCompilationAssembly(compilation)) { continue; } @@ -71,12 +71,12 @@ partial class ComputeShaderDescriptorGenerator continue; } - string typeName = fieldSymbol.Type.GetFullyQualifiedMetadataName(); + string typeName = typeSymbol.GetFullyQualifiedMetadataName(); // Check if the field is a resource (note: resources can only be top level fields) if (HlslKnownTypes.IsTypedResourceType(typeName)) { - resourceBuilder.Add(new ResourceInfo(fieldName, unspeakableName)); + resourceBuilder.Add(new ResourceInfo(fieldName, GetResourceTypeName(typeSymbol), unspeakableName)); // Populate the resource descriptors as well if (HlslKnownTypes.IsConstantBufferType(typeName)) @@ -110,5 +110,37 @@ partial class ComputeShaderDescriptorGenerator diagnostics.Add(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol); } } + + /// + /// Gets the name of a given resource field type. + /// + /// The input field type to inspect. + /// The fully qualified resource type name, nicely formatted. + private static string GetResourceTypeName(INamedTypeSymbol typeSymbol) + { + using ImmutableArrayBuilder builder = new(); + + // Add the type name (we'll add the ComputeSharp namespace, so no need for fully qualified type names) + builder.AddRange(typeSymbol.Name.AsSpan()); + builder.Add('<'); + + _ = HlslKnownTypes.TryGetMappedName(typeSymbol.TypeArguments[0].GetFullyQualifiedMetadataName(), out string? mappedName); + + // We always have at least one type argument, so first append it. We either append the mapped + // type name (ie. the friendly primitive or HLSL type name), or the fully qualified type name. + builder.AddRange((mappedName ?? typeSymbol.TypeArguments[0].GetFullyQualifiedName(includeGlobal: true)).AsSpan()); + + // If the resource also has a pixel type, append that too. + // We only need the name again, as the namespace is imported. + if (typeSymbol.TypeArguments is [_, INamedTypeSymbol pixelTypeSymbol]) + { + builder.AddRange(", ".AsSpan()); + builder.AddRange(pixelTypeSymbol.Name.AsSpan()); + } + + builder.Add('>'); + + return builder.ToString(); + } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Models/ResourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/ResourceInfo.cs index 87c5ca6a..3e6e2c5b 100644 --- a/src/ComputeSharp.SourceGenerators/Models/ResourceInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/ResourceInfo.cs @@ -4,5 +4,6 @@ namespace ComputeSharp.SourceGenerators.Models; /// A model describing a captured resource (either a buffer or a texture). /// /// The name of the resource field. +/// The fully qualified type name of the field. /// The unspeakable name of the field, if present. -public sealed record ResourceInfo(string FieldName, string? UnspeakableName); \ No newline at end of file +public sealed record ResourceInfo(string FieldName, string FieldType, string? UnspeakableName); \ No newline at end of file diff --git a/src/ComputeSharp/Core/Imaging/Interfaces/IPixel{T,TPixel}.cs b/src/ComputeSharp/Core/Imaging/Interfaces/IPixel{T,TPixel}.cs index 5e285582..bf2e808a 100644 --- a/src/ComputeSharp/Core/Imaging/Interfaces/IPixel{T,TPixel}.cs +++ b/src/ComputeSharp/Core/Imaging/Interfaces/IPixel{T,TPixel}.cs @@ -5,6 +5,7 @@ namespace ComputeSharp; /// /// The pixel type, when stored in memory (either on the CPU or the GPU side). /// The type of pixel when normalized and used within a shader. +/// This interface is not meant to be implemented by user defined types. public interface IPixel where T : unmanaged, IPixel where TPixel : unmanaged From 8229ccd8102f5e640e5f04ba6d953673a559df6c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Mon, 20 Nov 2023 22:17:54 +0100 Subject: [PATCH 6/6] Suppress warning for unused field in benchmark project --- .../ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs b/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs index 35d57b83..976dab1c 100644 --- a/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs +++ b/samples/ComputeSharp.Benchmark/Dispatching/DispatchingBenchmark.cs @@ -3,7 +3,7 @@ using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Configs; -#pragma warning disable CA1063 +#pragma warning disable CA1063, IDE0052 namespace ComputeSharp.Benchmark.Blas;