Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ILProvider.cs « IL « TypeSystem « src « Common « src - github.com/mono/corert.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: eb1747beb692aa457ee6e94a4d536ec6f78ed7e6 (plain)
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;

using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;

using Internal.IL.Stubs;

using Debug = System.Diagnostics.Debug;

namespace Internal.IL
{
    internal sealed class ILProvider : LockFreeReaderHashtable<MethodDesc, ILProvider.MethodILData>
    {
        private PInvokeILProvider _pinvokeILProvider;

        public ILProvider(PInvokeILProvider pinvokeILProvider)
        {
            _pinvokeILProvider = pinvokeILProvider;
        }

        private MethodIL TryGetRuntimeImplementedMethodIL(MethodDesc method)
        {
            // Provides method bodies for runtime implemented methods. It can return null for
            // methods that are treated specially by the codegen.

            Debug.Assert(method.IsRuntimeImplemented);

            TypeDesc owningType = method.OwningType;

            if (owningType.IsDelegate)
            {
                return DelegateMethodILEmitter.EmitIL(method);
            }

            return null;
        }

        /// <summary>
        /// Provides method bodies for intrinsics recognized by the compiler.
        /// It can return null if it's not an intrinsic recognized by the compiler,
        /// but an intrinsic e.g. recognized by codegen.
        /// </summary>
        private MethodIL TryGetIntrinsicMethodIL(MethodDesc method)
        {
            Debug.Assert(method.IsIntrinsic);

            MetadataType owningType = method.OwningType as MetadataType;
            if (owningType == null)
                return null;

            switch (owningType.Name)
            {
                case "Unsafe":
                    {
                        if (owningType.Namespace == "Internal.Runtime.CompilerServices")
                            return UnsafeIntrinsics.EmitIL(method);
                    }
                    break;
                case "Debug":
                    {
                        if (owningType.Namespace == "System.Diagnostics" && method.Name == "DebugBreak")
                            return new ILStubMethodIL(method, new byte[] { (byte)ILOpcode.break_, (byte)ILOpcode.ret }, Array.Empty<LocalVariableDefinition>(), null);
                    }
                    break;
                case "EETypePtr":
                    {
                        if (owningType.Namespace == "System" && method.Name == "EETypePtrOf")
                            return EETypePtrOfIntrinsic.EmitIL(method);
                    }
                    break;
                case "RuntimeAugments":
                    {
                        if (owningType.Namespace == "Internal.Runtime.Augments" && method.Name == "GetCanonType")
                            return GetCanonTypeIntrinsic.EmitIL(method);
                    }
                    break;
                case "EEType":
                    {
                        if (owningType.Namespace == "Internal.Runtime" && method.Name == "get_SupportsRelativePointers")
                        {
                            ILOpcode value = method.Context.Target.SupportsRelativePointers ?
                                ILOpcode.ldc_i4_1 : ILOpcode.ldc_i4_0;
                            return new ILStubMethodIL(method, new byte[] { (byte)value, (byte)ILOpcode.ret }, Array.Empty<LocalVariableDefinition>(), null);
                        }
                    }
                    break;
            }

            return null;
        }

