-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
Program.cs
680 lines (552 loc) · 33.3 KB
/
Program.cs
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#pragma warning disable IDE0005
using System;
using System.Collections.Generic;
using System.CommandLine;
using System.CommandLine.Help;
using System.CommandLine.Parsing;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using Internal.IL;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
using ILCompiler.Dataflow;
using ILLink.Shared;
using Debug = System.Diagnostics.Debug;
using InstructionSet = Internal.JitInterface.InstructionSet;
namespace ILCompiler
{
internal sealed class Program
{
private readonly ILCompilerRootCommand _command;
public Program(ILCompilerRootCommand command)
{
_command = command;
if (Get(command.WaitForDebugger))
{
Console.WriteLine("Waiting for debugger to attach. Press ENTER to continue");
Console.ReadLine();
}
}
private IReadOnlyCollection<MethodDesc> CreateInitializerList(CompilerTypeSystemContext context)
{
List<ModuleDesc> assembliesWithInitializers = new List<ModuleDesc>();
// Build a list of assemblies that have an initializer that needs to run before
// any user code runs.
foreach (string initAssemblyName in Get(_command.InitAssemblies))
{
ModuleDesc assembly = context.ResolveAssembly(new AssemblyName(initAssemblyName), throwIfNotFound: true);
assembliesWithInitializers.Add(assembly);
}
var libraryInitializers = new LibraryInitializers(context, assembliesWithInitializers);
List<MethodDesc> initializerList = new List<MethodDesc>(libraryInitializers.LibraryInitializerMethods);
// If there are any AppContext switches the user wishes to enable, generate code that sets them.
string[] appContextSwitches = Get(_command.AppContextSwitches);
if (appContextSwitches.Length > 0)
{
MethodDesc appContextInitMethod = new Internal.IL.Stubs.StartupCode.AppContextInitializerMethod(
context.GeneratedAssembly.GetGlobalModuleType(), appContextSwitches);
initializerList.Add(appContextInitMethod);
}
return initializerList;
}
public int Run()
{
string outputFilePath = Get(_command.OutputFilePath);
if (outputFilePath == null)
throw new CommandLineException("Output filename must be specified (/out <file>)");
TargetArchitecture targetArchitecture = Get(_command.TargetArchitecture);
TargetOS targetOS = Get(_command.TargetOS);
InstructionSetSupport instructionSetSupport = Helpers.ConfigureInstructionSetSupport(Get(_command.InstructionSet), targetArchitecture, targetOS,
"Unrecognized instruction set {0}", "Unsupported combination of instruction sets: {0}/{1}");
string systemModuleName = Get(_command.SystemModuleName);
string reflectionData = Get(_command.ReflectionData);
bool supportsReflection = reflectionData != "none" && systemModuleName == Helpers.DefaultSystemModule;
//
// Initialize type system context
//
SharedGenericsMode genericsMode = SharedGenericsMode.CanonicalReferenceTypes;
var simdVectorLength = instructionSetSupport.GetVectorTSimdVector();
var targetAbi = TargetAbi.NativeAot;
var targetDetails = new TargetDetails(targetArchitecture, targetOS, targetAbi, simdVectorLength);
CompilerTypeSystemContext typeSystemContext =
new CompilerTypeSystemContext(targetDetails, genericsMode, supportsReflection ? DelegateFeature.All : 0, Get(_command.MaxGenericCycle));
//
// TODO: To support our pre-compiled test tree, allow input files that aren't managed assemblies since
// some tests contain a mixture of both managed and native binaries.
//
// See: https://github.com/dotnet/corert/issues/2785
//
// When we undo this hack, replace the foreach with
// typeSystemContext.InputFilePaths = _command.Result.GetValueForArgument(inputFilePaths);
//
Dictionary<string, string> inputFilePaths = new Dictionary<string, string>();
foreach (var inputFile in _command.Result.GetValue(_command.InputFilePaths))
{
try
{
var module = typeSystemContext.GetModuleFromPath(inputFile.Value);
inputFilePaths.Add(inputFile.Key, inputFile.Value);
}
catch (TypeSystemException.BadImageFormatException)
{
// Keep calm and carry on.
}
}
typeSystemContext.InputFilePaths = inputFilePaths;
typeSystemContext.ReferenceFilePaths = Get(_command.ReferenceFiles);
if (!typeSystemContext.InputFilePaths.ContainsKey(systemModuleName)
&& !typeSystemContext.ReferenceFilePaths.ContainsKey(systemModuleName))
throw new CommandLineException($"System module {systemModuleName} does not exists. Make sure that you specify --systemmodule");
typeSystemContext.SetSystemModule(typeSystemContext.GetModuleForSimpleName(systemModuleName));
if (typeSystemContext.InputFilePaths.Count == 0)
throw new CommandLineException("No input files specified");
SecurityMitigationOptions securityMitigationOptions = 0;
string guard = Get(_command.Guard);
if (StringComparer.OrdinalIgnoreCase.Equals(guard, "cf"))
{
if (targetOS != TargetOS.Windows)
{
throw new CommandLineException($"Control flow guard only available on Windows");
}
securityMitigationOptions = SecurityMitigationOptions.ControlFlowGuardAnnotations;
}
else if (!string.IsNullOrEmpty(guard))
{
throw new CommandLineException($"Unrecognized mitigation option '{guard}'");
}
//
// Initialize compilation group and compilation roots
//
// Single method mode?
MethodDesc singleMethod = CheckAndParseSingleMethodModeArguments(typeSystemContext);
CompilationModuleGroup compilationGroup;
List<ICompilationRootProvider> compilationRoots = new List<ICompilationRootProvider>();
bool multiFile = Get(_command.MultiFile);
if (singleMethod != null)
{
// Compiling just a single method
compilationGroup = new SingleMethodCompilationModuleGroup(singleMethod);
compilationRoots.Add(new SingleMethodRootProvider(singleMethod));
}
else
{
// Either single file, or multifile library, or multifile consumption.
EcmaModule entrypointModule = null;
bool systemModuleIsInputModule = false;
foreach (var inputFile in typeSystemContext.InputFilePaths)
{
EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value);
if (module.PEReader.PEHeaders.IsExe)
{
if (entrypointModule != null)
throw new Exception("Multiple EXE modules");
entrypointModule = module;
}
if (module == typeSystemContext.SystemModule)
systemModuleIsInputModule = true;
compilationRoots.Add(new ExportedMethodsRootProvider(module));
}
bool nativeLib = Get(_command.NativeLib);
if (multiFile)
{
List<EcmaModule> inputModules = new List<EcmaModule>();
foreach (var inputFile in typeSystemContext.InputFilePaths)
{
EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value);
if (entrypointModule == null)
{
// This is a multifile production build - we need to root all methods
compilationRoots.Add(new LibraryRootProvider(module));
}
inputModules.Add(module);
}
compilationGroup = new MultiFileSharedCompilationModuleGroup(typeSystemContext, inputModules);
}
else
{
if (entrypointModule == null && !nativeLib)
throw new Exception("No entrypoint module");
if (!systemModuleIsInputModule)
compilationRoots.Add(new ExportedMethodsRootProvider((EcmaModule)typeSystemContext.SystemModule));
compilationGroup = new SingleFileCompilationModuleGroup();
}
string[] runtimeOptions = Get(_command.RuntimeOptions);
if (nativeLib)
{
// Set owning module of generated native library startup method to compiler generated module,
// to ensure the startup method is included in the object file during multimodule mode build
compilationRoots.Add(new NativeLibraryInitializerRootProvider(typeSystemContext.GeneratedAssembly, CreateInitializerList(typeSystemContext)));
compilationRoots.Add(new RuntimeConfigurationRootProvider(runtimeOptions));
compilationRoots.Add(new ExpectedIsaFeaturesRootProvider(instructionSetSupport));
}
else if (entrypointModule != null)
{
compilationRoots.Add(new MainMethodRootProvider(entrypointModule, CreateInitializerList(typeSystemContext)));
compilationRoots.Add(new RuntimeConfigurationRootProvider(runtimeOptions));
compilationRoots.Add(new ExpectedIsaFeaturesRootProvider(instructionSetSupport));
}
foreach (var rdXmlFilePath in Get(_command.RdXmlFilePaths))
{
compilationRoots.Add(new RdXmlRootProvider(typeSystemContext, rdXmlFilePath));
}
foreach (var linkTrimFilePath in Get(_command.LinkTrimFilePaths))
{
if (!File.Exists(linkTrimFilePath))
throw new CommandLineException($"'{linkTrimFilePath}' doesn't exist");
compilationRoots.Add(new ILCompiler.DependencyAnalysis.TrimmingDescriptorNode(linkTrimFilePath));
}
}
// Root whatever assemblies were specified on the command line
string[] rootedAssemblies = Get(_command.RootedAssemblies);
foreach (var rootedAssembly in rootedAssemblies)
{
// For compatibility with IL Linker, the parameter could be a file name or an assembly name.
// This is the logic IL Linker uses to decide how to interpret the string. Really.
EcmaModule module = File.Exists(rootedAssembly)
? typeSystemContext.GetModuleFromPath(rootedAssembly)
: typeSystemContext.GetModuleForSimpleName(rootedAssembly);
// We only root the module type. The rest will fall out because we treat rootedAssemblies
// same as conditionally rooted ones and here we're fulfilling the condition ("something is used").
compilationRoots.Add(
new GenericRootProvider<ModuleDesc>(module,
(ModuleDesc module, IRootingServiceProvider rooter) => rooter.AddReflectionRoot(module.GetGlobalModuleType(), "Command line root")));
}
//
// Compile
//
CompilationBuilder builder = new RyuJitCompilationBuilder(typeSystemContext, compilationGroup);
string compilationUnitPrefix = multiFile ? Path.GetFileNameWithoutExtension(outputFilePath) : "";
builder.UseCompilationUnitPrefix(compilationUnitPrefix);
string[] mibcFilePaths = Get(_command.MibcFilePaths);
if (mibcFilePaths.Length > 0)
((RyuJitCompilationBuilder)builder).UseProfileData(mibcFilePaths);
string jitPath = Get(_command.JitPath);
if (!string.IsNullOrEmpty(jitPath))
((RyuJitCompilationBuilder)builder).UseJitPath(jitPath);
PInvokeILEmitterConfiguration pinvokePolicy = new ConfigurablePInvokePolicy(typeSystemContext.Target,
Get(_command.DirectPInvokes), Get(_command.DirectPInvokeLists));
ILProvider ilProvider = new NativeAotILProvider();
var suppressedWarningCategories = new List<string>();
if (Get(_command.NoTrimWarn))
suppressedWarningCategories.Add(MessageSubCategory.TrimAnalysis);
if (Get(_command.NoAotWarn))
suppressedWarningCategories.Add(MessageSubCategory.AotAnalysis);
var logger = new Logger(Console.Out, ilProvider, Get(_command.IsVerbose), ProcessWarningCodes(Get(_command.SuppressedWarnings)),
Get(_command.SingleWarn), Get(_command.SingleWarnEnabledAssemblies), Get(_command.SingleWarnDisabledAssemblies), suppressedWarningCategories);
List<KeyValuePair<string, bool>> featureSwitches = new List<KeyValuePair<string, bool>>();
foreach (var switchPair in Get(_command.FeatureSwitches))
{
string[] switchAndValue = switchPair.Split('=');
if (switchAndValue.Length != 2
|| !bool.TryParse(switchAndValue[1], out bool switchValue))
throw new CommandLineException($"Unexpected feature switch pair '{switchPair}'");
featureSwitches.Add(new KeyValuePair<string, bool>(switchAndValue[0], switchValue));
}
ilProvider = new FeatureSwitchManager(ilProvider, logger, featureSwitches);
CompilerGeneratedState compilerGeneratedState = new CompilerGeneratedState(ilProvider, logger);
var stackTracePolicy = Get(_command.EmitStackTraceData) ?
(StackTraceEmissionPolicy)new EcmaMethodStackTraceEmissionPolicy() : new NoStackTraceEmissionPolicy();
MetadataBlockingPolicy mdBlockingPolicy;
ManifestResourceBlockingPolicy resBlockingPolicy;
UsageBasedMetadataGenerationOptions metadataGenerationOptions = default;
if (supportsReflection)
{
mdBlockingPolicy = Get(_command.NoMetadataBlocking) ?
new NoMetadataBlockingPolicy() : new BlockedInternalsBlockingPolicy(typeSystemContext);
resBlockingPolicy = new ManifestResourceBlockingPolicy(logger, featureSwitches);
metadataGenerationOptions |= UsageBasedMetadataGenerationOptions.AnonymousTypeHeuristic;
if (Get(_command.CompleteTypesMetadata))
metadataGenerationOptions |= UsageBasedMetadataGenerationOptions.CompleteTypesOnly;
if (Get(_command.ScanReflection))
metadataGenerationOptions |= UsageBasedMetadataGenerationOptions.ReflectionILScanning;
if (reflectionData == "all")
metadataGenerationOptions |= UsageBasedMetadataGenerationOptions.CreateReflectableArtifacts;
if (Get(_command.RootDefaultAssemblies))
metadataGenerationOptions |= UsageBasedMetadataGenerationOptions.RootDefaultAssemblies;
}
else
{
mdBlockingPolicy = new FullyBlockedMetadataBlockingPolicy();
resBlockingPolicy = new FullyBlockedManifestResourceBlockingPolicy();
}
DynamicInvokeThunkGenerationPolicy invokeThunkGenerationPolicy = new DefaultDynamicInvokeThunkGenerationPolicy();
var flowAnnotations = new ILLink.Shared.TrimAnalysis.FlowAnnotations(logger, ilProvider, compilerGeneratedState);
MetadataManagerOptions metadataOptions = default;
if (Get(_command.Dehydrate))
metadataOptions |= MetadataManagerOptions.DehydrateData;
MetadataManager metadataManager = new UsageBasedMetadataManager(
compilationGroup,
typeSystemContext,
mdBlockingPolicy,
resBlockingPolicy,
Get(_command.MetadataLogFileName),
stackTracePolicy,
invokeThunkGenerationPolicy,
flowAnnotations,
metadataGenerationOptions,
metadataOptions,
logger,
featureSwitches,
Get(_command.ConditionallyRootedAssemblies),
rootedAssemblies,
Get(_command.TrimmedAssemblies));
InteropStateManager interopStateManager = new InteropStateManager(typeSystemContext.GeneratedAssembly);
InteropStubManager interopStubManager = new UsageBasedInteropStubManager(interopStateManager, pinvokePolicy, logger);
// Unless explicitly opted in at the command line, we enable scanner for retail builds by default.
// We also don't do this for multifile because scanner doesn't simulate inlining (this would be
// fixable by using a CompilationGroup for the scanner that has a bigger worldview, but
// let's cross that bridge when we get there).
bool useScanner = Get(_command.UseScanner) ||
(_command.OptimizationMode != OptimizationMode.None && !multiFile);
useScanner &= !Get(_command.NoScanner);
// Enable static data preinitialization in optimized builds.
bool preinitStatics = Get(_command.PreinitStatics) ||
(_command.OptimizationMode != OptimizationMode.None && !multiFile);
preinitStatics &= !Get(_command.NoPreinitStatics);
TypePreinit.TypePreinitializationPolicy preinitPolicy = preinitStatics ?
new TypePreinit.TypeLoaderAwarePreinitializationPolicy() : new TypePreinit.DisabledPreinitializationPolicy();
var preinitManager = new PreinitializationManager(typeSystemContext, compilationGroup, ilProvider, preinitPolicy);
builder
.UseILProvider(ilProvider)
.UsePreinitializationManager(preinitManager);
#if DEBUG
List<TypeDesc> scannerConstructedTypes = null;
List<MethodDesc> scannerCompiledMethods = null;
#endif
int parallelism = Get(_command.Parallelism);
if (useScanner)
{
// Run the scanner in a separate stack frame so that there's no dangling references to
// it once we're done with it and it can be garbage collected.
RunScanner();
}
[MethodImpl(MethodImplOptions.NoInlining)]
void RunScanner()
{
ILScannerBuilder scannerBuilder = builder.GetILScannerBuilder()
.UseCompilationRoots(compilationRoots)
.UseMetadataManager(metadataManager)
.UseParallelism(parallelism)
.UseInteropStubManager(interopStubManager)
.UseLogger(logger);
string scanDgmlLogFileName = Get(_command.ScanDgmlLogFileName);
if (scanDgmlLogFileName != null)
scannerBuilder.UseDependencyTracking(Get(_command.GenerateFullScanDgmlLog) ?
DependencyTrackingLevel.All : DependencyTrackingLevel.First);
IILScanner scanner = scannerBuilder.ToILScanner();
ILScanResults scanResults = scanner.Scan();
#if DEBUG
scannerCompiledMethods = new List<MethodDesc>(scanResults.CompiledMethodBodies);
scannerConstructedTypes = new List<TypeDesc>(scanResults.ConstructedEETypes);
#endif
if (scanDgmlLogFileName != null)
scanResults.WriteDependencyLog(scanDgmlLogFileName);
metadataManager = ((UsageBasedMetadataManager)metadataManager).ToAnalysisBasedMetadataManager();
interopStubManager = scanResults.GetInteropStubManager(interopStateManager, pinvokePolicy);
// If we have a scanner, feed the vtable analysis results to the compilation.
// This could be a command line switch if we really wanted to.
builder.UseVTableSliceProvider(scanResults.GetVTableLayoutInfo());
// If we have a scanner, feed the generic dictionary results to the compilation.
// This could be a command line switch if we really wanted to.
builder.UseGenericDictionaryLayoutProvider(scanResults.GetDictionaryLayoutInfo());
// If we have a scanner, we can drive devirtualization using the information
// we collected at scanning time (effectively sealing unsealed types if possible).
// This could be a command line switch if we really wanted to.
builder.UseDevirtualizationManager(scanResults.GetDevirtualizationManager());
// If we use the scanner's result, we need to consult it to drive inlining.
// This prevents e.g. devirtualizing and inlining methods on types that were
// never actually allocated.
builder.UseInliningPolicy(scanResults.GetInliningPolicy());
// Use an error provider that prevents us from re-importing methods that failed
// to import with an exception during scanning phase. We would see the same failure during
// compilation, but before RyuJIT gets there, it might ask questions that we don't
// have answers for because we didn't scan the entire method.
builder.UseMethodImportationErrorProvider(scanResults.GetMethodImportationErrorProvider());
// If we're doing preinitialization, use a new preinitialization manager that
// has the whole program view.
if (preinitStatics)
{
preinitManager = new PreinitializationManager(typeSystemContext, compilationGroup, ilProvider, scanResults.GetPreinitializationPolicy());
builder.UsePreinitializationManager(preinitManager);
}
}
string ilDump = Get(_command.IlDump);
DebugInformationProvider debugInfoProvider = Get(_command.EnableDebugInfo) ?
(ilDump == null ? new DebugInformationProvider() : new ILAssemblyGeneratingMethodDebugInfoProvider(ilDump, new EcmaOnlyDebugInformationProvider())) :
new NullDebugInformationProvider();
string dgmlLogFileName = Get(_command.DgmlLogFileName);
DependencyTrackingLevel trackingLevel = dgmlLogFileName == null ?
DependencyTrackingLevel.None : (Get(_command.GenerateFullDgmlLog) ?
DependencyTrackingLevel.All : DependencyTrackingLevel.First);
compilationRoots.Add(metadataManager);
compilationRoots.Add(interopStubManager);
builder
.UseInstructionSetSupport(instructionSetSupport)
.UseBackendOptions(Get(_command.CodegenOptions))
.UseMethodBodyFolding(enable: Get(_command.MethodBodyFolding))
.UseParallelism(parallelism)
.UseMetadataManager(metadataManager)
.UseInteropStubManager(interopStubManager)
.UseLogger(logger)
.UseDependencyTracking(trackingLevel)
.UseCompilationRoots(compilationRoots)
.UseOptimizationMode(_command.OptimizationMode)
.UseSecurityMitigationOptions(securityMitigationOptions)
.UseDebugInfoProvider(debugInfoProvider)
.UseDwarf5(Get(_command.UseDwarf5));
builder.UseResilience(Get(_command.Resilient));
ICompilation compilation = builder.ToCompilation();
string mapFileName = Get(_command.MapFileName);
string mstatFileName = Get(_command.MstatFileName);
List<ObjectDumper> dumpers = new List<ObjectDumper>();
if (mapFileName != null)
dumpers.Add(new XmlObjectDumper(mapFileName));
if (mstatFileName != null)
dumpers.Add(new MstatObjectDumper(mstatFileName, typeSystemContext));
CompilationResults compilationResults = compilation.Compile(outputFilePath, ObjectDumper.Compose(dumpers));
string exportsFile = Get(_command.ExportsFile);
if (exportsFile != null)
{
ExportsFileWriter defFileWriter = new ExportsFileWriter(typeSystemContext, exportsFile);
foreach (var compilationRoot in compilationRoots)
{
if (compilationRoot is ExportedMethodsRootProvider provider)
defFileWriter.AddExportedMethods(provider.ExportedMethods);
}
defFileWriter.EmitExportedMethods();
}
typeSystemContext.LogWarnings(logger);
if (dgmlLogFileName != null)
compilationResults.WriteDependencyLog(dgmlLogFileName);
#if DEBUG
if (scannerConstructedTypes != null)
{
// If the scanner and compiler don't agree on what to compile, the outputs of the scanner might not actually be usable.
// We are going to check this two ways:
// 1. The methods and types generated during compilation are a subset of method and types scanned
// 2. The methods and types scanned are a subset of methods and types compiled (this has a chance to hold for unoptimized builds only).
// Check that methods and types generated during compilation are a subset of method and types scanned
bool scanningFail = false;
DiffCompilationResults(ref scanningFail, compilationResults.CompiledMethodBodies, scannerCompiledMethods,
"Methods", "compiled", "scanned", method => !(method.GetTypicalMethodDefinition() is EcmaMethod) || IsRelatedToInvalidInput(method));
DiffCompilationResults(ref scanningFail, compilationResults.ConstructedEETypes, scannerConstructedTypes,
"EETypes", "compiled", "scanned", type => !(type.GetTypeDefinition() is EcmaType));
static bool IsRelatedToInvalidInput(MethodDesc method)
{
// RyuJIT is more sensitive to invalid input and might detect cases that the scanner didn't have trouble with.
// If we find logic related to compiling fallback method bodies (methods that just throw) that got compiled
// but not scanned, it's usually fine. If it wasn't fine, we would probably crash before getting here.
return method.OwningType is MetadataType mdType
&& mdType.Module == method.Context.SystemModule
&& (mdType.Name.EndsWith("Exception") || mdType.Namespace.StartsWith("Internal.Runtime"));
}
// If optimizations are enabled, the results will for sure not match in the other direction due to inlining, etc.
// But there's at least some value in checking the scanner doesn't expand the universe too much in debug.
if (_command.OptimizationMode == OptimizationMode.None)
{
// Check that methods and types scanned are a subset of methods and types compiled
// If we find diffs here, they're not critical, but still might be causing a Size on Disk regression.
bool dummy = false;
// We additionally skip methods in SIMD module because there's just too many intrisics to handle and IL scanner
// doesn't expand them. They would show up as noisy diffs.
DiffCompilationResults(ref dummy, scannerCompiledMethods, compilationResults.CompiledMethodBodies,
"Methods", "scanned", "compiled", method => !(method.GetTypicalMethodDefinition() is EcmaMethod) || method.OwningType.IsIntrinsic);
DiffCompilationResults(ref dummy, scannerConstructedTypes, compilationResults.ConstructedEETypes,
"EETypes", "scanned", "compiled", type => !(type.GetTypeDefinition() is EcmaType));
}
if (scanningFail)
throw new Exception("Scanning failure");
}
#endif
if (debugInfoProvider is IDisposable)
((IDisposable)debugInfoProvider).Dispose();
preinitManager.LogStatistics(logger);
return 0;
}
private static void DiffCompilationResults<T>(ref bool result, IEnumerable<T> set1, IEnumerable<T> set2, string prefix,
string set1name, string set2name, Predicate<T> filter)
{
HashSet<T> diff = new HashSet<T>(set1);
diff.ExceptWith(set2);
// TODO: move ownership of compiler-generated entities to CompilerTypeSystemContext.
// https://github.com/dotnet/corert/issues/3873
diff.RemoveWhere(filter);
if (diff.Count > 0)
{
result = true;
Console.WriteLine($"*** {prefix} {set1name} but not {set2name}:");
foreach (var d in diff)
{
Console.WriteLine(d.ToString());
}
}
}
private static TypeDesc FindType(CompilerTypeSystemContext context, string typeName)
{
ModuleDesc systemModule = context.SystemModule;
TypeDesc foundType = systemModule.GetTypeByCustomAttributeTypeName(typeName, false, (typeDefName, module, throwIfNotFound) =>
{
return (MetadataType)context.GetCanonType(typeDefName)
?? CustomAttributeTypeNameParser.ResolveCustomAttributeTypeDefinitionName(typeDefName, module, throwIfNotFound);
});
if (foundType == null)
throw new CommandLineException($"Type '{typeName}' not found");
return foundType;
}
private MethodDesc CheckAndParseSingleMethodModeArguments(CompilerTypeSystemContext context)
{
string singleMethodName = Get(_command.SingleMethodName);
string singleMethodTypeName = Get(_command.SingleMethodTypeName);
string[] singleMethodGenericArgs = Get(_command.SingleMethodGenericArgs);
if (singleMethodName == null && singleMethodTypeName == null && singleMethodGenericArgs.Length == 0)
return null;
if (singleMethodName == null || singleMethodTypeName == null)
throw new CommandLineException("Both method name and type name are required parameters for single method mode");
TypeDesc owningType = FindType(context, singleMethodTypeName);
// TODO: allow specifying signature to distinguish overloads
MethodDesc method = owningType.GetMethod(singleMethodName, null);
if (method == null)
throw new CommandLineException($"Method '{singleMethodName}' not found in '{singleMethodTypeName}'");
if (method.Instantiation.Length != singleMethodGenericArgs.Length)
{
throw new CommandLineException(
$"Expected {method.Instantiation.Length} generic arguments for method '{singleMethodName}' on type '{singleMethodTypeName}'");
}
if (method.HasInstantiation)
{
List<TypeDesc> genericArguments = new List<TypeDesc>();
foreach (var argString in singleMethodGenericArgs)
genericArguments.Add(FindType(context, argString));
method = method.MakeInstantiatedMethod(genericArguments.ToArray());
}
return method;
}
private static IEnumerable<int> ProcessWarningCodes(IEnumerable<string> warningCodes)
{
foreach (string value in warningCodes)
{
string[] values = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string id in values)
{
if (!id.StartsWith("IL", StringComparison.Ordinal) || !ushort.TryParse(id.AsSpan(2), out ushort code))
continue;
yield return code;
}
}
}
private T Get<T>(Option<T> option) => _command.Result.GetValue(option);
private static int Main(string[] args) =>
new CommandLineBuilder(new ILCompilerRootCommand(args))
.UseTokenReplacer(Helpers.TryReadResponseFile)
.UseVersionOption("--version", "-v")
.UseHelp(context => context.HelpBuilder.CustomizeLayout(ILCompilerRootCommand.GetExtendedHelp))
.UseParseErrorReporting()
.Build()
.Invoke(args);
}
}