Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 105 additions & 8 deletions src/coreclr/tools/Common/TypeSystem/IL/Stubs/AsyncResumptionStub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ public partial class AsyncResumptionStub : ILStubMethod
{
private readonly MethodDesc _owningMethod;
private MethodSignature _signature;
private MethodIL _methodIL;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We do not store IL on the ILStubMethods. There is a cache in the ILProvider.


public AsyncResumptionStub(MethodDesc owningMethod)
{
Debug.Assert(owningMethod.IsAsyncVariant()
|| (owningMethod.IsAsync && !owningMethod.Signature.ReturnsTaskOrValueTask()));
Debug.Assert(owningMethod.IsAsyncCall());
_owningMethod = owningMethod;
}

Expand All @@ -32,22 +32,119 @@ public AsyncResumptionStub(MethodDesc owningMethod)

public override TypeSystemContext Context => _owningMethod.Context;

protected override int ClassCode => unchecked((int)0xa91ac565);

Copy link

Copilot AI Nov 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This ClassCode value conflicts with the existing value in AsyncResumptionStub.Sorting.cs (0x773ab1). Both implementations define ClassCode for the same partial class, creating a duplicate definition that will cause a compilation error.

Suggested change
protected override int ClassCode => unchecked((int)0xa91ac565);

Copilot uses AI. Check for mistakes.
private MethodSignature InitializeSignature()
{
TypeDesc objectType = Context.GetWellKnownType(WellKnownType.Object);
TypeDesc byrefByte = Context.GetWellKnownType(WellKnownType.Byte).MakeByRefType();
return _signature = new MethodSignature(0, 0, objectType, [objectType, byrefByte]);
}

public override MethodIL EmitIL()
private MethodIL InitializeMethodIL()
{
var emitter = new ILEmitter();
ILCodeStream codeStream = emitter.NewCodeStream();
Debug.Assert(_methodIL == null);
ILEmitter ilEmitter = new ILEmitter();
ILCodeStream ilStream = ilEmitter.NewCodeStream();

// Ported from jitinterface.cpp CEEJitInfo::getAsyncResumptionStub
// Emitted IL:
// if (!_owningMethod.Signature.IsStatic)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do not think this comment useful. You can easily tell what the IL is from the actual emitter below. It can only get out of sync overtime.

// {
// if (_owningMethod.OwningType.IsValueType)
// ldc.i4.0
// conv.u
// else
// ldnull
// }
// foreach (param in _owningMethod.Signature)
// {
// ldloca.s <local>
// initobj <param type>
// ldloc.s <local>
// }
// ldftn <_owningMethod>
// calli <this.Signature>
// if (!returnsVoid)
// stloc.s <resultLocal>
// call System.StubHelpers.StubHelpers::AsyncCallContinuation()
// stloc.s <newContinuationLocal>
// if (!returnsVoid)
// {
// ldloca.s <newContinuationLocal>
// brtrue.s done_result
// ldarg.1
// ldloc.s <resultLocal>
// stobj <return type>
// done_result:
// }
// ldloc.s <newContinuationLocal>
// ret

// if it has this pointer
if (!_owningMethod.Signature.IsStatic)
{
if (_owningMethod.OwningType.IsValueType)
{
ilStream.EmitLdc(0);
ilStream.Emit(ILOpcode.conv_u);
}
else
{
ilStream.Emit(ILOpcode.ldnull);
}
}

foreach (var param in _owningMethod.Signature)
Copy link
Member

@VSadov VSadov Nov 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On the JIT side here, between this and other arguments, we also put:

  • generic context arg, if present.
    It is set to 0, and will not be used by the calee. Continuation has captured the real value and that will be used instead. But we need to match what the calee expects, so we need to push 0 for the context.
  • continuation.
    it is our arg0. Per the ABI of Async* calls it goes right before the other arguments.
    (unless this is x86)

On x86, as usual, there is a difference and the hidden args go after formal ones and in reverse order.

--
*Note - the resume stub is an ordinary function, but what we are resuming is an Async method, thus we shuffle the continuation from our arg0 to its predefined/hidden position in the calee signature.

{
var local = ilEmitter.NewLocal(param);
ilStream.EmitLdLoca(local);
ilStream.Emit(ILOpcode.initobj, ilEmitter.NewToken(param));
ilStream.EmitLdLoc(local);
}
ilStream.Emit(ILOpcode.ldftn, ilEmitter.NewToken(_owningMethod));
Copy link
Member

@VSadov VSadov Nov 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure. Maybe this is correct in NAOT, but ldftn is a bit suspicious.

If this is a metadata token for the method that we are resuming, you may end up calling the Task-returning variant.
In the JIT counterpart we load the actual address of the JITed target method.
As in:

        pCode->EmitLDC((DWORD_PTR)m_finalCodeAddressSlot);
        pCode->EmitLDIND_I();

cc: @MichalStrehovsky - will ldftn do the right thing here?

Copy link
Member

@jkotas jkotas Nov 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be emitted as a regular call and the JIT/EE interface and/or the JIT itself should make sure that the call does the right thing.

(Once we figure out what to do here, we may want to switch the JIT counterpart to the same plan.)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this should be a regular call. The call will be to a thing with RuntimeAsync calling convention; we can make tokens for that and we will make such token here. We probably don't need to pass generic context explicitly either.

But the question is what this will do in the JIT. My expectation is that it will take similar paths as a AsyncExplicitImpl method call.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But the question is what this will do in the JIT. My expectation is that it will take similar paths as a AsyncExplicitImpl method call.

Runtime async method calls pass a null continuation in the JIT. This needs to pass an actual continuation.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Resume" in a way is the opposite of "Call". In Call we pass formal arguments, generic context, etc.., but continuation is null. In Resume only continuation is what is not default/null.

Doing CALLI with a special-crafted signature is the technique to do a low level "unsafe cast" through call conventions in IL. I have seen it in other places (like instantiating stubs?).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My expectation is that it will take similar paths as a AsyncExplicitImpl method call.

Note - what we are resuming may actually be AsyncExplicitImpl.

Anything with Async call conv may need resuming. Whether it has a variant with non-async call convention is unimportant here. Just the part is that it is Async (i.e. emitted as a state machine, has async call conv).

Copy link
Member

@jkotas jkotas Nov 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have seen it in other places (like instantiating stubs?).

I do not think that this trick is used anywhere in AOT compilers (just looked through all Emit(ILOpcode.calli - none of them look like that).

AsyncCallContinuation() intrinsic gets the async continuation from the last call. Can we have a counterpart that sets the async continuation for the next call?

We can try going the ldftn route, but I expect that it will hit problems with generics and the generated code won't be the best at the end if we manage to make it work. Managed function pointers in NAOT are tagged pointers. Regular calli of a managed function pointer compiles into if (ptr & tag_bit) { ptr[0](ptr[1] /* instantiating arg */, regular args); } else { ptr(regular args) }. We would probably need to suppress this for this ldftn + calli pair.

Copy link
Member

@VSadov VSadov Nov 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could CALLI trick work the same as in JIT case if we clear the tag after LDFTN?

(This all assumes that we can know if the calee/resumee has a generic context parameter and can push 0 to its position)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As another wild thought - I think this IL is never exposed outside of internals of VM/JIT/AOT. Perhaps we could use an IL prefix to tag a call as a resuming call?

Ex:

// load continuation 
   ldarg 0     
// the prefix means "consume one arg as a continuation argument, pass everything else as default"
// could be applied to calli as well
// callee must have async callconv
   resume.              
   call  <token>     

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could CALLI trick work the same as in JIT case if we clear the tag after LDFTN?

We can certainly try to make LDFTN + CALLI work and special-case it in enough places to make it do what we want. My gut feeling is that it won't be pretty.

Perhaps we could use an IL prefix to tag a call as a resuming call?

I think it is equivalent to AsyncCallContinuation setter intrinsic, just with a different encoding. We have prior art to use calls to encode internal custom modifiers of call instructions (e.g. NextCallReturnAddress or AsyncCallContinuation), so I would continue to do so here as well.

ilStream.Emit(ILOpcode.calli, ilEmitter.NewToken(this.Signature));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this.Signature the signature of the stub or the method that we are resuming?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this.Signature is the stub signature. This should be changed to _owningMethod.Signature.


bool returnsVoid = _owningMethod.Signature.ReturnType != Context.GetWellKnownType(WellKnownType.Void);
Internal.IL.Stubs.ILLocalVariable resultLocal = default;
if (!returnsVoid)
{
resultLocal = ilEmitter.NewLocal(_owningMethod.Signature.ReturnType);
ilStream.EmitStLoc(resultLocal);
}

MethodDesc asyncCallContinuation = Context.SystemModule.GetKnownType("System.StubHelpers"u8, "StubHelpers"u8)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we move this to AsyncHelpers so that we do not have to add StubHelpers.cs to NativeAOT?

StubHelpers in CoreCLR is everything-in-the-kitchen-sink type. It is not pretty.

.GetKnownMethod("AsyncCallContinuation"u8, null);
TypeDesc continuation = Context.SystemModule.GetKnownType("System.Runtime.CompilerServices"u8, "Continuation"u8);
var newContinuationLocal = ilEmitter.NewLocal(continuation);
ilStream.Emit(ILOpcode.call, ilEmitter.NewToken(asyncCallContinuation));
ilStream.EmitStLoc(newContinuationLocal);

// TODO: match getAsyncResumptionStub from CoreCLR VM
codeStream.EmitCallThrowHelper(emitter, Context.GetHelperEntryPoint("ThrowHelpers"u8, "ThrowNotSupportedException"u8));
if (!returnsVoid)
{
var doneResult = ilEmitter.NewCodeLabel();
ilStream.EmitLdLoca(newContinuationLocal);
ilStream.Emit(ILOpcode.brtrue, doneResult);
ilStream.EmitLdArg(1);
ilStream.EmitLdLoc(resultLocal);
ilStream.Emit(ILOpcode.stobj, ilEmitter.NewToken(_owningMethod.Signature.ReturnType));
ilStream.EmitLabel(doneResult);
}
ilStream.EmitLdLoc(newContinuationLocal);
ilStream.Emit(ILOpcode.ret);

return emitter.Link(this);
return _methodIL = ilEmitter.Link(this);
}

public override MethodIL EmitIL()
{
return _methodIL ?? InitializeMethodIL();
}
Copy link

Copilot AI Nov 7, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The logic for returnsVoid is inverted. It should be == instead of !=. The variable is true when the return type is NOT void, which means the variable name and logic are contradictory. This will cause incorrect IL generation - the result handling code will execute when the method returns void and will be skipped when it doesn't return void.

Copilot uses AI. Check for mistakes.

protected override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer)
{
var othr = (AsyncResumptionStub)other;
return comparer.Compare(_owningMethod, othr._owningMethod);
}
}
}
Loading