diff --git a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj index 1644d727..7abb2695 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj +++ b/src/ComputeSharp.D2D1.SourceGenerators/ComputeSharp.D2D1.SourceGenerators.csproj @@ -1,6 +1,7 @@ netstandard2.0 + $(DefineConstants);D2D1_SOURCE_GENERATOR diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.cs index 210e2ee1..19bf6d1f 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.HlslBytecode.cs @@ -1,16 +1,8 @@ using System; -using System.Collections.Immutable; -using System.ComponentModel; -using System.Runtime.CompilerServices; -using System.Threading; -using ComputeSharp.D2D1.Shaders.Translation; -using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; using Microsoft.CodeAnalysis; -using Windows.Win32; -using Windows.Win32.Graphics.Direct3D; using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; namespace ComputeSharp.D2D1.SourceGenerators; @@ -23,11 +15,6 @@ partial class D2DPixelShaderDescriptorGenerator /// internal static partial class HlslBytecode { - /// - /// The shared cache of values. - /// - private static readonly DynamicCache HlslBytecodeCache = new(); - /// /// Extracts the requested shader profile for the current shader. /// @@ -178,142 +165,5 @@ partial class D2DPixelShaderDescriptorGenerator return isSimpleInputShader; } - - /// - /// Gets the instance for the input shader info. - /// - /// 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) - { - // Check if the compilation is not enabled (eg. if there's been errors earlier in the pipeline). - // In this case, skip the compilation, as diagnostic will be emitted for those anyway. - // Compiling would just add overhead and result in more errors, as the HLSL would be invalid. - if (!key.IsCompilationEnabled) - { - return HlslBytecodeInfo.Missing.Instance; - } - - try - { - token.ThrowIfCancellationRequested(); - - // Compile the shader bytecode using the effective parameters - using ComPtr d3DBlob = D3DCompiler.Compile( - key.HlslSource.AsSpan(), - key.ShaderProfile, - key.CompileOptions); - - token.ThrowIfCancellationRequested(); - - // Check whether double precision operations are required - bool requiresDoublePrecisionSupport = D3DCompiler.IsDoublePrecisionSupportRequired(d3DBlob.Get()); - - token.ThrowIfCancellationRequested(); - - byte* buffer = (byte*)d3DBlob.Get()->GetBufferPointer(); - int length = checked((int)d3DBlob.Get()->GetBufferSize()); - - byte[] array = new ReadOnlySpan(buffer, length).ToArray(); - - ImmutableArray bytecode = Unsafe.As>(ref array); - - return new HlslBytecodeInfo.Success(bytecode, requiresDoublePrecisionSupport); - } - catch (Win32Exception e) - { - return new HlslBytecodeInfo.Win32Error(e.NativeErrorCode, D3DCompiler.PrettifyFxcErrorMessage(e.Message)); - } - catch (FxcCompilationException e) - { - return new HlslBytecodeInfo.CompilerError(D3DCompiler.PrettifyFxcErrorMessage(e.Message)); - } - } - - // Get or create the HLSL bytecode compilation result for the input key. The dynamic cache - // will take care of retrieving an existing cached value if the same shader has been compiled - // already with the same parameters. After this call, callers must use the updated key value. - return HlslBytecodeCache.GetOrCreate(ref key, GetInfo, token); - } - - /// - /// Gets any diagnostics from a processed instance. - /// - /// The input instance to process. - /// The source instance. - /// The collection of produced instances. - public static void GetInfoDiagnostics( - INamedTypeSymbol structDeclarationSymbol, - HlslBytecodeInfo info, - ImmutableArrayBuilder diagnostics) - { - DiagnosticInfo? diagnostic = null; - - if (info is HlslBytecodeInfo.Win32Error win32Error) - { - diagnostic = DiagnosticInfo.Create( - HlslBytecodeFailedWithWin32Exception, - structDeclarationSymbol, - structDeclarationSymbol, - win32Error.HResult, - win32Error.Message); - } - else if (info is HlslBytecodeInfo.CompilerError fxcError) - { - diagnostic = DiagnosticInfo.Create( - HlslBytecodeFailedWithFxcCompilationException, - structDeclarationSymbol, - structDeclarationSymbol, - fxcError.Message); - } - - if (diagnostic is not null) - { - diagnostics.Add(diagnostic); - } - } - - /// - /// Gets the diagnostics for when double precision support is configured incorrectly. - /// - /// The input instance to process. - /// The source instance. - /// The collection of produced instances. - public static void GetDoublePrecisionSupportDiagnostics( - INamedTypeSymbol structDeclarationSymbol, - HlslBytecodeInfo info, - ImmutableArrayBuilder diagnostics) - { - // If we have no compiled HLSL bytecode, there is nothing more to do - if (info is not HlslBytecodeInfo.Success success) - { - return; - } - - bool hasD2DRequiresDoublePrecisionSupportAttribute = structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName( - "ComputeSharp.D2D1.D2DRequiresDoublePrecisionSupportAttribute", - out AttributeData? attributeData); - - // Check the two cases where diagnostics are necessary: - // - The shader does not have [D2DRequiresDoublePrecisionSupport], but it needs it - // - The shader has [D2DRequiresDoublePrecisionSupport], but it does not need it - if (!hasD2DRequiresDoublePrecisionSupportAttribute && success.RequiresDoublePrecisionSupport) - { - diagnostics.Add(DiagnosticInfo.Create( - MissingD2DRequiresDoublePrecisionSupportAttribute, - structDeclarationSymbol, - structDeclarationSymbol)); - } - else if (hasD2DRequiresDoublePrecisionSupportAttribute && !success.RequiresDoublePrecisionSupport) - { - diagnostics.Add(DiagnosticInfo.Create( - UnnecessaryD2DRequiresDoublePrecisionSupportAttribute, - attributeData!.GetLocation(), - structDeclarationSymbol)); - } - } } } \ No newline at end of file diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs index d46dc2c0..4266885c 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderDescriptorGenerator.cs @@ -163,13 +163,13 @@ public sealed partial class D2DPixelShaderDescriptorGenerator : IIncrementalGene isCompilationEnabled); // Get the existing compiled shader, or compile the processed HLSL code - HlslBytecodeInfo hlslInfo = HlslBytecode.GetInfo(ref hlslInfoKey, token); + HlslBytecodeInfo hlslInfo = HlslBytecodeSyntaxProcessor.GetInfo(ref hlslInfoKey, token); token.ThrowIfCancellationRequested(); // Append any diagnostic for the shader compilation - HlslBytecode.GetInfoDiagnostics(typeSymbol, hlslInfo, diagnostics); - HlslBytecode.GetDoublePrecisionSupportDiagnostics(typeSymbol, hlslInfo, diagnostics); + HlslBytecodeSyntaxProcessor.GetInfoDiagnostics(typeSymbol, hlslInfo, diagnostics); + HlslBytecodeSyntaxProcessor.GetDoublePrecisionSupportDiagnostics(typeSymbol, hlslInfo, diagnostics); token.ThrowIfCancellationRequested(); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs index f861bea0..ed19e18e 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/D2DPixelShaderSourceGenerator.cs @@ -4,10 +4,10 @@ using ComputeSharp.D2D1.SourceGenerators.Models; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; +using ComputeSharp.SourceGeneration.SyntaxProcessors; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using static ComputeSharp.D2D1.SourceGenerators.D2DPixelShaderDescriptorGenerator; namespace ComputeSharp.D2D1.SourceGenerators; @@ -55,7 +55,7 @@ public sealed partial class D2DPixelShaderSourceGenerator : IIncrementalGenerato isCompilationEnabled); // Get the existing compiled shader, or compile the processed HLSL code - HlslBytecodeInfo hlslInfo = HlslBytecode.GetInfo(ref hlslInfoKey, token); + HlslBytecodeInfo hlslInfo = HlslBytecodeSyntaxProcessor.GetInfo(ref hlslInfoKey, token); token.ThrowIfCancellationRequested(); diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index 23ce21bf..aa16d774 100644 --- a/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.D2D1.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -466,7 +466,7 @@ partial class DiagnosticDescriptors /// Format: "The shader of type {0} failed to compile due to an HLSL compiler error (Message: "{1}")". /// /// - public static readonly DiagnosticDescriptor HlslBytecodeFailedWithFxcCompilationException = new( + public static readonly DiagnosticDescriptor HlslBytecodeFailedWithCompilationException = new( id: "CMPSD2D0034", title: "HLSL bytecode compilation failed due to an HLSL compiler error", messageFormat: """The shader of type {0} failed to compile due to an HLSL compiler error (Message: "{1}")""", @@ -1197,7 +1197,7 @@ partial class DiagnosticDescriptors /// Format: "The shader {0} requires double precision support, but it does not have the [D2DRequiresDoublePrecisionSupport] attribute on it (adding the attribute is necessary to explicitly opt-in to that functionality)". /// /// - public static readonly DiagnosticDescriptor MissingD2DRequiresDoublePrecisionSupportAttribute = new( + public static readonly DiagnosticDescriptor MissingRequiresDoublePrecisionSupportAttribute = new( id: "CMPSD2D0080", title: "Missing [D2DRequiresDoublePrecisionSupport] attribute", messageFormat: "The shader {0} requires double precision support, but it does not have the [D2DRequiresDoublePrecisionSupport] attribute on it (adding the attribute is necessary to explicitly opt-in to that functionality)", @@ -1213,7 +1213,7 @@ partial class DiagnosticDescriptors /// Format: "The shader {0} does not require double precision support, but it has the [D2DRequiresDoublePrecisionSupport] attribute on it (using the attribute is not needed if the shader is not performing any double precision operations)". /// /// - public static readonly DiagnosticDescriptor UnnecessaryD2DRequiresDoublePrecisionSupportAttribute = new( + public static readonly DiagnosticDescriptor UnnecessaryRequiresDoublePrecisionSupportAttribute = new( id: "CMPSD2D0081", title: "Unnecessary [D2DRequiresDoublePrecisionSupport] attribute", messageFormat: "The shader {0} does not require double precision support, but it has the [D2DRequiresDoublePrecisionSupport] attribute on it (using the attribute is not needed if the shader is not performing any double precision operations)", diff --git a/src/ComputeSharp.D2D1.SourceGenerators/Polyfills/EncodingExtensions.cs b/src/ComputeSharp.D2D1.SourceGenerators/Polyfills/EncodingExtensions.cs new file mode 100644 index 00000000..8c985e6d --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/Polyfills/EncodingExtensions.cs @@ -0,0 +1,23 @@ +namespace System.Text; + +/// +/// Extensions for the type. +/// +internal static class EncodingExtensions +{ + /// + /// Encodes into a span of bytes a set of characters from the specified read-only span. + /// + /// The input instance to use. + /// The span containing the set of characters to encode. + /// The byte span to hold the encoded bytes. + /// The number of encoded bytes. + public static unsafe int GetBytes(this Encoding encoding, ReadOnlySpan chars, Span bytes) + { + fixed (char* charsPtr = chars) + fixed (byte* bytesPtr = bytes) + { + return encoding.GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length); + } + } +} diff --git a/src/ComputeSharp.D2D1.SourceGenerators/SyntaxProcessors/HlslBytecodeSyntaxProcessor.D2D1.cs b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxProcessors/HlslBytecodeSyntaxProcessor.D2D1.cs new file mode 100644 index 00000000..d87ed2a7 --- /dev/null +++ b/src/ComputeSharp.D2D1.SourceGenerators/SyntaxProcessors/HlslBytecodeSyntaxProcessor.D2D1.cs @@ -0,0 +1,40 @@ +using System; +using System.Threading; +using ComputeSharp.D2D1.Shaders.Translation; +using ComputeSharp.D2D1.SourceGenerators.Models; +using Windows.Win32; +using Windows.Win32.Graphics.Direct3D; + +namespace ComputeSharp.SourceGeneration.SyntaxProcessors; + +/// +partial class HlslBytecodeSyntaxProcessor +{ + /// + private static partial string GetRequiresDoublePrecisionSupportAttributeName() + { + return "ComputeSharp.D2D1.D2DRequiresDoublePrecisionSupportAttribute"; + } + + /// + private static partial ComPtr Compile(HlslBytecodeInfoKey key, CancellationToken token) + { + return D3DCompiler.Compile( + key.HlslSource.AsSpan(), + key.ShaderProfile, + key.CompileOptions, + token); + } + + /// + private static unsafe partial bool IsDoublePrecisionSupportRequired(ID3DBlob* d3DBlob) + { + return D3DCompiler.IsDoublePrecisionSupportRequired(d3DBlob); + } + + /// + private static partial string FixupErrorMessage(string message) + { + return D3DCompiler.PrettifyFxcErrorMessage(message); + } +} \ No newline at end of file diff --git a/src/ComputeSharp.D2D1/Shaders/Translation/D3DCompiler.cs b/src/ComputeSharp.D2D1/Shaders/Translation/D3DCompiler.cs index f1ab48c0..7550b9a4 100644 --- a/src/ComputeSharp.D2D1/Shaders/Translation/D3DCompiler.cs +++ b/src/ComputeSharp.D2D1/Shaders/Translation/D3DCompiler.cs @@ -5,6 +5,7 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; #if SOURCE_GENERATOR +using System.Threading; using Windows.Win32; using Windows.Win32.Foundation; using Windows.Win32.Graphics.Direct3D; @@ -34,21 +35,23 @@ internal static unsafe partial class D3DCompiler /// The shader profile to use to compile the shader. /// The options to use to compile the shader. /// The bytecode for the compiled shader. - public static ComPtr Compile(ReadOnlySpan source, D2D1ShaderProfile shaderProfile, D2D1CompileOptions options) + public static ComPtr Compile( + ReadOnlySpan source, + D2D1ShaderProfile shaderProfile, +#if SOURCE_GENERATOR +#pragma warning disable CS1573 + D2D1CompileOptions options, + CancellationToken token) // The cancellation token used to cancel the operation. +#pragma warning restore CS1573 +#else + D2D1CompileOptions options) +#endif { + // Transcode the input HLSL source from Unicode to ASCII encoding int maxLength = Encoding.ASCII.GetMaxByteCount(source.Length); byte[] buffer = ArrayPool.Shared.Rent(maxLength); - int writtenBytes; - -#if SOURCE_GENERATOR - fixed (char* pSource = source) - fixed (byte* pBuffer = buffer) - { - writtenBytes = Encoding.ASCII.GetBytes(pSource, source.Length, pBuffer, buffer.Length); - } -#else - writtenBytes = Encoding.ASCII.GetBytes(source, buffer); -#endif + int writtenBytes = Encoding.ASCII.GetBytes(source, buffer); + ReadOnlySpan sourceAscii = new(buffer, 0, writtenBytes); bool enableLinking = (options & D2D1CompileOptions.EnableLinking) == D2D1CompileOptions.EnableLinking; bool stripReflectionData = (options & D2D1CompileOptions.StripReflectionData) == D2D1CompileOptions.StripReflectionData; @@ -58,9 +61,13 @@ internal static unsafe partial class D3DCompiler try { +#if SOURCE_GENERATOR + token.ThrowIfCancellationRequested(); +#endif + // Compile the standalone D2D1 full shader using ComPtr d3DBlobFullShader = Compile( - source: buffer.AsSpan(0, writtenBytes), + source: sourceAscii, macro: ASCII.D2D_FULL_SHADER, d2DEntry: ASCII.Execute, entryPoint: ASCII.Execute, @@ -73,9 +80,13 @@ internal static unsafe partial class D3DCompiler return d3DBlobFullShader.Move(); } +#if SOURCE_GENERATOR + token.ThrowIfCancellationRequested(); +#endif + // Compile the export function using ComPtr d3DBlobFunction = Compile( - source: buffer.AsSpan(0, writtenBytes), + source: sourceAscii, macro: ASCII.D2D_FUNCTION, d2DEntry: ASCII.Execute, entryPoint: default, diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems index b858e0fa..ac737e05 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems +++ b/src/ComputeSharp.SourceGeneration.Hlsl/ComputeSharp.SourceGeneration.Hlsl.projitems @@ -29,6 +29,7 @@ + diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslBytecodeSyntaxProcessor.cs b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslBytecodeSyntaxProcessor.cs new file mode 100644 index 00000000..f530496e --- /dev/null +++ b/src/ComputeSharp.SourceGeneration.Hlsl/SyntaxProcessors/HlslBytecodeSyntaxProcessor.cs @@ -0,0 +1,196 @@ +using System; +using System.Collections.Immutable; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; +using ComputeSharp.SourceGeneration.Extensions; +using ComputeSharp.SourceGeneration.Helpers; +using ComputeSharp.SourceGeneration.Models; +using Microsoft.CodeAnalysis; +using Windows.Win32; +using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; +#if D2D1_SOURCE_GENERATOR +using HlslBytecodeInfoKey = ComputeSharp.D2D1.SourceGenerators.Models.HlslBytecodeInfoKey; +using HlslCompilationException = ComputeSharp.D2D1.FxcCompilationException; +using ID3DBlob = Windows.Win32.Graphics.Direct3D.ID3DBlob; +#else +using HlslBytecodeInfoKey = ComputeSharp.SourceGenerators.Models.HlslBytecodeInfoKey; +using HlslCompilationException = ComputeSharp.SourceGenerators.Dxc.DxcCompilationException; +using ID3DBlob = Windows.Win32.Graphics.Direct3D.Dxc.IDxcBlob; +#endif + +namespace ComputeSharp.SourceGeneration.SyntaxProcessors; + +/// +/// A processor responsible for extracting info about compiled HLSL bytecode. +/// +internal static partial class HlslBytecodeSyntaxProcessor +{ + /// + /// The shared cache of values. + /// + private static readonly DynamicCache HlslBytecodeCache = new(); + + /// + /// Gets the instance for the input shader info. + /// + /// 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) + { + // Check if the compilation is not enabled (eg. if there's been errors earlier in the pipeline). + // In this case, skip the compilation, as diagnostic will be emitted for those anyway. + // Compiling would just add overhead and result in more errors, as the HLSL would be invalid. + if (!key.IsCompilationEnabled) + { + return HlslBytecodeInfo.Missing.Instance; + } + + try + { + token.ThrowIfCancellationRequested(); + + // Compile the shader bytecode using the effective parameters + using ComPtr d3DBlob = Compile(key, token); + + token.ThrowIfCancellationRequested(); + + // Check whether double precision operations are required + bool requiresDoublePrecisionSupport = IsDoublePrecisionSupportRequired(d3DBlob.Get()); + + token.ThrowIfCancellationRequested(); + + byte* buffer = (byte*)d3DBlob.Get()->GetBufferPointer(); + int length = checked((int)d3DBlob.Get()->GetBufferSize()); + + byte[] array = new ReadOnlySpan(buffer, length).ToArray(); + + ImmutableArray bytecode = Unsafe.As>(ref array); + + return new HlslBytecodeInfo.Success(bytecode, requiresDoublePrecisionSupport); + } + catch (Win32Exception e) + { + return new HlslBytecodeInfo.Win32Error(e.NativeErrorCode, FixupErrorMessage(e.Message)); + } + catch (HlslCompilationException e) + { + return new HlslBytecodeInfo.CompilerError(FixupErrorMessage(e.Message)); + } + } + + // Get or create the HLSL bytecode compilation result for the input key. The dynamic cache + // will take care of retrieving an existing cached value if the same shader has been compiled + // already with the same parameters. After this call, callers must use the updated key value. + return HlslBytecodeCache.GetOrCreate(ref key, GetInfo, token); + } + + /// + /// Gets any diagnostics from a processed instance. + /// + /// The input instance to process. + /// The source instance. + /// The collection of produced instances. + public static void GetInfoDiagnostics( + INamedTypeSymbol structDeclarationSymbol, + HlslBytecodeInfo info, + ImmutableArrayBuilder diagnostics) + { + DiagnosticInfo? diagnostic = null; + + if (info is HlslBytecodeInfo.Win32Error win32Error) + { + diagnostic = DiagnosticInfo.Create( + HlslBytecodeFailedWithWin32Exception, + structDeclarationSymbol, + structDeclarationSymbol, + win32Error.HResult, + win32Error.Message); + } + else if (info is HlslBytecodeInfo.CompilerError fxcError) + { + diagnostic = DiagnosticInfo.Create( + HlslBytecodeFailedWithCompilationException, + structDeclarationSymbol, + structDeclarationSymbol, + fxcError.Message); + } + + if (diagnostic is not null) + { + diagnostics.Add(diagnostic); + } + } + + /// + /// Gets the diagnostics for when double precision support is configured incorrectly. + /// + /// The input instance to process. + /// The source instance. + /// The collection of produced instances. + public static void GetDoublePrecisionSupportDiagnostics( + INamedTypeSymbol structDeclarationSymbol, + HlslBytecodeInfo info, + ImmutableArrayBuilder diagnostics) + { + // If we have no compiled HLSL bytecode, there is nothing more to do + if (info is not HlslBytecodeInfo.Success success) + { + return; + } + + bool hasRequiresDoublePrecisionSupportAttribute = structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName( + GetRequiresDoublePrecisionSupportAttributeName(), + out AttributeData? attributeData); + + // Check the two cases where diagnostics are necessary: + // - The shader does not have [[D2D]RequiresDoublePrecisionSupport], but it needs it + // - The shader has [[D2D]RequiresDoublePrecisionSupport], but it does not need it + if (!hasRequiresDoublePrecisionSupportAttribute && success.RequiresDoublePrecisionSupport) + { + diagnostics.Add(DiagnosticInfo.Create( + MissingRequiresDoublePrecisionSupportAttribute, + structDeclarationSymbol, + structDeclarationSymbol)); + } + else if (hasRequiresDoublePrecisionSupportAttribute && !success.RequiresDoublePrecisionSupport) + { + diagnostics.Add(DiagnosticInfo.Create( + UnnecessaryRequiresDoublePrecisionSupportAttribute, + attributeData!.GetLocation(), + structDeclarationSymbol)); + } + } + + /// + /// Gets the type name for the attribute to indicate that double precision support is required. + /// + /// The type name for the attribute to indicate that double precision support is required. + private static partial string GetRequiresDoublePrecisionSupportAttributeName(); + + /// + /// Compiles the input HLSL source into bytecode. + /// + /// The instance for the shader to compile. + /// The used to cancel the operation, if needed. + /// The resulting HLSL bytecode. + private static partial ComPtr Compile(HlslBytecodeInfoKey key, CancellationToken token); + + /// + /// Checks whether double precision support is required. + /// + /// The input HLSL bytecode to inspect. + /// Whether double precision support is required for . + private static unsafe partial bool IsDoublePrecisionSupportRequired(ID3DBlob* d3DBlob); + + /// + /// Fixes up an exception message to improve the way it's displayed in VS. + /// + /// The input exception message. + /// The updated exception message. + /// + private static partial string FixupErrorMessage(string message); +} \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs index 298bffbd..9e10d0b5 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.HlslBytecode.cs @@ -1,17 +1,7 @@ -using System; -using System.Collections.Immutable; -using System.ComponentModel; -using System.Runtime.CompilerServices; -using System.Threading; using ComputeSharp.SourceGeneration.Extensions; using ComputeSharp.SourceGeneration.Helpers; using ComputeSharp.SourceGeneration.Models; -using ComputeSharp.SourceGenerators.Dxc; -using ComputeSharp.SourceGenerators.Models; using Microsoft.CodeAnalysis; -using Windows.Win32; -using Windows.Win32.Graphics.Direct3D.Dxc; -using static ComputeSharp.SourceGeneration.Diagnostics.DiagnosticDescriptors; namespace ComputeSharp.SourceGenerators; @@ -23,71 +13,6 @@ partial class ComputeShaderDescriptorGenerator /// private static partial class HlslBytecode { - /// - /// The shared cache of values. - /// - private static readonly DynamicCache HlslBytecodeCache = new(); - - /// - /// Gets the instance for the input shader info. - /// - /// 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 - { - token.ThrowIfCancellationRequested(); - - // Try to load dxcompiler.dll and dxil.dll - DxcLibraryLoader.LoadNativeDxcLibraries(); - - token.ThrowIfCancellationRequested(); - - // Compile the shader bytecode - using ComPtr dxcBlob = DxcShaderCompiler.Instance.Compile( - key.HlslSource.AsSpan(), - key.CompileOptions, - token); - - token.ThrowIfCancellationRequested(); - - // Check whether double precision operations are required - bool requiresDoublePrecisionSupport = DxcShaderCompiler.Instance.IsDoublePrecisionSupportRequired(dxcBlob.Get()); - - token.ThrowIfCancellationRequested(); - - byte* buffer = (byte*)dxcBlob.Get()->GetBufferPointer(); - int length = checked((int)dxcBlob.Get()->GetBufferSize()); - - byte[] array = new ReadOnlySpan(buffer, length).ToArray(); - - ImmutableArray bytecode = Unsafe.As>(ref array); - - return new HlslBytecodeInfo.Success(bytecode, requiresDoublePrecisionSupport); - } - catch (Win32Exception e) - { - return new HlslBytecodeInfo.Win32Error(e.NativeErrorCode, DxcShaderCompiler.FixupExceptionMessage(e.Message)); - } - catch (DxcCompilationException e) - { - return new HlslBytecodeInfo.CompilerError(DxcShaderCompiler.FixupExceptionMessage(e.Message)); - } - } - - return HlslBytecodeCache.GetOrCreate(ref key, GetInfo, token); - } - /// /// Extracts the compile options for the current shader. /// @@ -105,80 +30,5 @@ partial class ComputeShaderDescriptorGenerator return CompileOptions.Default; } - - /// - /// Gets any diagnostics from a processed instance. - /// - /// The input instance to process. - /// The source instance. - /// The collection of produced instances. - public static void GetInfoDiagnostics( - INamedTypeSymbol structDeclarationSymbol, - HlslBytecodeInfo info, - ImmutableArrayBuilder diagnostics) - { - DiagnosticInfo? diagnostic = null; - - if (info is HlslBytecodeInfo.Win32Error win32Error) - { - diagnostic = DiagnosticInfo.Create( - HlslBytecodeFailedWithWin32Exception, - structDeclarationSymbol, - structDeclarationSymbol, - win32Error.HResult, - win32Error.Message); - } - else if (info is HlslBytecodeInfo.CompilerError dxcError) - { - diagnostic = DiagnosticInfo.Create( - HlslBytecodeFailedWithDxcCompilationException, - structDeclarationSymbol, - structDeclarationSymbol, - dxcError.Message); - } - - if (diagnostic is not null) - { - diagnostics.Add(diagnostic); - } - } - - /// - /// Gets the diagnostics for when double precision support is configured incorrectly. - /// - /// The input instance to process. - /// The source instance. - /// The collection of produced instances. - public static void GetDoublePrecisionSupportDiagnostics( - INamedTypeSymbol structDeclarationSymbol, - HlslBytecodeInfo info, - ImmutableArrayBuilder diagnostics) - { - // If we have no compiled HLSL bytecode, there is nothing more to do - if (info is not HlslBytecodeInfo.Success success) - { - return; - } - - bool hasD2DRequiresDoublePrecisionSupportAttribute = structDeclarationSymbol.TryGetAttributeWithFullyQualifiedMetadataName( - "ComputeSharp.RequiresDoublePrecisionSupportAttribute", - out AttributeData? attributeData); - - // Check the two cases where diagnostics are necessary (same as the D2D generator) - if (!hasD2DRequiresDoublePrecisionSupportAttribute && success.RequiresDoublePrecisionSupport) - { - diagnostics.Add(DiagnosticInfo.Create( - MissingRequiresDoublePrecisionSupportAttribute, - structDeclarationSymbol, - structDeclarationSymbol)); - } - else if (hasD2DRequiresDoublePrecisionSupportAttribute && !success.RequiresDoublePrecisionSupport) - { - diagnostics.Add(DiagnosticInfo.Create( - UnnecessaryRequiresDoublePrecisionSupportAttribute, - attributeData!.GetLocation(), - structDeclarationSymbol)); - } - } } } \ No newline at end of file diff --git a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs index c218dd6e..4d3e6cbd 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs +++ b/src/ComputeSharp.SourceGenerators/ComputeShaderDescriptorGenerator.cs @@ -117,12 +117,12 @@ public sealed partial class ComputeShaderDescriptorGenerator : IIncrementalGener HlslBytecodeInfoKey hlslInfoKey = new(hlslSource, compileOptions, isCompilationEnabled); // Try to get the HLSL bytecode - HlslBytecodeInfo hlslInfo = HlslBytecode.GetBytecode(ref hlslInfoKey, token); + HlslBytecodeInfo hlslInfo = HlslBytecodeSyntaxProcessor.GetInfo(ref hlslInfoKey, token); token.ThrowIfCancellationRequested(); - HlslBytecode.GetInfoDiagnostics(typeSymbol, hlslInfo, diagnostics); - HlslBytecode.GetDoublePrecisionSupportDiagnostics(typeSymbol, hlslInfo, diagnostics); + HlslBytecodeSyntaxProcessor.GetInfoDiagnostics(typeSymbol, hlslInfo, diagnostics); + HlslBytecodeSyntaxProcessor.GetDoublePrecisionSupportDiagnostics(typeSymbol, hlslInfo, diagnostics); token.ThrowIfCancellationRequested(); diff --git a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj index 330353f5..7569624c 100644 --- a/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj +++ b/src/ComputeSharp.SourceGenerators/ComputeSharp.SourceGenerators.csproj @@ -1,6 +1,7 @@ netstandard2.0 + $(DefineConstants);D3D12_SOURCE_GENERATOR diff --git a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs index ce9a2f6b..4cd5a7da 100644 --- a/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs +++ b/src/ComputeSharp.SourceGenerators/Diagnostics/DiagnosticDescriptors.cs @@ -627,7 +627,7 @@ partial class DiagnosticDescriptors /// Format: "The shader of type {0} failed to compile due to an HLSL compiler error (Message: "{1}")". /// /// - public static readonly DiagnosticDescriptor HlslBytecodeFailedWithDxcCompilationException = new( + public static readonly DiagnosticDescriptor HlslBytecodeFailedWithCompilationException = new( id: "CMPS0046", title: "HLSL bytecode compilation failed due to an HLSL compiler error", messageFormat: """The shader of type {0} failed to compile due to an HLSL compiler error (Message: "{1}")""", diff --git a/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs b/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs index f3cdf3f1..875d1a7d 100644 --- a/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs +++ b/src/ComputeSharp.SourceGenerators/Dxc/DxcShaderCompiler.cs @@ -42,13 +42,13 @@ internal sealed unsafe class DxcShaderCompiler using ComPtr dxcCompiler = default; using ComPtr dxcUtils = default; - PInvoke.DxcCreateInstance( - PInvoke.CLSID_DxcCompiler, + DirectX.DxcCreateInstance( + DirectX.CLSID_DxcCompiler, IDxcCompiler3.IID_Guid, out *(void**)dxcCompiler.GetAddressOf()).Assert(); - PInvoke.DxcCreateInstance( - PInvoke.CLSID_DxcLibrary, + DirectX.DxcCreateInstance( + DirectX.CLSID_DxcLibrary, IDxcUtils.IID_Guid, out *(void**)dxcUtils.GetAddressOf()).Assert(); @@ -250,11 +250,7 @@ internal sealed unsafe class DxcShaderCompiler return dxcBlobBytecode.Move(); } - /// - /// Checks whether double precision support is required. - /// - /// The input HLSL bytecode to inspect. - /// Whether double precision support is required for . + /// public bool IsDoublePrecisionSupportRequired(IDxcBlob* dxcBlob) { using ComPtr d3D12ShaderReflection = default; @@ -275,11 +271,7 @@ internal sealed unsafe class DxcShaderCompiler return (d3D12ShaderReflection.Get()->GetRequiresFlags() & doublePrecisionFlags) != 0; } - /// - /// Fixes up an exception message to improve the way it's displayed in VS. - /// - /// The input exception message. - /// The updated exception message. + /// public static string FixupExceptionMessage(string message) { // Add square brackets around error headers diff --git a/src/ComputeSharp.SourceGenerators/SyntaxProcessors/HlslBytecodeSyntaxProcessor.D3D12.cs b/src/ComputeSharp.SourceGenerators/SyntaxProcessors/HlslBytecodeSyntaxProcessor.D3D12.cs new file mode 100644 index 00000000..1246494c --- /dev/null +++ b/src/ComputeSharp.SourceGenerators/SyntaxProcessors/HlslBytecodeSyntaxProcessor.D3D12.cs @@ -0,0 +1,45 @@ +using System; +using System.Threading; +using ComputeSharp.SourceGenerators.Dxc; +using ComputeSharp.SourceGenerators.Models; +using Windows.Win32; +using Windows.Win32.Graphics.Direct3D.Dxc; + +namespace ComputeSharp.SourceGeneration.SyntaxProcessors; + +/// +partial class HlslBytecodeSyntaxProcessor +{ + /// + private static partial string GetRequiresDoublePrecisionSupportAttributeName() + { + return "ComputeSharp.RequiresDoublePrecisionSupportAttribute"; + } + + /// + private static partial ComPtr Compile(HlslBytecodeInfoKey key, CancellationToken token) + { + // Try to load dxcompiler.dll and dxil.dll + DxcLibraryLoader.LoadNativeDxcLibraries(); + + token.ThrowIfCancellationRequested(); + + // Compile the shader bytecode using DXC + return DxcShaderCompiler.Instance.Compile( + key.HlslSource.AsSpan(), + key.CompileOptions, + token); + } + + /// + private static unsafe partial bool IsDoublePrecisionSupportRequired(IDxcBlob* d3DBlob) + { + return DxcShaderCompiler.Instance.IsDoublePrecisionSupportRequired(d3DBlob); + } + + /// + private static partial string FixupErrorMessage(string message) + { + return DxcShaderCompiler.FixupExceptionMessage(message); + } +} \ No newline at end of file