Skip to content

Commit de835bf

Browse files
lewingCopilot
andcommitted
Keep MustNot for casts whose types all version with the R2R code
Address review feedback: - Drop the Nullable<T> source exclusion. No object's exact type is Nullable<T> (the box path passes getTypeForBox), and the VM's compareTypesForCast doesn't exclude it. - Also keep MustNot when toType and every type in fromType's base chain and interface list version with the compilation (e.g. CoreLib, composite and input-bubble builds). Arrays, variant targets and COM types stay May. Move the policy into CorInfoImpl.ReadyToRun.cs. Cover both per-assembly and input-bubble builds in the R2R test, and fix the test harness's InputBubble option, which passed --input-bubble instead of --inputbubble. Co-authored-by: Copilot App <[email protected]> Copilot-Session: e57ce813-cc00-4e28-824c-2eecc4d8fb9f
1 parent 403230c commit de835bf

6 files changed

Lines changed: 189 additions & 56 deletions

File tree

‎src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3179,13 +3179,8 @@ private TypeCompareState compareTypesForCast(CORINFO_CLASS_STRUCT_* fromClass, C
31793179
// In R2R it is a breaking change for a previously positive
31803180
// cast to become negative, but not for a previously negative
31813181
// cast to become positive. So in R2R a negative result is
3182-
// reported back as May, unless it can't change across versions:
3183-
// a value type can gain interfaces (or become an enum), but its
3184-
// other cast targets are fixed.
3185-
if (result == TypeCompareState.MustNot &&
3186-
!(fromType.IsValueType && !fromType.IsNullable &&
3187-
!toType.IsInterface && !toType.IsWellKnownType(WellKnownType.Enum) &&
3188-
!fromType.HasTypeEquivalence && !toType.HasTypeEquivalence))
3182+
// reported back as May, unless it can't change across versions.
3183+
if (result == TypeCompareState.MustNot && !IsNegativeCastResultVersionResilient(fromType, toType))
31893184
{
31903185
result = TypeCompareState.May;
31913186
}

‎src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/CastFolding/BoxIsInstFolding.cs‎

Lines changed: 0 additions & 35 deletions
This file was deleted.
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using System;
5+
using System.Runtime.CompilerServices;
6+
using System.Runtime.InteropServices;
7+
8+
public interface INotImplemented
9+
{
10+
}
11+
12+
public interface INotImplementedByClass
13+
{
14+
}
15+
16+
public interface INotImplementedByCom
17+
{
18+
}
19+
20+
public interface IVariant<out T>
21+
{
22+
}
23+
24+
public interface ISource
25+
{
26+
}
27+
28+
public interface ITarget
29+
{
30+
}
31+
32+
public interface ISourceForOutsideTarget
33+
{
34+
}
35+
36+
public interface IDerivedFromOutside : IDisposable
37+
{
38+
}
39+
40+
public interface ITargetOfDerived
41+
{
42+
}
43+
44+
public interface IGenericSource<T>
45+
{
46+
}
47+
48+
public interface ITargetOfGeneric
49+
{
50+
}
51+
52+
public struct SourceStruct
53+
{
54+
public int Value;
55+
}
56+
57+
public struct TargetStruct
58+
{
59+
public int Value;
60+
}
61+
62+
public struct ControlStruct
63+
{
64+
public int Value;
65+
}
66+
67+
public sealed class SealedClass
68+
{
69+
}
70+
71+
public sealed class VariantImplementation : IVariant<string>
72+
{
73+
}
74+
75+
[ComImport]
76+
[Guid("8F4E2A61-5C9B-4D3E-A7F0-1B2C3D4E5F60")]
77+
public sealed class ComClass
78+
{
79+
}
80+
81+
public static class CastFolding
82+
{
83+
[MethodImpl(MethodImplOptions.NoInlining)]
84+
public static bool CharIsByte(char c) => (object)c is byte;
85+
86+
[MethodImpl(MethodImplOptions.NoInlining)]
87+
public static bool StructIsOtherStruct(SourceStruct s) => (object)s is TargetStruct;
88+
89+
[MethodImpl(MethodImplOptions.NoInlining)]
90+
public static bool StructIsInterface(ControlStruct s) => (object)s is INotImplemented;
91+
92+
[MethodImpl(MethodImplOptions.NoInlining)]
93+
public static bool SealedClassIsInterface(SealedClass c) => (object)c is INotImplementedByClass;
94+
95+
[MethodImpl(MethodImplOptions.NoInlining)]
96+
public static bool VariantCast(VariantImplementation v) => (object)v is IVariant<SealedClass>;
97+
98+
[MethodImpl(MethodImplOptions.NoInlining)]
99+
public static bool ComClassIsInterface(ComClass c) => (object)c is INotImplementedByCom;
100+
101+
// Each guard gets a signal of its own: an unfolded IsAssignableFrom or IsAssignableTo leaves an import
102+
// for its call, while the type handle imports for typeof remain even when the cast folds.
103+
[MethodImpl(MethodImplOptions.NoInlining)]
104+
public static bool InterfaceIsInterface() => typeof(ITarget).IsAssignableFrom(typeof(ISource));
105+
106+
[MethodImpl(MethodImplOptions.NoInlining)]
107+
public static bool InterfaceIsOutsideInterface() => typeof(IComparable).IsAssignableFrom(typeof(ISourceForOutsideTarget));
108+
109+
[MethodImpl(MethodImplOptions.NoInlining)]
110+
public static bool DerivedFromOutsideIsInterface() => typeof(IDerivedFromOutside).IsAssignableTo(typeof(ITargetOfDerived));
111+
112+
[MethodImpl(MethodImplOptions.NoInlining)]
113+
public static bool SharedGenericIsInterface<T>() where T : class => typeof(ITargetOfGeneric).IsAssignableFrom(typeof(IGenericSource<T>));
114+
115+
[MethodImpl(MethodImplOptions.NoInlining)]
116+
public static bool CallSharedGeneric() => SharedGenericIsInterface<string>();
117+
}

‎src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/R2RTestSuites.cs‎

Lines changed: 31 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -145,26 +145,31 @@ static void Validate(ReadyToRunReader reader)
145145
}
146146
}
147147

