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

RyuJitExecutionStrategy.cs « JitSupport « Runtime « Internal « src « System.Private.Jit « src - github.com/mono/corert.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 9548f2f08c4d8b54aea24b17c3428e210cfa4e07 (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
// 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 System.Runtime;
using System.Collections.Generic;
using System.Runtime.InteropServices;

using Internal.JitInterface;
using Internal.Runtime.Augments;
using Internal.Runtime.TypeLoader;
using Internal.TypeSystem;

using ILCompiler;
using ILCompiler.DependencyAnalysisFramework;
using ILCompiler.DependencyAnalysis;

using Debug = System.Diagnostics.Debug;

namespace Internal.Runtime.JitSupport
{
    public class RyuJitExecutionStrategy : MethodExecutionStrategy
    {
        private const string NativeJitSupportLibrary = "*";

        private CorInfoImpl _corInfoImpl;
        private TypeSystemContext _context;
        private NodeFactory _nodeFactory;

        private void UpdateBytesUsed(ObjectNode.ObjectData nodeData, ref int bytesUsed)
        {
            bytesUsed = bytesUsed.AlignUp(nodeData.Alignment);
            bytesUsed += nodeData.Data.Length;
            return;
        }

        [DllImport(NativeJitSupportLibrary)]
        static extern IntPtr AllocJittedCode(UInt32 cbCode, UInt32 align, out IntPtr pCodeManager);

        [DllImport(NativeJitSupportLibrary)]
        static extern void SetEHInfoPtr(IntPtr pCodeManager, IntPtr pbCode, IntPtr ehInfo);

        [DllImport(NativeJitSupportLibrary)]
        static extern unsafe IntPtr PublishRuntimeFunction(
            IntPtr pCodeManager,
            IntPtr pbCode,
            IntPtr pMainRuntimeFunction,
            UInt32 startOffset,
            UInt32 endOffset,
            byte[] pUnwindInfo,
            UInt32 cbUnwindInfo,
            byte[] pGCData,
            UInt32 cbGCData);

        [DllImport(NativeJitSupportLibrary)]
        static extern void UpdateRuntimeFunctionTable(IntPtr pCodeManager);

        [DllImport(NativeJitSupportLibrary)]
        static extern void InitJitCodeManager(IntPtr mrtModule);

        public override IntPtr OnEntryPoint(MethodEntrypointPtr methodEntrypoint, IntPtr callerArgs)
        {
            lock (this)
            {
                if (_corInfoImpl == null)
                {
                    InitJitCodeManager(RuntimeAugments.RhGetOSModuleForMrt ());

                    // TODO: Recycle jit interface object and TypeSystemContext
                    _context = TypeSystemContextFactory.Create();

                    Compilation compilation = new Compilation(_context);
                    _nodeFactory = compilation.NodeFactory;

                    JitConfigProvider configProvider = new JitConfigProvider(new CorJitFlag[] { CorJitFlag.CORJIT_FLAG_DEBUG_CODE }, Array.Empty<KeyValuePair<string, string>>());

                    _corInfoImpl = new CorInfoImpl(compilation, configProvider);
                }

                MethodDesc methodToCompile = methodEntrypoint.MethodIdentifier.ToMethodDesc(_context);

                JitMethodCodeNode codeNode = new JitMethodCodeNode(methodToCompile);
                _corInfoImpl.CompileMethod(codeNode);

                ObjectNode.ObjectData codeData = codeNode.GetData(null, false);

                List<ObjectNode> nodesToEmit = new List<ObjectNode>();
                Dictionary<DependencyNodeCore<NodeFactory>, object> relocTargets = new Dictionary<DependencyNodeCore<NodeFactory>, object>();
                int totalAllocSizeNeeded = 0;
                int nonObjectRelocTargets = 0;

                nodesToEmit.Add(codeNode);
                UpdateBytesUsed(codeNode.GetData(_nodeFactory), ref totalAllocSizeNeeded);

                int offsetOfEHData = totalAllocSizeNeeded;

                if (codeNode.EHInfo != null)
                {
                    Debug.Assert(codeNode.EHInfo.Alignment == 1); // Assert needed as otherwise offsetOfEHData will be wrong

                    UpdateBytesUsed(codeNode.EHInfo, ref totalAllocSizeNeeded);
                    ComputeDependencySizeAndRelocData(codeNode.EHInfo, relocTargets, nodesToEmit, ref totalAllocSizeNeeded, ref nonObjectRelocTargets);
                }

                for (int i = 0; i < nodesToEmit.Count; i++)
                {
                    ObjectNode objNode = nodesToEmit[i];
                    ComputeDependencySizeAndRelocData(objNode.GetData(_nodeFactory, true), relocTargets, nodesToEmit, ref totalAllocSizeNeeded, ref nonObjectRelocTargets);
                }

                if (nonObjectRelocTargets != 0)
                {
                    totalAllocSizeNeeded = totalAllocSizeNeeded.AlignUp(IntPtr.Size);
                }

                int relocTargetOffsetStart = totalAllocSizeNeeded;

                DependencyNodeCore<NodeFactory>[] relocTargetsArray = new DependencyNodeCore<NodeFactory>[nonObjectRelocTargets];
                {
                    int iRelocTarget = 0;
                    foreach (var relocTarget in relocTargets)
                    {
                        if (!(relocTarget.Key is ObjectNode))
                        {
                            relocTargetsArray[iRelocTarget] = relocTarget.Key;
                            totalAllocSizeNeeded += IntPtr.Size;
                            iRelocTarget++;
                        }
                    }
                    Debug.Assert(iRelocTarget == nonObjectRelocTargets);
                }

                GenericDictionaryCell[] genDictCells = new GenericDictionaryCell[relocTargetsArray.Length];
                for (int iRelocTarget = 0; iRelocTarget < relocTargetsArray.Length; iRelocTarget++)
                {
                    DependencyNodeCore<NodeFactory> relocTarget = relocTargetsArray[iRelocTarget];
                    GenericDictionaryCell newCell = null;

                    if (relocTarget is ExternObjectSymbolNode)
                    {
                        var externObjectSymbolNode = (ExternObjectSymbolNode)relocTarget;
                        var newMethodCell = externObjectSymbolNode.GetDictionaryCell();
                        newCell = newMethodCell;
                    }

                    if (newCell == null)
                    {
                        Environment.FailFast("Unknown reloc target type");
                    }
                    genDictCells[iRelocTarget] = newCell;
                }

                IntPtr[] relocTargetsAsIntPtr = null;

                TypeLoaderEnvironment.Instance.RunUnderTypeLoaderLock(
                    () =>
                    {
                        TypeBuilderApi.ResolveMultipleCells(genDictCells, out relocTargetsAsIntPtr);
                    });

                // Layout of allocated memory...
                // ObjectNodes (aligned as appropriate)
                IntPtr pCodeManager;
                IntPtr jittedCode = AllocJittedCode(checked((uint)totalAllocSizeNeeded), 8/* TODO, alignment calculation */, out pCodeManager);
                int currentOffset = 0;

                foreach (var node in nodesToEmit)
                {
                    ObjectNode.ObjectData objectData = node.GetData(_nodeFactory);
                    EmitAndRelocData(objectData, jittedCode, relocTargetOffsetStart, ref currentOffset, relocTargetsArray, relocTargetsAsIntPtr);

                    // EHInfo doesn't get its own node, but it does get emitted into the stream.
                    if ((node == codeNode) && (codeNode.EHInfo != null))
                    {
                        Debug.Assert(offsetOfEHData == currentOffset);
                        EmitAndRelocData(codeNode.EHInfo, jittedCode, relocTargetOffsetStart, ref currentOffset, relocTargetsArray, relocTargetsAsIntPtr);
                    }
                }

                foreach (IntPtr ptr in relocTargetsAsIntPtr)
                {
                    currentOffset = currentOffset.AlignUp(IntPtr.Size);
                    Marshal.WriteIntPtr(jittedCode, currentOffset, ptr);
                    currentOffset += IntPtr.Size;
                }

                SetEHInfoPtr(pCodeManager, jittedCode, jittedCode + offsetOfEHData);

                IntPtr mainRuntimeFunction = IntPtr.Zero;

                for (int i = 0; i < codeNode.FrameInfos.Length; i++)
                {
                    FrameInfo frame = codeNode.FrameInfos[i];
                    byte[] frameData = frame.BlobData;
                    byte[] gcInfoData = Array.Empty<byte>();
                    byte[] gcInfoDataDeref = frameData;

                    if (i == 0)
                    {
                        // For main function, add the gc info to the data
                        gcInfoDataDeref = gcInfoData = codeNode.GCInfo;
                    }

                    IntPtr publishedFunction = PublishRuntimeFunction(pCodeManager,
                                    jittedCode,
                                    mainRuntimeFunction,
                                    checked((uint)frame.StartOffset),
                                    checked((uint)frame.EndOffset),
                                    frameData,
                                    checked((uint)frameData.Length),
                                    gcInfoDataDeref,
                                    checked((uint)gcInfoData.Length));

                    if (i == 0)
                    {
                        mainRuntimeFunction = publishedFunction;
                    }
                }

                if (mainRuntimeFunction != IntPtr.Zero)
                {
                    UpdateRuntimeFunctionTable(pCodeManager);
                }

                methodEntrypoint.MethodCode = jittedCode;

                return jittedCode;
            }
        }

        void ComputeDependencySizeAndRelocData(ObjectNode.ObjectData objectData, Dictionary<DependencyNodeCore<NodeFactory>, object> relocTargets, List<ObjectNode> nodesToEmit, ref int totalAllocSizeNeeded, ref int nonObjectRelocTargets)
        {
            foreach (var reloc in objectData.Relocs)
            {
                DependencyNodeCore<NodeFactory> relocTargetAsNode = (DependencyNodeCore<NodeFactory>)reloc.Target;

                if (!relocTargets.ContainsKey(relocTargetAsNode))
                {
                    relocTargets.Add(relocTargetAsNode, null);
                    ObjectNode relocTargetObjectNode = relocTargetAsNode as ObjectNode;
                    if (relocTargetObjectNode != null)
                    {
                        UpdateBytesUsed(relocTargetObjectNode.GetData(_nodeFactory), ref totalAllocSizeNeeded);
                        nodesToEmit.Add(relocTargetObjectNode);
                    }
                    else
                    {
                        nonObjectRelocTargets++;
                    }
                }
            }
        }

        void EmitAndRelocData(ObjectNode.ObjectData objectData, IntPtr jittedCode, int relocTargetOffsetStart, ref int currentOffset, DependencyNodeCore<NodeFactory>[] relocTargetsArray, IntPtr[] relocTargetsAsIntPtr)
        {
            currentOffset = currentOffset.AlignUp(objectData.Alignment);
            Marshal.Copy(objectData.Data, 0, jittedCode + currentOffset, objectData.Data.Length);
            foreach (Relocation reloc in objectData.Relocs)
            {
                switch (reloc.RelocType)
                {
                    case RelocType.IMAGE_REL_BASED_REL32:
                        // 4 byte offset from current pointer to target
                        // ADD ROUTINE TO FIND Relocation
                        for (int i = 0; i < relocTargetsArray.Length; i++)
                        {
                            if (relocTargetsArray[i] == reloc.Target)
                            {
                                int relocTargetAddressOffset = relocTargetOffsetStart + i * IntPtr.Size;
                                int relocAddressOffset = currentOffset + reloc.Offset;

                                int relocTargetAddressDelta = relocTargetAddressOffset - relocAddressOffset - 4;
                                Marshal.WriteInt32(jittedCode, relocAddressOffset, relocTargetAddressDelta);
                                break;
                            }
                        }
                        break;

                    default:
                        Environment.FailFast("Unknown RelocType");
                        break;
                }
            }

            currentOffset += objectData.Data.Length;
        }
    }
}