Skip to content

Commit 3d26705

Browse files
lewingCopilot
andauthored
Fix missing transition adapters for shared Wasm R2R unboxing stubs (#133516)
<!-- --> Fixes browser-Wasm CoreCLR ReadyToRun failures introduced after #133218 while preserving shared `U`, `UG`, and `UM` unboxing stubs and almost all of their binary-size benefit. ## Corrected root-cause analysis The initial version of this PR replaced `U`/`UG` with per-method managed thunks based on an ABI-mismatch hypothesis. That approach and its portable-prestub changes have been removed. The revised patch does not change the shared-stub calling conventions or lookup keys. NESM inspection stopped immediately before the failing Test23 `call_indirect`: the call expected five `i32` parameters, but the selected table slot was zero (a null function reference). The expected parameter count alone did not establish a `U` versus `UG` mismatch. The observed delay-load fixup resolved to a non-unboxing shared target requiring a generic context, whose portable entrypoint lacked an R2R-to-interpreter adapter such as `IvTiS1p`. Replacing a compiled per-method unboxing thunk with a structural assembly stub lost dependencies previously introduced by compiling the thunk's managed body. There are two distinct transitions: - **Interpreter -> unboxing stub:** needs an `M` adapter for the full managed unboxing signature, for example `MS56Tp`. - **Unboxing stub -> target:** needs an `I` adapter for the target signature, including its generic context where applicable, for example `IS56Tip` or `IvTiS1p`, so its portable entrypoint is callable before the target's native body is published. Structural sharing also allows the runtime to find a shared stub for a generic instantiation Crossgen2 never compiled. A matching Wasm function shape does not imply that the exact managed transition cookie exists: different struct sizes can share the same structural stub but require different interpreter adapters. The actual `GitHub_19361` execution exposed this case with a missing `MS56Tp` cookie. ## Changes - Add a per-target dependency node retaining the shared stub, compiled target, interpreter-to-R2R adapter for the unboxing signature, and R2R-to-interpreter adapter for the target signature. - Keep these dependencies per managed target rather than on the structurally shared node, so signatures with the same Wasm shape but different managed layouts retain their distinct adapters. - Before publishing a shared unboxing stub, require the exact incoming interpreter cookie and callable code in the target portable entrypoint. An installed R2R-to-interpreter adapter counts as callable code; this does not require a precompiled native target body. - If either transition is unavailable, use the existing interpreted IL-stub fallback. R2R callers independently root their call-signature `I` adapters through the existing call-site recording machinery. - Extend the existing Wasm generic-dispatch tests with a 56-byte struct return alongside the 16-byte case, checking distinct adapters while retaining the original shared-stub assertions. ## Evidence and validation Browser-Wasm **Release CoreCLR under Node.js 26.4.0**, with explicitly regenerated and Wasm-validated CoreLib, LINQ, and test images: | Runtime case | Actual execution evidence | Result | |---|---|---| | `LoaderClassloaderGenerics`, `DisplayName~genrecur.dll` | `Test23 OK`, matching `Passed test` line | Exit 100 | | `Regressions`, `DisplayName~genrecur.dll` | `Test23 OK`, matching `Passed test` line | Exit 100 | | `Regression_NoOptimize_r_1`, `Repro.Program.TestEntryPoint` | `Starting stress loop`, `Result: Completed Normally`, matching `Passed test` line | Exit 100 | The earlier `GitHub_19361` name filter matched no test; earlier success claims using that filter were invalid. The results above use the actual fully qualified method name and confirm that the stress loop executed. Earlier stale CoreLib images were also replaced explicitly rather than relying on layout generation to refresh them. Additional validation: - Browser Release runtime and corerun build: succeeded. - Wasm `ILCompiler.ReadyToRun.Tests`: 75 passed, 37 target-inapplicable skips. - Host macOS arm64 generic-dispatch tests: 3 passed, 2 Wasm-only skips. - Negative dependency checks: removing only `I(target)` fails on missing `IS16Tip`; removing only `M(unboxing)` fails on missing `MS56Tp`. Restoring both passes. The full CI outer-loop matrix and a browser-hosted run have not been rerun locally. ## Binary size Optimized browser `System.Private.CoreLib` images using `--optimize --generate-unboxing-stubs` in the local comparison: | Variant | Bytes | |---|---:| | Earlier fully shared prototype | 26,991,640 | | Revised shared stubs with transition dependencies | 26,993,234 | | Superseded per-method `U`/`UG` fallback | 27,387,567 | The revised image adds **1,594 bytes** over the earlier fully shared prototype and saves **394,333 bytes** compared with the superseded fallback, retaining approximately **99.6%** of the size reduction in that comparison. This supersedes the initial description's claim that the fix gives back nearly the entire saving. Fixes #133491 > [!NOTE] > This pull request description and investigation summary were generated with GitHub Copilot. --------- Co-authored-by: Copilot App <[email protected]>
1 parent ef97eb5 commit 3d26705

5 files changed

Lines changed: 117 additions & 11 deletions

File tree

‎src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/R2RTestSuites.cs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1908,6 +1908,11 @@ static void Validate(ReadyToRunReader reader)
19081908
Assert.True(R2RAssert.HasStringThunkWithPrefix(reader, "UG", out diag), diag);
19091909
Assert.True(R2RAssert.HasStringThunk(reader, "UGviiii", out diag), diag);
19101910
Assert.True(R2RAssert.HasStringThunk(reader, "UGvriiii", out diag), diag);
1911+
Assert.True(R2RAssert.HasStringThunk(reader, "MS56Tp", out diag), diag);
1912+
Assert.True(R2RAssert.HasStringThunk(reader, "MS56Tip", out diag), diag);
1913+
Assert.True(R2RAssert.HasStringThunk(reader, "MS16Tp", out diag), diag);
1914+
Assert.True(R2RAssert.HasStringThunk(reader, "IS16Tip", out diag), diag);
1915+
Assert.True(R2RAssert.HasStringThunk(reader, "IS56Tip", out diag), diag);
19111916
}
19121917
}
19131918

