Enabled initial support for shader metaprogramming

このコミットが含まれているのは:
Sergio Pedri committed 2021-07-12 20:21:56 +02:00
1 親 f2c1b79b6a
コミット ce5e9703cd
7ファイル変更
+189 -78

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

-1
ファイルの表示
@@ -22,7 +22,6 @@
<Compile Include="..\ComputeSharp\Core\Dispatch\ThreadIds.cs" Link="Core\Dispatch\ThreadIds.cs" />
<Compile Include="..\ComputeSharp\Core\Dispatch\ThreadIds.Normalized.cs" Link="Core\Dispatch\ThreadIds.Normalized.cs" />
<Compile Include="..\ComputeSharp\Core\Exceptions\InvalidExecutionContextException.cs" Link="Core\Exceptions\InvalidExecutionContextException.cs" />
<Compile Include="..\ComputeSharp\Core\Exceptions\MissingMethodSourceException.cs" Link="Core\Exceptions\MissingMethodSourceException.cs" />
<Compile Include="..\ComputeSharp\Core\Extensions\MethodInfoExtensions.cs" Link="Core\Extensions\MethodInfoExtensions.cs" />
<Compile Include="..\ComputeSharp\Core\Helpers\AlignmentHelper.cs" Link="Core\Helpers\AlignmentHelper.cs" />
<Compile Include="..\ComputeSharp\Core\Interfaces\IComputeShader.cs" Link="Core\Interfaces\IComputeShader.cs" />
+49 -9
ファイルの表示
@@ -2,6 +2,7 @@
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
using ComputeSharp.__Internals;
using ComputeSharp.SourceGenerators.Diagnostics;
using ComputeSharp.SourceGenerators.Extensions;
using ComputeSharp.SourceGenerators.Helpers;
@@ -14,6 +15,8 @@ using static ComputeSharp.SourceGenerators.Diagnostics.DiagnosticDescriptors;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle;
#pragma warning disable CS0618
namespace ComputeSharp.SourceGenerators
{
/// <inheritdoc/>
@@ -404,7 +407,7 @@ namespace ComputeSharp.SourceGenerators
/// </summary>
/// <param name="types">The sequence of discovered custom types.</param>
/// <returns>A sequence of custom type definitions to add to the shader source.</returns>
internal static IEnumerable<string> GetProcessedTypes(IEnumerable<INamedTypeSymbol> types)
internal static IEnumerable<(string Name, string Definition)> GetProcessedTypes(IEnumerable<INamedTypeSymbol> types)
{
foreach (var type in HlslKnownTypes.GetCustomTypes(types))
{
@@ -430,10 +433,11 @@ namespace ComputeSharp.SourceGenerators
// Insert the trailing ; right after the closing bracket (after normalization)
yield return
structDeclaration
.NormalizeWhitespace(eol: "\n")
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
.ToFullString();
(structType,
structDeclaration
.NormalizeWhitespace(eol: "\n")
.WithSemicolonToken(Token(SyntaxKind.SemicolonToken))
.ToFullString());
}
}
@@ -468,7 +472,7 @@ namespace ComputeSharp.SourceGenerators
private static IEnumerable<StatementSyntax> GenerateRenderMethodBody(
IEnumerable<(string Name, string Value)> definedConstants,
IEnumerable<(string Name, string TypeDeclaration, string? Assignment)> staticFields,
IEnumerable<string> declaredTypes,
IEnumerable<(string Name, string Definition)> declaredTypes,
bool isComputeShader,
IEnumerable<(IFieldSymbol Symbol, string HlslName, string HlslType)> instanceFields,
string? implicitTextureType,
@@ -479,6 +483,32 @@ namespace ComputeSharp.SourceGenerators
string executeMethod)
{
List<StatementSyntax> statements = new();
int capturedDelegates = 0;
foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields)
{
if (fieldSymbol.Type.TypeKind == TypeKind.Delegate)
{
// ShaderMethodSourceAttribute __<DELEGATE_NAME>Attribute = ShaderMethodSourceAttribute.GetForDelegate(<DELEGATE_NAME>, "<DELEGATE_NAME>");
statements.Add(
LocalDeclarationStatement(VariableDeclaration(IdentifierName(nameof(ShaderMethodSourceAttribute)))
.AddVariables(
VariableDeclarator(Identifier($"__{fieldName}Attribute"))
.WithInitializer(
EqualsValueClause(
InvocationExpression(
MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
IdentifierName(nameof(ShaderMethodSourceAttribute)),
IdentifierName(nameof(ShaderMethodSourceAttribute.GetForDelegate))))
.AddArgumentListArguments(
Argument(IdentifierName(fieldName)),
Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(fieldName)))))))));
capturedDelegates++;
}
}
int sizeHint = 64;
void AppendLF()
@@ -554,10 +584,10 @@ namespace ComputeSharp.SourceGenerators
}
// Declared types
foreach (var type in declaredTypes)
foreach (var (typeName, typeDefinition) in declaredTypes)
{
AppendLF();
AppendLineAndLF(type);
AppendLineAndLF(typeDefinition);
}
// Captured variables
@@ -656,13 +686,23 @@ namespace ComputeSharp.SourceGenerators
}
}
// Captured delegate methods
foreach (var (fieldSymbol, fieldName, fieldType) in instanceFields)
{
if (fieldSymbol.Type.TypeKind == TypeKind.Delegate)
{
AppendLF();
statements.Add(ParseStatement($"builder.AppendLine(__{fieldName}Attribute.{nameof(ShaderMethodSourceAttribute.GetMappedInvokeMethod)}(\"{fieldName}\"));"));
}
}
// Entry point
AppendLF();
AppendLineAndLF("[NumThreads(__GroupSize__get_X, __GroupSize__get_Y, __GroupSize__get_Z)]");
AppendLineAndLF(executeMethod);
// builder = ArrayPoolStringBuilder.Create(<SIZE_HINT>);
statements.Insert(0,
statements.Insert(capturedDelegates,
ExpressionStatement(
AssignmentExpression(
SyntaxKind.SimpleAssignmentExpression,
+3 -3
ファイルの表示
@@ -70,7 +70,7 @@ namespace ComputeSharp.SourceGenerators
Dictionary<IFieldSymbol, string> constantDefinitions = new(SymbolEqualityComparer.Default);
// Explore the syntax tree and extract the processed info
var (invokeMethod, processedMethods) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, staticMethods, constantDefinitions);
var (invokeMethod, localFunctions) = GetProcessedMethods(context, methodDeclaration, semanticModel, discoveredTypes, staticMethods, constantDefinitions);
var processedTypes = IShaderGenerator.GetProcessedTypes(discoveredTypes).ToArray();
var processedConstants = IShaderGenerator.GetProcessedConstants(constantDefinitions);
@@ -80,9 +80,9 @@ namespace ComputeSharp.SourceGenerators
AttributeList(SingletonSeparatedList(
Attribute(IdentifierName(typeof(ShaderMethodSourceAttribute).FullName)).AddArgumentListArguments(
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(methodDeclarationSymbol.GetFullMetadataName(true)))),
AttributeArgument(ArrayExpression(processedTypes)),
AttributeArgument(NestedArrayExpression(processedTypes)),
AttributeArgument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(invokeMethod))),
AttributeArgument(ArrayExpression(processedMethods)),
AttributeArgument(ArrayExpression(localFunctions)),
AttributeArgument(NestedArrayExpression(processedConstants)))))
.WithOpenBracketToken(Token(TriviaList(Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true))), SyntaxKind.OpenBracketToken, TriviaList()))
.WithTarget(AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword))))
+20 -10
ファイルの表示
@@ -5,7 +5,6 @@ using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using ComputeSharp.Core.Extensions;
using ComputeSharp.Exceptions;
namespace ComputeSharp.__Internals
{
@@ -37,12 +36,12 @@ namespace ComputeSharp.__Internals
/// <param name="invokeMethod">The source code for the target entry point method.</param>
/// <param name="methods">The collection of processed methods.</param>
/// <param name="constants">The collection of discovered constants.</param>
public ShaderMethodSourceAttribute(string methodName, string[] types, string invokeMethod, string[] methods, object[] constants)
public ShaderMethodSourceAttribute(string methodName, object[] types, string invokeMethod, string[] methods, object[] constants)
{
this.invokeMethod = invokeMethod;
MethodName = methodName;
Types = types;
Types = types.Cast<string[]>().ToDictionary(static c => c[0], static c => c[1]);
Methods = methods;
Constants = constants.Cast<string[]>().ToDictionary(static c => c[0], static c => c[1]);
}
@@ -55,7 +54,7 @@ namespace ComputeSharp.__Internals
/// <summary>
/// Gets the collection of processed custom types.
/// </summary>
internal IReadOnlyCollection<string> Types { get; }
internal IReadOnlyDictionary<string, string> Types { get; }
/// <summary>
/// Gets the collection of processed methods.
@@ -73,7 +72,7 @@ namespace ComputeSharp.__Internals
/// <param name="name">The name to bind the method to.</param>
/// <returns>The mapped source code for the current mehtod.</returns>
[Pure]
internal string GetMappedInvokeMethod(string name)
public string GetMappedInvokeMethod(string name)
{
return this.invokeMethod.Replace(InvokeMethodIdentifier, name);
}
@@ -82,13 +81,14 @@ namespace ComputeSharp.__Internals
/// Gets the associated <see cref="ShaderMethodSourceAttribute"/> instance for a specified delegate.
/// </summary>
/// <param name="function">The input <see cref="Delegate"/> instance to get info for.</param>
/// <param name="name">The name of the shader field containing <paramref name="function"/>.</param>
/// <returns>The associated <see cref="ShaderMethodSourceAttribute"/> instance for the given delegate.</returns>
[Pure]
internal static ShaderMethodSourceAttribute GetForDelegate(Delegate function)
public static ShaderMethodSourceAttribute GetForDelegate(Delegate function, string name)
{
if (!function.Method.IsStatic)
{
ThrowArgumentExceptionForNonStaticShader();
return ThrowArgumentExceptionForNonStaticMethod(name);
}
var attributes = function.Method.DeclaringType!.Assembly.GetCustomAttributes<ShaderMethodSourceAttribute>();
@@ -102,15 +102,25 @@ namespace ComputeSharp.__Internals
}
}
return MissingMethodSourceException.Throw(function);
return ThrowArgumentExceptionForMissingShaderMethodAttribute(name);
}
/// <summary>
/// Throws an <see cref="ArgumentException"/> when a given <see cref="Delegate"/> is not static.
/// </summary>
private static void ThrowArgumentExceptionForNonStaticShader()
/// <param name="name">The name of the shader field containing the invalid method.</param>
private static ShaderMethodSourceAttribute ThrowArgumentExceptionForNonStaticMethod(string name)
{
throw new ArgumentException("Captured delegates in a shader need to wrap a static method.", "function");
throw new ArgumentException($"The captured delegate \"{name}\" was wrapping a non static method (only static methods are supported for captured delegates).", name);
}
/// <summary>
/// Throws an <see cref="ArgumentException"/> when a given <see cref="Delegate"/> doesn't have <see cref="ShaderMethodAttribute"/> applied to it.
/// </summary>
/// <param name="name">The name of the shader field containing the invalid method.</param>
private static ShaderMethodSourceAttribute ThrowArgumentExceptionForMissingShaderMethodAttribute(string name)
{
throw new ArgumentException($"The captured delegate \"{name}\" was wrapping a method without the [ShaderMethod] attribute applied to it.", name);
}
}
}
-53
ファイルの表示
@@ -1,53 +0,0 @@
using System;
using System.Diagnostics.Contracts;
using System.Text;
using ComputeSharp.__Internals;
using ComputeSharp.Core.Extensions;
#pragma warning disable CS0618
namespace ComputeSharp.Exceptions
{
/// <summary>
/// A custom <see cref="InvalidOperationException"/> that indicates when an HLSL-only API is called from C#
/// </summary>
public sealed class MissingMethodSourceException : InvalidOperationException
{
/// <summary>
/// Creates a new <see cref="MissingMethodSourceException"/> instance.
/// </summary>
/// <param name="message">The exception message to display.</param>
private MissingMethodSourceException(string message)
: base(message)
{
}
/// <summary>
/// Creates a new <see cref="MissingMethodSourceException"/> instance from the specified parameters.
/// </summary>
/// <param name="method">The target <see cref="Delegate"/> that couldn't be processed.</param>
/// <returns>A new <see cref="MissingMethodSourceException"/> instance with a formatted error message.</returns>
[Pure]
private static MissingMethodSourceException Create(Delegate method)
{
StringBuilder builder = new(512);
builder.AppendLine("The processed source for a method captured as a delegate in a shader was not found.");
builder.AppendLine($"The delegate was of type {method.GetType()} and it was wrapping the method {method.Method.GetFullName()}.");
builder.Append($"Make sure that the target method is annotated with [{nameof(ShaderMethodAttribute)}].");
builder.ToString();
return new(builder.ToString());
}
/// <summary>
/// Throws a new <see cref="MissingMethodSourceException"/> for a given delegate.
/// </summary>
/// <param name="method">The target <see cref="Delegate"/> that couldn't be processed.</param>
/// <returns>This method always throws and never actually returns anything.</returns>
internal static ShaderMethodSourceAttribute Throw(Delegate method)
{
throw Create(method);
}
}
}
+2 -2
ファイルの表示
@@ -23,10 +23,10 @@ namespace ComputeSharp.Core.Extensions
{
var arguments = string.Join(", ", method.GetGenericArguments().Select(static t => t.FullName));
return $"{method.DeclaringType!.FullName}.{method.Name}<{arguments}>({parameters})";
return $"{method.DeclaringType!.FullName!.Replace('+', '.')}.{method.Name}<{arguments}>({parameters})";
}
return $"{method.DeclaringType!.FullName}.{method.Name}({parameters})";
return $"{method.DeclaringType!.FullName!.Replace('+', '.')}.{method.Name}({parameters})";
}
}
}
+115
ファイルの表示
@@ -0,0 +1,115 @@
using System;
using ComputeSharp.Tests.Attributes;
using ComputeSharp.Tests.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
#pragma warning disable IDE0062
namespace ComputeSharp.Tests
{
[TestClass]
[TestCategory("Metaprogramming")]
public partial class MetaprogrammingTests
{
[AutoConstructor]
internal readonly partial struct ActivationWithDelegateShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
public readonly Func<int, int> activation;
public void Execute()
{
buffer[ThreadIds.X] = activation(ThreadIds.X);
}
}
public static class Activations
{
[ShaderMethod]
public static int Square(int x) => x * x;
[ShaderMethod]
public static int AddOne(int x) => x + 1;
// Missing attribute
public static int Identity(int x) => x;
}
[CombinatorialTestMethod]
[AllDevices]
public unsafe void ActivationWithDelegate(Device device)
{
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(100);
device.Get().For(100, new ActivationWithDelegateShader(buffer, Activations.Square));
int[] result = buffer.ToArray();
for (int i = 0; i < 100; i++)
{
Assert.AreEqual(result[i], Activations.Square(i));
}
device.Get().For(100, new ActivationWithDelegateShader(buffer, Activations.AddOne));
result = buffer.ToArray();
for (int i = 0; i < 100; i++)
{
Assert.AreEqual(result[i], Activations.AddOne(i));
}
}
[CombinatorialTestMethod]
[AllDevices]
[ExpectedException(typeof(ArgumentException))]
public unsafe void DelegateWithMissingAttributeOnMethod(Device device)
{
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(100);
device.Get().For(100, new ActivationWithDelegateShader(buffer, Activations.Identity));
}
[CombinatorialTestMethod]
[AllDevices]
[ExpectedException(typeof(ArgumentException))]
public unsafe void DelegateWrappingNonStaticMethod(Device device)
{
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(100);
[ShaderMethod]
int Dummy(int x) => x;
device.Get().For(100, new ActivationWithDelegateShader(buffer, Dummy));
}
[AutoConstructor]
internal readonly partial struct ActivationWithMultipleDelegatesShader : IComputeShader
{
public readonly ReadWriteBuffer<int> buffer;
public readonly Func<int, int> f1;
public readonly Func<int, int> f2;
public void Execute()
{
buffer[ThreadIds.X] = f2(f1(ThreadIds.X));
}
}
[CombinatorialTestMethod]
[AllDevices]
public unsafe void ActivationWithMultipleDelegates(Device device)
{
using ReadWriteBuffer<int> buffer = device.Get().AllocateReadWriteBuffer<int>(100);
device.Get().For(100, new ActivationWithMultipleDelegatesShader(buffer, Activations.Square, Activations.AddOne));
int[] result = buffer.ToArray();
for (int i = 0; i < 100; i++)
{
Assert.AreEqual(result[i], Activations.AddOne(Activations.Square(i)));
}
}
}
}