Implement initial version of TryGetBytecode generator

このコミットが含まれているのは:
Sergio Pedri committed 2021-12-06 17:43:44 +01:00
1 親 7c46fad051
コミット 0f6ae572cd
6ファイル変更
+290 -33

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

+4
ファイルの表示
@@ -16,6 +16,7 @@
and to match members based on full name, so the types being in the generator assembly are not an issue.-->
<ItemGroup>
<Compile Include="..\ComputeSharp\Core\Attributes\AutoConstructorAttribute.cs" Link="ComputeSharp\Core\Attributes\AutoConstructorAttribute.cs" />
<Compile Include="..\ComputeSharp\Core\Attributes\EmbeddedBytecodeAttribute.cs" Link="ComputeSharp\Core\Attributes\EmbeddedBytecodeAttribute.cs" />
<Compile Include="..\ComputeSharp\Core\Attributes\GroupSharedAttribute.cs" Link="ComputeSharp\Core\Attributes\GroupSharedAttribute.cs" />
<Compile Include="..\ComputeSharp\Core\Attributes\ShaderMethodAttribute.cs" Link="ComputeSharp\Core\Attributes\ShaderMethodAttribute.cs" />
<Compile Include="..\ComputeSharp\Core\Attributes\__Internals\ShaderMethodSourceAttribute.cs" Link="ComputeSharp\Core\Attributes\__Internals\ShaderMethodSourceAttribute.cs" />
@@ -70,6 +71,9 @@
<Compile Include="..\ComputeSharp\Core\Primitives\UInt\UInt4.g.cs" Link="ComputeSharp\Core\Primitives\UInt\UInt4.g.cs" />
<Compile Include="..\ComputeSharp\Core\Primitives\UInt\UIntMxN.g.cs" Link="ComputeSharp\Core\Primitives\UInt\UIntMxN.g.cs" />
<Compile Include="..\ComputeSharp\Core\Primitives\MatrixIndex.cs" Link="ComputeSharp\Core\Primitives\MatrixIndex.cs" />
<Compile Include="..\ComputeSharp\Graphics\Extensions\Interop\ComPtrExtensions.cs" Link="ComputeSharp\Graphics\Extensions\Interop\ComPtrExtensions.cs" />
<Compile Include="..\ComputeSharp\Shaders\Exceptions\HlslCompilationException.cs" Link="ComputeSharp\Shaders\Exceptions\HlslCompilationException.cs" />
<Compile Include="..\ComputeSharp\Shaders\Translation\ShaderCompiler.cs" Link="ComputeSharp\Shaders\Translation\ShaderCompiler.cs" />
</ItemGroup>
<ItemGroup>
@@ -0,0 +1,35 @@
using System.ComponentModel;
using System.Diagnostics;
using TerraFX.Interop.Windows;
namespace ComputeSharp.Core.Extensions;
/// <summary>
/// Helper methods to efficiently throw exceptions.
/// </summary>
[DebuggerStepThrough]
internal static class HResultExtensions
{
/// <summary>
/// Throws a <see cref="Win32Exception"/> if <paramref name="result"/> represents an error.
/// </summary>
/// <param name="result">The input <see cref="HRESULT"/> to check.</param>
/// <exception cref="Win32Exception">Thrown if <paramref name="result"/> represents an error.</exception>
public static void Assert(this HRESULT result)
{
Assert((int)result);
}
/// <summary>
/// Throws a <see cref="Win32Exception"/> if <paramref name="result"/> represents an error.
/// </summary>
/// <param name="result">The input <see cref="int"/> to check.</param>
/// <exception cref="Win32Exception">Thrown if <paramref name="result"/> represents an error.</exception>
public static void Assert(this int result)
{
if (result < 0)
{
throw new Win32Exception(result);
}
}
}
+33 -14
ファイルの表示
@@ -29,7 +29,8 @@ public sealed partial class IShaderGenerator
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
out string? implicitTextureType,
out bool isSamplerUsed)
out bool isSamplerUsed,
out string hlslSource)
{
// Properties are not supported
DetectAndReportPropertyDeclarations(context, structDeclarationSymbol);
@@ -70,7 +71,8 @@ public sealed partial class IShaderGenerator
accessesStaticSampler,
sharedBuffers,
processedMethods,
entryPoint);
entryPoint,
out hlslSource);
implicitTextureType = pixelShaderTextureType;
isSamplerUsed = accessesStaticSampler;
@@ -472,6 +474,7 @@ public sealed partial class IShaderGenerator
/// <param name="sharedBuffers">The sequence of shared buffers declared by the shader.</param>
/// <param name="processedMethods">The sequence of processed methods used by the shader.</param>
/// <param name="executeMethod">The body of the entry point of the shader.</param>
/// <param name="hlslSource">The generated HLSL source code (ignoring captured delegates, if present).</param>
/// <returns>The series of statements to build the HLSL source to compile to execute the current shader.</returns>
private static IEnumerable<StatementSyntax> GenerateRenderMethodBody(
IEnumerable<(string Name, string Value)> definedConstants,
@@ -483,34 +486,41 @@ public sealed partial class IShaderGenerator
bool isSamplerUsed,
IEnumerable<(string Name, string Type, int? Count)> sharedBuffers,
IEnumerable<(string Signature, string Definition)> processedMethods,
string executeMethod)
string executeMethod,
out string hlslSource)
{
List<StatementSyntax> statements = new();
StringBuilder textBuilder = new();
StringBuilder chunkedTextBuilder = new();
StringBuilder aggregateTextBuilder = new();
int capturedDelegates = 0;
int prologueStatements = 0;
int sizeHint = 64;
void AppendLF()
{
textBuilder.Append('\n');
chunkedTextBuilder.Append('\n');
}
void AppendLine(string text)
{
textBuilder.Append(text);
chunkedTextBuilder.Append(text);
}
void AppendLineAndLF(string text)
{
textBuilder.Append(text);
textBuilder.Append('\n');
chunkedTextBuilder.Append(text);
chunkedTextBuilder.Append('\n');
}
void AppendCharacterAndLF(char c)
{
textBuilder.Append(c);
textBuilder.Append('\n');
chunkedTextBuilder.Append(c);
chunkedTextBuilder.Append('\n');
}
void AppendThreadNumIdentifier(string name)
{
aggregateTextBuilder.Append(name);
}
void AppendParsedStatement(string text)
@@ -522,17 +532,21 @@ public sealed partial class IShaderGenerator
void FlushText()
{
if (textBuilder.Length > 0)
if (chunkedTextBuilder.Length > 0)
{
sizeHint += textBuilder.Length;
string chunkedText = chunkedTextBuilder.ToString();
aggregateTextBuilder.Append(chunkedText);
sizeHint += chunkedTextBuilder.Length;
statements.Add(
ExpressionStatement(
InvocationExpression(
MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, IdentifierName("builder"), IdentifierName("Append")))
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(textBuilder.ToString()))))));
.AddArgumentListArguments(Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(chunkedText))))));
textBuilder.Clear();
chunkedTextBuilder.Clear();
}
}
@@ -608,12 +622,15 @@ public sealed partial class IShaderGenerator
AppendLF();
AppendLine("#define __GroupSize__get_X ");
AppendParsedStatement("builder.Append(threadsX);");
AppendThreadNumIdentifier("<THREADSX>");
AppendLF();
AppendLine("#define __GroupSize__get_Y ");
AppendParsedStatement("builder.Append(threadsY);");
AppendThreadNumIdentifier("<THREADSY>");
AppendLF();
AppendLine("#define __GroupSize__get_Z ");
AppendParsedStatement("builder.Append(threadsZ);");
AppendThreadNumIdentifier("<THREADSZ>");
AppendLF();
// Define declarations
@@ -810,6 +827,8 @@ public sealed partial class IShaderGenerator
SyntaxKind.NumericLiteralExpression,
Literal(sizeHint)))))));
hlslSource = aggregateTextBuilder.ToString();
return statements;
}
}
+6 -3
ファイルの表示
@@ -16,7 +16,7 @@ namespace ComputeSharp.SourceGenerators;
public sealed partial class IShaderGenerator
{
/// <inheritdoc/>
private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol)
private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol, out bool isDynamicShader)
{
// This code produces a method declaration as follows:
//
@@ -30,16 +30,17 @@ public sealed partial class IShaderGenerator
Identifier("GetDispatchId"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.WithBody(GetShaderHashCodeBody(structDeclarationSymbol));
.WithBody(GetShaderHashCodeBody(structDeclarationSymbol, out isDynamicShader));
}
/// <summary>
/// Gets a <see cref="BlockSyntax"/> instance with the logic to compute the hashcode of a given shader type.
/// </summary>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="isDynamicShader">Indicates whether or not the shader is dynamic (ie. captures delegates).</param>
/// <returns>The <see cref="BlockSyntax"/> instance to hash the input shader.</returns>
[Pure]
private static BlockSyntax GetShaderHashCodeBody(INamedTypeSymbol structDeclarationSymbol)
private static BlockSyntax GetShaderHashCodeBody(INamedTypeSymbol structDeclarationSymbol, out bool isDynamicShader)
{
var delegateFields = structDeclarationSymbol
.GetMembers()
@@ -47,6 +48,8 @@ public sealed partial class IShaderGenerator
.Where(static m => m.Type is INamedTypeSymbol { TypeKind: TypeKind.Delegate, IsStatic: false })
.ToImmutableArray();
isDynamicShader = delegateFields.Length > 0;
if (delegateFields.Length == 0)
{
// return 0;
+186 -11
ファイルの表示
@@ -1,14 +1,182 @@
using System;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using ComputeSharp.__Internals;
using ComputeSharp.Exceptions;
using ComputeSharp.Shaders.Translation;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using TerraFX.Interop.DirectX;
using TerraFX.Interop.Windows;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators;
/// <inheritdoc/>
public sealed partial class IShaderGenerator
{
/// <summary>
/// Indicates whether the required <c>dxcompiler.dll</c> and <c>dxil.dll</c> libraries have been loaded.
/// </summary>
private static bool areDxcLibrariesLoaded;
/// <inheritdoc/>
private static partial MethodDeclarationSyntax CreateTryGetBytecodeMethod(
GeneratorExecutionContext context,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
bool isDynamicShader,
string hlslSource)
{
// This code produces a method declaration as follows:
//
// readonly int global::ComputeSharp.__Internals.IShader.TryGetBytecode(int threadsX, int threadsY, int threadsZ, out ReadOnlySpan<byte> bytecode)
// {
// <BODY>
// }
return
MethodDeclaration(
PredefinedType(Token(SyntaxKind.BoolKeyword)),
Identifier("TryGetBytecode"))
.WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifier(IdentifierName($"global::ComputeSharp.__Internals.{nameof(IShader)}")))
.AddModifiers(Token(SyntaxKind.ReadOnlyKeyword))
.AddParameterListParameters(
Parameter(Identifier("threadsX")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("threadsY")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("threadsZ")).WithType(PredefinedType(Token(SyntaxKind.IntKeyword))),
Parameter(Identifier("bytecode")).AddModifiers(Token(SyntaxKind.OutKeyword)).WithType(IdentifierName("global::System.ReadOnlySpan<byte>")))
.WithBody(GetShaderBytecodeBody(structDeclarationSymbol, isDynamicShader, hlslSource));
}
/// <summary>
/// Gets a <see cref="BlockSyntax"/> instance with the logic to try to get a compiled shader bytecode.
/// </summary>
/// <param name="structDeclarationSymbol">The input <see cref="INamedTypeSymbol"/> instance to process.</param>
/// <param name="isDynamicShader">Indicates whether or not the shader is dynamic (ie. captures delegates).</param>
/// <param name="hlslSource">The generated HLSL source code (ignoring captured delegates, if present).</param>
/// <returns>The <see cref="BlockSyntax"/> instance to hash the input shader.</returns>
[Pure]
private static unsafe BlockSyntax GetShaderBytecodeBody(INamedTypeSymbol structDeclarationSymbol, bool isDynamicShader, string hlslSource)
{
AttributeData? attribute = structDeclarationSymbol.GetAttributes().FirstOrDefault(static a => a.AttributeClass is { Name: nameof(EmbeddedBytecodeAttribute) });
// No embedded shader was requested
if (attribute is null)
{
// This code produces a method declaration as follows:
//
// bytecode = default;
//
// return false;
return
Block(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName("bytecode"),
LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))),
ReturnStatement(
LiteralExpression(
SyntaxKind.FalseLiteralExpression)));
}
// If the current shader is dynamic, emit a diagnostic error
if (isDynamicShader)
{
// TODO
return Block();
}
// Validate the thread number arguments
if (attribute.ConstructorArguments[0].Value is not int threadsX ||
attribute.ConstructorArguments[1].Value is not int threadsY ||
attribute.ConstructorArguments[2].Value is not int threadsZ ||
threadsX is < 1 or > 1024 ||
threadsY is < 1 or > 1024 ||
threadsZ is < 1 or > 64)
{
// TODO
return Block();
}
LoadNativeDxcLibraries();
try
{
// Replace the actual thread num values
hlslSource = hlslSource.Replace("<THREADSX>", threadsX.ToString()).Replace("<THREADSY>", threadsY.ToString()).Replace("<THREADSZ>", threadsZ.ToString());
// Compile the shader bytecode
using ComPtr<IDxcBlob> dxcBlobBytecode = ShaderCompiler.Instance.CompileShader(hlslSource.AsSpan());
byte* buffer = (byte*)dxcBlobBytecode.Get()->GetBufferPointer();
int length = checked((int)dxcBlobBytecode.Get()->GetBufferSize());
string bytecode = string.Join(",", new Span<byte>(buffer, length).ToArray().Select(static b => $"0x{b:X2}"));
// This code produces a method declaration as follows:
//
// if (threadsX == <X> && threadsY == <Y> && threadsZ == <Z>)
// {
// bytecode = new byte[] { 0x00, 0x01, ..., 0xFF };
//
// return true;
// }
//
// bytecode = default;
//
// return false;
return
Block(
IfStatement(
BinaryExpression(
SyntaxKind.LogicalAndExpression,
BinaryExpression(
SyntaxKind.LogicalAndExpression,
BinaryExpression(
SyntaxKind.EqualsExpression,
IdentifierName("threadsX"),
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(threadsX))),
BinaryExpression(
SyntaxKind.EqualsExpression,
IdentifierName("threadsY"),
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(threadsY)))),
BinaryExpression(
SyntaxKind.EqualsExpression,
IdentifierName("threadsZ"),
LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(threadsZ)))),
Block(
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName("bytecode"),
ParseExpression($"new byte[] {{ {bytecode} }}"))),
ReturnStatement(LiteralExpression(SyntaxKind.TrueLiteralExpression)))),
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
IdentifierName("bytecode"),
LiteralExpression(SyntaxKind.DefaultLiteralExpression, Token(SyntaxKind.DefaultKeyword)))),
ReturnStatement(LiteralExpression(SyntaxKind.FalseLiteralExpression)));
}
catch (Win32Exception)
{
// TODO
return Block();
}
catch (HlslCompilationException)
{
// TODO
return Block();
}
}
/// <summary>
/// Extracts and loads the <c>dxcompiler.dll</c> and <c>dxil.dll</c> libraries.
/// </summary>
@@ -16,18 +184,13 @@ public sealed partial class IShaderGenerator
/// <exception cref="Win32Exception">Thrown if a library fails to load.</exception>
private static void LoadNativeDxcLibraries()
{
string rid = RuntimeInformation.ProcessArchitecture switch
{
Architecture.X64 => "win-x64",
Architecture.Arm64 => "win-arm64",
_ => throw new NotSupportedException("Invalid process architecture")
};
// Extracts a specified native library for a given runtime identifier
static string ExtractLibrary(string rid, string name)
{
string sourceFilename = $"ComputeSharp.SourceGenerators.Libraries.{rid}.{name}.dll";
string targetFilename = Path.Combine("%TEMP%", "ComputeSharp.SourceGenerators", rid, $"{name}.dll");
string sourceFilename = $"ComputeSharp.SourceGenerators.ComputeSharp.Libraries.{rid}.{name}.dll";
string targetFilename = Path.Combine(Path.GetTempPath(), "ComputeSharp.SourceGenerators", Path.GetRandomFileName(), rid, $"{name}.dll");
Directory.CreateDirectory(Path.GetDirectoryName(targetFilename));
using Stream sourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(sourceFilename);
@@ -61,7 +224,19 @@ public sealed partial class IShaderGenerator
}
}
LoadLibrary(ExtractLibrary(rid, "dxil"));
LoadLibrary(ExtractLibrary(rid, "dxcompiler"));
if (!areDxcLibrariesLoaded)
{
string rid = RuntimeInformation.ProcessArchitecture switch
{
Architecture.X64 => "x64",
Architecture.Arm64 => "arm64",
_ => throw new NotSupportedException("Invalid process architecture")
};
LoadLibrary(ExtractLibrary(rid, "dxil"));
LoadLibrary(ExtractLibrary(rid, "dxcompiler"));
}
areDxcLibrariesLoaded = true;
}
}
+26 -5
ファイルの表示
@@ -56,10 +56,11 @@ public sealed partial class IShaderGenerator : ISourceGenerator
private static void OnExecute(GeneratorExecutionContext context, StructDeclarationSyntax structDeclaration, INamedTypeSymbol structDeclarationSymbol)
{
// Create the required interface methods for the current shader type
MethodDeclarationSyntax getDispatchIdMethod = CreateGetDispatchIdMethod(structDeclarationSymbol);
MethodDeclarationSyntax getDispatchIdMethod = CreateGetDispatchIdMethod(structDeclarationSymbol, out bool isDynamicShader);
MethodDeclarationSyntax loadDispatchDataMethod = CreateLoadDispatchDataMethod(context, structDeclarationSymbol, out var discoveredResources, out int root32BitConstants);
MethodDeclarationSyntax buildHlslStringMethod = CreateBuildHlslStringMethod(context, structDeclaration, structDeclarationSymbol, out string? implicitTextureType, out bool isSamplerUsed);
MethodDeclarationSyntax buildHlslStringMethod = CreateBuildHlslStringMethod(context, structDeclaration, structDeclarationSymbol, out string? implicitTextureType, out bool isSamplerUsed, out string hlslSource);
MethodDeclarationSyntax loadDispatchMetadataMethod = CreateLoadDispatchMetadataMethod(implicitTextureType, discoveredResources, root32BitConstants, isSamplerUsed);
MethodDeclarationSyntax tryGetBytecodeMethod = CreateTryGetBytecodeMethod(context, structDeclaration, structDeclarationSymbol, isDynamicShader, hlslSource);
// Reorder the method declarations to respect the order in the interface definition
MethodDeclarationSyntax[] methods =
@@ -67,7 +68,8 @@ public sealed partial class IShaderGenerator : ISourceGenerator
getDispatchIdMethod,
loadDispatchDataMethod,
loadDispatchMetadataMethod,
buildHlslStringMethod
buildHlslStringMethod,
tryGetBytecodeMethod
};
// Method attributes
@@ -148,8 +150,9 @@ public sealed partial class IShaderGenerator : ISourceGenerator
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.
/// </summary>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for the input struct declaration.</param>
/// <param name="isDynamicShader">Indicates whether or not the shader is dynamic (ie. captures delegates).</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>GetDispatchId</c> method.</returns>
private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol);
private static partial MethodDeclarationSyntax CreateGetDispatchIdMethod(INamedTypeSymbol structDeclarationSymbol, out bool isDynamicShader);
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchDataMethod</c> method.
@@ -173,13 +176,15 @@ public sealed partial class IShaderGenerator : ISourceGenerator
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
/// <param name="implicitTextureType">The implicit texture type, if available (if the shader is a pixel shader).</param>
/// <param name="isSamplerUsed">Whether or not the current shader type requires a static sampler to be available.</param>
/// <param name="hlslSource">The generated HLSL source code (ignoring captured delegates, if present).</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.</returns>
private static partial MethodDeclarationSyntax CreateBuildHlslStringMethod(
GeneratorExecutionContext context,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
out string? implicitTextureType,
out bool isSamplerUsed);
out bool isSamplerUsed,
out string hlslSource);
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>LoadDispatchMetadata</c> method.
@@ -194,4 +199,20 @@ public sealed partial class IShaderGenerator : ISourceGenerator
IReadOnlyCollection<string> discoveredResources,
int root32BitConstantsCount,
bool isSamplerUsed);
/// <summary>
/// Creates a <see cref="MethodDeclarationSyntax"/> instance for the <c>TryGetBytecode</c> method.
/// </summary>
/// <param name="context">The input <see cref="GeneratorExecutionContext"/> instance to use.</param>
/// <param name="structDeclaration">The <see cref="StructDeclarationSyntax"/> node to process.</param>
/// <param name="structDeclarationSymbol">The <see cref="INamedTypeSymbol"/> for <paramref name="structDeclaration"/>.</param>
/// <param name="isDynamicShader">Indicates whether or not the shader is dynamic (ie. captures delegates).</param>
/// <param name="hlslSource">The generated HLSL source code (ignoring captured delegates, if present).</param>
/// <returns>The resulting <see cref="MethodDeclarationSyntax"/> instance for the <c>BuildHlslString</c> method.</returns>
private static partial MethodDeclarationSyntax CreateTryGetBytecodeMethod(
GeneratorExecutionContext context,
StructDeclarationSyntax structDeclaration,
INamedTypeSymbol structDeclarationSymbol,
bool isDynamicShader,
string hlslSource);
}