‎src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/TestCases/VirtualMethodGenerics/NonGVM.cs‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,27 @@ struct Test10<T> : ITest10
188188
public void SetValue(nint value) { }
189189
}
190190

191+
struct Test11Result
192+
{
193+
public long A;
194+
public long B;
195+
public long C;
196+
public long D;
197+
public long E;
198+
public long F;
199+
public long G;
200+
}
201+
202+
interface ITest11
203+
{
204+
Test11Result GetValue();
205+
}
206+
207+
struct Test11<T> : ITest11
208+
{
209+
public Test11Result GetValue() => new Test11Result();
210+
}
211+
191212
// Entry points that drive dependency analysis
192213
static class NonGVMTests
193214
{
@@ -227,6 +248,9 @@ static class NonGVMTests
227248
[MethodImpl(MethodImplOptions.NoInlining)]
228249
static void CallSetValue(ITest10 value) => value.SetValue(0);
229250

251+
[MethodImpl(MethodImplOptions.NoInlining)]
252+
static Test11Result CallTest11(ITest11 value) => value.GetValue();
253+
230254
static void Run()
231255
{
232256
ITest1<int> t1 = CreateTest1(42);
@@ -267,5 +291,10 @@ static void Run()
267291
ITest10 t10 = new Test10<object>();
268292
Console.WriteLine(CallGetValue(t10).A);
269293
CallSetValue(t10);
294+
295+
// Test11: the interpreter-to-R2R adapter for a shared generic unboxing thunk with a
296+
// 56-byte struct return must be rooted along with the target method.
297+
ITest11 t11 = new Test11<object>();
298+
Console.WriteLine(CallTest11(t11).A);
270299
}
271300
}

‎src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmUnboxingStubNode.cs‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,47 @@ private static void AppendTypeCode(Utf8StringBuilder sb, WasmValueType type)
224224
protected override void EmitCode(NodeFactory factory, ref RiscV64.RiscV64Emitter instructionEncoder, bool relocsOnly) => throw new NotSupportedException();
225225
}
226226

