Skip to content

Commit 4ff0041

Browse files
AaronRobinsonMSFTjkotas
authored andcommitted
Update docs for ByRefLike with generics for work in .NET 10 (#103318)
Co-authored-by: Jan Kotas <[email protected]>
1 parent 4541933 commit 4ff0041

File tree

6 files changed

+447
-113
lines changed

6 files changed

+447
-113
lines changed

docs/design/features/byreflike-generics.md

Lines changed: 121 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -7,22 +7,26 @@ Using ByRefLike types in Generic parameters is possible by building upon support
77

88
## Runtime impact
99

10-
Supporting ByRefLike type as Generic parameters will impact the following IL instructions:
10+
Supporting ByRefLike types as Generic parameters will impact the following IL instructions.
1111

12-
- `box` &ndash; Types with ByRefLike parameters used in fields cannot be boxed.
12+
The `constrained. callvirt` sequence is valid if a ByRefLike type is provided. A `NotSupportedException` will be thrown at the call-site, if the target resolves to a method implemented on `object` or a default interface method.
13+
14+
Throws `InvalidProgramException` when passed a ByRefLike type:
15+
- `box` &ndash; ByRefLike types cannot be allocated on the heap.
16+
17+
Throws `TypeLoadException` when passed a ByRefLike type:
1318
- `stsfld` / `ldsfld` &ndash; Type fields of a ByRefLike parameter cannot be marked `static`.
1419
- `newarr` / `stelem` / `ldelem` / `ldelema` &ndash; Arrays are not able to contain ByRefLike types.
1520
- `newobj` &ndash; For multi-dimensional array construction.
16-
- `constrained.callvirt` &ndash; If this IL sequence resolves to a method implemented on `object` or default interface method, an error will occur during the attempt to box the instance.
17-
18-
If any of the above instructions are attempted to be used with a ByRefLike type, the runtime will throw an `InvalidProgramException`. Sequences involving some of the above instructions are considered optimizations and represent cases that will remain valid regardless of a `T` being ByRefLike. See "Special IL Sequences" section below for details.
1921

2022
The following instructions are already set up to support this feature since their behavior will fail as currently defined due to the inability to box a ByRefLike type.
2123

22-
- `throw` &ndash; Requires an object reference to be on stack, which can never be a ByRefLike type.
23-
- `unbox` / `unbox.any` &ndash; Requires an object reference to be on stack, which can never be a ByRefLike type.
24-
- `isinst` &ndash; Will always place `null` on stack.
25-
- `castclass` &ndash; Will always throw `InvalidCastException`.
24+
- `throw`
25+
- `unbox` / `unbox.any`
26+
- `isinst`
27+
- `castclass`
28+
29+
**NOTE** There are sequences involving some of the above instructions that may remain valid regardless of a `T` being ByRefLike&mdash;see ["Options for invalid IL" section](#invalid_il_options) below for details.
2630

2731
The expansion of ByRefLike types as Generic parameters does not relax restrictions on where ByRefLike types can be used. When `T` is ByRefLike, the use of `T` as a field will require the enclosing type to be ByRefLike.
2832

@@ -110,23 +114,123 @@ throw
110114

111115
Adding `gpAcceptByRefLike` to the metadata of a Generic parameter will be considered a non-breaking binary change.
112116

113-
Enumerating of constructors/methods on `Span<T>` and `ReadOnlySpan<T>` may throw `TypeLoadException` if `T` is a ByRefLike type. See "Troublesome APIs" above for the list of APIs that cause this condition.
117+
Enumerating of constructors/methods on `Span<T>` and `ReadOnlySpan<T>` may throw `TypeLoadException` if `T` is a ByRefLike type. See "Troublesome API mitigation" above for the list of APIs that cause this condition.
118+
119+
## <a name="invalid_il_options"></a> Options for invalid IL
120+
121+
There are two potential options below for how to address this issue. Based on communication with the Roslyn team, option (1) is the current plan of record for .NET 10.
122+
123+
The first indented IL sequences below represents the `is-type` sequence. Combining the first with the second indented section represents the "type pattern matching" scenario in C#. The below sequence performs a type check and then, if successful, consumes the unboxed instance.
124+
125+
```IL
126+
// Type check
127+
ldarg.0
128+
box <Source>
129+
isinst <Target>
130+
brfalse.s NOT_INST
131+
132+
// Unbox and store unboxed instance
133+
ldarg.0
134+
box <Source>
135+
isinst <Target>
136+
unbox.any <Target>
137+
stloc.X
138+
139+
NOT_INST:
140+
ret
141+
```
142+
143+
With the above IL composition implemented, the following C# describes the following "type pattern matching" scenarios and what one might expect given current C# semantics.
144+
145+
```csharp
146+
struct S {}
147+
struct S<T> {}
148+
ref struct RS {}
149+
ref struct RS<T> {}
150+
interface I {}
151+
class C {}
152+
class C<T> {}
153+
154+
// Not currently valid C#
155+
void M<T, U>(T t) where T: allows ref struct
156+
{
157+
// Valid
158+
if (t is int i)
159+
160+
if (t is S s)
161+
if (t is S<char> sc)
162+
if (t is S<U> su)
163+
164+
if (t is RS rs)
165+
if (t is RS<char> rsc)
166+
if (t is RS<U> rsu)
167+
168+
if (t is string str)
169+
if (t is C c)
170+
if (t is C<I> ci)
171+
if (t is C<U> cu)
172+
173+
// Can be made to work in IL.
174+
if (t is I itf) // A new local "I" would not be used for ByRefLike scenarios.
175+
// The local would be the ByRefLike type, not "I".
176+
177+
// Invalid
178+
if (t is object o) // ByRefLike types evaluate "true" for object.
179+
if (t is U u)
180+
}
181+
```
182+
183+
### Option 1) Compiler helpers
184+
185+
The following two helper functions could be introduced and would replace currently invalid `is-type` IL sequences when ByRefLike types are involved. Their behavior would broadly be defined to operate as if the ByRefLike aspect of either the `TFrom` and `TTo` is not present. An alternative approach would be consult with the Roslyn team and define the semantics of these functions to adhere to C# language rules.
186+
187+
```csharp
188+
namespace System.Runtime.CompilerServices
189+
{
190+
public static class RuntimeHelpers
191+
{
192+
// Replacement for the [box; isinst; brfalse/true] sequence.
193+
public static bool IsInstanceOf<TFrom, TTo>(TFrom source)
194+
where TFrom: allows ref struct
195+
where TTo: allows ref struct;
196+
197+
// Replacement for the [box; isinst; unbox.any] sequence.
198+
// Would throw InvalidCastException for invalid use at run-time.
199+
// For example:
200+
// TFrom: RS, TTo: object => always throws
201+
// TFrom: RS, TTo: <interface> => always throws
202+
public static TTo CastTo<TFrom, TTo>(TFrom source)
203+
where TFrom: allows ref struct
204+
where TTo: allows ref struct;
205+
}
206+
}
207+
```
208+
209+
Example usage of the above methods.
210+
211+
```csharp
212+
TTo result;
213+
if (RuntimeHelpers.IsInstanceOf<TFrom, TTo>(source))
214+
{
215+
result = RuntimeHelpers.CastTo<TFrom, TTo>(source);
216+
}
217+
```
114218

115-
## Special IL Sequences
219+
### Option 2) Special IL sequences
116220

117-
The following are IL sequences involving the `box` instruction. They are used for common C# language constructs and shall continue to be valid, even with ByRefLike types, in cases where the result can be computed at JIT time and elided safely. These sequences must now be elided when the target type is ByRefLike. The conditions where each sequence is elided are described below and each condition will be added to the ECMA-335 addendum.
221+
The following are IL sequences involving the `box` instruction. They are used for common C# language constructs and would continue to be valid, even with ByRefLike types. These sequences would be **required** to be valid when the target type is ByRefLike. Each sequence would be added to the ECMA-335 addendum.
118222

119-
`box` ; `unbox.any` &ndash; The box target type is equal to the unboxed target type.
223+
`box` ; `isinst` ; `br_true/false` &ndash; Passing a ByRefLike type as the argument to the `box` instruction is permitted to accomplish a type check, in C# `x is Y`. **Note** ByRefLike types would evaluate to `true` when compared against `System.Object`.
120224

121-
`box` ; `br_true/false` &ndash; The box target type is non-`Nullable<T>`.
225+
`box` ; `isinst` ; `unbox.any` &ndash; In order to permit "type pattern matching", in C# `x is Y y`, this sequence will permit use of a ByRefLike type on any instruction, but does not permit the use of generic parameters being exposed to `isinst` or `unbox.any`.
122226

123-
`box` ; `isinst` ; `unbox.any` &ndash; The box, `isint`, and unbox target types are all equal.
227+
`box` ; `unbox.any` &ndash; Valid to use ByRefLike types.
124228

125-
`box` ; `isinst` ; `br_true/false` &ndash; The box target type is equal to the unboxed target type or the box target type is `Nullable<T>` and target type equalities can be computed.
229+
`box` ; `br_true/false` &ndash; Valid to use ByRefLike types.
126230

127231
## Examples
128232

129-
Below are valid and invalid examples of ByRefLike as Generic parameters. All examples use the **not official** syntax, `allows ref struct`, for indicating the Generic permits ByRefLike types.
233+
Below are currently (.NET 9) valid and invalid examples of ByRefLike as Generic parameters.
130234

131235
**1) Valid**
132236
```csharp

docs/design/specs/Ecma-335-Augments.md

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ This is a list of additions and edits to be made in ECMA-335 specifications. It
1414
- [Covariant Return Types](#covariant-return-types)
1515
- [Function Pointer Type Identity](#function-pointer-type-identity)
1616
- [Unsigned data conversion with overflow detection](#unsigned-data-conversion-with-overflow-detection)
17-
- [Ref field support](#ref-fields)
17+
- [Ref fields support](#ref-fields)
18+
- [ByRefLike types in generics](#byreflike-generics)
1819
- [Rules for IL rewriters](#rules-for-il-rewriters)
1920
- [Checked user-defined operators](#checked-user-defined-operators)
2021
- [Atomic reads and writes](#atomic-reads-and-writes)
@@ -1026,6 +1027,31 @@ Changes to signatures:
10261027
- Add a bullet point
10271028
- Managed pointers which point at null, the address just past the end of an object, or the address where an element just past the end of an array would be stored, are permitted but not dereferenceable.
10281029

1030+
## <a name="byreflike-generics"></a> ByRefLike types in generics
1031+
1032+
ByRefLike types, defined in C# with the `ref struct` syntax, represent types that cannot escape to the managed heap and must remain on the stack. It is possible for these types to be used as generic parameters, but in order to improve utility certain affordances are required.
1033+
1034+
### II.10.1.7
1035+
An additional IL keyword, `byreflike`, is introduced to indicate use of ByRefLike types is permitted. This expands the set of permissible types used by this parameters, but limits the potential instructions that can be used on instances of this generic parameter type.
1036+
1037+
### II.23.1.7
1038+
Update the `SpecialConstraintMask` flag value and description, and add a new flag, `AllowByRefLike`.
1039+
1040+
| Flag | Value | Description |
1041+
| --- | ----- | ----------- |
1042+
| `SpecialConstraintMask` | `0x3C` | These 4 bits contain one of the following values: |
1043+
| ... | ... | ... |
1044+
| `AllowByRefLike` | `0x20` | The generic parameter is allowed to be ByRefLike |
1045+
1046+
### III.2.1
1047+
The following case is added as the **third** cases in the "if _thisType_" sequence.
1048+
1049+
> If _thisType_ is ByRefLike and _thisType_ does not implement _method_ then; a `NotSupportedException` is thrown at the callsite.
1050+
1051+
The following is added to the paragraph starting with "This last case can only occur when _method_ was defined on `System.Object`, `System.ValueType`, or `System.Enum`".
1052+
1053+
> The third case can only occur when _method_ was defined on `System.Object` or is a Default Interface Method.
1054+
10291055
## Rules for IL Rewriters
10301056

10311057
There are apis such as `System.Runtime.CompilerServices.RuntimeHelpers.CreateSpan<T>(...)` which require that the PE file have a particular structure. In particular, that api requires that the associated RVA of a FieldDef which is used to create a span must be naturally aligned over the data type that `CreateSpan` is instantiated over. There are 2 major concerns.

src/coreclr/inc/corinfo.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2402,7 +2402,7 @@ class ICorStaticInfo
24022402
virtual size_t getClassThreadStaticDynamicInfo (
24032403
CORINFO_CLASS_HANDLE cls
24042404
) = 0;
2405-
2405+
24062406
virtual bool getStaticBaseAddress(
24072407
CORINFO_CLASS_HANDLE cls,
24082408
bool isGc,

src/coreclr/nativeaot/Runtime.Base/src/System/Runtime/TypeCast.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -414,10 +414,10 @@ public static unsafe object CheckCastClass(MethodTable* pTargetType, object obj)
414414
[RuntimeExport("RhTypeCast_CheckCastClassSpecial")]
415415
private static unsafe object CheckCastClassSpecial(MethodTable* pTargetType, object obj)
416416
{
417-
Debug.Assert(!pTargetType->IsParameterizedType, "CheckCastClass called with parameterized MethodTable");
418-
Debug.Assert(!pTargetType->IsFunctionPointer, "CheckCastClass called with function pointer MethodTable");
419-
Debug.Assert(!pTargetType->IsInterface, "CheckCastClass called with interface MethodTable");
420-
Debug.Assert(!pTargetType->HasGenericVariance, "CheckCastClass with variant MethodTable");
417+
Debug.Assert(!pTargetType->IsParameterizedType, "CheckCastClassSpecial called with parameterized MethodTable");
418+
Debug.Assert(!pTargetType->IsFunctionPointer, "CheckCastClassSpecial called with function pointer MethodTable");
419+
Debug.Assert(!pTargetType->IsInterface, "CheckCastClassSpecial called with interface MethodTable");
420+
Debug.Assert(!pTargetType->HasGenericVariance, "CheckCastClassSpecial with variant MethodTable");
421421

422422
MethodTable* mt = obj.GetMethodTable();
423423
Debug.Assert(mt != pTargetType, "The check for the trivial cases should be inlined by the JIT");

0 commit comments

Comments
 (0)