Skip to content

Commit

Permalink
Add ILLink/ILCompiler support for feature checks (#99267)
Browse files Browse the repository at this point in the history
This will substitute static boolean properties with `false` when
decorated with `[FeatureGuard(typeof(SomeFeature))]`, where
`SomeFeature` is known to be disabled.

The "feature" of unreferenced code, represented by
`RequiresUnreferencedCodeAttribute`, is always considered
disabled. For ILC, `RequiresDynamicCodeAttribute` and
`RequiresAssemblyFilesAttribute` are also disabled. ILLink also
respects the feature switch for `IsDynamicCodeSupported` to
disable the `RequiresDynamicCodeAttribute` feature.

We don't want this kicking in when trimming in library mode, so
this adds an ILLink option to disable the optimization.

Additionally, a property is substituted if it has
`[FeatureSwitchDefinition("SomeFeatureName")]` and
`"SomeFeatureName"` is set in the command-line arguments.

XML substitutions take precedence over this behavior.

Includes a few tweaks and cleanup to the analyzer logic.
  • Loading branch information
sbomer committed Mar 11, 2024
1 parent 6aca07a commit e9e33e1
Show file tree
Hide file tree
Showing 23 changed files with 794 additions and 199 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Resources;
Expand Down Expand Up @@ -33,11 +34,84 @@ public BodySubstitution GetSubstitution(MethodDesc method)
AssemblyFeatureInfo info = _hashtable.GetOrCreateValue(ecmaMethod.Module);
if (info.BodySubstitutions != null && info.BodySubstitutions.TryGetValue(ecmaMethod, out BodySubstitution result))
return result;

if (TryGetFeatureCheckValue(ecmaMethod, out bool value))
return BodySubstitution.Create(value ? 1 : 0);
}

return null;
}

private bool TryGetFeatureCheckValue(EcmaMethod method, out bool value)
{
value = false;

if (!method.Signature.IsStatic)
return false;

if (!method.Signature.ReturnType.IsWellKnownType(WellKnownType.Boolean))
return false;

if (FindProperty(method) is not PropertyPseudoDesc property)
return false;

if (property.SetMethod != null)
return false;

foreach (var featureSwitchDefinitionAttribute in property.GetDecodedCustomAttributes("System.Diagnostics.CodeAnalysis", "FeatureSwitchDefinitionAttribute"))
{
if (featureSwitchDefinitionAttribute.FixedArguments is not [CustomAttributeTypedArgument<TypeDesc> { Value: string switchName }])
continue;

// If there's a FeatureSwitchDefinition, don't continue looking for FeatureGuard.
// We don't want to infer feature switch settings from FeatureGuard.
return _hashtable._switchValues.TryGetValue(switchName, out value);
}

foreach (var featureGuardAttribute in property.GetDecodedCustomAttributes("System.Diagnostics.CodeAnalysis", "FeatureGuardAttribute"))
{
if (featureGuardAttribute.FixedArguments is not [CustomAttributeTypedArgument<TypeDesc> { Value: EcmaType featureType }])
continue;

if (featureType.Namespace == "System.Diagnostics.CodeAnalysis") {
switch (featureType.Name) {
case "RequiresAssemblyFilesAttribute":
case "RequiresUnreferencedCodeAttribute":
return true;
case "RequiresDynamicCodeAttribute":
if (_hashtable._switchValues.TryGetValue(
"System.Runtime.CompilerServices.RuntimeFeature.IsDynamicCodeSupported",
out bool isDynamicCodeSupported)
&& !isDynamicCodeSupported)
return true;
break;
}
}
}

return false;

static PropertyPseudoDesc FindProperty(EcmaMethod method)
{
if ((method.Attributes & MethodAttributes.SpecialName) == 0)
return null;

if (method.OwningType is not EcmaType declaringType)
return null;

var reader = declaringType.MetadataReader;
foreach (PropertyDefinitionHandle propertyHandle in reader.GetTypeDefinition(declaringType.Handle).GetProperties())
{
PropertyDefinition propertyDef = reader.GetPropertyDefinition(propertyHandle);
var property = new PropertyPseudoDesc(declaringType, propertyHandle);
if (property.GetMethod == method)
return property;
}

return null;
}
}

public object GetSubstitution(FieldDesc field)
{
if (field.GetTypicalFieldDefinition() is EcmaField ecmaField)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ public static IEnumerable<object[]> SingleFile ()
return TestNamesBySuiteName ();
}

public static IEnumerable<object[]> Substitutions ()
{
return TestNamesBySuiteName ();
}

public static IEnumerable<object[]> TopLevelStatements ()
{
return TestNamesBySuiteName ();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,20 @@ public void SingleFile (string t)
Run (t);
}

[Theory]
[MemberData (nameof (TestDatabase.Substitutions), MemberType = typeof (TestDatabase))]
public void Substitutions (string t)
{
switch (t) {
case "FeatureGuardSubstitutions":
Run (t);
break;
default:
// Skip the rest for now
break;
}
}

[Theory]
[MemberData (nameof (TestDatabase.TopLevelStatements), MemberType = typeof (TestDatabase))]
public void TopLevelStatements (string t)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,8 @@ internal static DynamicallyAccessedMemberTypes GetDynamicallyAccessedMemberTypes
internal static ValueSet<string> GetFeatureGuardAnnotations (this IPropertySymbol propertySymbol)
{
HashSet<string> featureSet = new ();
foreach (var attributeData in propertySymbol.GetAttributes (DynamicallyAccessedMembersAnalyzer.FullyQualifiedFeatureGuardAttribute)) {
if (attributeData.ConstructorArguments is [TypedConstant { Value: INamedTypeSymbol featureType }])
foreach (var featureGuardAttribute in propertySymbol.GetAttributes (DynamicallyAccessedMembersAnalyzer.FullyQualifiedFeatureGuardAttribute)) {
if (featureGuardAttribute.ConstructorArguments is [TypedConstant { Value: INamedTypeSymbol featureType }])
featureSet.Add (featureType.GetDisplayName ());
}
return featureSet.Count == 0 ? ValueSet<string>.Empty : new ValueSet<string> (featureSet);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ protected virtual bool CreateSpecialIncompatibleMembersDiagnostic (
internal static bool IsAnnotatedFeatureGuard (IPropertySymbol propertySymbol, string featureName)
{
// Only respect FeatureGuardAttribute on static boolean properties.
if (!propertySymbol.IsStatic || propertySymbol.Type.SpecialType != SpecialType.System_Boolean)
if (!propertySymbol.IsStatic || propertySymbol.Type.SpecialType != SpecialType.System_Boolean || propertySymbol.SetMethod != null)
return false;

ValueSet<string> featureCheckAnnotations = propertySymbol.GetFeatureGuardAnnotations ();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ public IEnumerable<Diagnostic> CollectDiagnostics (DataFlowAnalyzerContext conte
if (!context.EnableTrimAnalyzer)
return diagnosticContext.Diagnostics;

if (!OwningSymbol.IsStatic || OwningSymbol.Type.SpecialType != SpecialType.System_Boolean) {
// Warn about invalid feature checks (non-static or non-bool properties)
if (!OwningSymbol.IsStatic || OwningSymbol.Type.SpecialType != SpecialType.System_Boolean || OwningSymbol.SetMethod != null) {
// Warn about invalid feature checks (non-static or non-bool properties or properties with setter)
diagnosticContext.AddDiagnostic (
DiagnosticId.InvalidFeatureGuard);
return diagnosticContext.Diagnostics;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,6 @@ public class TrimAnalysisVisitor : LocalDataFlowVisitor<

FeatureChecksVisitor _featureChecksVisitor;

DataFlowAnalyzerContext _dataFlowAnalyzerContext;

public TrimAnalysisVisitor (
Compilation compilation,
LocalStateAndContextLattice<MultiValue, FeatureContext, ValueSetLattice<SingleValue>, FeatureContextLattice> lattice,
Expand All @@ -59,7 +57,6 @@ public TrimAnalysisVisitor (
_multiValueLattice = lattice.LocalStateLattice.Lattice.ValueLattice;
TrimAnalysisPatterns = trimAnalysisPatterns;
_featureChecksVisitor = new FeatureChecksVisitor (dataFlowAnalyzerContext);
_dataFlowAnalyzerContext = dataFlowAnalyzerContext;
}

public override FeatureChecksValue GetConditionValue (IOperation branchValueOperation, StateValue state)
Expand Down Expand Up @@ -436,7 +433,8 @@ public override void HandleReturnConditionValue (FeatureChecksValue returnCondit
if (OwningSymbol is not IMethodSymbol method)
return;

// FeatureGuard validation needs to happen only for properties.
// FeatureGuard validation needs to happen only for property getters.
// Include properties with setters here because they will get validated later.
if (method.MethodKind != MethodKind.PropertyGet)
return;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ protected override void Process ()
CodeOptimizations.RemoveLinkAttributes |
CodeOptimizations.RemoveSubstitutions |
CodeOptimizations.RemoveDynamicDependencyAttribute |
CodeOptimizations.OptimizeTypeHierarchyAnnotations, assembly.Name.Name);
CodeOptimizations.OptimizeTypeHierarchyAnnotations |
CodeOptimizations.SubstituteFeatureGuards, assembly.Name.Name);

// Enable EventSource special handling
Context.DisableEventSourceSpecialHandling = false;
Expand Down
8 changes: 8 additions & 0 deletions src/tools/illink/src/linker/Linker/CustomAttributeSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,14 @@ public bool TryGetEmbeddedXmlInfo (ICustomAttributeProvider provider, [NotNullWh
return xmlInfo != null;
}

public IEnumerable<CustomAttribute> GetCustomAttributes (ICustomAttributeProvider provider, string attributeNamespace, string attributeName)
{
foreach (var attr in GetCustomAttributes (provider)) {
if (attr.AttributeType.Namespace == attributeNamespace && attr.AttributeType.Name == attributeName)
yield return attr;
}
}

public IEnumerable<CustomAttribute> GetCustomAttributes (ICustomAttributeProvider provider)
{
if (provider.HasCustomAttributes) {
Expand Down
4 changes: 4 additions & 0 deletions src/tools/illink/src/linker/Linker/Driver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1179,6 +1179,9 @@ protected bool GetOptimizationName (string text, out CodeOptimizations optimizat
case "sealer":
optimization = CodeOptimizations.Sealer;
return true;
case "substitutefeatureguards":
optimization = CodeOptimizations.SubstituteFeatureGuards;
return true;
}

Context.LogError (null, DiagnosticId.InvalidOptimizationValue, text);
Expand Down Expand Up @@ -1361,6 +1364,7 @@ static void Usage ()
Console.WriteLine (" unreachablebodies: Instance methods that are marked but not executed are converted to throws");
Console.WriteLine (" unusedinterfaces: Removes interface types from declaration when not used");
Console.WriteLine (" unusedtypechecks: Inlines never successful type checks");
Console.WriteLine (" substitutefeatureguards: Substitutes properties annotated as FeatureGuard(typeof(RequiresUnreferencedCodeAttribute)) to false");
Console.WriteLine (" --enable-opt NAME [ASM] Enable one of the additional optimizations globaly or for a specific assembly name");
Console.WriteLine (" sealer: Any method or type which does not have override is marked as sealed");
Console.WriteLine (" --explicit-reflection Adds to members never used through reflection DisablePrivateReflection attribute. Defaults to false");
Expand Down
8 changes: 7 additions & 1 deletion src/tools/illink/src/linker/Linker/LinkContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,8 @@ protected LinkContext (Pipeline pipeline, ILogger logger, string outputDirectory
CodeOptimizations.RemoveLinkAttributes |
CodeOptimizations.RemoveSubstitutions |
CodeOptimizations.RemoveDynamicDependencyAttribute |
CodeOptimizations.OptimizeTypeHierarchyAnnotations;
CodeOptimizations.OptimizeTypeHierarchyAnnotations |
CodeOptimizations.SubstituteFeatureGuards;

DisableEventSourceSpecialHandling = true;

Expand Down Expand Up @@ -1144,5 +1145,10 @@ public enum CodeOptimizations
/// Otherwise, type annotation will only be applied with calls to object.GetType()
/// </summary>
OptimizeTypeHierarchyAnnotations = 1 << 24,

/// <summary>
/// Option to substitute properties annotated as FeatureGuard(typeof(RequiresUnreferencedCodeAttribute)) with false
/// </summary>
SubstituteFeatureGuards = 1 << 25,
}
}
79 changes: 76 additions & 3 deletions src/tools/illink/src/linker/Linker/MemberActionStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using ILLink.Shared;
using Mono.Cecil;

namespace Mono.Linker
Expand All @@ -20,7 +22,7 @@ public MemberActionStore (LinkContext context)
_context = context;
}

public bool TryGetSubstitutionInfo (MemberReference member, [NotNullWhen (true)] out SubstitutionInfo? xmlInfo)
private bool TryGetSubstitutionInfo (MemberReference member, [NotNullWhen (true)] out SubstitutionInfo? xmlInfo)
{
var assembly = member.Module.Assembly;
if (!_embeddedXmlInfos.TryGetValue (assembly, out xmlInfo)) {
Expand All @@ -41,6 +43,9 @@ public MethodAction GetAction (MethodDefinition method)
return action;
}

if (TryGetFeatureCheckValue (method, out _))
return MethodAction.ConvertToStub;

return MethodAction.Nothing;
}

Expand All @@ -49,10 +54,78 @@ public bool TryGetMethodStubValue (MethodDefinition method, out object? value)
if (PrimarySubstitutionInfo.MethodStubValues.TryGetValue (method, out value))
return true;

if (!TryGetSubstitutionInfo (method, out var embeddedXml))
if (TryGetSubstitutionInfo (method, out var embeddedXml)
&& embeddedXml.MethodStubValues.TryGetValue (method, out value))
return true;

if (TryGetFeatureCheckValue (method, out bool bValue)) {
value = bValue ? 1 : 0;
return true;
}

return false;
}

internal bool TryGetFeatureCheckValue (MethodDefinition method, out bool value)
{
value = false;

if (!method.IsStatic)
return false;

if (method.ReturnType.MetadataType != MetadataType.Boolean)
return false;

if (FindProperty (method) is not PropertyDefinition property)
return false;

return embeddedXml.MethodStubValues.TryGetValue (method, out value);
if (property.SetMethod != null)
return false;

foreach (var featureSwitchDefinitionAttribute in _context.CustomAttributes.GetCustomAttributes (property, "System.Diagnostics.CodeAnalysis", "FeatureSwitchDefinitionAttribute")) {
if (featureSwitchDefinitionAttribute.ConstructorArguments is not [CustomAttributeArgument { Value: string switchName }])
continue;

// If there's a FeatureSwitchDefinition, don't continue looking for FeatureGuard.
// We don't want to infer feature switch settings from FeatureGuard.
return _context.FeatureSettings.TryGetValue (switchName, out value);
}

if (!_context.IsOptimizationEnabled (CodeOptimizations.SubstituteFeatureGuards, method))
return false;

foreach (var featureGuardAttribute in _context.CustomAttributes.GetCustomAttributes (property, "System.Diagnostics.CodeAnalysis", "FeatureGuardAttribute")) {
if (featureGuardAttribute.ConstructorArguments is not [CustomAttributeArgument { Value: TypeReference featureType }])
continue;

if (featureType.Namespace == "System.Diagnostics.CodeAnalysis") {
switch (featureType.Name) {
case "RequiresUnreferencedCodeAttribute":
return true;
case "RequiresDynamicCodeAttribute":
if (_context.FeatureSettings.TryGetValue (
"System.Runtime.CompilerServices.RuntimeFeature.IsDynamicCodeSupported",
out bool isDynamicCodeSupported)
&& !isDynamicCodeSupported)
return true;
break;
}
}
}

return false;

static PropertyDefinition? FindProperty (MethodDefinition method) {
if (!method.IsGetter)
return null;

foreach (var property in method.DeclaringType.Properties) {
if (property.GetMethod == method)
return property;
}

return null;
}
}

public bool TryGetFieldUserValue (FieldDefinition field, out object? value)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;
using System.Threading.Tasks;
using Xunit;

namespace ILLink.RoslynAnalyzer.Tests
{
public sealed partial class SubstitutionsTests : LinkerTestBase
{
protected override string TestSuiteName => "Substitutions";

[Fact]
public Task FeatureGuardSubstitutions ()
{
return RunTest ();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ namespace ILLink.RoslynAnalyzer.Tests
public sealed partial class SubstitutionsTests : LinkerTestBase
{

protected override string TestSuiteName => "Substitutions";

[Fact]
public Task EmbeddedFieldSubstitutionsInReferencedAssembly ()
{
Expand Down Expand Up @@ -45,6 +43,12 @@ public Task EmbeddedSubstitutionsNotProcessedWithIgnoreSubstitutionsAndRemoved (
return RunTest (allowMissingWarnings: true);
}

[Fact]
public Task FeatureGuardSubstitutionsDisabled ()
{
return RunTest (allowMissingWarnings: true);
}

[Fact]
public Task InitField ()
{
Expand Down
Loading

0 comments on commit e9e33e1

Please sign in to comment.