Skip to content

ILC: do not root delegates that are only stored into fields nobody reads - #138030

Draft
Sergio0694 wants to merge 3 commits into
dotnet:mainfrom
Sergio0694:user/sergiopedri/ilc-skip-dead-delegate-stores
Draft

Sergio0694 wants to merge 3 commits into
dotnet:mainfrom
Sergio0694:user/sergiopedri/ilc-skip-dead-delegate-stores

Conversation

@Sergio0694

Copy link
Copy Markdown
Contributor

A delegate created with ldftn + newobj roots its target as soon as the creation is reachable, even if the delegate can never be invoked. The System.Text.Json source generator emits one such lambda per property (AttributeProviderFactory, and ConstructorAttributeProviderFactory per constructor). They are only read through JsonPropertyInfo.AttributeProvider and JsonParameterInfo.AttributeProvider, but in an app that never reads those they still keep the lambdas, and the reflection metadata their bodies cause (typeof(T).GetProperty("Name")), alive.

This teaches the dependency scanner to skip delegates that are only stored into fields whose value is never observed:

  • A field of delegate type is tracked, and a delegate creation that is directly stored into it (or stored through a trivial setter, optionally via the C# lambda caching pattern) roots its target only if the field is read.
  • Field to field copies and trivial getters forward the question to the destination. Any other use of a tracked field (ldfld, ldflda, ldsfld, reflection, calls to the getter that are not themselves forwarded, and so on) counts as a read.
  • Only the C# delegate cache pattern and plain stores are matched, with a receiver that cannot have side effects. Anything unrecognized keeps today's behavior.
  • The analysis runs for single-file compilations only. The compilation phase replaces creations the scanner proved dead with null, so both phases see the same IL.
  • Dataflow dependencies coming from the body of a non-generic lambda or local function are now conditional on that body being compiled, so a dead lambda no longer causes reflection metadata either.

Size impact

Microsoft Store (WinStore.App.dll, Release x64, OptimizationPreference=Size), same inputs, ILC with and without this change. The Store can't be built with the current main compiler yet, so this was measured on the equivalent change on top of the release/11.0 gate backport.

WinStore.App.dll MSIX (deflate level 6)
Before 82,178,048 26,928,776
After 80,630,784 (-1,547,264) 26,406,670 (-522,106)

The removed code is the expected one: the AttributeProviderFactory lambdas of the source generated contexts and the reflection metadata, invoke map entries and accessors they kept alive, plus three dead stores outside System.Text.Json. An earlier build of this change was smoke tested in Windows Sandbox (no app errors or crashes); the binary was not re-tested after the final review fixes.

Testing

  • Added TestDeadDelegateStores to the TrimmingBehaviors smoke test: dead and live stores, setters and getters, copies, shared generic code, reflection, and a regression case for delegates created in code run by a static constructor.
  • The new test code, compiled as a standalone NativeAOT app with the locally built ILC, returns the success code. ILCompiler.Trimming.Tests: 622 passed, 4 failed (ilasm isn't built in my tree, unrelated).
  • Not measured: ILC throughput and memory impact of the extra scanner analysis.

Part of #137567.
Resolves #137809

Note

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

A delegate whose creation is ldftn + newobj roots its target as soon as it is created, even
if the delegate can never be invoked. The System.Text.Json source generator stores one such
lambda per property (AttributeProviderFactory), which is only read by
JsonPropertyInfo.AttributeProvider, and keeps both the lambdas and the reflection metadata
they cause alive in apps that never read that property.

Track, in the scanner, which delegate typed fields may have their contents observed. A
delegate creation that is directly stored into a tracked field (or into one through a trivial
setter, optionally through the C# lambda caching pattern) only roots its target if the field
is read. Copies between fields and trivial getters forward the question to the destination.
Any other use of a tracked field marks it as read. The compilation phase replaces the
creation of delegates that turned out to be unobserved with null.

Dataflow dependencies that come from the body of a non-generic lambda or local function are
now conditional on the body of the lambda being compiled, so a dead lambda does not cause
reflection metadata either.

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.

@Sergio0694

Copy link
Copy Markdown
Contributor Author

@eiriktsarpalis this fixes #137809, however it does add complexity, and it doesn't work if anyone in the app does use AttributeProvider. I'd consider the new flag not mutually exclusive with this change, as it'd allow folks that do need that provider for only some JSON context to still get the same binary size saves from the other JSON contexts.

Comment on lines +506 to +522
if (i >= 5
&& i + 4 < count
&& instructions[i - 5].Opcode == ILOpcode.ldsfld
&& instructions[i - 4].Opcode == ILOpcode.dup
&& instructions[i - 3].Opcode is ILOpcode.brtrue or ILOpcode.brtrue_s
&& instructions[i - 2].Opcode == ILOpcode.pop
&& instructions[i - 1].Opcode is ILOpcode.ldsfld or ILOpcode.ldnull
&& instructions[i + 2].Opcode == ILOpcode.dup
&& instructions[i + 3].Opcode == ILOpcode.stsfld
&& instructions[i - 3].BranchDestination == instructions[i + 4].Offset
&& !isTarget[instructions[i - 4].Offset]
&& !isTarget[instructions[i - 3].Offset]
&& !isTarget[instructions[i - 2].Offset]
&& !isTarget[instructions[i - 1].Offset]
&& !isTarget[ldftn.Offset]
&& !isTarget[instructions[i + 2].Offset]
&& !isTarget[instructions[i + 3].Offset])

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

In theory if we had #85014, this could be simplified a fair amount.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Yes, I would rather build #85014 than this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Note that even if we had #85014, this would still be needed. I'm just saying that building this on top of that would simplify the logic we need in ILC to detect delegate instantiations. But all the rest of the data flow analysis in this PR would still be needed. That is, or we just add that generator option to STJ and then this PR isn't needed as much.

@Sergio0694
Sergio0694 marked this pull request as draft November 20, 2026 20:49
…ield

The singleton receiver check now looks at the shape of the field (static initonly field of the
containing closure class) instead of its name, and delegate cache containers are also recognized
for generic methods (<Method>O__ordinal_id), not only <>O.

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

Copy link
Copy Markdown
Contributor Author

@MichalStrehovsky opening this up as draft to get some feedback on it. Is this change in general something you'd want to consider for ILC, or is data flow intentionally not part of ILC? Either case would also help us understand how much to prioritize #137566 🙂

The IL patterns are now matched where the scanner imports the instructions, with peeks at the following
instructions like the other pattern matching in the importer, instead of a pre-pass that decodes
every method. The compilation phase no longer matches anything: it replaces every delegate creation of a
target in a method when the scanner found all of them to be dead, so the scanner registers a use for the
delegate creations it does not understand. A read of a delegate cache that is forwarded to another field
now requires the null case to be the creation that refills the cache.

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

Copy link
Copy Markdown
Member

@MichalStrehovsky opening this up as draft to get some feedback on it.

MichalStrehovsky/rt-sz#307 (comment) says all I need to know. Don't even need to look at code

@Sergio0694

Copy link
Copy Markdown
Contributor Author

@eiriktsarpalis given what @MichalStrehovsky said (and the fact that this change adds substantial complexity with basically no benefits outside of that very specific scenario in System.Text.Json), can we go with the proposed generator option instead and bring that to API review? I am happy to also look into adding the analyzer @jkotas suggested if that would help, I agree it should be possible to at least statically flag cases that are provably incorrect in theory.

@jkotas

jkotas commented Nov 21, 2026

Copy link
Copy Markdown
Member

System.Text.Json

System.Text.Json is designed as a reflection first serializer. You can wrap it with layers of options to cut down some of the gross inefficiencies, but I doubt that you will be able to get close to optimal.

How many different types do you need to serialize as json in the store app? How much total binary size do you pay for it? It may be interesting to get a number for how much you can save by a vibe-coded precompiled serializer that avoids the cruft from System.Text.Json.

@eiriktsarpalis

eiriktsarpalis commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

@Sergio0694 given your stated requirement of needing to mix and match uses of the attribute provider in a single app, it is true that this change will not help a lot. We can look at the source gen opt out mechanism as proposed, although due to overridding priorities we the libraries team don't have the bandwidth to look at .NET 12 features at this moment. I would suggest pinging me again after the holidays.

@eiriktsarpalis

Copy link
Copy Markdown
Member

It may be interesting to get a number for how much you can save by a vibe-coded precompiled serializer that avoids the cruft from System.Text.Json.

In my experiments, you stand to save ~20% of application size (in a basic console app that roundtrips a JSON value), but that's assuming your app doesn't have any special requirements such as conditional writes, reference preservation, async, number handling, property naming policies, etc. As these features stack up a fully inlined serializer tends to grow bigger than a metadata-based one.

@Sergio0694

Copy link
Copy Markdown
Contributor Author

"How many different types do you need to serialize as json in the store app?"

We have about 460 distinct types we serialize (~340 are our own models, ~120 are built-in types/collections), for a total of 660 generated type metadata entries (which also includes e.g. arrays/collections over those types). So we have quite a lot of stuff. And for us migrating to System.Text.Json isn't really viable, we heavily rely on its infrastructure to implement e.g. custom converters etc., we use its APIs both to serialize into buffers/strings but also asynchronously to/from streams, and also many of our models are shared across packages shared with other teams and tools, so they act as a "contract" that everyone can rely on (including for test coverage for the custom serializers). If we were to handroll our serialization infrastructure just on the Store side, the whole thing would also lose all that cross-team end to end validation and shared contract. Plus what Eirik said that as you use more features and have lots of types, System.Text.Json might actually use less size than fully generated serializers. In general we're very happy with System.Text.Json, we're just trying to further optimize it in cases where it still has a noticeable impact on binary size for features we genuinely don't need at all (same goes not just for us, but also for other inbox apps and also for various built-in Windows components which we're now writing in C#).

"given your stated requirement of needing to mix and match uses of the attribute provider in a single app, it is true that this change will not help a lot"

@eiriktsarpalis I actually investigated this in the Store, and we can easily stop using it entirely (I'll probably do this regardless given that looking up attributes is less efficient anyway and not consistent with how we handle JSON models in other projects), so in my case I don't even need the per-context opt-out anymore either, I'd be fine with a global switch as well if that simplifies things. I still feel like the per-context switch might make sense in general, but I'm saying if you have a strong preference for either approach, both would work just as well for us, as long as we can still stop emitting all that code 🙂

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.

NativeAOT retains an unused lambda but eliminates an unused interface implementation

4 participants