From 93153b6b2b5f25f50291a35dbe5da0af83ea4f4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20K=C3=B6plinger?= Date: Fri, 27 Nov 2026 13:10:28 +0100 Subject: [PATCH] Fix crossgen2 IL body fixup for async thunks over out-of-bubble generics When a Task-returning runtime-async method's thunk is instantiated over an out-of-version-bubble type (e.g. CoreLib's ValueTuple), crossgen2 emitted a Check_IL_Body fixup for the thunk itself and hit the assert in the ILBodyFixupSignature constructor, since the thunk has a compiler-generated IL body with no IL header at runtime. Use the method's async variant for the fixup instead. Both variants hash the same metadata IL and impl flags, so the check still fails if the method body or its async-ness changes. Also stop skipping such thunks when encoding cross-module inliners, and assert the invariants that thunks always return Task/ValueTask and never reach CreateCrossModuleInlineableTokensForILBody. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../TestCases/R2RTestSuites.cs | 50 +++++++++++++++++++ .../AsyncThunkOverCoreLibGeneric.cs | 22 ++++++++ .../ReadyToRun/ILBodyFixupSignature.cs | 21 +++++++- .../ReadyToRun/InliningInfoNode.cs | 4 +- .../IL/ReadyToRunILProvider.cs | 5 ++ .../JitInterface/CorInfoImpl.ReadyToRun.cs | 4 +- 6 files changed, 101 insertions(+), 5 deletions(-) create mode 100644 src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/RuntimeAsync/AsyncThunkOverCoreLibGeneric.cs diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/R2RTestSuites.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/R2RTestSuites.cs index b0e5c75e576553..d76222ac438bff 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/R2RTestSuites.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/R2RTestSuites.cs @@ -3092,6 +3092,56 @@ static void Validate(ReadyToRunReader reader) } } + /// + /// The Task-returning thunk of an in-module runtime-async method has no IL body at runtime, so a + /// cross-module compiled instantiation of it must use the async variant for its own IL body fixup. + /// + [ConditionalFact(typeof(TestPaths), nameof(TestPaths.IsNotWasmTarget))] + public void RuntimeAsyncThunkILBodyFixup() + { + var asm = new CompiledAssembly + { + AssemblyName = nameof(RuntimeAsyncThunkILBodyFixup), + SourceResourceNames = + [ + "RuntimeAsync/AsyncThunkOverCoreLibGeneric.cs", + ], + Features = { RuntimeAsyncFeature }, + }; + + new R2RTestRunner(_output).Run(new R2RTestCase( + nameof(RuntimeAsyncThunkILBodyFixup), + [ + new(nameof(RuntimeAsyncThunkILBodyFixup), [new CrossgenAssembly(asm)]) + { + Options = [Crossgen2Option.Optimize], + AdditionalArgs = ["--opt-cross-module", "*"], + Validate = Validate, + }, + ])); + + static void Validate(ReadyToRunReader reader) + { + var formattingOptions = new SignatureFormattingOptions(); + List thunks = R2RAssert.GetAllMethods(reader) + .Where(m => m.Name == "PassThrough" + && m.SignatureString.Contains("ValueTuple", StringComparison.Ordinal) + && !m.SignatureString.Contains("[ASYNC]", StringComparison.Ordinal) + && !m.SignatureString.Contains("[RESUME]", StringComparison.Ordinal)) + .ToList(); + Assert.True(thunks.Count == 1, + $"Expected one Task-returning PassThrough over ValueTuple, found: [{string.Join(", ", thunks.Select(m => m.SignatureString))}]"); + + List ilBodyFixups = (thunks[0].Fixups ?? Array.Empty()) + .Where(f => f.Signature?.FixupKind == ReadyToRunFixupKind.Check_IL_Body) + .Select(f => f.Signature.ToString(formattingOptions)) + .Where(s => s.Contains("AsyncThunkOverCoreLibGeneric.PassThrough", StringComparison.Ordinal)) + .ToList(); + Assert.True(ilBodyFixups.Count == 1 && ilBodyFixups[0].StartsWith("[ASYNC] ", StringComparison.Ordinal), + $"Expected one Check_IL_Body fixup for the async variant of PassThrough, found: [{string.Join(", ", ilBodyFixups)}]"); + } + } + /// /// Validates that ResumptionStubEntryPoint fixups are deduplicated for a method: /// even with multiple suspension points and forced compilation retries (via diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/RuntimeAsync/AsyncThunkOverCoreLibGeneric.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/RuntimeAsync/AsyncThunkOverCoreLibGeneric.cs new file mode 100644 index 00000000000000..1ffc7a7ad61edb --- /dev/null +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/RuntimeAsync/AsyncThunkOverCoreLibGeneric.cs @@ -0,0 +1,22 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +// Test: Task-returning thunk of an in-module runtime-async generic method +// instantiated over a shared System.Private.CoreLib generic struct. +using System; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +public static class AsyncThunkOverCoreLibGeneric +{ + [MethodImpl(MethodImplOptions.NoInlining)] + public static async Task PassThrough(T value) + { + await Task.Yield(); + return value; + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public static Task> CallPassThrough(object first, object second) + => PassThrough((first, second)); +} diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ILBodyFixupSignature.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ILBodyFixupSignature.cs index 8fdae301435767..97dd864ed84d61 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ILBodyFixupSignature.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/ILBodyFixupSignature.cs @@ -54,10 +54,29 @@ public ILBodyFixupSignature(ReadyToRunFixupKind fixupKind, MethodDesc signatureM /// /// Returns the method a compiled method's own IL body fixup is created for, or null if the compiled method cannot have one. /// + /// + /// A compiler-generated async thunk has no IL header at runtime, so it is checked using the other variant of + /// the same method. Both variants hash the same metadata IL and impl flags, so the check still fails if the + /// method's body or async-ness changes. + /// public static MethodDesc GetSignatureMethodForCompiledMethod(MethodDesc compiledMethod) { MethodDesc typicalDef = compiledMethod.GetTypicalMethodDefinition(); - return typicalDef is EcmaMethod or AsyncMethodVariant ? typicalDef : null; + if (typicalDef is not (EcmaMethod or AsyncMethodVariant)) + return null; + + if (typicalDef.IsCompilerGeneratedILBodyForAsync()) + { + if (typicalDef is AsyncMethodVariant) + return typicalDef.GetPrimaryMethodDesc(); + + // Only Task-returning runtime-async methods have a thunk and an async variant. The others only exist in + // CoreLib and are [BypassReadyToRun]. + Debug.Assert(typicalDef.Signature.ReturnsTaskOrValueTask()); + return typicalDef.GetAsyncVariant(); + } + + return typicalDef; } public override int ClassCode => 308579267; diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/InliningInfoNode.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/InliningInfoNode.cs index 8ce396d50f9359..0625bf40b25474 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/InliningInfoNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/InliningInfoNode.cs @@ -89,8 +89,8 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { inlinerIdentity = ILBodyFixupSignature.GetSignatureMethodForCompiledMethod(inliner); - // Cross-module inliners are encoded by their own Check_IL_Body import. Thunks and stubs don't have one. - if (inlinerIdentity is null || inlinerIdentity.IsCompilerGeneratedILBodyForAsync()) + // Cross-module inliners are encoded by their own Check_IL_Body import. Stubs don't have one. + if (inlinerIdentity is null) continue; } else diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/IL/ReadyToRunILProvider.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/IL/ReadyToRunILProvider.cs index 145f0cc1a898ba..a68150c5520162 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/IL/ReadyToRunILProvider.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/IL/ReadyToRunILProvider.cs @@ -168,6 +168,11 @@ public void CreateCrossModuleInlineableTokensForILBody(MethodDesc method) Debug.Assert(!_compilationModuleGroup.VersionsWithMethodBody(method) && _compilationModuleGroup.CrossModuleInlineable(method)); + // The wrapped IL is the metadata IL, which for a Task-returning runtime-async method is the body of its + // async variant, not of its thunk. Thunks are never compiled outside the version bubble or inlined + // because their IL has a catch clause, so they must never get here. + Debug.Assert(!NeedsTaskReturningThunk(method)); + if (!wrappedMethodIL.Initialize(_manifestMutableModule, EcmaMethodIL.Create((EcmaMethod)method.GetPrimaryMethodDesc().GetTypicalMethodDefinition()))) { // If we could not initialize the wrapped method IL, we should store a null. diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs index 7d6bd89fd29136..d569a489402a9e 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs @@ -869,14 +869,14 @@ private ManagedHelperProbeResult CompileMethod(MethodWithGCInfo methodCodeNodeNe } var typicalDef = MethodBeingCompiled.GetTypicalMethodDefinition(); - if (ILBodyFixupSignature.GetSignatureMethodForCompiledMethod(MethodBeingCompiled) is not null) + if (ILBodyFixupSignature.GetSignatureMethodForCompiledMethod(MethodBeingCompiled) is MethodDesc ilBodySignatureMethod) { var ecmaMethod = (EcmaMethod)typicalDef.GetPrimaryMethodDesc(); if ((methodIL.GetMethodILScopeDefinition() is IEcmaMethodIL && _compilation.SymbolNodeFactory.VerifyTypeAndFieldLayout && ecmaMethod.Module == typicalDef.Context.SystemModule) || (!_compilation.NodeFactory.CompilationModuleGroup.VersionsWithMethodBody(MethodBeingCompiled) && _compilation.NodeFactory.CompilationModuleGroup.CrossModuleInlineable(MethodBeingCompiled))) { - ISymbolNode ilBodyNode = _compilation.SymbolNodeFactory.CheckILBodyFixupSignature(typicalDef); + ISymbolNode ilBodyNode = _compilation.SymbolNodeFactory.CheckILBodyFixupSignature(ilBodySignatureMethod); AddPrecodeFixup(ilBodyNode); }