Skip to content

AsyncTaskMethodBuilder<TResult>.AwaitUnsafeOnCompleted boxes for the value task case #130185

Closed

Description

@jakobbotsch

Specifically the following line:

((IStateMachineBoxAwareAwaiter)awaiter).AwaitUnsafeOnCompleted(box);

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.

cc @AndyAyersMS @BrennanConroy

Activity

  1. added
    untriaged
    on Jul 3, 2026
  2. added
    area-CodeGen-coreclr
    and removed
    untriaged
    on Jul 3, 2026
  3. added this to the 11.0.0 milestone on Jul 3, 2026
  4. dotnet-policy-service commented on Jul 3, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
    See info in area-owners.md if you want to be subscribed.

  5. hamarb123 commented on Jul 3, 2026

    @hamarb123
    Contributor

    As mentioned on Discord, you can get a non-boxing version like so:

    static class Helper1<T> where T : struct, IStateMachineBoxAwareAwaiter
    {
        public static void AwaitUnsafeOnCompleted(ref T value, IAsyncStateMachineBox box) => value.AwaitUnsafeOnCompleted(box);
    }
    
    static class Helper2<T>
    {
        public delegate void AwaitUnsafeOnCompletedDel(ref T value, IAsyncStateMachineBox box);
        public static readonly AwaitUnsafeOnCompletedDel? Inst = (typeof(T).IsAssignableTo(typeof(IStateMachineBoxAwareAwaiter)) && typeof(T).IsValueType) ? typeof(Helper1<>).MakeGenericType(typeof(T)).GetMethod("AwaitUnsafeOnCompleted").CreateDelegate<AwaitUnsafeOnCompletedDel>() : null;
    }
    
    if (instance is IAsyncStateMachineBox)
    {
        if (typeof(T).IsValueType) Helper2<T>.Inst!(ref instance, argument);
        else ((IStateMachineBoxAwareAwaiter)instance).AwaitUnsafeOnCompleted(argument);
    }

    However this has a number of considerations:

    • 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.

  6. hamarb123 commented on Jul 4, 2026

    @hamarb123
    Contributor

    The other option (as mentioned by @Windows10CE on discord) is to use #119876, but that seems to have been delayed to .NET 12

  7. hez2010 commented on Jul 4, 2026

    @hez2010
    Contributor
    • DPGO will be able to make it conditionally inlined (behind a guard) I believe

    This is not true as of today. DPGO doesn't handle delegates over value types, or delegates of static methods.

  8. hamarb123 commented on Jul 4, 2026

    @hamarb123
    Contributor

    This is not true as of today. DPGO doesn't handle delegates over value types, or delegates of static methods.

    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.

  9. hamarb123 commented on Jul 4, 2026

    @hamarb123
    Contributor

    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
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Runtime.CompilerServices;
    
    static class C
    {
        static void Main()
        {
            while (true) Iter();
        }
    
        [MethodImpl(MethodImplOptions.NoInlining)]
        static void Iter()
        {
            M(new X(), "abc");
            M(new Y(), "def");
        }
    
        static void M<T>(T instance, object argument)
        {
            if (instance is IStateMachineBoxAwareAwaiter)
            {
                if (typeof(T).IsValueType) Helper3<T>.Inst!.AwaitUnsafeOnCompleted(ref instance, argument);
                else ((IStateMachineBoxAwareAwaiter)instance).AwaitUnsafeOnCompleted(argument);
            }
        }
    }
    
    interface IStateMachineBoxAwareAwaiter
    {
        void AwaitUnsafeOnCompleted(object box);
    }
    
    abstract class Helper1<T>
    {
        public abstract void AwaitUnsafeOnCompleted(ref T value, object box);
    }
    
    sealed class Helper2<T> : Helper1<T> where T : struct, IStateMachineBoxAwareAwaiter
    {
        public override void AwaitUnsafeOnCompleted(ref T value, object box) => value.AwaitUnsafeOnCompleted(box);
    }
    
    static class Helper3<T>
    {
        public static readonly Helper1<T>? Inst;
    
        [UnconditionalSuppressMessage("Trimming", "IL2091", Justification = "We validate the constructed type argument.")]
        static Helper3()
        {
            Inst = (typeof(T).IsAssignableTo(typeof(IStateMachineBoxAwareAwaiter)) && typeof(T).IsValueType && Nullable.GetUnderlyingType(typeof(T)) is null) ? (Helper1<T>?)Activator.CreateInstance(typeof(Helper2<>).MakeGenericType(typeof(T))) : null;
        }
    }
    
    struct X : IStateMachineBoxAwareAwaiter
    {
        public void AwaitUnsafeOnCompleted(object box) => Consume(1);
    
        static void Consume<T>(T value)
        {
        }
    }
    
    struct Y : IStateMachineBoxAwareAwaiter
    {
        public void AwaitUnsafeOnCompleted(object box) => Consume(box);
    
        static void Consume<T>(T value)
        {
        }
    }

    gives:

    Image

    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).

  10. jakobbotsch commented on Jul 7, 2026

    @jakobbotsch
    MemberAuthor

    @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:

    RuntimeHelpers.NonEscaping((IStateMachineBoxAwareAwaiter)awaiter).AwaitUnsafeOnCompleted(box);

    JIT/interpreter can use the presence of this intrinsic to recognize that it is ok to turn the box+unbox into a local copy.

    TAwaiter awaiterCopy = awaiter;
    RuntimeHelpers.SwapNextUnboxedReceiver(ref awaiterCopy);
    ((IStateMachineBoxAwareAwaiter)awaiter).AwaitUnsafeOnCompleted(box);

    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.

    Thoughts?

  11. jakobbotsch commented on Jul 7, 2026

    @jakobbotsch
    MemberAuthor

    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.

  12. 4 remaining items

  13. timcassell commented on Jul 7, 2026

    @timcassell

    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.

    https://github.com/timcassell/ProtoPromise/blob/9ce9c6d579b69f3a0a0c8531d8cd8b56e36af439/Package/Core/Promises/Internal/AsyncInternal.cs#L151

  14. hamarb123 commented on Jul 8, 2026

    @hamarb123
    Contributor

    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.

  15. hamarb123 commented on Jul 8, 2026

    @hamarb123
    Contributor

    Are all these cases that regressed from #128270?

    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.

  16. jkotas commented on Jul 8, 2026

    @jkotas
    Member

    What are your opinions 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.

  17. hamarb123 commented on Jul 8, 2026

    @hamarb123
    Contributor

    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).

  18. jkotas commented on Jul 8, 2026

    @jkotas
    Member

    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.

  19. hamarb123 commented on Jul 8, 2026

    @hamarb123
    Contributor

    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.

  20. hamarb123 commented on Jul 8, 2026

    @hamarb123
    Contributor

    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).

  21. added
    Priority:2
    on Jul 9, 2026
  22. NinoFloris commented on Jul 9, 2026

    @NinoFloris
    Contributor

    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.

  23. jakobbotsch commented on Jul 9, 2026

    @jakobbotsch
    MemberAuthor

    @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.

  24. jilles-sg commented on Jul 17, 2026

    @jilles-sg

    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).
  25. jakobbotsch commented on Jul 24, 2026

    @jakobbotsch
    MemberAuthor

    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 opened an agent session to expand the API docs: dotnet/dotnet-api-docs#12902

  26. locked and limited conversation to collaborators on Aug 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Priority:2area-CodeGen-coreclr

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions