Repository navigation
Expand file tree
/
Copy pathDirectILKernelGenerator.Scalar.cs
More file actions
160 lines (136 loc) · 6.04 KB
/
Copy pathDirectILKernelGenerator.Scalar.cs
File metadata and controls
160 lines (136 loc) · 6.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Intrinsics;
// =============================================================================
// DirectILKernelGenerator.Scalar.cs - Scalar Kernel Delegates
// =============================================================================
//
// RESPONSIBILITY:
// - Unary scalar kernels: Func<TInput, TOutput>
// - Binary scalar kernels: Func<TLhs, TRhs, TResult>
// - Used for single-value operations in broadcasting
//
// =============================================================================
namespace NumSharp.Backends.Kernels
{
public static partial class DirectILKernelGenerator
{
#region Scalar Kernel Generation
/// <summary>
/// Cache for unary scalar kernels.
/// Key: UnaryScalarKernelKey (InputType, OutputType, Op)
/// Value: Delegate (Func<TInput, TOutput>)
/// </summary>
internal static readonly ConcurrentDictionary<UnaryScalarKernelKey, Delegate> _unaryScalarCache = new();
/// <summary>
/// Cache for binary scalar kernels.
/// Key: BinaryScalarKernelKey (LhsType, RhsType, ResultType, Op)
/// Value: Delegate (Func<TLhs, TRhs, TResult>)
/// </summary>
internal static readonly ConcurrentDictionary<BinaryScalarKernelKey, Delegate> _binaryScalarCache = new();
/// <summary>
/// Get or generate an IL-based unary scalar delegate.
/// Returns a Func<TInput, TOutput> delegate.
/// </summary>
public static Delegate GetUnaryScalarDelegate(UnaryScalarKernelKey key)
{
if (!Enabled)
throw new InvalidOperationException("IL generation is disabled");
return _unaryScalarCache.GetOrAdd(key, GenerateUnaryScalarDelegate);
}
/// <summary>
/// Get or generate an IL-based binary scalar delegate.
/// Returns a Func<TLhs, TRhs, TResult> delegate.
/// </summary>
public static Delegate GetBinaryScalarDelegate(BinaryScalarKernelKey key)
{
if (!Enabled)
throw new InvalidOperationException("IL generation is disabled");
return _binaryScalarCache.GetOrAdd(key, GenerateBinaryScalarDelegate);
}
/// <summary>
/// Generate an IL-based unary scalar delegate.
/// Creates a Func<TInput, TOutput> that performs the operation.
/// </summary>
private static Delegate GenerateUnaryScalarDelegate(UnaryScalarKernelKey key)
{
var inputClr = GetClrType(key.InputType);
var outputClr = GetClrType(key.OutputType);
// Create DynamicMethod: TOutput Method(TInput input)
var dm = new DynamicMethod(
name: $"ScalarUnary_{key}",
returnType: outputClr,
parameterTypes: new[] { inputClr },
owner: typeof(DirectILKernelGenerator),
skipVisibility: true
);
var il = dm.GetILGenerator();
// Load input argument
il.Emit(OpCodes.Ldarg_0);
// For predicate operations (IsFinite, IsNan, IsInf), operate on INPUT type
// and the operation itself produces bool. For other ops, convert first.
if (IsPredicateOp(key.Op))
{
// Perform operation on input type - produces bool
EmitUnaryScalarOperation(il, key.Op, key.InputType);
}
else if (key.Op == UnaryOp.Abs && key.InputType == NPTypeCode.Complex)
{
// Special case: Complex abs returns magnitude (double), not Real part
// NumPy: np.abs(complex) returns float64
il.EmitCall(OpCodes.Call, CachedMethods.ComplexAbs, null);
if (key.OutputType != NPTypeCode.Double)
EmitConvertTo(il, NPTypeCode.Double, key.OutputType);
}
else
{
// Convert to output type if different
EmitConvertTo(il, key.InputType, key.OutputType);
// Perform the unary operation (result is on stack)
EmitUnaryScalarOperation(il, key.Op, key.OutputType);
}
// Return
il.Emit(OpCodes.Ret);
// Create typed Func<TInput, TOutput>
var funcType = typeof(Func<,>).MakeGenericType(inputClr, outputClr);
return dm.CreateDelegate(funcType);
}
/// <summary>
/// Generate an IL-based binary scalar delegate.
/// Creates a Func<TLhs, TRhs, TResult> that performs the operation.
/// </summary>
private static Delegate GenerateBinaryScalarDelegate(BinaryScalarKernelKey key)
{
var lhsClr = GetClrType(key.LhsType);
var rhsClr = GetClrType(key.RhsType);
var resultClr = GetClrType(key.ResultType);
// Create DynamicMethod: TResult Method(TLhs lhs, TRhs rhs)
var dm = new DynamicMethod(
name: $"ScalarBinary_{key}",
returnType: resultClr,
parameterTypes: new[] { lhsClr, rhsClr },
owner: typeof(DirectILKernelGenerator),
skipVisibility: true
);
var il = dm.GetILGenerator();
// Load lhs, convert to result type
il.Emit(OpCodes.Ldarg_0);
EmitConvertTo(il, key.LhsType, key.ResultType);
// Load rhs, convert to result type
il.Emit(OpCodes.Ldarg_1);
EmitConvertTo(il, key.RhsType, key.ResultType);
// Perform binary operation
EmitScalarOperation(il, key.Op, key.ResultType);
// Return
il.Emit(OpCodes.Ret);
// Create typed Func<TLhs, TRhs, TResult>
var funcType = typeof(Func<,,>).MakeGenericType(lhsClr, rhsClr, resultClr);
return dm.CreateDelegate(funcType);
}
#endregion
}
}