227+
public sealed class WasmUnboxingStubTargetNode : DependencyNodeCore<NodeFactory>
228+
{
229+
private readonly MethodDesc _targetMethod;
230+
private readonly WasmSignature _signature;
231+
private readonly WasmUnboxingStubNode _stub;
232+
233+
public WasmUnboxingStubTargetNode(MethodDesc targetMethod, WasmSignature signature, WasmUnboxingStubNode stub)
234+
{
235+
_targetMethod = targetMethod;
236+
_signature = signature;
237+
_stub = stub;
238+
}
239+
240+
public override bool InterestingForDynamicDependencyAnalysis => false;
241+
242+
public override bool HasDynamicDependencies => false;
243+
244+
public override bool HasConditionalStaticDependencies => false;
245+
246+
public override bool StaticDependenciesAreComputed => true;
247+
248+
public override IEnumerable<CombinedDependencyListEntry> GetConditionalStaticDependencies(NodeFactory context) => null;
249+
250+
public override IEnumerable<DependencyListEntry> GetStaticDependencies(NodeFactory context)
251+
{
252+
DependencyList dependencies = new DependencyList();
253+
dependencies.Add(_stub, "Wasm unboxing stub for target method");
254+
dependencies.Add(context.CompiledMethodNode(_targetMethod), "Target method for Wasm unboxing stub");
255+
dependencies.Add(context.WasmR2RToInterpreterThunk(WasmLowering.GetSignature(_targetMethod)), "Interpreter fallback for Wasm unboxing target");
256+
dependencies.Add(context.WasmInterpreterToR2RThunk(_signature), "Interpreter-to-R2R thunk for Wasm unboxing stub target");
257+
return dependencies;
258+
}
259+
260+
public override IEnumerable<CombinedDependencyListEntry> SearchDynamicDependencies(
261+
List<DependencyNodeCore<NodeFactory>> markedNodes,
262+
int firstNode,
263+
NodeFactory context) => null;
264+
265+
protected override string GetName(NodeFactory factory) => $"Wasm unboxing stub target for {_targetMethod}";
266+
}
267+
227268
public enum UnboxingStubKind
228269
{
229270
Normal,

‎src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs‎

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -171,24 +171,38 @@ public bool NeedsUnboxingStub(MethodDesc method)
171171
public DependencyNodeCore<NodeFactory> UnboxingStub(MethodDesc targetMethod)
172172
{
173173
Debug.Assert(NeedsUnboxingStub(targetMethod));
174-
ModuleDesc ownerModule = ((MetadataType)targetMethod.GetTypicalMethodDefinition().OwningType).Module;
175-
MethodDesc thunk = targetMethod.IsSharedByGenericInstantiations && !targetMethod.HasInstantiation
176-
? TypeSystemContext.GetSpecialUnboxingThunk(targetMethod, ownerModule)
177-
: TypeSystemContext.GetUnboxingThunk(targetMethod, ownerModule);
178174

179175
if (Target.Architecture == TargetArchitecture.Wasm32)
180176
{
181-
UnboxingStubKind kind = targetMethod.RequiresInstMethodDescArg()
182-
? UnboxingStubKind.MethodDesc
183-
: (targetMethod.RequiresInstMethodTableArg() ? UnboxingStubKind.MethodTable : UnboxingStubKind.Normal);
184-
WasmSignature signature = WasmLowering.GetSignature(thunk.Signature, WasmLowering.LoweringFlags.None);
185-
bool hasReturnBuffer = kind != UnboxingStubKind.Normal && signature.SignatureString[0] == 'S';
186-
return _wasmUnboxingStubs.GetOrAdd(new WasmUnboxingStubKey(signature, WasmTypeNode(targetMethod), kind, hasReturnBuffer));
177+
return _wasmUnboxingStubTargets.GetOrAdd(targetMethod);
187178
}
188179

180+
ModuleDesc ownerModule = ((MetadataType)targetMethod.GetTypicalMethodDefinition().OwningType).Module;
181+
MethodDesc thunk = targetMethod.IsSharedByGenericInstantiations && !targetMethod.HasInstantiation
182+
? TypeSystemContext.GetSpecialUnboxingThunk(targetMethod, ownerModule)
183+
: TypeSystemContext.GetUnboxingThunk(targetMethod, ownerModule);
184+
189185
return _localMethodCache.GetOrAdd(thunk);
190186
}
191187

188+
private WasmUnboxingStubTargetNode CreateWasmUnboxingStubTargetNode(MethodDesc targetMethod)
189+
{
190+
ModuleDesc ownerModule = ((MetadataType)targetMethod.GetTypicalMethodDefinition().OwningType).Module;
191+
MethodDesc thunk = targetMethod.IsSharedByGenericInstantiations && !targetMethod.HasInstantiation
192+
? TypeSystemContext.GetSpecialUnboxingThunk(targetMethod, ownerModule)
193+
: TypeSystemContext.GetUnboxingThunk(targetMethod, ownerModule);
194+
UnboxingStubKind kind = targetMethod.RequiresInstMethodDescArg()
195+
? UnboxingStubKind.MethodDesc
196+
: (targetMethod.RequiresInstMethodTableArg() ? UnboxingStubKind.MethodTable : UnboxingStubKind.Normal);
197+
WasmSignature signature = WasmLowering.GetSignature(thunk.Signature, WasmLowering.LoweringFlags.None);
198+
WasmSignature targetSignature = WasmLowering.GetSignature(targetMethod);
199+
WasmTypeNode targetType = WasmTypeNode(targetSignature);
200+
bool hasReturnBuffer = kind != UnboxingStubKind.Normal && signature.SignatureString[0] == 'S';
201+
WasmUnboxingStubNode stub = _wasmUnboxingStubs.GetOrAdd(
202+
new WasmUnboxingStubKey(signature, targetType, kind, hasReturnBuffer));
203+
return new WasmUnboxingStubTargetNode(targetMethod, signature, stub);
204+
}
205+
192206
private NodeCache<TypeDesc, AllMethodsOnTypeNode> _allMethodsOnType;
193207

194208
public AllMethodsOnTypeNode AllMethodsOnType(TypeDesc type)
@@ -457,6 +471,8 @@ private void CreateNodeCaches()
457471
return new WasmUnboxingStubNode(this, key.Signature, key.TargetType, key.Kind, key.HasReturnBuffer);
458472
});
459473

474+
_wasmUnboxingStubTargets = new NodeCache<MethodDesc, WasmUnboxingStubTargetNode>(CreateWasmUnboxingStubTargetNode);
475+
460476
_importMethods = new NodeCache<TypeAndMethod, IMethodNode>(CreateMethodEntrypoint);
461477

462478
_localMethodCache = new NodeCache<MethodDesc, MethodWithGCInfo>(key =>
@@ -1439,6 +1455,7 @@ public bool Equals(WasmUnboxingStubKey other) =>
14391455
}
14401456

14411457
private NodeCache<WasmUnboxingStubKey, WasmUnboxingStubNode> _wasmUnboxingStubs;
1458+
private NodeCache<MethodDesc, WasmUnboxingStubTargetNode> _wasmUnboxingStubTargets;
14421459

14431460
public WasmTypeNode WasmTypeNode(CorInfoWasmType[] types)
14441461
{

‎src/coreclr/vm/wasm/helpers.cpp‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1638,8 +1638,22 @@ void* GetUnboxingStub(MethodDesc* pMD, MethodDesc** ppTargetMethodDesc, PCODE* p
16381638
return nullptr;
16391639
}
16401640

1641+
// Structural sharing can find a stub even when this particular managed signature
1642+
// was never compiled. Do not publish native code that the interpreter cannot call.
1643+
MetaSig unboxingSig(pMD);
1644+
if (ComputeCalliSigThunk(unboxingSig) == nullptr)
1645+
{
1646+
return nullptr;
1647+
}
1648+
1649+
PCODE targetEntryPoint = pTargetMD->GetMultiCallableAddrOfCode(CORINFO_ACCESS_ANY);
1650+
if (!PortableEntryPoint::ToPortableEntryPoint(targetEntryPoint)->HasNativeCode())
1651+
{
1652+
return nullptr;
1653+
}
1654+
16411655
*ppTargetMethodDesc = pTargetMethodDesc;
1642-
*pTargetEntryPoint = pTargetMD->GetMultiCallableAddrOfCode(CORINFO_ACCESS_ANY);
1656+
*pTargetEntryPoint = targetEntryPoint;
16431657
return unboxingStub;
16441658
}
16451659

0 commit comments

Comments
 (0)