From 75a04100ec11e61595e5a9131504d76712d2a0a4 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 21 Oct 2022 16:23:17 +0200 Subject: [PATCH 1/4] Add NotNullAttribute polyfill in ComputeSharp.D2D1 --- .../ComputeSharp.D2D1.NetStandard.projitems | 1 + .../Diagnostics.CodeAnalysis/NotNullAttribute.cs | 15 +++++++++++++++ 2 files changed, 16 insertions(+) create mode 100644 src/ComputeSharp.D2D1.NetStandard/System/Diagnostics.CodeAnalysis/NotNullAttribute.cs diff --git a/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.projitems b/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.projitems index ab355d3f..e130179f 100644 --- a/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.projitems +++ b/src/ComputeSharp.D2D1.NetStandard/ComputeSharp.D2D1.NetStandard.projitems @@ -11,6 +11,7 @@ + diff --git a/src/ComputeSharp.D2D1.NetStandard/System/Diagnostics.CodeAnalysis/NotNullAttribute.cs b/src/ComputeSharp.D2D1.NetStandard/System/Diagnostics.CodeAnalysis/NotNullAttribute.cs new file mode 100644 index 00000000..ca082723 --- /dev/null +++ b/src/ComputeSharp.D2D1.NetStandard/System/Diagnostics.CodeAnalysis/NotNullAttribute.cs @@ -0,0 +1,15 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace System.Diagnostics.CodeAnalysis; + +/// +/// Specifies that an output will not be null even if the corresponding type allows it. +/// Specifies that an input argument was not null when the call returns. +/// +/// Internal copy from the BCL attribute. +[AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue, Inherited = false)] +internal sealed class NotNullAttribute : Attribute +{ +} \ No newline at end of file From b1ce0e9c43ddfccc6ffffb6214b1cd2b6fb9e39f Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 21 Oct 2022 16:24:45 +0200 Subject: [PATCH 2/4] Add APIs to get effective shader profile and compile options --- .../Interfaces/__Internals/ID2D1Shader.cs | 6 +- .../Shaders/Interop/D2D1PixelShader.cs | 127 +++++++++++++++--- .../Shaders/Interop/D2D1ReflectionServices.cs | 5 +- .../D2D1PixelShaderTests.cs | 8 +- 4 files changed, 121 insertions(+), 25 deletions(-) diff --git a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs index e4e84512..e4c9ae28 100644 --- a/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs +++ b/src/ComputeSharp.D2D1/Interfaces/__Internals/ID2D1Shader.cs @@ -1,5 +1,6 @@ using System; using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; namespace ComputeSharp.D2D1.__Internals; @@ -98,10 +99,11 @@ public interface ID2D1Shader /// The type of bytecode loader being used. /// The instance to use to load the bytecode. /// The shader profile to use to get the shader bytecode (if , the precompiled shader will be used). - /// The compile options to use to get the shader bytecode (if , the precompiled shader will be used). + /// The compile options to use to get the shader bytecode (if , the precompiled shader will be used). /// Thrown if a precompiled bytecode was requested ( is ), but it wasn't availablle. + /// When this method returns, and will be set to the effective laues used to create the shader bytecode that was loaded. [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This method is not intended to be used directly by user code")] - void LoadBytecode(ref TLoader loader, D2D1ShaderProfile? shaderProfile, D2D1CompileOptions? options) + void LoadBytecode(ref TLoader loader, [NotNull] ref D2D1ShaderProfile? shaderProfile, [NotNull] ref D2D1CompileOptions? compileOptions) where TLoader : struct, ID2D1BytecodeLoader; } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs index 134616a9..4203a859 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1PixelShader.cs @@ -30,7 +30,27 @@ public static class D2D1PixelShader public static ReadOnlyMemory LoadBytecode() where T : unmanaged, ID2D1PixelShader { - return LoadOrCompileBytecode(null, null); + return LoadOrCompileBytecode(null, null, out _, out _); + } + + /// + /// Loads the bytecode from an input D2D1 pixel shader. + /// + /// The type of D2D1 pixel shader to load the bytecode for. + /// The resulting that was used to compile the returned bytecode. + /// The resulting that were used to compile the returned bytecode. + /// A instance with the resulting shader bytecode. + /// + /// This method will only compile the shader using if no precompiled shader is available. + /// + /// If the input shader was precompiled, the returned instance will wrap a pinned memory buffer (from the PE section). + /// If the shader was compiled at runtime, the returned instance will wrap a array with the bytecode. + /// + /// + public static ReadOnlyMemory LoadBytecode(out D2D1ShaderProfile shaderProfile, out D2D1CompileOptions compileOptions) + where T : unmanaged, ID2D1PixelShader + { + return LoadOrCompileBytecode(null, null, out shaderProfile, out compileOptions); } /// @@ -56,19 +76,46 @@ public static class D2D1PixelShader public static ReadOnlyMemory LoadBytecode(D2D1ShaderProfile shaderProfile) where T : unmanaged, ID2D1PixelShader { - return LoadOrCompileBytecode(shaderProfile, null); + return LoadOrCompileBytecode(shaderProfile, null, out _, out _); } /// /// Loads the bytecode from an input D2D1 pixel shader. /// /// The type of D2D1 pixel shader to load the bytecode for. - /// + /// The shader profile to use to get the shader bytecode. + /// The resulting that were used to compile the returned bytecode. + /// A instance with the resulting shader bytecode. + /// + /// + /// If precompiled shader for the profile does not exist, the shader will be compiled with either the custom compile options specified on the shader + /// type (through ), or using otherwise. + /// + /// + /// Additionally, in case no custom compile options are specified and the the shader type + /// supports linking, will also be automatically added. + /// + /// + /// If the input shader was precompiled, the returned instance will wrap a pinned memory buffer (from the PE section). + /// If the shader was compiled at runtime, the returned instance will wrap a array with the bytecode. + /// + /// + public static ReadOnlyMemory LoadBytecode(D2D1ShaderProfile shaderProfile, out D2D1CompileOptions compileOptions) + where T : unmanaged, ID2D1PixelShader + { + return LoadOrCompileBytecode(shaderProfile, null, out _, out compileOptions); + } + + /// + /// Loads the bytecode from an input D2D1 pixel shader. + /// + /// The type of D2D1 pixel shader to load the bytecode for. + /// /// The compile options to use to get the shader bytecode. /// For consistency with , will be automatically added. /// /// A instance with the resulting shader bytecode. - /// Thrown if is specified within . + /// Thrown if is specified within . /// /// /// If precompiled shader with the requested options does not exist, the shader will be compiled with the input options. If additional compile @@ -82,15 +129,50 @@ public static class D2D1PixelShader /// If the shader was compiled at runtime, the returned instance will wrap a array with the bytecode. /// /// - public static ReadOnlyMemory LoadBytecode(D2D1CompileOptions options) + public static ReadOnlyMemory LoadBytecode(D2D1CompileOptions compileOptions) where T : unmanaged, ID2D1PixelShader { - if ((options & D2D1CompileOptions.PackMatrixColumnMajor) != 0) + if ((compileOptions & D2D1CompileOptions.PackMatrixColumnMajor) != 0) { - ThrowHelper.ThrowArgumentException(nameof(options), "The PackMatrixColumnMajor compile options is not compatible with ComputeSharp.D2D1 shaders."); + ThrowHelper.ThrowArgumentException(nameof(compileOptions), "The PackMatrixColumnMajor compile options is not compatible with ComputeSharp.D2D1 shaders."); } - return LoadOrCompileBytecode(null, options | D2D1CompileOptions.PackMatrixRowMajor); + return LoadOrCompileBytecode(null, compileOptions | D2D1CompileOptions.PackMatrixRowMajor, out _, out _); + } + + /// + /// Loads the bytecode from an input D2D1 pixel shader. + /// + /// The type of D2D1 pixel shader to load the bytecode for. + /// + /// The compile options to use to get the shader bytecode. + /// For consistency with , will be automatically added. + /// + /// The resulting that was used to compile the returned bytecode. + /// A instance with the resulting shader bytecode. + /// Thrown if is specified within . + /// + /// + /// If precompiled shader with the requested options does not exist, the shader will be compiled with the input options. If additional compile + /// options have been specified on the shader type (through ), they will be ignored. + /// + /// + /// If the shader needs to be recompiled, the shader profile that will be used is . + /// + /// + /// If the input shader was precompiled, the returned instance will wrap a pinned memory buffer (from the PE section). + /// If the shader was compiled at runtime, the returned instance will wrap a array with the bytecode. + /// + /// + public static ReadOnlyMemory LoadBytecode(D2D1CompileOptions compileOptions, out D2D1ShaderProfile shaderProfile) + where T : unmanaged, ID2D1PixelShader + { + if ((compileOptions & D2D1CompileOptions.PackMatrixColumnMajor) != 0) + { + ThrowHelper.ThrowArgumentException(nameof(compileOptions), "The PackMatrixColumnMajor compile options is not compatible with ComputeSharp.D2D1 shaders."); + } + + return LoadOrCompileBytecode(null, compileOptions | D2D1CompileOptions.PackMatrixRowMajor, out shaderProfile, out _); } /// @@ -98,43 +180,52 @@ public static class D2D1PixelShader /// /// The type of D2D1 pixel shader to load the bytecode for. /// The shader profile to use to get the shader bytecode. - /// + /// /// The compile options to use to get the shader bytecode. /// For consistency with , will be automatically added. /// /// A instance with the resulting shader bytecode. - /// Thrown if is specified within . + /// Thrown if is specified within . /// /// If the input shader was precompiled, the returned instance will wrap a pinned memory buffer (from the PE section). /// If the shader was compiled at runtime, the returned instance will wrap a array with the bytecode. /// - public static ReadOnlyMemory LoadBytecode(D2D1ShaderProfile shaderProfile, D2D1CompileOptions options) + public static ReadOnlyMemory LoadBytecode(D2D1ShaderProfile shaderProfile, D2D1CompileOptions compileOptions) where T : unmanaged, ID2D1PixelShader { - if ((options & D2D1CompileOptions.PackMatrixColumnMajor) != 0) + if ((compileOptions & D2D1CompileOptions.PackMatrixColumnMajor) != 0) { - ThrowHelper.ThrowArgumentException(nameof(options), "The PackMatrixColumnMajor compile options is not compatible with ComputeSharp.D2D1 shaders."); + ThrowHelper.ThrowArgumentException(nameof(compileOptions), "The PackMatrixColumnMajor compile options is not compatible with ComputeSharp.D2D1 shaders."); } - return LoadOrCompileBytecode(shaderProfile, options | D2D1CompileOptions.PackMatrixRowMajor); + return LoadOrCompileBytecode(shaderProfile, compileOptions | D2D1CompileOptions.PackMatrixRowMajor, out _, out _); } /// /// Loads or compiles the bytecode from an input D2D1 pixel shader. /// /// The type of D2D1 pixel shader to load the bytecode for. - /// The shader profile to use to get the shader bytecode. - /// The compile options to use to get the shader bytecode. + /// The requested shader profile to use to get the shader bytecode. + /// The requested compile options to use to get the shader bytecode. + /// The effective shader profile that was used to get the shader bytecode. + /// The effective compile options that were used to get the shader bytecode. /// A instance with the resulting shader bytecode. /// Thrown if the input shader has not been precompiled. - private static unsafe ReadOnlyMemory LoadOrCompileBytecode(D2D1ShaderProfile? shaderProfile, D2D1CompileOptions? options) + private static unsafe ReadOnlyMemory LoadOrCompileBytecode( + D2D1ShaderProfile? requestedShaderProfile, + D2D1CompileOptions? requestedCompileOptions, + out D2D1ShaderProfile effectiveShaderProfile, + out D2D1CompileOptions effectiveCompileOptions) where T : unmanaged, ID2D1PixelShader { D2D1ShaderBytecodeLoader bytecodeLoader = default; Unsafe.SkipInit(out T shader); - shader.LoadBytecode(ref bytecodeLoader, shaderProfile, options); + shader.LoadBytecode(ref bytecodeLoader, ref requestedShaderProfile, ref requestedCompileOptions); + + effectiveShaderProfile = requestedShaderProfile.GetValueOrDefault(); + effectiveCompileOptions = requestedCompileOptions.GetValueOrDefault(); using ComPtr dynamicBytecode = bytecodeLoader.GetResultingShaderBytecode(out ReadOnlySpan precompiledBytecode); diff --git a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs index 64c066df..958e4c5d 100644 --- a/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs +++ b/src/ComputeSharp.D2D1/Shaders/Interop/D2D1ReflectionServices.cs @@ -37,7 +37,10 @@ public static class D2D1ReflectionServices D2D1ShaderBytecodeLoader bytecodeLoader = default; - shader.LoadBytecode(ref bytecodeLoader, null, null); + D2D1ShaderProfile? shaderProfile = null; + D2D1CompileOptions? compileOptions = null; + + shader.LoadBytecode(ref bytecodeLoader, ref shaderProfile, ref compileOptions); using ComPtr dynamicBytecode = bytecodeLoader.GetResultingShaderBytecode(out ReadOnlySpan precompiledBytecode); diff --git a/tests/ComputeSharp.D2D1.Tests.AssemblyLevelAttributes/D2D1PixelShaderTests.cs b/tests/ComputeSharp.D2D1.Tests.AssemblyLevelAttributes/D2D1PixelShaderTests.cs index 4a26be0f..9c3b0f3e 100644 --- a/tests/ComputeSharp.D2D1.Tests.AssemblyLevelAttributes/D2D1PixelShaderTests.cs +++ b/tests/ComputeSharp.D2D1.Tests.AssemblyLevelAttributes/D2D1PixelShaderTests.cs @@ -21,7 +21,7 @@ public partial class D2D1PixelShaderTests _ = D2D1PixelShader.LoadBytecode( shaderProfile: D2D1ShaderProfile.PixelShader41, - options: D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.PartialPrecision); + compileOptions: D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.PartialPrecision); // Verify the expected options were used Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager)); @@ -55,7 +55,7 @@ public partial class D2D1PixelShaderTests _ = D2D1PixelShader.LoadBytecode( shaderProfile: D2D1ShaderProfile.PixelShader50, - options: D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.PartialPrecision); + compileOptions: D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.PartialPrecision); Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager)); Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name); @@ -89,7 +89,7 @@ public partial class D2D1PixelShaderTests _ = D2D1PixelShader.LoadBytecode( shaderProfile: D2D1ShaderProfile.PixelShader41, - options: D2D1CompileOptions.Debug | D2D1CompileOptions.AvoidFlowControl | D2D1CompileOptions.PartialPrecision); + compileOptions: D2D1CompileOptions.Debug | D2D1CompileOptions.AvoidFlowControl | D2D1CompileOptions.PartialPrecision); Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager)); Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name); @@ -123,7 +123,7 @@ public partial class D2D1PixelShaderTests _ = D2D1PixelShader.LoadBytecode( shaderProfile: D2D1ShaderProfile.PixelShader50, - options: D2D1CompileOptions.Debug | D2D1CompileOptions.AvoidFlowControl | D2D1CompileOptions.PartialPrecision); + compileOptions: D2D1CompileOptions.Debug | D2D1CompileOptions.AvoidFlowControl | D2D1CompileOptions.PartialPrecision); Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager)); Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name); From 01a80f1e3372f07d1119a9c72403d9b57e166d1b Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 21 Oct 2022 17:22:59 +0200 Subject: [PATCH 3/4] Update source generator and fix default shader profile codegen --- ...nerator.CreateLoadBytecodeMethod.Syntax.cs | 108 ++++++++++++------ ...haderGenerator.CreateLoadBytecodeMethod.cs | 24 ++-- .../ID2D1ShaderGenerator.cs | 7 +- .../Models/EmbeddedBytecodeInfo.cs | 6 +- 4 files changed, 91 insertions(+), 54 deletions(-) diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs index fa1d20f6..3dd66174 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.Syntax.cs @@ -42,7 +42,7 @@ partial class ID2D1ShaderGenerator // This code produces a method declaration as follows: // - // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadBytecode(ref TLoader loader, global::ComputeSharp.D2D1.D2D1ShaderProfile? shaderProfile, global::ComputeSharp.D2D1.D2D1CompileOptions? options) + // readonly void global::ComputeSharp.D2D1.__Internals.ID2D1Shader.LoadBytecode(ref TLoader loader, ref global::ComputeSharp.D2D1.D2D1ShaderProfile? shaderProfile, ref global::ComputeSharp.D2D1.D2D1CompileOptions? compileOptions) // { // // } @@ -53,8 +53,8 @@ partial class ID2D1ShaderGenerator .AddTypeParameterListParameters(TypeParameter(Identifier("TLoader"))) .AddParameterListParameters( Parameter(Identifier("loader")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(IdentifierName("TLoader")), - Parameter(Identifier("shaderProfile")).WithType(NullableType(IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile"))), - Parameter(Identifier("options")).WithType(NullableType(IdentifierName("global::ComputeSharp.D2D1.D2D1CompileOptions")))) + Parameter(Identifier("shaderProfile")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(NullableType(IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile"))), + Parameter(Identifier("compileOptions")).AddModifiers(Token(SyntaxKind.RefKeyword)).WithType(NullableType(IdentifierName("global::ComputeSharp.D2D1.D2D1CompileOptions")))) .WithBody(block); } @@ -80,59 +80,85 @@ partial class ID2D1ShaderGenerator // and the options will be set to D2D1CompileOptions.Default (and optionally, D2D1CompileOptions.EnableLinking too). // Get a formatted representation of the compile options being used - ExpressionSyntax optionsExpression = + ExpressionSyntax compileOptionsExpression = ParseExpression( bytecodeInfo.CompileOptions - .GetValueOrDefault() .ToString(CultureInfo.InvariantCulture) .Split(',') .Select(static name => $"global::ComputeSharp.D2D1.D2D1CompileOptions.{name.Trim()}") .Aggregate("", static (left, right) => left.Length > 0 ? $"{left} | {right}" : right)); // Add parantheses if needed - if (optionsExpression is BinaryExpressionSyntax) + if (compileOptionsExpression is BinaryExpressionSyntax) { - optionsExpression = ParenthesizedExpression(optionsExpression); + compileOptionsExpression = ParenthesizedExpression(compileOptionsExpression); } - // This code produces a method declaration as follows: + // This code produces a block declaration as follows: // - // global::ComputeSharp.D2D1.__Internals.D2D1ShaderCompiler.LoadDynamicBytecode(ref loader, in this, shaderProfile ?? , options ?? ); - ExpressionStatementSyntax dynamicLoadingStatement = - ExpressionStatement( - InvocationExpression( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::ComputeSharp.D2D1.__Internals.D2D1ShaderCompiler"), - IdentifierName("LoadDynamicBytecode"))) - .AddArgumentListArguments( - Argument(IdentifierName("loader")).WithRefKindKeyword(Token(SyntaxKind.RefKeyword)), - Argument(ThisExpression()).WithRefKindKeyword(Token(SyntaxKind.InKeyword)), - Argument(BinaryExpression( - SyntaxKind.CoalesceExpression, - IdentifierName("shaderProfile"), - IdentifierName($"global::ComputeSharp.D2D1.D2D1ShaderProfile.{D2D1ShaderProfile.PixelShader50}"))), - Argument(BinaryExpression( - SyntaxKind.CoalesceExpression, - IdentifierName("options"), - optionsExpression)))); + // global::ComputeSharp.D2D1.D2D1ShaderProfile effectiveShaderProfile = shaderProfile ??= ; + // global::ComputeSharp.D2D1.D2D1CompileOptions effectiveCompileOptions = compileOptions ??= ; + // + // global::ComputeSharp.D2D1.__Internals.D2D1ShaderCompiler.LoadDynamicBytecode(ref loader, in this, effectiveShaderProfile, effectiveCompileOptions); + BlockSyntax dynamicLoadingBlock = + Block( + LocalDeclarationStatement( + VariableDeclaration(IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile")) + .AddVariables( + VariableDeclarator(Identifier("effectiveShaderProfile")) + .WithInitializer(EqualsValueClause( + AssignmentExpression( + SyntaxKind.CoalesceAssignmentExpression, + IdentifierName("shaderProfile"), + IdentifierName($"global::ComputeSharp.D2D1.D2D1ShaderProfile.{D2D1ShaderProfile.PixelShader50}")))))), + LocalDeclarationStatement( + VariableDeclaration(IdentifierName("global::ComputeSharp.D2D1.D2D1CompileOptions")) + .AddVariables( + VariableDeclarator(Identifier("effectiveCompileOptions")) + .WithInitializer(EqualsValueClause( + AssignmentExpression( + SyntaxKind.CoalesceAssignmentExpression, + IdentifierName("compileOptions"), + compileOptionsExpression))))), + ExpressionStatement( + InvocationExpression( + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("global::ComputeSharp.D2D1.__Internals.D2D1ShaderCompiler"), + IdentifierName("LoadDynamicBytecode"))) + .AddArgumentListArguments( + Argument(IdentifierName("loader")).WithRefKindKeyword(Token(SyntaxKind.RefKeyword)), + Argument(ThisExpression()).WithRefKindKeyword(Token(SyntaxKind.InKeyword)), + Argument(IdentifierName("effectiveShaderProfile")), + Argument(IdentifierName("effectiveCompileOptions"))))); // If there is no precompiled bytecode, just return the dynamic path if (bytecodeInfo.Bytecode.IsDefaultOrEmpty) { bytecodeLiterals = null; - return Block(dynamicLoadingStatement); + return dynamicLoadingBlock; } bytecodeLiterals = SyntaxFormattingHelper.BuildByteArrayInitializationExpressionString(bytecodeInfo.Bytecode.AsSpan()); + // Prepare the expression for the default shader profile to use + ExpressionSyntax shaderProfileExpression = + MemberAccessExpression( + SyntaxKind.SimpleMemberAccessExpression, + IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile"), + IdentifierName(bytecodeInfo.ShaderProfile.ToString(CultureInfo.InvariantCulture))); + // This code produces a branch as follows: // - // if (shaderProfile is null or && options is null or ) + // if (shaderProfile is null or && compileOptions is null or ) // { // global::System.ReadOnlySpan bytecode = new byte[] { __EMBEDDED_SHADER_BYTECODE }; + // // loader.LoadEmbeddedBytecode(bytecode); + // + // shaderProfile = ; + // compileOptions = ; // } // // Note that the __EMBEDDED_SHADER_BYTECODE identifier will be replaced after the string @@ -147,17 +173,13 @@ partial class ID2D1ShaderGenerator BinaryPattern( SyntaxKind.OrPattern, ConstantPattern(LiteralExpression(SyntaxKind.NullLiteralExpression)), - ConstantPattern( - MemberAccessExpression( - SyntaxKind.SimpleMemberAccessExpression, - IdentifierName("global::ComputeSharp.D2D1.D2D1ShaderProfile"), - IdentifierName(bytecodeInfo.ShaderProfile.GetValueOrDefault().ToString(CultureInfo.InvariantCulture)))))), + ConstantPattern(shaderProfileExpression))), IsPatternExpression( - IdentifierName("options"), + IdentifierName("compileOptions"), BinaryPattern( SyntaxKind.OrPattern, ConstantPattern(LiteralExpression(SyntaxKind.NullLiteralExpression)), - ConstantPattern(optionsExpression)))), + ConstantPattern(compileOptionsExpression)))), Block( LocalDeclarationStatement( VariableDeclaration( @@ -180,10 +202,20 @@ partial class ID2D1ShaderGenerator SyntaxKind.SimpleMemberAccessExpression, IdentifierName("loader"), IdentifierName("LoadEmbeddedBytecode"))) - .AddArgumentListArguments(Argument(IdentifierName("bytecode")))))); + .AddArgumentListArguments(Argument(IdentifierName("bytecode")))), + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("shaderProfile"), + shaderProfileExpression)), + ExpressionStatement( + AssignmentExpression( + SyntaxKind.SimpleAssignmentExpression, + IdentifierName("compileOptions"), + compileOptionsExpression)))); // Return the combined block - return Block(embeddedBranch.WithElse(ElseClause(Block(dynamicLoadingStatement)))); + return Block(embeddedBranch.WithElse(ElseClause(dynamicLoadingBlock))); } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs index 8c684364..4eeeca26 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.CreateLoadBytecodeMethod.cs @@ -117,15 +117,24 @@ partial class ID2D1ShaderGenerator /// /// The source info for the shader to compile. /// The used to cancel the operation, if needed. - /// The effective compile options used to create the shader bytecode. + /// The effective shader profile used to create the shader bytecode, or the default profile to use. + /// The effective compile options used to create the shader bytecode, or the default options to use. /// 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 D2D1CompileOptions options, + out D2D1ShaderProfile shaderProfile, + out D2D1CompileOptions compileOptions, out DeferredDiagnosticInfo? diagnostic) { + // Set the shader profile to either be the requested one, or the default value (which maps to PS5.0) + shaderProfile = sourceInfo.ShaderProfile ?? D2D1ShaderProfile.PixelShader50; + + // If an explicit set of compile options is provided, use that directly. Otherwise, use the default + // options plus the option to enable linking only if the shader can potentially support it. + compileOptions = sourceInfo.CompileOptions ?? (D2D1CompileOptions.Default | (sourceInfo.IsLinkingSupported ? D2D1CompileOptions.EnableLinking : 0)); + ImmutableArray bytecode = ImmutableArray.Empty; // No embedded shader was requested, or there were some errors earlier in the pipeline. @@ -133,7 +142,6 @@ partial class ID2D1ShaderGenerator // Compiling would just add overhead and result in more errors, as the HLSL would be invalid. if (sourceInfo is { HasErrors: true } or { ShaderProfile: null }) { - options = default; diagnostic = null; goto End; @@ -143,15 +151,11 @@ partial class ID2D1ShaderGenerator { token.ThrowIfCancellationRequested(); - // If an explicit set of compile options is provided, use that directly. Otherwise, use the default - // options plus the option to enable linking only if the shader can potentially support it. - options = sourceInfo.CompileOptions ?? (D2D1CompileOptions.Default | (sourceInfo.IsLinkingSupported ? D2D1CompileOptions.EnableLinking : 0)); - // Compile the shader bytecode using the requested parameters using ComPtr dxcBlobBytecode = D3DCompiler.Compile( sourceInfo.HlslSource.AsSpan(), sourceInfo.ShaderProfile.Value, - options); + compileOptions); token.ThrowIfCancellationRequested(); @@ -165,12 +169,12 @@ partial class ID2D1ShaderGenerator } catch (Win32Exception e) { - options = default; + compileOptions = default; diagnostic = DeferredDiagnosticInfo.Create(EmbeddedBytecodeFailedWithWin32Exception, e.HResult, FixupExceptionMessage(e.Message)); } catch (FxcCompilationException e) { - options = default; + compileOptions = default; diagnostic = DeferredDiagnosticInfo.Create(EmbeddedBytecodeFailedWithFxcCompilationException, FixupExceptionMessage(e.Message)); } diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs index ed1238b5..cbaa6994 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/ID2D1ShaderGenerator.cs @@ -239,15 +239,16 @@ public sealed partial class ID2D1ShaderGenerator : IIncrementalGenerator ImmutableArray bytecode = LoadBytecode.GetBytecode( item.Source, token, - out D2D1CompileOptions options, + out D2D1ShaderProfile shaderProfile, + out D2D1CompileOptions compileOptions, out DeferredDiagnosticInfo? diagnostic); token.ThrowIfCancellationRequested(); EmbeddedBytecodeInfo bytecodeInfo = new( item.Source.HlslSource, - item.Source.ShaderProfile, - options, + shaderProfile, + compileOptions, bytecode); return (item.Hierarchy, bytecodeInfo, diagnostic); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeInfo.cs b/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeInfo.cs index 72a49d1e..d8dade33 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeInfo.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Models/EmbeddedBytecodeInfo.cs @@ -6,7 +6,7 @@ namespace ComputeSharp.D2D1.SourceGenerators.Models; /// A model representing info on a shader that has requested to be precompiled at build time. /// /// The HLSL source for the shader. -/// The shader profile to use to compile the shader, if requested. -/// The compile options to use to compile the shader. +/// The shader profile to use to compile the shader, or the default one. +/// The compile options to use to compile the shader, or the default one. /// The compiled shader bytecode, if available. -internal sealed record EmbeddedBytecodeInfo(string HlslSource, D2D1ShaderProfile? ShaderProfile, D2D1CompileOptions? CompileOptions, EquatableArray Bytecode); \ No newline at end of file +internal sealed record EmbeddedBytecodeInfo(string HlslSource, D2D1ShaderProfile ShaderProfile, D2D1CompileOptions CompileOptions, EquatableArray Bytecode); \ No newline at end of file From 8e5fc40f927cc983eae51dc8636c18ab0ae825e6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 21 Oct 2022 17:59:07 +0200 Subject: [PATCH 4/4] Add unit tests for shader compilation effective values --- .../D2D1PixelShaderTests.cs | 72 +++++++++++++++++-- 1 file changed, 68 insertions(+), 4 deletions(-) diff --git a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs index 336f47b4..6c264798 100644 --- a/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs +++ b/tests/ComputeSharp.D2D1.Tests/D2D1PixelShaderTests.cs @@ -316,11 +316,13 @@ public partial class D2D1PixelShaderTests Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out MemoryManager? manager)); Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name); - // Matching shader profile - bytecode = D2D1PixelShader.LoadBytecode(D2D1ShaderProfile.PixelShader40Level91); + // Bytecode with all output parameters + ReadOnlyMemory bytecode2 = D2D1PixelShader.LoadBytecode(out D2D1ShaderProfile shaderProfile, out D2D1CompileOptions compileOptions); - Assert.IsTrue(MemoryMarshal.TryGetMemoryManager(bytecode, out manager)); - Assert.AreEqual("PinnedBufferMemoryManager", manager!.GetType().Name); + // The bytecode is the same + Assert.IsTrue(bytecode.Span == bytecode2.Span); + Assert.AreEqual(shaderProfile, D2D1ShaderProfile.PixelShader40Level91); + Assert.AreEqual(compileOptions, D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.PackMatrixRowMajor); // Matching compile options bytecode = D2D1PixelShader.LoadBytecode(D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.OptimizationLevel2); @@ -354,6 +356,68 @@ public partial class D2D1PixelShaderTests } } + [TestMethod] + public void LoadBytecode_VerifyEffectiveValues_ExplicitShaderProfile() + { + _ = D2D1PixelShader.LoadBytecode(out D2D1ShaderProfile shaderProfile, out D2D1CompileOptions compileOptions); + + Assert.AreEqual(shaderProfile, D2D1ShaderProfile.PixelShader40Level91); + Assert.AreEqual(compileOptions, D2D1CompileOptions.Default | D2D1CompileOptions.EnableLinking); + + _ = D2D1PixelShader.LoadBytecode(out shaderProfile, out compileOptions); + + // This shader has a complex input, so it can't support shader linking + Assert.AreEqual(shaderProfile, D2D1ShaderProfile.PixelShader40Level91); + Assert.AreEqual(compileOptions, D2D1CompileOptions.Default); + } + + [D2DInputCount(1)] + [D2DInputSimple(0)] + [D2DShaderProfile(D2D1ShaderProfile.PixelShader40Level91)] + private readonly partial struct SimpleShaderWithExplicitShaderProfileAndNoCompileOptions : ID2D1PixelShader + { + public float4 Execute() + { + return D2D.GetInput(0); + } + } + + [D2DInputCount(1)] + [D2DInputComplex(0)] + [D2DShaderProfile(D2D1ShaderProfile.PixelShader40Level91)] + private readonly partial struct ComplexShaderWithExplicitShaderProfileAndNoCompileOptions : ID2D1PixelShader + { + public float4 Execute() + { + return D2D.GetInput(0); + } + } + + [TestMethod] + public void LoadBytecode_VerifyEffectiveValues_ExplicitCompileOptions() + { + _ = D2D1PixelShader.LoadBytecode(out D2D1ShaderProfile shaderProfile, out D2D1CompileOptions compileOptions); + + // PS5.0 is the default, when no value is specified + Assert.AreEqual(shaderProfile, D2D1ShaderProfile.PixelShader50); + Assert.AreEqual(compileOptions, D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.PackMatrixRowMajor); + + _ = D2D1PixelShader.LoadBytecode(D2D1ShaderProfile.PixelShader40, out compileOptions); + + Assert.AreEqual(compileOptions, D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.IeeeStrictness | D2D1CompileOptions.PackMatrixRowMajor); + } + + [D2DInputCount(1)] + [D2DInputSimple(0)] + [D2DCompileOptions(D2D1CompileOptions.OptimizationLevel2 | D2D1CompileOptions.IeeeStrictness)] + private readonly partial struct ShaderWithExplicitCompileOptionsAndNoShaderProfile : ID2D1PixelShader + { + public float4 Execute() + { + return D2D.GetInput(0); + } + } + [TestMethod] public unsafe void GetConstantBufferSize_Empty() {