diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.Syntax.cs deleted file mode 100644 index 2d79b8a2..00000000 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.Syntax.cs +++ /dev/null @@ -1,415 +0,0 @@ -using System.Linq; -using ComputeSharp.D2D1.SourceGenerators.Models; -using ComputeSharp.SourceGeneration.Extensions; -using ComputeSharp.SourceGeneration.Helpers; -using ComputeSharp.SourceGeneration.Mappings; -using ComputeSharp.SourceGeneration.Models; - -namespace ComputeSharp.D2D1.SourceGenerators; - -/// -partial class D2DPixelShaderDescriptorGenerator -{ - /// - partial class ConstantBuffer - { - /// - /// Writes the LoadConstantBuffer method. - /// - /// The input instance with gathered shader info. - /// The instance to write into. - public static void WriteLoadConstantBufferSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) - { - string typeName = info.Hierarchy.Hierarchy[0].QualifiedName; - - writer.WriteLine("/// "); - writer.WriteGeneratedAttributes(GeneratorName); - writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]"); - writer.WriteLine($"static unsafe void global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{typeName}>.LoadConstantBuffer(in {typeName} shader, ref TLoader loader)"); - - using (writer.WriteBlock()) - { - // If there are no fields, just load an empty buffer - if (info.Fields.IsEmpty) - { - writer.WriteLine("loader.LoadConstantBuffer(default);"); - } - else - { - // Otherwise, pass a span into the marshalled native layout buffer - writer.WriteLine("global::ComputeSharp.D2D1.Generated.ConstantBufferMarshaller.FromManaged(in shader, out global::ComputeSharp.D2D1.Generated.ConstantBuffer buffer);"); - writer.WriteLine(); - writer.WriteLine("loader.LoadConstantBuffer(new global::System.ReadOnlySpan(&buffer, sizeof(global::ComputeSharp.D2D1.Generated.ConstantBuffer)));"); - } - } - } - - /// - /// Writes the CreateFromConstantBuffer method. - /// - /// The input instance with gathered shader info. - /// The instance to write into. - public static void WriteCreateFromConstantBufferSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) - { - string typeName = info.Hierarchy.Hierarchy[0].QualifiedName; - - writer.WriteLine("/// "); - writer.WriteGeneratedAttributes(GeneratorName); - writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]"); - writer.WriteLine($"static unsafe {typeName} global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{typeName}>.CreateFromConstantBuffer(global::System.ReadOnlySpan data)"); - - using (writer.WriteBlock()) - { - // If there are no fields, just return an empty shader - if (info.Fields.IsEmpty) - { - writer.WriteLine("return default;"); - - return; - } - - // Get a reference to the data through the generated native layout type and define the shader - writer.WriteLine("ref readonly global::ComputeSharp.D2D1.Generated.ConstantBuffer buffer = ref global::System.Runtime.InteropServices.MemoryMarshal.AsRef(data);"); - writer.WriteLine(); - writer.WriteLine("return global::ComputeSharp.D2D1.Generated.ConstantBufferMarshaller.ToManaged(in buffer);"); - } - } - - /// - /// 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( - D2D1ShaderInfo info, - ImmutableArrayBuilder> callbacks, - ImmutableHashSetBuilder usingDirectives) - { - // If there are no fields, there is no need for a constant buffer type - if (info.Fields.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::System.Runtime.InteropServices"); - - // Declare the ConstantBuffer type - static void ConstantBufferCallback(D2D1ShaderInfo info, IndentedTextWriter writer) - { - string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName(); - - writer.WriteLine($"""/// """); - writer.WriteLine($"""/// A type representing the constant buffer native layout for ."""); - writer.WriteLine($"""/// """); - writer.WriteGeneratedAttributes(GeneratorName, useFullyQualifiedTypeNames: false); - writer.WriteLine($"""[StructLayout(LayoutKind.Explicit, Size = {info.ConstantBufferSizeInBytes})]"""); - writer.WriteLine($"""file struct ConstantBuffer"""); - - using (writer.WriteBlock()) - { - // Declare fields for every mapped item from the shader layout - writer.WriteLineSeparatedMembers(info.Fields.AsSpan(), (field, writer) => - { - switch (field) - { - case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive: - - // Append a field as a global::ComputeSharp.Bool value (will use the implicit conversion from bool values) - writer.WriteFieldXmlSummary(field, fullyQualifiedTypeName); - writer.WriteFieldXmlRemarks(field); - writer.WriteLine($"""[FieldOffset({primitive.Offset})]"""); - writer.WriteLine($"""public global::ComputeSharp.Bool {string.Join("_", primitive.FieldPath.Select(static path => path.Name))};"""); - break; - case FieldInfo.Primitive primitive: - - // Append primitive fields of other types with their mapped names - writer.WriteFieldXmlSummary(field, fullyQualifiedTypeName); - writer.WriteFieldXmlRemarks(field); - writer.WriteLine($"""[FieldOffset({primitive.Offset})]"""); - writer.WriteLine($"""public {HlslKnownTypes.GetMappedName(primitive.TypeName)} {string.Join("_", primitive.FieldPath.Select(static path => path.Name))};"""); - break; - - case FieldInfo.NonLinearMatrix matrix: - string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}"); - string fieldNamePrefix = string.Join("_", matrix.FieldPath.Select(static path => path.Name)); - - // Declare a field for every row of the matrix type - for (int j = 0; j < matrix.Rows; j++) - { - writer.WriteLineIf(j > 0); - writer.WriteFieldXmlSummary(field, fullyQualifiedTypeName); - writer.WriteFieldXmlRemarks(field, row: j); - writer.WriteLine($"""[FieldOffset({matrix.Offsets[j]})]"""); - writer.WriteLine($"""public {rowTypeName} {fieldNamePrefix}_{j};"""); - } - - break; - } - }); - } - } - - // Declare the ConstantBufferMarshaller type - static void ConstantBufferMarshallerCallback(D2D1ShaderInfo info, IndentedTextWriter writer) - { - string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName(); - - writer.WriteLine($"""/// """); - writer.WriteLine($"""/// A type containing marshalling logic for shaders of type ."""); - writer.WriteLine($"""/// """); - writer.WriteGeneratedAttributes(GeneratorName, useFullyQualifiedTypeNames: false); - writer.WriteLine($"""file static class ConstantBufferMarshaller"""); - - using (writer.WriteBlock()) - { - // Define the ToManaged method (native constant buffer to managed shader type) - writer.WriteLine($"""/// """); - writer.WriteLine($"""/// Marshals native constant buffer data to managed instances."""); - writer.WriteLine($"""/// """); - writer.WriteLine($"""/// The input native constant buffer."""); - writer.WriteLine($"""/// The marshalled instance."""); - writer.WriteLine($"""[MethodImpl(MethodImplOptions.AggressiveInlining)]"""); - writer.WriteLine($"""[SkipLocalsInit]"""); - writer.WriteLine($"public static {fullyQualifiedTypeName} ToManaged(in ConstantBuffer buffer)"); - - using (writer.WriteBlock()) - { - writer.WriteLine($"Unsafe.SkipInit(out {fullyQualifiedTypeName} shader);"); - writer.WriteLine(); - - // Generate loading statements for each captured field - foreach (FieldInfo fieldInfo in info.Fields) - { - switch (fieldInfo) - { - case FieldInfo.Primitive primitive: - - // Read a nested primitive value - writer.WriteFieldAccessExpression(fieldInfo); - writer.WriteLine($" = buffer.{string.Join("_", primitive.FieldPath.Select(static path => path.Name))};"); - break; - - case FieldInfo.NonLinearMatrix matrix: - string primitiveTypeName = matrix.ElementName.ToLowerInvariant(); - string matrixHlslTypeName = $"{primitiveTypeName}{matrix.Rows}x{matrix.Columns}"; - string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}"); - string fieldNamePrefix = string.Join("_", matrix.FieldPath.Select(static path => path.Name)); - - // Get a reference to the whole matrix field, just once for all rows - writer.WriteLine(skipIfPresent: true); - writer.Write($"ref {matrixHlslTypeName} __{fieldNamePrefix} = ref "); - writer.WriteFieldAccessExpression(fieldInfo); - writer.WriteLine(";"); - writer.WriteLine(); - - // Read all rows of a given matrix type - for (int j = 0; j < matrix.Rows; j++) - { - writer.WriteLine($"Unsafe.As<{primitiveTypeName}, {rowTypeName}>(ref __{fieldNamePrefix}.M{j + 1}1) = buffer.{fieldNamePrefix}_{j};"); - } - - writer.WriteLine(); - break; - } - } - - writer.WriteLine(skipIfPresent: true); - writer.WriteLine("return shader;"); - } - - // Define the FromManaged method (managed shader type to native constant buffer) - writer.WriteLine(); - writer.WriteLine($"""/// """); - writer.WriteLine($"""/// Marshals managed instances to native constant buffer data."""); - writer.WriteLine($"""/// """); - writer.WriteLine($"""/// The input native constant buffer."""); - writer.WriteLine($"""/// The marshalled instance."""); - writer.WriteLine($"""[MethodImpl(MethodImplOptions.AggressiveInlining)]"""); - writer.WriteLine($"""[SkipLocalsInit]"""); - writer.WriteLine($"public static void FromManaged(in {fullyQualifiedTypeName} shader, out ConstantBuffer buffer)"); - - using (writer.WriteBlock()) - { - // Generate loading statements for each captured field - foreach (FieldInfo fieldInfo in info.Fields) - { - switch (fieldInfo) - { - case FieldInfo.Primitive primitive: - - // Assign a primitive value - writer.Write($"buffer.{string.Join("_", primitive.FieldPath.Select(static path => path.Name))} = "); - writer.WriteFieldAccessExpression(fieldInfo); - writer.WriteLine(";"); - break; - - case FieldInfo.NonLinearMatrix matrix: - string primitiveTypeName = matrix.ElementName.ToLowerInvariant(); - string matrixHlslTypeName = $"{primitiveTypeName}{matrix.Rows}x{matrix.Columns}"; - string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}"); - string fieldNamePrefix = string.Join("_", matrix.FieldPath.Select(static path => path.Name)); - - // Get a reference to the whole matrix field, just once for all rows - writer.WriteLine(skipIfPresent: true); - writer.Write($"ref {matrixHlslTypeName} __{fieldNamePrefix} = ref "); - writer.WriteFieldAccessExpression(fieldInfo); - writer.WriteLine(";"); - writer.WriteLine(); - - // Assign all rows of a given matrix type - for (int j = 0; j < matrix.Rows; j++) - { - writer.WriteLine($"buffer.{fieldNamePrefix}_{j} = Unsafe.As<{primitiveTypeName}, {rowTypeName}>(ref __{fieldNamePrefix}.M{j + 1}1);"); - } - - writer.WriteLine(); - break; - } - } - } - - using ImmutableHashSetBuilder<(string ContainerType, string FieldName)> generatedAccessors = new(); - - // Define all field accessors. Note that these are generated regardless of the accessibility - // of the field they're getting the value for. This simplifies the rest of the code, and allows - // stripping the readonly-ness of the field references, and has no binary size impact anyway. - // This is because the fields are compiled to be exactly equivalent to direct field references. - foreach (FieldInfo fieldInfo in info.Fields) - { - for (int i = 0; i < fieldInfo.FieldPath.Length; i++) - { - FieldPathPart pathPart = fieldInfo.FieldPath[i]; - - // Get the friendly type name for the field: - // - If the part path is a nested struct, the type name is embedded - // - Otherwise, get the correct HLSL mapped type name for the field - string typeName = pathPart switch - { - FieldPathPart.Nested nested => nested.TypeName, - FieldPathPart.Leaf when fieldInfo.TypeName is "System.Boolean" => "global::ComputeSharp.Bool", - _ => HlslKnownTypes.GetMappedName(fieldInfo.TypeName) - }; - - // Get the friendly type name for the field. If this nested field is the - // first path, then the parent is the shader type itself. Otherwise, the - // container path is the type of the previous containing type of the field. - string containingTypeName = i == 0 - ? fullyQualifiedTypeName - : ((FieldPathPart.Nested)fieldInfo.FieldPath[i - 1]).TypeName; - - // Make sure to skip repeated field accessors. It's possible for some accessors to end up - // being required, in case a shader type had multiple fields of the same nested struct type. - // To avoid so, we just add the containing type and name to an hashset that we update. - if (!generatedAccessors.Add((containingTypeName, pathPart.Name))) - { - continue; - } - - writer.WriteLine(); - - // If there is no unspeakable name, we can reference the field directly. This means we can both - // use that in XML docs to refer to it (and inherit the docs), and we don't need an explicit name. - if (pathPart.UnspeakableName is null) - { - writer.WriteLine($""" - /// - /// The input value. - /// A mutable reference to . - [UnsafeAccessor(UnsafeAccessorKind.Field)] - private static extern ref {typeName} {pathPart.Name}(this ref readonly {containingTypeName} value); - """, isMultiline: true); - } - else - { - writer.WriteLine($""" - /// Gets a reference to the unspeakable field "{pathPart.Name}" of type . - /// The input value. - /// A mutable reference to the unspeakable field "{pathPart.Name}". - [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "{pathPart.UnspeakableName}")] - private static extern ref {typeName} {pathPart.Name}(this ref readonly {containingTypeName} value); - """, isMultiline: true); - } - } - } - } - } - - callbacks.Add(ConstantBufferCallback); - callbacks.Add(ConstantBufferMarshallerCallback); - } - } -} - -/// -file static class IndentedTextWriterExtensions -{ - /// - /// Writes the XML summary for a given field. - /// - /// The instance to write into. - /// The input field to write the XML summary for. - /// The fully qualified type name of the containing type. - public static void WriteFieldXmlSummary(this IndentedTextWriter writer, FieldInfo fieldInfo, string fullyQualifiedTypeName) - { - if (fieldInfo.FieldPath[0].UnspeakableName is null) - { - writer.WriteLine($"""/// """); - } - else - { - writer.WriteLine($"""/// The unspeakable field "{fieldInfo.FieldPath[0].Name}" of ."""); - } - } - - /// - /// Writes the XML remarks for a given field, if needed. - /// - /// The instance to write into. - /// The input field to write the XML remarks for, if needed. - /// The row for the field, if this is a matrix type. - public static void WriteFieldXmlRemarks(this IndentedTextWriter writer, FieldInfo fieldInfo, int? row = null) - { - // The remarks are only needed if the field is nested - if (fieldInfo.FieldPath is not [.., FieldPathPart.Nested nested, FieldPathPart.Leaf leaf]) - { - return; - } - - // Write the correct remarks depending on whether the field can be referenced directly - if (leaf.UnspeakableName is null) - { - writer.Write($"""/// Serialized field mapping to"""); - writer.WriteIf(row is not null, $""" row {row} of"""); - writer.WriteLine($""" ."""); - } - else - { - writer.Write($"""/// Serialized field mapping to"""); - writer.WriteIf(row is not null, $""" row {row} of"""); - writer.WriteLine($""" the unspeakable field "{leaf.Name}" of ."""); - } - } - - /// - /// Writes an expression to access a given field. - /// - /// The instance to write into. - /// The input field to write the expression for. - public static void WriteFieldAccessExpression(this IndentedTextWriter writer, FieldInfo fieldInfo) - { - writer.Write("shader"); - - // Invoke all generated field accessors to get to the target field. - // Because they're extension methods, we can chain them sequentially. - // This simplifies the formatting and makes the code easier to read. - foreach (FieldPathPart part in fieldInfo.FieldPath) - { - writer.Write($".{part.Name}()"); - } - } -} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.cs index d86dbe5b..449c9833 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.ConstantBuffer.cs @@ -1,12 +1,10 @@ using System; using System.Collections.Immutable; -using System.Diagnostics.CodeAnalysis; -using System.Text.RegularExpressions; -using ComputeSharp.Core.Helpers; +using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; -using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGeneration.Models; +using ComputeSharp.SourceGeneration.SyntaxProcessors; using Microsoft.CodeAnalysis; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; @@ -16,26 +14,16 @@ namespace ComputeSharp.D2D1.SourceGenerators; partial class D2DPixelShaderDescriptorGenerator { /// - /// A helper with all logic to generate the ConstantBuffer methods and additional types. + /// A helper with all logic to generate the constant buffer marshalling methods and additional types. /// - private static partial class ConstantBuffer + private static class ConstantBuffer { - /// - /// A to extract the parameter name of a primary constructor capture field. - /// - /// - /// Temporary workaround until is available. - /// - private static readonly Regex PrimaryConstructorNameRegex = new("^<([^>]+)>P$", RegexOptions.Compiled); - - /// - /// Explores a given type hierarchy and generates statements to load fields. - /// + /// /// The collection of produced instances. - /// The input object currently in use. - /// The current shader type being explored. - /// The size of the shader constant buffer. - /// The sequence of instances for all captured values. + /// + /// + /// + /// public static void GetInfo( ImmutableArrayBuilder diagnostics, Compilation compilation, @@ -43,79 +31,13 @@ partial class D2DPixelShaderDescriptorGenerator out int constantBufferSizeInBytes, out ImmutableArray fields) { - // Helper method that uses boxes instead of ref-s (illegal in enumerators) - static void GetInfo( - Compilation compilation, - ITypeSymbol currentTypeSymbol, - ImmutableArray fieldPath, - ref int rawDataOffset, - ImmutableArrayBuilder fields) - { - bool isFirstField = true; + constantBufferSizeInBytes = 0; - foreach (ISymbol memberSymbol in currentTypeSymbol.GetMembers()) - { - // Only process fields of a valid shape/type - if (memberSymbol is not IFieldSymbol { Type: INamedTypeSymbol { IsStatic: false }, IsConst: false, IsStatic: false, IsFixedSizeBuffer: false } fieldSymbol) - { - continue; - } - - // Skip fields of not accessible types (the analyzer will handle this) - if (!fieldSymbol.Type.IsAccessibleFromCompilationAssembly(compilation)) - { - continue; - } - - // Try to get the name to use for the field and the accessor - if (!TryGetFieldAccessorName(fieldSymbol, out string? fieldName, out string? unspeakableName)) - { - continue; - } - - string typeName = fieldSymbol.Type.GetFullyQualifiedMetadataName(); - - // The first item in each nested struct needs to be aligned to 16 bytes - if (isFirstField && fieldPath.Length > 0) - { - rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); - - isFirstField = false; - } - - if (HlslKnownTypes.IsKnownHlslType(typeName)) - { - ImmutableArray nestedFieldPath = fieldPath.Add(new FieldPathPart.Leaf(fieldName, unspeakableName)); - - fields.Add(GetHlslKnownTypeFieldInfo(nestedFieldPath, typeName, ref rawDataOffset)); - } - else if (fieldSymbol.Type.IsUnmanagedType) - { - string nestedTypeName = fieldSymbol.Type.GetFullyQualifiedName(includeGlobal: true); - FieldPathPart fieldPathPart = new FieldPathPart.Nested(fieldName, unspeakableName, nestedTypeName); - - // Custom struct type defined by the user - GetInfo(compilation, fieldSymbol.Type, fieldPath.Add(fieldPathPart), ref rawDataOffset, fields); - } - } - } - - // Setup the resource and byte offsets for tracking - int rawDataOffset = 0; - - using (ImmutableArrayBuilder fieldBuilder = new()) - { - // Traverse all shader fields and gather info, and update the tracking offsets - GetInfo( - compilation, - structDeclarationSymbol, - ImmutableArray.Empty, - ref rawDataOffset, - fieldBuilder); - - constantBufferSizeInBytes = rawDataOffset; - fields = fieldBuilder.ToImmutable(); - } + ConstantBufferSyntaxProcessor.GetInfo( + compilation, + structDeclarationSymbol, + ref constantBufferSizeInBytes, + out fields); // The maximum size for a constant buffer is 64KB const int D3D11_REQ_CONSTANT_BUFFER_ELEMENT_COUNT = 4096; @@ -129,95 +51,64 @@ partial class D2DPixelShaderDescriptorGenerator } /// - /// Tries to get the field name and the accessor name for a given field. + /// Writes the LoadConstantBuffer method. /// - /// The field symbol to analyze. - /// The name of the field that's referenced in code by users. - /// The real name of the field that should be accessed, when different. - /// Whether the field is supported and the necessary info could be retrieved. - public static bool TryGetFieldAccessorName( - IFieldSymbol fieldSymbol, - [NotNullWhen(true)] out string? referencedName, - out string? unspeakableName) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteLoadConstantBufferSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - // If the field can be referenced by name, we can just access it directly - if (fieldSymbol.CanBeReferencedByName) + string typeName = info.Hierarchy.Hierarchy[0].QualifiedName; + + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(GeneratorName); + writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]"); + writer.WriteLine($"static unsafe void global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{typeName}>.LoadConstantBuffer(in {typeName} shader, ref TLoader loader)"); + + using (writer.WriteBlock()) { - referencedName = fieldSymbol.Name; - unspeakableName = null; - - return true; + // If there are no fields, just load an empty buffer + if (info.Fields.IsEmpty) + { + writer.WriteLine("loader.LoadConstantBuffer(default);"); + } + else + { + // Otherwise, pass a span into the marshalled native layout buffer + writer.WriteLine("global::ComputeSharp.D2D1.Generated.ConstantBufferMarshaller.FromManaged(in shader, out global::ComputeSharp.D2D1.Generated.ConstantBuffer buffer);"); + writer.WriteLine(); + writer.WriteLine("loader.LoadConstantBuffer(new global::System.ReadOnlySpan(&buffer, sizeof(global::ComputeSharp.D2D1.Generated.ConstantBuffer)));"); + } } - - // If the field is a primary constructor capture field, get the original name - if (PrimaryConstructorNameRegex.Match(fieldSymbol.Name) is { Success: true, Groups: [_, { Value: string parameterName }] }) - { - referencedName = parameterName; - unspeakableName = fieldSymbol.Name; - - return true; - } - - // The field is not recognized, so just invalid - referencedName = null; - unspeakableName = null; - - return false; } /// - /// Gets info on a given captured HLSL primitive type (either a scalar, a vector or a matrix). + /// Writes the CreateFromConstantBuffer method. /// - /// 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) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteCreateFromConstantBufferSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) { - // For scalar, vector and linear matrix types, serialize the value normally. - // Only the initial alignment needs to be considered, while data is packed. - (int fieldSize, int fieldPack) = HlslKnownSizes.GetTypeInfo(typeName); + string typeName = info.Hierarchy.Hierarchy[0].QualifiedName; - // 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)) + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(GeneratorName); + writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]"); + writer.WriteLine($"static unsafe {typeName} global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{typeName}>.CreateFromConstantBuffer(global::System.ReadOnlySpan data)"); + + using (writer.WriteBlock()) { - using ImmutableArrayBuilder builder = new(); - - for (int j = 0; j < rows; j++) + // If there are no fields, just return an empty shader + if (info.Fields.IsEmpty) { - int startingRawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); + writer.WriteLine("return default;"); - builder.Add(startingRawDataOffset); - - rawDataOffset = startingRawDataOffset + (fieldPack * columns); + return; } - return new FieldInfo.NonLinearMatrix( - fieldPath, - typeName, - elementName!, - rows, - columns, - builder.ToImmutable()); - } - 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. - int startingRawDataOffset = AlignmentHelper.AlignToBoundary( - AlignmentHelper.Pad(rawDataOffset, fieldPack), - fieldSize, - 16); - - rawDataOffset = startingRawDataOffset + fieldSize; - - return new FieldInfo.Primitive(fieldPath, typeName, startingRawDataOffset); + // Get a reference to the data through the generated native layout type and define the shader + writer.WriteLine("ref readonly global::ComputeSharp.D2D1.Generated.ConstantBuffer buffer = ref global::System.Runtime.InteropServices.MemoryMarshal.AsRef(data);"); + writer.WriteLine(); + writer.WriteLine("return global::ComputeSharp.D2D1.Generated.ConstantBufferMarshaller.ToManaged(in buffer);"); } } } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs index 5415f5f3..fcf1994d 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslSource.cs @@ -6,6 +6,7 @@ using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGeneration.Models; +using ComputeSharp.SourceGeneration.SyntaxProcessors; using ComputeSharp.SourceGeneration.SyntaxRewriters; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -117,7 +118,7 @@ partial class D2DPixelShaderDescriptorGenerator } // Try to get the actual field name - if (!ConstantBuffer.TryGetFieldAccessorName(fieldSymbol, out string? fieldName, out _)) + if (!ConstantBufferSyntaxProcessor.TryGetFieldAccessorName(fieldSymbol, out string? fieldName, out _)) { continue; } @@ -411,7 +412,7 @@ partial class D2DPixelShaderDescriptorGenerator } // Try to get the actual field name - if (!ConstantBuffer.TryGetFieldAccessorName(fieldSymbol, out string? fieldName, out _)) + if (!ConstantBufferSyntaxProcessor.TryGetFieldAccessorName(fieldSymbol, out string? fieldName, out _)) { continue; } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.PixelOptions.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.PixelOptions.Syntax.cs deleted file mode 100644 index 6f0cf8b5..00000000 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.PixelOptions.Syntax.cs +++ /dev/null @@ -1,32 +0,0 @@ -using ComputeSharp.D2D1.SourceGenerators.Models; -using ComputeSharp.SourceGeneration.Extensions; -using ComputeSharp.SourceGeneration.Helpers; - -namespace ComputeSharp.D2D1.SourceGenerators; - -/// -partial class D2DPixelShaderDescriptorGenerator -{ - /// - partial class PixelOptions - { - /// - /// Writes the PixelOptions property. - /// - /// The input instance with gathered shader info. - /// The instance to write into. - public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) - { - // Set the right expression if the pixel options are valid - string pixelOptionsExpression = (info.PixelOptions is D2D1PixelOptions.None or D2D1PixelOptions.TrivialSampling) switch - { - true => $"global::ComputeSharp.D2D1.D2D1PixelOptions.{info.PixelOptions}", - false => "default" - }; - - writer.WriteLine("/// "); - writer.WriteGeneratedAttributes(GeneratorName); - writer.WriteLine($"static ComputeSharp.D2D1.D2D1PixelOptions global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{info.Hierarchy.Hierarchy[0].QualifiedName}>.PixelOptions => {pixelOptionsExpression};"); - } - } -} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.PixelOptions.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.PixelOptions.cs index 5c974352..5a891287 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.PixelOptions.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.PixelOptions.cs @@ -1,4 +1,6 @@ +using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; using Microsoft.CodeAnalysis; namespace ComputeSharp.D2D1.SourceGenerators; @@ -9,7 +11,7 @@ partial class D2DPixelShaderDescriptorGenerator /// /// A helper with all logic to generate the PixelOptions property. /// - private static partial class PixelOptions + private static class PixelOptions { /// /// Extracts the pixel options for the current shader. @@ -27,5 +29,24 @@ partial class D2DPixelShaderDescriptorGenerator pixelOptions = D2D1PixelOptions.None; } } + + /// + /// Writes the PixelOptions property. + /// + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(D2D1ShaderInfo info, IndentedTextWriter writer) + { + // Set the right expression if the pixel options are valid + string pixelOptionsExpression = (info.PixelOptions is D2D1PixelOptions.None or D2D1PixelOptions.TrivialSampling) switch + { + true => $"global::ComputeSharp.D2D1.D2D1PixelOptions.{info.PixelOptions}", + false => "default" + }; + + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(GeneratorName); + writer.WriteLine($"static ComputeSharp.D2D1.D2D1PixelOptions global::ComputeSharp.D2D1.Descriptors.ID2D1PixelShaderDescriptor<{info.Hierarchy.Hierarchy[0].QualifiedName}>.PixelOptions => {pixelOptionsExpression};"); + } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs index 5f6d96c4..5322c88c 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs @@ -1,9 +1,11 @@ using System.Collections.Immutable; +using System.ComponentModel; using System.Linq; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; +using ComputeSharp.SourceGeneration.SyntaxProcessors; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -233,7 +235,7 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene using ImmutableArrayBuilder> additionalTypes = new(); using ImmutableHashSetBuilder usingDirectives = new(); - ConstantBuffer.RegisterAdditionalTypesSyntax(item, additionalTypes, usingDirectives); + ConstantBufferSyntaxProcessor.RegisterAdditionalTypesSyntax(GeneratorName, BindingDirection.TwoWay, item, additionalTypes, usingDirectives); InputDescriptions.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives); InputTypes.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives); HlslBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs index 1540b7a0..31d5d1be 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/D2D1ShaderInfo.cs @@ -40,4 +40,4 @@ internal sealed record D2D1ShaderInfo( D2D1PixelOptions PixelOptions, HlslBytecodeInfoKey HlslInfoKey, HlslBytecodeInfo HlslInfo, - EquatableArray Diagnostcs); \ No newline at end of file + EquatableArray Diagnostcs) : IConstantBufferInfo; \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxProcessors/ConstantBufferSyntaxProcessor.ArtificialFields.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxProcessors/ConstantBufferSyntaxProcessor.ArtificialFields.cs new file mode 100644 index 00000000..51678124 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxProcessors/ConstantBufferSyntaxProcessor.ArtificialFields.cs @@ -0,0 +1,11 @@ +namespace ComputeSharp.SourceGeneration.SyntaxProcessors; + +/// +partial class ConstantBufferSyntaxProcessor +{ + /// + private static partial bool HasArtificialFields() + { + return false; + } +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems index 86c8f648..0f3f97f3 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems +++ b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems @@ -26,9 +26,12 @@ + + + \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Models/Interfaces/IConstantBufferInfo.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Models/Interfaces/IConstantBufferInfo.cs new file mode 100644 index 00000000..9ccb3bd1 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Models/Interfaces/IConstantBufferInfo.cs @@ -0,0 +1,24 @@ +using ComputeSharp.SourceGeneration.Helpers; + +namespace ComputeSharp.SourceGeneration.Models; + +/// +/// An interface for a model providing info on constant buffer fields. +/// +internal interface IConstantBufferInfo +{ + /// + /// The hierarchy info for the shader type. + /// + HierarchyInfo Hierarchy { get; } + + /// + /// The size of the shader constant buffer. + /// + int ConstantBufferSizeInBytes { get; } + + /// + /// The description on shader instance fields. + /// + EquatableArray Fields { get; } +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/ConstantBufferSyntaxProcessor.Generation.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/ConstantBufferSyntaxProcessor.Generation.cs new file mode 100644 index 00000000..f251d0c9 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/ConstantBufferSyntaxProcessor.Generation.cs @@ -0,0 +1,409 @@ +using System.ComponentModel; +using System.Linq; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Mappings; +using ComputeSharp.SourceGeneration.Models; + +namespace ComputeSharp.SourceGeneration.SyntaxProcessors; + +/// +partial class ConstantBufferSyntaxProcessor +{ + /// + /// The name of generator to include in the generated code. + /// + private static string? generatorName; + + /// + /// The direction to generate marshalling code for. + /// + private static BindingDirection direction; + + /// + /// Registers a callback to generate additional types, if needed. + /// + /// The type of model providing the necessary info. + /// The name of generator to include in the generated code. + /// The direction to generate marshalling code for. + /// 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( + string generatorName, + BindingDirection direction, + TInfo info, + ImmutableArrayBuilder> callbacks, + ImmutableHashSetBuilder usingDirectives) + where TInfo : class, IConstantBufferInfo + { + // Store the generator name and marshalling direction for later. This avoids needing closures for each + // callback below. It is assumed that all calls to this method will have the same arguments in each assembly. + ConstantBufferSyntaxProcessor.generatorName = generatorName; + ConstantBufferSyntaxProcessor.direction = direction; + + // If there are no fields (including artificial ones), there is no need for a constant buffer type + if (info.Fields.IsEmpty && !HasArtificialFields()) + { + 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::System.Runtime.InteropServices"); + + // Declare the ConstantBuffer type + static void ConstantBufferCallback(TInfo info, IndentedTextWriter writer) + { + string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName(); + + writer.WriteLine($"""/// """); + writer.WriteLine($"""/// A type representing the constant buffer native layout for ."""); + writer.WriteLine($"""/// """); + writer.WriteGeneratedAttributes(ConstantBufferSyntaxProcessor.generatorName!, useFullyQualifiedTypeNames: false); + writer.WriteLine($"""[StructLayout(LayoutKind.Explicit, Size = {info.ConstantBufferSizeInBytes})]"""); + writer.WriteLine($"""file struct ConstantBuffer"""); + + using (writer.WriteBlock()) + { + // Append any artificial fields, if needed + AppendArtificialFields(info, writer); + + // Declare fields for every mapped item from the shader layout + writer.WriteLineSeparatedMembers(info.Fields.AsSpan(), (field, writer) => + { + switch (field) + { + case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive: + + // Append a field as a global::ComputeSharp.Bool value (will use the implicit conversion from bool values) + writer.WriteFieldXmlSummary(field, fullyQualifiedTypeName); + writer.WriteFieldXmlRemarks(field); + writer.WriteLine($"""[FieldOffset({primitive.Offset})]"""); + writer.WriteLine($"""public global::ComputeSharp.Bool {string.Join("_", primitive.FieldPath.Select(static path => path.Name))};"""); + break; + case FieldInfo.Primitive primitive: + + // Append primitive fields of other types with their mapped names + writer.WriteFieldXmlSummary(field, fullyQualifiedTypeName); + writer.WriteFieldXmlRemarks(field); + writer.WriteLine($"""[FieldOffset({primitive.Offset})]"""); + writer.WriteLine($"""public {HlslKnownTypes.GetMappedName(primitive.TypeName)} {string.Join("_", primitive.FieldPath.Select(static path => path.Name))};"""); + break; + + case FieldInfo.NonLinearMatrix matrix: + string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}"); + string fieldNamePrefix = string.Join("_", matrix.FieldPath.Select(static path => path.Name)); + + // Declare a field for every row of the matrix type + for (int j = 0; j < matrix.Rows; j++) + { + writer.WriteLineIf(j > 0); + writer.WriteFieldXmlSummary(field, fullyQualifiedTypeName); + writer.WriteFieldXmlRemarks(field, row: j); + writer.WriteLine($"""[FieldOffset({matrix.Offsets[j]})]"""); + writer.WriteLine($"""public {rowTypeName} {fieldNamePrefix}_{j};"""); + } + + break; + } + }); + } + } + + // Declare the ConstantBufferMarshaller type + static void ConstantBufferMarshallerCallback(TInfo info, IndentedTextWriter writer) + { + string fullyQualifiedTypeName = info.Hierarchy.GetFullyQualifiedTypeName(); + + writer.WriteLine($"""/// """); + writer.WriteLine($"""/// A type containing marshalling logic for shaders of type ."""); + writer.WriteLine($"""/// """); + writer.WriteGeneratedAttributes(ConstantBufferSyntaxProcessor.generatorName!, useFullyQualifiedTypeNames: false); + writer.WriteLine($"""file static class ConstantBufferMarshaller"""); + + using (writer.WriteBlock()) + { + // Define the FromManaged method (managed shader type to native constant buffer) + writer.WriteLine($"""/// """); + writer.WriteLine($"""/// Marshals managed instances to native constant buffer data."""); + writer.WriteLine($"""/// """); + writer.WriteLine($"""/// The input native constant buffer."""); + writer.WriteLine($"""/// The marshalled instance."""); + writer.WriteLine($"""[MethodImpl(MethodImplOptions.AggressiveInlining)]"""); + writer.WriteLine($"""[SkipLocalsInit]"""); + writer.WriteLine($"public static void FromManaged(in {fullyQualifiedTypeName} shader, out ConstantBuffer buffer)"); + + using (writer.WriteBlock()) + { + // Initialize any artificial fields, if needed. This is necessary to avoid compiler errors due to + // the resulting constant buffer not being fully initialized, in case it had some extra fields. + InitializeArtificialFields(info, writer); + + // Generate loading statements for each captured field + foreach (FieldInfo fieldInfo in info.Fields) + { + switch (fieldInfo) + { + case FieldInfo.Primitive primitive: + + // Assign a primitive value + writer.Write($"buffer.{string.Join("_", primitive.FieldPath.Select(static path => path.Name))} = "); + writer.WriteFieldAccessExpression(fieldInfo); + writer.WriteLine(";"); + break; + + case FieldInfo.NonLinearMatrix matrix: + string primitiveTypeName = matrix.ElementName.ToLowerInvariant(); + string matrixHlslTypeName = $"{primitiveTypeName}{matrix.Rows}x{matrix.Columns}"; + string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}"); + string fieldNamePrefix = string.Join("_", matrix.FieldPath.Select(static path => path.Name)); + + // Get a reference to the whole matrix field, just once for all rows + writer.WriteLine(skipIfPresent: true); + writer.Write($"ref {matrixHlslTypeName} __{fieldNamePrefix} = ref "); + writer.WriteFieldAccessExpression(fieldInfo); + writer.WriteLine(";"); + writer.WriteLine(); + + // Assign all rows of a given matrix type + for (int j = 0; j < matrix.Rows; j++) + { + writer.WriteLine($"buffer.{fieldNamePrefix}_{j} = Unsafe.As<{primitiveTypeName}, {rowTypeName}>(ref __{fieldNamePrefix}.M{j + 1}1);"); + } + + writer.WriteLine(); + break; + } + } + } + + // Only generate the other direction if requested + if (ConstantBufferSyntaxProcessor.direction == BindingDirection.TwoWay) + { + // Define the ToManaged method (native constant buffer to managed shader type) + writer.WriteLine(); + writer.WriteLine($"""/// """); + writer.WriteLine($"""/// Marshals native constant buffer data to managed instances."""); + writer.WriteLine($"""/// """); + writer.WriteLine($"""/// The input native constant buffer."""); + writer.WriteLine($"""/// The marshalled instance."""); + writer.WriteLine($"""[MethodImpl(MethodImplOptions.AggressiveInlining)]"""); + writer.WriteLine($"""[SkipLocalsInit]"""); + writer.WriteLine($"public static {fullyQualifiedTypeName} ToManaged(in ConstantBuffer buffer)"); + + using (writer.WriteBlock()) + { + writer.WriteLine($"Unsafe.SkipInit(out {fullyQualifiedTypeName} shader);"); + writer.WriteLine(); + + // Generate loading statements for each captured field + foreach (FieldInfo fieldInfo in info.Fields) + { + switch (fieldInfo) + { + case FieldInfo.Primitive primitive: + + // Read a nested primitive value + writer.WriteFieldAccessExpression(fieldInfo); + writer.WriteLine($" = buffer.{string.Join("_", primitive.FieldPath.Select(static path => path.Name))};"); + break; + + case FieldInfo.NonLinearMatrix matrix: + string primitiveTypeName = matrix.ElementName.ToLowerInvariant(); + string matrixHlslTypeName = $"{primitiveTypeName}{matrix.Rows}x{matrix.Columns}"; + string rowTypeName = HlslKnownTypes.GetMappedName($"ComputeSharp.{matrix.ElementName}{matrix.Columns}"); + string fieldNamePrefix = string.Join("_", matrix.FieldPath.Select(static path => path.Name)); + + // Get a reference to the whole matrix field, just once for all rows + writer.WriteLine(skipIfPresent: true); + writer.Write($"ref {matrixHlslTypeName} __{fieldNamePrefix} = ref "); + writer.WriteFieldAccessExpression(fieldInfo); + writer.WriteLine(";"); + writer.WriteLine(); + + // Read all rows of a given matrix type + for (int j = 0; j < matrix.Rows; j++) + { + writer.WriteLine($"Unsafe.As<{primitiveTypeName}, {rowTypeName}>(ref __{fieldNamePrefix}.M{j + 1}1) = buffer.{fieldNamePrefix}_{j};"); + } + + writer.WriteLine(); + break; + } + } + + writer.WriteLine(skipIfPresent: true); + writer.WriteLine("return shader;"); + } + } + + using ImmutableHashSetBuilder<(string ContainerType, string FieldName)> generatedAccessors = new(); + + // Define all field accessors. Note that these are generated regardless of the accessibility + // of the field they're getting the value for. This simplifies the rest of the code, and allows + // stripping the readonly-ness of the field references, and has no binary size impact anyway. + // This is because the fields are compiled to be exactly equivalent to direct field references. + foreach (FieldInfo fieldInfo in info.Fields) + { + for (int i = 0; i < fieldInfo.FieldPath.Length; i++) + { + FieldPathPart pathPart = fieldInfo.FieldPath[i]; + + // Get the friendly type name for the field: + // - If the part path is a nested struct, the type name is embedded + // - Otherwise, get the correct HLSL mapped type name for the field + string typeName = pathPart switch + { + FieldPathPart.Nested nested => nested.TypeName, + _ => HlslKnownTypes.GetMappedName(fieldInfo.TypeName) + }; + + // Get the friendly type name for the field. If this nested field is the + // first path, then the parent is the shader type itself. Otherwise, the + // container path is the type of the previous containing type of the field. + string containingTypeName = i == 0 + ? fullyQualifiedTypeName + : ((FieldPathPart.Nested)fieldInfo.FieldPath[i - 1]).TypeName; + + // Make sure to skip repeated field accessors. It's possible for some accessors to end up + // being required, in case a shader type had multiple fields of the same nested struct type. + // To avoid so, we just add the containing type and name to an hashset that we update. + if (!generatedAccessors.Add((containingTypeName, pathPart.Name))) + { + continue; + } + + writer.WriteLine(); + + // If there is no unspeakable name, we can reference the field directly. This means we can both + // use that in XML docs to refer to it (and inherit the docs), and we don't need an explicit name. + if (pathPart.UnspeakableName is null) + { + writer.WriteLine($""" + /// + /// The input value. + /// A mutable reference to . + [UnsafeAccessor(UnsafeAccessorKind.Field)] + private static extern ref {typeName} {pathPart.Name}(this ref readonly {containingTypeName} value); + """, isMultiline: true); + } + else + { + writer.WriteLine($""" + /// Gets a reference to the unspeakable field "{pathPart.Name}" of type . + /// The input value. + /// A mutable reference to the unspeakable field "{pathPart.Name}". + [UnsafeAccessor(UnsafeAccessorKind.Field, Name = "{pathPart.UnspeakableName}")] + private static extern ref {typeName} {pathPart.Name}(this ref readonly {containingTypeName} value); + """, isMultiline: true); + } + } + } + } + } + + callbacks.Add(ConstantBufferCallback); + + // Only emit the marshaller type if there are any non artificial fields. + // Otherwise, it's not needed, as there are either just no fields at all, + // or only artificial ones, which would be assigned directly by callers. + if (!info.Fields.IsEmpty) + { + callbacks.Add(ConstantBufferMarshallerCallback); + } + } + + /// + /// Checks whether any artificial fields are present. + /// + /// Whether any artificial fields are present. + private static partial bool HasArtificialFields(); + + /// + /// Appends any artificial fields to the generated constant buffer type. + /// + /// The instance to use to extract info. + /// The instance to write into. + /// This method is responsible for leaving trailing blanklines, if it adds any fields. + static partial void AppendArtificialFields(IConstantBufferInfo info, IndentedTextWriter writer); + + /// + /// Initializes any artificial fields that have been generated into the constant buffer. + /// + /// The instance to use to extract info. + /// The instance to write into. + /// This method is responsible for leaving trailing blanklines, if it emits any statements. + static partial void InitializeArtificialFields(IConstantBufferInfo info, IndentedTextWriter writer); +} + +/// +file static class IndentedTextWriterExtensions +{ + /// + /// Writes the XML summary for a given field. + /// + /// The instance to write into. + /// The input field to write the XML summary for. + /// The fully qualified type name of the containing type. + public static void WriteFieldXmlSummary(this IndentedTextWriter writer, FieldInfo fieldInfo, string fullyQualifiedTypeName) + { + if (fieldInfo.FieldPath[0].UnspeakableName is null) + { + writer.WriteLine($"""/// """); + } + else + { + writer.WriteLine($"""/// The unspeakable field "{fieldInfo.FieldPath[0].Name}" of ."""); + } + } + + /// + /// Writes the XML remarks for a given field, if needed. + /// + /// The instance to write into. + /// The input field to write the XML remarks for, if needed. + /// The row for the field, if this is a matrix type. + public static void WriteFieldXmlRemarks(this IndentedTextWriter writer, FieldInfo fieldInfo, int? row = null) + { + // The remarks are only needed if the field is nested + if (fieldInfo.FieldPath is not [.., FieldPathPart.Nested nested, FieldPathPart.Leaf leaf]) + { + return; + } + + // Write the correct remarks depending on whether the field can be referenced directly + if (leaf.UnspeakableName is null) + { + writer.Write($"""/// Serialized field mapping to"""); + writer.WriteIf(row is not null, $""" row {row} of"""); + writer.WriteLine($""" ."""); + } + else + { + writer.Write($"""/// Serialized field mapping to"""); + writer.WriteIf(row is not null, $""" row {row} of"""); + writer.WriteLine($""" the unspeakable field "{leaf.Name}" of ."""); + } + } + + /// + /// Writes an expression to access a given field. + /// + /// The instance to write into. + /// The input field to write the expression for. + public static void WriteFieldAccessExpression(this IndentedTextWriter writer, FieldInfo fieldInfo) + { + writer.Write("shader"); + + // Invoke all generated field accessors to get to the target field. + // Because they're extension methods, we can chain them sequentially. + // This simplifies the formatting and makes the code easier to read. + foreach (FieldPathPart part in fieldInfo.FieldPath) + { + writer.Write($".{part.Name}()"); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/ConstantBufferSyntaxProcessor.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/ConstantBufferSyntaxProcessor.cs new file mode 100644 index 00000000..3d24fa41 --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/ConstantBufferSyntaxProcessor.cs @@ -0,0 +1,201 @@ +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using System.Text.RegularExpressions; +using ComputeSharp.Core.Helpers; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Mappings; +using ComputeSharp.SourceGeneration.Models; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.SourceGeneration.SyntaxProcessors; + +/// +/// A processor responsible for extracting info and writing syntax for the constant buffer syntax for shader types. +/// +internal static partial class ConstantBufferSyntaxProcessor +{ + /// + /// A to extract the parameter name of a primary constructor capture field. + /// + /// + /// Temporary workaround until is available. + /// + private static readonly Regex PrimaryConstructorNameRegex = new("^<([^>]+)>P$", RegexOptions.Compiled); + + /// + /// Explores a given type hierarchy and generates statements to load fields. + /// + /// The input object currently in use. + /// The current shader type being explored. + /// The size of the shader constant buffer. + /// The sequence of instances for all captured values. + public static void GetInfo( + Compilation compilation, + ITypeSymbol structDeclarationSymbol, + ref int constantBufferSizeInBytes, + out ImmutableArray fields) + { + // Helper method that uses boxes instead of ref-s (illegal in enumerators) + static void GetInfo( + Compilation compilation, + ITypeSymbol currentTypeSymbol, + ImmutableArray fieldPath, + ref int constantBufferSizeInBytes, + ImmutableArrayBuilder fields) + { + bool isFirstField = true; + + foreach (ISymbol memberSymbol in currentTypeSymbol.GetMembers()) + { + // Only process fields of a valid shape/type + if (memberSymbol is not IFieldSymbol { Type: INamedTypeSymbol { IsStatic: false }, IsConst: false, IsStatic: false, IsFixedSizeBuffer: false } fieldSymbol) + { + continue; + } + + // Skip fields of not accessible types (the analyzer will handle this) + if (!fieldSymbol.Type.IsAccessibleFromCompilationAssembly(compilation)) + { + continue; + } + + // Try to get the name to use for the field and the accessor + if (!TryGetFieldAccessorName(fieldSymbol, out string? fieldName, out string? unspeakableName)) + { + continue; + } + + string typeName = fieldSymbol.Type.GetFullyQualifiedMetadataName(); + + // The first item in each nested struct needs to be aligned to 16 bytes + if (isFirstField && fieldPath.Length > 0) + { + constantBufferSizeInBytes = AlignmentHelper.Pad(constantBufferSizeInBytes, 16); + + isFirstField = false; + } + + if (HlslKnownTypes.IsKnownHlslType(typeName)) + { + ImmutableArray nestedFieldPath = fieldPath.Add(new FieldPathPart.Leaf(fieldName, unspeakableName)); + + fields.Add(GetHlslKnownTypeFieldInfo(nestedFieldPath, typeName, ref constantBufferSizeInBytes)); + } + else if (fieldSymbol.Type.IsUnmanagedType) + { + string nestedTypeName = fieldSymbol.Type.GetFullyQualifiedName(includeGlobal: true); + FieldPathPart fieldPathPart = new FieldPathPart.Nested(fieldName, unspeakableName, nestedTypeName); + + // Custom struct type defined by the user + GetInfo(compilation, fieldSymbol.Type, fieldPath.Add(fieldPathPart), ref constantBufferSizeInBytes, fields); + } + } + } + + using ImmutableArrayBuilder fieldBuilder = new(); + + // Traverse all shader fields and gather info, and update the tracking offsets + GetInfo( + compilation, + structDeclarationSymbol, + ImmutableArray.Empty, + ref constantBufferSizeInBytes, + fieldBuilder); + + fields = fieldBuilder.ToImmutable(); + } + + /// + /// Tries to get the field name and the accessor name for a given field. + /// + /// The field symbol to analyze. + /// The name of the field that's referenced in code by users. + /// The real name of the field that should be accessed, when different. + /// Whether the field is supported and the necessary info could be retrieved. + public static bool TryGetFieldAccessorName( + IFieldSymbol fieldSymbol, + [NotNullWhen(true)] out string? referencedName, + out string? unspeakableName) + { + // If the field can be referenced by name, we can just access it directly + if (fieldSymbol.CanBeReferencedByName) + { + referencedName = fieldSymbol.Name; + unspeakableName = null; + + return true; + } + + // If the field is a primary constructor capture field, get the original name + if (PrimaryConstructorNameRegex.Match(fieldSymbol.Name) is { Success: true, Groups: [_, { Value: string parameterName }] }) + { + referencedName = parameterName; + unspeakableName = fieldSymbol.Name; + + return true; + } + + // The field is not recognized, so just invalid + referencedName = null; + unspeakableName = null; + + return false; + } + + /// + /// 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) + { + // For scalar, vector and linear matrix types, serialize the value normally. + // Only the initial alignment needs to be considered, while data is packed. + (int fieldSize, int 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)) + { + using ImmutableArrayBuilder builder = new(); + + 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.ToImmutable()); + } + 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. + int startingRawDataOffset = AlignmentHelper.AlignToBoundary( + AlignmentHelper.Pad(rawDataOffset, fieldPack), + fieldSize, + 16); + + rawDataOffset = startingRawDataOffset + fieldSize; + + return new FieldInfo.Primitive(fieldPath, typeName, startingRawDataOffset); + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.ConstantBuffer.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.ConstantBuffer.cs new file mode 100644 index 00000000..8ec40690 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.ConstantBuffer.cs @@ -0,0 +1,88 @@ +using System.Collections.Immutable; +using ComputeSharp.Core.Helpers; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Models; +using ComputeSharp.SourceGeneration.SyntaxProcessors; +using ComputeSharp.SourceGenerators.Models; +using Microsoft.CodeAnalysis; + +namespace ComputeSharp.SourceGenerators; + +/// +partial class ComputeShaderDescriptorGenerator +{ + /// + /// A helper with all logic to generate the constant buffer marshalling methods and additional types. + /// + private static class ConstantBuffer + { + /// + /// + /// + /// Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture. + /// + /// + public static void GetInfo( + Compilation compilation, + ITypeSymbol structDeclarationSymbol, + bool isPixelShaderLike, + out int constantBufferSizeInBytes, + out ImmutableArray fields) + { + // 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. + constantBufferSizeInBytes = sizeof(int) * (isPixelShaderLike ? 2 : 3); + + ConstantBufferSyntaxProcessor.GetInfo( + compilation, + structDeclarationSymbol, + ref constantBufferSizeInBytes, + out fields); + + // After all the captured fields have been processed, ensure 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. + constantBufferSizeInBytes = AlignmentHelper.Pad(constantBufferSizeInBytes, sizeof(int)); + } + + /// + /// Writes the LoadConstantBuffer 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("[global::System.Runtime.CompilerServices.SkipLocalsInit]"); + writer.WriteLine($"static unsafe void global::ComputeSharp.Descriptors.IComputeShaderDescriptor<{typeName}>.LoadConstantBuffer(in {typeName} shader, ref TLoader loader, int x, int y, int z)"); + + using (writer.WriteBlock()) + { + // If there are no fields (ie. there are only artificial ones), just get an uninitialized instance. + // All fields (ie. the thread size values) will be assigned directly inline, with no marshalling. + if (info.Fields.IsEmpty) + { + writer.WriteLine("global::System.Runtime.CompilerServices.Unsafe.SkipInit(out global::ComputeSharp.Generated.ConstantBuffer buffer);"); + } + else + { + // Otherwise, let the generated marshaller create an initialized instance of the constant buffer type + writer.WriteLine("global::ComputeSharp.Generated.ConstantBufferMarshaller.FromManaged(in shader, out global::ComputeSharp.Generated.ConstantBuffer buffer);"); + } + + // Initialize the artificial fields and finally pass a span over the constant buffer + writer.WriteLine(); + writer.WriteLine("buffer.__x = x;"); + writer.WriteLine("buffer.__y = y;"); + writer.WriteLineIf(!info.IsPixelShaderLike, "buffer.__z = z;"); + writer.WriteLineIf(!info.IsPixelShaderLike); + writer.WriteLine("loader.LoadConstantBuffer(new global::System.ReadOnlySpan(&buffer, sizeof(global::ComputeSharp.Generated.ConstantBuffer)));"); + } + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.DispatchDataLoading.Syntax.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.DispatchDataLoading.Syntax.cs deleted file mode 100644 index ccdd6076..00000000 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.DispatchDataLoading.Syntax.cs +++ /dev/null @@ -1,115 +0,0 @@ -using System.Linq; -using ComputeSharp.SourceGeneration.Extensions; -using ComputeSharp.SourceGeneration.Helpers; -using ComputeSharp.SourceGeneration.Models; -using ComputeSharp.SourceGenerators.Models; - -namespace ComputeSharp.SourceGenerators; - -/// -partial class ComputeShaderDescriptorGenerator -{ - /// - partial class DispatchDataLoading - { - /// - /// Writes the LoadConstantBuffer method. - /// - /// The input instance with gathered shader info. - /// The instance to write into. - public static void WriteLoadConstantBufferSyntax(ShaderInfo info, IndentedTextWriter writer) - { - string typeName = info.Hierarchy.Hierarchy[0].QualifiedName; - - writer.WriteLine("/// "); - writer.WriteGeneratedAttributes(GeneratorName); - writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]"); - writer.WriteLine($"static void global::ComputeSharp.Descriptors.IComputeShaderDescriptor<{typeName}>.LoadConstantBuffer(in {typeName} shader, ref TLoader loader, int x, int y, int z)"); - - using (writer.WriteBlock()) - { - writer.WriteLine($"global::System.Span span = stackalloc byte[{info.ConstantBufferSizeInBytes}];"); - - // Append the statements for the dispatch ranges - writer.WriteLine("global::System.Runtime.CompilerServices.Unsafe.As(ref span[0]) = (uint)x;"); - writer.WriteLine("global::System.Runtime.CompilerServices.Unsafe.As(ref span[4]) = (uint)y;"); - writer.WriteLineIf(!info.IsPixelShaderLike, "global::System.Runtime.CompilerServices.Unsafe.As(ref span[8]) = (uint)z;"); - - // Generate loading statements for each captured field - foreach (FieldInfo fieldInfo in info.Fields) - { - switch (fieldInfo) - { - case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive: - - // Read a boolean value and cast it to Bool first, which will apply the correct size expansion - writer.WriteLine( - $"global::System.Runtime.CompilerServices.Unsafe.As(ref span[{primitive.Offset}]) = " + - $"(global::ComputeSharp.Bool)shader.{string.Join(".", primitive.FieldPath.Select(static path => path.Name))};"); - break; - case FieldInfo.Primitive primitive: - - // Read a primitive value and serialize it into the target buffer - writer.WriteLine( - $"global::System.Runtime.CompilerServices.Unsafe.As(ref span[{primitive.Offset}]) = " + - $"shader.{string.Join(".", primitive.FieldPath.Select(static path => path.Name))};"); - break; - - case FieldInfo.NonLinearMatrix matrix: - string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}"; - string rowLocalName = $"__{string.Join("_", matrix.FieldPath.Select(static path => path.Name))}__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 )); - writer.WriteLine( - $"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(" + - $"ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in shader.{string.Join(".", matrix.FieldPath.Select(static path => path.Name))}));"); - - // 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++) - { - writer.WriteLine( - $"global::System.Runtime.CompilerServices.Unsafe.As(ref span[{matrix.Offsets[j]}]) = " + - $"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j});"); - } - - break; - } - } - - // Load the prepared buffer - writer.WriteLine("loader.LoadConstantBuffer(span);"); - } - } - - /// - /// Writes the LoadGraphicsResources method. - /// - /// The input instance with gathered shader info. - /// The instance to write into. - public static void WriteLoadGraphicsResourcesSyntax(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()) - { - // Generate loading statements for each captured resource - foreach (ResourceInfo resource in info.Resources) - { - writer.WriteLine($"loader.LoadGraphicsResource(shader.{resource.FieldName}, {resource.Offset});"); - } - } - } - } -} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.DispatchDataLoading.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.DispatchDataLoading.cs deleted file mode 100644 index 01105349..00000000 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.DispatchDataLoading.cs +++ /dev/null @@ -1,197 +0,0 @@ -using System; -using System.Collections.Immutable; -using ComputeSharp.Core.Helpers; -using ComputeSharp.SourceGeneration.Extensions; -using ComputeSharp.SourceGeneration.Helpers; -using ComputeSharp.SourceGeneration.Mappings; -using ComputeSharp.SourceGeneration.Models; -using ComputeSharp.SourceGenerators.Models; -using Microsoft.CodeAnalysis; -using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; - -namespace ComputeSharp.SourceGenerators; - -/// -partial class ComputeShaderDescriptorGenerator -{ - /// - /// A helper with all logic to generate the dispatch data loading methods. - /// - private static partial class DispatchDataLoading - { - /// - /// Explores a given type hierarchy and generates statements to load fields. - /// - /// The collection of produced instances. - /// The input object currently in use. - /// The current shader type being explored. - /// Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture. - /// The size of the shader constant buffer. - /// The total number of captured resources in the shader. - /// The sequence of instances for all captured values. - /// The sequence of instances for all captured resources. - public static void GetInfo( - ImmutableArrayBuilder diagnostics, - Compilation compilation, - ITypeSymbol structDeclarationSymbol, - bool isPixelShaderLike, - out int constantBufferSizeInBytes, - out int resourceCount, - out ImmutableArray fields, - out ImmutableArray resources) - { - static void GetInfo( - Compilation compilation, - ITypeSymbol currentTypeSymbol, - ImmutableArray fieldPath, - ref int resourceOffset, - ref int rawDataOffset, - ImmutableArrayBuilder fields, - ImmutableArrayBuilder resources) - { - bool isFirstField = true; - - foreach (ISymbol memberSymbol in currentTypeSymbol.GetMembers()) - { - // Only process fields - if (memberSymbol is not IFieldSymbol { Type: INamedTypeSymbol { IsStatic: false }, IsConst: false, IsStatic: false, IsFixedSizeBuffer: false, IsImplicitlyDeclared: false } fieldSymbol) - { - continue; - } - - // Skip fields of not accessible types (the analyzer will handle this) - if (!fieldSymbol.Type.IsAccessibleFromCompilationAssembly(compilation)) - { - continue; - } - - string fieldName = fieldSymbol.Name; - string typeName = fieldSymbol.Type.GetFullyQualifiedMetadataName(); - - // The first item in each nested struct needs to be aligned to 16 bytes - if (isFirstField && fieldPath.Length > 0) - { - rawDataOffset = AlignmentHelper.Pad(rawDataOffset, 16); - - isFirstField = false; - } - - if (HlslKnownTypes.IsTypedResourceType(typeName)) - { - resources.Add(new ResourceInfo(fieldName, typeName, resourceOffset++)); - } - else if (HlslKnownTypes.IsKnownHlslType(typeName)) - { - // TODO: share the logic and fix the field path parts - fields.Add(GetHlslKnownTypeFieldInfo(fieldPath.Add(new FieldPathPart.Leaf(fieldName, null)), typeName, ref rawDataOffset)); - } - else if (fieldSymbol.Type.IsUnmanagedType) - { - // Custom struct type defined by the user - GetInfo(compilation, fieldSymbol.Type, fieldPath.Add(new FieldPathPart.Leaf(fieldName, null)), ref resourceOffset, ref rawDataOffset, fields, resources); - } - } - } - - // 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. - int rawDataOffset = sizeof(int) * (isPixelShaderLike ? 2 : 3); - int resourceOffset = 0; - - using (ImmutableArrayBuilder fieldBuilder = new()) - using (ImmutableArrayBuilder resourceBuilder = new()) - { - // Traverse all shader fields and gather info, and update the tracking offsets - GetInfo( - compilation, - structDeclarationSymbol, - ImmutableArray.Empty, - ref resourceOffset, - ref rawDataOffset, - fieldBuilder, - resourceBuilder); - - resourceCount = resourceOffset; - fields = fieldBuilder.ToImmutable(); - resources = resourceBuilder.ToImmutable(); - } - - // After all the captured fields have been processed, ensure 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. - constantBufferSizeInBytes = AlignmentHelper.Pad(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 root32BitConstantCount = (constantBufferSizeInBytes / sizeof(int)) + resourceCount; - - if (root32BitConstantCount > 64) - { - diagnostics.Add(ShaderDispatchDataSizeExceeded, structDeclarationSymbol, structDeclarationSymbol); - } - } - - /// - /// 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) - { - // For scalar, vector and linear matrix types, serialize the value normally. - // Only the initial alignment needs to be considered, while data is packed. - (int fieldSize, int 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)) - { - using ImmutableArrayBuilder builder = new(); - - 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.ToImmutable()); - } - 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. - int startingRawDataOffset = AlignmentHelper.AlignToBoundary( - AlignmentHelper.Pad(rawDataOffset, fieldPack), - fieldSize, - 16); - - rawDataOffset = startingRawDataOffset + fieldSize; - - return new FieldInfo.Primitive(fieldPath, typeName, startingRawDataOffset); - } - } - } -} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.Syntax.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.Syntax.cs index c8a1a0ca..a081e890 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.Syntax.cs @@ -16,7 +16,7 @@ partial class ComputeShaderDescriptorGenerator /// /// The input instance with gathered shader info. /// The instance to write into. - public static void WriteHlslBytecodeSyntax(ShaderInfo info, IndentedTextWriter writer) + public static void WriteSyntax(ShaderInfo info, IndentedTextWriter writer) { writer.WriteLine("/// "); writer.WriteGeneratedAttributes(GeneratorName); diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs new file mode 100644 index 00000000..065b7544 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.Resources.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Immutable; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Mappings; +using ComputeSharp.SourceGeneration.Models; +using ComputeSharp.SourceGenerators.Models; +using Microsoft.CodeAnalysis; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; + +namespace ComputeSharp.SourceGenerators; + +/// +partial class ComputeShaderDescriptorGenerator +{ + /// + /// A helper with all logic to generate the resources loading code. + /// + private static class Resources + { + /// + /// Explores a given type hierarchy and generates statements to load fields. + /// + /// The collection of produced instances. + /// The input object currently in use. + /// The current shader type being explored. + /// The size of the shader constant buffer. + /// The sequence of instances for all captured resources. + public static void GetInfo( + ImmutableArrayBuilder diagnostics, + Compilation compilation, + ITypeSymbol structDeclarationSymbol, + int constantBufferSizeInBytes, + out ImmutableArray resources) + { + using ImmutableArrayBuilder resourceBuilder = new(); + + 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) + { + continue; + } + + // Skip fields of not accessible types (the analyzer will handle this just like other fields) + if (!fieldSymbol.Type.IsAccessibleFromCompilationAssembly(compilation)) + { + continue; + } + + string fieldName = fieldSymbol.Name; + 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)); + } + } + + resources = resourceBuilder.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: + // - 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. + if ((constantBufferSizeInBytes / sizeof(int)) + resourceBuilder.Count > 64) + { + 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()) + { + // Generate loading statements for each captured resource + for (int i = 0; i < info.Resources.Length; i++) + { + writer.WriteLine($"loader.LoadGraphicsResource(shader.{info.Resources[i].FieldName}, {i});"); + } + } + } + } +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs index 7de05e5b..37da4b50 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs @@ -1,8 +1,10 @@ using System.Collections.Immutable; +using System.ComponentModel; using System.Linq; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; +using ComputeSharp.SourceGeneration.SyntaxProcessors; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -58,14 +60,21 @@ public sealed partial class ComputeShaderDescriptorGenerator : IIncrementalGener using ImmutableArrayBuilder diagnostics = new(); // Get the fields info - DispatchDataLoading.GetInfo( - diagnostics, + ConstantBuffer.GetInfo( context.SemanticModel.Compilation, typeSymbol, isPixelShaderLike, out int constantBufferSizeInBytes, - out int resourceCount, - out ImmutableArray fieldInfos, + out ImmutableArray fieldInfos); + + token.ThrowIfCancellationRequested(); + + // Get the resources info + Resources.GetInfo( + diagnostics, + context.SemanticModel.Compilation, + typeSymbol, + constantBufferSizeInBytes, out ImmutableArray resourceInfo); token.ThrowIfCancellationRequested(); @@ -129,7 +138,6 @@ public sealed partial class ComputeShaderDescriptorGenerator : IIncrementalGener IsPixelShaderLike: isPixelShaderLike, IsSamplerUsed: isSamplerUsed, ConstantBufferSizeInBytes: constantBufferSizeInBytes, - ResourceCount: resourceCount, Fields: fieldInfos, Resources: resourceInfo, ResourceDescriptors: resourceDescriptors, @@ -158,13 +166,14 @@ public sealed partial class ComputeShaderDescriptorGenerator : IIncrementalGener declaredMembers.Add(MetadataProperties.WriteIsStaticSamplerRequiredSyntax); declaredMembers.Add(ResourceDescriptorRanges.WriteSyntax); declaredMembers.Add(HlslSource.WriteSyntax); - declaredMembers.Add(HlslBytecode.WriteHlslBytecodeSyntax); - declaredMembers.Add(DispatchDataLoading.WriteLoadConstantBufferSyntax); - declaredMembers.Add(DispatchDataLoading.WriteLoadGraphicsResourcesSyntax); + declaredMembers.Add(HlslBytecode.WriteSyntax); + declaredMembers.Add(ConstantBuffer.WriteSyntax); + declaredMembers.Add(Resources.WriteSyntax); using ImmutableArrayBuilder> additionalTypes = new(); using ImmutableHashSetBuilder usingDirectives = new(); + ConstantBufferSyntaxProcessor.RegisterAdditionalTypesSyntax(GeneratorName, BindingDirection.OneWay, item, additionalTypes, usingDirectives); ResourceDescriptorRanges.RegisterAdditionalDataMemberSyntax(item, additionalTypes, usingDirectives); HlslBytecode.RegisterAdditionalTypeSyntax(item, additionalTypes, usingDirectives); diff --git a/src/ComputeSharp.SourceGenerators/Models/ResourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/ResourceInfo.cs index 49fc0c32..dab66a81 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 full metadata name for the resource type. -/// The offset for the resource within the root signature. -public sealed record ResourceInfo(string FieldName, string TypeName, int Offset); \ No newline at end of file +public sealed record ResourceInfo(string FieldName, string TypeName); \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs b/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs index 68909fb9..c2617537 100644 --- a/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs @@ -13,7 +13,6 @@ namespace ComputeSharp.SourceGenerators.Models; /// Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture. /// Whether or not the static sampler is used. /// The size of the shader constant buffer. -/// The total number of captured resources in the shader. /// The description on shader instance fields. /// The description on shader captured resources. /// The sequence of resource descriptors for the shader. @@ -28,10 +27,9 @@ internal sealed record ShaderInfo( bool IsPixelShaderLike, bool IsSamplerUsed, int ConstantBufferSizeInBytes, - int ResourceCount, EquatableArray Fields, EquatableArray Resources, EquatableArray ResourceDescriptors, HlslBytecodeInfoKey HlslInfoKey, HlslBytecodeInfo HlslInfo, - EquatableArray Diagnostcs); \ No newline at end of file + EquatableArray Diagnostcs) : IConstantBufferInfo; \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/SyntaxProcessors/ConstantBufferSyntaxProcessor.ArtificialFields.cs b/src/ComputeSharp.SourceGenerators/SyntaxProcessors/ConstantBufferSyntaxProcessor.ArtificialFields.cs new file mode 100644 index 00000000..0b87fada --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/SyntaxProcessors/ConstantBufferSyntaxProcessor.ArtificialFields.cs @@ -0,0 +1,53 @@ +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Models; +using ComputeSharp.SourceGenerators.Models; + +namespace ComputeSharp.SourceGeneration.SyntaxProcessors; + +/// +partial class ConstantBufferSyntaxProcessor +{ + /// + private static partial bool HasArtificialFields() + { + return true; + } + + /// + static partial void AppendArtificialFields(IConstantBufferInfo info, IndentedTextWriter writer) + { + // The X and Y axes are always present + writer.WriteLine(""" + /// The artificial field backing . + [FieldOffset(0)] + public int __x; + + /// The artificial field backing . + [FieldOffset(4)] + public int __y; + """, isMultiline: true); + + // The Z axis is only present for non pixel-shader-like compute shaders + writer.WriteLineIf(!((ShaderInfo)info).IsPixelShaderLike); + writer.WriteLineIf( + condition: !((ShaderInfo)info).IsPixelShaderLike, + """ + /// The artificial field backing . + [FieldOffset(8)] + public int __z; + """, isMultiline: true); + + // Leave a trailing blank line if the shader has any fields + writer.WriteLineIf(!info.Fields.IsEmpty); + } + + /// + static partial void InitializeArtificialFields(IConstantBufferInfo info, IndentedTextWriter writer) + { + // Ignore the artificial fields (they will be set separately) + writer.WriteLine("Unsafe.SkipInit(out buffer.__x);"); + writer.WriteLine("Unsafe.SkipInit(out buffer.__y);"); + writer.WriteLineIf(!((ShaderInfo)info).IsPixelShaderLike, "Unsafe.SkipInit(out buffer.__z);"); + writer.WriteLineIf(!info.Fields.IsEmpty); + } +} \ No newline at end of file diff --git a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs index 79a8b2a8..bd9ad46b 100644 --- a/tests/ComputeSharp.Tests/ShaderCompilerTests.cs +++ b/tests/ComputeSharp.Tests/ShaderCompilerTests.cs @@ -293,7 +293,7 @@ namespace ComputeSharp.Tests static int C() => 1; - int D() => A() + E() + F(); + public int D() => A() + E() + F(); int E() => 1; diff --git a/tests/ComputeSharp.Tests/Shaders/Compute/TriangleGridContouring.cs b/tests/ComputeSharp.Tests/Shaders/Compute/TriangleGridContouring.cs index de1e0b2c..f75fb189 100644 --- a/tests/ComputeSharp.Tests/Shaders/Compute/TriangleGridContouring.cs +++ b/tests/ComputeSharp.Tests/Shaders/Compute/TriangleGridContouring.cs @@ -31,12 +31,6 @@ internal readonly partial struct TriangleGridContouring : IComputeShader return new(c, -s, s, c); } - // IQ's float2 to float hash. - private static float Hash21(float2 p) - { - return Hlsl.Frac(Hlsl.Sin(Hlsl.Dot(p, new float2(27.619f, 57.583f))) * 43758.5453f); - } - // float2 to float2 hash. private float2 Hash22(float2 p) {