diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs new file mode 100644 index 00000000..889f1abe --- /dev/null +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.IL.cs @@ -0,0 +1,170 @@ +using System; +using System.Buffers; +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using System.Linq; +using System.Reflection.Emit; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Shaders.Mappings; +using ComputeSharp.Shaders.Translation.Models; + +namespace ComputeSharp.Shaders.Translation +{ + /// + internal sealed partial class ShaderLoader + { + /// + /// The number of captured graphics resources (buffers) + /// + private int _ResourcesCount; + + /// + /// The size in bytes of the buffer with the captured variables + /// + private int _VariablesByteSize = 3 * sizeof(int); // X, Y and Z threads count + + // The cached loader method + private DispatchDataLoader? _DispatchDataLoader; + + /// + /// The of instances mapping the captured variables in the current shader + /// + private readonly List _CapturedMembers = new List(); + + /// + /// A that loads all the captured members from a shader closure + /// + /// The shader closure instance to load the data from + /// A reference to the buffer with all the captured instances + /// A reference to the buffer to use to store all the captured value types + private delegate void DispatchDataLoader(object obj, ref GraphicsResource r0, ref byte r1); + + /// + /// Gets a new instance with all the captured data for the current shader instance + /// + /// The input representing the compute shader to run + /// The number of iterations to run on the X axis + /// The number of iterations to run on the Y axis + /// The number of iterations to run on the Z axis + [Pure] + public DispatchData GetDispatchData(Action action, int x, int y, int z) + { + // Resources and variables buffers + GraphicsResource[] resources = ArrayPool.Shared.Rent(_ResourcesCount); + byte[] variables = ArrayPool.Shared.Rent(_VariablesByteSize); + ref GraphicsResource r0 = ref resources[0]; + ref byte r1 = ref variables[0]; + + // Set the x, y and z counters + Unsafe.As(ref r1) = x; + Unsafe.Add(ref Unsafe.As(ref r1), 1) = y; + Unsafe.Add(ref Unsafe.As(ref r1), 2) = z; + + // Invoke the dynamic method to extract the captured data + _DispatchDataLoader!(action.Target, ref r0, ref r1); + + return new DispatchData(resources, _ResourcesCount, variables, _VariablesByteSize); + } + + /// + /// Builds a new instance that loads the dispatch data for the current shader type + /// + private void BuildDispatchDataLoader() + { + // Mapping of parent members to index of the relative local variable + var map = + _CapturedMembers + .Where(m => !m.IsStatic && m.Parents != null) + .SelectMany(m => m.Parents) + .Distinct() + .Select((m, i) => (Member: m, Index: i)) + .ToDictionary(p => (object)p.Member, p => p.Index + 1); + object root = new object(); // Placeholder + map.Add(root, 0); + + // Set of indices of the loaded parent members + HashSet loaded = new HashSet(new[] { 0 }); + + // Build the dynamic IL method + _DispatchDataLoader = DynamicMethod.New(il => + { + // Loads a given member on the top of the execution stack + void LoadMember(ReadableMember member) + { + if (!member.IsStatic) + { + // Load the parent instance on the execution stack if the member isn't static + int index = map[member.Parents?.Last() ?? root]; + if (loaded.Contains(index)) il.EmitLoadLocal(index); + else + { + // Seek upwards to find the most in depth loaded parent + int i = member.Parents!.Count - 1; + while (i > 0 && !loaded.Contains(map[member.Parents[i]])) i--; + + // Load the local variables for all the parents of the current member + il.EmitLoadLocal(i); + for (; i < member.Parents.Count; i++) + { + index = map[member.Parents[i]]; + il.Emit(OpCodes.Ldfld, member.Parents[i]); + il.EmitStoreLocal(index); + il.EmitLoadLocal(index); + loaded.Add(index); + } + } + } + + il.EmitReadMember(member); + } + + // Declare the local variables + il.DeclareLocal(typeof(T)); + foreach (ReadableMember member in map.OrderBy(p => p.Value).Skip(1).Select(p => p.Key)) + { + il.DeclareLocal(member.MemberType); + } + + // Cast the closure instance and assign it to the local variable + il.Emit(OpCodes.Ldarg_0); + il.EmitCastOrUnbox(typeof(T)); + il.Emit(OpCodes.Stloc_0); + + // Handle all the captured members, both resources and variables + foreach (ReadableMember member in _CapturedMembers) + { + if (HlslKnownTypes.IsKnownBufferType(member.MemberType)) + { + // Load the offset address into the resource buffers + il.Emit(OpCodes.Ldarg_1); + if (_ResourcesCount > 0) il.EmitAddOffset(_ResourcesCount); + _ResourcesCount++; + } + else if (HlslKnownTypes.IsKnownScalarType(member.MemberType) || HlslKnownTypes.IsKnownVectorType(member.MemberType)) + { + // Calculate the right offset with 16-bytes padding (HLSL constant buffer) + int size = member.MemberType == typeof(bool) ? sizeof(uint) : Marshal.SizeOf(member.MemberType); // bool is 4 bytes in HLSL + if (_VariablesByteSize % 16 > 16 - size) _VariablesByteSize += 16 - _VariablesByteSize % 16; + + // Load the target address into the variables buffer + il.Emit(OpCodes.Ldarg_2); + il.EmitAddOffset(_VariablesByteSize); + _VariablesByteSize += size; + } + else throw new InvalidOperationException($"Invalid captured member of type {member.MemberType}"); + + /* Load the current member accordingly. + * When this method returns, the value of the current + * member will be at the top of the execution stack */ + LoadMember(member); + + il.EmitStoreToAddress(member.MemberType); + } + + il.Emit(OpCodes.Ret); + }); + } + } +} diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs new file mode 100644 index 00000000..ad0a7141 --- /dev/null +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader{T}.cs @@ -0,0 +1,332 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using System.Linq; +using System.Reflection; +using System.Text.RegularExpressions; +using ComputeSharp.Graphics.Extensions; +using ComputeSharp.Shaders.Mappings; +using ComputeSharp.Shaders.Renderer.Models.Fields; +using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract; +using ComputeSharp.Shaders.Renderer.Models.Functions; +using ComputeSharp.Shaders.Translation.Enums; +using ComputeSharp.Shaders.Translation.Models; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Vortice.Direct3D12; +using ParameterInfo = ComputeSharp.Shaders.Renderer.Models.Functions.ParameterInfo; + +#pragma warning disable CS8618 // Non-nullable field is uninitialized + +namespace ComputeSharp.Shaders.Translation +{ + /// + /// A responsible for loading and processing shaders of a given type + /// + /// The type of compute shader currently in use + internal sealed partial class ShaderLoader + where T : struct, IComputeShader + { + /// + /// The current (boxed) shader being loaded + /// + /// + /// The overhead for the boxing can be ignored here since this will + /// only be done once per shader type/variables combination + /// + private readonly object Shader; + + /// + /// Creates a new with the specified parameters + /// + /// The instance to use to build the shader + private ShaderLoader(T shader) + { + Shader = shader; + } + + /// + /// The number of constant buffers to define in the shader + /// + private int _ConstantBuffersCount; + + /// + /// The number of readonly buffers to define in the shader + /// + private int _ReadOnlyBuffersCount; + + /// + /// The number of read write buffers to define in the shader + /// + private int _ReadWriteBuffersCount; + + /// + /// The of items that are required to load the captured values + /// + private readonly List DescriptorRanges = new List(); + + private RootParameter1[]? _RootParameters; + + /// + /// Gets the array for the current shader + /// + public RootParameter1[] RootParameters => _RootParameters ??= DescriptorRanges.Select(range => new RootParameter1(new RootDescriptorTable1(range), ShaderVisibility.All)).ToArray(); + + private readonly List _BuffersList = new List(); + + /// + /// Gets the collection of items for the shader fields + /// + public IReadOnlyList BuffersList => _BuffersList; + + private readonly List _FieldsList = new List(); + + /// + /// Gets the collection of items for the shader fields + /// + public IReadOnlyList FieldsList => _FieldsList; + + /// + /// Gets the name of the variable used as input for the shader method + /// + public string ThreadsIdsVariableName { get; private set; } + + /// + /// Gets the generated source code for the method in the current shader + /// + public string MethodBody { get; private set; } + + private readonly List _FunctionsList = new List(); + + /// + /// Gets the collection of items for the shader + /// + public IReadOnlyList FunctionsList => _FunctionsList; + + private readonly List _LocalFunctionsList = new List(); + + /// + /// Gets the collection of items for the shader + /// + public IReadOnlyList LocalFunctionsList => _LocalFunctionsList; + + /// + /// Loads and processes an input shadeer + /// + /// The instance to use to build the shader + /// A new instance representing the input shader + [Pure] + public static ShaderLoader Load(in T shader) + { + ShaderLoader @this = new ShaderLoader(shader); + + @this.LoadFieldsInfo(); + @this.LoadMethodSource(); + @this.BuildDispatchDataLoader(); + + return @this; + } + + /// + /// Loads the fields info for the current shader being loaded + /// + private void LoadFieldsInfo() + { + IReadOnlyList shaderFields = typeof(T).GetFields().ToArray(); + + if (shaderFields.Count == 0) throw new InvalidOperationException("Empty shader body"); + + // Descriptor for the buffer for captured scalar/vector variables + DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.ConstantBufferView, 1, _ConstantBuffersCount++)); + + // Inspect the captured fields + foreach (FieldInfo fieldInfo in shaderFields) + { + LoadFieldInfo(fieldInfo); + } + } + + /// + /// Loads a specified and adds it to the shader model + /// + /// The target to load + /// The optional explicit name to use for the field + /// The list of parent fields to reach the current from a given + private void LoadFieldInfo(ReadableMember memberInfo, string? name = null, IReadOnlyList? parents = null) + { + Type fieldType = memberInfo.MemberType; + string fieldName = HlslKnownKeywords.GetMappedName(name ?? memberInfo.Name); + + // Constant buffer + if (HlslKnownTypes.IsConstantBufferType(fieldType)) + { + DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.ConstantBufferView, 1, _ConstantBuffersCount)); + + // Track the buffer field + memberInfo.Parents = parents; + _CapturedMembers.Add(memberInfo); + + string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]); + _BuffersList.Add(new ConstantBufferFieldInfo(fieldType, typeName, fieldName, _ConstantBuffersCount++)); + } + else if (HlslKnownTypes.IsReadOnlyBufferType(fieldType)) + { + // Root parameter for a readonly buffer + DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.ShaderResourceView, 1, _ReadOnlyBuffersCount)); + + // Track the buffer field + memberInfo.Parents = parents; + _CapturedMembers.Add(memberInfo); + + string typeName = HlslKnownTypes.GetMappedName(fieldType); + _BuffersList.Add(new ReadOnlyBufferFieldInfo(fieldType, typeName, fieldName, _ReadOnlyBuffersCount++)); + } + else if (HlslKnownTypes.IsReadWriteBufferType(fieldType)) + { + // Root parameter for a read write buffer + DescriptorRanges.Add(new DescriptorRange1(DescriptorRangeType.UnorderedAccessView, 1, _ReadWriteBuffersCount)); + + // Track the buffer field + memberInfo.Parents = parents; + _CapturedMembers.Add(memberInfo); + + string typeName = HlslKnownTypes.GetMappedName(fieldType); + _BuffersList.Add(new ReadWriteBufferFieldInfo(fieldType, typeName, fieldName, _ReadWriteBuffersCount++)); + } + else if (HlslKnownTypes.IsKnownScalarType(fieldType) || HlslKnownTypes.IsKnownVectorType(fieldType)) + { + // Register the captured field + memberInfo.Parents = parents; + _CapturedMembers.Add(memberInfo); + + string typeName = HlslKnownTypes.GetMappedName(fieldType); + _FieldsList.Add(new CapturedFieldInfo(fieldType, typeName, fieldName)); + } + else if (fieldType.IsClass && fieldName.StartsWith("CS$<>")) + { + // Captured scope, update the parents list + List updatedParents = parents?.ToList() ?? new List(); + updatedParents.Add(memberInfo); + + // Recurse on the new compiler generated class + IReadOnlyList fields = fieldType.GetFields().ToArray(); + foreach (FieldInfo fieldInfo in fields) + { + LoadFieldInfo(fieldInfo, null, updatedParents); + } + } + else if (fieldType.IsDelegate() && + memberInfo.GetValue(Shader) is Delegate func && + (func.Method.IsStatic || func.Method.DeclaringType.IsStatelessDelegateContainer()) && + (HlslKnownTypes.IsKnownScalarType(func.Method.ReturnType) || HlslKnownTypes.IsKnownVectorType(func.Method.ReturnType)) && + fieldType.GenericTypeArguments.All(type => HlslKnownTypes.IsKnownScalarType(type) || + HlslKnownTypes.IsKnownVectorType(type))) + { + // Captured static delegates with a return type + LoadStaticMethodSource(fieldName, func.Method); + } + else throw new ArgumentException($"Invalid captured variable of type {fieldType} with name \"{memberInfo.Name}\""); + } + + /// + /// Loads the entry method for the current shader being loaded + /// + private void LoadMethodSource() + { + // Decompile the shader method + MethodInfo methodInfo = typeof(T).GetMethod(nameof(IComputeShader.Execute)); + MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Closure, out MethodDeclarationSyntax root, out SemanticModel semanticModel); + + // Rewrite the shader method (eg. to fix the type declarations) + ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, typeof(T)); + root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root); + + // Extract the implicit local functions + var locals = root.DescendantNodes().OfType().ToArray(); + root = root.RemoveNodes(locals, SyntaxRemoveOptions.KeepNoTrivia); + 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) + { + LoadFieldInfo(member.Value, member.Key); + } + + // Register the captured static methods + foreach (var method in syntaxRewriter.StaticMethods) + { + LoadStaticMethodSource(method.Key, method.Value); + } + + // Get the thread ids identifier name and shader method body + ThreadsIdsVariableName = root.ParameterList.Parameters.First().Identifier.Text; + MethodBody = root.Body.ToFullString(); + + // Additional preprocessing + MethodBody = Regex.Replace(MethodBody, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value); + MethodBody = MethodBody.TrimEnd('\n', '\r', ' '); + MethodBody = HlslKnownKeywords.GetMappedText(MethodBody); + } + + /// + /// Loads additional static methods used by the shader + /// + /// The HLSL name of the new method to load + /// The instance for the method to load + private void LoadStaticMethodSource(string name, MethodInfo methodInfo) + { + // Decompile the target method + MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Static, out MethodDeclarationSyntax root, out SemanticModel semanticModel); + + // Rewrite the method + ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, methodInfo.DeclaringType); + root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root); + + // Register the captured static members + foreach (var member in syntaxRewriter.StaticMembers) + { + LoadFieldInfo(member.Value, member.Key); + } + + // Register the captured static methods + foreach (var method in syntaxRewriter.StaticMethods) + { + LoadStaticMethodSource(method.Key, method.Value); + } + + // Get the function parameters + IReadOnlyList parameters = ( + from parameter in root.ParameterList.Parameters.Select((p, i) => (Node: p, Index: i)) + let modifiers = parameter.Node.Modifiers + let type = parameter.Node.Type.ToFullString() + let parameterName = parameter.Node.Identifier.ToFullString() + let last = parameter.Index == root.ParameterList.Parameters.Count - 1 + select new ParameterInfo(modifiers, type, parameterName, last)).ToArray(); + + // Get the function body + string body = root.Body.ToFullString(); + body = Regex.Replace(body, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value); + body = body.TrimEnd('\n', '\r', ' '); + body = HlslKnownKeywords.GetMappedText(body); + + // Get the final function info instance + FunctionInfo functionInfo = new FunctionInfo( + methodInfo.ReturnType, + $"{methodInfo.DeclaringType.FullName}{Type.Delimiter}{methodInfo.Name}", + string.Join(", ", methodInfo.GetParameters().Select(p => $"{p.ParameterType.ToFriendlyString()} {p.Name}")), + root.ReturnType.ToString(), + name, + parameters, + body); + + _FunctionsList.Add(functionInfo); + } + } +}