Skip to content

[r2r] Add support for compiling szarray methods - #130413

Merged
BrzVlad merged 1 commit into
dotnet:mainfrom
BrzVlad:feature-r2r-szarray-methods
Jul 23, 2026
Merged

BrzVlad merged 1 commit into
dotnet:mainfrom
BrzVlad:feature-r2r-szarray-methods

Conversation

@BrzVlad

@BrzVlad BrzVlad commented Jul 9, 2026

Copy link
Copy Markdown
Member

For example, an array of T casts to IList. Calling get_Count on this interface will be resolved at runtime to a call to SZArrayHelper:get_Count. This interface method resolution happens magically at runtime, R2R has no way to detect the methods on the SZArrayHelper since the array type doesn't derive from it.

In order to fix this, whenever we detect an Array type, we create the ArrayInterfaceMethodsNode for the canonicalized type. This node will iterate over all implemented generic interfaces. For each interface it will iterate over all methods and try to match them with methods from the SZArrayHelper, by name (the runtime asserts the names are identical in GetActualImplementationForArrayGenericIListOrIReadOnlyListMethod as well). Once we obtain a match of szArrayMethod + interfaceMethod, we add a conditional dependency that the szArrayMethod is compiled only if the equivalent interfaceMethod is discovered as well.

The initial approach included all SZArrayHelper methods naively. Using conditional dependencies for this reduced the number of compiled methods by ~6x. The size increase in negligible, less than 0.1% for corerun framework.

Fixes performance on benchmarks like EmptyTakeSelectToArray

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.

Pull request overview

This PR extends ReadyToRun (R2R) dependency analysis so that when an SZ array is used, the compiler can also discover/compile the corresponding System.SZArrayHelper methods that the runtime dispatches to when calling through generic collection interfaces.

Changes:

  • Added ArrayInterfaceMethodsNode to model conditional compilation of SZArrayHelper implementations keyed off generic interface slot usage.
  • Introduced NodeFactory.AddVirtualMethodDiscoveryDependencies and wired it into existing fixup signatures to centralize virtual dispatch discovery and add the array-specific path.
  • Hooked the new node into NodeFactory caching and the project file.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
src/coreclr/tools/aot/ILCompiler.ReadyToRun/ILCompiler.ReadyToRun.csproj Adds the new dependency analysis node to the build.
src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunCodegenNodeFactory.cs Adds node caching + shared helper for virtual-dispatch discovery, including arrays.
src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/TypeFixupSignature.cs Switches to the shared helper to add virtual-dispatch discovery deps.
src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/NewArrayFixupSignature.cs Adds virtual-dispatch discovery deps for array fixups.
src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/GenericLookupSignature.cs Switches to the shared helper for discovery in generic-lookup fixups.
src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ArrayInterfaceMethodsNode.cs Implements conditional dependencies from generic interface slots to SZArrayHelper compiled methods.

For example, an array of T casts to IList<T>. Calling `get_Count` on this interface will be resolved at runtime to a call to `SZArrayHelper:get_Count`. This interface method resolution happens magically at runtime, R2R has no way to detect the methods on the `SZArrayHelper` since the array type doesn't derive from it.

In order to fix this, whenever we detect an Array type, we create the ArrayInterfaceMethodsNode for the canonicalized type. This node will iterate over all implemented generic interfaces. For each interface it will iterate over all methods and try to match them with methods from the `SZArrayHelper`, by name (the runtime asserts the names are identical in GetActualImplementationForArrayGenericIListOrIReadOnlyListMethod as well). Once we obtain a match of szArrayMethod + interfaceMethod, we add a conditional dependency that the szArrayMethod is compiled only if the equivalent interfaceMethod is discovered as well.

The initial approach included all SZArrayHelper methods naively. Using conditional dependencies for this reduced the number of compiled methods by ~6x. The size increase in negligible, less than 0.1% for corerun framework.

Fixes performance on benchmarks like EmptyTakeSelectToArray
Copilot AI review requested due to automatic review settings July 13, 2026 14:53
@BrzVlad
BrzVlad force-pushed the feature-r2r-szarray-methods branch from 364be8e to e630c08 Compare July 13, 2026 14:53

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.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated no new comments.

@github-actions

github-actions Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow state for the Holistic Review Orchestrator.

{
  "version": 5,
  "last_dispatched_commit": "e630c08120c8050a5b3cb0159dfba1a578e72877",
  "last_dispatched_base_ref": "main",
  "last_dispatched_base_sha": "0836e3b19f8c651cfeba4d9f374176150c440137",
  "last_reviewed_commit": "e630c08120c8050a5b3cb0159dfba1a578e72877",
  "last_reviewed_base_ref": "main",
  "last_reviewed_base_sha": "0836e3b19f8c651cfeba4d9f374176150c440137",
  "last_recorded_worker_run_id": "29682976078",
  "review_attempt_commit": "",
  "review_attempt_base_ref": "",
  "review_attempt_count": 0,
  "max_review_attempts": 5,
  "review_history_format": "holistic-review-disclosure-v1",
  "review_history": [
    {
      "commit": "e630c08120c8050a5b3cb0159dfba1a578e72877",
      "review_id": 4730591963
    }
  ]
}

