Skip to content

Fix crossgen2 IL body fixup for async thunks over out-of-bubble generics - #138405

Open
akoeplinger wants to merge 1 commit into
dotnet:mainfrom
akoeplinger:akoeplinger-crossgen2-async-fixups
Open

akoeplinger wants to merge 1 commit into
dotnet:mainfrom
akoeplinger:akoeplinger-crossgen2-async-fixups

Conversation

@akoeplinger

Copy link
Copy Markdown
Member

Enabling runtime-async for packable (OOB) shared-framework libraries in #138389 makes crossgen2 hit this assert in the browser-wasm build (build 1701767):

Assert failure: !signatureMethod.IsCompilerGeneratedILBodyForAsync()
   at ILCompiler.DependencyAnalysis.ReadyToRun.ILBodyFixupSignature..ctor(...)
   at Internal.JitInterface.CorInfoImpl.CompileMethod(...)

Cause

A Task-returning runtime-async method's thunk is compiled outside the version bubble when it's instantiated over an out-of-bubble CoreLib type such as ValueTuple<__Canon, __Canon>. Examples:

  • AsyncEnumerable.<ToDictionaryAsync>g__Impl|206_0
  • HttpClientJsonExtensions.<FromJsonAsyncCore>g__Core|12_0
  • DnsResolver.ResolveWithTelemetry

CorInfoImpl.CompileMethod then emits a Check_IL_Body fixup for the thunk itself. That's wrong: the thunk's IL is generated by the compiler, so there's no IL header to check at runtime.

Fix

  • ILBodyFixupSignature.GetSignatureMethodForCompiledMethod maps a compiler-generated thunk to its [ASYNC] variant. Both variants hash the same metadata IL and impl flags, so the check still fails if the method's body or its async-ness changes.
  • CorInfoImpl.CompileMethod uses that method for the fixup, and InliningInfoNode no longer skips such thunks when encoding cross-module inliners.
  • Debug asserts encode two invariants:
    • Thunks always return Task/ValueTask. Non-Task miAsync methods only exist in CoreLib and are [BypassReadyToRun].
    • Thunks never reach CreateCrossModuleInlineableTokensForILBody. Their catch clause keeps them from being compiled outside the bubble or inlined.

NativeAOT isn't affected; it has no IL body fixups.

Validation

  • New R2R test RuntimeAsyncThunkILBodyFixup. The full ILCompiler.ReadyToRun.Tests suite passes: 417 passed, 0 failed.
  • With Opt-in into runtime async for all .NET 12+ projects #138389's opt-in applied locally, I compiled all 180 shared-framework assemblies with -O -m StandardOptimizationData.mibc --opt-cross-module:* for osx-arm64 and browser-wasm:
    • Before the fix, the exact CI assert reproduces in System.Linq.AsyncEnumerable, System.Net.Http.Json and System.Net.NameResolution on both targets.
    • After the fix, all 180 compile on both targets.
  • CoreLib compiled with --verify-type-and-field-layout: no assert.
  • Ran the AsyncEnumerable, Http.Json and NameResolution library tests on an osx-arm64 testhost using the new R2R images: all pass, and the images load. A small app confirmed the new [ASYNC] fixups are accepted at runtime: the affected AsyncEnumerable and Http.Json methods run from the precompiled code instead of being JIT-compiled.
  • Not validated: running these images in an actual browser-wasm runtime.

Note

This PR description was generated with GitHub Copilot.

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>
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
12 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/crossgen-contrib
See info in area-owners.md if you want to be subscribed.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

The fix changes compiler/runtime IL-body import identities, but browser-wasm remains unvalidated and excluded from the regression test, requiring maintainer judgment on whether native validation is sufficient.

No open issues 🎉

What changed in this PR

Fixes crossgen2 IL body checks for runtime-async thunks instantiated over generic types outside the version bubble, supporting the broader runtime-async opt-in in #138389.

Changes:

  • Maps compiler-generated async thunks to their metadata-backed method variants for IL body fixups.
  • Updates cross-module inliner tracking and adds assertions documenting thunk restrictions.
  • Adds a regression test verifying that a thunk over a CoreLib generic struct uses an [ASYNC] fixup.
