You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
AsyncTaskMethodBuilder<TResult>.AwaitUnsafeOnCompleted boxes for the value task case #130185
Priority:2Work that is important, but not critical for the releasearea-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI
This started boxing for ValueTaskAwaiter after #128270. In this case the optimization is ok since IStateMachineBoxAwareAwaiter is an internal interface so we control the implementations. The allocations show up in TechEmpower benchmarks.
I could not find a way to write what we want in C# without generic bridging. My best idea is an intrinsic to tell escape analysis explicitly that a manually allocated box does not escape.
Firstly, iirc you will get a warning on NAOT you have to suppress as it doesn't recognise the type checks for the generic parameter
Secondly, any cases that would have been inlined before no longer will be as we do not have any kind of delegate inlining (there have been PRs attempting this before - last attempt was Non-PGO calli/delegate call transformation #109679 I believe)
The effect of this is lessened on coreclr, as DPGO will be able to make it conditionally inlined (behind a guard) I believe, but on NAOT you get the full effect of no cases being able to be inlined in any cases
If we get delegate inlining & ensure the above style of reflection logic can be fully pre-init'd on NAOT (no idea how much of that can be pre-init'd today), then it could be made as good as a direct call without actual generic bridges feature - but otherwise, you have to choose between the potential benefits of inlining with object stack allocation in some cases (i.e., what you have now, since if all calls on the object are able to be inlined, it can stack allocate) vs no inlining & no boxing.
On coreclr, it should end up similar via DPGO (or just tiering if it has run the cctor by then & sees the exact type & is willing to de-virtualize it) I would assume.
Yep, coreclr can optimize this all the way (with the main concern ofc being that we're probably using a lot more of the inlining budget than we usually would be):
Code
usingSystem;usingSystem.Diagnostics.CodeAnalysis;usingSystem.Runtime.CompilerServices;staticclassC{staticvoidMain(){while(true)Iter();}[MethodImpl(MethodImplOptions.NoInlining)]staticvoidIter(){M(newX(),"abc");M(newY(),"def");}staticvoidM<T>(Tinstance,objectargument){if(instanceisIStateMachineBoxAwareAwaiter){if(typeof(T).IsValueType)Helper3<T>.Inst!.AwaitUnsafeOnCompleted(refinstance,argument);else((IStateMachineBoxAwareAwaiter)instance).AwaitUnsafeOnCompleted(argument);}}}interfaceIStateMachineBoxAwareAwaiter{voidAwaitUnsafeOnCompleted(objectbox);}abstractclassHelper1<T>{publicabstractvoidAwaitUnsafeOnCompleted(refTvalue,objectbox);}sealedclassHelper2<T>:Helper1<T>whereT:struct,IStateMachineBoxAwareAwaiter{publicoverridevoidAwaitUnsafeOnCompleted(refTvalue,objectbox)=>value.AwaitUnsafeOnCompleted(box);}staticclassHelper3<T>{publicstaticreadonlyHelper1<T>?Inst;[UnconditionalSuppressMessage("Trimming","IL2091",Justification="We validate the constructed type argument.")]staticHelper3(){Inst=(typeof(T).IsAssignableTo(typeof(IStateMachineBoxAwareAwaiter))&&typeof(T).IsValueType&&Nullable.GetUnderlyingType(typeof(T))isnull)?(Helper1<T>?)Activator.CreateInstance(typeof(Helper2<>).MakeGenericType(typeof(T))):null;}}structX:IStateMachineBoxAwareAwaiter{publicvoidAwaitUnsafeOnCompleted(objectbox)=>Consume(1);staticvoidConsume<T>(Tvalue){}}structY:IStateMachineBoxAwareAwaiter{publicvoidAwaitUnsafeOnCompleted(objectbox)=>Consume(box);staticvoidConsume<T>(Tvalue){}}
gives:
I've been using this trick for a while, the delegate one is just the shorter version of the same thing basically (and is not as optimal).
It is a shame NAOT's pre-init is very limited, as otherwise we could have (imperfect & high effort, but quite good) relatively-low-overhead (when only involving structs) generic bridges today (that relies on inlining & a bunch of stuff ofc).
I am inclined to introduce an intrinsic to solve it, but I recognize that this may not be a workable solution for user code. I think we were hoping with #128270 that escape analysis would be sufficient, but at least in the BCL that does not seem to always be the case. Do we need to think about some mechanism that users can switch to for .NET 11 to write the above without boxing? Is the solution presented by @hamarb123 reasonable to expect from users?
A couple of potential intrinsics that we could do this with in the BCL:
This intrinsic will swap the receiver of the next call, provided it is called on an unboxed entry point.
These allow the caller to control the behavior. There are also solutions where we allow the callee to control it, e.g. we could use an attribute like [ReceiverDoesNotEscape] on implementations of IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted; or an aggressively-inlined wrapper that copies the receiver, so that escape analysis can naturally prove that the box does not escape.
Also cc @EgorBo in case he has thoughts on this. We did try to originally spec us into a way of allowing the optimization, but we gave up on that since it was unclear what the right spec sounds like that does not make existing patterns in the BCL illegal.
Do we know of other cases where user code was relying on the old optimization?
At least in my library I rely on it by copying the BCL pattern. I doubt I'm the only one.
Yeah, as I mentioned, I am relying on this in a number of places too.
Or opportunities to leverage some kind of more general solution (eg allow some user-supplied form of IPA)?
Presumably most real solutions to this, e.g., generic bridges, would not have time to be done for .NET 11? Hence why I made my PR, which includes a solution that I think is workable & should be able to get ready for the soon-upcoming freeze; even if it is not a particularly ideal workaround, it does provide a solution for us users if & when we run into this scenario.
There's 2 that maybe don't count (the ones that are doing if (x is IFormattable y) y.ToString(...) kind of setup (idr if it pattern matched this case too) - all of the rest definitely do count will be regressing for any T that can't inline its implementation method enough to see that the box semantics are unnecessary (e.g., Guid as I already showed, or user-defined types with decent amount of code that runs in the formatting process). Plus any similar patterns / setups in user-code are also not addressable without some kind of solution here.
Can we put some more work into #122821 so that (1) the important optimizations in safe code are allowed and (2) the unsafe code patterns that are incompatible with these optimizations are described accurately?
Is the solution presented by @hamarb123 reasonable to expect from users?
This solution obfuscates the intent that always ends up hurting us at the end.
Can we put some more work into #122821 so that (1) the important optimizations in safe code are allowed and (2) the unsafe code patterns that are incompatible with these optimizations are described accurately?
I personally don't like this idea & think it will inevitably lead to even more issues. If you do this, you may as well completely ban pointers to ref structs imo (slight hyperbole ofc), as it would be next to impossible to use them consistently since a caller may happen to not have any obvious ref / ref struct in their signature - I do not think this kind of non-local correctness is good. Another option could be to opt-in to saying "I will not allow the this ref to escape", but it would likely have to be an unsafe attribute like SkipLocalsInit (since you're making code that would otherwise be correct become memory unsafe) which would make it basically unusable / a non-starter. Or it could be opt-out of assuming "the ref to this won't escape", but that then would cause problems if you define a struct with generic fields especially (but also just normal fields could run into the problem too), since one of the fields may not guarantee this & you might call a method on them (e.g., imagine you write something like ValueTuple<T1, T2>, and one of the field's ToString methods does this, you would have to defensively mark your ToString as well else risk causing UB). I honestly don't think there's any real solution here that won't cause more problems than it solves.
This solution obfuscates the intent that always ends up hurting us at the end.
Another solution could be runtime-constraint-checks for UnsafeAccessor (#119876), which was marked for 11 originally, but has been delayed for 12. That would be less obfuscated than my one (and also fully resistant to getting unlucky with branches on jit platform & having the cctor not called before tier1 code) but is also not happening in 11, which we are asking for a (end-user-usable) solution to be available for.
I think my solution, while certainly being backed by some ugly code, is the most practical to get done for .NET 11 at this point - I'd love to see something like generic bridges / runtime-constraint-checks / proper IPA come in .NET 12 that makes it no longer necessary, but I am not convinced anything like these will happen in time for 11 (runtime-constraint-checks is probably the most do-able if I had to guess, and if we got that I'd be happy as it'd allow a less verbose / obfuscated & better solution, but I'm assuming it's not going to happen based on the most recent comments).
If you do this, you may as well completely ban pointers to ref structs imo
I am not opposed to declaring unsafe code that is getting in the way here to be invalid. I want to optimize for straightforward safe C# to work great and express as much as possible. Things like user supplied IPAs would add more reason for writing unsafe C#. It would go against our larger effort with reducing amount of unsafe code.
I am not opposed to declaring unsafe code that is getting in the way here to be invalid. I want to optimize for straightforward safe C# to work great and express as much as possible. Things like user supplied IPAs would add more reason for writing unsafe C#. It would go against our larger effort with reducing amount of unsafe code.
There are a number of solutions here that would be relatively straightforward for C# code, that don't require changing the rules of what is valid:
Generic bridges, which would allow me to write the code that actually expresses my intent to start with, rather than obfuscating what I wanted to write with a boxing cast that I am expecting the runtime to remove
Inter-procedural analysis, which would also presumably open up lots of other object stack allocation opportunities beyond just this
And probably others, plus the solutions that have less straight-forward C# code but still solve the problem (like runtime-type-constraint checks for example).
I do not think it is necessary to change what unsafe code is valid to achieve good performance with reasonable C# code here, it's just a matter of what can be done for .NET 11 so users who have performance/allocation critical code can ensure they are not regressed, even if it's just a stopgap solution until we get something like generic bridges in .NET 12.
Plus, I do not think the goal of reducing unsafe code means we have to change what is valid or invalid - it means creating safe constructs that are as efficient where possible. If you change what is valid / invalid all the time, it actually means that unsafe code needs to be re-learnt & re-validated much more frequently to be used correctly, which seems to me like it'd increase the chance of having code that gets left behind (i.e., is doing something that was safe, but is now suddenly unsafe), which overall reduces safety of the ecosystem.
Personally, if the answer ended up being "it's going to be a bit worse in .NET 11 in some cases, but in .NET 12 we will have at least runtime-constraint-checks, and aim to have generic bridges too", I think I'd be okay with that since 11 is only STS & 12 is the LTS, but I would want to know that there will definitely be a solution in .NET 12. I am, however, concerned that there's always the chance things get delayed again and we might not get any real solution until like .NET 13/14/later, unless there's an actual commitment to ensuring we get one of these (especially since generic bridges do not appear to be coming imminently, and runtime type checks got delayed from 11 to 12 despite the UnsafeAccessor feature itself existing since 8 & with generics support since 9).
I think an *allocation* regression to this extremely well-established pattern, for 11.0, that only closes an edge case unsoundness issue is prio 1. It seems this should be handled at the level of reverting for 11.0, alternatively adding the temporary widening #122821, or to work on offering an actual solution. Not a 'maybe we'll get to it' prioritization.
@NinoFloris Don't pay too much attention to the description on the label applied here, it is just some internal triaging we (the JIT team) are doing for each of our issues.
I would like to see a note in the System.Diagnostics.CodeAnalysis.UnscopedRefAttribute API documentation as well:
The runtime uses the attribute, so it cannot be stripped and dynamic IL must use it when appropriate.
The attribute now still has some meaning even if there are no apparent ways for the ref to escape (ref return, return of ref struct type, ref/out parameter of ref struct type): it allows unsafe code to cause the ref to escape (such as by writing into a ref struct via an unmanaged pointer).
I would like to see a note in the System.Diagnostics.CodeAnalysis.UnscopedRefAttribute API documentation as well:
* The runtime uses the attribute, so it cannot be stripped and dynamic IL must use it when appropriate.
* The attribute now still has some meaning even if there are no apparent ways for the ref to escape (ref return, return of ref struct type, ref/out parameter of ref struct type): it allows unsafe code to cause the ref to escape (such as by writing into a ref struct via an unmanaged pointer).
Priority:2Work that is important, but not critical for the releasearea-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI
Activity
dotnet-policy-service commentedon Jul 3, 2026
Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
See info in area-owners.md if you want to be subscribed.
hamarb123 commentedon Jul 3, 2026
As mentioned on Discord, you can get a non-boxing version like so:
However this has a number of considerations:
If we get delegate inlining & ensure the above style of reflection logic can be fully pre-init'd on NAOT (no idea how much of that can be pre-init'd today), then it could be made as good as a direct call without actual generic bridges feature - but otherwise, you have to choose between the potential benefits of inlining with object stack allocation in some cases (i.e., what you have now, since if all calls on the object are able to be inlined, it can stack allocate) vs no inlining & no boxing.
hamarb123 commentedon Jul 4, 2026
The other option (as mentioned by @Windows10CE on discord) is to use #119876, but that seems to have been delayed to .NET 12
hez2010 commentedon Jul 4, 2026
This is not true as of today. DPGO doesn't handle delegates over value types, or delegates of static methods.
hamarb123 commentedon Jul 4, 2026
This minor adjustment of the same principle which uses abstract class instead of delegate seems to work fairly well on NAOT also: https://godbolt.org/z/roz5jxdTq.
On coreclr, it should end up similar via DPGO (or just tiering if it has run the cctor by then & sees the exact type & is willing to de-virtualize it) I would assume.
hamarb123 commentedon Jul 4, 2026
Yep, coreclr can optimize this all the way (with the main concern ofc being that we're probably using a lot more of the inlining budget than we usually would be):
Code
gives:
I've been using this trick for a while, the delegate one is just the shorter version of the same thing basically (and is not as optimal).
It is a shame NAOT's pre-init is very limited, as otherwise we could have (imperfect & high effort, but quite good) relatively-low-overhead (when only involving
structs) generic bridges today (that relies on inlining & a bunch of stuff ofc).jakobbotsch commentedon Jul 7, 2026
@AndyAyersMS @jkotas @davidwrighton What are your opinions here?
I am inclined to introduce an intrinsic to solve it, but I recognize that this may not be a workable solution for user code. I think we were hoping with #128270 that escape analysis would be sufficient, but at least in the BCL that does not seem to always be the case. Do we need to think about some mechanism that users can switch to for .NET 11 to write the above without boxing? Is the solution presented by @hamarb123 reasonable to expect from users?
A couple of potential intrinsics that we could do this with in the BCL:
JIT/interpreter can use the presence of this intrinsic to recognize that it is ok to turn the box+unbox into a local copy.
This intrinsic will swap the receiver of the next call, provided it is called on an unboxed entry point.
These allow the caller to control the behavior. There are also solutions where we allow the callee to control it, e.g. we could use an attribute like
[ReceiverDoesNotEscape]on implementations ofIStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted; or an aggressively-inlined wrapper that copies the receiver, so that escape analysis can naturally prove that the box does not escape.Thoughts?
jakobbotsch commentedon Jul 7, 2026
Also cc @EgorBo in case he has thoughts on this. We did try to originally spec us into a way of allowing the optimization, but we gave up on that since it was unclear what the right spec sounds like that does not make existing patterns in the BCL illegal.
4 remaining items
timcassell commentedon Jul 7, 2026
At least in my library I rely on it by copying the BCL pattern. I doubt I'm the only one.
https://github.com/timcassell/ProtoPromise/blob/9ce9c6d579b69f3a0a0c8531d8cd8b56e36af439/Package/Core/Promises/Internal/AsyncInternal.cs#L151
hamarb123 commentedon Jul 8, 2026
Yeah, as I mentioned, I am relying on this in a number of places too.
Presumably most real solutions to this, e.g., generic bridges, would not have time to be done for .NET 11? Hence why I made my PR, which includes a solution that I think is workable & should be able to get ready for the soon-upcoming freeze; even if it is not a particularly ideal workaround, it does provide a solution for us users if & when we run into this scenario.
hamarb123 commentedon Jul 8, 2026
There's 2 that maybe don't count (the ones that are doing
if (x is IFormattable y) y.ToString(...)kind of setup (idr if it pattern matched this case too) - all of the rest definitely do count will be regressing for any T that can't inline its implementation method enough to see that the box semantics are unnecessary (e.g.,Guidas I already showed, or user-defined types with decent amount of code that runs in the formatting process). Plus any similar patterns / setups in user-code are also not addressable without some kind of solution here.jkotas commentedon Jul 8, 2026
Can we put some more work into #122821 so that (1) the important optimizations in safe code are allowed and (2) the unsafe code patterns that are incompatible with these optimizations are described accurately?
This solution obfuscates the intent that always ends up hurting us at the end.
hamarb123 commentedon Jul 8, 2026
I personally don't like this idea & think it will inevitably lead to even more issues. If you do this, you may as well completely ban pointers to ref structs imo (slight hyperbole ofc), as it would be next to impossible to use them consistently since a caller may happen to not have any obvious ref / ref struct in their signature - I do not think this kind of non-local correctness is good. Another option could be to opt-in to saying "I will not allow the this ref to escape", but it would likely have to be an unsafe attribute like SkipLocalsInit (since you're making code that would otherwise be correct become memory unsafe) which would make it basically unusable / a non-starter. Or it could be opt-out of assuming "the ref to this won't escape", but that then would cause problems if you define a struct with generic fields especially (but also just normal fields could run into the problem too), since one of the fields may not guarantee this & you might call a method on them (e.g., imagine you write something like ValueTuple<T1, T2>, and one of the field's ToString methods does this, you would have to defensively mark your ToString as well else risk causing UB). I honestly don't think there's any real solution here that won't cause more problems than it solves.
Another solution could be runtime-constraint-checks for UnsafeAccessor (#119876), which was marked for 11 originally, but has been delayed for 12. That would be less obfuscated than my one (and also fully resistant to getting unlucky with branches on jit platform & having the cctor not called before tier1 code) but is also not happening in 11, which we are asking for a (end-user-usable) solution to be available for.
I think my solution, while certainly being backed by some ugly code, is the most practical to get done for .NET 11 at this point - I'd love to see something like generic bridges / runtime-constraint-checks / proper IPA come in .NET 12 that makes it no longer necessary, but I am not convinced anything like these will happen in time for 11 (runtime-constraint-checks is probably the most do-able if I had to guess, and if we got that I'd be happy as it'd allow a less verbose / obfuscated & better solution, but I'm assuming it's not going to happen based on the most recent comments).
jkotas commentedon Jul 8, 2026
I am not opposed to declaring unsafe code that is getting in the way here to be invalid. I want to optimize for straightforward safe C# to work great and express as much as possible. Things like user supplied IPAs would add more reason for writing unsafe C#. It would go against our larger effort with reducing amount of unsafe code.
hamarb123 commentedon Jul 8, 2026
There are a number of solutions here that would be relatively straightforward for C# code, that don't require changing the rules of what is valid:
And probably others, plus the solutions that have less straight-forward C# code but still solve the problem (like runtime-type-constraint checks for example).
I do not think it is necessary to change what unsafe code is valid to achieve good performance with reasonable C# code here, it's just a matter of what can be done for .NET 11 so users who have performance/allocation critical code can ensure they are not regressed, even if it's just a stopgap solution until we get something like generic bridges in .NET 12.
Plus, I do not think the goal of reducing unsafe code means we have to change what is valid or invalid - it means creating safe constructs that are as efficient where possible. If you change what is valid / invalid all the time, it actually means that unsafe code needs to be re-learnt & re-validated much more frequently to be used correctly, which seems to me like it'd increase the chance of having code that gets left behind (i.e., is doing something that was safe, but is now suddenly unsafe), which overall reduces safety of the ecosystem.
hamarb123 commentedon Jul 8, 2026
Personally, if the answer ended up being "it's going to be a bit worse in .NET 11 in some cases, but in .NET 12 we will have at least runtime-constraint-checks, and aim to have generic bridges too", I think I'd be okay with that since 11 is only STS & 12 is the LTS, but I would want to know that there will definitely be a solution in .NET 12. I am, however, concerned that there's always the chance things get delayed again and we might not get any real solution until like .NET 13/14/later, unless there's an actual commitment to ensuring we get one of these (especially since generic bridges do not appear to be coming imminently, and runtime type checks got delayed from 11 to 12 despite the UnsafeAccessor feature itself existing since 8 & with generics support since 9).
NinoFloris commentedon Jul 9, 2026
I think an *allocation* regression to this extremely well-established pattern, for 11.0, that only closes an edge case unsoundness issue is prio 1. It seems this should be handled at the level of reverting for 11.0, alternatively adding the temporary widening #122821, or to work on offering an actual solution. Not a 'maybe we'll get to it' prioritization.
jakobbotsch commentedon Jul 9, 2026
@NinoFloris Don't pay too much attention to the description on the label applied here, it is just some internal triaging we (the JIT team) are doing for each of our issues.
jilles-sg commentedon Jul 17, 2026
I would like to see a note in the
System.Diagnostics.CodeAnalysis.UnscopedRefAttributeAPI documentation as well:jakobbotsch commentedon Jul 24, 2026
I opened an agent session to expand the API docs: dotnet/dotnet-api-docs#12902