Add HlslBytecodeSyntaxProcessor shared helper type

このコミットが含まれているのは:
Sergio Pedri committed 2023-12-17 13:31:17 +01:00
1 親 ef821be2b2
コミット 2a519c3f51
11ファイル変更
+284 -22

検索条件に一致するファイルはありません

+1
ファイルの表示
@@ -1,6 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<DefineConstants>$(DefineConstants);D2D1_SOURCE_GENERATOR</DefineConstants>
</PropertyGroup>
<PropertyGroup>
@@ -265,7 +265,7 @@ partial class D2DPixelShaderDescriptorGenerator
else if (info is HlslBytecodeInfo.CompilerError fxcError)
{
diagnostic = DiagnosticInfo.Create(
HlslBytecodeFailedWithFxcCompilationException,
HlslBytecodeFailedWithCompilationException,
structDeclarationSymbol,
structDeclarationSymbol,
fxcError.Message);
@@ -304,14 +304,14 @@ partial class D2DPixelShaderDescriptorGenerator
if (!hasD2DRequiresDoublePrecisionSupportAttribute && success.RequiresDoublePrecisionSupport)
{
diagnostics.Add(DiagnosticInfo.Create(
MissingD2DRequiresDoublePrecisionSupportAttribute,
MissingRequiresDoublePrecisionSupportAttribute,
structDeclarationSymbol,
structDeclarationSymbol));
}
else if (hasD2DRequiresDoublePrecisionSupportAttribute && !success.RequiresDoublePrecisionSupport)
{
diagnostics.Add(DiagnosticInfo.Create(
UnnecessaryD2DRequiresDoublePrecisionSupportAttribute,
UnnecessaryRequiresDoublePrecisionSupportAttribute,
attributeData!.GetLocation(),
structDeclarationSymbol));
}
+3 -3
ファイルの表示
@@ -466,7 +466,7 @@ partial class DiagnosticDescriptors
/// Format: <c>"The shader of type {0} failed to compile due to an HLSL compiler error (Message: "{1}")"</c>.
/// </para>
/// </summary>
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: <c>"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)"</c>.
/// </para>
/// </summary>
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: <c>"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)"</c>.
/// </para>
/// </summary>
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)",
@@ -0,0 +1,39 @@
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;
/// <inheritdoc/>
partial class HlslBytecodeSyntaxProcessor
{
/// <summary>
/// The name of the attribute to enable double precision support.
/// </summary>
private const string RequiresDoublePrecisionSupportAttributeName = "ComputeSharp.D2D1.D2DRequiresDoublePrecisionSupportAttribute";
/// <inheritdoc/>
private static partial ComPtr<ID3DBlob> Compile(HlslBytecodeInfoKey key, CancellationToken token)
{
return D3DCompiler.Compile(
key.HlslSource.AsSpan(),
key.ShaderProfile,
key.CompileOptions,
token);
}
/// <inheritdoc/>
private static unsafe partial bool IsDoublePrecisionSupportRequired(ID3DBlob* d3DBlob)
{
return D3DCompiler.IsDoublePrecisionSupportRequired(d3DBlob);
}
/// <inheritdoc/>
private static partial string FixupErrorMessage(string message)
{
return D3DCompiler.PrettifyFxcErrorMessage(message);
}
}
@@ -29,6 +29,7 @@
<Compile Include="$(MSBuildThisFileDirectory)Models\HlslBytecodeInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Models\Interfaces\IConstantBufferInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Models\TypeAliases.cs" />
<Compile Include="$(MSBuildThisFileDirectory)SyntaxProcessors\HlslBytecodeSyntaxProcessor.cs" />
<Compile Include="$(MSBuildThisFileDirectory)SyntaxProcessors\ConstantBufferSyntaxProcessor.Generation.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Helpers\HlslSourceHelper.cs" />
<Compile Include="$(MSBuildThisFileDirectory)SyntaxProcessors\HlslDefinitionsSyntaxProcessor.cs" />
@@ -0,0 +1,190 @@
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;
/// <summary>
/// A processor responsible for extracting info about compiled HLSL bytecode.
/// </summary>
internal static partial class HlslBytecodeSyntaxProcessor
{
/// <summary>
/// The shared cache of <see cref="HlslBytecodeInfo"/> values.
/// </summary>
private static readonly DynamicCache<HlslBytecodeInfoKey, HlslBytecodeInfo> HlslBytecodeCache = new();
/// <summary>
/// Gets the <see cref="HlslBytecodeInfo"/> instance for the input shader info.
/// </summary>
/// <param name="key">The <see cref="HlslBytecodeInfoKey"/> instance for the shader to compile.</param>
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
/// <returns>The <see cref="HlslBytecodeInfo"/> instance for the current shader.</returns>
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<ID3DBlob> 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<byte>(buffer, length).ToArray();
ImmutableArray<byte> bytecode = Unsafe.As<byte[], ImmutableArray<byte>>(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);
}
/// <summary>
/// Gets any diagnostics from a processed <see cref="HlslBytecodeInfo"/> instance.
/// </summary>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="info">The source <see cref="HlslBytecodeInfo"/> instance.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
public static void GetInfoDiagnostics(
INamedTypeSymbol structDeclarationSymbol,
HlslBytecodeInfo info,
ImmutableArrayBuilder<DiagnosticInfo> 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);
}
}
/// <summary>
/// Gets the diagnostics for when double precision support is configured incorrectly.
/// </summary>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="info">The source <see cref="HlslBytecodeInfo"/> instance.</param>
/// <param name="diagnostics">The collection of produced <see cref="DiagnosticInfo"/> instances.</param>
public static void GetDoublePrecisionSupportDiagnostics(
INamedTypeSymbol structDeclarationSymbol,
HlslBytecodeInfo info,
ImmutableArrayBuilder<DiagnosticInfo> 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(
RequiresDoublePrecisionSupportAttributeName,
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 (!hasD2DRequiresDoublePrecisionSupportAttribute && success.RequiresDoublePrecisionSupport)
{
diagnostics.Add(DiagnosticInfo.Create(
MissingRequiresDoublePrecisionSupportAttribute,
structDeclarationSymbol,
structDeclarationSymbol));
}
else if (hasD2DRequiresDoublePrecisionSupportAttribute && !success.RequiresDoublePrecisionSupport)
{
diagnostics.Add(DiagnosticInfo.Create(
UnnecessaryRequiresDoublePrecisionSupportAttribute,
attributeData!.GetLocation(),
structDeclarationSymbol));
}
}
/// <summary>
/// Compiles the input HLSL source into bytecode.
/// </summary>
/// <param name="key">The <see cref="HlslBytecodeInfoKey"/> instance for the shader to compile.</param>
/// <param name="token">The <see cref="CancellationToken"/> used to cancel the operation, if needed.</param>
/// <returns>The resulting HLSL bytecode.</returns>
private static partial ComPtr<ID3DBlob> Compile(HlslBytecodeInfoKey key, CancellationToken token);
/// <summary>
/// Checks whether double precision support is required.
/// </summary>
/// <param name="d3DBlob">The input HLSL bytecode to inspect.</param>
/// <returns>Whether double precision support is required for <paramref name="d3DBlob"/>.</returns>
private static unsafe partial bool IsDoublePrecisionSupportRequired(ID3DBlob* d3DBlob);
/// <summary>
/// Fixes up an exception message to improve the way it's displayed in VS.
/// </summary>
/// <param name="message">The input exception message.</param>
/// <returns>The updated exception message.</returns>
/// <returns></returns>
private static partial string FixupErrorMessage(string message);
}
+1 -1
ファイルの表示
@@ -131,7 +131,7 @@ partial class ComputeShaderDescriptorGenerator
else if (info is HlslBytecodeInfo.CompilerError dxcError)
{
diagnostic = DiagnosticInfo.Create(
HlslBytecodeFailedWithDxcCompilationException,
HlslBytecodeFailedWithCompilationException,
structDeclarationSymbol,
structDeclarationSymbol,
dxcError.Message);
+1
ファイルの表示
@@ -1,6 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<DefineConstants>$(DefineConstants);D3D12_SOURCE_GENERATOR</DefineConstants>
</PropertyGroup>
<PropertyGroup>
+1 -1
ファイルの表示
@@ -627,7 +627,7 @@ partial class DiagnosticDescriptors
/// Format: <c>"The shader of type {0} failed to compile due to an HLSL compiler error (Message: "{1}")"</c>.
/// </para>
/// </summary>
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}")""",
+6 -14
ファイルの表示
@@ -42,13 +42,13 @@ internal sealed unsafe class DxcShaderCompiler
using ComPtr<IDxcCompiler3> dxcCompiler = default;
using ComPtr<IDxcUtils> 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();
}
/// <summary>
/// Checks whether double precision support is required.
/// </summary>
/// <param name="dxcBlob">The input HLSL bytecode to inspect.</param>
/// <returns>Whether double precision support is required for <paramref name="dxcBlob"/>.</returns>
/// <inheritdoc cref="SourceGeneration.SyntaxProcessors.HlslBytecodeSyntaxProcessor.IsDoublePrecisionSupportRequired"/>
public bool IsDoublePrecisionSupportRequired(IDxcBlob* dxcBlob)
{
using ComPtr<ID3D12ShaderReflection> d3D12ShaderReflection = default;
@@ -275,11 +271,7 @@ internal sealed unsafe class DxcShaderCompiler
return (d3D12ShaderReflection.Get()->GetRequiresFlags() & doublePrecisionFlags) != 0;
}
/// <summary>
/// Fixes up an exception message to improve the way it's displayed in VS.
/// </summary>
/// <param name="message">The input exception message.</param>
/// <returns>The updated exception message.</returns>
/// <inheritdoc cref="SourceGeneration.SyntaxProcessors.HlslBytecodeSyntaxProcessor.FixupErrorMessage"/>
public static string FixupExceptionMessage(string message)
{
// Add square brackets around error headers
@@ -0,0 +1,38 @@
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;
/// <inheritdoc/>
partial class HlslBytecodeSyntaxProcessor
{
/// <summary>
/// The name of the attribute to enable double precision support.
/// </summary>
private const string RequiresDoublePrecisionSupportAttributeName = "ComputeSharp.RequiresDoublePrecisionSupportAttribute";
/// <inheritdoc/>
private static partial ComPtr<IDxcBlob> Compile(HlslBytecodeInfoKey key, CancellationToken token)
{
return DxcShaderCompiler.Instance.Compile(
key.HlslSource.AsSpan(),
key.CompileOptions,
token);
}
/// <inheritdoc/>
private static unsafe partial bool IsDoublePrecisionSupportRequired(IDxcBlob* d3DBlob)
{
return DxcShaderCompiler.Instance.IsDoublePrecisionSupportRequired(d3DBlob);
}
/// <inheritdoc/>
private static partial string FixupErrorMessage(string message)
{
return DxcShaderCompiler.FixupExceptionMessage(message);
}
}