148-
[Fact]
149-
public void BoxIsInstOfValueTypeFolds()
148+
[Theory]
149+
[InlineData(false)]
150+
[InlineData(true)]
151+
public void CastFoldingRespectsVersionBubble(bool inputBubble)
150152
{
151-
var boxIsInstFolding = new CompiledAssembly
153+
var castFolding = new CompiledAssembly
152154
{
153-
AssemblyName = nameof(BoxIsInstOfValueTypeFolds),
154-
SourceResourceNames = ["CastFolding/BoxIsInstFolding.cs"],
155+
AssemblyName = nameof(CastFoldingRespectsVersionBubble),
156+
SourceResourceNames = ["CastFolding/CastFolding.cs"],
155157
};
156158

159+
// With --input-bubble and no explicit bubble references, the framework is in the version bubble.
160+
List<Crossgen2Option> options = inputBubble ? [Crossgen2Option.InputBubble, Crossgen2Option.Optimize] : [Crossgen2Option.Optimize];
161+
157162
new R2RTestRunner(_output).Run(new R2RTestCase(
158-
nameof(BoxIsInstOfValueTypeFolds),
163+
nameof(CastFoldingRespectsVersionBubble),
159164
[
160-
new(nameof(BoxIsInstOfValueTypeFolds), [new CrossgenAssembly(boxIsInstFolding)])
165+
new(nameof(CastFoldingRespectsVersionBubble), [new CrossgenAssembly(castFolding)])
161166
{
162-
Options = [Crossgen2Option.Optimize],
167+
Options = options,
163168
Validate = Validate,
164169
},
165170
]));
166171

167-
static void Validate(ReadyToRunReader reader)
172+
void Validate(ReadyToRunReader reader)
168173
{
169174
// Box and isinst reference their types through NEW_OBJECT/IS_INSTANCE_OF imports
170175
// or TYPE_HANDLE fixups depending on the target, so look for the type in any import.
@@ -183,15 +188,28 @@ static void Validate(ReadyToRunReader reader)
183188

184189
string diagnostic = $"Imported types: [{string.Join(", ", importedTypes)}]";
185190

186-
// An interface cast may succeed in a later version, so it isn't folded.
187-
Assert.True(importedTypes.Contains("ControlStruct"), diagnostic);
188-
Assert.True(importedTypes.Contains("INotImplemented"), diagnostic);
189-
190191
// Value type casts to other non-interface types fold, along with their boxes.
191192
Assert.False(importedTypes.Contains("char"), diagnostic);
192193
Assert.False(importedTypes.Contains("byte"), diagnostic);
193194
Assert.False(importedTypes.Contains("SourceStruct"), diagnostic);
194195
Assert.False(importedTypes.Contains("TargetStruct"), diagnostic);
196+
197+
// Casts to interfaces fold only when every type in the hierarchy is in the version bubble,
198+
// which includes System.Object and System.ValueType only with the framework in the bubble.
199+
Assert.True(importedTypes.Contains("ControlStruct") != inputBubble, diagnostic);
200+
Assert.True(importedTypes.Contains("INotImplemented") != inputBubble, diagnostic);
201+
Assert.True(importedTypes.Contains("INotImplementedByClass") != inputBubble, diagnostic);
202+
203+
// Interfaces have no base type, so typeof(...) assignability checks between them fold whenever
204+
// the target and every inherited interface are in the version bubble, including for shared
205+
// generics. Per assembly, IsAssignableFrom stays only for the IComparable target and
206+
// IsAssignableTo only for the interface that inherits IDisposable.
207+
Assert.True(importedTypes.Any(s => s.Contains("System.Type.IsAssignableFrom(", StringComparison.Ordinal)) != inputBubble, diagnostic);
208+
Assert.True(importedTypes.Any(s => s.Contains("System.Type.IsAssignableTo(", StringComparison.Ordinal)) != inputBubble, diagnostic);
209+
210+
// Variant and COM casts are never folded.
211+
Assert.True(importedTypes.Contains("IVariant`1<SealedClass>"), diagnostic);
212+
Assert.True(importedTypes.Contains("INotImplementedByCom"), diagnostic);
195213
}
196214
}
197215