        /// <summary>
        /// Provides method bodies for intrinsics recognized by the compiler that
        /// are specialized per instantiation. It can return null if the intrinsic
        /// is not recognized.
        /// </summary>
        private MethodIL TryGetPerInstantiationIntrinsicMethodIL(MethodDesc method)
        {
            Debug.Assert(method.IsIntrinsic);

            MetadataType owningType = method.OwningType.GetTypeDefinition() as MetadataType;
            if (owningType == null)
                return null;

            string methodName = method.Name;

            switch (owningType.Name)
            {
                case "RuntimeHelpers":
                    {
                        if ((methodName == "IsReferenceOrContainsReferences" || methodName == "IsReference")
                            && owningType.Namespace == "System.Runtime.CompilerServices")
                        {
                            TypeDesc elementType = method.Instantiation[0];

                            // Fallback to non-intrinsic implementation for universal generics
                            if (elementType.IsCanonicalSubtype(CanonicalFormKind.Universal))
                                return null;

                            bool result = elementType.IsGCPointer;
                            if (methodName == "IsReferenceOrContainsReferences")
                            {
                                result |= (elementType.IsDefType ? ((DefType)elementType).ContainsGCPointers : false);
                            }

                            return new ILStubMethodIL(method, new byte[] {
                                    result ? (byte)ILOpcode.ldc_i4_1 : (byte)ILOpcode.ldc_i4_0,
                                    (byte)ILOpcode.ret }, 
                                Array.Empty<LocalVariableDefinition>(), null);
                        }
                    }
                    break;
                case "Comparer`1":
                    {
                        if (methodName == "Create" && owningType.Namespace == "System.Collections.Generic")
                            return ComparerIntrinsics.EmitComparerCreate(method);
                    }
                    break;
                case "EqualityComparer`1":
                    {
                        if (methodName == "Create" && owningType.Namespace == "System.Collections.Generic")
                            return ComparerIntrinsics.EmitEqualityComparerCreate(method);
                    }
                    break;
                case "EqualityComparerHelpers":
                    {
                        if (owningType.Namespace != "Internal.IntrinsicSupport")
                            return null;

                        if (methodName == "EnumOnlyEquals")
                        {
                            // EnumOnlyEquals would basically like to do this:
                            // static bool EnumOnlyEquals<T>(T x, T y) where T: struct => x == y;
                            // This is not legal though.
                            // We don't want to do this:
                            // static bool EnumOnlyEquals<T>(T x, T y) where T: struct => x.Equals(y);
                            // Because it would box y.
                            // So we resort to some per-instantiation magic.

                            TypeDesc elementType = method.Instantiation[0];
                            if (!elementType.IsEnum)
                                return null;

                            ILOpcode convInstruction;
                            if (((DefType)elementType).InstanceFieldSize.AsInt <= 4)
                            {
                                convInstruction = ILOpcode.conv_i4;
                            }
                            else
                            {
                                Debug.Assert(((DefType)elementType).InstanceFieldSize.AsInt == 8);
                                convInstruction = ILOpcode.conv_i8;
                            }

                            return new ILStubMethodIL(method, new byte[] {
                                (byte)ILOpcode.ldarg_0,
                                (byte)convInstruction,
                                (byte)ILOpcode.ldarg_1,
                                (byte)convInstruction,
                                (byte)ILOpcode.prefix1, unchecked((byte)ILOpcode.ceq),
                                (byte)ILOpcode.ret,
                            },
                            Array.Empty<LocalVariableDefinition>(), null);
                        }
                        else if (methodName == "GetComparerForReferenceTypesOnly")
                        {
                            TypeDesc elementType = method.Instantiation[0];
                            if (!elementType.IsRuntimeDeterminedSubtype
                                && !elementType.IsCanonicalSubtype(CanonicalFormKind.Any)
                                && !elementType.IsGCPointer)
                            {
                                return new ILStubMethodIL(method, new byte[] {
                                    (byte)ILOpcode.ldnull,
                                    (byte)ILOpcode.ret
                                },
                                Array.Empty<LocalVariableDefinition>(), null);
                            }
                        }
                        else if (methodName == "StructOnlyEquals")
                        {
                            TypeDesc elementType = method.Instantiation[0];
                            if (!elementType.IsRuntimeDeterminedSubtype
                                && !elementType.IsCanonicalSubtype(CanonicalFormKind.Any)
                                && !elementType.IsGCPointer)
                            {
                                Debug.Assert(elementType.IsValueType);

                                TypeSystemContext context = elementType.Context;
                                MetadataType helperType = context.SystemModule.GetKnownType("Internal.IntrinsicSupport", "EqualityComparerHelpers");

                                MethodDesc methodToCall;
                                if (elementType.IsEnum)
                                {
                                    methodToCall = helperType.GetKnownMethod("EnumOnlyEquals", null).MakeInstantiatedMethod(elementType);
                                }
                                else if (elementType.IsNullable && ComparerIntrinsics.ImplementsIEquatable(elementType.Instantiation[0]))
                                {
                                    methodToCall = helperType.GetKnownMethod("StructOnlyEqualsNullable", null).MakeInstantiatedMethod(elementType.Instantiation[0]);
                                }
                                else if (ComparerIntrinsics.ImplementsIEquatable(elementType))
                                {
                                    methodToCall = helperType.GetKnownMethod("StructOnlyEqualsIEquatable", null).MakeInstantiatedMethod(elementType);
                                }
                                else
                                {
                                    methodToCall = helperType.GetKnownMethod("StructOnlyNormalEquals", null).MakeInstantiatedMethod(elementType);
                                }

                                return new ILStubMethodIL(method, new byte[]
                                {
                                    (byte)ILOpcode.ldarg_0,
                                    (byte)ILOpcode.ldarg_1,
                                    (byte)ILOpcode.call, 1, 0, 0, 0,
                                    (byte)ILOpcode.ret
                                },
                                Array.Empty<LocalVariableDefinition>(), new object[] { methodToCall });
                            }
                        }
                    }
                    break;
            }

            return null;
        }