@github-actions github-actions Bot 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.

Holistic Review

Motivation: The problem is real and well-explained. In R2R, calls through the generic collection interfaces (IList<T>, ICollection<T>, IEnumerable<T>, IReadOnly*) on an SZ array are dispatched at runtime to SZArrayHelper methods, which the compiler never sees as members of the array type, so those helper bodies were left uncompiled and JIT'd at runtime, hurting benchmarks like EmptyTakeSelectToArray.

Approach: Sound and consistent with the existing design. A new ArrayInterfaceMethodsNode mirrors InheritedVirtualMethodsNode, emitting conditional static dependencies keyed on VirtualMethodUse(interfaceMethod) so an SZArrayHelper body is compiled only when the corresponding interface slot is actually used. Consolidating the duplicated discovery logic from TypeFixupSignature/GenericLookupSignature into NodeFactory.AddVirtualMethodDiscoveryDependencies and adding the array branch there (plus a new NewArrayFixupSignature override) is a clean refactor with no behavioral change on the pre-existing paths.

Summary: ⚠️ Needs Human Review. The code is well-structured and the refactor is behavior-preserving, but this is a subtle R2R correctness change with no automated test in the PR, and one runtime detail (the SZArrayHelper reference-type Object substitution) deserves a maintainer's confirmation that the compiled canonical body matches what the runtime resolves. A JIT/R2R maintainer should sign off.


Detailed Findings

✅ Refactor is behavior-preserving

AddVirtualMethodDiscoveryDependencies reproduces the prior TypeFixupSignature/GenericLookupSignature conditions exactly (CompilationCurrentPhase == 0, !IsGenericDefinition && !IsInterface && IsDefType && VersionsWithType). The early CompilationCurrentPhase != 0 return and the ConvertToCanonForm are equivalent to the removed inline code. The new else if (type.IsSzArray) branch is additive and only reachable for SZ arrays (non-DefType), so existing non-array flows are unaffected. Making InheritedVirtualMethods private and moving canonicalization into the factory helper is a reasonable tightening; the new Debug.Assert(type == type.ConvertToCanonForm(...)) in InheritedVirtualMethodsNode documents the invariant now that all callers canonicalize up front.

⚠️ Canonical vs. Object instantiation — worth a maintainer confirmation

GetActualImplementationForArrayGenericIListOrIReadOnlyListMethod (src/coreclr/vm/array.cpp) substitutes Object for reference-type T on every method except GetEnumerator, whereas the node instantiates the helper with the actual elementType and then calls GetCanonMethodTarget(CanonicalFormKind.Specific). For reference types both should resolve to the shared __Canon body (Object being a reference type), and for value types both keep the exact instantiation, so the compiled canonical body should be the one the runtime uses. This appears correct but relies on the shared-generics equivalence of __Canon and Object instantiations; a JIT/R2R maintainer should confirm there is no element-type shape (e.g. GetEnumerator<T> for value types, or a nullable/pointer/by-ref-like element) where the runtime picks a different associated MethodDesc than the compiled canon target.

💡 Interface-method filtering is looser than the sibling node

ArrayInterfaceMethodsNode.GetConditionalStaticDependencies iterates interfaceType.GetVirtualMethods() without the HasInstantiation/Signature.IsStatic guards that InheritedVirtualMethodsNode applies to skip GVMs and static virtuals. The generic collection interfaces don't currently expose GVM or static-virtual members, so this is not a live bug, but adding the same guards would make the node robust against future interface changes and match the established pattern. Non-blocking.

💡 Test coverage

No automated test accompanies the change; validation is via the cited benchmark. R2R method-compilation coverage is admittedly hard to unit test, but a small ILCompiler dependency-graph test (in the style of src/coreclr/tools/aot/ILCompiler.Compiler.Tests) asserting that using ((ICollection<int>)intArray).Count pulls in the SZArrayHelper.get_Count body, and that an unused slot does not, would lock in both the fix and the ~6x conditional-dependency reduction the description claims. Consider as a follow-up if not feasible inline.

Note

This review was generated by this repository's Holistic Review agentic workflow to complement the built-in Copilot review.

Generated by Holistic Review · 150.2 AIC · ⌖ 11 AIC · ⊞ 10K

@BrzVlad

BrzVlad commented Jul 23, 2026

Copy link
Copy Markdown
Member Author

/ba-g unrelated infra failure

@BrzVlad
BrzVlad merged commit 3eb69b8 into dotnet:main Jul 23, 2026
111 of 113 checks passed
@hez2010

hez2010 commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Since we are compiling SZArray methods in R2R, I think we should also enable devirtualization for them (they were already devirtualized in CoreCLR)?

#if READYTORUN
if (isArray)
{
// Array interface devirt is not yet supported by R2R.
info->detail = CORINFO_DEVIRTUALIZATION_DETAIL.CORINFO_DEVIRTUALIZATION_FAILED_CANON;
return false;
}
#endif

@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 11.0-rc1 milestone Jul 24, 2026
@github-actions github-actions Bot locked and limited conversation to collaborators Aug 23, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants