diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.Syntax.cs index 2f65635c..4dc54c8a 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.Syntax.cs @@ -2,6 +2,7 @@ using System.Linq; using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; namespace ComputeSharp.D2D1.SourceGenerators; diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.cs index 087ef987..496d9798 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.cs @@ -148,7 +148,7 @@ partial class D2DPixelShaderDescriptorGenerator /// /// The instance for the shader to compile. /// The used to cancel the operation, if needed. - /// + /// The instance for the current shader. public static HlslBytecodeInfo GetInfo(ref HlslBytecodeInfoKey key, CancellationToken token) { static unsafe HlslBytecodeInfo GetInfo(HlslBytecodeInfoKey key, CancellationToken token) @@ -188,7 +188,7 @@ partial class D2DPixelShaderDescriptorGenerator } catch (FxcCompilationException e) { - return new HlslBytecodeInfo.FxcError(D3DCompiler.PrettifyFxcErrorMessage(e.Message)); + return new HlslBytecodeInfo.CompilerError(D3DCompiler.PrettifyFxcErrorMessage(e.Message)); } } @@ -218,7 +218,7 @@ partial class D2DPixelShaderDescriptorGenerator structDeclarationSymbol, new object[] { structDeclarationSymbol, win32Error.HResult, win32Error.Message }); } - else if (info is HlslBytecodeInfo.FxcError fxcError) + else if (info is HlslBytecodeInfo.CompilerError fxcError) { diagnostic = DiagnosticInfo.Create( EmbeddedBytecodeFailedWithFxcCompilationException, diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs index 3a1e4bc1..813e40ac 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs @@ -142,7 +142,7 @@ partial class D2DPixelShaderSourceGenerator methodSymbol, new object[] { methodSymbol, methodSymbol.ContainingType, win32Error.HResult, win32Error.Message }); } - else if (info is HlslBytecodeInfo.FxcError fxcError) + else if (info is HlslBytecodeInfo.CompilerError fxcError) { diagnostic = DiagnosticInfo.Create( D2DPixelShaderSourceCompilationFailedWithFxcCompilationException, diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems index f6f89407..f8c64c28 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems +++ b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems @@ -14,7 +14,6 @@ - @@ -22,6 +21,7 @@ + diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs index adb62bf4..7d630da4 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs @@ -91,28 +91,4 @@ internal static class SyntaxFormattingHelper span = span.Slice(6); } } - - /// - /// Creates a formatted expression to initialize a with a given content. - /// - /// The input byte content to serialize. - /// A formatted with the specified data. - /// - /// This function will produce raw byte initialization expressions, such as: - /// [1, 2, 3, 4, 5] => 0x01, 0x02, 0x03, 0x04, 0x05. - /// - public static string BuildByteArrayInitializationExpressionString(ReadOnlySpan bytecode) - { - using ImmutableArrayBuilder builder = new(); - - builder.AddRange(FormattedBytes[bytecode[0]].AsSpan()); - - foreach (byte b in bytecode.Slice(1)) - { - builder.AddRange(", ".AsSpan()); - builder.AddRange(FormattedBytes[b].AsSpan()); - } - - return builder.ToString(); - } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxTokenHelper.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxTokenHelper.cs deleted file mode 100644 index 8210504c..00000000 --- a/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxTokenHelper.cs +++ /dev/null @@ -1,33 +0,0 @@ -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -namespace ComputeSharp.SourceGeneration.Helpers; - -/// -/// Helpers to create and work with -s. -/// -internal static class SyntaxTokenHelper -{ - /// - /// Creates a representing a raw multiline string literal with the given text. - /// - /// The text to use for the created raw multiline string literal token. - /// The current indentation level to use. - /// A representing a raw multiline string literal with the value of . - public static SyntaxToken CreateRawMultilineStringLiteral(string text, int indentationLevel) - { - // Create a token to represent the raw multiline string literal expression. An extra newline and indentation - // has to be added to the raw text when there is no trailing newline, as not doing so would otherwise case - // the terminating """ token to fall on the same line, which is invalid syntax. This is only needed to make - // the code valid, as the actual literal context of the string is not affected and remains the same. - string indentation = new(' ', 4 * indentationLevel); - - return Token( - TriviaList(), - SyntaxKind.MultiLineRawStringLiteralToken, - $"\"\"\"\n{indentation}{text.Replace("\n", $"\n{indentation}")}{(text.EndsWith("\n") ? "" : $"\n{indentation}")}\"\"\"", - text, - TriviaList()); - } -} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslBytecodeInfo.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Models/HlslBytecodeInfo.cs similarity index 86% rename from src/ComputeSharp.D2D1.SourceGenerators/Models/HlslBytecodeInfo.cs rename to src/ComputeSharp.SourceGeneration.Hlsl/Models/HlslBytecodeInfo.cs index fc547efe..cb8b9bba 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/HlslBytecodeInfo.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Models/HlslBytecodeInfo.cs @@ -1,6 +1,6 @@ using ComputeSharp.SourceGeneration.Helpers; -namespace ComputeSharp.D2D1.SourceGenerators.Models; +namespace ComputeSharp.SourceGeneration.Models; /// /// A model representing info on compiled HLSL bytecode, if available. @@ -21,10 +21,10 @@ internal abstract record HlslBytecodeInfo public sealed record Win32Error(int HResult, string Message) : HlslBytecodeInfo; /// - /// An HLSL shader that failed to compile due to an FXC compiler error. + /// An HLSL shader that failed to compile due to a compiler error. /// /// The error message from compiling the shader. - public sealed record FxcError(string Message) : HlslBytecodeInfo; + public sealed record CompilerError(string Message) : HlslBytecodeInfo; /// /// No HLSL bytecode is available (ie. compilation was not requested or some other error was detected). diff --git a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems index 413e50cc..3dc0426f 100644 --- a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems +++ b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems @@ -26,7 +26,6 @@ - diff --git a/src/ComputeSharp.SourceGeneration/Extensions/CompilationExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/CompilationExtensions.cs index 0c10fb39..364a639a 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/CompilationExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/CompilationExtensions.cs @@ -55,46 +55,4 @@ internal static class CompilationExtensions { return compilation.Options is CSharpCompilationOptions { AllowUnsafe: true }; } - - /// - /// - /// Checks whether or not a type with a specified metadata name is accessible from a given instance. - /// - /// - /// This method enumerates candidate type symbols to find a match in the following order: - /// - /// - /// If only one type with the given name is found within the compilation and its referenced assemblies, check its accessibility. - /// - /// - /// If the current defines the symbol, check its accessibility. - /// - /// - /// Otherwise, check whether the type exists and is accessible from any of the referenced assemblies. - /// - /// - /// - /// - /// The to consider for analysis. - /// The fully-qualified metadata type name to find. - /// Whether a type with the specified metadata name can be accessed from the given compilation. - public static bool HasAccessibleTypeWithMetadataName(this Compilation compilation, string fullyQualifiedMetadataName) - { - // If there is only a single matching symbol, check its accessibility - if (compilation.GetTypeByMetadataName(fullyQualifiedMetadataName) is INamedTypeSymbol typeSymbol) - { - return compilation.IsSymbolAccessibleWithin(typeSymbol, compilation.Assembly); - } - - // Otherwise, check all available types - foreach (INamedTypeSymbol currentTypeSymbol in compilation.GetTypesByMetadataName(fullyQualifiedMetadataName)) - { - if (compilation.IsSymbolAccessibleWithin(currentTypeSymbol, compilation.Assembly)) - { - return true; - } - } - - return false; - } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs index 033be458..f5aadb9b 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/DiagnosticsExtensions.cs @@ -41,16 +41,6 @@ internal static class DiagnosticsExtensions diagnostics.Add(DiagnosticInfo.Create(descriptor, node, args)); } - /// - /// Registers an output node into an to output diagnostics. - /// - /// The input instance. - /// The input sequence of diagnostics. - public static void ReportDiagnostics(this IncrementalGeneratorInitializationContext context, IncrementalValuesProvider diagnostics) - { - context.RegisterSourceOutput(diagnostics, static (context, diagnostic) => context.ReportDiagnostic(diagnostic.ToDiagnostic())); - } - /// /// Registers an output node into an to output diagnostics. /// diff --git a/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs b/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs index 262e6aa2..41770120 100644 --- a/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs +++ b/src/ComputeSharp.SourceGeneration/Extensions/IndentedTextWriterExtensions.cs @@ -1,4 +1,5 @@ using System; +using System.Runtime.CompilerServices; using ComputeSharp.SourceGeneration.Helpers; namespace ComputeSharp.SourceGeneration.Extensions; @@ -52,6 +53,37 @@ internal static class IndentedTextWriterExtensions } } + /// + /// Writes a new line into the target writer depending on an input condition. + /// + /// The instance to write into. + /// The content to write. + /// The condition to use to decide whether or not to write a new line. + public static void WriteLineIf(this IndentedTextWriter writer, string content, bool condition) + { + if (condition) + { + writer.WriteLine(content); + } + } + + /// + /// Writes a new line into the target writer depending on an input condition. + /// + /// The instance to write into. + /// The interpolated string handler with content to write. + /// The condition to use to decide whether or not to write a new line. + public static void WriteLineIf( + this IndentedTextWriter writer, + [InterpolatedStringHandlerArgument(nameof(writer))] ref IndentedTextWriter.WriteInterpolatedStringHandler handler, + bool condition) + { + if (condition) + { + writer.WriteLine(ref handler); + } + } + /// /// Writes a series of members separated by one line between each of them. /// diff --git a/src/ComputeSharp.SourceGeneration/Models/DeferredDiagnosticInfo.cs b/src/ComputeSharp.SourceGeneration/Models/DeferredDiagnosticInfo.cs deleted file mode 100644 index a88117ba..00000000 --- a/src/ComputeSharp.SourceGeneration/Models/DeferredDiagnosticInfo.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Collections.Immutable; -using System.Linq; -using ComputeSharp.SourceGeneration.Helpers; -using Microsoft.CodeAnalysis; - -namespace ComputeSharp.SourceGeneration.Models; - -/// -/// A model for a serializeable diagnostic info to be reconstructed later in a pipeline. -/// -/// The wrapped instance. -/// The diagnostic arguments. -internal sealed record DeferredDiagnosticInfo(DiagnosticDescriptor Descriptor, EquatableArray Arguments) -{ - /// - /// Creates a new instance with the specified parameters. - /// - /// The input for the diagnostics to create. - /// The optional arguments for the formatted message to include. - /// A new instance with the specified parameters. - public static DeferredDiagnosticInfo Create(DiagnosticDescriptor descriptor, params object[] args) - { - return new(descriptor, args.Select(static arg => arg.ToString()).ToImmutableArray()); - } -} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGeneration/Models/DiagnosticInfo.cs b/src/ComputeSharp.SourceGeneration/Models/DiagnosticInfo.cs index e7009ff6..de3ae0ed 100644 --- a/src/ComputeSharp.SourceGeneration/Models/DiagnosticInfo.cs +++ b/src/ComputeSharp.SourceGeneration/Models/DiagnosticInfo.cs @@ -13,7 +13,11 @@ namespace ComputeSharp.SourceGeneration.Models; /// The tree to use as location for the diagnostic, if available. /// The span to use as location for the diagnostic. /// The diagnostic arguments. -internal sealed record DiagnosticInfo(DiagnosticDescriptor Descriptor, SyntaxTree? SyntaxTree, TextSpan TextSpan, EquatableArray Arguments) +internal sealed record DiagnosticInfo( + DiagnosticDescriptor Descriptor, + SyntaxTree? SyntaxTree, + TextSpan TextSpan, + EquatableArray Arguments) { /// /// Creates a new instance with the state from this model. diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs index cf9d323a..1f86db7d 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.Syntax.cs @@ -1,12 +1,6 @@ -using ComputeSharp.__Internals; +using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGenerators.Models; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 namespace ComputeSharp.SourceGenerators; @@ -17,36 +11,25 @@ partial class IShaderGenerator partial class BuildHlslSource { /// - /// Creates a instance for the BuildHlslSource method. + /// Writes the BuildHlslSource method. /// - /// The input instance to use. - /// The depth of the hierarchy for this type (used to calculate the right indentation). - /// The resulting instance for the BuildHlslSource method. - public static MethodDeclarationSyntax GetSyntax(HlslShaderSourceInfo hlslSourceInfo, int hierarchyDepth) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(ShaderInfo info, IndentedTextWriter writer) { - // The indentation level is the current depth + 2 (the method, and the return expression) - SyntaxToken hlslSourceLiteralExpression = SyntaxTokenHelper.CreateRawMultilineStringLiteral(hlslSourceInfo.HlslSource, hierarchyDepth + 2); + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(GeneratorName); + writer.WriteLine("readonly void global::ComputeSharp.__Internals.IShader.BuildHlslSource(out string hlslSource)"); - // This code produces a method declaration as follows: - // - // readonly void global::ComputeSharp.__Internals.IShader.BuildHlslSource(out string hlslSource) - // { - // hlslSource = ; - // } - return - MethodDeclaration( - PredefinedType(Token(SyntaxKind.VoidKeyword)), - Identifier("BuildHlslSource")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .AddParameterListParameters( - Parameter(Identifier("hlslSource")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(PredefinedType(Token(SyntaxKind.StringKeyword)))) - .WithBody(Block( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - IdentifierName("hlslSource"), - LiteralExpression(SyntaxKind.StringLiteralExpression, hlslSourceLiteralExpression))))); + using (writer.WriteBlock()) + { + writer.WriteLine("hlslSource ="); + writer.IncreaseIndent(); + writer.WriteLine("\"\"\""); + writer.Write(info.HlslInfoKey.HlslSource, isMultiline: true); + writer.WriteLine("\"\"\";"); + writer.DecreaseIndent(); + } } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs index 80ab5c6c..92d1d182 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateBuildHlslSourceMethod.cs @@ -7,7 +7,6 @@ using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Mappings; using ComputeSharp.SourceGeneration.Models; using ComputeSharp.SourceGeneration.SyntaxRewriters; -using ComputeSharp.SourceGenerators.Models; using ComputeSharp.SourceGenerators.SyntaxRewriters; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -32,16 +31,23 @@ partial class IShaderGenerator /// The input object currently in use. /// The node to process. /// The for . - /// The info on the shader thread count size to use. + /// The thread ids value for the X axis. + /// The thread ids value for the Y axis. + /// The thread ids value for the Z axis. /// Indicates whether the current shader uses an implicit texture. - /// The resulting info on the processed shader. - public static HlslShaderSourceInfo GetInfo( + /// Whether or not the static sampler is used. + /// The resulting HLSL source for the current shader. + public static void GetInfo( ImmutableArrayBuilder diagnostics, Compilation compilation, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol, - ThreadIdsInfo threadIds, - out bool isImplicitTextureUsed) + int threadsX, + int threadsY, + int threadsZ, + out bool isImplicitTextureUsed, + out bool isSamplerUsed, + out string hlslSource) { // Detect invalid properties DetectAndReportInvalidPropertyDeclarations(diagnostics, structDeclarationSymbol); @@ -65,7 +71,7 @@ partial class IShaderGenerator string? implicitTextureType = isComputeShader ? null : HlslKnownTypes.GetMappedNameForPixelShaderType(pixelShaderSymbol!); (ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields, ImmutableArray<(string Name, string HlslType)> valueFields) = GetInstanceFields(diagnostics, structDeclarationSymbol, discoveredTypes, isComputeShader); ImmutableArray<(string Name, string Type, int? Count)> sharedBuffers = GetSharedBuffers(diagnostics, structDeclarationSymbol, discoveredTypes); - (string entryPoint, ImmutableArray<(string Signature, string Definition)> processedMethods, bool isSamplerUsed) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, instanceMethods, constantDefinitions, isComputeShader); + (string entryPoint, ImmutableArray<(string Signature, string Definition)> processedMethods, isSamplerUsed) = GetProcessedMethods(diagnostics, structDeclaration, structDeclarationSymbol, semanticModelProvider, discoveredTypes, staticMethods, instanceMethods, constantDefinitions, isComputeShader); (string, string)? implicitSamplerField = isSamplerUsed ? ("SamplerState", "__sampler") : default((string, string)?); ImmutableArray<(string Name, string TypeDeclaration, string? Assignment)> staticFields = GetStaticFields(diagnostics, semanticModelProvider, structDeclaration, structDeclarationSymbol, discoveredTypes, constantDefinitions); @@ -77,8 +83,10 @@ partial class IShaderGenerator isImplicitTextureUsed = implicitTextureType is not null; // Get the HLSL source data with the intermediate info - return GetHlslSourceInfo( - threadIds, + hlslSource = GetHlslSourceInfo( + threadsX, + threadsY, + threadsZ, definedConstants, declaredTypes, resourceFields, @@ -544,7 +552,9 @@ partial class IShaderGenerator /// /// Produces the series of statements to build the current HLSL source. /// - /// The info on the shader thread count size to use. + /// The thread ids value for the X axis. + /// The thread ids value for the Y axis. + /// The thread ids value for the Z axis. /// The sequence of defined constants for the shader. /// The sequence of declared types used by the shader. /// The sequence of resource instance fields for the current shader. @@ -556,9 +566,11 @@ partial class IShaderGenerator /// The type of the implicit target texture, if present. /// Whether the static sampler is used by the shader. /// The body of the entry point of the shader. - /// The series of statements to build the HLSL source to compile to execute the current shader. - private static HlslShaderSourceInfo GetHlslSourceInfo( - ThreadIdsInfo threadIds, + /// The HLSL source for the current shader. + private static string GetHlslSourceInfo( + int threadsX, + int threadsY, + int threadsZ, ImmutableArray<(string Name, string Value)> definedConstants, ImmutableArray<(string Name, string Definition)> declaredTypes, ImmutableArray<(string MetadataName, string Name, string HlslType)> resourceFields, @@ -578,11 +590,6 @@ partial class IShaderGenerator hlslBuilder.Add('\n'); } - void AppendLine(string text) - { - hlslBuilder.AddRange(text.AsSpan()); - } - void AppendLineAndLF(string text) { hlslBuilder.AddRange(text.AsSpan()); @@ -613,12 +620,9 @@ partial class IShaderGenerator // Group size constants AppendLF(); - AppendLine("#define __GroupSize__get_X "); - AppendLineAndLF(threadIds.X.ToString()); - AppendLine("#define __GroupSize__get_Y "); - AppendLineAndLF(threadIds.Y.ToString()); - AppendLine("#define __GroupSize__get_Z "); - AppendLineAndLF(threadIds.Z.ToString()); + AppendLineAndLF($"#define __GroupSize__get_X {threadsX}"); + AppendLineAndLF($"#define __GroupSize__get_Y {threadsY}"); + AppendLineAndLF($"#define __GroupSize__get_Z {threadsZ}"); // Define declarations foreach ((string name, string value) in definedConstants) @@ -740,9 +744,7 @@ partial class IShaderGenerator AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]"); AppendLineAndLF(executeMethod); - string hlslSource = FlushText(); - - return new(hlslSource, isSamplerUsed); + return FlushText(); } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs index 9538ffb4..1fef76ce 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs @@ -1,15 +1,7 @@ -using System; -using System.Text; -using ComputeSharp.__Internals; +using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Models; using ComputeSharp.SourceGenerators.Models; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Text; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 namespace ComputeSharp.SourceGenerators; @@ -20,120 +12,38 @@ partial class IShaderGenerator partial class LoadBytecode { /// - /// Creates a instance for the TryGetBytecode method. + /// Writes the LoadBytecode method. /// - /// The input instance. - /// An opaque instance to transform the final tree into text. - /// The resulting instance for the BuildHlslSource method. - public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeInfo bytecodeInfo, out Func fixup) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(ShaderInfo info, IndentedTextWriter writer) { - BlockSyntax block = GetShaderBytecodeBody(bytecodeInfo, out string? bytecodeLiterals); + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(GeneratorName); + writer.WriteLine("readonly void global::ComputeSharp.__Internals.IShader.LoadBytecode(ref TLoader loader, int threadsX, int threadsY, int threadsZ)"); - if (bytecodeLiterals is not null) + using (writer.WriteBlock()) { - fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals), Encoding.UTF8); + // If there is no HLSL bytecode, there's nothing left to do + if (info.HlslInfo is not HlslBytecodeInfo.Success success) + { + return; + } + + // Check that the [numthreads] values match + writer.WriteLine($"if (threadsX == {info.ThreadsX} && threadsY == {info.ThreadsY} && threadsZ == {info.ThreadsZ})"); + + using (writer.WriteBlock()) + { + writer.Write("global::System.ReadOnlySpan bytecode = new byte[] { "); + + SyntaxFormattingHelper.WriteByteArrayInitializationExpressions(success.Bytecode.AsSpan(), writer); + + writer.WriteLine(" };"); + writer.WriteLine(); + writer.WriteLine("loader.LoadEmbeddedBytecode(bytecode);"); + } } - else - { - fixup = static tree => tree.GetText(Encoding.UTF8); - } - - // This code produces a method declaration as follows: - // - // readonly void global::ComputeSharp.__Internals.IShader.LoadBytecode(ref TLoader loader, int threadsX, int threadsY, int threadsZ) - // { - // - // } - return - MethodDeclaration( - PredefinedType(Token(SyntaxKind.VoidKeyword)), - Identifier("LoadBytecode")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .AddTypeParameterListParameters(TypeParameter(Identifier("TLoader"))) - .AddParameterListParameters( - Parameter(Identifier("loader")) - .AddModifiers(Token(SyntaxKind.RefKeyword)) - .WithType(IdentifierName("TLoader")), - Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) - .WithBody(block); - } - - /// - /// Gets a instance with the logic to try to get a compiled shader bytecode. - /// - /// The input instance. - /// The resulting bytecode literals to insert into the final source code. - /// The instance trying to retrieve the precompiled shader. - private static unsafe BlockSyntax GetShaderBytecodeBody(EmbeddedBytecodeInfo bytecodeInfo, out string? bytecodeLiterals) - { - if (bytecodeInfo.Bytecode.IsEmpty) - { - bytecodeLiterals = null; - - // Faulting path - return Block(); - } - - bytecodeLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(bytecodeInfo.Bytecode.AsSpan()); - - // This code produces a branch as follows: - // - // if (threadsX == && threadsY == && threadsZ == ) - // { - // global::System.ReadOnlySpan bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE }; - // loader.LoadEmbeddedBytecode(bytecode); - // } - // - // Note that the __EMBEDDED_SHADER_BYTECODE identifier will be replaced after the string - // is created by the generator. This greatly speeds up the code generation, as it avoids - // having to create/parse tens of thousands of literal expression nodes for every shader. - IfStatementSyntax embeddedBranch = - IfStatement( - BinaryExpression( - SyntaxKind.LogicalAndExpression, - BinaryExpression( - SyntaxKind.LogicalAndExpression, - BinaryExpression( - SyntaxKind.EqualsExpression, - IdentifierName("threadsX"), - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.X))), - BinaryExpression( - SyntaxKind.EqualsExpression, - IdentifierName("threadsY"), - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Y)))), - BinaryExpression( - SyntaxKind.EqualsExpression, - IdentifierName("threadsZ"), - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(bytecodeInfo.Z)))), - Block( - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("global::System.ReadOnlySpan")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("bytecode")) - .WithInitializer( - EqualsValueClause( - ArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) - .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) - .WithInitializer( - InitializerExpression( - SyntaxKind.ArrayInitializerExpression, - SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE")))))))), - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("loader"), - IdentifierName("LoadEmbeddedBytecode"))) - .AddArgumentListArguments(Argument(IdentifierName("bytecode")))))); - - // If there is no dynamic shader support, add the faulting path after the branch - return Block(embeddedBranch.WithElse(ElseClause(Block()))); } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs index 1a29c02b..e21a34e2 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadBytecodeMethod.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Immutable; using System.ComponentModel; -using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; @@ -14,7 +13,6 @@ using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; @@ -31,17 +29,32 @@ partial class IShaderGenerator /// private static partial class LoadBytecode { + /// + /// The shared cache of values. + /// + private static readonly DynamicCache HlslBytecodeCache = new(); + + /// + /// Indicates whether the required dxcompiler.dll and dxil.dll libraries have been loaded. + /// + private static volatile bool areDxcLibrariesLoaded; + /// /// Gets the thread ids values for a given shader type, if available. /// /// The collection of produced instances. /// The input instance to process. - /// Indicates whether or not dynamic shaders are supported. - /// The thread ids for the precompiled shader, if available. - public static ThreadIdsInfo GetInfo( + /// The thread ids value for the X axis. + /// The thread ids value for the Y axis. + /// The thread ids value for the Z axis. + /// Whether compilation should be attempted for the current info. + public static void GetInfo( ImmutableArrayBuilder diagnostics, INamedTypeSymbol structDeclarationSymbol, - bool supportsDynamicShaders) + out int threadsX, + out int threadsY, + out int threadsZ, + out bool isCompilationEnabled) { // Try to get the attribute that controls shader precompilation (has to be present when ComputeSharp.Dynamic is not referenced) if (!structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName(typeof(EmbeddedBytecodeAttribute).FullName, out AttributeData? attribute)) @@ -49,12 +62,11 @@ partial class IShaderGenerator // Emit the diagnostics if dynamic shaders are not supported diagnostics.Add(MissingEmbeddedBytecodeAttributeWhenDynamicShaderCompilationIsNotSupported, structDeclarationSymbol, structDeclarationSymbol); - return new(true, 0, 0, 0); - } + threadsX = threadsY = threadsZ = 0; + isCompilationEnabled = false; - int threadsX; - int threadsY; - int threadsZ; + return; + } // Check for a dispatch axis argument first if (attribute.ConstructorArguments.Length == 1) @@ -78,8 +90,13 @@ partial class IShaderGenerator { diagnostics.Add(InvalidEmbeddedBytecodeDispatchAxis, structDeclarationSymbol, structDeclarationSymbol); - return new(true, 0, 0, 0); + threadsX = threadsY = threadsZ = 0; + isCompilationEnabled = false; + + return; } + + isCompilationEnabled = true; } else if ( attribute.ConstructorArguments.Length != 3 || @@ -93,91 +110,102 @@ partial class IShaderGenerator // Failed to validate the thread number arguments diagnostics.Add(InvalidEmbeddedBytecodeThreadIds, structDeclarationSymbol, structDeclarationSymbol); - return new(true, 0, 0, 0); + threadsX = threadsY = threadsZ = 0; + isCompilationEnabled = false; + + return; } else { threadsX = explicitThreadsX; threadsY = explicitThreadsY; threadsZ = explicitThreadsZ; + isCompilationEnabled = true; } - - // Ensure the bytecode generation is disabled if any errors are present. This step is done last to ensure that - // all available diagnostics are still emitted correctly before reaching this point, instead of being disabled. - if (diagnostics.Count > 0) - { - return new(true, 0, 0, 0); - } - - return new(false, threadsX, threadsY, threadsZ); } /// - /// Indicates whether the required dxcompiler.dll and dxil.dll libraries have been loaded. + /// Gets the instance for the input shader info. /// - private static volatile bool areDxcLibrariesLoaded; + /// The instance for the shader to compile. + /// The used to cancel the operation, if needed. + /// The instance for the current shader. + public static unsafe HlslBytecodeInfo GetBytecode(ref HlslBytecodeInfoKey key, CancellationToken token) + { + static unsafe HlslBytecodeInfo GetInfo(HlslBytecodeInfoKey key, CancellationToken token) + { + // Skip even attempting to compile if compilation is disabled (see comments in D2D1 generator) + if (!key.IsCompilationEnabled) + { + return HlslBytecodeInfo.Missing.Instance; + } + + try + { + // Try to load dxcompiler.dll and dxil.dll + LoadNativeDxcLibraries(); + + token.ThrowIfCancellationRequested(); + + // Compile the shader bytecode + using ComPtr dxcBlobBytecode = ShaderCompiler.Instance.Compile(key.HlslSource.AsSpan()); + + token.ThrowIfCancellationRequested(); + + byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer(); + int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize()); + + byte[] array = new ReadOnlySpan(buffer, length).ToArray(); + + ImmutableArray bytecode = Unsafe.As>(ref array); + + return new HlslBytecodeInfo.Success(bytecode); + } + catch (Win32Exception e) + { + return new HlslBytecodeInfo.Win32Error(e.NativeErrorCode, FixupExceptionMessage(e.Message)); + } + catch (DxcCompilationException e) + { + return new HlslBytecodeInfo.CompilerError(FixupExceptionMessage(e.Message)); + } + } + + return HlslBytecodeCache.GetOrCreate(ref key, GetInfo, token); + } /// - /// Gets a instance with the logic to try to get a compiled shader bytecode. + /// Gets any diagnostics from a processed instance. /// - /// The input instance to process. - /// The generated HLSL source code (ignoring captured delegates, if present). - /// The used to cancel the operation, if needed. - /// The resulting diagnostic from the processing operation, if any. - /// The instance with the compiled shader bytecode. - public static unsafe ImmutableArray GetBytecode( - ThreadIdsInfo threadIds, - string hlslSource, - CancellationToken token, - out DeferredDiagnosticInfo? diagnostic) + /// The input instance to process. + /// The source instance. + /// The collection of produced instances. + public static void GetInfoDiagnostics( + INamedTypeSymbol structDeclarationSymbol, + HlslBytecodeInfo info, + ImmutableArrayBuilder diagnostics) { - ImmutableArray bytecode = ImmutableArray.Empty; + DiagnosticInfo? diagnostic = null; - // No embedded shader was requested - if (threadIds.IsDefault) + if (info is HlslBytecodeInfo.Win32Error win32Error) { - diagnostic = null; - - goto End; + diagnostic = DiagnosticInfo.Create( + EmbeddedBytecodeFailedWithWin32Exception, + structDeclarationSymbol, + new object[] { structDeclarationSymbol, win32Error.HResult, win32Error.Message }); + } + else if (info is HlslBytecodeInfo.CompilerError dxcError) + { + diagnostic = DiagnosticInfo.Create( + EmbeddedBytecodeFailedWithDxcCompilationException, + structDeclarationSymbol, + new object[] { structDeclarationSymbol, dxcError.Message }); } - try + if (diagnostic is not null) { - // Try to load dxcompiler.dll and dxil.dll - LoadNativeDxcLibraries(); - - token.ThrowIfCancellationRequested(); - - // Replace the actual thread num values - hlslSource = hlslSource - .Replace("", threadIds.X.ToString(CultureInfo.InvariantCulture)) - .Replace("", threadIds.Y.ToString(CultureInfo.InvariantCulture)) - .Replace("", threadIds.Z.ToString(CultureInfo.InvariantCulture)); - - // Compile the shader bytecode - using ComPtr dxcBlobBytecode = ShaderCompiler.Instance.Compile(hlslSource.AsSpan()); - - token.ThrowIfCancellationRequested(); - - byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer(); - int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize()); - - byte[] array = new ReadOnlySpan(buffer, length).ToArray(); - - bytecode = Unsafe.As>(ref array); - diagnostic = null; + diagnostics.Add(diagnostic); } - catch (Win32Exception e) - { - diagnostic = DeferredDiagnosticInfo.Create(EmbeddedBytecodeFailedWithWin32Exception, e.HResult, FixupExceptionMessage(e.Message)); - } - catch (DxcCompilationException e) - { - diagnostic = DeferredDiagnosticInfo.Create(EmbeddedBytecodeFailedWithDxcCompilationException, FixupExceptionMessage(e.Message)); - } - - End: - return bytecode; } /// diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs index d73836c6..6c272144 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.Syntax.cs @@ -1,12 +1,6 @@ -using System.Collections.Immutable; -using ComputeSharp.__Internals; +using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGenerators.Models; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 namespace ComputeSharp.SourceGenerators; @@ -17,252 +11,89 @@ partial class IShaderGenerator partial class LoadDispatchData { /// - /// Creates a instance for the LoadDispatchDataMethod method. + /// Writes the LoadDispatchData method. /// - /// The type of shader interface currently being processed. - /// The array of values for all captured fields. - /// The total number of captured resources in the shader. - /// The total number of needed 32 bit constants in the shader root signature. - /// The resulting instance for the LoadDispatchDataMethod method. - public static MethodDeclarationSyntax GetSyntax( - ShaderType shaderType, - ImmutableArray fieldInfos, - int resourceCount, - int root32BitConstantsCount) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(ShaderInfo info, IndentedTextWriter writer) { - // This code produces a method declaration as follows: - // - // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData(ref TLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z) - // { - // - // } - return - MethodDeclaration( - PredefinedType(Token(SyntaxKind.VoidKeyword)), - Identifier("LoadDispatchData")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .AddTypeParameterListParameters(TypeParameter(Identifier("TLoader"))) - .AddParameterListParameters( - Parameter(Identifier("loader")) - .AddModifiers(Token(SyntaxKind.RefKeyword)) - .WithType(IdentifierName("TLoader")), - Parameter(Identifier("device")).WithType(IdentifierName("global::ComputeSharp.GraphicsDevice")), - Parameter(Identifier("x")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("y")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))), - Parameter(Identifier("z")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword)))) - .WithBody(Block(GetDispatchDataLoadingStatements(shaderType, fieldInfos, resourceCount, root32BitConstantsCount))); - } + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(GeneratorName); + writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]"); + writer.WriteLine("readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchData(ref TLoader loader, global::ComputeSharp.GraphicsDevice device, int x, int y, int z)"); - /// - /// Gets a sequence of statements to load the dispatch data for a given shader. - /// - /// The type of shader interface currently being processed. - /// The array of values for all captured fields. - /// The total number of captured resources in the shader. - /// The total number of needed 32 bit constants in the shader root signature. - /// The sequence of instances to load shader dispatch data. - private static ImmutableArray GetDispatchDataLoadingStatements( - ShaderType shaderType, - ImmutableArray fieldInfos, - int resourceCount, - int root32BitConstantsCount) - { - using ImmutableArrayBuilder statements = new(); - - // global::System.Span span0 = stackalloc uint[]; - statements.Add( - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.UIntKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("span0")) - .WithInitializer(EqualsValueClause( - StackAllocArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.UIntKeyword))) - .AddRankSpecifiers( - ArrayRankSpecifier(SingletonSeparatedList( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(root32BitConstantsCount))))))))))); - - if (resourceCount > 0) + using (writer.WriteBlock()) { - // global::System.Span span1 = stackalloc ulong[]; - statements.Add( - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ULongKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("span1")) - .WithInitializer(EqualsValueClause( - StackAllocArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ULongKeyword))) - .AddRankSpecifiers( - ArrayRankSpecifier(SingletonSeparatedList( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(resourceCount))))))))))); - } + writer.WriteLine($"global::System.Span span0 = stackalloc uint[{info.Root32BitConstantCount}];"); + writer.WriteLineIf($"global::System.Span span1 = stackalloc ulong[{info.ResourceCount}];", info.ResourceCount > 0); + writer.WriteLine("ref uint r0 = ref span0[0];"); + writer.WriteLineIf("ref ulong r1 = ref span1[0];", info.ResourceCount > 0); - // ref uint r0 = ref span0[0]; - statements.Add( - LocalDeclarationStatement( - VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.UIntKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("r0")) - .WithInitializer(EqualsValueClause( - RefExpression( - ElementAccessExpression(IdentifierName("span0")) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))))))))); + // Append the statements for the dispatch ranges + writer.WriteLine("span0[0] = (uint)x;"); + writer.WriteLine("span0[1] = (uint)y;"); + writer.WriteLineIf("span0[2] = (uint)z;", !info.IsPixelShaderLike); - if (resourceCount > 0) - { - // ref ulong r1 = ref span1[0]; - statements.Add( - LocalDeclarationStatement( - VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ULongKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("r1")) - .WithInitializer(EqualsValueClause( - RefExpression( - ElementAccessExpression(IdentifierName("span1")) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))))))))); - } - - // Append the statements for the dispatch ranges: - // - // span0[0] = (uint)x; - // span0[1] = (uint)y; - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ElementAccessExpression(IdentifierName("span0")) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(0)))), - CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("x"))))); - - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ElementAccessExpression(IdentifierName("span0")) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(1)))), - CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("y"))))); - - // If the shader is a compute shader, also track the bounds on the Z axis: - // - // span0[2] = (uint)z; - if (shaderType == ShaderType.ComputeShader) - { - statements.Add( - ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ElementAccessExpression(IdentifierName("span0")) - .AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(2)))), - CastExpression(PredefinedType(Token(SyntaxKind.UIntKeyword)), IdentifierName("z"))))); - } - - // Generate loading statements for each captured field - foreach (FieldInfo fieldInfo in fieldInfos) - { - switch (fieldInfo) + // Generate loading statements for each captured field + foreach (FieldInfo fieldInfo in info.Fields) { - case FieldInfo.Resource resource: + switch (fieldInfo) + { + case FieldInfo.Resource resource: - // Validate the resource and get a handle for it. This will generate: - // - // global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, ) = - // global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle(, device); - statements.Add(ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resource.Offset})"), - ParseExpression($"global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({resource.FieldName}, device)")))); - break; - case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive: + // Validate the resource and get a handle for it + writer.WriteLine( + $"global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {resource.Offset}) = " + + $"global::ComputeSharp.__Internals.GraphicsResourceHelper.ValidateAndGetGpuDescriptorHandle({resource.FieldName}, device);"); + break; + case FieldInfo.Primitive { TypeName: "System.Boolean" } primitive: - // Read a boolean value and cast it to Bool first, which will apply the correct size expansion. This will generate the following: - // - // global::System.Runtime.CompilerServices.Unsafe.As( - // ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint))) = (global::ComputeSharp.Bool) - statements.Add(ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))"), - ParseExpression($"(global::ComputeSharp.Bool){string.Join(".", primitive.FieldPath)}")))); - break; - case FieldInfo.Primitive 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 global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset})) = " + + $"(global::ComputeSharp.Bool){string.Join(".", primitive.FieldPath)};"); + break; + case FieldInfo.Primitive primitive: - // Read a primitive value and serialize it into the target buffer. This will generate: - // - // global::System.Runtime.CompilerServices.Unsafe.As>( - // ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint))) = - statements.Add(ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset}))"), - ParseExpression($"{string.Join(".", primitive.FieldPath)}")))); - break; + // Read a primitive value and serialize it into the target buffer + writer.WriteLine( + $"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){primitive.Offset})) = " + + $"{string.Join(".", primitive.FieldPath)};"); + break; - case FieldInfo.NonLinearMatrix matrix: - string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}"; - string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__row0"; + case FieldInfo.NonLinearMatrix matrix: + string rowTypeName = $"global::ComputeSharp.{matrix.ElementName}{matrix.Columns}"; + string rowLocalName = $"__{string.Join("_", matrix.FieldPath)}__row0"; - // Declare a local to index into individual rows. This will generate: - // - // ref = ref global::System.Runtime.CompilerServices.Unsafe.As, >( - // ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in )); - statements.Add(ParseStatement($"ref {rowTypeName} {rowLocalName} = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in {string.Join(".", matrix.FieldPath)}));")); + // 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 {string.Join(".", matrix.FieldPath)}));"); - // Generate the loading code for each individual row, with proper alignment. - // This will result in the following (assuming Float2x3 m): - // - // ref global::ComputeSharp.Float3 __m__row0 = ref global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AsRef(in m)); - // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)rawDataOffset)) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 0); - // global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint)(rawDataOffset + 16))) = global::System.Runtime.CompilerServices.Unsafe.Add(ref __m__row0, 1); - for (int j = 0; j < matrix.Rows; j++) - { - statements.Add(ExpressionStatement( - AssignmentExpression( - SyntaxKind.SimpleAssignmentExpression, - ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.As(ref global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]}))"), - ParseExpression($"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j})")))); - } + // 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 global::System.Runtime.CompilerServices.Unsafe.AddByteOffset(ref r0, (nint){matrix.Offsets[j]})) = " + + $"global::System.Runtime.CompilerServices.Unsafe.Add(ref {rowLocalName}, {j});"); + } - break; + break; + } } + + // Load the prepared buffers + writer.WriteLine("loader.LoadCapturedValues(span0);"); + writer.WriteLineIf("loader.LoadCapturedResources(span1);", info.ResourceCount > 0); } - - // loader.LoadCapturedValues(span0); - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("loader"), - IdentifierName("LoadCapturedValues"))) - .AddArgumentListArguments(Argument(IdentifierName("span0"))))); - - if (resourceCount > 0) - { - // loader.LoadCapturedResources(span1); - statements.Add( - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("loader"), - IdentifierName("LoadCapturedResources"))) - .AddArgumentListArguments(Argument(IdentifierName("span1"))))); - } - - return statements.ToImmutable(); } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs index 6a3cba0f..0636ebc0 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchDataMethod.cs @@ -27,14 +27,14 @@ partial class IShaderGenerator /// /// The collection of produced instances. /// The current shader type being explored. - /// The type of shader currently being processed. + /// Whether the compute shader is "pixel shader like", ie. outputting a pixel into a target texture. /// The total number of captured resources in the shader. /// The total number of needed 32 bit constants in the shader root signature. /// The sequence of instances for all captured resources and values. public static ImmutableArray GetInfo( ImmutableArrayBuilder diagnostics, ITypeSymbol structDeclarationSymbol, - ShaderType shaderType, + bool isPixelShaderLike, out int resourceCount, out int root32BitConstantCount) { @@ -91,8 +91,7 @@ partial class IShaderGenerator // Setup the resource and byte offsets for tracking. Pixel shaders have only two // implicitly captured int values, as they're always dispatched over a 2D texture. - bool isComputeShader = shaderType == ShaderType.ComputeShader; - int initialRawDataOffset = sizeof(int) * (isComputeShader ? 3 : 2); + int initialRawDataOffset = sizeof(int) * (isPixelShaderLike ? 2 : 3); StrongBox resourceOffsetAsBox = new(); StrongBox rawDataOffsetAsBox = new(initialRawDataOffset); diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs index 8850cb37..2faed681 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.Syntax.cs @@ -1,14 +1,7 @@ -using System; -using System.Collections.Immutable; using System.Globalization; -using ComputeSharp.__Internals; +using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGenerators.Models; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; - -#pragma warning disable CS0618 namespace ComputeSharp.SourceGenerators; @@ -19,119 +12,40 @@ partial class IShaderGenerator partial class LoadDispatchMetadata { /// - /// Creates a instance for the LoadDispatchMetadata method. + /// Writes the LoadDispatchMetadata method. /// - /// The dispatch metadata for the current shader.. - /// The resulting instance for the LoadDispatchMetadata method. - public static MethodDeclarationSyntax GetSyntax(DispatchMetadataInfo metadataInfo) + /// The input instance with gathered shader info. + /// The instance to write into. + public static void WriteSyntax(ShaderInfo info, IndentedTextWriter writer) { - // This code produces a method declaration as follows: - // - // readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata(ref TLoader loader, out global::System.IntPtr result) - // { - // - // } - return - MethodDeclaration( - PredefinedType(Token(SyntaxKind.VoidKeyword)), - Identifier("LoadDispatchMetadata")) - .WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}"))) - .AddModifiers(Token(SyntaxKind.ReadOnlyKeyword)) - .AddTypeParameterListParameters(TypeParameter(Identifier("TLoader"))) - .AddParameterListParameters( - Parameter(Identifier("loader")) - .AddModifiers(Token(SyntaxKind.RefKeyword)) - .WithType(IdentifierName("TLoader")), - Parameter(Identifier("result")) - .AddModifiers(Token(SyntaxKind.OutKeyword)) - .WithType(IdentifierName($"global::System.{nameof(IntPtr)}"))) - .WithBody(Block(GetDispatchMetadataLoadingStatements(metadataInfo))); - } + writer.WriteLine("/// "); + writer.WriteGeneratedAttributes(GeneratorName); + writer.WriteLine("[global::System.Runtime.CompilerServices.SkipLocalsInit]"); + writer.WriteLine("readonly void global::ComputeSharp.__Internals.IShader.LoadDispatchMetadata(ref TLoader loader, out global::System.IntPtr result)"); - /// - /// Gets a sequence of statements to load the dispatch metadata for a given shader type. - /// - /// The dispatch metadata for the current shader.. - /// The sequence of instances to load shader dispatch data. - private static ImmutableArray GetDispatchMetadataLoadingStatements(DispatchMetadataInfo metadataInfo) - { - using ImmutableArrayBuilder statements = new(); - - // global::System.Span span0 = stackalloc byte[5]; - statements.Add( - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("span0")) - .WithInitializer(EqualsValueClause( - StackAllocArrayCreationExpression( - ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) - .AddRankSpecifiers( - ArrayRankSpecifier(SingletonSeparatedList( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(5))))))))))); - - // Compute the total number of resources - int totalResourcesCount = metadataInfo.ResourceDescriptors.Length; - - // Span span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[]; - statements.Add( - LocalDeclarationStatement( - VariableDeclaration( - GenericName(Identifier("global::System.Span")) - .AddTypeArgumentListArguments(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))) - .AddVariables( - VariableDeclarator(Identifier("span1")) - .WithInitializer(EqualsValueClause( - StackAllocArrayCreationExpression( - ArrayType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor")) - .AddRankSpecifiers( - ArrayRankSpecifier(SingletonSeparatedList( - LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(totalResourcesCount))))))))))); - - // ref byte r0 = ref span0[0]; - statements.Add( - LocalDeclarationStatement( - VariableDeclaration(RefType(PredefinedType(Token(SyntaxKind.ByteKeyword)))) - .AddVariables( - VariableDeclarator(Identifier("r0")) - .WithInitializer(EqualsValueClause( - RefExpression( - ElementAccessExpression(IdentifierName("span0")) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))))))))); - - // ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0]; - statements.Add( - LocalDeclarationStatement( - VariableDeclaration(RefType(IdentifierName("global::ComputeSharp.__Internals.ResourceDescriptor"))) - .AddVariables( - VariableDeclarator(Identifier("r1")) - .WithInitializer(EqualsValueClause( - RefExpression( - ElementAccessExpression(IdentifierName("span1")) - .AddArgumentListArguments(Argument( - LiteralExpression( - SyntaxKind.NumericLiteralExpression, - Literal(0)))))))))); - - // Serialized shader metadata - statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {metadataInfo.Root32BitConstantCount});")); - statements.Add(ParseStatement($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {metadataInfo.IsSamplerUsed.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()});")); - - // Populate the sequence of resource descriptors - foreach (ResourceDescriptor descriptor in metadataInfo.ResourceDescriptors) + using (writer.WriteBlock()) { - statements.Add(ParseStatement($"global::ComputeSharp.__Internals.ResourceDescriptor.Create({descriptor.TypeId}, {descriptor.RegisterOffset}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {descriptor.Offset}));")); + // Compute the total number of resources + int totalResourcesCount = info.ResourceDescriptors.Length; + + writer.WriteLine("global::System.Span span0 = stackalloc byte[5];"); + writer.WriteLine($"global::System.Span span1 = stackalloc global::ComputeSharp.__Internals.ResourceDescriptor[{totalResourcesCount}];"); + writer.WriteLine("ref byte r0 = ref span0[0];"); + writer.WriteLine("ref global::ComputeSharp.__Internals.ResourceDescriptor r1 = ref span1[0];"); + + // Write the serialized shader metadata + writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 0), {info.Root32BitConstantCount});"); + writer.WriteLine($"global::System.Runtime.CompilerServices.Unsafe.WriteUnaligned(ref global::System.Runtime.CompilerServices.Unsafe.Add(ref r0, 4), {info.IsSamplerUsed.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()});"); + + // Populate the sequence of resource descriptors + foreach (ResourceDescriptor descriptor in info.ResourceDescriptors) + { + writer.WriteLine($"global::ComputeSharp.__Internals.ResourceDescriptor.Create({descriptor.TypeId}, {descriptor.RegisterOffset}, out global::System.Runtime.CompilerServices.Unsafe.Add(ref r1, {descriptor.Offset}));"); + } + + // Invoke the value delegate to create the opaque root signature handle + writer.WriteLine("loader.LoadMetadataHandle(span0, span1, out result);"); } - - // Invoke the value delegate to create the opaque root signature handle - statements.Add(ParseStatement("loader.LoadMetadataHandle(span0, span1, out result);")); - - return statements.ToImmutable(); } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs index 6822c017..96fe4ebf 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.CreateLoadDispatchMetadataMethod.cs @@ -21,7 +21,7 @@ partial class IShaderGenerator /// Whether the static sampler is used by the shader. /// The sequence of captured fields for the shader. /// The metadata info for the shader. - public static DispatchMetadataInfo GetInfo( + public static ImmutableArray GetInfo( int root32BitConstantCount, bool isImplicitTextureUsed, bool isSamplerUsed, @@ -57,10 +57,7 @@ partial class IShaderGenerator } } - return new( - root32BitConstantCount, - isSamplerUsed, - descriptors.ToImmutable()); + return descriptors.ToImmutable(); } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs index 465269b7..f12485d9 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.Helpers.cs @@ -1,10 +1,4 @@ -using System.Collections.Generic; -using ComputeSharp.SourceGeneration.Models; -using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace ComputeSharp.SourceGenerators; @@ -12,75 +6,36 @@ namespace ComputeSharp.SourceGenerators; partial class IShaderGenerator { /// - /// Gets the shader type for a given shader, if any. + /// Gets whether a given type is a compute shader type (ie. implements any of the interfaces). /// /// The input instance to check. /// The instance currently in use. - /// The shader type for , or . - private static ShaderType? GetShaderType(INamedTypeSymbol typeSymbol, Compilation compilation) + /// Whether is a "pixel shader like" type. + /// Whether is a compute shader type at all. + private static bool TryGetIsPixelShaderLike(INamedTypeSymbol typeSymbol, Compilation compilation, out bool result) { + INamedTypeSymbol computeShaderSymbol = compilation.GetTypeByMetadataName("ComputeSharp.IComputeShader")!; + INamedTypeSymbol pixelShaderSymbol = compilation.GetTypeByMetadataName("ComputeSharp.IPixelShader`1")!; + foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.AllInterfaces) { - if (interfaceSymbol.Name == nameof(IComputeShader)) + if (SymbolEqualityComparer.Default.Equals(interfaceSymbol, computeShaderSymbol)) { - INamedTypeSymbol computeShaderSymbol = compilation.GetTypeByMetadataName("ComputeSharp.IComputeShader")!; + result = false; - if (SymbolEqualityComparer.Default.Equals(interfaceSymbol, computeShaderSymbol)) - { - return ShaderType.ComputeShader; - } + return true; } - else if (interfaceSymbol is { IsGenericType: true, Name: nameof(IPixelShader) }) + else if (interfaceSymbol is { IsGenericType: true } && + SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, pixelShaderSymbol)) { - INamedTypeSymbol pixelShaderSymbol = compilation.GetTypeByMetadataName("ComputeSharp.IPixelShader`1")!; + result = true; - if (SymbolEqualityComparer.Default.Equals(interfaceSymbol.ConstructedFrom, pixelShaderSymbol)) - { - return ShaderType.PixelShader; - } + return true; } } - return null; - } + result = false; - /// - /// Creates a instance wrapping the given method. - /// - /// The instance for the current type. - /// The item to insert. - /// Whether [SkipLocalsInit] should be used. - /// A object wrapping . - private static CompilationUnitSyntax GetCompilationUnitFromMethod( - HierarchyInfo hierarchyInfo, - MethodDeclarationSyntax methodDeclaration, - bool addSkipLocalsInitAttribute) - { - // Method attributes - List attributes = new() - { - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")).AddArgumentListArguments( - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).FullName))), - AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(IShaderGenerator).Assembly.GetName().Version.ToString())))))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.DebuggerNonUserCode")))), - AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage")))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.ComponentModel.EditorBrowsable")).AddArgumentListArguments( - AttributeArgument(ParseExpression("global::System.ComponentModel.EditorBrowsableState.Never"))))), - AttributeList(SingletonSeparatedList( - Attribute(IdentifierName("global::System.Obsolete")).AddArgumentListArguments( - AttributeArgument(LiteralExpression( - SyntaxKind.StringLiteralExpression, - Literal("This method is not intended to be used directly by user code")))))) - }; - - // Add [SkipLocalsInit] if needed - if (addSkipLocalsInitAttribute) - { - attributes.Add(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Runtime.CompilerServices.SkipLocalsInit"))))); - } - - return hierarchyInfo.GetSyntax(methodDeclaration.AddAttributeLists(attributes.ToArray())); + return false; } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs index ed27be1b..f7b11ec2 100644 --- a/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/IShaderGenerator.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Immutable; using System.Linq; -using System.Text; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; @@ -9,7 +8,6 @@ using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Text; namespace ComputeSharp.SourceGenerators; @@ -19,11 +17,16 @@ namespace ComputeSharp.SourceGenerators; [Generator(LanguageNames.CSharp)] public sealed partial class IShaderGenerator : IIncrementalGenerator { + /// + /// The name of generator to include in the generated code. + /// + private const string GeneratorName = "ComputeSharp.IShaderGenerator"; + /// public void Initialize(IncrementalGeneratorInitializationContext context) { // Discover all shader types and extract all the necessary info from each of them - IncrementalValuesProvider shaderInfoWithErrors = + IncrementalValuesProvider shaderInfo = context.SyntaxProvider .CreateSyntaxProvider( static (node, _) => node.IsTypeDeclarationWithOrPotentiallyWithBaseTypes(), @@ -43,8 +46,8 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator return default; } - // Get the shader type, or return if none is present - if (GetShaderType(typeSymbol, context.SemanticModel.Compilation) is not ShaderType shaderType) + // Check whether type is a compute shader, and if so, if it's pixel shader like + if (!TryGetIsPixelShaderLike(typeSymbol, context.SemanticModel.Compilation, out bool isPixelShaderLike)) { return default; } @@ -55,157 +58,107 @@ public sealed partial class IShaderGenerator : IIncrementalGenerator ImmutableArray fieldInfos = LoadDispatchData.GetInfo( diagnostics, typeSymbol, - shaderType, + isPixelShaderLike, out int resourceCount, out int root32BitConstantCount); token.ThrowIfCancellationRequested(); // TryGetBytecode() info - ThreadIdsInfo threadIds = LoadBytecode.GetInfo( + LoadBytecode.GetInfo( diagnostics, typeSymbol, - false); + out int threadsX, + out int threadsY, + out int threadsZ, + out bool isCompilationEnabled); token.ThrowIfCancellationRequested(); // BuildHlslSource() info - HlslShaderSourceInfo hlslSourceInfo = BuildHlslSource.GetInfo( + BuildHlslSource.GetInfo( diagnostics, context.SemanticModel.Compilation, typeDeclaration, typeSymbol, - threadIds, - out bool isImplicitTextureUsed); + threadsX, + threadsY, + threadsZ, + out bool isImplicitTextureUsed, + out bool isSamplerUsed, + out string hlslSource); token.ThrowIfCancellationRequested(); // GetDispatchMetadata() info - DispatchMetadataInfo dispatchMetadataInfo = LoadDispatchMetadata.GetInfo( + ImmutableArray resourceDescriptors = LoadDispatchMetadata.GetInfo( root32BitConstantCount, isImplicitTextureUsed, - hlslSourceInfo.IsSamplerUsed, + isSamplerUsed, fieldInfos); token.ThrowIfCancellationRequested(); + // Prepare the lookup key for the HLSL shader bytecode + HlslBytecodeInfoKey hlslInfoKey = new(hlslSource, isCompilationEnabled); + + // Try to get the HLSL bytecode + HlslBytecodeInfo hlslInfo = LoadBytecode.GetBytecode(ref hlslInfoKey, token); + + token.ThrowIfCancellationRequested(); + + LoadBytecode.GetInfoDiagnostics(typeSymbol, hlslInfo, diagnostics); + + token.ThrowIfCancellationRequested(); + + // Also get the hierarchy too + HierarchyInfo hierarchyInfo = HierarchyInfo.From(typeSymbol); + + token.ThrowIfCancellationRequested(); + return new ShaderInfo( - Hierarchy: HierarchyInfo.From(typeSymbol), - DispatchData: new DispatchDataInfo( - shaderType, - fieldInfos, - resourceCount, - root32BitConstantCount), - DispatchMetadata: dispatchMetadataInfo, - HlslShaderSource: hlslSourceInfo, - ThreadIds: threadIds, + Hierarchy: hierarchyInfo, + ThreadsX: threadsX, + ThreadsY: threadsY, + ThreadsZ: threadsZ, + IsPixelShaderLike: isPixelShaderLike, + IsSamplerUsed: isSamplerUsed, + Fields: fieldInfos, + ResourceDescriptors: resourceDescriptors, + ResourceCount: resourceCount, + Root32BitConstantCount: root32BitConstantCount, + HlslInfoKey: hlslInfoKey, + HlslInfo: hlslInfo, Diagnostcs: diagnostics.ToImmutable()); }) .Where(static item => item is not null)!; + // Split the diagnostics, and drop them from the output provider (see more notes in the D2D1 generator) + IncrementalValuesProvider> diagnosticInfo = shaderInfo.Select(static (item, _) => item.Diagnostcs); + IncrementalValuesProvider outputInfo = shaderInfo.Select(static (item, _) => item with { Diagnostcs = default }); + // Output the diagnostics, if any - context.ReportDiagnostics( - shaderInfoWithErrors - .Select(static (item, _) => item.Diagnostcs)); + context.ReportDiagnostics(diagnosticInfo); - // Get the LoadDispatchData() info (hierarchy and dispatch data info) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchDataInfo DispatchData)> dispatchDataInfo = - shaderInfoWithErrors - .Select(static (item, _) => (item.Hierarchy, item.DispatchData)); - - // Generate the LoadDispatchData() methods - context.RegisterSourceOutput(dispatchDataInfo, static (context, item) => + // Generate the source files, if any + context.RegisterSourceOutput(outputInfo, static (context, item) => { - MethodDeclarationSyntax loadDispatchDataMethod = LoadDispatchData.GetSyntax( - item.DispatchData.Type, - item.DispatchData.FieldInfos, - item.DispatchData.ResourceCount, - item.DispatchData.Root32BitConstantCount); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, loadDispatchDataMethod, addSkipLocalsInitAttribute: true); + using ImmutableArrayBuilder> declaredMembers = new(); - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadDispatchData)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); - }); + declaredMembers.Add(LoadDispatchData.WriteSyntax); + declaredMembers.Add(LoadDispatchMetadata.WriteSyntax); + declaredMembers.Add(BuildHlslSource.WriteSyntax); + declaredMembers.Add(LoadBytecode.WriteSyntax); - // Get the BuildHlslSource info (hierarchy, HLSL source and parsing options) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo HlslShaderSource)> hlslSourceInfo = - shaderInfoWithErrors - .Select(static (item, _) => (item.Hierarchy, item.HlslShaderSource)); + using IndentedTextWriter writer = new(); - // Generate the BuildHlslSource() methods - context.RegisterSourceOutput(hlslSourceInfo, static (context, item) => - { - MethodDeclarationSyntax buildHlslStringMethod = BuildHlslSource.GetSyntax(item.HlslShaderSource, item.Hierarchy.Hierarchy.Length); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, buildHlslStringMethod, addSkipLocalsInitAttribute: true); + item.Hierarchy.WriteSyntax( + state: item, + writer: writer, + baseTypes: ReadOnlySpan.Empty, + memberCallbacks: declaredMembers.WrittenSpan); - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(BuildHlslSource)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); - }); - - // Get the LoadDispatchMetadata() info (hierarchy and dispatch metadata info) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, DispatchMetadataInfo DispatchMetadata)> dispatchMetadataInfo = - shaderInfoWithErrors - .Select(static (item, _) => (item.Hierarchy, item.DispatchMetadata)); - - // Generate the LoadDispatchMetadata() methods - context.RegisterSourceOutput(dispatchMetadataInfo, static (context, item) => - { - MethodDeclarationSyntax buildHlslStringMethod = LoadDispatchMetadata.GetSyntax(item.DispatchMetadata); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, buildHlslStringMethod, addSkipLocalsInitAttribute: true); - - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadDispatchMetadata)}.g.cs", compilationUnit.GetText(Encoding.UTF8)); - }); - - // Transform the raw HLSL source to compile (this step aggregates the HLSL source to ensure compilation is only done for actual HLSL changes) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, string Hlsl, ThreadIdsInfo ThreadIds)> shaderBytecodeInfo = - shaderInfoWithErrors - .Select(static (item, token) => (item.Hierarchy, item.HlslShaderSource.HlslSource, item.ThreadIds)); - - // Compile the requested shader bytecodes - IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo EmbeddedBytecode, DeferredDiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = - shaderBytecodeInfo - .Select(static (item, token) => - { - ImmutableArray bytecode = LoadBytecode.GetBytecode(item.ThreadIds, item.Hlsl, token, out DeferredDiagnosticInfo? diagnostic); - - token.ThrowIfCancellationRequested(); - - EmbeddedBytecodeInfo bytecodeInfo = new( - item.ThreadIds.X, - item.ThreadIds.Y, - item.ThreadIds.Z, - bytecode); - - return (item.Hierarchy, bytecodeInfo, diagnostic); - }); - - // Gather the diagnostics - IncrementalValuesProvider embeddedBytecodeDiagnostics = - embeddedBytecodeWithErrors - .Select(static (item, token) => (item.Hierarchy.FullyQualifiedMetadataName, item.Diagnostic)) - .Where(static item => item.Diagnostic is not null) - .Combine(context.CompilationProvider) - .Select(static (item, token) => - { - INamedTypeSymbol typeSymbol = item.Right.GetTypeByMetadataName(item.Left.FullyQualifiedMetadataName)!; - - return DiagnosticInfo.Create(item.Left.Diagnostic!.Descriptor, typeSymbol, new object[] { typeSymbol }.Concat(item.Left.Diagnostic.Arguments).ToArray()); - }); - - // Output the diagnostics - context.ReportDiagnostics(embeddedBytecodeDiagnostics); - - // Get the TryGetBytecode() info (hierarchy and compiled bytecode) - IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo EmbeddedBytecode)> embeddedBytecodeInfo = - embeddedBytecodeWithErrors - .Select(static (item, token) => (item.Hierarchy, item.EmbeddedBytecode)); - - // Generate the TryGetBytecode() methods - context.RegisterSourceOutput(embeddedBytecodeInfo, static (context, item) => - { - MethodDeclarationSyntax tryGetBytecodeMethod = LoadBytecode.GetSyntax(item.EmbeddedBytecode, out Func fixup); - CompilationUnitSyntax compilationUnit = GetCompilationUnitFromMethod(item.Hierarchy, tryGetBytecodeMethod, addSkipLocalsInitAttribute: false); - SourceText text = fixup(compilationUnit); - - context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.{nameof(LoadBytecode)}.g.cs", text); + context.AddSource($"{item.Hierarchy.FullyQualifiedMetadataName}.g.cs", writer.ToString()); }); } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs deleted file mode 100644 index bf68a1ae..00000000 --- a/src/ComputeSharp.SourceGenerators/Models/DispatchDataInfo.cs +++ /dev/null @@ -1,16 +0,0 @@ -using ComputeSharp.SourceGeneration.Helpers; - -namespace ComputeSharp.SourceGenerators.Models; - -/// -/// A model representing gathered info on a shader dispatch data. -/// -/// The shader interface type. -/// The description on shader instance fields. -/// The total number of captured resources. -/// The size of the shader root signature, in 32 bit constants. -internal sealed record DispatchDataInfo( - ShaderType Type, - EquatableArray FieldInfos, - int ResourceCount, - int Root32BitConstantCount); \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Models/DispatchMetadataInfo.cs b/src/ComputeSharp.SourceGenerators/Models/DispatchMetadataInfo.cs deleted file mode 100644 index 1cba4ce6..00000000 --- a/src/ComputeSharp.SourceGenerators/Models/DispatchMetadataInfo.cs +++ /dev/null @@ -1,11 +0,0 @@ -using ComputeSharp.SourceGeneration.Helpers; - -namespace ComputeSharp.SourceGenerators.Models; - -/// -/// A model containing info on shader dispatch metadata. -/// -/// The size of the shader root signature, in 32 bit constants. -/// Whether or not the static sampler is used. -/// The sequence of resource descriptors for the shader. -internal sealed record DispatchMetadataInfo(int Root32BitConstantCount, bool IsSamplerUsed, EquatableArray ResourceDescriptors); \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Models/EmbeddedBytecodeInfo.cs b/src/ComputeSharp.SourceGenerators/Models/EmbeddedBytecodeInfo.cs deleted file mode 100644 index f6fec7a6..00000000 --- a/src/ComputeSharp.SourceGenerators/Models/EmbeddedBytecodeInfo.cs +++ /dev/null @@ -1,12 +0,0 @@ -using ComputeSharp.SourceGeneration.Helpers; - -namespace ComputeSharp.SourceGenerators.Models; - -/// -/// A model representing a compiled shader bytecode, or none. -/// -/// The thread ids value for the X axis. -/// The thread ids value for the Y axis. -/// The thread ids value for the Z axis. -/// The compiled shader bytecode, if available. -internal sealed record EmbeddedBytecodeInfo(int X, int Y, int Z, EquatableArray Bytecode); \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Models/HlslBytecodeInfoKey.cs b/src/ComputeSharp.SourceGenerators/Models/HlslBytecodeInfoKey.cs new file mode 100644 index 00000000..78bc27a6 --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/Models/HlslBytecodeInfoKey.cs @@ -0,0 +1,10 @@ +using ComputeSharp.SourceGeneration.Models; + +namespace ComputeSharp.SourceGenerators.Models; + +/// +/// A model with info to be a unique key for instances. +/// +/// The input HLSL source code. +/// Whether compilation should be attempted for the current info. +internal sealed record HlslBytecodeInfoKey(string HlslSource, bool IsCompilationEnabled); \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs b/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs deleted file mode 100644 index e0220a50..00000000 --- a/src/ComputeSharp.SourceGenerators/Models/HlslShaderSourceInfo.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace ComputeSharp.SourceGenerators.Models; - -/// -/// A model for extracted info on a processed HLSL shader. -/// -/// The HLSL source for the shader. -/// Whether or not the static sampler is used. -internal sealed record HlslShaderSourceInfo(string HlslSource, bool IsSamplerUsed); \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs b/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs index 27cd2efc..cb51e35d 100644 --- a/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs +++ b/src/ComputeSharp.SourceGenerators/Models/ShaderInfo.cs @@ -7,15 +7,29 @@ namespace ComputeSharp.SourceGenerators.Models; /// A model representing all necessary info for a full generation pass for a shader. /// /// The hierarchy info for the shader type. -/// The gathered shader dispatch data. -/// The gathered shader dispatch metadata. -/// The processed HLSL source for the shader. -/// The thread ids for the shader, if compilation is requested. +/// The thread ids value for the X axis. +/// The thread ids value for the Y axis. +/// The thread ids value for the Z axis. +/// 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 description on shader instance fields. +/// The sequence of resource descriptors for the shader. +/// The total number of captured resources in the shader. +/// The size of the shader root signature, in 32 bit constants. +/// The key with processed info on the shader. +/// The value with processed info on the shader. /// The discovered diagnostics, if any. internal sealed record ShaderInfo( HierarchyInfo Hierarchy, - DispatchDataInfo DispatchData, - DispatchMetadataInfo DispatchMetadata, - HlslShaderSourceInfo HlslShaderSource, - ThreadIdsInfo ThreadIds, + int ThreadsX, + int ThreadsY, + int ThreadsZ, + bool IsPixelShaderLike, + bool IsSamplerUsed, + EquatableArray Fields, + EquatableArray ResourceDescriptors, + int ResourceCount, + int Root32BitConstantCount, + HlslBytecodeInfoKey HlslInfoKey, + HlslBytecodeInfo HlslInfo, EquatableArray Diagnostcs); \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Models/ShaderType.cs b/src/ComputeSharp.SourceGenerators/Models/ShaderType.cs deleted file mode 100644 index 9abb0833..00000000 --- a/src/ComputeSharp.SourceGenerators/Models/ShaderType.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace ComputeSharp.SourceGenerators.Models; - -/// -/// Indicates a type of shader being processed. -/// -public enum ShaderType -{ - /// - /// A compute shader. - /// - ComputeShader, - - /// - /// A pixel shader. - /// - PixelShader -} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/Models/ThreadIdsInfo.cs b/src/ComputeSharp.SourceGenerators/Models/ThreadIdsInfo.cs deleted file mode 100644 index aae33b3d..00000000 --- a/src/ComputeSharp.SourceGenerators/Models/ThreadIdsInfo.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace ComputeSharp.SourceGenerators.Models; - -/// -/// A model representing gathered info on a embedded thread ids. -/// -/// Whether the values are discarded. -/// The thread ids value for the X axis. -/// The thread ids value for the Y axis. -/// The thread ids value for the Z axis. -internal sealed record ThreadIdsInfo(bool IsDefault, int X, int Y, int Z); \ No newline at end of file