Skip to content

ILC: only keep delegate Invoke methods reflectable when they can be looked up on unknown delegate types - #138052

Open
Sergio0694 wants to merge 1 commit into
dotnet:mainfrom
Sergio0694:user/sergiopedri/ilc-delegate-invoke-reflectability
Open

Sergio0694 wants to merge 1 commit into
dotnet:mainfrom
Sergio0694:user/sergiopedri/ilc-delegate-invoke-reflectability

Conversation

@Sergio0694

Copy link
Copy Markdown
Contributor

NativeAOT makes the Invoke method of every delegate type with metadata reflectable ("Delegate invoke method is always reflectable", #72077), which keeps its metadata, reflection invoke stub and body for every delegate in the app. The rule exists because the reflection stack and some libraries look up Invoke on delegate types that are not statically known: Delegate.DynamicInvoke, Delegate.CreateDelegate, MethodInfo.CreateDelegate, Delegate.Method on marshalled function pointer and LINQ expression delegates, System.Linq.Expressions, and EventInfo.EventHandlerType.GetMethod("Invoke").

All of these look up "Invoke" by name on a type that dataflow doesn't know statically. This adds a DelegateInvokeReflectedOnUnknownTypeNode, marked by reflection dataflow when:

  • Type.GetMethod, Type.GetMember or RuntimeReflectionExtensions.GetRuntimeMethod is called with "Invoke" on a type that is not statically known, or
  • GetType() is called on a value of type System.Delegate, which dataflow models as typeof(Delegate).

Delegate Invoke methods are now made reflectable only when that node is present. When dataflow doesn't see the whole program (no reflection scanning, multi-file builds), or with IlcTrimMetadata=false, the previous unconditional behavior is kept. Lookups on statically known delegate types are already handled precisely by the existing analysis, and other reflection on unknown types (e.g. GetMethods() and filtering by name) already produces trim warnings.

Size impact

Microsoft Store (CsWinRT 3.0), same inputs, ILC with #137541, with and without this change, OptimizationPreference=Size:

WinStore.App.dll MSIX (estimated)
Before 82,356,224 26,967,783
After 81,504,256 (-851,968) 26,770,210 (-197,573)

The MSIX column is the image compressed at zlib level 6, as a proxy for its size in the package. It is not a measured MSIX build. With OptimizationPreference=Speed the saving is 887,296 bytes. All 141 delegate Invoke method metadata records are removed.

Testing

  • Added SmokeTests/DelegateInvoke, with one variant using DynamicInvoke and one using GetType().GetMethod("Invoke") on a Delegate. Each fails if its trigger is removed from the compiler.
  • Added a check to AttributeTrimming that a delegate that is only invoked doesn't have a reflectable Invoke.
  • Validated these tests with a local ILC harness, with and without the IL scanner, and built ILC and ILTrim. The full src/tests NativeAOT run was not done locally.

Part of #137567.

Note

This PR description and the change were prepared with GitHub Copilot.

…ooked up on unknown delegate types

Every delegate type with metadata had its Invoke method made reflectable, because the
reflection stack and some libraries look up Invoke on delegate types that are not statically
known (Delegate.DynamicInvoke, Delegate/MethodInfo.CreateDelegate, Delegate.Method on marshalled
function pointer and LINQ expression delegates, System.Linq.Expressions, EventHandlerType).

All of these look up "Invoke" by name on a type that is not statically known. Reflection
dataflow now marks a node when it sees such a lookup, or GetType on System.Delegate (which is
modeled as typeof(Delegate)), and the Invoke methods are only made reflectable when that node
is present. When dataflow does not see the whole program or metadata is not trimmed, the
previous unconditional behavior is kept.

Co-authored-by: Copilot App <[email protected]>
@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: @agocke, @dotnet/ilc-contrib
See info in area-owners.md if you want to be subscribed.

@MichalStrehovsky

Copy link
Copy Markdown
Member

This may break people who had a suppression for this. For example if the way they structured this doesn't let us see Invoke.

This will potentially be a support call. If as a result of this support call we'll say "okay, rewrite your pattern to this pattern and suppress the warning again, we pinky promise we'll not break this again", people will not be happy.

I think we'll need to pair this with a trim safe API to get delegate Invoke method so that we can say "use this new API that is trim safe".

I might have more opinion on all this when rt-sz result for this are in.

@Sergio0694

Sergio0694 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

I'm starting to feel perhaps those rt-sz scenarios might not be representative of a real world complex app. I find it a bit suspicious that the largest saving across those test projects is ~5 KB, yet this saves over 850 KB in the Store 🤔

Makes me wonder what we might've disregarded before because rt-sz didn't show enough savings in those samples.

@MichalStrehovsky

Copy link
Copy Markdown
Member

Does CsWinRT somehow end up with lots of delegates? Or some other pattern that is heavy on delegates in the Store app?

@MichalStrehovsky

Copy link
Copy Markdown
Member

Makes me wonder what we might've disregarded before because rt-sz didn't show enough savings in those samples.

This shows no savings for any app where the savings could be meaningful (ASP.NET or Avalonia) because they probably trigger the "I don't know what Invoke was looked up on" logic that then does nothing. It would be more interesting if you could look at what triggers it in ASP.NET and whether we can get rid of it.

@Sergio0694

Copy link
Copy Markdown
Contributor Author

Ok so I looked into both the Store and those samples, it makes a lot more sense now why this saves so much for us.

Store

This change removes a total of 1263 delegate Invoke methods in the Store. 774 are Func/Action/Comparison instantiations, the rest are mostly WinRT async/event handlers, and a few are our own delegate types defined in the Store. This is already way more than e.g. TodosApi, which has just 606. The reason why the size ends up getting even worse in the Store is because a lot of these delegate types show up in the type map as well (because they're WinRT types). That is:

  1. If a delegate's Invoke is reflectable, we get a type loader template for the delegate type.
  2. The type map "could be loaded at runtime" rule treats every matching CsWinRT type map key as loadable: every EventHandler<X,Y>, AsyncOperationCompletedHandler<T> and IAsyncOperation<T>. This then (by design) roots all the related ABI marshalling code for all of those types, along with supporting code. Note this is already on top of the gate that we already merged (or it would be even worse, because just all of them would always be kept).

With this change, 374 keys are dropped from the type map, which drops 253 KB just from WinRT.Interop.dll. The rest of the savings are just from the stripped metadata for all delegate types, same as in TodosApi. Basically the fact we're using the type map and that a lot of WinRT types are delegates makes rooting Invoke especially expensive. Any WinRT app would hit this.

rt-sz samples

Like you said, the fix isn't kicking in at all there. There's two reasons why:

  1. Delegate.GetMethodImpl looks up "Invoke" by name to handle function-pointer and LINQ-expression delegates. Any Delegate.Method or GetMethodInfo() call compiles that code, and ASP.NET uses it widely: WebHostBuilder.Configure, minimal API Map, endpoint routing, and DI diagnostics. Side note this also generally feels very wasteful, since we talked a lot before about how the second you touch Delegate.Method, you end up marking a crap ton of stuff rooted for reflection. It's unrelated from this issue but it feels like ASP.NET should consider looking into whether this is something they could avoid.
  2. MethodInfo.CreateDelegate looks up Invoke on its Type parameter. The callers are ASP.NET's middleware binder (with typeof(RequestDelegate)), DiagnosticSource, OpenTelemetry and Google.Protobuf.

If you just comment those calls out to get an approximate number, TodosApi saves 148,480 B (0.58%) with this fix.

Opus suggested these two possible fixes for them:

  • Delegate.Method: make the Invoke lookup in GetMethodImpl reachable only when function-pointer or LINQ-expression delegates can exist. That alone fixes kestrel-minimal.
  • CreateDelegate: have the compiler model it at the call site, where the delegate type is usually a typeof. That fits Michal's suggestion of a trim-safe API to get Invoke. Generic call sites like DiagnosticSource's typeof(Func<TObject,TProperty>) would still keep a canonical Invoke.

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

Labels

area-NativeAOT-coreclr community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants