From 99d4a04c549402e45a401ec6e7df10310318cfb8 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 18 Sep 2019 01:49:32 +0200 Subject: [PATCH 1/4] Added new DynamicMethod class --- .../Extensions/DynamicMethod{T}.cs | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/ComputeSharp.Shaders/Extensions/DynamicMethod{T}.cs diff --git a/src/ComputeSharp.Shaders/Extensions/DynamicMethod{T}.cs b/src/ComputeSharp.Shaders/Extensions/DynamicMethod{T}.cs new file mode 100644 index 00000000..5185d2ec --- /dev/null +++ b/src/ComputeSharp.Shaders/Extensions/DynamicMethod{T}.cs @@ -0,0 +1,62 @@ +using System; +using System.Diagnostics.Contracts; +using System.Linq; +using System.Reflection; +using System.Reflection.Emit; +using System.Threading; + +namespace ComputeSharp.Shaders.Extensions +{ + /// + /// A that can be used to easily (lol) create dynamic methods + /// + /// The type of that will be used to wrap the new methods + public static class DynamicMethod where T : Delegate + { + /// + /// The return type of the + /// + private static readonly Type ReturnType; + + /// + /// The array of types of the arguments of the + /// + private static readonly Type[] ParameterTypes; + + /// + /// Loads all the necessary info for the current parameter + /// + static DynamicMethod() + { + MethodInfo method = typeof(T).GetMethod("Invoke"); + ReturnType = method.ReturnType; + ParameterTypes = method.GetParameters().Select(p => p.ParameterType).ToArray(); + } + + /// + /// Local counter for dynamic methods of type ever generated + /// + private static int _Count; + + /// + /// Creates a new for the target owner + /// + /// The instance that will own the new method + /// An that builds the IL bytecode for the new method + /// A new dynamic method wrapped as a + [Pure] + public static T New(Type owner, Action builder) + { + // Create a new dynamic method with a unique id + string id = $"__IL__{typeof(T).Name}_{Interlocked.Increment(ref _Count)}"; + DynamicMethod method = new DynamicMethod(id, ReturnType, ParameterTypes, owner); + + // Build the IL bytecode + ILGenerator il = method.GetILGenerator(); + builder(il); + + // Build and delegate instance + return (T)method.CreateDelegate(typeof(T)); + } + } +} From 2b310aba259a37426194ee48a40caf58de07cfc2 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 18 Sep 2019 02:27:43 +0200 Subject: [PATCH 2/4] Code tweaks, added basic test --- .../Extensions/DynamicMethod{T}.cs | 14 ++++++---- .../DynamicMethodTests.cs | 28 +++++++++++++++++++ 2 files changed, 37 insertions(+), 5 deletions(-) create mode 100644 tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs diff --git a/src/ComputeSharp.Shaders/Extensions/DynamicMethod{T}.cs b/src/ComputeSharp.Shaders/Extensions/DynamicMethod{T}.cs index 5185d2ec..1fba1d60 100644 --- a/src/ComputeSharp.Shaders/Extensions/DynamicMethod{T}.cs +++ b/src/ComputeSharp.Shaders/Extensions/DynamicMethod{T}.cs @@ -11,15 +11,20 @@ namespace ComputeSharp.Shaders.Extensions /// A that can be used to easily (lol) create dynamic methods /// /// The type of that will be used to wrap the new methods - public static class DynamicMethod where T : Delegate + internal static class DynamicMethod where T : Delegate { + /// + /// The owner type for new dynamic methods + /// + private static readonly Type OwnerType = typeof(DynamicMethod); + /// /// The return type of the /// private static readonly Type ReturnType; /// - /// The array of types of the arguments of the + /// The types of the arguments of the /// private static readonly Type[] ParameterTypes; @@ -41,15 +46,14 @@ namespace ComputeSharp.Shaders.Extensions /// /// Creates a new for the target owner /// - /// The instance that will own the new method /// An that builds the IL bytecode for the new method /// A new dynamic method wrapped as a [Pure] - public static T New(Type owner, Action builder) + public static T New(Action builder) { // Create a new dynamic method with a unique id string id = $"__IL__{typeof(T).Name}_{Interlocked.Increment(ref _Count)}"; - DynamicMethod method = new DynamicMethod(id, ReturnType, ParameterTypes, owner); + DynamicMethod method = new DynamicMethod(id, ReturnType, ParameterTypes, OwnerType); // Build the IL bytecode ILGenerator il = method.GetILGenerator(); diff --git a/tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs b/tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs new file mode 100644 index 00000000..1537d452 --- /dev/null +++ b/tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs @@ -0,0 +1,28 @@ +using System.Reflection.Emit; +using ComputeSharp.Shaders.Extensions; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace ComputeSharp.Tests.Internals +{ + [TestClass] + [TestCategory("DynamicMethod")] + public class DynamicMethodTests + { + public delegate int Square(int x); + + public void TestSquare() + { + Square square = DynamicMethod.New(il => + { + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Dup); + il.Emit(OpCodes.Mul); + il.Emit(OpCodes.Ret); + }); + + int result = square(2); // result = 2 * 2 + + Assert.IsTrue(result == 4); + } + } +} From 52ba3183e6597ac4ec8f8a847103eee7d6fba26e Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 18 Sep 2019 02:33:36 +0200 Subject: [PATCH 3/4] Code refactoring using the new DynamicMethod type --- .../Models/ReadableMember.GetValue.cs | 51 +++++------ .../Translation/ShaderHashCodeProvider.cs | 90 +++++++++---------- .../DynamicMethodTests.cs | 20 ++++- 3 files changed, 86 insertions(+), 75 deletions(-) diff --git a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs index 411f6cb4..c4c73783 100644 --- a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs +++ b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs @@ -4,6 +4,7 @@ using System.Diagnostics.Contracts; using System.Linq; using System.Reflection.Emit; using System.Runtime.CompilerServices; +using ComputeSharp.Shaders.Extensions; namespace ComputeSharp.Shaders.Translation.Models { @@ -79,39 +80,35 @@ namespace ComputeSharp.Shaders.Translation.Models [Pure] private Getter BuildDynamicGetter() { - // Create a new dynamic method for the current member - DynamicMethod method = new DynamicMethod($"Get{Name}", typeof(object), new[] { typeof(object) }, DeclaringType); - ILGenerator il = method.GetILGenerator(); - - // 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) + return DynamicMethod.New(il => { - il.Emit(OpCodes.Ldarg_0); + // Info for hierarchical access + ReadableMember[] hierarchy = (Parents ?? Array.Empty()).Concat(new[] { this }).ToArray(); - Type unboxType = hierarchy[0].DeclaringType; - il.Emit(unboxType.IsValueType ? OpCodes.Unbox : OpCodes.Castclass, unboxType); - } + // Load the argument (the object instance) and cast it to the right type, if needed + if (!IsStatic) + { + il.Emit(OpCodes.Ldarg_0); - // 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"); - } + Type unboxType = hierarchy[0].DeclaringType; + il.Emit(unboxType.IsValueType ? OpCodes.Unbox : OpCodes.Castclass, unboxType); + } - // Box the value, if needed - if (MemberType.IsValueType) il.Emit(OpCodes.Box, MemberType); + // 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"); + } - // Return the member value from the top of the evaluation stack - il.Emit(OpCodes.Ret); + // Box the value, if needed + if (MemberType.IsValueType) il.Emit(OpCodes.Box, MemberType); - // Build and return the delegate - return (Getter)method.CreateDelegate(typeof(Getter)); + // Return the member value from the top of the evaluation stack + il.Emit(OpCodes.Ret); + }); } } } diff --git a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs index 44829285..bea29668 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs @@ -67,58 +67,54 @@ namespace ComputeSharp.Shaders.Translation [Pure] private static Hasher BuildDynamicHasher(Type declaringType, IReadOnlyCollection fieldInfos) { - // Create a new dynamic method for the current member - DynamicMethod method = new DynamicMethod("GetHashCodeForHlslDelegates", typeof(int), new[] { typeof(int), typeof(object) }, declaringType); - ILGenerator il = method.GetILGenerator(); - - // Declare the local variable to store the target instance - il.DeclareLocal(declaringType); - - // Load the argument (the object instance) - il.Emit(OpCodes.Ldarg_1); - il.Emit(OpCodes.Castclass, declaringType); - il.Emit(OpCodes.Stloc_0); - - // Unroll the member access - MethodInfo - validateDelegateInfo = typeof(ShaderHashCodeProvider).GetMethod(nameof(ValidateDelegate), BindingFlags.NonPublic | BindingFlags.Static), - getMethodInfo = typeof(Delegate).GetProperty(nameof(Delegate.Method)).GetMethod, - getHashCodeInfo = typeof(object).GetMethod(nameof(GetHashCode)); - foreach (FieldInfo fieldInfo in fieldInfos) + return DynamicMethod.New(il => { - Label label = il.DefineLabel(); + // Declare the local variable to store the target instance + il.DeclareLocal(declaringType); - // if (fieldInfo.GetValue(obj) != null) { - il.Emit(OpCodes.Ldloc_0); - il.Emit(OpCodes.Ldfld, fieldInfo); - il.Emit(OpCodes.Brfalse_S, label); + // Load the argument (the object instance) + il.Emit(OpCodes.Ldarg_1); + il.Emit(OpCodes.Castclass, declaringType); + il.Emit(OpCodes.Stloc_0); - // if (ValidateDelegate(field)) { - il.Emit(OpCodes.Ldloc_0); - il.Emit(OpCodes.Ldfld, fieldInfo); - il.EmitCall(OpCodes.Call, validateDelegateInfo, null); - il.Emit(OpCodes.Brfalse_S, label); + // Unroll the member access + MethodInfo + validateDelegateInfo = typeof(ShaderHashCodeProvider).GetMethod(nameof(ValidateDelegate), BindingFlags.NonPublic | BindingFlags.Static), + getMethodInfo = typeof(Delegate).GetProperty(nameof(Delegate.Method)).GetMethod, + getHashCodeInfo = typeof(object).GetMethod(nameof(GetHashCode)); + foreach (FieldInfo fieldInfo in fieldInfos) + { + Label label = il.DefineLabel(); - // hash = hash * 17 + field.Method.GetHashCode(); + // if (fieldInfo.GetValue(obj) != null) { + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldfld, fieldInfo); + il.Emit(OpCodes.Brfalse_S, label); + + // if (ValidateDelegate(field)) { + il.Emit(OpCodes.Ldloc_0); + il.Emit(OpCodes.Ldfld, fieldInfo); + il.EmitCall(OpCodes.Call, validateDelegateInfo, null); + il.Emit(OpCodes.Brfalse_S, label); + + // hash = hash * 17 + field.Method.GetHashCode(); + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldc_I4, 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.MarkLabel(label); + } + + // Return the computed hash il.Emit(OpCodes.Ldarg_0); - il.Emit(OpCodes.Ldc_I4, 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.MarkLabel(label); - } - - // Return the computed hash - il.Emit(OpCodes.Ldarg_0); - il.Emit(OpCodes.Ret); - - // Build and return the delegate - return (Hasher)method.CreateDelegate(typeof(Hasher)); + il.Emit(OpCodes.Ret); + }); } /// diff --git a/tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs b/tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs index 1537d452..42aeed8b 100644 --- a/tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs +++ b/tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs @@ -1,4 +1,5 @@ -using System.Reflection.Emit; +using System; +using System.Reflection.Emit; using ComputeSharp.Shaders.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -8,8 +9,25 @@ namespace ComputeSharp.Tests.Internals [TestCategory("DynamicMethod")] public class DynamicMethodTests { + [TestMethod] + public void TestFunc() + { + Func square = DynamicMethod>.New(il => + { + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Dup); + il.Emit(OpCodes.Mul); + il.Emit(OpCodes.Ret); + }); + + int result = square(2); // result = 2 * 2 + + Assert.IsTrue(result == 4); + } + public delegate int Square(int x); + [TestMethod] public void TestSquare() { Square square = DynamicMethod.New(il => From ca8c07af101269e159e2912799631ac2f54ddb4c Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Wed, 18 Sep 2019 02:38:32 +0200 Subject: [PATCH 4/4] Adjusted extensions namespaces --- src/ComputeSharp.Shaders/Extensions/DynamicMethod{T}.cs | 7 ++----- src/ComputeSharp.Shaders/Extensions/StringExtensions.cs | 5 ++--- .../Extensions/SyntaxNodeExtensions.cs | 5 +---- src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs | 5 ++--- .../Translation/Models/ReadableMember.GetValue.cs | 1 - .../Translation/ShaderHashCodeProvider.cs | 1 - src/ComputeSharp.Shaders/Translation/ShaderLoader.cs | 1 - .../Translation/ShaderSyntaxRewriter.cs | 1 - tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs | 1 - 9 files changed, 7 insertions(+), 20 deletions(-) diff --git a/src/ComputeSharp.Shaders/Extensions/DynamicMethod{T}.cs b/src/ComputeSharp.Shaders/Extensions/DynamicMethod{T}.cs index 1fba1d60..3b08edd3 100644 --- a/src/ComputeSharp.Shaders/Extensions/DynamicMethod{T}.cs +++ b/src/ComputeSharp.Shaders/Extensions/DynamicMethod{T}.cs @@ -1,11 +1,8 @@ -using System; -using System.Diagnostics.Contracts; +using System.Diagnostics.Contracts; using System.Linq; -using System.Reflection; -using System.Reflection.Emit; using System.Threading; -namespace ComputeSharp.Shaders.Extensions +namespace System.Reflection.Emit { /// /// A that can be used to easily (lol) create dynamic methods diff --git a/src/ComputeSharp.Shaders/Extensions/StringExtensions.cs b/src/ComputeSharp.Shaders/Extensions/StringExtensions.cs index 401321a3..16f21407 100644 --- a/src/ComputeSharp.Shaders/Extensions/StringExtensions.cs +++ b/src/ComputeSharp.Shaders/Extensions/StringExtensions.cs @@ -1,9 +1,8 @@ -using System; -using System.Diagnostics.Contracts; +using System.Diagnostics.Contracts; using System.Linq; using System.Text.RegularExpressions; -namespace ComputeSharp.Shaders.Extensions +namespace System { /// /// A that provides extension methods for the type diff --git a/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs b/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs index efc7b4be..8c7a0259 100644 --- a/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs +++ b/src/ComputeSharp.Shaders/Extensions/SyntaxNodeExtensions.cs @@ -5,11 +5,8 @@ using System.Linq; using System.Reflection; using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Translation.Models; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; -namespace ComputeSharp.Shaders.Extensions +namespace Microsoft.CodeAnalysis.CSharp.Syntax { /// /// A with some extension methods for C# syntax nodes diff --git a/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs b/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs index 0b31f9cc..56b40454 100644 --- a/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs +++ b/src/ComputeSharp.Shaders/Extensions/TypeExtensions.cs @@ -1,10 +1,9 @@ -using System; -using System.Diagnostics.CodeAnalysis; +using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.CompilerServices; -namespace ComputeSharp.Shaders.Extensions +namespace System { /// /// A that provides extension methods for the type diff --git a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs index c4c73783..db9df14d 100644 --- a/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs +++ b/src/ComputeSharp.Shaders/Translation/Models/ReadableMember.GetValue.cs @@ -4,7 +4,6 @@ using System.Diagnostics.Contracts; using System.Linq; using System.Reflection.Emit; using System.Runtime.CompilerServices; -using ComputeSharp.Shaders.Extensions; namespace ComputeSharp.Shaders.Translation.Models { diff --git a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs index bea29668..9a361ab4 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs @@ -5,7 +5,6 @@ using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; -using ComputeSharp.Shaders.Extensions; using ComputeSharp.Shaders.Mappings; namespace ComputeSharp.Shaders.Translation diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs index ff2a4ae6..d9d1f094 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs @@ -6,7 +6,6 @@ using System.Reflection; using System.Text.RegularExpressions; using ComputeSharp.Graphics.Buffers.Abstract; using ComputeSharp.Graphics.Extensions; -using ComputeSharp.Shaders.Extensions; using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Renderer.Models.Fields; using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract; diff --git a/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs b/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs index 0199e610..37d1f584 100644 --- a/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs +++ b/src/ComputeSharp.Shaders/Translation/ShaderSyntaxRewriter.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Reflection; -using ComputeSharp.Shaders.Extensions; using ComputeSharp.Shaders.Translation.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; diff --git a/tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs b/tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs index 42aeed8b..a00a7726 100644 --- a/tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs +++ b/tests/ComputeSharp.Tests.Internals/DynamicMethodTests.cs @@ -1,6 +1,5 @@ using System; using System.Reflection.Emit; -using ComputeSharp.Shaders.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ComputeSharp.Tests.Internals