From d72ebf45c560319ab876c8b7220950212c84fe87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Strehovsk=C3=BD?= Date: Tue, 25 Nov 2025 14:06:44 +0100 Subject: [PATCH 1/3] Use new JIT helpers for instantiating thunks --- .../tools/Common/JitInterface/CorInfoImpl.cs | 5 - .../CompilerTypeSystemContext.BoxedTypes.cs | 121 +----------------- ...mpilerTypeSystemContext.InterfaceThunks.cs | 115 +---------------- .../CompilerTypeSystemContext.Sorting.cs | 22 ---- .../DependencyAnalysis/ILScanNodeFactory.cs | 10 +- .../IL/ILImporter.Scanner.cs | 18 +-- .../DependencyAnalysis/RyuJitNodeFactory.cs | 10 +- 7 files changed, 21 insertions(+), 280 deletions(-) diff --git a/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs b/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs index ca41749d348bd0..5ca092d1e5eae0 100644 --- a/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs +++ b/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs @@ -842,11 +842,6 @@ private void Get_CORINFO_SIG_INFO(MethodDesc method, CORINFO_SIG_INFO* sig, Meth if (method.IsIntrinsic) { // Some intrinsics will beg to differ about the hasHiddenParameter decision -#if !READYTORUN - if (_compilation.TypeSystemContext.IsSpecialUnboxingThunkTargetMethod(method)) - hasHiddenParameter = false; -#endif - if (method.IsArrayAddressMethod()) hasHiddenParameter = true; } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.BoxedTypes.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.BoxedTypes.cs index 0b8d50589b9b5e..5b1d168a7107ff 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.BoxedTypes.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.BoxedTypes.cs @@ -38,14 +38,7 @@ // * Having the unboxing stub load the m_pEEType field (to get generic // context) and a byref to the actual value (to get a 'this' expected by // valuetype methods) -// * Generating a call to a fake instance method on the valuetype that has -// the hidden (generic context) argument explicitly present in the -// signature. We need a fake method to be able to refer to the hidden parameter -// from IL. -// -// At a later stage (once codegen is done), we replace the references to the -// fake instance method with the real instance method. Their signatures after -// compilation is identical. +// * Using a JIT intrinsic to set the generic context on the called method. // namespace ILCompiler @@ -122,24 +115,6 @@ public MethodDesc GetUnboxingThunk(MethodDesc targetMethod, ModuleDesc ownerModu return thunk; } - /// - /// Returns true of is a standin method for unboxing thunk target. - /// - public bool IsSpecialUnboxingThunkTargetMethod(MethodDesc method) - { - return method.GetTypicalMethodDefinition().GetType() == typeof(ValueTypeInstanceMethodWithHiddenParameter); - } - - /// - /// Returns the real target method of an unboxing stub. - /// - public MethodDesc GetRealSpecialUnboxingThunkTargetMethod(MethodDesc method) - { - MethodDesc typicalMethod = method.GetTypicalMethodDefinition(); - MethodDesc methodDefinitionRepresented = ((ValueTypeInstanceMethodWithHiddenParameter)typicalMethod).MethodRepresented; - return GetMethodForInstantiatedType(methodDefinitionRepresented, (InstantiatedType)method.OwningType); - } - private struct BoxedValuetypeHashtableKey { public readonly MetadataType ValueType; @@ -375,7 +350,6 @@ public MethodDesc GetTargetOfSpecialUnboxingThunk(MethodDesc method) private sealed partial class GenericUnboxingThunk : ILStubMethod { private MethodDesc _targetMethod; - private ValueTypeInstanceMethodWithHiddenParameter _nakedTargetMethod; private BoxedValueType _owningType; public GenericUnboxingThunk(BoxedValueType owningType, MethodDesc targetMethod) @@ -385,7 +359,6 @@ public GenericUnboxingThunk(BoxedValueType owningType, MethodDesc targetMethod) _owningType = owningType; _targetMethod = targetMethod; - _nakedTargetMethod = new ValueTypeInstanceMethodWithHiddenParameter(targetMethod); } public override TypeSystemContext Context => _targetMethod.Context; @@ -439,39 +412,26 @@ public override MethodIL EmitIL() ILEmitter emit = new ILEmitter(); ILCodeStream codeStream = emit.NewCodeStream(); - bool isX86 = Context.Target.Architecture == TargetArchitecture.X86; - FieldDesc eeTypeField = Context.GetWellKnownType(WellKnownType.Object).GetKnownField("m_pEEType"u8); // Load ByRef to the field with the value of the boxed valuetype codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldflda, emit.NewToken(Context.SystemModule.GetKnownType("System.Runtime.CompilerServices"u8, "RawData"u8).GetField("Data"u8))); - if (isX86) - { - for (int i = 0; i < _targetMethod.Signature.Length; i++) - { - codeStream.EmitLdArg(i + 1); - } - } - // Load the MethodTable of the boxed valuetype (this is the hidden generic context parameter expected // by the (canonical) instance method, but normally not part of the signature in IL). codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emit.NewToken(eeTypeField)); + codeStream.Emit(ILOpcode.call, emit.NewToken(Context.GetCoreLibEntryPoint("System.Runtime.CompilerServices"u8, "RuntimeHelpers"u8, "SetNextCallGenericContext"u8, null))); + // Load rest of the arguments - if (!isX86) + for (int i = 0; i < _targetMethod.Signature.Length; i++) { - for (int i = 0; i < _targetMethod.Signature.Length; i++) - { - codeStream.EmitLdArg(i + 1); - } + codeStream.EmitLdArg(i + 1); } - // Call an instance method on the target valuetype that has a fake instantiation parameter - // in it's signature. This will be swapped by the actual instance method after codegen is done. - codeStream.Emit(ILOpcode.call, emit.NewToken(_nakedTargetMethod.InstantiateAsOpen())); + codeStream.Emit(ILOpcode.call, emit.NewToken(_targetMethod.InstantiateAsOpen())); codeStream.Emit(ILOpcode.ret); return emit.Link(this); @@ -584,74 +544,5 @@ public override MethodIL EmitIL() public override Instantiation Instantiation => _targetMethod.Instantiation; } - - /// - /// Represents an instance method on a generic valuetype with an explicit instantiation parameter in the - /// signature. This is so that we can refer to the parameter from IL. References to this method will - /// be replaced by the actual instance method after codegen is done. - /// - internal sealed partial class ValueTypeInstanceMethodWithHiddenParameter : MethodDesc - { - private MethodDesc _methodRepresented; - private MethodSignature _signature; - - public ValueTypeInstanceMethodWithHiddenParameter(MethodDesc methodRepresented) - { - Debug.Assert(methodRepresented.OwningType.IsValueType); - Debug.Assert(!methodRepresented.Signature.IsStatic); - - _methodRepresented = methodRepresented; - } - - public MethodDesc MethodRepresented => _methodRepresented; - - // We really don't want this method to be inlined. - public override bool IsNoInlining => true; - - public override bool IsInternalCall => true; - - public override bool IsIntrinsic => true; - - public override TypeSystemContext Context => _methodRepresented.Context; - public override TypeDesc OwningType => _methodRepresented.OwningType; - - public override ReadOnlySpan Name => _methodRepresented.Name; - public override string DiagnosticName => _methodRepresented.DiagnosticName; - - public override MethodSignature Signature - { - get - { - if (_signature == null) - { - TypeDesc[] parameters = new TypeDesc[_methodRepresented.Signature.Length + 1]; - - // Shared instance methods on generic valuetypes have a hidden parameter with the generic context. - // We add it to the signature so that we can refer to it from IL. - if (Context.Target.Architecture == TargetArchitecture.X86) - { - for (int i = 0; i < _methodRepresented.Signature.Length; i++) - parameters[i] = _methodRepresented.Signature[i]; - parameters[_methodRepresented.Signature.Length] = Context.GetWellKnownType(WellKnownType.Void).MakePointerType(); - } - else - { - parameters[0] = Context.GetWellKnownType(WellKnownType.Void).MakePointerType(); - for (int i = 0; i < _methodRepresented.Signature.Length; i++) - parameters[i + 1] = _methodRepresented.Signature[i]; - } - - _signature = new MethodSignature(_methodRepresented.Signature.Flags, - _methodRepresented.Signature.GenericParameterCount, - _methodRepresented.Signature.ReturnType, - parameters); - } - - return _signature; - } - } - - public override bool HasCustomAttribute(string attributeNamespace, string attributeName) => false; - } } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.InterfaceThunks.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.InterfaceThunks.cs index 7eb8b349d1d1d0..bdead61ea39b95 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.InterfaceThunks.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.InterfaceThunks.cs @@ -99,23 +99,6 @@ public MethodDesc GetDefaultInterfaceMethodImplementationThunk(MethodDesc target return thunk; } - /// - /// Returns true of is a standin method for instantiating thunk target. - /// - public bool IsDefaultInterfaceMethodImplementationThunkTargetMethod(MethodDesc method) - { - return method.GetTypicalMethodDefinition().GetType() == typeof(DefaultInterfaceMethodImplementationWithHiddenParameter); - } - - /// - /// Returns the real target method of an instantiating thunk. - /// - public MethodDesc GetRealDefaultInterfaceMethodImplementationThunkTargetMethod(MethodDesc method) - { - MethodDesc typicalMethod = method.GetTypicalMethodDefinition(); - return ((DefaultInterfaceMethodImplementationWithHiddenParameter)typicalMethod).MethodRepresented; - } - private struct DefaultInterfaceMethodImplementationInstantiationThunkHashtableKey { public readonly MethodDesc TargetMethod; @@ -166,7 +149,6 @@ protected override DefaultInterfaceMethodImplementationInstantiationThunk Create private sealed partial class DefaultInterfaceMethodImplementationInstantiationThunk : ILStubMethod, IPrefixMangledMethod { private readonly MethodDesc _targetMethod; - private readonly DefaultInterfaceMethodImplementationWithHiddenParameter _nakedTargetMethod; private readonly TypeDesc _owningType; private readonly int _interfaceIndex; private readonly bool _useContextFromRuntime; @@ -178,7 +160,6 @@ public DefaultInterfaceMethodImplementationInstantiationThunk(TypeDesc owningTyp _owningType = owningType; _targetMethod = targetMethod; - _nakedTargetMethod = new DefaultInterfaceMethodImplementationWithHiddenParameter(targetMethod, owningType); _interfaceIndex = interfaceIndex; _useContextFromRuntime = useContextFromRuntime; } @@ -237,19 +218,9 @@ public override MethodIL EmitIL() MethodDesc getOrdinalInterfaceMethod = Context.GetHelperEntryPoint("SharedCodeHelpers"u8, "GetOrdinalInterface"u8); MethodDesc getCurrentContext = Context.GetHelperEntryPoint("SharedCodeHelpers"u8, "GetCurrentSharedThunkContext"u8); - bool isX86 = Context.Target.Architecture == TargetArchitecture.X86; - // Load "this" codeStream.EmitLdArg(0); - if (isX86) - { - for (int i = 0; i < _targetMethod.Signature.Length; i++) - { - codeStream.EmitLdArg(i + 1); - } - } - // Load the instantiating argument. if (_useContextFromRuntime) { @@ -267,93 +238,19 @@ public override MethodIL EmitIL() codeStream.Emit(ILOpcode.call, emit.NewToken(getOrdinalInterfaceMethod)); } - if (!isX86) + codeStream.Emit(ILOpcode.call, emit.NewToken(Context.GetCoreLibEntryPoint("System.Runtime.CompilerServices"u8, "RuntimeHelpers"u8, "SetNextCallGenericContext"u8, null))); + + // Load rest of the arguments + for (int i = 0; i < _targetMethod.Signature.Length; i++) { - // Load rest of the arguments - for (int i = 0; i < _targetMethod.Signature.Length; i++) - { - codeStream.EmitLdArg(i + 1); - } + codeStream.EmitLdArg(i + 1); } - // Call an instance method on the target interface that has a fake instantiation parameter - // in it's signature. This will be swapped by the actual instance method after codegen is done. - codeStream.Emit(ILOpcode.call, emit.NewToken(_nakedTargetMethod)); + codeStream.Emit(ILOpcode.call, emit.NewToken(_targetMethod)); codeStream.Emit(ILOpcode.ret); return emit.Link(this); } } - - /// - /// Represents an instance method on a generic interface with an explicit instantiation parameter in the - /// signature. This is so that we can refer to the parameter from IL. References to this method will - /// be replaced by the actual instance method after codegen is done. - /// - internal sealed partial class DefaultInterfaceMethodImplementationWithHiddenParameter : MethodDesc - { - private readonly MethodDesc _methodRepresented; - private readonly TypeDesc _owningType; - private MethodSignature _signature; - - public DefaultInterfaceMethodImplementationWithHiddenParameter(MethodDesc methodRepresented, TypeDesc owningType) - { - Debug.Assert(methodRepresented.OwningType.IsInterface); - Debug.Assert(!methodRepresented.Signature.IsStatic); - - _methodRepresented = methodRepresented; - _owningType = owningType; - } - - public MethodDesc MethodRepresented => _methodRepresented; - - // We really don't want this method to be inlined. - public override bool IsNoInlining => true; - - public override bool IsInternalCall => true; - - public override bool IsIntrinsic => true; - - public override TypeSystemContext Context => _methodRepresented.Context; - public override TypeDesc OwningType => _owningType; - - public override ReadOnlySpan Name => _methodRepresented.Name; - public override string DiagnosticName => _methodRepresented.DiagnosticName; - - public override MethodSignature Signature - { - get - { - if (_signature == null) - { - TypeDesc[] parameters = new TypeDesc[_methodRepresented.Signature.Length + 1]; - - // Shared instance methods on generic interfaces have a hidden parameter with the generic context. - // We add it to the signature so that we can refer to it from IL. - if (Context.Target.Architecture == TargetArchitecture.X86) - { - for (int i = 0; i < _methodRepresented.Signature.Length; i++) - parameters[i] = _methodRepresented.Signature[i]; - parameters[_methodRepresented.Signature.Length] = Context.GetWellKnownType(WellKnownType.Void).MakePointerType(); - } - else - { - parameters[0] = Context.GetWellKnownType(WellKnownType.Void).MakePointerType(); - for (int i = 0; i < _methodRepresented.Signature.Length; i++) - parameters[i + 1] = _methodRepresented.Signature[i]; - } - - _signature = new MethodSignature(_methodRepresented.Signature.Flags, - _methodRepresented.Signature.GenericParameterCount, - _methodRepresented.Signature.ReturnType, - parameters); - } - - return _signature; - } - } - - public override bool HasCustomAttribute(string attributeNamespace, string attributeName) => false; - } } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.Sorting.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.Sorting.cs index 92f553ce526f96..7af34cd89a3b08 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.Sorting.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/CompilerTypeSystemContext.Sorting.cs @@ -40,17 +40,6 @@ protected override int CompareToImpl(MethodDesc other, TypeSystemComparer compar } } - internal partial class ValueTypeInstanceMethodWithHiddenParameter - { - protected override int ClassCode => 2131875345; - - protected override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) - { - var otherMethod = (ValueTypeInstanceMethodWithHiddenParameter)other; - return comparer.Compare(_methodRepresented, otherMethod._methodRepresented); - } - } - private partial class DefaultInterfaceMethodImplementationInstantiationThunk { protected override int ClassCode => -789598; @@ -66,16 +55,5 @@ protected override int CompareToImpl(MethodDesc other, TypeSystemComparer compar return comparer.Compare(_targetMethod, otherMethod._targetMethod); } } - - internal partial class DefaultInterfaceMethodImplementationWithHiddenParameter - { - protected override int ClassCode => 4903209; - - protected override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) - { - var otherMethod = (DefaultInterfaceMethodImplementationWithHiddenParameter)other; - return comparer.Compare(_methodRepresented, otherMethod._methodRepresented); - } - } } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ILScanNodeFactory.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ILScanNodeFactory.cs index 00496eba03a6de..97a5d4fb51cb10 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ILScanNodeFactory.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ILScanNodeFactory.cs @@ -22,15 +22,7 @@ protected override IMethodNode CreateMethodEntrypointNode(MethodDesc method) if (method.IsInternalCall) { // TODO: come up with a scheme where this can be shared between codegen backends and the scanner - if (TypeSystemContext.IsSpecialUnboxingThunkTargetMethod(method)) - { - return MethodEntrypoint(TypeSystemContext.GetRealSpecialUnboxingThunkTargetMethod(method)); - } - else if (TypeSystemContext.IsDefaultInterfaceMethodImplementationThunkTargetMethod(method)) - { - return MethodEntrypoint(TypeSystemContext.GetRealDefaultInterfaceMethodImplementationThunkTargetMethod(method)); - } - else if (method.IsExplicitContinuationAsyncMethod()) + if (method.IsExplicitContinuationAsyncMethod()) { return MethodEntrypoint(method.GetExplicitContinuationAsyncMethodTarget()); } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/ILImporter.Scanner.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/ILImporter.Scanner.cs index 549793267cfe43..cf1a92fef36a8c 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/ILImporter.Scanner.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/ILImporter.Scanner.cs @@ -777,22 +777,18 @@ private void ImportCall(ILOpcode opcode, int token) { ISymbolNode instParam = null; - if (targetMethod.RequiresInstMethodDescArg()) + if (!_canonMethod.IsSharedByGenericInstantiations) + { + // Some handemitted IL helpers will call __Canon methods directly from unshared context. + // This is fine, we just don't report any dependencies for the exact instantiation. + } + else if (targetMethod.RequiresInstMethodDescArg()) { instParam = GetGenericLookupHelper(ReadyToRunHelperId.MethodDictionary, runtimeDeterminedMethod); } else if (targetMethod.RequiresInstMethodTableArg()) { - bool hasHiddenParameter = true; - - if (targetMethod.IsIntrinsic) - { - if (_factory.TypeSystemContext.IsSpecialUnboxingThunkTargetMethod(targetMethod)) - hasHiddenParameter = false; - } - - if (hasHiddenParameter) - instParam = GetGenericLookupHelper(ReadyToRunHelperId.TypeHandle, runtimeDeterminedMethod.OwningType); + instParam = GetGenericLookupHelper(ReadyToRunHelperId.TypeHandle, runtimeDeterminedMethod.OwningType); } if (instParam != null) diff --git a/src/coreclr/tools/aot/ILCompiler.RyuJit/Compiler/DependencyAnalysis/RyuJitNodeFactory.cs b/src/coreclr/tools/aot/ILCompiler.RyuJit/Compiler/DependencyAnalysis/RyuJitNodeFactory.cs index dc9bef2b66c87c..fd1abaeba8989c 100644 --- a/src/coreclr/tools/aot/ILCompiler.RyuJit/Compiler/DependencyAnalysis/RyuJitNodeFactory.cs +++ b/src/coreclr/tools/aot/ILCompiler.RyuJit/Compiler/DependencyAnalysis/RyuJitNodeFactory.cs @@ -20,15 +20,7 @@ protected override IMethodNode CreateMethodEntrypointNode(MethodDesc method) { if (method.IsInternalCall) { - if (TypeSystemContext.IsSpecialUnboxingThunkTargetMethod(method)) - { - return MethodEntrypoint(TypeSystemContext.GetRealSpecialUnboxingThunkTargetMethod(method)); - } - else if (TypeSystemContext.IsDefaultInterfaceMethodImplementationThunkTargetMethod(method)) - { - return MethodEntrypoint(TypeSystemContext.GetRealDefaultInterfaceMethodImplementationThunkTargetMethod(method)); - } - else if (method.IsExplicitContinuationAsyncMethod()) + if (method.IsExplicitContinuationAsyncMethod()) { return MethodEntrypoint(method.GetExplicitContinuationAsyncMethodTarget()); } From 84adb2c8e266ea09263ac82057f904c3fa12c190 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Strehovsk=C3=BD?= Date: Tue, 25 Nov 2025 14:07:40 +0100 Subject: [PATCH 2/3] Use new JIT helpers for continuations --- .../IL/Stubs/AsyncResumptionStub.Sorting.cs | 10 -- .../IL/Stubs/AsyncResumptionStub.cs | 164 ++---------------- .../DependencyAnalysis/ILScanNodeFactory.cs | 6 +- .../DependencyAnalysis/RyuJitNodeFactory.cs | 6 +- 4 files changed, 13 insertions(+), 173 deletions(-) diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/AsyncResumptionStub.Sorting.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/AsyncResumptionStub.Sorting.cs index 3117ad5e742319..e62e414c99f2e5 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/AsyncResumptionStub.Sorting.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/AsyncResumptionStub.Sorting.cs @@ -15,14 +15,4 @@ protected override int CompareToImpl(MethodDesc other, TypeSystemComparer compar return comparer.Compare(_targetMethod, ((AsyncResumptionStub)other)._targetMethod); } } - - internal sealed partial class ExplicitContinuationAsyncMethod : MethodDesc - { - protected override int ClassCode => 0xd076659; - - protected override int CompareToImpl(MethodDesc other, TypeSystemComparer comparer) - { - return comparer.Compare(_wrappedMethod, ((ExplicitContinuationAsyncMethod)other)._wrappedMethod); - } - } } diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/AsyncResumptionStub.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/AsyncResumptionStub.cs index f768c793083f56..6297eab0b03814 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/AsyncResumptionStub.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/AsyncResumptionStub.cs @@ -60,16 +60,16 @@ public override MethodIL EmitIL() } } - if (Context.Target.Architecture != TargetArchitecture.X86) + if (_targetMethod.RequiresInstArg()) { - if (_targetMethod.RequiresInstArg()) - { - ilStream.EmitLdc(0); - ilStream.Emit(ILOpcode.conv_i); - } - ilStream.EmitLdArg(0); + ilStream.EmitLdc(0); + ilStream.Emit(ILOpcode.conv_i); + ilStream.Emit(ILOpcode.call, ilEmitter.NewToken(Context.GetCoreLibEntryPoint("System.Runtime.CompilerServices"u8, "RuntimeHelpers"u8, "SetNextCallGenericContext"u8, null))); } + ilStream.EmitLdArg(0); + ilStream.Emit(ILOpcode.call, ilEmitter.NewToken(Context.GetCoreLibEntryPoint("System.Runtime.CompilerServices"u8, "RuntimeHelpers"u8, "SetNextCallAsyncContinuation"u8, null))); + foreach (var param in _targetMethod.Signature) { var local = ilEmitter.NewLocal(param); @@ -78,24 +78,13 @@ public override MethodIL EmitIL() ilStream.EmitLdLoc(local); } - if (Context.Target.Architecture == TargetArchitecture.X86) - { - ilStream.EmitLdArg(0); - if (_targetMethod.RequiresInstArg()) - { - ilStream.EmitLdc(0); - ilStream.Emit(ILOpcode.conv_i); - } - } + ilStream.Emit(ILOpcode.call, ilEmitter.NewToken(_targetMethod)); - MethodDesc resumingMethod = new ExplicitContinuationAsyncMethod(_targetMethod); - ilStream.Emit(ILOpcode.call, ilEmitter.NewToken(resumingMethod)); - - bool returnsVoid = resumingMethod.Signature.ReturnType.IsVoid; + bool returnsVoid = _targetMethod.Signature.ReturnType.IsVoid; ILLocalVariable resultLocal = default; if (!returnsVoid) { - resultLocal = ilEmitter.NewLocal(resumingMethod.Signature.ReturnType); + resultLocal = ilEmitter.NewLocal(_targetMethod.Signature.ReturnType); ilStream.EmitStLoc(resultLocal); } @@ -113,7 +102,7 @@ public override MethodIL EmitIL() ilStream.Emit(ILOpcode.brtrue, doneResult); ilStream.EmitLdArg(1); ilStream.EmitLdLoc(resultLocal); - ilStream.Emit(ILOpcode.stobj, ilEmitter.NewToken(resumingMethod.Signature.ReturnType)); + ilStream.Emit(ILOpcode.stobj, ilEmitter.NewToken(_targetMethod.Signature.ReturnType)); ilStream.EmitLabel(doneResult); } ilStream.EmitLdLoc(newContinuationLocal); @@ -122,135 +111,4 @@ public override MethodIL EmitIL() return ilEmitter.Link(this); } } - - /// - /// A dummy method used to tell the jit that we want to explicitly pass the hidden Continuation parameter - /// as well as the generic context parameter (if any) for async resumption methods. - /// This method should be marked IsAsync=false and HasInstantiation=false. These are defaults - /// for MethodDesc and so aren't explicitly set in the code below. - /// - internal sealed partial class ExplicitContinuationAsyncMethod : MethodDesc - { - private MethodSignature _signature; - private readonly MethodDesc _wrappedMethod; - private readonly MethodDesc _typicalDefinition; - - public ExplicitContinuationAsyncMethod(MethodDesc target) - { - _wrappedMethod = target; - - MethodDesc targetTypicalDefinition = target.GetTypicalMethodDefinition(); - if (targetTypicalDefinition != target) - _typicalDefinition = new ExplicitContinuationAsyncMethod(targetTypicalDefinition); - else - _typicalDefinition = this; - } - - public MethodDesc Target => _wrappedMethod; - - /// - /// To explicitly pass the hidden parameters for async resumption methods, - /// we need to add explicit Continuation and generic context parameters to the signature. - /// - private MethodSignature InitializeSignature() - { - // Async methods have an implicit Continuation parameter - // The order of parameters depends on the architecture - // non-x86: this?, genericCtx?, continuation, params... - // x86: this?, params, continuation, genericCtx? - // To make the jit pass arguments in this order, we can add the continuation parameter - // at the end for x86 and at the beginning for other architectures. - // The 'this' parameter and generic context parameter (if any) can be handled by the jit. - - var parameters = new TypeDesc[_wrappedMethod.Signature.Length + 1 + (_wrappedMethod.RequiresInstArg() ? 1 : 0)]; - - TypeDesc continuation = Context.SystemModule.GetKnownType("System.Runtime.CompilerServices"u8, "Continuation"u8); - if (Context.Target.Architecture == TargetArchitecture.X86) - { - int i = 0; - for (; i < _wrappedMethod.Signature.Length; i++) - { - parameters[i] = _wrappedMethod.Signature[i]; - } - parameters[i++] = continuation; - if (_wrappedMethod.RequiresInstArg()) - { - parameters[i] = Context.GetWellKnownType(WellKnownType.Void).MakePointerType(); - } - } - else - { - int i = 0; - if (_wrappedMethod.RequiresInstArg()) - { - parameters[i++] = Context.GetWellKnownType(WellKnownType.Void).MakePointerType(); - } - parameters[i++] = continuation; - foreach (var param in _wrappedMethod.Signature) - { - parameters[i++] = param; - } - } - // Get the return type from the Task-returning variant - TypeDesc returnType; - if (_wrappedMethod is AsyncMethodVariant variant) - { - Debug.Assert(variant.Target.Signature.ReturnsTaskOrValueTask()); - if (variant.Target.Signature.ReturnType is { HasInstantiation: true } wrappedReturnType) - { - returnType = wrappedReturnType.Instantiation[0]; - } - else - { - returnType = Context.GetWellKnownType(WellKnownType.Void); - } - } - else - { - // AsyncExplicitImpl - returnType = _wrappedMethod.Signature.ReturnType; - } - - return _signature = new MethodSignature( - _wrappedMethod.Signature.Flags, - 0, - returnType, - parameters); - } - - public override bool HasCustomAttribute(string attributeNamespace, string attributeName) => throw new NotImplementedException(); - - public override MethodSignature Signature - { - get - { - if (_signature is null) - return InitializeSignature(); - - return _signature; - } - } - - public override string DiagnosticName => $"ExplicitContinuationAsyncMethod({_wrappedMethod.DiagnosticName})"; - - public override TypeDesc OwningType => _wrappedMethod.OwningType; - - public override TypeSystemContext Context => _wrappedMethod.Context; - - public override bool IsInternalCall => true; - - public override MethodDesc GetTypicalMethodDefinition() => _typicalDefinition; - } - - public static class AsyncResumptionStubExtensions - { - public static bool IsExplicitContinuationAsyncMethod(this MethodDesc method) - { - return method is ExplicitContinuationAsyncMethod; - } - public static MethodDesc GetExplicitContinuationAsyncMethodTarget(this MethodDesc method) - { - return ((ExplicitContinuationAsyncMethod)method).Target; - } - } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ILScanNodeFactory.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ILScanNodeFactory.cs index 97a5d4fb51cb10..774bd20b1104fb 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ILScanNodeFactory.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/ILScanNodeFactory.cs @@ -22,11 +22,7 @@ protected override IMethodNode CreateMethodEntrypointNode(MethodDesc method) if (method.IsInternalCall) { // TODO: come up with a scheme where this can be shared between codegen backends and the scanner - if (method.IsExplicitContinuationAsyncMethod()) - { - return MethodEntrypoint(method.GetExplicitContinuationAsyncMethodTarget()); - } - else if (method.IsArrayAddressMethod()) + if (method.IsArrayAddressMethod()) { return new ScannedMethodNode(((ArrayType)method.OwningType).GetArrayMethod(ArrayMethodKind.AddressWithHiddenArg)); } diff --git a/src/coreclr/tools/aot/ILCompiler.RyuJit/Compiler/DependencyAnalysis/RyuJitNodeFactory.cs b/src/coreclr/tools/aot/ILCompiler.RyuJit/Compiler/DependencyAnalysis/RyuJitNodeFactory.cs index fd1abaeba8989c..0e5574b7dd652c 100644 --- a/src/coreclr/tools/aot/ILCompiler.RyuJit/Compiler/DependencyAnalysis/RyuJitNodeFactory.cs +++ b/src/coreclr/tools/aot/ILCompiler.RyuJit/Compiler/DependencyAnalysis/RyuJitNodeFactory.cs @@ -20,11 +20,7 @@ protected override IMethodNode CreateMethodEntrypointNode(MethodDesc method) { if (method.IsInternalCall) { - if (method.IsExplicitContinuationAsyncMethod()) - { - return MethodEntrypoint(method.GetExplicitContinuationAsyncMethodTarget()); - } - else if (method.IsArrayAddressMethod()) + if (method.IsArrayAddressMethod()) { return MethodEntrypoint(((ArrayType)method.OwningType).GetArrayMethod(ArrayMethodKind.AddressWithHiddenArg)); } From 892ab7a9a711526c73250f5d000bd3d504ee23d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Strehovsk=C3=BD?= Date: Tue, 25 Nov 2025 14:19:59 -0800 Subject: [PATCH 3/3] Refactor async call handling in lower.cpp Removed comments about marking calls as async for NativeAOT and added an assertion to ensure the call is async. --- src/coreclr/jit/lower.cpp | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/src/coreclr/jit/lower.cpp b/src/coreclr/jit/lower.cpp index 6c096d3d3c5cb9..3bbad6a8b81367 100644 --- a/src/coreclr/jit/lower.cpp +++ b/src/coreclr/jit/lower.cpp @@ -5864,12 +5864,6 @@ GenTree* Lowering::LowerAsyncContinuation(GenTree* asyncCont) // 2. In the async transformation, ASYNC_CONTINUATION nodes are inserted // after calls to async calls. // - // In the former case, for NativeAOT nothing has marked the previous call - // as an "async" method. We need to do that here to ensure that the backend - // knows that the call has a non-standard calling convention that returns - // an additional GC ref. This requires additional GC tracking that we would - // otherwise not get. - // GenTree* node = asyncCont; while (true) { @@ -5878,13 +5872,7 @@ GenTree* Lowering::LowerAsyncContinuation(GenTree* asyncCont) if (node->IsCall()) { - if (!node->AsCall()->IsAsync()) - { - JITDUMP("Marking the call [%06u] before async continuation [%06u] as an async call\n", - Compiler::dspTreeID(node), Compiler::dspTreeID(asyncCont)); - node->AsCall()->SetIsAsync(new (comp, CMK_Async) AsyncCallInfo); - } - + assert(node->AsCall()->IsAsync()); BlockRange().Remove(asyncCont); BlockRange().InsertAfter(node, asyncCont); break;