diff --git a/src/ComputeSharp.Shaders/ShaderRunner.cs b/src/ComputeSharp.Shaders/ShaderRunner.cs
index 2b0ac27f..944aee43 100644
--- a/src/ComputeSharp.Shaders/ShaderRunner.cs
+++ b/src/ComputeSharp.Shaders/ShaderRunner.cs
@@ -7,6 +7,7 @@ using ComputeSharp.Graphics.Buffers.Extensions;
using ComputeSharp.Shaders.Renderer;
using ComputeSharp.Shaders.Renderer.Models;
using ComputeSharp.Shaders.Translation;
+using ComputeSharp.Shaders.Translation.Models;
using Vortice.Direct3D12;
using CommandList = ComputeSharp.Graphics.Commands.CommandList;
using PipelineState = ComputeSharp.Graphics.Commands.PipelineState;
@@ -40,7 +41,7 @@ namespace ComputeSharp.Shaders
///
/// The mapping used to cache and reuse compiled shaders
///
- private static readonly Dictionary<(int Id, int ThreadsX, int ThreadsY, int ThreadsZ), (ShaderLoader, ShaderBytecode)> ShadersCache = new Dictionary<(int, int, int, int), (ShaderLoader, ShaderBytecode)>();
+ private static readonly Dictionary<(int Id, int ThreadsX, int ThreadsY, int ThreadsZ), CachedShader> ShadersCache = new Dictionary<(int, int, int, int), CachedShader>();
///
/// Compiles and runs the input shader on a target instance, with the specified parameters
@@ -60,10 +61,10 @@ namespace ComputeSharp.Shaders
Action action)
{
// Try to get the cache shader
- (ShaderLoader Loader, ShaderBytecode Bytecode) shaderData;
+ CachedShader shaderData;
lock (ShadersCache)
{
- var key = (ShaderLoader.GetHashCode(action), threadsX, threadsY, threadsZ);
+ var key = (ShaderHashCodeProvider.GetHashCode(action), threadsX, threadsY, threadsZ);
if (!ShadersCache.TryGetValue(key, out shaderData))
{
// Load the input shader
@@ -88,7 +89,7 @@ namespace ComputeSharp.Shaders
ShaderBytecode shaderBytecode = ShaderCompiler.CompileShader(shaderSource);
// Cache for later use
- shaderData = (shaderLoader, shaderBytecode);
+ shaderData = new CachedShader(shaderLoader, shaderBytecode);
ShadersCache.Add(key, shaderData);
}
}
diff --git a/src/ComputeSharp.Shaders/Translation/Models/CachedShader.cs b/src/ComputeSharp.Shaders/Translation/Models/CachedShader.cs
new file mode 100644
index 00000000..8c5cf20c
--- /dev/null
+++ b/src/ComputeSharp.Shaders/Translation/Models/CachedShader.cs
@@ -0,0 +1,31 @@
+using Vortice.Direct3D12;
+
+namespace ComputeSharp.Shaders.Translation.Models
+{
+ ///
+ /// A that contains info on a cached shader
+ ///
+ internal readonly struct CachedShader
+ {
+ ///
+ /// The instance with the shader metadata
+ ///
+ public readonly ShaderLoader Loader;
+
+ ///
+ /// The compiled shader bytecode
+ ///
+ public readonly ShaderBytecode Bytecode;
+
+ ///
+ /// Creates a new instance with the specified parameters
+ ///
+ /// The instance with the shader metadata
+ /// The compiled shader bytecode
+ public CachedShader(ShaderLoader loader, ShaderBytecode bytecode)
+ {
+ Loader = loader;
+ Bytecode = bytecode;
+ }
+ }
+}
diff --git a/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs
new file mode 100644
index 00000000..44829285
--- /dev/null
+++ b/src/ComputeSharp.Shaders/Translation/ShaderHashCodeProvider.cs
@@ -0,0 +1,137 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.Contracts;
+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
+{
+ ///
+ /// A that handles the cache system for the generated shaders
+ ///
+ internal static class ShaderHashCodeProvider
+ {
+ ///
+ /// The mapping of hashcodes to aggregate hashing functions
+ ///
+ private static readonly Dictionary HasherMapping = new Dictionary();
+
+ ///
+ /// Gets a unique hashcode for the input shader closure
+ ///
+ /// The input representing the shader to run
+ [Pure]
+ public static int GetHashCode(Action action)
+ {
+ // Get the delegate hashcode
+ MethodInfo methodInfo = action.Method;
+ int hash = methodInfo.GetHashCode();
+
+ if (!HasherMapping.TryGetValue(hash, out Hasher? hasher))
+ {
+ // Get the candidate fields for delegate checking
+ FieldInfo[] delegateFieldInfos = (
+ from fieldInfo in methodInfo.DeclaringType.GetFields()
+ where fieldInfo.FieldType.IsDelegate() &&
+ fieldInfo.FieldType.GenericTypeArguments.All(type => HlslKnownTypes.IsKnownScalarType(type) || HlslKnownTypes.IsKnownVectorType(type))
+ select fieldInfo).ToArray();
+
+ // If at least one captured delegate is present, build the hasher method
+ hasher = delegateFieldInfos.Length == 0 ? null : BuildDynamicHasher(action.Method.DeclaringType, delegateFieldInfos);
+ HasherMapping.Add(hash, hasher);
+ }
+
+ // Aggregate the hash of the captured delegates, if needed
+ if (hasher != null) hash = hasher(hash, action.Target);
+
+ return hash;
+ }
+
+ ///
+ /// A that represents an aggregate hash function for a given instance
+ ///
+ /// The initial hash value
+ /// The closure instance to use to compute the final hash value
+ /// The final hash value for the input closure
+ private delegate int Hasher(int hash, object instance);
+
+ ///
+ /// Builds a new instance for the target and sequence of values
+ ///
+ /// The declaring to analyze
+ /// The list of captured fields to inspect
+ [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)
+ {
+ Label label = il.DefineLabel();
+
+ // 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.Ret);
+
+ // Build and return the delegate
+ return (Hasher)method.CreateDelegate(typeof(Hasher));
+ }
+
+ ///
+ /// A method that checks whether an input is supported in HLSL
+ ///
+ /// The input instance to check
+ [Pure]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static bool ValidateDelegate(Delegate candidate)
+ {
+ MethodInfo methodInfo = candidate.Method;
+ return (methodInfo.IsStatic || methodInfo.DeclaringType.IsStatelessDelegateContainer()) &&
+ (HlslKnownTypes.IsKnownScalarType(methodInfo.ReturnType) || HlslKnownTypes.IsKnownVectorType(methodInfo.ReturnType));
+ }
+ }
+}
diff --git a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs
index 7c6faaa8..ed75fcee 100644
--- a/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs
+++ b/src/ComputeSharp.Shaders/Translation/ShaderLoader.cs
@@ -147,31 +147,6 @@ namespace ComputeSharp.Shaders.Translation
///
public IReadOnlyList LocalFunctionsList => _LocalFunctionsList;
- ///
- /// Gets a unique hash code for a given
- ///
- /// The input instance to inspect
- [Pure]
- public static int GetHashCode(Action action)
- {
- int hashcode = action.Method.GetHashCode();
-
- foreach (FieldInfo fieldInfo in action.Method.DeclaringType.GetFields())
- {
- if (fieldInfo.FieldType.IsDelegate() &&
- fieldInfo.GetValue(action.Target) is Delegate func &&
- (func.Method.IsStatic || func.Method.DeclaringType.IsStatelessDelegateContainer()) &&
- (HlslKnownTypes.IsKnownScalarType(func.Method.ReturnType) || HlslKnownTypes.IsKnownVectorType(func.Method.ReturnType)) &&
- fieldInfo.FieldType.GenericTypeArguments.All(type => HlslKnownTypes.IsKnownScalarType(type) ||
- HlslKnownTypes.IsKnownVectorType(type)))
- {
- hashcode = unchecked(hashcode * 17 + func.Method.GetHashCode());
- }
- }
-
- return hashcode;
- }
-
///
/// Loads and processes an input
///
diff --git a/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs b/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs
new file mode 100644
index 00000000..bd0dfa99
--- /dev/null
+++ b/tests/ComputeSharp.Tests.Internals/ShaderHashCodeTests.cs
@@ -0,0 +1,54 @@
+using System;
+using ComputeSharp.Shaders.Translation;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+
+namespace ComputeSharp.Tests.Internals
+{
+ [TestClass]
+ [TestCategory("ShaderHashCodes")]
+ public class ShaderHashCodeTests
+ {
+ [TestMethod]
+ public void ShaderWithNoCapturedDelegates()
+ {
+ float value = 10;
+ using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1);
+
+ Action action1 = id => buffer[0] = value;
+
+ int
+ hash1 = ShaderHashCodeProvider.GetHashCode(action1),
+ hash2 = ShaderHashCodeProvider.GetHashCode(action1);
+
+ Assert.IsTrue(hash1 == hash2);
+
+ Action action2 = id => buffer[0] = value;
+
+ int hash3 = ShaderHashCodeProvider.GetHashCode(action2);
+
+ Assert.IsFalse(hash1 == hash3);
+ }
+
+ [TestMethod]
+ public void ShaderWithCapturedDelegates()
+ {
+ Func f = x => x * x;
+
+ using ReadWriteBuffer buffer = Gpu.Default.AllocateReadWriteBuffer(1);
+
+ Action action = id => buffer[0] = f(2);
+
+ int
+ hash1 = ShaderHashCodeProvider.GetHashCode(action),
+ hash2 = ShaderHashCodeProvider.GetHashCode(action);
+
+ Assert.IsTrue(hash1 == hash2);
+
+ f = x => x + 1;
+
+ int hash3 = ShaderHashCodeProvider.GetHashCode(action);
+
+ Assert.IsFalse(hash1 == hash3);
+ }
+ }
+}