xronos /Microsoft.Scripting/Interpretation/Interpreter.MatchCaller.cs

Language C# Lines 204
MD5 Hash 5dd2fa7af628e5b4200e9e09bd1275b0 Estimated Cost $3,095 (why?)
Repository https://bitbucket.org/stefanrusek/xronos View Raw File
  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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
/* ****************************************************************************
 *
 * Copyright (c) Microsoft Corporation. 
 *
 * This source code is subject to terms and conditions of the Microsoft Public License. A 
 * copy of the license can be found in the License.html file at the root of this distribution. If 
 * you cannot locate the  Microsoft Public License, please send an email to 
 * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound 
 * by the terms of the Microsoft Public License.
 *
 * You must not remove this notice, or any other, from this software.
 *
 *
 * ***************************************************************************/

#if CODEPLEX_40
using System;
#else
using System; using Microsoft;
#endif
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
#if !CODEPLEX_40
using Microsoft.Runtime.CompilerServices;
#endif

using System.Threading;
using Microsoft.Scripting.Generation;

namespace Microsoft.Scripting.Interpretation {
    public static partial class Interpreter {
        internal delegate object MatchCallerTarget(CallSite site, object[] args);

        /// <summary>
        /// MatchCaller allows to call match maker delegate with the signature (object, CallSite, object[])
        /// It is used by the call site cache lookup logic when searching for applicable rule.
        /// </summary>
        internal static class MatchCaller {
            public static object Target0(CallSite site, object[] args) {
                return ((CallSite<Func<CallSite, object>>)site).Target(site);
            }

            public static object Target1(CallSite site, object[] args) {
                return ((CallSite<Func<CallSite, object, object>>)site).Target(site, args[0]);
            }

            public static object Target2(CallSite site, object[] args) {
                return ((CallSite<Func<CallSite, object, object, object>>)site).Target(site, args[0], args[1]);
            }

            public static object Target3(CallSite site, object[] args) {
                return ((CallSite<Func<CallSite, object, object, object, object>>)site).Target(site, args[0], args[1], args[2]);
            }

            public static object Target4(CallSite site, object[] args) {
                return ((CallSite<Func<CallSite, object, object, object, object, object>>)site).Target(site, args[0], args[1], args[2], args[3]);
            }

            public static object Target5(CallSite site, object[] args) {
                return ((CallSite<Func<CallSite, object, object, object, object, object, object>>)site).Target(site, args[0], args[1], args[2], args[3], args[4]);
            }

            public static object Target6(CallSite site, object[] args) {
                return ((CallSite<Func<CallSite, object, object, object, object, object, object, object>>)site).Target(site, args[0], args[1], args[2], args[3], args[4], args[5]);
            }

            public static object Target7(CallSite site, object[] args) {
                return ((CallSite<Func<CallSite, object, object, object, object, object, object, object, object>>)site).Target(site, args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
            }

            public static object Target8(CallSite site, object[] args) {
                return ((CallSite<Func<CallSite, object, object, object, object, object, object, object, object, object>>)site).Target(site, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
            }

            public static object Target9(CallSite site, object[] args) {
                return ((CallSite<Func<CallSite, object, object, object, object, object, object, object, object, object, object>>)site).Target(site, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]);
            }

            private struct RefFixer {
                internal readonly LocalBuilder Temp;
                internal readonly int Index;

                internal RefFixer(LocalBuilder temp, int index) {
                    Temp = temp;
                    Index = index;
                }
            }

            // TODO: Should this really be Type -> WeakReference?
            // Issue #1, we'll end up growing the dictionary for each unique type
            // Issue #2, we'll lose the generated delegate in the first gen-0
            // collection.
            //
            // We probably need to replace this with an actual cache that holds
            // onto the delegates and ages them out.
            //
            private static readonly Dictionary<Type, MatchCallerTarget> _Callers = new Dictionary<Type, MatchCallerTarget>();
            private static readonly Type[] _CallerSignature = new Type[] { typeof(CallSite), typeof(object[]) };

