diff --git a/README.md b/README.md index 08fb7c30..7bf6e144 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,8 @@ If the shader in C# is capturing some local variable, those will be automaticall ✅ `Func`s, local methods or delegates with no captured variables +✅ `static` fields and properties with a supported delegate type + ## Advanced usage **ComputeSharp** lets you dispatch compute shaders over thread groups from 1 to 3 dimensions, includes supports for constant and readonly buffers, and more. The shader body can both be declared inline, as a separate `Action` or as a local method. Additionally, most of the [HLSL intrinsic functions](https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-intrinsic-functions) are available through the `Hlsl` class. Here is a more advanced sample showcasing all these features. @@ -71,11 +73,14 @@ float[] y = new float[height * width]; // Result array (assume both had some val using ReadOnlyBuffer xBuffer = Gpu.Default.AllocateReadOnlyBuffer(x); using ReadWriteBuffer yBuffer = Gpu.Default.AllocateReadWriteBuffer(y); +static float Sigmoid(float x) => 1 / (1 + Hlsl.Exp(-x)); + // Shader body void Kernel(ThreadIds id) { int offset = id.X + id.Y * width; - yBuffer[offset] = Hlsl.Pow(xBuffer[offset], 2); + float pow = Hlsl.Pow(xBuffer[offset], 2); + yBuffer[offset] = Sigmoid(pow); } // Run the shader diff --git a/src/ComputeSharp.Core/Intrinsics/Hlsl.cs b/src/ComputeSharp.Core/Intrinsics/Hlsl.cs index 892a0b9c..ace7a527 100644 --- a/src/ComputeSharp.Core/Intrinsics/Hlsl.cs +++ b/src/ComputeSharp.Core/Intrinsics/Hlsl.cs @@ -849,7 +849,7 @@ namespace ComputeSharp /// The input value /// The number of bits [Pure] - public static uint CountBits(uint x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(CountBits)}({nameof(Vector4)})"); + public static uint CountBits(uint x) => throw new InvalidExecutionContextException($"{nameof(Hlsl)}.{nameof(CountBits)}(uint)"); /// /// Returns the cross product of two values diff --git a/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs b/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs index dbec13e3..efc7b4be 100644 --- a/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs +++ b/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs @@ -168,6 +168,83 @@ namespace ComputeSharp.Shaders.Extensions return node; } + /// + /// Checks a instance and replaces it to be HLSL compatible, if needed + /// + /// The input to check and modify if needed + /// The in which the input syntax tree is declared in + /// The info on parsed static members, if any + /// The info on parsed static methods, if any + /// A instance that is compatible with HLSL + [Pure] + public static InvocationExpressionSyntax ReplaceInvocation(this InvocationExpressionSyntax node, Type declaringType, out (string Name, ReadableMember MemberInfo)? variable, out (string Name, MethodInfo MethodInfo)? method) + { + // Set the variable and method to null + variable = null; + method = null; + + // Explore the nested classes from bottom to top + if (declaringType.TryFindAncestorMember(node.Expression.ToString(), BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, out var result)) + { + // If a static method or delegate is found, track it + string name = $"{result.Value.DeclaringType.Name}_{result.Value.MemberInfo.Name}"; + switch (result.Value.MemberInfo) + { + case FieldInfo fieldInfo: + variable = (name, fieldInfo); + break; + case PropertyInfo propertyInfo: + variable = (name, propertyInfo); + break; + case MethodInfo methodInfo: + method = (name, methodInfo); + return SyntaxFactory.InvocationExpression(SyntaxFactory.ParseExpression(name), node.ArgumentList).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia()); + default: throw new InvalidOperationException($"Invalid symbol kind: {result.Value.MemberInfo.GetType()}"); + } + + // Return the mapped expression + return SyntaxFactory.InvocationExpression(SyntaxFactory.ParseExpression(name), node.ArgumentList).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia()); + } + + return node; + } + + /// + /// Checks a instance and replaces it to be HLSL compatible, if needed + /// + /// The input to check and modify if needed + /// The in which the input syntax tree is declared in + /// The info on parsed static members, if any + /// A instance that is compatible with HLSL + [Pure] + public static IdentifierNameSyntax ReplaceIdentifierName(this IdentifierNameSyntax node, Type declaringType, out (string Name, ReadableMember MemberInfo)? variable) + { + // Set the variable to null + variable = null; + + // Explore the nested classes from bottom to top + if (declaringType.TryFindAncestorMember(node.Identifier.ToString(), BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, out var result)) + { + // If a static scalar or vector member is found, track it + string name = $"{result.Value.DeclaringType.Name}_{result.Value.MemberInfo.Name}"; + switch (result.Value.MemberInfo) + { + case FieldInfo fieldInfo when HlslKnownTypes.IsKnownType(fieldInfo.FieldType): + variable = (name, fieldInfo); + break; + case PropertyInfo propertyInfo when HlslKnownTypes.IsKnownType(propertyInfo.PropertyType): + variable = (name, propertyInfo); + break; + default: return node; + } + + // Return the mapped expression + return SyntaxFactory.IdentifierName(name).WithLeadingTrivia(node.GetLeadingTrivia()).WithTrailingTrivia(node.GetTrailingTrivia()); + } + + return node; + } + /// /// Processes a loaded static member, either a field or a property /// diff --git a/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs b/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs index 77f693d5..467ccd8a 100644 --- a/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs +++ b/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; @@ -29,6 +30,29 @@ namespace ComputeSharp.Shaders.Extensions [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsStatelessDelegateContainer(this Type type) => type.GetFields(BindingFlags.Static | BindingFlags.Public).Length > 0; + /// + /// Tries to find an ancestor member starting from the input + /// + /// The input type to start the search from + /// The name of the member to retrieve + /// A bitmask comprised of one or more that specify how the search is conducted + /// when a member with the given name is found, otherwise + public static bool TryFindAncestorMember(this Type type, string name, BindingFlags bindingAttr, [NotNullWhen(true)] out (Type DeclaringType, MemberInfo MemberInfo)? result) + { + while ((type = type.DeclaringType) != null) + { + MemberInfo[] memberInfos = type.GetMember(name, bindingAttr); + if (memberInfos.Length > 0) + { + result = (type, memberInfos[0]); + return true; + } + } + + result = null; + return false; + } + /// /// The mapping of supported known types to display string /// diff --git a/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs index 2409c158..65bd4918 100644 --- a/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs @@ -58,6 +58,18 @@ namespace ComputeSharp.Shaders.Mappings /// public static IReadOnlyCollection HlslMappedVectorTypes => _HlslMappedVectorTypes; + /// + /// Checks whether or not the input type is a known HLSL-compatible type + /// + /// The input instance to check + /// A indicating whether the input is in fact a known HLSL type + [Pure] + public static bool IsKnownType(Type type) => IsKnownScalarType(type) || + IsKnownVectorType(type) || + IsConstantBufferType(type) || + IsReadOnlyBufferType(type) || + IsReadWriteBufferType(type); + /// /// Checks whether or not the input type is a known scalar type /// diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index d9010301..beeb82ac 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -299,13 +299,20 @@ namespace ComputeSharp.Shaders.Translation MethodDecompiler.Instance.GetSyntaxTree(Action.Method, MethodType.Closure, out MethodDeclarationSyntax root, out SemanticModel semanticModel); // Rewrite the shader method (eg. to fix the type declarations) - ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel); + ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, ShaderType); root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root); // Extract the implicit local functions var locals = root.DescendantNodes().OfType().ToArray(); root = root.RemoveNodes(locals, SyntaxRemoveOptions.KeepNoTrivia); - _LocalFunctionsList.AddRange(locals.Select(local => new LocalFunctionInfo(local.ToFullString().RemoveLeftPadding().Trim(' ', '\r', '\n')))); + foreach (var local in locals) + { + string alignedLocal = local.ToFullString().RemoveLeftPadding().Trim(' ', '\r', '\n'); + alignedLocal = Regex.Replace(alignedLocal, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value); + alignedLocal = HlslKnownKeywords.GetMappedText(alignedLocal); + + _LocalFunctionsList.Add(new LocalFunctionInfo(alignedLocal)); + } // Register the captured static members foreach (var member in syntaxRewriter.StaticMembers) @@ -340,7 +347,7 @@ namespace ComputeSharp.Shaders.Translation MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Static, out MethodDeclarationSyntax root, out SemanticModel semanticModel); // Rewrite the method - ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel); + ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, methodInfo.DeclaringType); root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root); // Register the captured static members diff --git a/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs b/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs index c92b2e37..0199e610 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Reflection; using ComputeSharp.Shaders.Extensions; using ComputeSharp.Shaders.Translation.Models; @@ -18,11 +19,21 @@ namespace ComputeSharp.Shaders.Translation /// private readonly SemanticModel SemanticModel; + /// + /// The declaring type that hosts the root from which the current syntax tree is inspected + /// + private readonly Type DeclaringType; + /// /// Creates a new instance with the specified parameters /// - /// - public ShaderSyntaxRewriter(SemanticModel semanticModel) => SemanticModel = semanticModel; + /// The instance to use to rewrite the decompiled code + /// The declaring type that hosts the root from which the current syntax tree is inspected + public ShaderSyntaxRewriter(SemanticModel semanticModel, Type declaringType) + { + SemanticModel = semanticModel; + DeclaringType = declaringType; + } private readonly Dictionary _StaticMembers = new Dictionary(); @@ -38,6 +49,21 @@ namespace ComputeSharp.Shaders.Translation /// public IReadOnlyDictionary StaticMethods => _StaticMethods; + /// + public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node) + { + node = (IdentifierNameSyntax)base.VisitIdentifierName(node); + node = node.ReplaceIdentifierName(DeclaringType, out var variable); + + // Register the captured member, if any + if (variable.HasValue && !_StaticMembers.ContainsKey(variable.Value.Name)) + { + _StaticMembers.Add(variable.Value.Name, variable.Value.MemberInfo); + } + + return node; + } + /// public override SyntaxNode VisitParameter(ParameterSyntax node) { @@ -119,6 +145,25 @@ namespace ComputeSharp.Shaders.Translation return syntaxNode; } + /// + public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node) + { + node = (InvocationExpressionSyntax)base.VisitInvocationExpression(node); + node = node.ReplaceInvocation(DeclaringType, out var variable, out var method); + + // Register the captured members, if any + if (variable.HasValue && !_StaticMembers.ContainsKey(variable.Value.Name)) + { + _StaticMembers.Add(variable.Value.Name, variable.Value.MemberInfo); + } + if (method.HasValue && !_StaticMethods.ContainsKey(method.Value.Name)) + { + _StaticMethods.Add(method.Value.Name, method.Value.MethodInfo); + } + + return node; + } + /// public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node) { diff --git a/tests/ComputeSharp.Tests/StaticFunctionsTests.cs b/tests/ComputeSharp.Tests/StaticFunctionsTests.cs index fbcd1c53..ce7ccb7c 100644 --- a/tests/ComputeSharp.Tests/StaticFunctionsTests.cs +++ b/tests/ComputeSharp.Tests/StaticFunctionsTests.cs @@ -135,5 +135,67 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); } + + public static float Square(float x) => x * x; + + [TestMethod] + public void StaticMethodInSameClass() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + Gpu.Default.For(1, id => buffer[0] = Square(3)); + + float[] result = buffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); + } + + public static Func SquareFunc { get; } = x => x * x; + + [TestMethod] + public void StaticFunctionInSameClass() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + Gpu.Default.For(1, id => buffer[0] = SquareFunc(3)); + + float[] result = buffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); + } + + [TestMethod] + public void StaticFunctionInExternalClass() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + Gpu.Default.For(1, id => buffer[0] = StaticPropertiesContainer.SquareFunc(3)); + + float[] result = buffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - 9) < 0.0001f); + } + + [TestMethod] + public void ReadmeSample() + { + float[] buffer = { 3 }; + using ReadWriteBuffer xBuffer = Gpu.Default.AllocateReadWriteBuffer(buffer); + + static float Sigmoid(float x) => 1 / (1 + Hlsl.Exp(-x)); + + void Kernel(ThreadIds id) + { + int offset = id.X + id.Y * 1; + float pow = Hlsl.Pow(xBuffer[offset], 2); // 9 + xBuffer[offset] = Sigmoid(pow); // 0.9998766 + } + + Gpu.Default.For(1, Kernel); + + float[] result = xBuffer.GetData(); + + Assert.IsTrue(MathF.Abs(result[0] - 0.9998766f) < 0.0001f); + } } } diff --git a/tests/ComputeSharp.Tests/StaticPropertiesTests.cs b/tests/ComputeSharp.Tests/StaticPropertiesTests.cs index 6290abf0..bf5ceb57 100644 --- a/tests/ComputeSharp.Tests/StaticPropertiesTests.cs +++ b/tests/ComputeSharp.Tests/StaticPropertiesTests.cs @@ -33,6 +33,11 @@ namespace ComputeSharp.Tests /// A property /// public static ReadOnlyBuffer StaticBuffer { get; set; } = Gpu.Default.AllocateReadOnlyBuffer(new[] { 3.14f, 7.77f }); + + /// + /// A property + /// + public static Func SquareFunc { get; } = x => x * x; } [TestClass] @@ -138,5 +143,21 @@ namespace ComputeSharp.Tests Assert.IsTrue(MathF.Abs(result[0] - expected[0]) < 0.0001f); Assert.IsTrue(MathF.Abs(result[1] - expected[1]) < 0.0001f); } + + public static int SomeNumber = 7; + + [TestMethod] + public void StaticLocalScalarFieldAssignToBuffer() + { + using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1); + + Action action = id => buffer[0] = SomeNumber; + + Gpu.Default.For(1, action); + + int[] result = buffer.GetData(); + + Assert.IsTrue(result[0] == SomeNumber); + } } }