File Description
src/​coreclr/​tools/​aot/​ILCompiler.ReadyToRun/​JitInterface/​CorInfoImpl.ReadyToRun.cs Uses the mapped method when creating IL body fixups.
src/​coreclr/​tools/​aot/​ILCompiler.ReadyToRun/​IL/​ReadyToRunILProvider.cs Asserts that thunks do not enter cross-module token generation.
src/​coreclr/​tools/​aot/​ILCompiler.ReadyToRun/​Compiler/​DependencyAnalysis/​ReadyToRun/​InliningInfoNode.cs Includes mapped async thunks in cross-module inliner tracking.
src/​coreclr/​tools/​aot/​ILCompiler.ReadyToRun/​Compiler/​DependencyAnalysis/​ReadyToRun/​ILBodyFixupSignature.cs Maps async thunks to metadata-backed variants and documents the check.
src/​coreclr/​tools/​aot/​ILCompiler.ReadyToRun.Tests/​TestCases/​RuntimeAsync/​AsyncThunkOverCoreLibGeneric.cs Adds the generic runtime-async regression scenario.
src/​coreclr/​tools/​aot/​ILCompiler.ReadyToRun.Tests/​TestCases/​R2RTestSuites.cs Verifies the compiled thunk has the expected async-variant fixup.

Review effort: Balanced

@jkotas

jkotas commented Nov 27, 2026

Copy link
Copy Markdown
Member

/azp run runtime-coreclr crossgen2

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).

@jkotas

jkotas commented Nov 29, 2026

Copy link
Copy Markdown
Member

/azp run runtime-coreclr crossgen2

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).

kubaflo added a commit to dotnet/maui that referenced this pull request Nov 29, 2026
<!-- copilot-assessment:v1 -->
### Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: `8dc4c8067df4d45478b93d52eab85aab0febce56`

| Dimension | Assessment | Rationale |
|---|---|---|
| Change confidence | 8/10 | ↑ The full MAUI package solution rebuilt
and packed at the assessed revision.<br>↑ MSBuild evaluation confirmed
net12 enables `runtime-async=on`, net11/netstandard remain unchanged,
and an explicit `runtime-async=off` is preserved.<br>↑ The Android
sample-content benchmark installed and launched with the feature; APK
size fell 0.48%.<br>↓ The .NET 12 upstream default-on rollout is still
open, and broad physical-device/CI runtime validation remains pending. |
<!-- /copilot-assessment -->

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.

### Description of Change