            internal static MatchCallerTarget GetCaller(Type type) {
                MatchCallerTarget target;

                // LOCK to extract the weak reference with the updater DynamicMethod 
                lock (_Callers) {
                    if (!_Callers.TryGetValue(type, out target)) {
                        target = (MatchCallerTarget)CreateCaller(type);
                        _Callers[type] = target;
                    }
                }

                return target;
            }

            private static int _id;

            /// <summary>
            /// Uses LCG to create method such as this:
            /// 
            /// object MatchCaller(object target, CallSite site, object[] args) {
            ///      return ((ActualDelegateType)target)(site, args[0], args[1], args[2], ...);
            /// }
            /// 
            /// inserting appropriate casts and boxings as needed.
            /// </summary>
            /// <param name="type">Type of the delegate to call</param>
            /// <returns>A MatchCallerTarget delegate.</returns>
            private static object CreateCaller(Type type) {
                PerfTrack.NoteEvent(PerfTrack.Categories.Count, "Interpreter.MatchCaller.CreateCaller");
                
                MethodInfo invoke = type.GetMethod("Invoke");
                ParameterInfo[] parameters = invoke.GetParameters();

                var il = Snippets.Shared.CreateDynamicMethod("_istub_" + Interlocked.Increment(ref _id), typeof(object), _CallerSignature, false);
                Type siteType = typeof(CallSite<>).MakeGenericType(type);

                List<RefFixer> fixers = null;

                // Emit the call site and cast it to the right type
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Castclass, siteType);
                il.Emit(OpCodes.Ldfld, siteType.GetField("Target"));

                // CallSite
                il.Emit(OpCodes.Ldarg_0);

                // Arguments
                for (int i = 1; i < parameters.Length; i++) {
                    il.Emit(OpCodes.Ldarg_1);
                    il.Emit(OpCodes.Ldc_I4, i - 1);
                    il.Emit(OpCodes.Ldelem_Ref);
                    Type pt = parameters[i].ParameterType;
                    if (pt.IsByRef) {
                        RefFixer rf = new RefFixer(il.DeclareLocal(pt.GetElementType()), i - 1);
                        if (rf.Temp.LocalType.IsValueType) {
                            il.Emit(OpCodes.Unbox_Any, rf.Temp.LocalType);
                        } else if (rf.Temp.LocalType != typeof(object)) {
                            il.Emit(OpCodes.Castclass, rf.Temp.LocalType);
                        }
                        il.Emit(OpCodes.Stloc, rf.Temp);
                        il.Emit(OpCodes.Ldloca, rf.Temp);

                        if (fixers == null) {
                            fixers = new List<RefFixer>();
                        }
                        fixers.Add(rf);
                    } else if (pt.IsValueType) {
                        il.Emit(OpCodes.Unbox_Any, pt);
                    } else if (pt != typeof(object)) {
                        il.Emit(OpCodes.Castclass, pt);
                    }
                }

                // Call the delegate
                il.Emit(OpCodes.Callvirt, invoke);

                // Propagate the ref parameters back into the array.
                if (fixers != null) {
                    foreach (RefFixer rf in fixers) {
                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Ldc_I4, rf.Index);
                        il.Emit(OpCodes.Ldloc, rf.Temp);
                        if (rf.Temp.LocalType.IsValueType) {
                            il.Emit(OpCodes.Box, rf.Temp.LocalType);
                        }
                        il.Emit(OpCodes.Stelem_Ref);
                    }
                }

                // Return value
                if (invoke.ReturnType == typeof(void)) {
                    il.Emit(OpCodes.Ldnull);
                } else if (invoke.ReturnType.IsValueType) {
                    il.Emit(OpCodes.Box, invoke.ReturnType);
                }

                il.Emit(OpCodes.Ret);
                return il.CreateDelegate<MatchCallerTarget>();
            }
        }
    }
}
Back to Top