‎src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCasesRunner/R2RDriver.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ internal static class Crossgen2OptionsExtensions
5656
public static string ToArg(this Crossgen2Option kind) => kind switch
5757
{
5858
Crossgen2Option.Composite => $"--composite",
59-
Crossgen2Option.InputBubble => $"--input-bubble",
59+
Crossgen2Option.InputBubble => $"--inputbubble",
6060
Crossgen2Option.HotColdSplitting => $"--hot-cold-splitting",
6161
Crossgen2Option.Optimize => $"--optimize",
6262
Crossgen2Option.StripILBodies => $"--strip-il-bodies",

‎src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3952,6 +3952,44 @@ void ValidateSafetyOfUsingTypeEquivalenceOfType(TypeDesc type)
39523952
}
39533953
}
39543954

3955+
/// <summary>
3956+
/// Returns true if a cast from an object of exact type <paramref name="fromType"/> to
3957+
/// <paramref name="toType"/> that fails now also fails in every later version of its dependencies.
3958+
/// </summary>
3959+
private bool IsNegativeCastResultVersionResilient(TypeDesc fromType, TypeDesc toType)
3960+
{
3961+
if (fromType.HasTypeEquivalence || toType.HasTypeEquivalence)
3962+
return false;
3963+
3964+
// A value type can gain interfaces (or become an enum), but its other cast targets are fixed.
3965+
if (fromType.IsValueType && !toType.IsInterface && !toType.IsWellKnownType(WellKnownType.Enum))
3966+
return true;
3967+
3968+
// Otherwise every type that decides the cast must version with this code. Array and variant casts
3969+
// also depend on element types and generic arguments, and COM objects can be cast to interfaces
3970+
// through QueryInterface.
3971+
if (fromType is not DefType || toType is not DefType || toType.HasVariance)
3972+
return false;
3973+
3974+
CompilationModuleGroup moduleGroup = _compilation.CompilationModuleGroup;
3975+
if (!moduleGroup.VersionsWithType(toType))
3976+
return false;
3977+
3978+
for (TypeDesc type = fromType; type is not null; type = type.BaseType)
3979+
{
3980+
if (type.IsComImport || !moduleGroup.VersionsWithType(type))
3981+
return false;
3982+
}
3983+
3984+
foreach (DefType iface in fromType.RuntimeInterfaces)
3985+
{
3986+
if (!moduleGroup.VersionsWithType(iface))
3987+
return false;
3988+
}
3989+
3990+
return true;
3991+
}
3992+
39553993
private bool notifyMethodInfoUsage(CORINFO_METHOD_STRUCT_* ftn)
39563994
{
39573995
MethodDesc method = HandleToObject(ftn);

0 commit comments

Comments
 (0)