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 ///