Enables [Runtime Async
V2](https://learn.microsoft.com/dotnet/core/whats-new/dotnet-11/runtime#runtime-async)
for the current .NET 12 target in both places MAUI compilation is
configured:

- In-tree MAUI projects receive the compiler feature in
`Directory.Build.targets`.
- The packaged MAUI SDK applies the same default to net12 consumer
projects through `BundledVersions.targets`.

The setting is idempotent and scoped to net12. It leaves net11 and .NET
Standard assets unchanged and does not replace an explicit
`runtime-async` selection, so a project can opt out with
`Features=runtime-async=off`.

#### What Runtime Async changes

Today, C# normally implements an `async` method by generating a
state-machine type and `MoveNext` method. Runtime Async instead marks
eligible methods with the runtime async metadata contract and lets the
runtime/JIT track suspension and resumption. The [draft ECMA-335
specification](https://github.com/dotnet/runtime/blob/main/docs/design/specs/runtime-async.md),
originally introduced by
[dotnet/runtime#104063](dotnet/runtime#104063),
documents the `MethodImplOptions.Async` method contract and
`AsyncHelpers` await operations.

The practical benefits are narrower, cleaner live stack traces/debugger
views, fewer compiler-generated async state-machine types, and
additional JIT opportunities such as directly calling runtime-async
variants and avoiding intermediate task/continuation work. The [.NET 11
performance deep
dive](https://devblogs.microsoft.com/dotnet/performance-improvements-in-net-11/#runtime-async)
covers those optimizations and also notes the current boundaries:
Runtime Async supports `Task`, `Task<T>`, `ValueTask`, and
`ValueTask<T>`, while `async void`, async iterators, and arbitrary
custom task-like builders continue to use the traditional
transformation.

Runtime Async supports both ReadyToRun and NativeAOT in .NET 11. The
corresponding upstream R2R and NativeAOT tracking issues are
[dotnet/runtime#115098](dotnet/runtime#115098)
and
[dotnet/runtime#124101](dotnet/runtime#124101);
the latter is complete and the former is closed with its implementation
work substantially complete.

#### .NET rollout and why .NET 12

The [upstream Runtime Async tracking
issue](dotnet/runtime#109632) is now on the
**.NET 12.0 milestone**. Its current status distinguishes the two stages
of rollout:

1. **.NET 11:** Runtime Async is available without preview-only
`EnablePreviewFeatures`; however, application code still opts in with
`runtime-async=on`. The runtime libraries/shared framework are already
compiled with it. See the [Microsoft Learn runtime
guide](https://learn.microsoft.com/dotnet/core/whats-new/dotnet-11/runtime#runtime-async)
and [.NET 11
overview](https://learn.microsoft.com/dotnet/core/whats-new/dotnet-11/overview).
2. **.NET 12:** This is the intended defaulting point. In [the tracking
issue's October 2026
guidance](dotnet/runtime#109632 (comment)),
a runtime maintainer states that Runtime Async is opt-in in .NET 11
because Mono does not support it, but in .NET 12 Mono goes away and
Runtime Async becomes the default.
[dotnet/runtime#134397](dotnet/runtime#134397)
tracks removal of the .NET 12 Mono runtime packs and already links the
related MAUI cleanup work.

There is a concrete upstream rollout PR: [dotnet/runtime#138389, “Opt-in
into runtime async for all .NET 12+
projects”](dotnet/runtime#138389). As of
2026-11-29 it is **open**, with approvals but not yet merged; a reviewer
notes that this repository-level opt-in should be removable once the
.NET SDK defaults it on. The PR also exposed a crossgen2 issue now being
addressed in
[dotnet/runtime#138405](dotnet/runtime#138405).

Earlier rollout work already auto-enabled Runtime Async for supported
shared-framework net11+ sources and removed the runtime configuration
knob in
[dotnet/runtime#125406](dotnet/runtime#125406),
with a corresponding .NET 11 preview backport in
[dotnet/runtime#126343](dotnet/runtime#126343).
This MAUI PR therefore targets the same transition for MAUI's .NET 12
source and packages without changing net11 or netstandard compatibility.

#### Android sample-content benchmark

The generated `maui --sample-content` app was compared in Release for
`android-arm64` with CoreCLR, ReadyToRun, and `TrimMode=partial`:

| Metric | Default | Runtime Async | Delta |
|---|---:|---:|---:|
| Signed APK | 21,319,306 B | 21,216,906 B | **−102,400 B (−0.48%)** |
| Signed AAB | 20,619,137 B | 20,517,222 B | **−101,915 B (−0.49%)** |
| Cold-process startup median | 766.0 ms | 780.5 ms | **+14.5 ms
(+1.9%)** |

The package reduction came entirely from `libassembly-store.so`. Startup
used 20 `am start -W -S` launches per variant across two speed-compiled,
warmed blocks on an ARM64 API 35 emulator. IQRs overlapped (710.5–819.25
ms vs. 747.75–825.5 ms) and paired block deltas had opposite signs, so
there was no demonstrated startup improvement or regression.

#### Validation

- `./.dotnet/dotnet msbuild eng/Microsoft.Maui.Packages-mac.slnf
-restore '-t:Rebuild;Pack' -p:Configuration=Release -p:Pack=true -m
-v:minimal` — **passed** at the assessed revision.
- `./.dotnet/dotnet build src/Core/src/Core.csproj -c Release -f
net12.0-android37.0 -t:Rebuild --no-restore -v:minimal` — **passed**.
- MSBuild `Features` evaluation — **net12 defaults to
`runtime-async=on`**, `runtime-async=off` is preserved, and
net11/netstandard remain unchanged.

### Issues Fixed

N/A — no issue was provided.

### Let AI finish this PR

- [ ] **Let the MAUI agent address review feedback and fix remaining
issues on this PR.** Maintainers still decide whether it is merged. For
PRs from forks, the agent opens a follow-up PR that keeps your commits.

<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants