Skip to content

[r2r][wasm] Use the VirtualEntry dynamic helper cell for LDVIRTFTN (DelayLoad_Helper_Obj) - #136774

Closed
lewing wants to merge 3 commits into
dotnet:mainfrom
lewing:lewing-wasm-delayload-helper-obj-thunks
Closed

lewing wants to merge 3 commits into
dotnet:mainfrom
lewing:lewing-wasm-delayload-helper-obj-thunks

Conversation

@lewing

@lewing lewing commented Nov 1, 2026

Copy link
Copy Markdown
Member

Important

Depends on #136769: the first two commits are that PR. Only the last commit ([r2r][wasm] Use the VirtualEntry dynamic helper cell for LDVIRTFTN) is new here. Opened as a draft for design feedback from the Wasm and ReadyToRun owners.

Summary

On CoreCLR WebAssembly, ReadyToRun code now uses the VirtualEntry dynamic helper cell (CORINFO_HELP_READYTORUN_VIRTUAL_FUNC_PTR) for LDVIRTFTN, as every other ReadyToRun target does. Today it calls CORINFO_HELP_VIRTUAL_FUNC_PTR(obj, methodHandle, classHandle) instead. To support this, the change implements DelayLoad_Helper_Obj, which was a PORTABILITY_ASSERT stub.

Since #133146, Wasm routes all interface calls, array interface methods and generic virtual methods through LDVIRTFTN. So this path covers every interface dispatch in Wasm R2R code.

Background

Because nothing referenced the cell, its VirtualEntry dependencies were lost. #136769 adds them explicitly. With the cell in use, the cell's MethodFixupSignature carries the dependencies again, and this change removes that explicit call.

Design

Layer Change
JIT (impImportLdvirtftn) Remove the Wasm carve-out. The existing Wasm call shape is reused: this as WellKnownArg::ThisPointer, with GTF_CALL_NULLCHECK, because Wasm has no hardware null faults. Shared code whose exact context needs a runtime lookup still uses CORINFO_HELP_VIRTUAL_FUNC_PTR, as on other targets.
crossgen2 (WasmImportThunkPortableEntrypoint) A DelayLoad_Helper_Obj + VirtualEntry import is called as (sp, obj, pe) -> nint. It uses the fixed signature already used for generic lookups, not the target method's signature. The check keys on the helper ID: #133146's [VSD] DelayLoad_MethodCall imports also carry VirtualEntry signatures and must keep the target signature.
crossgen2 (CorInfoImpl.ReadyToRun.cs) Drop #136769's explicit AddVirtualEntryDependencies call from the Wasm LDVIRTFTN lowering. The helper itself stays, because MethodFixupSignature uses it.
Runtime (DelayLoad_Helper_Obj) Same naked wrapper as DelayLoad_Helper, but passes DynamicHelperFrameFlags_ObjectArg so the object in the transition block is GC-reported. When DynamicHelperWorker returns NULL, it has stored the result in argument slot 0. This always happens for reliable fixups in _DEBUG, and after a swallowed exception. The wrapper then returns a static portable entrypoint for DynamicHelper_ReturnFirstArg, so the generic import thunk needs no special case.
Runtime (DynamicHelperFixup) VirtualEntry is enabled on Wasm. Wasm cannot generate code at runtime, so instead of CreateHelperWithArg/CreateReturnConst the cell resolves to loader-heap data {functionIndex, target, classHandle, methodHandle}. The first word selects a precompiled .S stub with signature (sp, obj, pe) -> nint.
Runtime (.S stubs) DynamicHelper_VirtualEntry_CallHelper calls VirtualDispatchHelpers.VirtualFunctionPointer_Dynamic(obj, ref args), with the args stored inline in the data block. DynamicHelper_VirtualEntry_ReturnConst handles non-vtable targets. Both targets are made callable from R2R code with EnsurePortableEntryPointIsCallableFromR2R.

Measurements

Environment: Node 26.4 on Apple Silicon, Release runtime. For the A/B, a temporary JIT knob (removed before commit) toggled only the LDVIRTFTN lowering. CoreLib and a microbenchmark were crossgen'd with the same crossgen2 and run on the same runtime binary. The receiver changes every iteration; otherwise both paths are hoisted out of the loop. Values are ns per iteration (median of 3 processes, best of 7 runs each).

Case Helper (#136769) Cell (this PR) Δ
Interface, monomorphic 5.07 6.63 +1.56
Interface, 2 types 7.42 9.47 +2.05
GVM G<int> 4.30 6.19 +1.89
GVM G<string> 41.43 45.63 +4.20
IList<int> over int[] 5.44 7.19 +1.75
ldvirtftn + delegate ctor 20.59 21.90 +1.31
Class virtual (control, unaffected) 3.89 3.99 +0.10
  • Steady state: the cell path is about 1.5–2 ns slower per dispatch. A resolved cell adds one call_indirect hop through the stub before the same managed GenericCache lookup (VirtualFunctionPointer_Dynamic instead of VirtualFunctionPointer). A CPU profile confirms the stub and VirtualFunctionPointer_Dynamic run in the cell build.
  • Cold first call: one method with 400 distinct interface callsites, median of 10 processes: 4.11 ms (cell) vs 4.15 ms (helper).
  • Callsite code: 1 cell load, a null check and a 3-argument call_indirect, instead of 3 cell loads and a 5-argument call_indirect.
  • Size:
  • Compiled methods: with the explicit dependency call removed (this PR's actual state), CoreLib compiles 34,496 methods versus 34,523 with [r2r][wasm] Add VirtualEntry dependencies for every LDVIRTFTN lowering #136769 alone. The 27 methods only [r2r][wasm] Add VirtualEntry dependencies for every LDVIRTFTN lowering #136769 compiles include SZArrayHelper.GetEnumerator<T> instantiations, List<KeyValuePair<__Canon,__Canon>> enumerator members and ValueTuple IValueTupleInternal.ToStringEnd implementations.

Validation

  • ILCompiler.ReadyToRun.Tests, full suites:
    • browser-wasm (dotnet build <csproj> -c Release -p:TargetOS=browser -p:TargetArchitecture=wasm, then dotnet test): 235 passed, 40 skipped, 0 failed.
    • osx-arm64 (dotnet build <csproj> -c Release, then dotnet test): 257 passed, 17 skipped, 0 failed.
    • On browser-wasm this includes [r2r][wasm] Add VirtualEntry dependencies for every LDVIRTFTN lowering #136769's WasmVirtualMethodGenericsNonGVM, WasmVirtualMethodGenericsGVM and VirtualMethodGenericsArrayInterfaceMethods.
  • Release browser runtime:
    • CoreLib crossgen'd with 714 VirtualEntry cells; the microbenchmark and a null-receiver test pass under corerun on Node.
    • Results are identical to the helper build.
    • Null receivers throw NullReferenceException for interface, GVM and IList<T>-over-array calls.
  • Debug browser runtime: CoreLib built by the Debug build. This forces every first call through the DynamicHelper_ReturnFirstArg path. The same tests pass.
  • R2R modes exercised: per-assembly R2R for CoreLib and the test apps, with --opt-cross-module:* and --target-allows-runtime-code-generation:false.
  • Not exercised:
    • composite images;
    • the ReturnConst (non-vtable) stub;
    • the runtime test suites.

Open questions

  1. Is ~1.5–2 ns per interface dispatch acceptable in exchange for:

    • parity with other R2R targets;
    • fewer per-callsite handle fixups;
    • smaller CoreLib (raw);
    • no explicit dependency workaround?

    Ways to recover the cost:

    • Have the stub tail-call the managed helper (return_call_indirect). The native runtime build doesn't enable Wasm tail calls today.
    • Let the JIT call VirtualFunctionPointer_Dynamic directly with the args pointer from the resolved cell. This needs a cell ABI change.
    • Add an interface dispatch cache on Wasm.
  2. Should DelayLoad_Helper_ObjObj (DelegateCtor) and the other object-taking fixups (IsInstanceOf, ChkCast) move to the same scheme here or separately?

  3. Compiler::getVirtMethodPointerTree (tail-call-via-helper) still embeds the type handle; see [browser][coreCLR] R2R: take the method-keyed virtual-dispatch fast path on wasm (replace the #130585 workaround) #132412, item 4.

Note

This PR description and the change were generated with GitHub Copilot and reviewed before posting.

lewing and others added 3 commits October 31, 2026 18:54
Wasm lowers every interface call to CORINFO_VIRTUALCALL_LDVIRTFTN, which
emits a MethodHandle fixup rather than a VirtualEntry dispatch cell.
VirtualMethodUse was only recorded for VirtualEntry fixups, so the
conditional discovery in InheritedVirtualMethodsNode and
ArrayInterfaceMethodsNode never fired on wasm. Interface implementations
on generic value-type instantiations (e.g. SZArrayHelper.get_Count<S>,
List<S>, Dictionary collections and enumerators) were left to the
interpreter, even in composite builds.

Mark the slot as used in the wasm interface LDVIRTFTN path. Extend the
wasm NonGVM test to assert the interface implementations it already
asserts on other targets, and add a composite test covering
SZArrayHelper instantiations.

Co-authored-by: Copilot App <[email protected]>
The Wasm JIT lowers CORINFO_VIRTUALCALL_LDVIRTFTN through
CORINFO_HELP_VIRTUAL_FUNC_PTR instead of the VirtualEntry dynamic helper
cell, because DelayLoad_Helper_Obj thunks are not implemented on Wasm.
The cell's MethodFixupSignature is what adds the virtual dispatch
dependencies, so on Wasm interface calls, generic virtual method calls
and delegates created with ldvirtftn lost them, and the implementations
were left to the interpreter.

Extract those dependencies into
MethodFixupSignature.AddVirtualEntryDependencies and apply them at the
LDVIRTFTN lowering on Wasm for callers that do not need a runtime lookup,
matching the call sites that create a VirtualEntry signature on other
targets. This replaces the interface-only VirtualMethodUse from the
previous commit, which also registered shared callers.

Share the compiled-implementation assertions between the Wasm and
non-Wasm VirtualMethodGenerics tests, and add delegate ldvirtftn cases.

Co-authored-by: Copilot App <[email protected]>
Implement DelayLoad_Helper_Obj for CoreCLR WebAssembly so the JIT can use
CORINFO_HELP_READYTORUN_VIRTUAL_FUNC_PTR (the VirtualEntry dynamic helper
cell) like other ReadyToRun targets, instead of CORINFO_HELP_VIRTUAL_FUNC_PTR.

Runtime: DelayLoad_Helper_Obj reports the object argument to the GC and,
when DynamicHelperWorker leaves its result in the first argument slot,
returns a portable entrypoint that hands back that argument. VirtualEntry
fixups resolve to loader-heap data whose first word indexes a precompiled
(sp, object, pe) -> nint stub that either calls
VirtualDispatchHelpers.VirtualFunctionPointer_Dynamic or returns a constant.

crossgen2: VirtualEntry cells imported through DelayLoad_Helper_Obj use the
fixed (sp, object, pe) -> nint thunk signature. The cell carries the
VirtualEntry dependencies, so the explicit dependency call added for the
Wasm LDVIRTFTN lowering is removed.

JIT: remove the Wasm carve-out in impImportLdvirtftn.

Co-authored-by: Copilot App <[email protected]>
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 5 pipeline(s).
10 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.

@lewing

lewing commented Nov 2, 2026

Copy link
Copy Markdown
Member Author

Closing. Using the VirtualEntry dynamic helper cell on Wasm adds about 1.5–2 ns to each virtual function pointer lookup. #136769 now gets the cell's dependencies without the cell: the JIT reports each CORINFO_HELP_VIRTUAL_FUNC_PTR lookup that survives to lowering through a JIT-EE notification (see #136769 (comment)).

Note

This comment was generated with GitHub Copilot.

@lewing lewing closed this Nov 2, 2026
lewing added a commit that referenced this pull request Nov 6, 2026
#136769)

On Wasm, crossgen2 never compiled implementations that are reachable
only through virtual dispatch from LDVIRTFTN call sites, so they ran in
the interpreter.

### Cause

For `CORINFO_VIRTUALCALL_LDVIRTFTN`, crossgen2 hands the JIT a dynamic
helper cell built from a `VirtualEntry` `MethodFixupSignature`. That
signature carries the virtual dispatch dependencies:

- `VirtualMethodUse`, which drives `InheritedVirtualMethodsNode` and
`ArrayInterfaceMethodsNode`;
- `GVMDependencies`;
- the cross-module compile dependency.

The Wasm JIT doesn't use the cell. It calls
`CORINFO_HELP_VIRTUAL_FUNC_PTR` with a method handle instead
(`impImportLdvirtftn`), so the dependencies were never added. Wasm
lowers every interface call through LDVIRTFTN, so this affected:

- interface calls, e.g. `SZArrayHelper` methods for
`IList<T>`/`IReadOnlyCollection<T>` over value-type arrays, and
`List<T>`/`Dictionary` collections and enumerators;
- generic virtual method calls;
- delegates created with `ldvirtftn`.

### Change

- Extract the `VirtualEntry` dependency rules into
`MethodFixupSignature.AddVirtualEntryDependencies`. Non-Wasm behavior is
unchanged.
- Add a JIT-EE notification,
`recordWasmVirtualFunctionPointerLookup(CORINFO_METHOD_HANDLE)`, modeled
on `recordWasmManagedCallSig`.
- `Lowering::LowerCall` reports each `CORINFO_HELP_VIRTUAL_FUNC_PTR`
call that survives to lowering, using the compile-time handle of its
`RuntimeMethodHandle` argument.
- crossgen2 applies `AddVirtualEntryDependencies` to the reported
method, so lookups the JIT removes don't add dependencies.
  - The notification is a no-op in the VM, NativeAOT and SuperPMI.

Using the cell itself (by implementing `DelayLoad_Helper_Obj` on Wasm)
was prototyped in #136774 and rejected: each lookup costs ~1.5–2 ns
more.

No image-format change.

### Testing

R2R modes exercised: per-assembly, and composite with CoreLib as an
unrooted input. Large version bubble and cross-module inlining were not
exercised.

- The Wasm `VirtualMethodGenerics` NonGVM and GVM tests now assert the
same compiled implementations as the non-Wasm tests; the assertions are
shared between them. Both tests failed before this change.
- New delegate `ldvirtftn` cases (Test12, Test13).
- New composite test covering `SZArrayHelper` instantiations, on all
targets.
- `ILCompiler.ReadyToRun.Tests` passes on browser-wasm and osx-arm64.

### Size and performance

Browser `System.Private.CoreLib.wasm`, built with the standard build
flags including MIBC, on the same base:

| | Raw |
|---|---|
| Without this change | 18,396,756 |
| With this change | 18,747,603 (+350.8 KB, +1.9%) |

Brotli grows by about 25–31 KB (+0.7–0.9%). Brotli-11 size varies by
about ±3 KB between rebuilds of identical sources, so the range is
approximate.

Microbenchmark: interface calls from R2R code over `int[]`, run with
`corerun` on Node/V8.

| Call | Before | After |
|---|---|---|
| `IReadOnlyCollection<int>.Count` (already compiled; control) | 1.8 ns
| 1.8 ns |
| `IList<int>[i]` | ~50 ns | 1.9 ns |
| `ICollection<int>.Contains` | ~80 ns | 7.5 ns |
| `IList<int>.IndexOf` | ~77 ns | 8.0 ns |

Relates to #135345

> [!NOTE]
> This PR description was generated with GitHub Copilot.

---------

Co-authored-by: Copilot App <[email protected]>
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.

1 participant