diff --git a/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs b/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs deleted file mode 100644 index 23cd38a7..00000000 --- a/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Numerics; -using System.Runtime.CompilerServices; -using ComputeSharp.Graphics.Buffers.Abstract; - -namespace ComputeSharp.Graphics.Buffers.Extensions -{ - /// - /// A with extension methods for the type to allocate generic resources - /// - internal static class GraphicsResourceExtensions - { - /// - /// Allocates a new constant buffer with the specified generic values - /// - /// The instance to use to allocate the buffer - /// The input sequence to copy to the allocated buffer - /// A constant instance (as a ) with the input data - [Pure] - public static GraphicsResource AllocateConstantBufferFromReflectedValues(this GraphicsDevice device, IReadOnlyList data) - { - Span temporarySpan = stackalloc Vector4[data.Count]; - ref byte r0 = ref Unsafe.As(ref temporarySpan.GetPinnableReference()); - int offset = 0; - - // Local method to write a value in the temporary buffer - void WriteValue(T value, ref byte target) where T : unmanaged - { - int size = Unsafe.SizeOf(); - if (offset % 16 > 16 - size) offset += 16 - offset % 16; - Unsafe.As(ref Unsafe.Add(ref target, offset)) = value; - offset += size; - } - - // Iterate on the input values and write them with the proper padding - for (int j = 0; j < data.Count; j++) - { - switch (data[j]) - { - case bool b: - uint ub = default; - Unsafe.As(ref ub) = b; - WriteValue(ub, ref r0); - break; - case Bool2 b2: WriteValue(b2, ref r0); break; - case Bool3 b3: WriteValue(b3, ref r0); break; - case Bool4 b4: WriteValue(b4, ref r0); break; - case int i: WriteValue(i, ref r0); break; - case Int2 i2: WriteValue(i2, ref r0); break; - case Int3 i3: WriteValue(i3, ref r0); break; - case Int4 i4: WriteValue(i4, ref r0); break; - case uint u: WriteValue(u, ref r0); break; - case UInt2 ui2: WriteValue(ui2, ref r0); break; - case UInt3 ui3: WriteValue(ui3, ref r0); break; - case UInt4 ui4: WriteValue(ui4, ref r0); break; - case float f: WriteValue(f, ref r0); break; - case Float2 f2: WriteValue(f2, ref r0); break; - case Float3 f3: WriteValue(f3, ref r0); break; - case Float4 f4: WriteValue(f4, ref r0); break; - case Vector2 v2: WriteValue(v2, ref r0); break; - case Vector3 v3: WriteValue(v3, ref r0); break; - case Vector4 v4: WriteValue(v4, ref r0); break; - case double d: WriteValue(d, ref r0); break; - case Double2 d2: WriteValue(d2, ref r0); break; - case Double3 d3: WriteValue(d3, ref r0); break; - case Double4 d4: WriteValue(d4, ref r0); break; - default: throw new InvalidOperationException($"Invalid item of type {data[j].GetType()}"); - } - } - - // Create the array to return - ConstantBuffer buffer = new ConstantBuffer(device, data.Count); - buffer.SetData(temporarySpan); - - return buffer; - } - } -} diff --git a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs new file mode 100644 index 00000000..acd78cf8 --- /dev/null +++ b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs @@ -0,0 +1,159 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace System.Reflection.Emit +{ + /// + /// A that provides extension methods for the type + /// + internal static class ILGeneratorExtensions + { + /// + /// Puts the appropriate or instruction to unbox/cast a value onto the stream of instructions + /// + /// The input instance to use to emit instructions + /// The type of value to convert + public static void EmitCastOrUnbox(this ILGenerator il, Type type) + { + il.Emit(type.IsValueType ? OpCodes.Unbox : OpCodes.Castclass, type); + } + + /// + /// Puts the appropriate instruction to read a local variable onto the stream of instructions + /// + /// The input instance to use to emit instructions + /// The index of the local variable to load + public static void EmitLoadLocal(this ILGenerator il, int index) + { + if (index <= 3) + { + il.Emit(index switch + { + 0 => OpCodes.Ldloc_0, + 1 => OpCodes.Ldloc_1, + 2 => OpCodes.Ldloc_2, + 3 => OpCodes.Ldloc_3, + _ => throw new InvalidOperationException($"Invalid local variable index [{index}]") + }); + } + else if (index <= 255) il.Emit(OpCodes.Ldloc_S, (byte)index); + else if (index <= 65534) il.Emit(OpCodes.Ldloc, (short)index); + else throw new ArgumentOutOfRangeException($"Invalid local index {index}"); + } + + /// + /// Puts the appropriate instruction to write a local variable onto the stream of instructions + /// + /// The input instance to use to emit instructions + /// The index of the local variable to store + public static void EmitStoreLocal(this ILGenerator il, int index) + { + if (index <= 3) + { + il.Emit(index switch + { + 0 => OpCodes.Stloc_0, + 1 => OpCodes.Stloc_1, + 2 => OpCodes.Stloc_2, + 3 => OpCodes.Stloc_3, + _ => throw new InvalidOperationException($"Invalid local variable index [{index}]") + }); + } + else if (index <= 255) il.Emit(OpCodes.Stloc_S, (byte)index); + else if (index <= 65534) il.Emit(OpCodes.Stloc, (short)index); + else throw new ArgumentOutOfRangeException($"Invalid local index {index}"); + } + + /// + /// Puts the appropriate , , or instruction to read a member onte the stream of instructions + /// + /// The input instance to use to emit instructions + /// The member to read + public static void EmitReadMember(this ILGenerator il, MemberInfo member) + { + switch (member) + { + case FieldInfo field: + il.Emit(field.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, field); + break; + case PropertyInfo property when property.CanRead: + il.EmitCall(property.GetMethod.IsStatic ? OpCodes.Call : OpCodes.Callvirt, property.GetMethod, null); + break; + default: throw new ArgumentException($"The input {member.GetType()} instance can't be read"); + } + } + + /// + /// Puts the appropriate , and instructions to advance a reference onto the stream of instructions + /// + /// The type of reference at the top of the stack + /// The input instance to use to emit instructions + /// The offset to use to advance the current reference on top of the execution stack + public static void EmitAddOffset(this ILGenerator il, int offset) => il.EmitAddOffset(Unsafe.SizeOf() * offset); + + /// + /// Puts the appropriate , and instructions to advance a reference onto the stream of instructions + /// + /// The input instance to use to emit instructions + /// The offset in bytes to use to advance the current reference on top of the execution stack + public static void EmitAddOffset(this ILGenerator il, int offset) + { + // Push the offset to the stack + if (offset < 128) il.Emit(OpCodes.Ldc_I4, offset); + else if (offset < 0) il.Emit(OpCodes.Ldc_I4_S, (sbyte)offset); + else if (offset <= 8) + { + il.Emit(offset switch + { + 0 => OpCodes.Ldc_I4_0, + 1 => OpCodes.Ldc_I4_1, + 2 => OpCodes.Ldc_I4_2, + 3 => OpCodes.Ldc_I4_3, + 4 => OpCodes.Ldc_I4_4, + 5 => OpCodes.Ldc_I4_5, + 6 => OpCodes.Ldc_I4_6, + 7 => OpCodes.Ldc_I4_7, + 8 => OpCodes.Ldc_I4_8, + _ => throw new InvalidOperationException($"Invalid offset value [{offset}]") + }); + } + else if (offset <= 127) il.Emit(OpCodes.Ldc_I4_S, (byte)offset); + else il.Emit(OpCodes.Ldc_I4, offset); + + // Converts the offset to native int and adds to the address + il.Emit(OpCodes.Conv_I); + il.Emit(OpCodes.Add); + } + + /// + /// Puts the appropriate or instruction to write to a reference onto the stream of instructions + /// + /// The input instance to use to emit instructions + /// The type of value being written to the current reference on top of the execution stack + public static void EmitStoreToAddress(this ILGenerator il, Type type) + { + if (type.IsValueType) + { + // Pick the optimal opcode to set a value type + OpCode opcode = Marshal.SizeOf(type) switch + { + // Use the faster op codes for sizes <= 8 + 1 when type == typeof(bool) || type == typeof(byte) || type == typeof(sbyte) => OpCodes.Stind_I1, + 2 when type == typeof(short) || type == typeof(ushort) => OpCodes.Stind_I2, + 4 when type == typeof(float) => OpCodes.Stind_R4, + 4 when type == typeof(int) || type == typeof(uint) => OpCodes.Stind_I4, + 8 when type == typeof(double) => OpCodes.Stind_R8, + 8 when type == typeof(long) || type == typeof(ulong) => OpCodes.Stind_I8, + + // Default to stobj for all other value types + _ => OpCodes.Stobj + }; + + // Also pass the type token if stobj is used + if (opcode == OpCodes.Stobj) il.Emit(opcode, type); + else il.Emit(opcode); + } + else il.Emit(OpCodes.Stind_Ref); + } + } +} diff --git a/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs b/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs index 65bd4918..de6c9a36 100644 --- a/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs +++ b/src/ComputeSharp.Shaders/Mappings/HlslKnownTypes.cs @@ -93,6 +93,16 @@ namespace ComputeSharp.Shaders.Mappings type == typeof(Vector3) || type == typeof(Vector4); + /// + /// Checks whether or not the input type is a known buffer type + /// + /// The input instance to check + /// A indicating whether the input is in fact a known buffer type + [Pure] + public static bool IsKnownBufferType(Type type) => IsConstantBufferType(type) || + IsReadOnlyBufferType(type) || + IsReadWriteBufferType(type); + /// /// Checks whether or not the input type is a value /// diff --git a/src/ComputeSharp.Shaders/ShaderRunner.cs b/src/ComputeSharp.Shaders/ShaderRunner.cs index 944aee43..090a474e 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner.cs @@ -1,9 +1,7 @@ using System; using System.Collections.Generic; -using System.Linq; using ComputeSharp.Graphics; using ComputeSharp.Graphics.Buffers.Abstract; -using ComputeSharp.Graphics.Buffers.Extensions; using ComputeSharp.Shaders.Renderer; using ComputeSharp.Shaders.Renderer.Models; using ComputeSharp.Shaders.Translation; @@ -103,15 +101,19 @@ namespace ComputeSharp.Shaders using CommandList commandList = new CommandList(device, CommandListType.Compute); commandList.SetPipelineState(pipelineState); + // Extract the dispatch data for the shader invocation + using DispatchData dispatchData = shaderData.Loader.GetDispatchData(action, x, y, z); + // Load the captured buffers - foreach (var buffer in shaderData.Loader.GetBuffers(action)) + Span resources = dispatchData.Resources; + for (int i = 0; i < resources.Length; i++) { - commandList.SetComputeRootDescriptorTable(buffer.Index, buffer.Resource); + commandList.SetComputeRootDescriptorTable(i + 1, resources[i]); } // Initialize the loop targets - IReadOnlyList variables = new object[] { (uint)x, (uint)y, (uint)z }.Concat(shaderData.Loader.GetVariables(action)).ToArray(); - using GraphicsResource variablesBuffer = device.AllocateConstantBufferFromReflectedValues(variables); + Span variables = dispatchData.Variables; + using GraphicsResource variablesBuffer = device.AllocateConstantBuffer(variables); commandList.SetComputeRootDescriptorTable(0, variablesBuffer); // Calculate the dispatch values diff --git a/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs b/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs new file mode 100644 index 00000000..e1d579f1 --- /dev/null +++ b/src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs @@ -0,0 +1,82 @@ +using System; +using System.Buffers; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using ComputeSharp.Graphics.Buffers.Abstract; + +namespace ComputeSharp.Shaders.Translation.Models +{ + /// + /// A that contains all the captured data to dispatch a shader + /// + internal readonly ref struct DispatchData + { + /// + /// The array with the captured buffers + /// + private readonly GraphicsResource[] ResourcesArray; + + /// + /// The number of instances in + /// + private readonly int ResourcesCount; + + /// + /// The array with all the captured variables, with proper padding + /// + private readonly byte[] VariablesArray; + + /// + /// The actual size in bytes to use from + /// + private readonly int VariablesByteSize; + + /// + /// Creates a new instance with the specified parameters + /// + /// The array with the captured buffers + /// The number of instances in + /// The array with all the captured variables, with proper padding + /// The actual size in bytes to use from + public DispatchData(GraphicsResource[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesByteSize) + { + ResourcesArray = resourcesArray; + VariablesArray = variablesArray; + ResourcesCount = resourcesCount; + VariablesByteSize = variablesByteSize; + } + + /// + /// Gets a with all the captured buffers + /// + public Span Resources + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ResourcesArray.AsSpan(0, ResourcesCount); + } + + /// + /// Gets a with the padded data representing all the captured variables + /// + public Span Variables + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + ref Int4 r = ref Unsafe.As(ref VariablesArray[0]); + bool mod = (VariablesByteSize & 15) > 0; + int length = VariablesByteSize / 4 + Unsafe.As(ref mod); + return MemoryMarshal.CreateSpan(ref r, length); + } + } + + /// + /// Implements the method and returns the rented buffers + /// + public void Dispose() + { + ArrayPool.Shared.Return(ResourcesArray); + ArrayPool.Shared.Return(VariablesArray); + } + } +} diff --git a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs deleted file mode 100644 index db9df14d..00000000 --- a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs +++ /dev/null @@ -1,113 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.Contracts; -using System.Linq; -using System.Reflection.Emit; -using System.Runtime.CompilerServices; - -namespace ComputeSharp.Shaders.Translation.Models -{ - internal sealed partial class ReadableMember - { - /// - /// The mapping of members to getter delegates - /// - private static readonly Dictionary GettersMapping = new Dictionary(); - - /// - /// The local instance, if already loaded - /// - private Getter? _Getter; - - /// - /// Ensures the dynamic accessor for the current instance is loaded and ready to use - /// - public void PreloadAccessor() - { - if (_Getter == null) - { - /* If the local delegate is available, use it and save the dictionary - * access entirely. If it's not, try to get the delegate from the dictionary - * first. This can save unnecessary overhead if a delegate for the same member has - * already been built, eg. if it belongs to a captured field that is used by two different - * shaders in the same closure. Once the getter is built, cache it and invoke it */ - if (GettersMapping.TryGetValue(Id, out Getter getter)) _Getter = getter; - else - { - _Getter = getter = BuildDynamicGetter(); - GettersMapping.Add(Id, getter); - } - } - } - - /// - /// Returns the value of the wrapped member for the current instance - /// - /// The target instance to use to read the value from - /// This method doesn't ensure that the accessor is available - /// The dynamic accessor is not available - [Pure] - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public object DangerousGetValue(object? instance) => _Getter!(instance); - - /// - /// Returns the value of the wrapped member for the current instance - /// - /// The target instance to use to read the value from - [Pure] - public object GetValue(object? instance) - { - PreloadAccessor(); - return _Getter!(instance); - } - - /// - /// A that represents a getter for a specific member - /// - /// The source object to get the member from - /// The value of the member, upcast to - private delegate object Getter(object? obj); - - /// - /// Gets or sets the list of parent members to access the current one from the root instance - /// - public IEnumerable? Parents { get; set; } - - /// - /// Builds a dynamic IL method to retrieve the value of the current member - /// - [Pure] - private Getter BuildDynamicGetter() - { - return DynamicMethod.New(il => - { - // Info for hierarchical access - ReadableMember[] hierarchy = (Parents ?? Array.Empty()).Concat(new[] { this }).ToArray(); - - // Load the argument (the object instance) and cast it to the right type, if needed - if (!IsStatic) - { - il.Emit(OpCodes.Ldarg_0); - - Type unboxType = hierarchy[0].DeclaringType; - il.Emit(unboxType.IsValueType ? OpCodes.Unbox : OpCodes.Castclass, unboxType); - } - - // Unroll the member access - foreach (ReadableMember member in hierarchy) - { - // Get the member value with the appropriate method - if (member.Property != null) il.EmitCall(member.IsStatic ? OpCodes.Call : OpCodes.Callvirt, member.Property.GetMethod, null); - else if (member.Field != null) il.Emit(member.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, member.Field); - else throw new InvalidOperationException("Field and property can't both be null at the same time"); - } - - // Box the value, if needed - if (MemberType.IsValueType) il.Emit(OpCodes.Box, MemberType); - - // Return the member value from the top of the evaluation stack - il.Emit(OpCodes.Ret); - }); - } - } -} diff --git a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs index 9883fd52..d20dd74e 100644 --- a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs +++ b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs @@ -1,4 +1,6 @@ using System; +using System.Collections.Generic; +using System.Diagnostics.Contracts; using System.Reflection; namespace ComputeSharp.Shaders.Translation.Models @@ -6,22 +8,12 @@ namespace ComputeSharp.Shaders.Translation.Models /// /// A that wraps a readable member of another and provides access to it /// - internal sealed partial class ReadableMember + internal sealed class ReadableMember { /// - /// The id of the current member + /// The object wrapped by the current instance /// - private readonly string Id; - - /// - /// The object wrapped by the current instance, if present - /// - private readonly FieldInfo? Field; - - /// - /// The object wrapped by the current instance, if present - /// - private readonly PropertyInfo? Property; + private readonly MemberInfo Member; /// /// Creates a new instance with the given parameters @@ -30,22 +22,22 @@ namespace ComputeSharp.Shaders.Translation.Models private ReadableMember(MemberInfo memberInfo) { // General properties + Member = memberInfo; Name = memberInfo.Name; - Id = $"{memberInfo.DeclaringType.FullName}{Type.Delimiter}{Name}"; DeclaringType = memberInfo.DeclaringType; // Type specific properties if (memberInfo is FieldInfo fieldInfo) { - Field = fieldInfo; - IsStatic = Field.IsStatic; - MemberType = Field.FieldType; + Member = fieldInfo; + IsStatic = fieldInfo.IsStatic; + MemberType = fieldInfo.FieldType; } else if (memberInfo is PropertyInfo propertyInfo) { - Property = propertyInfo; - IsStatic = Property.GetMethod.IsStatic; - MemberType = Property.PropertyType; + Member = propertyInfo; + IsStatic = propertyInfo.GetMethod.IsStatic; + MemberType = propertyInfo.PropertyType; } else throw new InvalidOperationException("Field and property can't both be null at the same time"); } @@ -70,6 +62,26 @@ namespace ComputeSharp.Shaders.Translation.Models /// public Type MemberType { get; } + /// + /// Gets or sets the list of parent members to access the current one from the root instance + /// + public IReadOnlyList? Parents { get; set; } + + /// + /// Returns the value of the wrapped member for the current instance + /// + /// The target instance to use to read the value from + [Pure] + public object GetValue(object? instance) + { + return Member switch + { + FieldInfo field => field.GetValue(instance), + PropertyInfo property => property.GetValue(instance), + _ => throw new InvalidOperationException("Field and property can't both be null at the same time") + }; + } + /// /// Converts a object into a instance /// @@ -81,5 +93,23 @@ namespace ComputeSharp.Shaders.Translation.Models /// /// The input object to wrap public static implicit operator ReadableMember(PropertyInfo property) => new ReadableMember(property); + + /// + /// Converts a object into a instance + /// + /// The input object to unwrap + public static implicit operator MemberInfo(ReadableMember member) => member.Member; + + /// + /// Converts a object into a instance + /// + /// The input object to unwrap + public static implicit operator FieldInfo(ReadableMember member) => (FieldInfo)member.Member; + + /// + /// Converts a object into a instance + /// + /// The input object to unwrap + public static implicit operator PropertyInfo(ReadableMember member) => (PropertyInfo)member.Member; } } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs index 9a361ab4..93c32d04 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs @@ -98,14 +98,14 @@ namespace ComputeSharp.Shaders.Translation // hash = hash * 17 + field.Method.GetHashCode(); il.Emit(OpCodes.Ldarg_0); - il.Emit(OpCodes.Ldc_I4, 17); + il.Emit(OpCodes.Ldc_I4_S, (byte)17); il.Emit(OpCodes.Mul); il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Ldfld, fieldInfo); il.EmitCall(OpCodes.Callvirt, getMethodInfo, null); il.EmitCall(OpCodes.Callvirt, getHashCodeInfo, null); il.Emit(OpCodes.Add); - il.Emit(OpCodes.Starg_S, 0); + il.Emit(OpCodes.Starg_S, (byte)0); il.MarkLabel(label); } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs new file mode 100644 index 00000000..0669ae18 --- /dev/null +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs @@ -0,0 +1,176 @@ +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) + { + /* Create the data loader instance, if not available already. + * This will also initialize the other local fields in the shader + * loader class, which are used to rent the buffers used to store + * the captured resources and variables. This is why this call + * has to be the first one in this method, it must NOT be moved */ + DispatchDataLoader loader = _DispatchDataLoader ??= BuildDispatchDataLoader(); + + // 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 + loader(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 + /// + [Pure] + private DispatchDataLoader 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 + return 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 + if (i == 0) il.EmitLoadLocal(0); + for (; i < member.Parents.Count; i++) + { + il.Emit(OpCodes.Ldfld, member.Parents[i]); + il.EmitStoreLocal(map[member.Parents[i]]); + il.EmitLoadLocal(map[member.Parents[i]]); + } + } + } + + il.EmitReadMember(member); + } + + // Declare the local variables + il.DeclareLocal(ShaderType); + 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(ShaderType); + 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.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index d9d1f094..dfc6a2ae 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -4,7 +4,6 @@ using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; -using ComputeSharp.Graphics.Buffers.Abstract; using ComputeSharp.Graphics.Extensions; using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Renderer.Models.Fields; @@ -24,7 +23,7 @@ namespace ComputeSharp.Shaders.Translation /// /// A responsible for loading and processing instances /// - internal sealed class ShaderLoader + internal sealed partial class ShaderLoader { /// /// The that represents the shader to load @@ -73,41 +72,6 @@ namespace ComputeSharp.Shaders.Translation /// public RootParameter1[] RootParameters => _RootParameters ??= DescriptorRanges.Select(range => new RootParameter1(new RootDescriptorTable1(range), ShaderVisibility.All)).ToArray(); - /// - /// The of instances mapping the captured buffers in the current shader - /// - private readonly List _BufferMembers = new List(); - - /// - /// Gets the ordered collection of buffers used as fields in the current shader - /// - /// The to use to build the shader - public IEnumerable<(int Index, GraphicsResource Resource)> GetBuffers(Action action) - { - int index = 1; - foreach (var item in _BufferMembers) - { - yield return (index++, (GraphicsResource)item.DangerousGetValue(action.Target)); - } - } - - /// - /// The of instances mapping the captured scalar/vector variables in the current shader - /// - private readonly List _VariableMembers = new List(); - - /// - /// Gets the collection of values of the captured fields for the current shader - /// - /// The to use to build the shader - public IEnumerable GetVariables(Action action) - { - foreach (var item in _VariableMembers) - { - yield return item.DangerousGetValue(action.Target); - } - } - private readonly List _BuffersList = new List(); /// @@ -198,7 +162,7 @@ namespace ComputeSharp.Shaders.Translation // Track the buffer field memberInfo.Parents = parents; - _BufferMembers.Add(memberInfo); + _CapturedMembers.Add(memberInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType.GenericTypeArguments[0]); _BuffersList.Add(new ConstantBufferFieldInfo(fieldType, typeName, fieldName, _ConstantBuffersCount++)); @@ -210,7 +174,7 @@ namespace ComputeSharp.Shaders.Translation // Track the buffer field memberInfo.Parents = parents; - _BufferMembers.Add(memberInfo); + _CapturedMembers.Add(memberInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType); _BuffersList.Add(new ReadOnlyBufferFieldInfo(fieldType, typeName, fieldName, _ReadOnlyBuffersCount++)); @@ -222,7 +186,7 @@ namespace ComputeSharp.Shaders.Translation // Track the buffer field memberInfo.Parents = parents; - _BufferMembers.Add(memberInfo); + _CapturedMembers.Add(memberInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType); _BuffersList.Add(new ReadWriteBufferFieldInfo(fieldType, typeName, fieldName, _ReadWriteBuffersCount++)); @@ -231,7 +195,7 @@ namespace ComputeSharp.Shaders.Translation { // Register the captured field memberInfo.Parents = parents; - _VariableMembers.Add(memberInfo); + _CapturedMembers.Add(memberInfo); string typeName = HlslKnownTypes.GetMappedName(fieldType); _FieldsList.Add(new CapturedFieldInfo(fieldType, typeName, fieldName)); @@ -259,14 +223,6 @@ namespace ComputeSharp.Shaders.Translation // Captured static delegates with a return type LoadStaticMethodSource(fieldName, func.Method); } - - /* Build the dynamic IL accessor for the current member, if one is - * not available already. This is done during while the shader is - * being loaded and not just when needed because the internal cache - * system for the accessors is not thread safe. Preloading the accessor here - * leverages the external lock around the shader loading, ensuring - * that no race conditions occur when accessing the cached mapping */ - memberInfo.PreloadAccessor(); } /// diff --git a/tests/ComputeSharp.Tests.Internals/BufferTests.cs b/tests/ComputeSharp.Tests.Internals/BufferTests.cs deleted file mode 100644 index 0ef723d2..00000000 --- a/tests/ComputeSharp.Tests.Internals/BufferTests.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; -using System.Numerics; -using System.Runtime.CompilerServices; -using ComputeSharp.Graphics.Buffers.Extensions; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -namespace ComputeSharp.Tests.Internals -{ - [TestClass] - [TestCategory("Buffers")] - public class BufferTests - { - [TestMethod] - public void ConstantBufferGetSetFromGenericValues() - { - object[] values = { 7, 3.14, Vector2.UnitX, 3.14f, new Vector4(7.14f, 7.15f, 7.77f, 2.55f) }; - - using ConstantBuffer buffer = (ConstantBuffer)Gpu.Default.AllocateConstantBufferFromReflectedValues(values); - Vector4[] data = buffer.GetData(); - ref byte r0 = ref Unsafe.As(ref data[0]); - - int i = Unsafe.As(ref Unsafe.Add(ref r0, 0)); // 0 -> 3, sizeof(int) == 4 - double d = Unsafe.As(ref Unsafe.Add(ref r0, 4)); // 4 -> 11, sizeof(double) == 8 - Vector2 v2 = Unsafe.As(ref Unsafe.Add(ref r0, 16)); // 16 -> 23, sizeof(Vector2) == 8 - float f = Unsafe.As(ref Unsafe.Add(ref r0, 24)); // 24 -> 27, sizeof(float) == 4 - Vector4 v4 = Unsafe.As(ref Unsafe.Add(ref r0, 32)); // 32 -> 47, sizeof(Vector4) == 16 - - Assert.IsTrue((int)values[0] == i); - Assert.IsTrue(Math.Abs((double)values[1] - d) < 0.0001); - Assert.IsTrue((Vector2)values[2] == v2); - Assert.IsTrue(MathF.Abs((float)values[3] - f) < 0.0001); - Assert.IsTrue((Vector4)values[4] == v4); - } - } -}