        private MethodIL CreateMethodIL(MethodDesc method)
        {
            if (method is EcmaMethod)
            {
                // TODO: Workaround: we should special case methods with Intrinsic attribute, but since
                //       CoreLib source is still not in the repo, we have to work with what we have, which is
                //       an MCG attribute on the type itself...
                if (((MetadataType)method.OwningType).HasCustomAttribute("System.Runtime.InteropServices", "McgIntrinsicsAttribute"))
                {
                    var name = method.Name;
                    if (name == "Call" || name.StartsWith("StdCall"))
                    {
                        return CalliIntrinsic.EmitIL(method);
                    }
                    else
                    if (name == "AddrOf")
                    {
                        return AddrOfIntrinsic.EmitIL(method);
                    }
                }

                if (method.IsIntrinsic)
                {
                    MethodIL result = TryGetIntrinsicMethodIL(method);
                    if (result != null)
                        return result;
                }

                if (method.IsPInvoke)
                {
                    var pregenerated = McgInteropSupport.TryGetPregeneratedPInvoke(method);
                    if (pregenerated == null)
                        return _pinvokeILProvider.EmitIL(method);
                    method = pregenerated;
                }

                if (method.IsRuntimeImplemented)
                {
                    MethodIL result = TryGetRuntimeImplementedMethodIL(method);
                    if (result != null)
                        return result;
                }

                MethodIL methodIL = EcmaMethodIL.Create((EcmaMethod)method);
                if (methodIL != null)
                    return methodIL;

                return null;
            }
            else
            if (method is MethodForInstantiatedType || method is InstantiatedMethod)
            {
                // Intrinsics specialized per instantiation
                if (method.IsIntrinsic)
                {
                    MethodIL methodIL = TryGetPerInstantiationIntrinsicMethodIL(method);
                    if (methodIL != null)
                        return methodIL;
                }

                var methodDefinitionIL = GetMethodIL(method.GetTypicalMethodDefinition());
                if (methodDefinitionIL == null)
                    return null;
                return new InstantiatedMethodIL(method, methodDefinitionIL);
            }
            else
            if (method is ILStubMethod)
            {
                return ((ILStubMethod)method).EmitIL();
            }
            else
            if (method is ArrayMethod)
            {
                return ArrayMethodILEmitter.EmitIL((ArrayMethod)method);
            }
            else
            {
                Debug.Assert(!(method is PInvokeTargetNativeMethod), "Who is asking for IL of PInvokeTargetNativeMethod?");
                return null;
            }
        }

        internal class MethodILData
        {
            public MethodDesc Method;
            public MethodIL MethodIL;
        }
        protected override int GetKeyHashCode(MethodDesc key)
        {
            return key.GetHashCode();
        }
        protected override int GetValueHashCode(MethodILData value)
        {
            return value.Method.GetHashCode();
        }
        protected override bool CompareKeyToValue(MethodDesc key, MethodILData value)
        {
            return Object.ReferenceEquals(key, value.Method);
        }
        protected override bool CompareValueToValue(MethodILData value1, MethodILData value2)
        {
            return Object.ReferenceEquals(value1.Method, value2.Method);
        }
        protected override MethodILData CreateValueFromKey(MethodDesc key)
        {
            return new MethodILData() { Method = key, MethodIL = CreateMethodIL(key) };
        }

        public MethodIL GetMethodIL(MethodDesc method)
        {
            return GetOrCreateValue(method).MethodIL;
        }
    }
}