From 4e6f4f55d4721b2e5e1b822793af33e9cfffdad5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 10 Aug 2022 13:47:09 +0200 Subject: [PATCH] Initial implementation of generator for shader methods --- .../ComputeSharp.D2D1.SourceGenerators.csproj | 1 + ...xelShaderSourceGenerator.Execute.Syntax.cs | 73 +++++++++ .../D2DPixelShaderSourceGenerator.Execute.cs | 152 ++++++++++++++++++ .../D2DPixelShaderSourceGenerator.cs | 121 ++++++++++++++ ...nerator.CreateLoadBytecodeMethod.Syntax.cs | 2 +- ...haderGenerator.CreateLoadBytecodeMethod.cs | 8 +- 6 files changed, 351 insertions(+), 6 deletions(-) create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.Syntax.cs create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs create mode 100644 src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj index ec2e545f..6bc6a048 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj @@ -76,6 +76,7 @@ + diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.Syntax.cs new file mode 100644 index 00000000..bff66911 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.Syntax.cs @@ -0,0 +1,73 @@ +using System; +using System.Text; +using ComputeSharp.D2D1.SourceGenerators.Models; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; +using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class D2DPixelShaderSourceGenerator +{ + /// + partial class Execute + { + /// + /// Creates a instance for the TryGetBytecode method. + /// + /// The input bytecode info. + /// An opaque instance to transform the final tree into text. + /// The resulting instance for the target method. + public static MethodDeclarationSyntax GetSyntax(EmbeddedBytecodeInfo bytecodeInfo, out Func fixup) + { + // If there is no precompiled bytecode, just emit a span with a 0 value + string bytecodeLiterals = bytecodeInfo.Bytecode.IsDefaultOrEmpty + ? "0" + : ID2D1ShaderGenerator.LoadBytecode.BuildShaderBytecodeExpressionString(bytecodeInfo.Bytecode.AsSpan()); + + // Prepare the fixup function + fixup = tree => SourceText.From(tree.ToFullString().Replace("__EMBEDDED_SHADER_BYTECODE", bytecodeLiterals), Encoding.UTF8); + + // This code produces a branch as follows: + // + // /// + // [global::System.CodeDom.Compiler.GeneratedCode("...", "...")] + // [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] + // global::System.ReadOnlySpan () + // { + // return new byte[] { __EMBEDDED_SHADER_BYTECODE }; + // } + // + // As in the ID2D1Shader generator, the __EMBEDDED_SHADER_BYTECODE identifier will be replaced with the bytecode + // after the full string for the syntax tree has been generated, to avoid every literal going through a token. + return + MethodDeclaration( + GenericName(Identifier("global::System.ReadOnlySpan")) + .AddTypeArgumentListArguments(PredefinedType(Token(SyntaxKind.ByteKeyword))), + Identifier("TheMethodName")).AddModifiers(Token(SyntaxKind.PartialKeyword)) + .AddAttributeLists( + AttributeList(SingletonSeparatedList( + Attribute(IdentifierName("global::System.CodeDom.Compiler.GeneratedCode")) + .AddArgumentListArguments( + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(D2DPixelShaderSourceAttribute).FullName))), + AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(typeof(D2DPixelShaderSourceAttribute).Assembly.GetName().Version.ToString())))))) + .WithOpenBracketToken(Token(TriviaList(Comment( + $"/// ")), + SyntaxKind.OpenBracketToken, + TriviaList())), + AttributeList(SingletonSeparatedList(Attribute(IdentifierName("global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage"))))) + .WithBody(Block( + ReturnStatement( + ArrayCreationExpression( + ArrayType(PredefinedType(Token(SyntaxKind.ByteKeyword))) + .AddRankSpecifiers(ArrayRankSpecifier(SingletonSeparatedList(OmittedArraySizeExpression())))) + .WithInitializer( + InitializerExpression( + SyntaxKind.ArrayInitializerExpression, + SingletonSeparatedList(IdentifierName("__EMBEDDED_SHADER_BYTECODE"))))))); + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs new file mode 100644 index 00000000..9bd70fab --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.Execute.cs @@ -0,0 +1,152 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.ComponentModel; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading; +using ComputeSharp.D2D1.Exceptions; +using ComputeSharp.D2D1.Shaders.Translation; +using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Models; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; +using TerraFX.Interop.DirectX; +using TerraFX.Interop.Windows; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +partial class D2DPixelShaderSourceGenerator +{ + /// + /// A container for all the logic for . + /// + private static partial class Execute + { + /// + /// Extracts the HLSL source from a method with the annotation. + /// + /// The collection of produced instances. + /// The input instance to process. + /// The HLSL source to compile, if present. + public static string? GetHlslSource(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) + { + _ = methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DPixelShaderSourceAttribute", out AttributeData? attributeData); + + if (!attributeData!.TryGetConstructorArgument(0, out string? hlslSource)) + { + // TODO: no string diagnostic + } + + return hlslSource; + } + + /// + /// Extracts the shader profile for a target method, if present. + /// + /// The collection of produced instances. + /// The input instance to process. + /// The shader profile to use to compile the shader, if present. + public static D2D1ShaderProfile? GetShaderProfile(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) + { + if (methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DEmbeddedBytecodeAttribute", out AttributeData? attributeData)) + { + return (D2D1ShaderProfile)attributeData!.ConstructorArguments[0].Value!; + } + + if (methodSymbol.ContainingAssembly.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DEmbeddedBytecodeAttribute", out attributeData)) + { + return (D2D1ShaderProfile)attributeData!.ConstructorArguments[0].Value!; + } + + // TODO: diagnostics + + return null; + } + + /// + /// Extracts the compile options for the current shader. + /// + /// The collection of produced instances. + /// The input instance to process. + /// The compile options to use to compile the shader, if present. + public static D2D1CompileOptions? GetCompileOptions(ImmutableArray.Builder diagnostics, IMethodSymbol methodSymbol) + { + if (methodSymbol.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out AttributeData? attributeData)) + { + return (D2D1CompileOptions)attributeData!.ConstructorArguments[0].Value!; + } + + if (methodSymbol.ContainingAssembly.TryGetAttributeWithFullMetadataName("ComputeSharp.D2D1.D2DCompileOptionsAttribute", out attributeData)) + { + return (D2D1CompileOptions)attributeData!.ConstructorArguments[0].Value!; + } + + // TODO: diagnostics + + return null; + } + + /// + /// Gets an instance with the compiled bytecode for the current shader. + /// + /// The source info for the shader to compile. + /// 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(HlslShaderSourceInfo sourceInfo, CancellationToken token, out DiagnosticInfo? diagnostic) + { + ImmutableArray bytecode = ImmutableArray.Empty; + + // Skip compilation if there are any errors + if (sourceInfo is { HasErrors: true }) + { + diagnostic = null; + + goto End; + } + + try + { + token.ThrowIfCancellationRequested(); + + // Compile the shader bytecode using the requested parameters + using ComPtr dxcBlobBytecode = D3DCompiler.Compile( + sourceInfo.HlslSource.AsSpan(), + sourceInfo.ShaderProfile!.Value, + sourceInfo.CompileOptions!.Value); + + 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; + } + catch (Win32Exception e) + { + diagnostic = new DiagnosticInfo( + null!, // TODO + e.HResult, + ID2D1ShaderGenerator.LoadBytecode.FixupExceptionMessage(e.Message)); + } + catch (FxcCompilationException e) + { + diagnostic = new DiagnosticInfo( + null!, // TODO + ID2D1ShaderGenerator.LoadBytecode.FixupExceptionMessage(e.Message)); + } + + End: + return bytecode; + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs new file mode 100644 index 00000000..cf32c82f --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs @@ -0,0 +1,121 @@ +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using ComputeSharp.D2D1.SourceGenerators.Models; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Models; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace ComputeSharp.D2D1.SourceGenerators; + +/// +/// A source generator compiling methods annotated with . +/// +[Generator(LanguageNames.CSharp)] +public sealed partial class D2DPixelShaderSourceGenerator : IIncrementalGenerator +{ + /// + public void Initialize(IncrementalGeneratorInitializationContext context) + { + // Get all method declarations with the [D2DPixelShaderSource] attribute + IncrementalValuesProvider methodSymbols = + context.SyntaxProvider + .CreateSyntaxProvider( + static (node, _) => node is MethodDeclarationSyntax { Parent: ClassDeclarationSyntax, AttributeLists.Count: > 0 }, + static (context, _) => (IMethodSymbol)context.SemanticModel.GetDeclaredSymbol(context.Node)!) + .Where(static symbol => symbol.HasAttributeWithFullyQualifiedName("ComputeSharp.D2D1.D2DPixelShaderSourceAttribute")); + + // Gather info for all annotated methods + IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo Source, ImmutableArray Diagnostics)> shaderInfoWithErrors = + methodSymbols + .Select(static (item, _) => + { + ImmutableArray.Builder diagnostics = ImmutableArray.CreateBuilder(); + + // Get all necessary info for the current shader + string? hlslSource = Execute.GetHlslSource(diagnostics, item) ?? ""; + D2D1ShaderProfile? shaderProfile = Execute.GetShaderProfile(diagnostics, item); + D2D1CompileOptions? compileOptions = Execute.GetCompileOptions(diagnostics, item); + + HlslShaderSourceInfo sourceInfo = new( + hlslSource, + shaderProfile, + compileOptions, + IsLinkingSupported: false, + HasErrors: diagnostics.Count > 0); + + HierarchyInfo hierarchy = HierarchyInfo.From(item.ContainingType!); + + return (hierarchy, sourceInfo, diagnostics.ToImmutable()); + }); + + // Output the diagnostics + context.ReportDiagnostics(shaderInfoWithErrors.Select(static (item, _) => item.Diagnostics)); + + // Filter all items to enable caching at a coarse level, and remove diagnostics + IncrementalValuesProvider<(HierarchyInfo Hierarchy, HlslShaderSourceInfo Source)> shaderInfo = + shaderInfoWithErrors + .Select(static (item, token) => (item.Hierarchy, item.Source)) + .WithComparers(HierarchyInfo.Comparer.Default, EqualityComparer.Default); + + // Compile the requested shader bytecodes + IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo, DiagnosticInfo? Diagnostic)> embeddedBytecodeWithErrors = + shaderInfo + .Select(static (item, token) => + { + ImmutableArray bytecode = Execute.GetBytecode( + item.Source, + token, + out DiagnosticInfo? diagnostic); + + token.ThrowIfCancellationRequested(); + + EmbeddedBytecodeInfo bytecodeInfo = new( + item.Source.HlslSource, + item.Source.ShaderProfile, + item.Source.CompileOptions, + 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 Diagnostic.Create( + item.Left.Diagnostic!.Descriptor, + typeSymbol.Locations.FirstOrDefault(), + new object[] { typeSymbol }.Concat(item.Left.Diagnostic.Args).ToArray()); + }); + + // Output the diagnostics + context.ReportDiagnostics(embeddedBytecodeDiagnostics); + + // Get the filtered sequence to enable caching + IncrementalValuesProvider<(HierarchyInfo Hierarchy, EmbeddedBytecodeInfo BytecodeInfo)> embeddedBytecode = + embeddedBytecodeWithErrors + .Select(static (item, token) => (item.Hierarchy, item.BytecodeInfo)) + .WithComparers(HierarchyInfo.Comparer.Default, EmbeddedBytecodeInfo.Comparer.Default); + + // Generate the shader bytecode methods + context.RegisterSourceOutput(embeddedBytecode, static (context, item) => + { + MethodDeclarationSyntax loadBytecodeMethod = Execute.GetSyntax(item.BytecodeInfo, out Func fixup); + CompilationUnitSyntax compilationUnit = item.Hierarchy.GetSyntax(loadBytecodeMethod); + SourceText text = fixup(compilationUnit); + + context.AddSource($"{item.Hierarchy.FilenameHint}.TESTMETHOD", text); + }); + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs index be30d274..32b042eb 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs @@ -214,7 +214,7 @@ partial class ID2D1ShaderGenerator /// /// The input shader bytecode to serialize. /// A formatted with the serialized data. - private static string BuildShaderBytecodeExpressionString(ReadOnlySpan bytecode) + internal static string BuildShaderBytecodeExpressionString(ReadOnlySpan bytecode) { //The estimation is 4 characters per byte (up to "255" in hex), plus ", " to separate sequential values using ArrayPoolStringBuilder builder = ArrayPoolStringBuilder.Create(bytecode.Length * 6); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs index a9cc40d5..97dacb14 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs @@ -11,8 +11,6 @@ using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; using TerraFX.Interop.DirectX; using TerraFX.Interop.Windows; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; @@ -25,7 +23,7 @@ partial class ID2D1ShaderGenerator /// /// A helper with all logic to generate the LoadBytecode method. /// - private static partial class LoadBytecode + internal static partial class LoadBytecode { /// /// Extracts the shader profile for the current shader. @@ -142,7 +140,7 @@ partial class ID2D1ShaderGenerator } /// - /// Gets a instance with the logic to try to get a compiled shader bytecode. + /// Gets an instance with the compiled bytecode for the current shader. /// /// The source info for the shader to compile. /// The used to cancel the operation, if needed. @@ -212,7 +210,7 @@ partial class ID2D1ShaderGenerator /// /// The input exception message. /// The updated exception message. - private static string FixupExceptionMessage(string message) + internal static string FixupExceptionMessage(string message) { // Add square brackets around error headers message = Regex.Replace(message, @"((?:error|warning) \w+):", static m => $"[{m.Groups[1].Value}]:");