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

LinkContext.cs « Linker « linker « src - github.com/mono/linker.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6bd0ff73b748f274fe1c24830661b2a0e902f7e1 (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
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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

//
// LinkContext.cs
//
// Author:
//   Jb Evain (jbevain@gmail.com)
//
// (C) 2006 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using ILLink.Shared;
using ILLink.Shared.TypeSystemProxy;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Linker.Dataflow;
using Mono.Linker.Steps;

namespace Mono.Linker
{

	public class UnintializedContextFactory
	{
		public virtual AnnotationStore CreateAnnotationStore (LinkContext context) => new AnnotationStore (context);
		public virtual MarkingHelpers CreateMarkingHelpers (LinkContext context) => new MarkingHelpers (context);
		public virtual Tracer CreateTracer (LinkContext context) => new Tracer (context);
	}

	public static class TargetRuntimeVersion
	{
		public const int NET5 = 5;
		public const int NET6 = 6;
	}

	public interface ITryResolveMetadata
	{
		MethodDefinition? TryResolve (MethodReference methodReference);
		TypeDefinition? TryResolve (TypeReference typeReference);
	}

	public class LinkContext : IMetadataResolver, ITryResolveMetadata, IDisposable
	{

		readonly Pipeline _pipeline;
		readonly Dictionary<string, AssemblyAction> _actions;
		readonly Dictionary<string, string> _parameters;
		int? _targetRuntime;

		readonly AssemblyResolver _resolver;
		readonly TypeNameResolver _typeNameResolver;

		readonly AnnotationStore _annotations;
		readonly CustomAttributeSource _customAttributes;
		readonly CompilerGeneratedState _compilerGeneratedState;
		readonly List<MessageContainer> _cachedWarningMessageContainers;
		readonly ILogger _logger;
		readonly Dictionary<AssemblyDefinition, bool> _isTrimmable;
		readonly UnreachableBlocksOptimizer _unreachableBlocksOptimizer;

		public Pipeline Pipeline {
			get { return _pipeline; }
		}

		public CustomAttributeSource CustomAttributes => _customAttributes;

		public CompilerGeneratedState CompilerGeneratedState => _compilerGeneratedState;

		public AnnotationStore Annotations => _annotations;

		public bool DeterministicOutput { get; set; }

		public int ErrorsCount { get; private set; }

		public string OutputDirectory { get; set; }

		public MetadataTrimming MetadataTrimming { get; set; }

		public AssemblyAction TrimAction { get; set; }

		public AssemblyAction DefaultAction { get; set; }

		public bool LinkSymbols { get; set; }

		public readonly bool KeepMembersForDebugger = true;

		public bool IgnoreUnresolved { get; set; }

		public bool EnableReducedTracing { get; set; }

		public bool KeepUsedAttributeTypesOnly { get; set; }

		public bool EnableSerializationDiscovery { get; set; }

		public bool DisableOperatorDiscovery { get; set; }

		/// <summary>
		/// Option to not special case EventSource.
		/// Currently, values are hard-coded and does not have a command line option to control
		/// </summary>
		public bool DisableEventSourceSpecialHandling { get; set; }

		public bool IgnoreDescriptors { get; set; }

		public bool IgnoreSubstitutions { get; set; }

		public bool IgnoreLinkAttributes { get; set; }

		public Dictionary<string, bool> FeatureSettings { get; init; }

		public List<PInvokeInfo> PInvokes { get; private set; }

		public string? PInvokesListFile;

		public bool StripSecurity { get; set; }

		public Dictionary<string, AssemblyAction> Actions {
			get { return _actions; }
		}

		public AssemblyResolver Resolver {
			get { return _resolver; }
		}

		internal TypeNameResolver TypeNameResolver {
			get { return _typeNameResolver; }
		}

		public ISymbolReaderProvider SymbolReaderProvider { get; set; }

		public bool LogMessages { get; set; }

		public MarkingHelpers MarkingHelpers { get; private set; }

		public KnownMembers MarkedKnownMembers { get; private set; }

		public WarningSuppressionWriter? WarningSuppressionWriter { get; set; }

		public HashSet<int> NoWarn { get; set; }

		public bool NoTrimWarn { get; set; }

		public Dictionary<int, bool> WarnAsError { get; set; }

		public bool GeneralWarnAsError { get; set; }

		public WarnVersion WarnVersion { get; set; }

		public UnconditionalSuppressMessageAttributeState Suppressions { get; set; }

		public Tracer Tracer { get; private set; }

		public CodeOptimizationsSettings Optimizations { get; set; }

		public bool AddReflectionAnnotations { get; set; }

		public string? AssemblyListFile { get; set; }

		public List<IMarkHandler> MarkHandlers { get; }

		public Dictionary<string, bool> SingleWarn { get; set; }

		public bool GeneralSingleWarn { get; set; }

		public HashSet<string> AssembliesWithGeneratedSingleWarning { get; set; }

		public SerializationMarker SerializationMarker { get; }

		public LinkContext (Pipeline pipeline, ILogger logger, string outputDirectory)
		{
			_pipeline = pipeline;
			_logger = logger ?? throw new ArgumentNullException (nameof (logger));

			_resolver = new AssemblyResolver (this);
			_typeNameResolver = new TypeNameResolver (this);
			_actions = new Dictionary<string, AssemblyAction> ();
			_parameters = new Dictionary<string, string> (StringComparer.Ordinal);
			_customAttributes = new CustomAttributeSource (this);
			_compilerGeneratedState = new CompilerGeneratedState (this);
			_cachedWarningMessageContainers = new List<MessageContainer> ();
			_isTrimmable = new Dictionary<AssemblyDefinition, bool> ();
			OutputDirectory = outputDirectory;
			FeatureSettings = new Dictionary<string, bool> (StringComparer.Ordinal);

			SymbolReaderProvider = new DefaultSymbolReaderProvider (false);

			var factory = new UnintializedContextFactory ();
			_annotations = factory.CreateAnnotationStore (this);
			MarkingHelpers = factory.CreateMarkingHelpers (this);
			SerializationMarker = new SerializationMarker (this);
			Tracer = factory.CreateTracer (this);
			MarkedKnownMembers = new KnownMembers ();
			PInvokes = new List<PInvokeInfo> ();
			Suppressions = new UnconditionalSuppressMessageAttributeState (this);
			NoWarn = new HashSet<int> ();
			GeneralWarnAsError = false;
			WarnAsError = new Dictionary<int, bool> ();
			WarnVersion = WarnVersion.Latest;
			MarkHandlers = new List<IMarkHandler> ();
			GeneralSingleWarn = false;
			SingleWarn = new Dictionary<string, bool> ();
			AssembliesWithGeneratedSingleWarning = new HashSet<string> ();
			_unreachableBlocksOptimizer = new UnreachableBlocksOptimizer (this);

			const CodeOptimizations defaultOptimizations =
				CodeOptimizations.BeforeFieldInit |
				CodeOptimizations.OverrideRemoval |
				CodeOptimizations.UnusedInterfaces |
				CodeOptimizations.UnusedTypeChecks |
				CodeOptimizations.IPConstantPropagation |
				CodeOptimizations.UnreachableBodies |
				CodeOptimizations.RemoveDescriptors |
				CodeOptimizations.RemoveLinkAttributes |
				CodeOptimizations.RemoveSubstitutions |
				CodeOptimizations.RemoveDynamicDependencyAttribute |
				CodeOptimizations.OptimizeTypeHierarchyAnnotations;

			DisableEventSourceSpecialHandling = true;

			Optimizations = new CodeOptimizationsSettings (defaultOptimizations);
		}

		public void SetFeatureValue (string feature, bool value)
		{
			Debug.Assert (!String.IsNullOrEmpty (feature));
			FeatureSettings[feature] = value;
		}

		public bool HasFeatureValue (string feature, bool value)
		{
			return FeatureSettings.TryGetValue (feature, out bool fvalue) && value == fvalue;
		}

		public TypeDefinition? GetType (string fullName)
		{
			int pos = fullName.IndexOf (",");
			fullName = TypeReferenceExtensions.ToCecilName (fullName);
			if (pos == -1) {
				foreach (AssemblyDefinition asm in GetReferencedAssemblies ()) {
					var type = asm.MainModule.GetType (fullName);
					if (type != null)
						return type;
				}

				return null;
			}

			string asmname = fullName.Substring (pos + 1);
			fullName = fullName.Substring (0, pos);
			AssemblyDefinition? assembly = Resolve (AssemblyNameReference.Parse (asmname));
			return assembly?.MainModule.GetType (fullName);
		}

		public AssemblyDefinition? TryResolve (string name)
		{
			return TryResolve (new AssemblyNameReference (name, new Version ()));
		}

		public AssemblyDefinition? TryResolve (AssemblyNameReference name)
		{
			return _resolver.Resolve (name, probing: true);
		}

		public AssemblyDefinition? Resolve (IMetadataScope scope)
		{
			AssemblyNameReference reference = GetReference (scope);
			return _resolver.Resolve (reference);
		}

		public AssemblyDefinition? Resolve (AssemblyNameReference name)
		{
			return _resolver.Resolve (name);
		}

		public void RegisterAssembly (AssemblyDefinition assembly)
		{
			if (SeenFirstTime (assembly)) {
				SafeReadSymbols (assembly);
				Annotations.SetAction (assembly, CalculateAssemblyAction (assembly));
			}
		}

		protected bool SeenFirstTime (AssemblyDefinition assembly)
		{
			return !_annotations.HasAction (assembly);
		}

		public virtual void SafeReadSymbols (AssemblyDefinition assembly)
		{
			if (assembly.MainModule.HasSymbols)
				return;

			if (SymbolReaderProvider == null)
				throw new InvalidOperationException ("Symbol provider is not set");

			try {
				var symbolReader = SymbolReaderProvider.GetSymbolReader (
					assembly.MainModule,
					GetAssemblyLocation (assembly));

				if (symbolReader == null)
					return;

				try {
					assembly.MainModule.ReadSymbols (symbolReader);
				} catch {
					symbolReader.Dispose ();
					return;
				}

				// Add symbol reader to annotations only if we have successfully read it
				_annotations.AddSymbolReader (assembly, symbolReader);
			} catch { }
		}

		public virtual ICollection<AssemblyDefinition> ResolveReferences (AssemblyDefinition assembly)
		{
			List<AssemblyDefinition> references = new List<AssemblyDefinition> ();
			if (assembly == null)
				return references;

			foreach (AssemblyNameReference reference in assembly.MainModule.AssemblyReferences) {
				AssemblyDefinition? definition = Resolve (reference);
				if (definition != null)
					references.Add (definition);
			}

			return references;
		}

		static AssemblyNameReference GetReference (IMetadataScope scope)
		{
			AssemblyNameReference reference;
			if (scope is ModuleDefinition moduleDefinition) {
				AssemblyDefinition asm = moduleDefinition.Assembly;
				reference = asm.Name;
			} else
				reference = (AssemblyNameReference) scope;

			return reference;
		}

		public void RegisterAssemblyAction (string assemblyName, AssemblyAction action)
		{
			_actions[assemblyName] = action;
		}

#if !FEATURE_ILLINK
		public void SetAction (AssemblyDefinition assembly, AssemblyAction defaultAction)
		{
			if (!_actions.TryGetValue (assembly.Name.Name, out AssemblyAction action))
				action = defaultAction;

			Annotations.SetAction (assembly, action);
		}
#endif
		public AssemblyAction CalculateAssemblyAction (AssemblyDefinition assembly)
		{
			if (_actions.TryGetValue (assembly.Name.Name, out AssemblyAction action)) {
				if (IsCPPCLIAssembly (assembly.MainModule) && action != AssemblyAction.Copy && action != AssemblyAction.Skip) {
					LogWarning ($"Invalid assembly action '{action}' specified for assembly '{assembly.Name.Name}'. C++/CLI assemblies can only be copied or skipped.", 2106, GetAssemblyLocation (assembly));
					return AssemblyAction.Copy;
				}

				return action;
			}

			if (IsCPPCLIAssembly (assembly.MainModule))
				return DefaultAction == AssemblyAction.Skip ? DefaultAction : AssemblyAction.Copy;

			if (IsTrimmable (assembly))
				return TrimAction;

			return DefaultAction;

			static bool IsCPPCLIAssembly (ModuleDefinition module)
			{
				foreach (var type in module.Types)
					if (type.Namespace == "<CppImplementationDetails>" ||
						type.Namespace == "<CrtImplementationDetails>")
						return true;

				return false;
			}
		}

		public bool IsTrimmable (AssemblyDefinition assembly)
		{
			if (_isTrimmable.TryGetValue (assembly, out bool isTrimmable))
				return isTrimmable;

			if (!assembly.HasCustomAttributes) {
				_isTrimmable.Add (assembly, false);
				return false;
			}

			foreach (var ca in assembly.CustomAttributes) {
				if (!ca.AttributeType.IsTypeOf<AssemblyMetadataAttribute> ())
					continue;

				var args = ca.ConstructorArguments;
				if (args.Count != 2)
					continue;

				if (args[0].Value is not string key || !key.Equals ("IsTrimmable", StringComparison.OrdinalIgnoreCase))
					continue;

				if (args[1].Value is not string value || !value.Equals ("True", StringComparison.OrdinalIgnoreCase)) {
					LogWarning (GetAssemblyLocation (assembly), DiagnosticId.InvalidIsTrimmableValue, args[1].Value.ToString () ?? "", assembly.Name.Name);
					continue;
				}

				isTrimmable = true;
			}

			_isTrimmable.Add (assembly, isTrimmable);
			return isTrimmable;
		}

		public virtual AssemblyDefinition[] GetAssemblies ()
		{
			var cache = _resolver.AssemblyCache;
			AssemblyDefinition[] asms = new AssemblyDefinition[cache.Count];
			cache.Values.CopyTo (asms, 0);
			return asms;
		}

		public AssemblyDefinition? GetLoadedAssembly (string name)
		{
			if (!string.IsNullOrEmpty (name) && _resolver.AssemblyCache.TryGetValue (name, out var ad))
				return ad;

			return null;
		}

		public string GetAssemblyLocation (AssemblyDefinition assembly)
		{
			return Resolver.GetAssemblyLocation (assembly);
		}

		public IEnumerable<AssemblyDefinition> GetReferencedAssemblies ()
		{
			var assemblies = GetAssemblies ();

			foreach (var assembly in assemblies)
				yield return assembly;

			var loaded = new HashSet<AssemblyDefinition> (assemblies);
			var toProcess = new Queue<AssemblyDefinition> (assemblies);

			while (toProcess.Count > 0) {
				var assembly = toProcess.Dequeue ();
				foreach (var reference in ResolveReferences (assembly)) {
					if (!loaded.Add (reference))
						continue;
					yield return reference;
					toProcess.Enqueue (reference);
				}
			}
		}

		public void SetCustomData (string key, string value)
		{
			_parameters[key] = value;
		}

		public bool HasCustomData (string key)
		{
			return _parameters.ContainsKey (key);
		}

		public bool TryGetCustomData (string key, [NotNullWhen (true)] out string? value)
		{
			return _parameters.TryGetValue (key, out value);
		}

		public void Dispose ()
		{
			_resolver.Dispose ();
		}

		public bool IsOptimizationEnabled (CodeOptimizations optimization, MemberReference context)
		{
			return Optimizations.IsEnabled (optimization, context?.Module.Assembly);
		}

		public bool IsOptimizationEnabled (CodeOptimizations optimization, AssemblyDefinition? context)
		{
			return Optimizations.IsEnabled (optimization, context);
		}

		public bool CanApplyOptimization (CodeOptimizations optimization, AssemblyDefinition context)
		{
			return Annotations.GetAction (context) == AssemblyAction.Link &&
				IsOptimizationEnabled (optimization, context);
		}

		public void LogMessage (MessageContainer message)
		{
			if (message == MessageContainer.Empty)
				return;

			if ((message.Category == MessageCategory.Diagnostic ||
				message.Category == MessageCategory.Info) && !LogMessages)
				return;

			if (WarningSuppressionWriter != null &&
				message.IsWarningMessage (out int? code) &&
				message.Origin?.Provider is Mono.Cecil.ICustomAttributeProvider provider)
				WarningSuppressionWriter.AddWarning (code.Value, provider);

			if (message.Category == MessageCategory.Error || message.Category == MessageCategory.WarningAsError)
				ErrorsCount++;

			_logger.LogMessage (message);
		}

		public void LogMessage (string message)
		{
			if (!LogMessages)
				return;

			LogMessage (MessageContainer.CreateInfoMessage (message));
		}

		public void LogDiagnostic (string message)
		{
			if (!LogMessages)
				return;

			LogMessage (MessageContainer.CreateDiagnosticMessage (message));
		}


		/// <summary>
		/// Display a warning message to the end user.
		/// This API is used for warnings defined in the linker, not by custom steps. Warning
		/// versions are inferred from the code, and every warning that we define is versioned.
		/// </summary>
		/// <param name="text">Humanly readable message describing the warning</param>
		/// <param name="code">Unique warning ID. Please see https://github.com/dotnet/linker/blob/main/docs/error-codes.md for the list of warnings and possibly add a new one</param>
		/// <param name="origin">Filename or member where the warning is coming from</param>
		/// <param name="subcategory">Optionally, further categorize this warning</param>
		/// <returns>New MessageContainer of 'Warning' category</returns>
		public void LogWarning (string text, int code, MessageOrigin origin, string subcategory = MessageSubCategory.None)
		{
			WarnVersion version = GetWarningVersion ();
			MessageContainer warning = MessageContainer.CreateWarningMessage (this, text, code, origin, version, subcategory);
			_cachedWarningMessageContainers.Add (warning);
		}

		/// <summary>
		/// Display a warning message to the end user.
		/// This API is used for warnings defined in the linker, not by custom steps. Warning
		/// versions are inferred from the code, and every warning that we define is versioned.
		/// </summary>
		/// <param name="origin">Filename or member where the warning is coming from</param>
		/// <param name="id">Unique warning ID. Please see https://github.com/dotnet/linker/blob/main/docs/error-codes.md for the list of warnings and possibly add a new one</param>
		/// <param name="args">Additional arguments to form a humanly readable message describing the warning</param>
		/// <returns>New MessageContainer of 'Warning' category</returns>
		public void LogWarning (MessageOrigin origin, DiagnosticId id, params string[] args)
		{
			WarnVersion version = GetWarningVersion ();
			MessageContainer warning = MessageContainer.CreateWarningMessage (this, origin, id, version, args);
			_cachedWarningMessageContainers.Add (warning);
		}

		/// <summary>
		/// Display a warning message to the end user.
		/// This API is used for warnings defined in the linker, not by custom steps. Warning
		/// versions are inferred from the code, and every warning that we define is versioned.
		/// </summary>
		/// <param name="text">Humanly readable message describing the warning</param>
		/// <param name="code">Unique warning ID. Please see https://github.com/dotnet/linker/blob/main/docs/error-codes.md for the list of warnings and possibly add a new one</param>
		/// <param name="origin">Type or member where the warning is coming from</param>
		/// <param name="subcategory">Optionally, further categorize this warning</param>
		/// <returns>New MessageContainer of 'Warning' category</returns>
		public void LogWarning (string text, int code, IMemberDefinition origin, int? ilOffset = null, string subcategory = MessageSubCategory.None)
		{
			MessageOrigin _origin = new MessageOrigin (origin, ilOffset);
			LogWarning (text, code, _origin, subcategory);
		}

		/// <summary>
		/// Display a warning message to the end user.
		/// This API is used for warnings defined in the linker, not by custom steps. Warning
		/// versions are inferred from the code, and every warning that we define is versioned.
		/// </summary>
		/// <param name="origin">Type or member where the warning is coming from</param>
		/// <param name="id">Unique warning ID. Please see https://github.com/dotnet/linker/blob/main/docs/error-codes.md for the list of warnings and possibly add a new one</param>
		/// <param name="args">Additional arguments to form a humanly readable message describing the warning</param>
		/// <returns>New MessageContainer of 'Warning' category</returns>
		public void LogWarning (IMemberDefinition origin, DiagnosticId id, int? ilOffset = null, params string[] args)
		{
			MessageOrigin _origin = new MessageOrigin (origin, ilOffset);
			LogWarning (_origin, id, args);
		}

		/// <summary>
		/// Display a warning message to the end user.
		/// This API is used for warnings defined in the linker, not by custom steps. Warning
		/// versions are inferred from the code, and every warning that we define is versioned.
		/// </summary>
		/// <param name="origin">Type or member where the warning is coming from</param>
		/// <param name="id">Unique warning ID. Please see https://github.com/dotnet/linker/blob/main/docs/error-codes.md for the list of warnings and possibly add a new one</param>
		/// <param name="args">Additional arguments to form a humanly readable message describing the warning</param>
		/// <returns>New MessageContainer of 'Warning' category</returns>
		public void LogWarning (IMemberDefinition origin, DiagnosticId id, params string[] args)
		{
			MessageOrigin _origin = new MessageOrigin (origin);
			LogWarning (_origin, id, args);
		}

		/// <summary>
		/// Display a warning message to the end user.
		/// This API is used for warnings defined in the linker, not by custom steps. Warning
		/// versions are inferred from the code, and every warning that we define is versioned.
		/// </summary>
		/// <param name="text">Humanly readable message describing the warning</param>
		/// <param name="code">Unique warning ID. Please see https://github.com/dotnet/linker/blob/main/docs/error-codes.md for the list of warnings and possibly add a new one</param>
		/// <param name="origin">Filename where the warning is coming from</param>
		/// <param name="subcategory">Optionally, further categorize this warning</param>
		/// <returns>New MessageContainer of 'Warning' category</returns>
		public void LogWarning (string text, int code, string origin, string subcategory = MessageSubCategory.None)
		{
			MessageOrigin _origin = new MessageOrigin (origin);
			LogWarning (text, code, _origin, subcategory);
		}

		/// <summary>
		/// Display a warning message to the end user.
		/// This API is used for warnings defined in the linker, not by custom steps. Warning
		/// versions are inferred from the code, and every warning that we define is versioned.
		/// </summary>
		/// <param name="origin">Filename where the warning is coming from</param>
		/// <param name="id">Unique warning ID. Please see https://github.com/dotnet/linker/blob/main/docs/error-codes.md for the list of warnings and possibly add a new one</param>
		/// <param name="args">Additional arguments to form a humanly readable message describing the warning</param>
		/// <returns>New MessageContainer of 'Warning' category</returns>
		public void LogWarning (string origin, DiagnosticId id, params string[] args)
		{
			MessageOrigin _origin = new MessageOrigin (origin);
			LogWarning (_origin, id, args);
		}

		/// <summary>
		/// Display an error message to the end user.
		/// </summary>
		/// <param name="text">Humanly readable message describing the error</param>
		/// <param name="code">Unique error ID. Please see https://github.com/dotnet/linker/blob/main/docs/error-codes.md for the list of errors and possibly add a new one</param>
		/// <param name="subcategory">Optionally, further categorize this error</param>
		/// <param name="origin">Filename, line, and column where the error was found</param>
		/// <returns>New MessageContainer of 'Error' category</returns>
		public void LogError (string text, int code, string subcategory = MessageSubCategory.None, MessageOrigin? origin = null)
		{
			var error = MessageContainer.CreateErrorMessage (text, code, subcategory, origin);
			LogMessage (error);
		}

		/// <summary>
		/// Display an error message to the end user.
		/// </summary>
		/// <param name="origin">Filename, line, and column where the error was found</param>
		/// <param name="id">Unique error ID. Please see https://github.com/dotnet/linker/blob/main/docs/error-codes.md and https://github.com/dotnet/linker/blob/main/src/ILLink.Shared/DiagnosticId.cs for the list of errors and possibly add a new one</param>
		/// <param name="args">Additional arguments to form a humanly readable message describing the warning</param>
		/// <returns>New MessageContainer of 'Error' category</returns>
		public void LogError (MessageOrigin? origin, DiagnosticId id, params string[] args)
		{
			var error = MessageContainer.CreateErrorMessage (origin, id, args);
			LogMessage (error);
		}

		public void FlushCachedWarnings ()
		{
			_cachedWarningMessageContainers.Sort ();
			foreach (var warning in _cachedWarningMessageContainers)
				LogMessage (warning);

			_cachedWarningMessageContainers.Clear ();
		}

		public bool IsWarningSuppressed (int warningCode, string subcategory, MessageOrigin origin)
		{
			if (subcategory == MessageSubCategory.TrimAnalysis && NoTrimWarn)
				return true;

			// This warning was turned off by --nowarn.
			if (NoWarn.Contains (warningCode))
				return true;

			if (Suppressions == null)
				return false;

			return Suppressions.IsSuppressed (warningCode, origin, out _);
		}

		public bool IsWarningAsError (int warningCode)
		{
			bool value;
			if (GeneralWarnAsError)
				return !WarnAsError.TryGetValue (warningCode, out value) || value;

			return WarnAsError.TryGetValue (warningCode, out value) && value;
		}

		public bool IsSingleWarn (string assemblyName)
		{
			bool value;
			if (GeneralSingleWarn)
				return !SingleWarn.TryGetValue (assemblyName, out value) || value;

			return SingleWarn.TryGetValue (assemblyName, out value) && value;
		}

		static WarnVersion GetWarningVersion ()
		{
			// This should return an increasing WarnVersion for new warning waves.
			return WarnVersion.ILLink5;
		}

		public int GetTargetRuntimeVersion ()
		{
			if (_targetRuntime != null)
				return _targetRuntime.Value;

			TypeDefinition? objectType = BCL.FindPredefinedType (WellKnownType.System_Object, this);
			_targetRuntime = objectType?.Module.Assembly.Name.Version.Major ?? -1;

			return _targetRuntime.Value;
		}

		readonly Dictionary<MethodReference, MethodDefinition?> methodresolveCache = new ();
		readonly Dictionary<FieldReference, FieldDefinition?> fieldresolveCache = new ();
		readonly Dictionary<TypeReference, TypeDefinition?> typeresolveCache = new ();
		readonly Dictionary<ExportedType, TypeDefinition?> exportedTypeResolveCache = new ();

		/// <summary>
		/// Tries to resolve the MethodReference to a MethodDefinition and logs a warning if it can't
		/// </summary>
		public MethodDefinition? Resolve (MethodReference methodReference)
		{
			if (methodReference is MethodDefinition methodDefinition)
				return methodDefinition;

			if (methodReference is null)
				return null;

			if (methodresolveCache.TryGetValue (methodReference, out MethodDefinition? md))
				return md;

#pragma warning disable RS0030 // Cecil's resolve is banned -- this provides the wrapper
			md = methodReference.Resolve ();
#pragma warning restore RS0030
			if (md == null && !IgnoreUnresolved)
				ReportUnresolved (methodReference);

			methodresolveCache.Add (methodReference, md);
			return md;
		}

		/// <summary>
		/// Tries to resolve the MethodReference to a MethodDefinition and returns null if it can't
		/// </summary>
		public MethodDefinition? TryResolve (MethodReference methodReference)
		{
			if (methodReference is MethodDefinition methodDefinition)
				return methodDefinition;

			if (methodReference is null)
				return null;

			if (methodresolveCache.TryGetValue (methodReference, out MethodDefinition? md))
				return md;

#pragma warning disable RS0030 // Cecil's resolve is banned -- this method provides the wrapper
			md = methodReference.Resolve ();
#pragma warning restore RS0030
			methodresolveCache.Add (methodReference, md);
			return md;
		}

		/// <summary>
		/// Tries to resolve the FieldReference to a FieldDefinition and logs a warning if it can't
		/// </summary>
		public FieldDefinition? Resolve (FieldReference fieldReference)
		{
			if (fieldReference is FieldDefinition fieldDefinition)
				return fieldDefinition;

			if (fieldReference is null)
				return null;

			if (fieldresolveCache.TryGetValue (fieldReference, out FieldDefinition? fd))
				return fd;

			fd = fieldReference.Resolve ();
			if (fd == null && !IgnoreUnresolved)
				ReportUnresolved (fieldReference);

			fieldresolveCache.Add (fieldReference, fd);
			return fd;
		}

		/// <summary>
		/// Tries to resolve the FieldReference to a FieldDefinition and returns null if it can't
		/// </summary>
		public FieldDefinition? TryResolve (FieldReference fieldReference)
		{
			if (fieldReference is FieldDefinition fieldDefinition)
				return fieldDefinition;

			if (fieldReference is null)
				return null;

			if (fieldresolveCache.TryGetValue (fieldReference, out FieldDefinition? fd))
				return fd;

			fd = fieldReference.Resolve ();
			fieldresolveCache.Add (fieldReference, fd);
			return fd;
		}

		/// <summary>
		/// Tries to resolve the TypeReference to a TypeDefinition and logs a warning if it can't
		/// </summary>
		public TypeDefinition? Resolve (TypeReference typeReference)
		{
			if (typeReference is TypeDefinition typeDefinition)
				return typeDefinition;

			if (typeReference is null)
				return null;

			if (typeresolveCache.TryGetValue (typeReference, out TypeDefinition? td))
				return td;

			//
			// Types which never have TypeDefinition or can have ambiguous definition should not be passed in
			//
			if (typeReference is GenericParameter || (typeReference is TypeSpecification && typeReference is not GenericInstanceType))
				throw new NotSupportedException ($"TypeDefinition cannot be resolved from '{typeReference.GetType ()}' type");

#pragma warning disable RS0030
			td = typeReference.Resolve ();
#pragma warning restore RS0030
			if (td == null && !IgnoreUnresolved)
				ReportUnresolved (typeReference);

			typeresolveCache.Add (typeReference, td);
			return td;
		}

		/// <summary>
		/// Tries to resolve the TypeReference to a TypeDefinition and returns null if it can't
		/// </summary>
		public TypeDefinition? TryResolve (TypeReference typeReference)
		{
			if (typeReference is TypeDefinition typeDefinition)
				return typeDefinition;

			if (typeReference is null || typeReference is GenericParameter)
				return null;

			if (typeresolveCache.TryGetValue (typeReference, out TypeDefinition? td))
				return td;

			if (typeReference is TypeSpecification ts) {
				if (typeReference is FunctionPointerType) {
					td = null;
				} else {
					//
					// It returns element-type for arrays and also element type for wrapping types like ByReference, PinnedType, etc
					//
					td = TryResolve (ts.GetElementType ());
				}
			} else {
#pragma warning disable RS0030
				td = typeReference.Resolve ();
#pragma warning restore RS0030
			}

			typeresolveCache.Add (typeReference, td);
			return td;
		}

		/// <summary>
		/// Tries to resolve the ExportedType to a TypeDefinition and logs a warning if it can't
		/// </summary>
		public TypeDefinition? Resolve (ExportedType et)
		{
			if (TryResolve (et) is not TypeDefinition td) {
				ReportUnresolved (et);
				return null;
			}
			return td;
		}

		/// <summary>
		/// Tries to resolve the ExportedType to a TypeDefinition and returns null if it can't
		/// </summary>
		public TypeDefinition? TryResolve (ExportedType et)
		{
			if (exportedTypeResolveCache.TryGetValue (et, out var td)) {
				return td;
			}
#pragma warning disable RS0030 // Cecil's Resolve is banned -- this method provides the wrapper
			td = et.Resolve ();
#pragma warning restore RS0030
			exportedTypeResolveCache.Add (et, td);
			return td;
		}

		public TypeDefinition? TryResolve (AssemblyDefinition assembly, string typeNameString)
		{
			// It could be cached if it shows up on fast path
			return _typeNameResolver.TryResolveTypeName (assembly, typeNameString, out TypeReference? typeReference, out _)
				? TryResolve (typeReference)
				: null;
		}

		readonly HashSet<MethodDefinition> _processed_bodies_for_method = new HashSet<MethodDefinition> (2048);

		/// <summary>
		/// Linker applies some optimization on method bodies. For example it can remove dead branches of code
		/// based on constant propagation. To avoid overmarking, all code which processes the method's IL
		/// should only view the IL after it's been optimized.
		/// As such typically MethodDefinition.MethodBody should not be accessed directly on the Cecil object model
		/// instead all accesses to method body should go through the ILProvider here
		/// which will make sure the IL of the method is fully optimized before it's handed out.
		/// </summary>
		public MethodIL GetMethodIL (Cecil.Cil.MethodBody methodBody)
			=> GetMethodIL (methodBody.Method);

		public MethodIL GetMethodIL (MethodDefinition method)
		{
			if (_processed_bodies_for_method.Add (method)) {
				_unreachableBlocksOptimizer.ProcessMethod (method);
			}

			return MethodIL.Create (method.Body);
		}

		readonly HashSet<MemberReference> unresolved_reported = new ();

		readonly HashSet<ExportedType> unresolved_exported_types_reported = new ();

		protected virtual void ReportUnresolved (FieldReference fieldReference)
		{
			if (unresolved_reported.Add (fieldReference))
				LogError (string.Format (SharedStrings.FailedToResolveFieldElementMessage, fieldReference.FullName), (int) DiagnosticId.FailedToResolveMetadataElement);
		}

		protected virtual void ReportUnresolved (MethodReference methodReference)
		{
			if (unresolved_reported.Add (methodReference))
				LogError (string.Format (SharedStrings.FailedToResolveMethodElementMessage, methodReference.GetDisplayName ()), (int) DiagnosticId.FailedToResolveMetadataElement);
		}

		protected virtual void ReportUnresolved (TypeReference typeReference)
		{
			if (unresolved_reported.Add (typeReference))
				LogError (string.Format (SharedStrings.FailedToResolveTypeElementMessage, typeReference.GetDisplayName ()), (int) DiagnosticId.FailedToResolveMetadataElement);
		}

		protected virtual void ReportUnresolved (ExportedType et)
		{
			if (unresolved_exported_types_reported.Add (et))
				LogError (string.Format (SharedStrings.FailedToResolveTypeElementMessage, et.Name), (int) DiagnosticId.FailedToResolveMetadataElement);
		}
	}

	public class CodeOptimizationsSettings
	{
		sealed class Pair
		{
			public Pair (CodeOptimizations set, CodeOptimizations values)
			{
				this.Set = set;
				this.Values = values;
			}

			public CodeOptimizations Set;
			public CodeOptimizations Values;
		}

		readonly Dictionary<string, Pair> perAssembly = new ();

		public CodeOptimizationsSettings (CodeOptimizations globalOptimizations)
		{
			Global = globalOptimizations;
		}

		public CodeOptimizations Global { get; private set; }

		internal bool IsEnabled (CodeOptimizations optimizations, AssemblyDefinition? context)
		{
			return IsEnabled (optimizations, context?.Name.Name);
		}

		public bool IsEnabled (CodeOptimizations optimizations, string? assemblyName)
		{
			// Only one bit is set
			Debug.Assert (optimizations != 0 && (optimizations & (optimizations - 1)) == 0);

			if (perAssembly.Count > 0 && assemblyName != null &&
				perAssembly.TryGetValue (assemblyName, out var assemblySetting) &&
				(assemblySetting.Set & optimizations) != 0) {
				return (assemblySetting.Values & optimizations) != 0;
			}

			return (Global & optimizations) != 0;
		}

		public void Enable (CodeOptimizations optimizations, string? assemblyContext = null)
		{
			if (assemblyContext == null) {
				Global |= optimizations;
				return;
			}

			if (!perAssembly.TryGetValue (assemblyContext, out var assemblySetting)) {
				perAssembly.Add (assemblyContext, new Pair (optimizations, optimizations));
				return;
			}

			assemblySetting.Set |= optimizations;
			assemblySetting.Values |= optimizations;
		}

		public void Disable (CodeOptimizations optimizations, string? assemblyContext = null)
		{
			if (assemblyContext == null) {
				Global &= ~optimizations;
				return;
			}

			if (!perAssembly.TryGetValue (assemblyContext, out var assemblySetting)) {
				perAssembly.Add (assemblyContext, new Pair (optimizations, 0));
				return;
			}

			assemblySetting.Set |= optimizations;
			assemblySetting.Values &= ~optimizations;
		}
	}

	[Flags]
	public enum CodeOptimizations
	{
		BeforeFieldInit = 1 << 0,

		/// <summary>
		/// Option to disable removal of overrides of virtual methods when a type is never instantiated
		///
		/// Being able to disable this optimization is helpful when trying to troubleshoot problems caused by types created via reflection or from native
		/// that do not get an instance constructor marked.
		/// </summary>
		OverrideRemoval = 1 << 1,

		/// <summary>
		/// Option to disable delaying marking of instance methods until an instance of that type could exist
		/// </summary>
		UnreachableBodies = 1 << 2,

		/// <summary>
		/// Option to remove .interfaceimpl for interface types that are not used
		/// </summary>
		UnusedInterfaces = 1 << 3,

		/// <summary>
		/// Option to do interprocedural constant propagation on return values
		/// </summary>
		IPConstantPropagation = 1 << 4,

		/// <summary>
		/// Devirtualizes methods and seals types
		/// </summary>
		Sealer = 1 << 5,

		/// <summary>
		/// Option to inline typechecks for never instantiated types
		/// </summary>
		UnusedTypeChecks = 1 << 6,


		RemoveDescriptors = 1 << 20,
		RemoveSubstitutions = 1 << 21,
		RemoveLinkAttributes = 1 << 22,
		RemoveDynamicDependencyAttribute = 1 << 23,

		/// <summary>
		/// Option to apply annotations to type heirarchy
		/// Enable type heirarchy apply in library mode to annotate derived types eagerly
		/// Otherwise, type annotation will only be applied with calls to object.GetType()
		/// </summary>
		OptimizeTypeHierarchyAnnotations = 1 << 24,
	}
}