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

UtcNodeFactory.cs « DependencyAnalysis « Compiler « src « ILCompiler.Compiler « src - github.com/mono/corert.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 80aec11b0b39f36bdc432e3fe6d0a922134792ff (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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
// 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.Collections.Generic;
using System.Diagnostics;
using System.IO;

using ILCompiler.DependencyAnalysis;
using ILCompiler.DependencyAnalysisFramework;
using Internal.Runtime;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;

namespace ILCompiler
{
    public class UtcNodeFactory : NodeFactory
    {
        public static string CompilationUnitPrefix = "";
        public string targetPrefix;
        private bool buildMRT;

        private static byte[] ReadBytesFromFile(string filename)
        {
            using (FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                int fileLen = checked((int)file.Length);
                int fileLenRemaining = fileLen;
                int curPos = 0;
                byte[] returnValue = new byte[fileLen];
                while (fileLenRemaining > 0)
                {
                    // Read may return anything from 0 to 10.
                    int n = file.Read(returnValue, curPos, fileLenRemaining);

                    // Unexpected end of file
                    if (n == 0)
                        throw new IOException();

                    curPos += n;
                    fileLenRemaining -= n;
                }

                return returnValue;
            }
        }

        private static ModuleDesc FindMetadataDescribingModuleInInputSet(IEnumerable<ModuleDesc> inputModules)
        {
            foreach (ModuleDesc module in inputModules)
            {
                if (PrecomputedMetadataManager.ModuleHasMetadataMappings(module))
                {
                    return module;
                }
            }

            return null;
        }

        private static MetadataManager PickMetadataManager(CompilerTypeSystemContext context, CompilationModuleGroup compilationModuleGroup, IEnumerable<ModuleDesc> inputModules, IEnumerable<ModuleDesc> inputMetadataOnlyAssemblies, string metadataFile, bool emitStackTraceMetadata, bool disableExceptionMessages, bool disableInvokeThunks)
        {
            if (metadataFile == null)
            {
                return new EmptyMetadataManager(context);
            }
            else
            {
                // Set Policies according to passed arguments
                StackTraceEmissionPolicy stackTraceEmissionPolicy;
                if (emitStackTraceMetadata)
                {
                    stackTraceEmissionPolicy = new UtcStackTraceEmissionPolicy();
                }
                else
                {
                    stackTraceEmissionPolicy = new NoStackTraceEmissionPolicy();
                }

                ManifestResourceBlockingPolicy resourceBlockingPolicy;
                if (disableExceptionMessages)
                {
                    resourceBlockingPolicy = new FrameworkStringResourceBlockingPolicy();
                }
                else
                {
                    resourceBlockingPolicy = new NoManifestResourceBlockingPolicy();
                }

                return new PrecomputedMetadataManager(compilationModuleGroup, context, FindMetadataDescribingModuleInInputSet(inputModules), inputModules, inputMetadataOnlyAssemblies, ReadBytesFromFile(metadataFile), stackTraceEmissionPolicy , resourceBlockingPolicy, disableInvokeThunks);
            }
        }

        private static InteropStubManager NewEmptyInteropStubManager(CompilerTypeSystemContext context, CompilationModuleGroup compilationModuleGroup)
        {
            // On Project N, the compiler doesn't generate the interop code on the fly
            return new EmptyInteropStubManager(compilationModuleGroup, context, null);
        }

        public UtcNodeFactory(
            CompilerTypeSystemContext context, 
            CompilationModuleGroup compilationModuleGroup, 
            IEnumerable<ModuleDesc> inputModules, 
            IEnumerable<ModuleDesc> inputMetadataOnlyAssemblies, 
            string metadataFile, 
            string outputFile, 
            UTCNameMangler nameMangler, 
            bool buildMRT, 
            bool emitStackTraceMetadata,
            bool disableExceptionMessages,
            bool allowInvokeThunks,
            DictionaryLayoutProvider dictionaryLayoutProvider,
            ImportedNodeProvider importedNodeProvider) 
            : base(context, 
                  compilationModuleGroup, 
                  PickMetadataManager(context, compilationModuleGroup, inputModules, inputMetadataOnlyAssemblies, metadataFile, emitStackTraceMetadata, disableExceptionMessages, allowInvokeThunks),
                  NewEmptyInteropStubManager(context, compilationModuleGroup), 
                  nameMangler, 
                  new AttributeDrivenLazyGenericsPolicy(), 
                  null, 
                  dictionaryLayoutProvider,
                  importedNodeProvider)
        {
            CreateHostedNodeCaches();
            CompilationUnitPrefix = nameMangler.CompilationUnitPrefix;
            ThreadStaticsIndex = new ThreadStaticsIndexNode(nameMangler.GetCurrentModuleTlsIndexPrefix());
            targetPrefix = context.Target.Architecture == TargetArchitecture.X86 ? "_" : "";
            TLSDirectory = new ThreadStaticsDirectoryNode(targetPrefix);
            TlsStart = new ExternSymbolNode(targetPrefix + "_tls_start");
            TlsEnd = new ExternSymbolNode(targetPrefix + "_tls_end");
            LoopHijackFlag = new LoopHijackFlagNode();
            this.buildMRT = buildMRT;
        }

        private void CreateHostedNodeCaches()
        {
            _GCStaticDescs = new NodeCache<MetadataType, GCStaticDescNode>((MetadataType type) =>
            {
                return new GCStaticDescNode(type, false);
            });

            _threadStaticGCStaticDescs = new NodeCache<MetadataType, GCStaticDescNode>((MetadataType type) =>
            {
                return new GCStaticDescNode(type, true);
            });

            _threadStaticsOffset = new NodeCache<MetadataType, ISortableSymbolNode>((MetadataType type) =>
            {
                if (CompilationModuleGroup.ContainsType(type) && !(CompilationModuleGroup.ShouldReferenceThroughImportTable(type)))
                {
                    return new ThreadStaticsOffsetNode(type, this);
                }
                else
                {
                    return _importedNodeProvider.ImportedThreadStaticOffsetNode(this, type);
                }
            });

            _importedThreadStaticsIndices = new NodeCache<MetadataType, ImportedThreadStaticsIndexNode>((MetadataType type) =>
            {
                return new ImportedThreadStaticsIndexNode(this);
            });

            _nonExternMethodSymbols = new NodeCache<MethodKey, NonExternMethodSymbolNode>((MethodKey method) =>
            {
                return new NonExternMethodSymbolNode(this, method.Method, method.IsUnboxingStub);
            });

            _standaloneGCStaticDescs = new NodeCache<GCStaticDescNode, StandaloneGCStaticDescRegionNode>((GCStaticDescNode staticDesc) =>
            {
                return new StandaloneGCStaticDescRegionNode(staticDesc);
            });
        }

        public override void AttachToDependencyGraph(DependencyAnalyzerBase<NodeFactory> graph)
        {
            ReadyToRunHeader = new ReadyToRunHeaderNode(Target);

            graph.AddRoot(ReadyToRunHeader, "ReadyToRunHeader is always generated");
            graph.AddRoot(new ModulesSectionNode(Target), "ModulesSection is always generated");

            graph.AddRoot(EagerCctorTable, "EagerCctorTable is always generated");
            graph.AddRoot(DispatchMapTable, "DispatchMapTable is always generated");
            graph.AddRoot(FrozenSegmentRegion, "FrozenSegmentRegion is always generated");
            graph.AddRoot(InterfaceDispatchCellSection, "Interface dispatch cell section is always generated");
            graph.AddRoot(TypeManagerIndirection, "ModuleManagerIndirection is always generated");
            graph.AddRoot(GCStaticsRegion, "GC StaticsRegion is always generated");
            graph.AddRoot(GCStaticDescRegion, "GC Static Desc is always generated");
            graph.AddRoot(ThreadStaticsOffsetRegion, "Thread Statics Offset Region is always generated");
            graph.AddRoot(ThreadStaticGCDescRegion, "Thread Statics GC Desc Region is always generated");
            graph.AddRoot(ImportAddressTablesTable, "Import address tables region");


            if (Target.IsWindows)
            {
                // We need 2 delimiter symbols to bound the unboxing stubs region on Windows platforms (these symbols are
                // accessed using extern "C" variables in the bootstrapper)
                // On non-Windows platforms, the linker emits special symbols with special names at the begining/end of a section
                // so we do not need to emit them ourselves.
                graph.AddRoot(new WindowsUnboxingStubsRegionNode(false), "UnboxingStubsRegion delimiter for Windows platform");
                graph.AddRoot(new WindowsUnboxingStubsRegionNode(true), "UnboxingStubsRegion delimiter for Windows platform");
            }

            // The native part of the MRT library links against CRT which defines _tls_index and _tls_used.
            if (!buildMRT)
            {
                graph.AddRoot(ThreadStaticsIndex, "Thread statics index is always generated");
                graph.AddRoot(TLSDirectory, "TLS Directory is always generated");
            }

            ReadyToRunHeader.Add(ReadyToRunSectionType.EagerCctor, EagerCctorTable, EagerCctorTable.StartSymbol, EagerCctorTable.EndSymbol);
            ReadyToRunHeader.Add(ReadyToRunSectionType.InterfaceDispatchTable, DispatchMapTable, DispatchMapTable.StartSymbol);
            ReadyToRunHeader.Add(ReadyToRunSectionType.FrozenObjectRegion, FrozenSegmentRegion, FrozenSegmentRegion.StartSymbol, FrozenSegmentRegion.EndSymbol);
            ReadyToRunHeader.Add(ReadyToRunSectionType.TypeManagerIndirection, TypeManagerIndirection, TypeManagerIndirection);
            ReadyToRunHeader.Add(ReadyToRunSectionType.GCStaticRegion, GCStaticsRegion, GCStaticsRegion.StartSymbol, GCStaticsRegion.EndSymbol);
            ReadyToRunHeader.Add(ReadyToRunSectionType.GCStaticDesc, GCStaticDescRegion, GCStaticDescRegion.StartSymbol, GCStaticDescRegion.EndSymbol);
            ReadyToRunHeader.Add(ReadyToRunSectionType.ThreadStaticOffsetRegion, ThreadStaticsOffsetRegion, ThreadStaticsOffsetRegion.StartSymbol, ThreadStaticsOffsetRegion.EndSymbol);
            ReadyToRunHeader.Add(ReadyToRunSectionType.ThreadStaticGCDescRegion, ThreadStaticGCDescRegion, ThreadStaticGCDescRegion.StartSymbol, ThreadStaticGCDescRegion.EndSymbol);
            ReadyToRunHeader.Add(ReadyToRunSectionType.LoopHijackFlag, LoopHijackFlag, LoopHijackFlag);
            ReadyToRunHeader.Add(ReadyToRunSectionType.ImportAddressTables, ImportAddressTablesTable, ImportAddressTablesTable.StartSymbol, ImportAddressTablesTable.EndSymbol);

            if (!buildMRT)
            {
                ReadyToRunHeader.Add(ReadyToRunSectionType.ThreadStaticIndex, ThreadStaticsIndex, ThreadStaticsIndex);
            }


            var commonFixupsTableNode = new ExternalReferencesTableNode("CommonFixupsTable", this);
            InteropStubManager.AddToReadyToRunHeader(ReadyToRunHeader, this, commonFixupsTableNode);
            MetadataManager.AddToReadyToRunHeader(ReadyToRunHeader, this, commonFixupsTableNode);
            MetadataManager.AttachToDependencyGraph(graph);
            ReadyToRunHeader.Add(MetadataManager.BlobIdToReadyToRunSection(ReflectionMapBlob.CommonFixupsTable), commonFixupsTableNode, commonFixupsTableNode, commonFixupsTableNode.EndSymbol);
        }

        protected override IMethodNode CreateMethodEntrypointNode(MethodDesc method)
        {
            if (method.HasCustomAttribute("System.Runtime", "RuntimeImportAttribute"))
            {
                RuntimeImportMethodNode runtimeImportMethod = new RuntimeImportMethodNode(method);
              
                // If the method is imported from either the current module or the runtime, reference it directly
                if (CompilationModuleGroup.ContainsMethodBody(method, false))
                    return runtimeImportMethod;
                // If the method is imported from the runtime but not a managed assembly, reference it directly
                else if (!CompilationModuleGroup.ImportsMethod(method, false))
                    return runtimeImportMethod;
                
                // If the method is imported from a managed assembly, reference it via an import cell
            }
            else
            {
                if (CompilationModuleGroup.ContainsMethodBody(method, false))
                    return NonExternMethodSymbol(method, false);
            }

            return _importedNodeProvider.ImportedMethodCodeNode(this, method, false);
        }

        protected override IMethodNode CreateUnboxingStubNode(MethodDesc method)
        {
            if (method.IsCanonicalMethod(CanonicalFormKind.Any) && !method.HasInstantiation)
            {
                // Unboxing stubs to canonical instance methods need a special unboxing instantiating stub that unboxes
                // 'this' and also provides an instantiation argument (we do a calling convention conversion).
                // The unboxing instantiating stub is emitted by UTC.
                if (CompilationModuleGroup.ContainsMethodBody(method, true))
                {
                    return NonExternMethodSymbol(method, true);
                }

                return _importedNodeProvider.ImportedMethodCodeNode(this, method, true);
            }
            else
            {
                // Otherwise we just unbox 'this' and don't touch anything else.
                return new UnboxingStubNode(method, Target);
            }
        }

        protected override ISymbolNode CreateReadyToRunHelperNode(ReadyToRunHelperKey helperCall)
        {
            return new ReadyToRunHelperNode(this, helperCall.HelperId, helperCall.Target);
        }

        public GCStaticDescRegionNode GCStaticDescRegion = new GCStaticDescRegionNode(
            CompilationUnitPrefix + "__GCStaticDescStart", 
            CompilationUnitPrefix + "__GCStaticDescEnd",
            new SortableDependencyNode.EmbeddedObjectNodeComparer(new CompilerComparer()));

        public GCStaticDescRegionNode ThreadStaticGCDescRegion = new GCStaticDescRegionNode(
            CompilationUnitPrefix + "__ThreadStaticGCDescStart", 
            CompilationUnitPrefix + "__ThreadStaticGCDescEnd",
            new SortableDependencyNode.EmbeddedObjectNodeComparer(new CompilerComparer()));

        public ArrayOfEmbeddedDataNode<ThreadStaticsOffsetNode> ThreadStaticsOffsetRegion = new ArrayOfEmbeddedDataNode<ThreadStaticsOffsetNode>(
            CompilationUnitPrefix + "__ThreadStaticOffsetRegionStart",
            CompilationUnitPrefix + "__ThreadStaticOffsetRegionEnd",
            new SortableDependencyNode.EmbeddedObjectNodeComparer(new CompilerComparer()));

        public ThreadStaticsIndexNode ThreadStaticsIndex;

        public ThreadStaticsDirectoryNode TLSDirectory;

        // These two are defined in startup code to mark start and end of the entire Thread Local Storage area,
        // including the TLS data from different managed and native object files.
        public ExternSymbolNode TlsStart;
        public ExternSymbolNode TlsEnd;

        public LoopHijackFlagNode LoopHijackFlag;

        protected override ISymbolDefinitionNode CreateThreadStaticsNode(MetadataType type)
        {
            return new UtcThreadStaticsNode(type);
        }

        private NodeCache<MetadataType, GCStaticDescNode> _GCStaticDescs;

        public ISymbolNode TypeGCStaticDescSymbol(MetadataType type)
        {
            if (CompilationModuleGroup.ContainsType(type))
            {
                return _GCStaticDescs.GetOrAdd(type);
            }
            else
            {
                return ExternSymbol(GCStaticDescNode.GetMangledName(NameMangler, type, false));
            }
        }

        private NodeCache<MetadataType, GCStaticDescNode> _threadStaticGCStaticDescs;

        public ISymbolNode TypeThreadStaticGCDescNode(MetadataType type)
        {
            if (CompilationModuleGroup.ContainsType(type))
            {
                return _threadStaticGCStaticDescs.GetOrAdd(type);
            }
            else
            {
                return ExternSymbol(GCStaticDescNode.GetMangledName(NameMangler, type, true));
            }
        }

        private NodeCache<MetadataType, ISortableSymbolNode> _threadStaticsOffset;

        public ISortableSymbolNode TypeThreadStaticsOffsetSymbol(MetadataType type)
        {
            return _threadStaticsOffset.GetOrAdd(type);            
        }

        private NodeCache<MetadataType, ImportedThreadStaticsIndexNode> _importedThreadStaticsIndices;

        public ISortableSymbolNode TypeThreadStaticsIndexSymbol(MetadataType type)
        {
            if (CompilationModuleGroup.ContainsType(type) && !CompilationModuleGroup.ShouldReferenceThroughImportTable(type))
            {
                return ThreadStaticsIndex;
            }
            else
            {
                return _importedNodeProvider.ImportedThreadStaticIndexNode(this, type);
            }
        }

        private NodeCache<MethodKey, NonExternMethodSymbolNode> _nonExternMethodSymbols;

        public NonExternMethodSymbolNode NonExternMethodSymbol(MethodDesc method, bool isUnboxingStub)
        {
            return _nonExternMethodSymbols.GetOrAdd(new MethodKey(method, isUnboxingStub));
        }

        private NodeCache<GCStaticDescNode, StandaloneGCStaticDescRegionNode> _standaloneGCStaticDescs;

        public StandaloneGCStaticDescRegionNode StandaloneGCStaticDescRegion(GCStaticDescNode staticDesc)
        {
            return _standaloneGCStaticDescs.GetOrAdd(staticDesc);
        }

        public BlobNode FieldRvaDataBlob(FieldDesc field)
        {
            // Use the typical field definition in case this is an instantiated generic type
            field = field.GetTypicalFieldDefinition();
            return ReadOnlyDataBlob(NameMangler.GetMangledFieldName(field), ((EcmaField)field).GetFieldRvaData(), Target.PointerSize);
        }

        public ISymbolNode LoopHijackFlagSymbol()
        {
            return LoopHijackFlag;
        }
    }
}