From 533f07f10e18f51faaa4ef1e4aca67872686da25 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 18 Sep 2019 15:09:58 +0200 Subject: [PATCH 01/17] Added initial ILGeneratorExtensions class --- .../Extensions/ILGeneratorExtensions.cs | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs diff --git a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs new file mode 100644 index 00000000..57855ccb --- /dev/null +++ b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs @@ -0,0 +1,58 @@ +using System.Runtime.InteropServices; + +namespace System.Reflection.Emit +{ + /// + /// A that provides extension methods for the type + /// + internal static class ILGeneratorExtensions + { + /// + /// Puts the appropriate , and instructions to advance a reference onto the stream of instructions + /// + /// 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 EmitAddByteOffset(this ILGenerator il, int offset) + { + // Push the offset to the stack + if (offset > 8) il.Emit(OpCodes.Ldc_I4, offset); + else + { + il.Emit(offset switch + { + 1 => OpCodes.Ldc_I4_1, + 2 => OpCodes.Ldc_I4_2, + 4 => OpCodes.Ldc_I4_4, + 8 => OpCodes.Ldc_I4_8, + _ => throw new InvalidOperationException("Huh?") + }); + } + + // 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) + { + il.Emit(Marshal.SizeOf(type) switch + { + // Use the faster op codes for sizes <= 8 + 1 => OpCodes.Stind_I1, + 2 => OpCodes.Stind_I2, + 4 when type == typeof(float) => OpCodes.Stind_R4, + 4 => 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 + }); + } + } +} From a18baed6fe486c75e150cc52f459a74cc23aac3b Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 18 Sep 2019 15:29:09 +0200 Subject: [PATCH 02/17] Code refactoring --- .../Extensions/ILGeneratorExtensions.cs | 29 ++++++++++++++++++ .../Models/ReadableMember.GetValue.cs | 9 ++---- .../Translation/Models/ReadableMember.cs | 30 ++++++++++--------- 3 files changed, 47 insertions(+), 21 deletions(-) diff --git a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs index 57855ccb..af8e3dc9 100644 --- a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs +++ b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs @@ -7,6 +7,35 @@ namespace System.Reflection.Emit /// 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 , , 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 /// diff --git a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs index db9df14d..a3858ec0 100644 --- a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs +++ b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs @@ -88,18 +88,13 @@ namespace ComputeSharp.Shaders.Translation.Models if (!IsStatic) { il.Emit(OpCodes.Ldarg_0); - - Type unboxType = hierarchy[0].DeclaringType; - il.Emit(unboxType.IsValueType ? OpCodes.Unbox : OpCodes.Castclass, unboxType); + il.EmitCastOrUnbox(hierarchy[0].DeclaringType); } // 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"); + il.EmitReadMember(member); } // Box the value, if needed diff --git a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs index 9883fd52..a18e0d12 100644 --- a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs +++ b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs @@ -14,14 +14,9 @@ namespace ComputeSharp.Shaders.Translation.Models private readonly string Id; /// - /// The object wrapped by the current instance, if present + /// The object wrapped by the current instance /// - 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 +25,23 @@ namespace ComputeSharp.Shaders.Translation.Models private ReadableMember(MemberInfo memberInfo) { // General properties + Id = $"{memberInfo.DeclaringType.FullName}{Type.Delimiter}{memberInfo.Name}"; + 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"); } @@ -81,5 +77,11 @@ 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; } } From c58b63a25427366d3ca0f7f302352706a3b2e834 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 18 Sep 2019 20:28:49 +0200 Subject: [PATCH 03/17] Added IL extensions to load and store local variables --- .../Extensions/ILGeneratorExtensions.cs | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs index af8e3dc9..afedebb6 100644 --- a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs +++ b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs @@ -17,6 +17,52 @@ namespace System.Reflection.Emit 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("Huh?") + }); + } + 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("Huh?") + }); + } + 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 /// From 3cd3814df7a85b1e1f7b8967f39d7a4174d1e0ed Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 18 Sep 2019 22:06:28 +0200 Subject: [PATCH 04/17] Code refactoring to the ILGenerator extensions --- .../Extensions/ILGeneratorExtensions.cs | 39 ++++++++++++------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs index afedebb6..31f9094a 100644 --- a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs +++ b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs @@ -1,4 +1,5 @@ -using System.Runtime.InteropServices; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; namespace System.Reflection.Emit { @@ -85,9 +86,17 @@ namespace System.Reflection.Emit /// /// 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 EmitAddByteOffset(this ILGenerator il, int offset) + 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 > 8) il.Emit(OpCodes.Ldc_I4, offset); @@ -115,19 +124,23 @@ namespace System.Reflection.Emit /// 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) { - il.Emit(Marshal.SizeOf(type) switch + if (type.IsValueType) { - // Use the faster op codes for sizes <= 8 - 1 => OpCodes.Stind_I1, - 2 => OpCodes.Stind_I2, - 4 when type == typeof(float) => OpCodes.Stind_R4, - 4 => OpCodes.Stind_I4, - 8 when type == typeof(double) => OpCodes.Stind_R8, - 8 when type == typeof(long) || type == typeof(ulong) => OpCodes.Stind_I8, + il.Emit(Marshal.SizeOf(type) switch + { + // Use the faster op codes for sizes <= 8 + 1 => OpCodes.Stind_I1, + 2 => OpCodes.Stind_I2, + 4 when type == typeof(float) => OpCodes.Stind_R4, + 4 => 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 - }); + // Default to stobj for all other value types + _ => OpCodes.Stobj + }); + } + else il.Emit(OpCodes.Stind_Ref); } } } From ac6236fa751269a84071662ff8a539b414207f74 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 18 Sep 2019 22:06:56 +0200 Subject: [PATCH 05/17] Added initial draft version of new shader data loader --- .../Mappings/HlslKnownTypes.cs | 10 + .../Models/ReadableMember.GetValue.cs | 2 +- .../Translation/ShaderLoader.IL.cs | 196 ++++++++++++++++++ .../Translation/ShaderLoader.cs | 2 +- 4 files changed, 208 insertions(+), 2 deletions(-) create mode 100644 src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs 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/Translation/Models/ReadableMember.GetValue.cs b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs index a3858ec0..70e665c6 100644 --- a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs +++ b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs @@ -71,7 +71,7 @@ namespace ComputeSharp.Shaders.Translation.Models /// /// Gets or sets the list of parent members to access the current one from the root instance /// - public IEnumerable? Parents { get; set; } + public IReadOnlyList? Parents { get; set; } /// /// Builds a dynamic IL method to retrieve the value of the current member diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs new file mode 100644 index 00000000..297d8365 --- /dev/null +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs @@ -0,0 +1,196 @@ +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 + { + private int _ResourcesCount; + + private int _VariablesByteSize = 3 * sizeof(int); // X, Y and Z threads count + + /// + /// 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 MembersLoader(object obj, ref GraphicsResource r0, ref byte r1); + + // The cached loader method + private MembersLoader? _MembersLoader; + + [Pure] + public ShaderDispatchData GetDispatchData(Action action, int x, int y, int z) + { + if (_MembersLoader == null) + { + // 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 + _MembersLoader = 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].MemberType); + 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).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_0); + if (_ResourcesCount > 0) il.EmitAddOffset(_ResourcesCount); + _ResourcesCount++; + + /* 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); + } + else if (HlslKnownTypes.IsKnownScalarType(member.MemberType) || + HlslKnownTypes.IsKnownVectorType(member.MemberType)) + { + // Calculate the right offset with 16-bytes padding (HLSL constant buffer) + int size = Marshal.SizeOf(member.MemberType); + if (_VariablesByteSize % 16 > 16 - size) _VariablesByteSize += 16 - _VariablesByteSize % 16; + + // Load the target address into the variables buffer + il.Emit(OpCodes.Ldarg_1); + il.EmitAddOffset(_VariablesByteSize); + + // Load the variable and store it in the loaded address + LoadMember(member); + il.EmitStoreToAddress(member.MemberType); + } + else throw new InvalidOperationException($"Invalid captured member of type {member.MemberType}"); + } + + il.Emit(OpCodes.Ret); + }); + } + + // 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 + _MembersLoader(action.Target, ref r0, ref r1); + + return new ShaderDispatchData(resources, _ResourcesCount, variables, _VariablesByteSize); + } + + public readonly ref struct ShaderDispatchData + { + private readonly GraphicsResource[] ResourcesArray; + + private readonly byte[] VariablesArray; + + private readonly int ResourcesCount; + + private readonly int VariablesInt4Size; + + public Span Resources + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get => ResourcesArray.AsSpan(0, ResourcesCount); + } + + public Span Variables + { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + get + { + ref Int4 r = ref Unsafe.As(ref VariablesArray[0]); + return MemoryMarshal.CreateSpan(ref r, VariablesInt4Size); + } + } + + public ShaderDispatchData(GraphicsResource[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesInt4Size) + { + ResourcesArray = resourcesArray; + VariablesArray = variablesArray; + ResourcesCount = resourcesCount; + VariablesInt4Size = variablesInt4Size; + } + + public void Dispose() + { + ArrayPool.Shared.Return(ResourcesArray); + ArrayPool.Shared.Return(VariablesArray); + } + } + } +} diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index d9d1f094..c4cbd824 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -24,7 +24,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 From 608330c5bb3f2953ad39377197ca1356a2205f2d Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 18 Sep 2019 23:03:59 +0200 Subject: [PATCH 06/17] Minor bug fixes --- src/ComputeSharp.Shaders/ShaderRunner.cs | 12 ++++++++---- .../Translation/ShaderLoader.IL.cs | 2 +- src/ComputeSharp.Shaders/Translation/ShaderLoader.cs | 8 ++++---- 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/src/ComputeSharp.Shaders/ShaderRunner.cs b/src/ComputeSharp.Shaders/ShaderRunner.cs index 944aee43..944a72cd 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner.cs @@ -103,15 +103,19 @@ namespace ComputeSharp.Shaders using CommandList commandList = new CommandList(device, CommandListType.Compute); commandList.SetPipelineState(pipelineState); + // Extract the dispatch data for the shader invocation + using var 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/ShaderLoader.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs index 297d8365..3e01ddeb 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs @@ -86,7 +86,7 @@ namespace ComputeSharp.Shaders.Translation // Declare the local variables il.DeclareLocal(ShaderType); - foreach (ReadableMember member in map.OrderBy(p => p.Value).Select(p => p.Key)) + foreach (ReadableMember member in map.OrderBy(p => p.Value).Skip(1).Select(p => p.Key)) { il.DeclareLocal(member.MemberType); } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index c4cbd824..044fd898 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -198,7 +198,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 +210,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 +222,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 +231,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)); From e049c79aacdbf8304fe6d344a804f01d603f18fc Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 18 Sep 2019 23:46:30 +0200 Subject: [PATCH 07/17] Fixed bug with arguments in dispatch data loading --- src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs index 3e01ddeb..630b43d5 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs @@ -102,7 +102,7 @@ namespace ComputeSharp.Shaders.Translation if (HlslKnownTypes.IsKnownBufferType(member.MemberType)) { // Load the offset address into the resource buffers - il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldarg_1); if (_ResourcesCount > 0) il.EmitAddOffset(_ResourcesCount); _ResourcesCount++; @@ -121,7 +121,7 @@ namespace ComputeSharp.Shaders.Translation if (_VariablesByteSize % 16 > 16 - size) _VariablesByteSize += 16 - _VariablesByteSize % 16; // Load the target address into the variables buffer - il.Emit(OpCodes.Ldarg_1); + il.Emit(OpCodes.Ldarg_2); il.EmitAddOffset(_VariablesByteSize); // Load the variable and store it in the loaded address From c66a68afeb4abba5581dcbf9079d10164e60de52 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 19 Sep 2019 00:14:33 +0200 Subject: [PATCH 08/17] Minor IL optimizations, fixed variables loading --- src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs | 5 +++-- src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs index 31f9094a..05256421 100644 --- a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs +++ b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs @@ -99,8 +99,7 @@ namespace System.Reflection.Emit public static void EmitAddOffset(this ILGenerator il, int offset) { // Push the offset to the stack - if (offset > 8) il.Emit(OpCodes.Ldc_I4, offset); - else + if (offset <= 8) { il.Emit(offset switch { @@ -111,6 +110,8 @@ namespace System.Reflection.Emit _ => throw new InvalidOperationException("Huh?") }); } + 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); diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs index 630b43d5..393a2302 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs @@ -123,6 +123,7 @@ namespace ComputeSharp.Shaders.Translation // Load the target address into the variables buffer il.Emit(OpCodes.Ldarg_2); il.EmitAddOffset(_VariablesByteSize); + _VariablesByteSize += size; // Load the variable and store it in the loaded address LoadMember(member); From 7f3f0f58d10c63ff1f9f9c51dff129ebb5650d03 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 19 Sep 2019 01:33:57 +0200 Subject: [PATCH 09/17] Fixed IL generation when using stobj --- .../Extensions/ILGeneratorExtensions.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs index 05256421..860e0a41 100644 --- a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs +++ b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs @@ -127,7 +127,8 @@ namespace System.Reflection.Emit { if (type.IsValueType) { - il.Emit(Marshal.SizeOf(type) switch + // Pick the optimal opcode to set a value type + OpCode opcode = Marshal.SizeOf(type) switch { // Use the faster op codes for sizes <= 8 1 => OpCodes.Stind_I1, @@ -139,7 +140,11 @@ namespace System.Reflection.Emit // 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); } From 85cce1db3cd0c4ae595d9bc20418961b7c98d9b5 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 19 Sep 2019 02:21:19 +0200 Subject: [PATCH 10/17] Fixed IL generation when loading nested fields --- .../Translation/Models/ReadableMember.cs | 12 ++++++++++++ .../Translation/ShaderLoader.IL.cs | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs index a18e0d12..5b26c690 100644 --- a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs +++ b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.cs @@ -83,5 +83,17 @@ namespace ComputeSharp.Shaders.Translation.Models /// /// 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/ShaderLoader.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs index 393a2302..1c8c32d8 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs @@ -74,7 +74,7 @@ namespace ComputeSharp.Shaders.Translation if (i == 0) il.EmitLoadLocal(0); for (; i < member.Parents.Count; i++) { - il.Emit(OpCodes.Ldfld, member.Parents[i].MemberType); + il.Emit(OpCodes.Ldfld, member.Parents[i]); il.EmitStoreLocal(map[member.Parents[i]]); il.EmitLoadLocal(map[member.Parents[i]]); } From d91c2be519174d9a117bf55f9e1e33caff9604f0 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 19 Sep 2019 03:09:16 +0200 Subject: [PATCH 11/17] Code refactoring to the DispatchData struct --- src/ComputeSharp.Shaders/ShaderRunner.cs | 2 +- .../Translation/Models/DispatchData.cs | 82 +++++++++++++++++++ .../Translation/ShaderLoader.IL.cs | 45 +--------- 3 files changed, 85 insertions(+), 44 deletions(-) create mode 100644 src/ComputeSharp.Shaders/Translation/Models/DispatchData.cs diff --git a/src/ComputeSharp.Shaders/ShaderRunner.cs b/src/ComputeSharp.Shaders/ShaderRunner.cs index 944a72cd..f96dac8c 100644 --- a/src/ComputeSharp.Shaders/ShaderRunner.cs +++ b/src/ComputeSharp.Shaders/ShaderRunner.cs @@ -104,7 +104,7 @@ namespace ComputeSharp.Shaders commandList.SetPipelineState(pipelineState); // Extract the dispatch data for the shader invocation - using var dispatchData = shaderData.Loader.GetDispatchData(action, x, y, z); + using DispatchData dispatchData = shaderData.Loader.GetDispatchData(action, x, y, z); // Load the captured buffers Span resources = dispatchData.Resources; 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/ShaderLoader.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs index 1c8c32d8..49f225aa 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs @@ -35,7 +35,7 @@ namespace ComputeSharp.Shaders.Translation private MembersLoader? _MembersLoader; [Pure] - public ShaderDispatchData GetDispatchData(Action action, int x, int y, int z) + public DispatchData GetDispatchData(Action action, int x, int y, int z) { if (_MembersLoader == null) { @@ -150,48 +150,7 @@ namespace ComputeSharp.Shaders.Translation // Invoke the dynamic method to extract the captured data _MembersLoader(action.Target, ref r0, ref r1); - return new ShaderDispatchData(resources, _ResourcesCount, variables, _VariablesByteSize); - } - - public readonly ref struct ShaderDispatchData - { - private readonly GraphicsResource[] ResourcesArray; - - private readonly byte[] VariablesArray; - - private readonly int ResourcesCount; - - private readonly int VariablesInt4Size; - - public Span Resources - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get => ResourcesArray.AsSpan(0, ResourcesCount); - } - - public Span Variables - { - [MethodImpl(MethodImplOptions.AggressiveInlining)] - get - { - ref Int4 r = ref Unsafe.As(ref VariablesArray[0]); - return MemoryMarshal.CreateSpan(ref r, VariablesInt4Size); - } - } - - public ShaderDispatchData(GraphicsResource[] resourcesArray, int resourcesCount, byte[] variablesArray, int variablesInt4Size) - { - ResourcesArray = resourcesArray; - VariablesArray = variablesArray; - ResourcesCount = resourcesCount; - VariablesInt4Size = variablesInt4Size; - } - - public void Dispose() - { - ArrayPool.Shared.Return(ResourcesArray); - ArrayPool.Shared.Return(VariablesArray); - } + return new DispatchData(resources, _ResourcesCount, variables, _VariablesByteSize); } } } From d70dc975eb5b9054be41bc1be89a1146ef9ca5cc Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 19 Sep 2019 03:32:30 +0200 Subject: [PATCH 12/17] Minor code tweaks --- src/ComputeSharp.Shaders/ShaderRunner.cs | 2 -- .../Translation/ShaderLoader.IL.cs | 21 +++++++------------ 2 files changed, 8 insertions(+), 15 deletions(-) diff --git a/src/ComputeSharp.Shaders/ShaderRunner.cs b/src/ComputeSharp.Shaders/ShaderRunner.cs index f96dac8c..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; diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs index 49f225aa..11fbf8c3 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs @@ -105,16 +105,8 @@ namespace ComputeSharp.Shaders.Translation il.Emit(OpCodes.Ldarg_1); if (_ResourcesCount > 0) il.EmitAddOffset(_ResourcesCount); _ResourcesCount++; - - /* 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); } - else if (HlslKnownTypes.IsKnownScalarType(member.MemberType) || - HlslKnownTypes.IsKnownVectorType(member.MemberType)) + else if (HlslKnownTypes.IsKnownScalarType(member.MemberType) || HlslKnownTypes.IsKnownVectorType(member.MemberType)) { // Calculate the right offset with 16-bytes padding (HLSL constant buffer) int size = Marshal.SizeOf(member.MemberType); @@ -124,12 +116,15 @@ namespace ComputeSharp.Shaders.Translation il.Emit(OpCodes.Ldarg_2); il.EmitAddOffset(_VariablesByteSize); _VariablesByteSize += size; - - // Load the variable and store it in the loaded address - LoadMember(member); - il.EmitStoreToAddress(member.MemberType); } 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); From 47ca3adf0c9d0968c689fe9fbdf0fc6b6038ef83 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 19 Sep 2019 14:38:05 +0200 Subject: [PATCH 13/17] Code refactoring, removed unnecessary code --- .../Translation/ShaderLoader.IL.cs | 217 ++++++++++-------- .../Translation/ShaderLoader.cs | 36 --- 2 files changed, 118 insertions(+), 135 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs index 11fbf8c3..5e365681 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs @@ -12,12 +12,22 @@ 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 /// @@ -29,108 +39,18 @@ namespace ComputeSharp.Shaders.Translation /// 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 MembersLoader(object obj, ref GraphicsResource r0, ref byte r1); - - // The cached loader method - private MembersLoader? _MembersLoader; + 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) { - if (_MembersLoader == null) - { - // 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 - _MembersLoader = 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 = Marshal.SizeOf(member.MemberType); - 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); - }); - } - // Resources and variables buffers GraphicsResource[] resources = ArrayPool.Shared.Rent(_ResourcesCount); byte[] variables = ArrayPool.Shared.Rent(_VariablesByteSize); @@ -143,9 +63,108 @@ namespace ComputeSharp.Shaders.Translation Unsafe.Add(ref Unsafe.As(ref r1), 2) = z; // Invoke the dynamic method to extract the captured data - _MembersLoader(action.Target, ref r0, ref r1); + DispatchDataLoader loader = _DispatchDataLoader ??= BuildDispatchDataLoader(); + 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 = Marshal.SizeOf(member.MemberType); + 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 044fd898..ca422307 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; @@ -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(); /// From 7c3c642fad62faef20684ee0883ac89b12a284b8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 19 Sep 2019 15:08:34 +0200 Subject: [PATCH 14/17] More code refactoring, removed all legacy code --- .../Extensions/GraphicsResourceExtensions.cs | 80 ------------- .../Models/ReadableMember.GetValue.cs | 108 ------------------ .../Translation/Models/ReadableMember.cs | 30 +++-- .../Translation/ShaderLoader.IL.cs | 8 +- .../Translation/ShaderLoader.cs | 8 -- .../BufferTests.cs | 35 ------ 6 files changed, 30 insertions(+), 239 deletions(-) delete mode 100644 src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs delete mode 100644 src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs delete mode 100644 tests/ComputeSharp.Tests.Internals/BufferTests.cs 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/Translation/Models/ReadableMember.GetValue.cs b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs deleted file mode 100644 index 70e665c6..00000000 --- a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs +++ /dev/null @@ -1,108 +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 IReadOnlyList? 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); - il.EmitCastOrUnbox(hierarchy[0].DeclaringType); - } - - // Unroll the member access - foreach (ReadableMember member in hierarchy) - { - il.EmitReadMember(member); - } - - // 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 5b26c690..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,13 +8,8 @@ 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 - /// - private readonly string Id; - /// /// The object wrapped by the current instance /// @@ -25,7 +22,6 @@ namespace ComputeSharp.Shaders.Translation.Models private ReadableMember(MemberInfo memberInfo) { // General properties - Id = $"{memberInfo.DeclaringType.FullName}{Type.Delimiter}{memberInfo.Name}"; Member = memberInfo; Name = memberInfo.Name; DeclaringType = memberInfo.DeclaringType; @@ -66,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 /// diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs index 5e365681..5ee94f91 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs @@ -51,6 +51,13 @@ namespace ComputeSharp.Shaders.Translation [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); @@ -63,7 +70,6 @@ namespace ComputeSharp.Shaders.Translation Unsafe.Add(ref Unsafe.As(ref r1), 2) = z; // Invoke the dynamic method to extract the captured data - DispatchDataLoader loader = _DispatchDataLoader ??= BuildDispatchDataLoader(); loader(action.Target, ref r0, ref r1); return new DispatchData(resources, _ResourcesCount, variables, _VariablesByteSize); diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index ca422307..dfc6a2ae 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -223,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); - } - } -} From 5b9ac13a19fb77859d0b23211c748eafbb4eece6 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 19 Sep 2019 16:36:48 +0200 Subject: [PATCH 15/17] Minor IL optimizations --- .../Translation/ShaderHashCodeProvider.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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); } From ce28fc9097d7a097e3b038ea16dfd18e78ce9229 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Thu, 19 Sep 2019 16:47:11 +0200 Subject: [PATCH 16/17] Fixed offsetting for byte values --- src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs index 5ee94f91..0669ae18 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.IL.cs @@ -151,7 +151,7 @@ namespace ComputeSharp.Shaders.Translation else if (HlslKnownTypes.IsKnownScalarType(member.MemberType) || HlslKnownTypes.IsKnownVectorType(member.MemberType)) { // Calculate the right offset with 16-bytes padding (HLSL constant buffer) - int size = Marshal.SizeOf(member.MemberType); + 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 From b1ce5edda0ef33583c0b017d7a7d8fe808244202 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Fri, 20 Sep 2019 00:33:47 +0200 Subject: [PATCH 17/17] Minor code tweaks to the IL extensions --- .../Extensions/ILGeneratorExtensions.cs | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs index 860e0a41..acd78cf8 100644 --- a/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs +++ b/src/ComputeSharp.Shaders/Extensions/ILGeneratorExtensions.cs @@ -33,7 +33,7 @@ namespace System.Reflection.Emit 1 => OpCodes.Ldloc_1, 2 => OpCodes.Ldloc_2, 3 => OpCodes.Ldloc_3, - _ => throw new InvalidOperationException("Huh?") + _ => throw new InvalidOperationException($"Invalid local variable index [{index}]") }); } else if (index <= 255) il.Emit(OpCodes.Ldloc_S, (byte)index); @@ -56,7 +56,7 @@ namespace System.Reflection.Emit 1 => OpCodes.Stloc_1, 2 => OpCodes.Stloc_2, 3 => OpCodes.Stloc_3, - _ => throw new InvalidOperationException("Huh?") + _ => throw new InvalidOperationException($"Invalid local variable index [{index}]") }); } else if (index <= 255) il.Emit(OpCodes.Stloc_S, (byte)index); @@ -99,15 +99,22 @@ namespace System.Reflection.Emit public static void EmitAddOffset(this ILGenerator il, int offset) { // Push the offset to the stack - if (offset <= 8) + 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("Huh?") + _ => throw new InvalidOperationException($"Invalid offset value [{offset}]") }); } else if (offset <= 127) il.Emit(OpCodes.Ldc_I4_S, (byte)offset); @@ -131,10 +138,10 @@ namespace System.Reflection.Emit OpCode opcode = Marshal.SizeOf(type) switch { // Use the faster op codes for sizes <= 8 - 1 => OpCodes.Stind_I1, - 2 => OpCodes.Stind_I2, + 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 => OpCodes.Stind_I4, + 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,